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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

95
static void destroyFillOperatorInfo(void* param, int32_t numOfOutput);
96 97 98
static void destroyProjectOperatorInfo(void* param, int32_t numOfOutput);
static void destroyOrderOperatorInfo(void* param, int32_t numOfOutput);
static void destroyAggOperatorInfo(void* param, int32_t numOfOutput);
X
Xiaoyu Wang 已提交
99

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

103 104
static void destroyOperatorInfo(SOperatorInfo* pOperator);

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

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

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

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

  return fpSet;
}

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

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

143
static void initCtxOutputBuffer(SqlFunctionCtx* pCtx, int32_t size);
144
static void doSetTableGroupOutputBuf(SOperatorInfo* pOperator, int32_t numOfOutput, uint64_t groupId);
145

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

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

  return true;
}

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

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

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

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

    return existed;
  }

  return p1 != NULL;
}
197
#endif
198

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

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

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

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

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

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

229 230
  setBufPageDirty(pData, true);

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

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

  return pResultRow;
}

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

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

256 257
  SResultRow* pResult = NULL;

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

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

  // allocate a new buffer page
  if (pResult == NULL) {
286
#ifdef BUF_PAGE_DEBUG
wmmhello's avatar
wmmhello 已提交
287
    qDebug("page_2");
288
#endif
H
Haojun Liao 已提交
289
    ASSERT(pSup->resultRowSize > 0);
290 291
    pResult = getNewResultRow(pResultBuf, groupId, pSup->resultRowSize);

292
    initResultRow(pResult);
H
Haojun Liao 已提交
293

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

300 301 302
  // 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 已提交
303
  // too many time window in query
304 305
  if (pTaskInfo->execModel == OPTR_EXEC_MODEL_BATCH &&
      taosHashGetSize(pSup->pResultRowHashTable) > MAX_INTERVAL_TIME_WINDOW) {
H
Haojun Liao 已提交
306 307 308
    longjmp(pTaskInfo->env, TSDB_CODE_QRY_TOO_MANY_TIMEWINDOW);
  }

H
Haojun Liao 已提交
309
  return pResult;
H
Haojun Liao 已提交
310 311
}

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

L
Liu Jicong 已提交
318
  SFilePage* pData = NULL;
319 320 321 322 323 324

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

  if (taosArrayGetSize(list) == 0) {
H
Haojun Liao 已提交
325
    pData = getNewBufPage(pResultBuf, tid, &pageId);
326
    pData->num = sizeof(SFilePage);
327 328
  } else {
    SPageInfo* pi = getLastPageInfo(list);
329
    pData = getBufPage(pResultBuf, getPageId(pi));
330
    pageId = getPageId(pi);
331

332
    if (pData->num + size > getBufPageSize(pResultBuf)) {
333
      // release current page first, and prepare the next one
334
      releaseBufPageInfo(pResultBuf, pi);
335

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

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

359
//  query_range_start, query_range_end, window_duration, window_start, window_end
360
void initExecTimeWindowInfo(SColumnInfoData* pColData, STimeWindow* pQueryWindow) {
361 362 363
  pColData->info.type = TSDB_DATA_TYPE_TIMESTAMP;
  pColData->info.bytes = sizeof(int64_t);

364
  colInfoDataEnsureCapacity(pColData, 5);
365 366 367 368 369 370 371 372 373
  colDataAppendInt64(pColData, 0, &pQueryWindow->skey);
  colDataAppendInt64(pColData, 1, &pQueryWindow->ekey);

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

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

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

386
    pCtx[k].input.startRowIndex = offset;
387
    pCtx[k].input.numOfRows = forwardStep;
388 389 390

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

395 396
    if (fmIsWindowPseudoColumnFunc(pCtx[k].functionId)) {
      SResultRowEntryInfo* pEntryInfo = GET_RES_INFO(&pCtx[k]);
397 398

      char* p = GET_ROWCELL_INTERBUF(pEntryInfo);
399

400
      SColumnInfoData idata = {0};
dengyihao's avatar
dengyihao 已提交
401
      idata.info.type = TSDB_DATA_TYPE_BIGINT;
402
      idata.info.bytes = tDataTypes[TSDB_DATA_TYPE_BIGINT].bytes;
dengyihao's avatar
dengyihao 已提交
403
      idata.pData = p;
404 405 406 407

      SScalarParam out = {.columnData = &idata};
      SScalarParam tw = {.numOfRows = 5, .columnData = pTimeWindowData};
      pCtx[k].sfp.process(&tw, 1, &out);
408
      pEntryInfo->numOfRes = 1;
409 410 411 412 413 414 415 416 417 418
    } else {
      int32_t code = TSDB_CODE_SUCCESS;
      if (functionNeedToExecute(&pCtx[k]) && pCtx[k].fpSet.process != NULL) {
        code = pCtx[k].fpSet.process(&pCtx[k]);

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

421 422 423 424 425
      // restore it
      pCtx[k].input.colDataAggIsSet = hasAgg;
      pCtx[k].input.startRowIndex = startOffset;
      pCtx[k].input.numOfRows = numOfRows;
    }
426 427 428
  }
}

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

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

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

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

    pInput->pData[paramIndex] = pColInfo;
464 465
  } else {
    pColInfo = pInput->pData[paramIndex];
466 467
  }

468
  colInfoDataEnsureCapacity(pColInfo, numOfRows);
469

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

  return TSDB_CODE_SUCCESS;
}

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

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

L
Liu Jicong 已提交
500
    pCtx[i].pSrcBlock = pBlock;
X
Xiaoyu Wang 已提交
501
    pCtx[i].scanFlag = scanFlag;
H
Haojun Liao 已提交
502

503
    SInputColumnInfoData* pInput = &pCtx[i].input;
504
    pInput->uid = pBlock->info.uid;
C
Cary Xu 已提交
505
    pInput->colDataAggIsSet = false;
506

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

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

532
          code = doCreateConstantValColumnInfo(pInput, pFuncParam, j, pBlock->info.rows);
533 534 535
          if (code != TSDB_CODE_SUCCESS) {
            return code;
          }
536
        }
G
Ganlin Zhao 已提交
537 538
      }
    }
H
Haojun Liao 已提交
539
  }
540 541

  return code;
H
Haojun Liao 已提交
542 543
}

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

552 553 554 555
      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;
556
      }
557 558
    }
  }
559 560

  return TSDB_CODE_SUCCESS;
561 562
}

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

570
int32_t projectApplyFunctions(SExprInfo* pExpr, SSDataBlock* pResult, SSDataBlock* pSrcBlock, SqlFunctionCtx* pCtx,
X
Xiaoyu Wang 已提交
571
                              int32_t numOfOutput, SArray* pPseudoList) {
H
Haojun Liao 已提交
572
  setPseudoOutputColInfo(pResult, pCtx, pPseudoList);
573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592

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

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

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

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

H
Haojun Liao 已提交
593
  pResult->info.groupId = pSrcBlock->info.groupId;
H
Haojun Liao 已提交
594

595 596
  // if the source equals to the destination, it is to create a new column as the result of scalar
  // function or some operators.
597 598
  bool createNewColModel = (pResult == pSrcBlock);

599 600
  int32_t numOfRows = 0;

601
  for (int32_t k = 0; k < numOfOutput; ++k) {
602 603
    int32_t               outputSlotId = pExpr[k].base.resSchema.slotId;
    SqlFunctionCtx*       pfCtx = &pCtx[k];
604
    SInputColumnInfoData* pInputData = &pfCtx->input;
605

L
Liu Jicong 已提交
606
    if (pExpr[k].pExpr->nodeType == QUERY_NODE_COLUMN) {  // it is a project query
607
      SColumnInfoData* pColInfoData = taosArrayGet(pResult->pDataBlock, outputSlotId);
608
      if (pResult->info.rows > 0 && !createNewColModel) {
609 610
        colDataMergeCol(pColInfoData, pResult->info.rows, &pResult->info.capacity, pInputData->pData[0],
                        pInputData->numOfRows);
611
      } else {
612
        colDataAssign(pColInfoData, pInputData->pData[0], pInputData->numOfRows, &pResult->info);
613
      }
614

615
      numOfRows = pInputData->numOfRows;
616
    } else if (pExpr[k].pExpr->nodeType == QUERY_NODE_VALUE) {
617
      SColumnInfoData* pColInfoData = taosArrayGet(pResult->pDataBlock, outputSlotId);
618

dengyihao's avatar
dengyihao 已提交
619
      int32_t offset = createNewColModel ? 0 : pResult->info.rows;
620 621 622 623 624 625 626 627

      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);
        }
628
      }
629 630

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

635
      SColumnInfoData* pResColData = taosArrayGet(pResult->pDataBlock, outputSlotId);
636
      SColumnInfoData  idata = {.info = pResColData->info, .hasNull = true};
637

638
      SScalarParam dest = {.columnData = &idata};
X
Xiaoyu Wang 已提交
639
      int32_t      code = scalarCalculate(pExpr[k].pExpr->_optrRoot.pRootNode, pBlockList, &dest);
640 641 642 643
      if (code != TSDB_CODE_SUCCESS) {
        taosArrayDestroy(pBlockList);
        return code;
      }
644

dengyihao's avatar
dengyihao 已提交
645
      int32_t startOffset = createNewColModel ? 0 : pResult->info.rows;
646
      ASSERT(pResult->info.capacity > 0);
647
      colDataMergeCol(pResColData, startOffset, &pResult->info.capacity, &idata, dest.numOfRows);
D
dapan1121 已提交
648
      colDataDestroy(&idata);
L
Liu Jicong 已提交
649

650
      numOfRows = dest.numOfRows;
651 652
      taosArrayDestroy(pBlockList);
    } else if (pExpr[k].pExpr->nodeType == QUERY_NODE_FUNCTION) {
653 654
      // _rowts/_c0, not tbname column
      if (fmIsPseudoColumnFunc(pfCtx->functionId) && (!fmIsScanPseudoColumnFunc(pfCtx->functionId))) {
H
Haojun Liao 已提交
655
        // do nothing
656
      } else if (fmIsIndefiniteRowsFunc(pfCtx->functionId)) {
657 658
        SResultRowEntryInfo* pResInfo = GET_RES_INFO(pfCtx);
        pfCtx->fpSet.init(pfCtx, pResInfo);
659 660 661 662 663 664 665 666 667 668

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

669 670 671 672 673
        // link pDstBlock to set selectivity value
        if (pfCtx->subsidiaries.num > 0) {
          pfCtx->pDstBlock = pResult;
        }

674
        numOfRows = pfCtx->fpSet.process(pfCtx);
H
Haojun Liao 已提交
675
      } else if (fmIsAggFunc(pfCtx->functionId)) {
G
Ganlin Zhao 已提交
676
        // selective value output should be set during corresponding function execution
677 678 679
        if (fmIsSelectValueFunc(pfCtx->functionId)) {
          continue;
        }
680 681
        // _group_key function for "partition by tbname" + csum(col_name) query
        SColumnInfoData* pOutput = taosArrayGet(pResult->pDataBlock, outputSlotId);
682
        int32_t          slotId = pfCtx->param[0].pCol->slotId;
683 684 685

        // todo handle the json tag
        SColumnInfoData* pInput = taosArrayGet(pSrcBlock->pDataBlock, slotId);
686
        for (int32_t f = 0; f < pSrcBlock->info.rows; ++f) {
687 688 689 690 691 692 693 694 695
          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 已提交
696 697 698
      } else {
        SArray* pBlockList = taosArrayInit(4, POINTER_BYTES);
        taosArrayPush(pBlockList, &pSrcBlock);
G
Ganlin Zhao 已提交
699

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

703
        SScalarParam dest = {.columnData = &idata};
X
Xiaoyu Wang 已提交
704
        int32_t      code = scalarCalculate((SNode*)pExpr[k].pExpr->_function.pFunctNode, pBlockList, &dest);
705 706 707 708
        if (code != TSDB_CODE_SUCCESS) {
          taosArrayDestroy(pBlockList);
          return code;
        }
709

dengyihao's avatar
dengyihao 已提交
710
        int32_t startOffset = createNewColModel ? 0 : pResult->info.rows;
711
        ASSERT(pResult->info.capacity > 0);
712
        colDataMergeCol(pResColData, startOffset, &pResult->info.capacity, &idata, dest.numOfRows);
D
dapan1121 已提交
713
        colDataDestroy(&idata);
714 715

        numOfRows = dest.numOfRows;
H
Haojun Liao 已提交
716 717
        taosArrayDestroy(pBlockList);
      }
718
    } else {
719
      ASSERT(0);
720 721
    }
  }
722

723 724 725
  if (!createNewColModel) {
    pResult->info.rows += numOfRows;
  }
726 727

  return TSDB_CODE_SUCCESS;
728 729
}

5
54liuyao 已提交
730
bool functionNeedToExecute(SqlFunctionCtx* pCtx) {
731
  struct SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
732

733 734 735 736 737
  // in case of timestamp column, always generated results.
  int32_t functionId = pCtx->functionId;
  if (functionId == -1) {
    return false;
  }
738

739 740
  if (pCtx->scanFlag == REPEAT_SCAN) {
    return fmIsRepeatScanFunc(pCtx->functionId);
741 742
  }

743 744
  if (isRowEntryCompleted(pResInfo)) {
    return false;
745 746
  }

747 748 749
  return true;
}

750 751 752 753 754 755 756
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;
    }
757

758 759 760
    // Set the correct column info (data type and bytes)
    pInput->pData[paramIndex]->info.type = type;
    pInput->pData[paramIndex]->info.bytes = tDataTypes[type].bytes;
761
  }
H
Haojun Liao 已提交
762

763 764 765 766 767 768
  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;
769 770
    }
  } else {
771
    da = pInput->pColumnDataAgg[paramIndex];
772 773
  }

774
  ASSERT(!IS_VAR_DATA_TYPE(type));
775

776 777
  if (type == TSDB_DATA_TYPE_BIGINT) {
    int64_t v = pFuncParam->param.i;
778
    *da = (SColumnDataAgg){.numOfNull = 0, .min = v, .max = v, .sum = v * numOfRows};
779 780
  } else if (type == TSDB_DATA_TYPE_DOUBLE) {
    double v = pFuncParam->param.d;
781
    *da = (SColumnDataAgg){.numOfNull = 0};
782

783 784 785 786 787 788
    *(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;

789
    *da = (SColumnDataAgg){.numOfNull = 0};
790 791 792 793 794
    *(bool*)&da->min = 0;
    *(bool*)&da->max = v;
    *(bool*)&da->sum = v * numOfRows;
  } else if (type == TSDB_DATA_TYPE_TIMESTAMP) {
    // do nothing
795
  } else {
796
    ASSERT(0);
797 798
  }

799 800
  return TSDB_CODE_SUCCESS;
}
801 802 803 804 805 806 807 808 809 810 811

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

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

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

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

815 816
      if (pFuncParam->type == FUNC_PARAM_TYPE_COLUMN) {
        int32_t slotId = pFuncParam->pCol->slotId;
817 818 819 820
        pInput->pColumnDataAgg[j] = pBlock->pBlockAgg[slotId];
        if (pInput->pColumnDataAgg[j] == NULL) {
          pInput->colDataAggIsSet = false;
        }
821 822 823 824

        // 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);
825 826
      } else if (pFuncParam->type == FUNC_PARAM_TYPE_VALUE) {
        doCreateConstantValColumnAggInfo(pInput, pFuncParam, pFuncParam->param.nType, j, pBlock->info.rows);
827 828
      }
    }
829
  } else {
830
    pInput->colDataAggIsSet = false;
831 832 833
  }

  // set the statistics data for primary time stamp column
834 835 836 837 838
  //  if (pCtx->functionId == FUNCTION_SPREAD && pColumn->colId == PRIMARYKEY_TIMESTAMP_COL_ID) {
  //    pCtx->isAggSet = true;
  //    pCtx->agg.min = pBlock->info.window.skey;
  //    pCtx->agg.max = pBlock->info.window.ekey;
  //  }
839 840
}

L
Liu Jicong 已提交
841
bool isTaskKilled(SExecTaskInfo* pTaskInfo) {
842 843
  // query has been executed more than tsShellActivityTimer, and the retrieve has not arrived
  // abort current query execution.
L
Liu Jicong 已提交
844 845
  if (pTaskInfo->owner != 0 &&
      ((taosGetTimestampSec() - pTaskInfo->cost.start / 1000) > 10 * getMaximumIdleDurationSec())
846 847
      /*(!needBuildResAfterQueryComplete(pTaskInfo))*/) {
    assert(pTaskInfo->cost.start != 0);
L
Liu Jicong 已提交
848 849 850
    //    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;
851 852 853 854 855
  }

  return false;
}

L
Liu Jicong 已提交
856
void setTaskKilled(SExecTaskInfo* pTaskInfo) { pTaskInfo->code = TSDB_CODE_TSC_QUERY_CANCELLED; }
857 858

/////////////////////////////////////////////////////////////////////////////////////////////
859
STimeWindow getAlignQueryTimeWindow(SInterval* pInterval, int32_t precision, int64_t key) {
L
Liu Jicong 已提交
860
  STimeWindow win = {0};
861
  win.skey = taosTimeTruncate(key, pInterval, precision);
862 863

  /*
H
Haojun Liao 已提交
864
   * if the realSkey > INT64_MAX - pInterval->interval, the query duration between
865 866
   * realSkey and realEkey must be less than one interval.Therefore, no need to adjust the query ranges.
   */
867 868 869
  win.ekey = taosTimeAdd(win.skey, pInterval->interval, pInterval->intervalUnit, precision) - 1;
  if (win.ekey < win.skey) {
    win.ekey = INT64_MAX;
870
  }
871 872

  return win;
873 874
}

875
#if 0
L
Liu Jicong 已提交
876
static int32_t updateBlockLoadStatus(STaskAttr* pQuery, int32_t status) {
877

878 879 880
  bool hasFirstLastFunc = false;
  bool hasOtherFunc = false;

881
  if (status == BLK_DATA_DATA_LOAD || status == BLK_DATA_FILTEROUT) {
882 883 884 885 886
    return status;
  }

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

888 889 890 891 892 893 894 895 896 897
    if (functionId == FUNCTION_TS || functionId == FUNCTION_TS_DUMMY || functionId == FUNCTION_TAG ||
        functionId == FUNCTION_TAG_DUMMY) {
      continue;
    }

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

899 900
  }

901
  if (hasFirstLastFunc && status == BLK_DATA_NOT_LOAD) {
L
Liu Jicong 已提交
902
    if (!hasOtherFunc) {
903
      return BLK_DATA_FILTEROUT;
904
    } else {
905
      return BLK_DATA_DATA_LOAD;
906 907 908 909 910 911
    }
  }

  return status;
}

912 913
#endif

L
Liu Jicong 已提交
914 915
// static void updateDataCheckOrder(SQInfo *pQInfo, SQueryTableReq* pQueryMsg, bool stableQuery) {
//   STaskAttr* pQueryAttr = pQInfo->runtimeEnv.pQueryAttr;
H
Haojun Liao 已提交
916
//
L
Liu Jicong 已提交
917 918 919 920
//   // in case of point-interpolation query, use asc order scan
//   char msg[] = "QInfo:0x%"PRIx64" scan order changed for %s query, old:%d, new:%d, qrange exchanged, old qrange:%"
//   PRId64
//                "-%" PRId64 ", new qrange:%" PRId64 "-%" PRId64;
H
Haojun Liao 已提交
921
//
L
Liu Jicong 已提交
922 923 924 925 926
//   // todo handle the case the the order irrelevant query type mixed up with order critical query type
//   // descending order query for last_row query
//   if (isFirstLastRowQuery(pQueryAttr)) {
//     //qDebug("QInfo:0x%"PRIx64" scan order changed for last_row query, old:%d, new:%d", pQInfo->qId,
//     pQueryAttr->order.order, TSDB_ORDER_ASC);
H
Haojun Liao 已提交
927
//
L
Liu Jicong 已提交
928 929
//     pQueryAttr->order.order = TSDB_ORDER_ASC;
//     if (pQueryAttr->window.skey > pQueryAttr->window.ekey) {
wafwerar's avatar
wafwerar 已提交
930
//       TSWAP(pQueryAttr->window.skey, pQueryAttr->window.ekey);
L
Liu Jicong 已提交
931
//     }
H
Haojun Liao 已提交
932
//
L
Liu Jicong 已提交
933 934 935
//     pQueryAttr->needReverseScan = false;
//     return;
//   }
H
Haojun Liao 已提交
936
//
L
Liu Jicong 已提交
937 938 939
//   if (pQueryAttr->groupbyColumn && pQueryAttr->order.order == TSDB_ORDER_DESC) {
//     pQueryAttr->order.order = TSDB_ORDER_ASC;
//     if (pQueryAttr->window.skey > pQueryAttr->window.ekey) {
wafwerar's avatar
wafwerar 已提交
940
//       TSWAP(pQueryAttr->window.skey, pQueryAttr->window.ekey);
L
Liu Jicong 已提交
941
//     }
H
Haojun Liao 已提交
942
//
L
Liu Jicong 已提交
943 944 945 946
//     pQueryAttr->needReverseScan = false;
//     doUpdateLastKey(pQueryAttr);
//     return;
//   }
H
Haojun Liao 已提交
947
//
L
Liu Jicong 已提交
948 949 950 951 952 953
//   if (pQueryAttr->pointInterpQuery && pQueryAttr->interval.interval == 0) {
//     if (!QUERY_IS_ASC_QUERY(pQueryAttr)) {
//       //qDebug(msg, pQInfo->qId, "interp", pQueryAttr->order.order, TSDB_ORDER_ASC, pQueryAttr->window.skey,
//       pQueryAttr->window.ekey, pQueryAttr->window.ekey, pQueryAttr->window.skey); TSWAP(pQueryAttr->window.skey,
//       pQueryAttr->window.ekey, TSKEY);
//     }
H
Haojun Liao 已提交
954
//
L
Liu Jicong 已提交
955 956 957
//     pQueryAttr->order.order = TSDB_ORDER_ASC;
//     return;
//   }
H
Haojun Liao 已提交
958
//
L
Liu Jicong 已提交
959 960 961 962
//   if (pQueryAttr->interval.interval == 0) {
//     if (onlyFirstQuery(pQueryAttr)) {
//       if (!QUERY_IS_ASC_QUERY(pQueryAttr)) {
//         //qDebug(msg, pQInfo->qId, "only-first", pQueryAttr->order.order, TSDB_ORDER_ASC, pQueryAttr->window.skey,
H
Haojun Liao 已提交
963 964
////               pQueryAttr->window.ekey, pQueryAttr->window.ekey, pQueryAttr->window.skey);
//
wafwerar's avatar
wafwerar 已提交
965
//        TSWAP(pQueryAttr->window.skey, pQueryAttr->window.ekey);
H
Haojun Liao 已提交
966 967 968 969 970 971 972 973 974 975
//        doUpdateLastKey(pQueryAttr);
//      }
//
//      pQueryAttr->order.order = TSDB_ORDER_ASC;
//      pQueryAttr->needReverseScan = false;
//    } else if (onlyLastQuery(pQueryAttr) && notContainSessionOrStateWindow(pQueryAttr)) {
//      if (QUERY_IS_ASC_QUERY(pQueryAttr)) {
//        //qDebug(msg, pQInfo->qId, "only-last", pQueryAttr->order.order, TSDB_ORDER_DESC, pQueryAttr->window.skey,
////               pQueryAttr->window.ekey, pQueryAttr->window.ekey, pQueryAttr->window.skey);
//
wafwerar's avatar
wafwerar 已提交
976
//        TSWAP(pQueryAttr->window.skey, pQueryAttr->window.ekey);
H
Haojun Liao 已提交
977 978 979 980 981 982 983 984 985 986 987 988
//        doUpdateLastKey(pQueryAttr);
//      }
//
//      pQueryAttr->order.order = TSDB_ORDER_DESC;
//      pQueryAttr->needReverseScan = false;
//    }
//
//  } else {  // interval query
//    if (stableQuery) {
//      if (onlyFirstQuery(pQueryAttr)) {
//        if (!QUERY_IS_ASC_QUERY(pQueryAttr)) {
//          //qDebug(msg, pQInfo->qId, "only-first stable", pQueryAttr->order.order, TSDB_ORDER_ASC,
L
Liu Jicong 已提交
989 990
////                 pQueryAttr->window.skey, pQueryAttr->window.ekey, pQueryAttr->window.ekey,
/// pQueryAttr->window.skey);
H
Haojun Liao 已提交
991
//
wafwerar's avatar
wafwerar 已提交
992
//          TSWAP(pQueryAttr->window.skey, pQueryAttr->window.ekey);
H
Haojun Liao 已提交
993 994 995 996 997 998 999 1000
//          doUpdateLastKey(pQueryAttr);
//        }
//
//        pQueryAttr->order.order = TSDB_ORDER_ASC;
//        pQueryAttr->needReverseScan = false;
//      } else if (onlyLastQuery(pQueryAttr)) {
//        if (QUERY_IS_ASC_QUERY(pQueryAttr)) {
//          //qDebug(msg, pQInfo->qId, "only-last stable", pQueryAttr->order.order, TSDB_ORDER_DESC,
L
Liu Jicong 已提交
1001 1002
////                 pQueryAttr->window.skey, pQueryAttr->window.ekey, pQueryAttr->window.ekey,
/// pQueryAttr->window.skey);
H
Haojun Liao 已提交
1003
//
wafwerar's avatar
wafwerar 已提交
1004
//          TSWAP(pQueryAttr->window.skey, pQueryAttr->window.ekey);
H
Haojun Liao 已提交
1005 1006 1007 1008 1009 1010 1011 1012 1013
//          doUpdateLastKey(pQueryAttr);
//        }
//
//        pQueryAttr->order.order = TSDB_ORDER_DESC;
//        pQueryAttr->needReverseScan = false;
//      }
//    }
//  }
//}
1014

L
Liu Jicong 已提交
1015 1016 1017
// static FORCE_INLINE bool doFilterByBlockStatistics(STaskRuntimeEnv* pRuntimeEnv, SDataStatis *pDataStatis,
// SqlFunctionCtx *pCtx, int32_t numOfRows) {
//   STaskAttr* pQueryAttr = pRuntimeEnv->pQueryAttr;
1018
//
L
Liu Jicong 已提交
1019 1020 1021
//   if (pDataStatis == NULL || pQueryAttr->pFilters == NULL) {
//     return true;
//   }
1022
//
L
Liu Jicong 已提交
1023 1024
//   return filterRangeExecute(pQueryAttr->pFilters, pDataStatis, pQueryAttr->numOfCols, numOfRows);
// }
1025
#if 0
H
Haojun Liao 已提交
1026
static bool overlapWithTimeWindow(STaskAttr* pQueryAttr, SDataBlockInfo* pBlockInfo) {
1027 1028
  STimeWindow w = {0};

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

1032
  if (true) {
L
Liu Jicong 已提交
1033
    //    getAlignQueryTimeWindow(pQueryAttr, pBlockInfo->window.skey, sk, ek, &w);
1034 1035 1036 1037 1038 1039
    assert(w.ekey >= pBlockInfo->window.skey);

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

L
Liu Jicong 已提交
1040 1041
    while (1) {
      //      getNextTimeWindow(pQueryAttr, &w);
1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
      if (w.skey > pBlockInfo->window.ekey) {
        break;
      }

      assert(w.ekey > pBlockInfo->window.ekey);
      if (w.skey <= pBlockInfo->window.ekey && w.skey > pBlockInfo->window.skey) {
        return true;
      }
    }
  } else {
L
Liu Jicong 已提交
1052
    //    getAlignQueryTimeWindow(pQueryAttr, pBlockInfo->window.ekey, sk, ek, &w);
1053 1054 1055 1056 1057 1058
    assert(w.skey <= pBlockInfo->window.ekey);

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

L
Liu Jicong 已提交
1059 1060
    while (1) {
      //      getNextTimeWindow(pQueryAttr, &w);
1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073
      if (w.ekey < pBlockInfo->window.skey) {
        break;
      }

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

  return false;
}
1074
#endif
1075 1076

static uint32_t doFilterByBlockTimeWindow(STableScanInfo* pTableScanInfo, SSDataBlock* pBlock) {
H
Haojun Liao 已提交
1077
#if 0
H
Haojun Liao 已提交
1078
  SqlFunctionCtx* pCtx = pTableScanInfo->pCtx;
1079
  uint32_t        status = BLK_DATA_NOT_LOAD;
1080

L
Liu Jicong 已提交
1081
  int32_t numOfOutput = 0;  // pTableScanInfo->numOfOutput;
1082 1083
  for (int32_t i = 0; i < numOfOutput; ++i) {
    int32_t functionId = pCtx[i].functionId;
H
Haojun Liao 已提交
1084
    int32_t colId = pTableScanInfo->pExpr[i].base.pParam[0].pCol->colId;
1085 1086 1087

    // group by + first/last should not apply the first/last block filter
    if (functionId < 0) {
1088
      status |= BLK_DATA_DATA_LOAD;
1089 1090
      return status;
    } else {
L
Liu Jicong 已提交
1091
      //      status |= aAggs[functionId].dataReqFunc(&pTableScanInfo->pCtx[i], &pBlock->info.window, colId);
1092
      //      if ((status & BLK_DATA_DATA_LOAD) == BLK_DATA_DATA_LOAD) {
L
Liu Jicong 已提交
1093 1094
      //        return status;
      //      }
1095 1096 1097 1098
    }
  }

  return status;
H
Haojun Liao 已提交
1099 1100
#endif
  return 0;
1101 1102
}

L
Liu Jicong 已提交
1103 1104
int32_t loadDataBlockOnDemand(SExecTaskInfo* pTaskInfo, STableScanInfo* pTableScanInfo, SSDataBlock* pBlock,
                              uint32_t* status) {
1105
  *status = BLK_DATA_NOT_LOAD;
1106

H
Haojun Liao 已提交
1107
  pBlock->pDataBlock = NULL;
L
Liu Jicong 已提交
1108
  pBlock->pBlockAgg = NULL;
H
Haojun Liao 已提交
1109

L
Liu Jicong 已提交
1110 1111
  //  int64_t groupId = pRuntimeEnv->current->groupIndex;
  //  bool    ascQuery = QUERY_IS_ASC_QUERY(pQueryAttr);
1112

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

1115 1116
//  pCost->totalBlocks += 1;
//  pCost->totalRows += pBlock->info.rows;
H
Haojun Liao 已提交
1117
#if 0
1118 1119 1120
  // 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 已提交
1121
      (QUERY_IS_INTERVAL_QUERY(pQueryAttr) && overlapWithTimeWindow(pTaskInfo, &pBlock->info))) {
1122
    (*status) = BLK_DATA_DATA_LOAD;
1123 1124 1125
  }

  // check if this data block is required to load
1126
  if ((*status) != BLK_DATA_DATA_LOAD) {
1127 1128 1129 1130 1131 1132 1133
    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 已提交
1134
      bool  masterScan = IS_MAIN_SCAN(pRuntimeEnv);
1135 1136 1137 1138 1139 1140
      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,
1141
                                    pTableScanInfo->rowEntryInfoOffset);
1142 1143 1144
      } else {
        if (setResultOutputBufByKey(pRuntimeEnv, pTableScanInfo->pResultRowInfo, pBlock->info.uid, &win, masterScan, &pResult, groupId,
                                    pTableScanInfo->pCtx, pTableScanInfo->numOfOutput,
1145
                                    pTableScanInfo->rowEntryInfoOffset) != TSDB_CODE_SUCCESS) {
1146 1147 1148 1149 1150
          longjmp(pRuntimeEnv->env, TSDB_CODE_QRY_OUT_OF_MEMORY);
        }
      }
    } else if (pQueryAttr->stableQuery && (!pQueryAttr->tsCompQuery) && (!pQueryAttr->diffQuery)) { // stable aggregate, not interval aggregate or normal column aggregate
      doSetTableGroupOutputBuf(pRuntimeEnv, pTableScanInfo->pResultRowInfo, pTableScanInfo->pCtx,
1151
                               pTableScanInfo->rowEntryInfoOffset, pTableScanInfo->numOfOutput,
1152 1153 1154 1155 1156 1157
                               pRuntimeEnv->current->groupIndex);
    }

    if (needFilter) {
      (*status) = doFilterByBlockTimeWindow(pTableScanInfo, pBlock);
    } else {
1158
      (*status) = BLK_DATA_DATA_LOAD;
1159 1160 1161 1162
    }
  }

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

1165
  if ((*status) == BLK_DATA_NOT_LOAD || (*status) == BLK_DATA_FILTEROUT) {
1166 1167
    //qDebug("QInfo:0x%"PRIx64" data block discard, brange:%" PRId64 "-%" PRId64 ", rows:%d", pQInfo->qId, pBlockInfo->window.skey,
//           pBlockInfo->window.ekey, pBlockInfo->rows);
1168
    pCost->skipBlocks += 1;
1169
  } else if ((*status) == BLK_DATA_SMA_LOAD) {
1170 1171
    // this function never returns error?
    pCost->loadBlockStatis += 1;
1172
//    tsdbRetrieveDatablockSMA(pTableScanInfo->pTsdbReadHandle, &pBlock->pBlockAgg);
1173 1174

    if (pBlock->pBlockAgg == NULL) {  // data block statistics does not exist, load data block
1175
//      pBlock->pDataBlock = tsdbRetrieveDataBlock(pTableScanInfo->pTsdbReadHandle, NULL);
1176 1177 1178
      pCost->totalCheckedRows += pBlock->info.rows;
    }
  } else {
1179
    assert((*status) == BLK_DATA_DATA_LOAD);
1180 1181 1182

    // load the data block statistics to perform further filter
    pCost->loadBlockStatis += 1;
1183
//    tsdbRetrieveDatablockSMA(pTableScanInfo->pTsdbReadHandle, &pBlock->pBlockAgg);
1184 1185 1186 1187 1188 1189

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

H
Haojun Liao 已提交
1190
          bool  masterScan = IS_MAIN_SCAN(pRuntimeEnv);
1191 1192 1193 1194 1195
          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,
1196
                                      pTableScanInfo->rowEntryInfoOffset) != TSDB_CODE_SUCCESS) {
1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207
            longjmp(pRuntimeEnv->env, TSDB_CODE_QRY_OUT_OF_MEMORY);
          }
        }
      }
      bool load = false;
      for (int32_t i = 0; i < pQueryAttr->numOfOutput; ++i) {
        int32_t functionId = pTableScanInfo->pCtx[i].functionId;
        if (functionId == FUNCTION_TOP || functionId == FUNCTION_BOTTOM) {
//          load = topbot_datablock_filter(&pTableScanInfo->pCtx[i], (char*)&(pBlock->pBlockAgg[i].min),
//                                         (char*)&(pBlock->pBlockAgg[i].max));
          if (!load) { // current block has been discard due to filter applied
1208
            pCost->skipBlocks += 1;
1209 1210
            //qDebug("QInfo:0x%"PRIx64" data block discard, brange:%" PRId64 "-%" PRId64 ", rows:%d", pQInfo->qId,
//                   pBlockInfo->window.skey, pBlockInfo->window.ekey, pBlockInfo->rows);
1211
            (*status) = BLK_DATA_FILTEROUT;
1212 1213 1214 1215 1216 1217 1218 1219
            return TSDB_CODE_SUCCESS;
          }
        }
      }
    }

    // current block has been discard due to filter applied
//    if (!doFilterByBlockStatistics(pRuntimeEnv, pBlock->pBlockAgg, pTableScanInfo->pCtx, pBlockInfo->rows)) {
1220
//      pCost->skipBlocks += 1;
1221 1222
//      qDebug("QInfo:0x%"PRIx64" data block discard, brange:%" PRId64 "-%" PRId64 ", rows:%d", pQInfo->qId, pBlockInfo->window.skey,
//             pBlockInfo->window.ekey, pBlockInfo->rows);
1223
//      (*status) = BLK_DATA_FILTEROUT;
1224 1225 1226 1227 1228
//      return TSDB_CODE_SUCCESS;
//    }

    pCost->totalCheckedRows += pBlockInfo->rows;
    pCost->loadBlocks += 1;
1229
//    pBlock->pDataBlock = tsdbRetrieveDataBlock(pTableScanInfo->pTsdbReadHandle, NULL);
1230 1231 1232 1233 1234
//    if (pBlock->pDataBlock == NULL) {
//      return terrno;
//    }

//    if (pQueryAttr->pFilters != NULL) {
1235
//      filterSetColFieldData(pQueryAttr->pFilters, taosArrayGetSize(pBlock->pDataBlock), pBlock->pDataBlock);
1236
//    }
1237

1238 1239 1240 1241
//    if (pQueryAttr->pFilters != NULL || pRuntimeEnv->pTsBuf != NULL) {
//      filterColRowsInDataBlock(pRuntimeEnv, pBlock, ascQuery);
//    }
  }
H
Haojun Liao 已提交
1242
#endif
1243 1244 1245
  return TSDB_CODE_SUCCESS;
}

L
Liu Jicong 已提交
1246
static void updateTableQueryInfoForReverseScan(STableQueryInfo* pTableQueryInfo) {
1247 1248 1249 1250
  if (pTableQueryInfo == NULL) {
    return;
  }

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

L
Liu Jicong 已提交
1254 1255
  //  SWITCH_ORDER(pTableQueryInfo->cur.order);
  //  pTableQueryInfo->cur.vgroupIndex = -1;
1256 1257

  // set the index to be the end slot of result rows array
dengyihao's avatar
dengyihao 已提交
1258 1259 1260 1261 1262 1263
  //  SResultRowInfo* pResultRowInfo = &pTableQueryInfo->resInfo;
  //  if (pResultRowInfo->size > 0) {
  //    pResultRowInfo->curPos = pResultRowInfo->size - 1;
  //  } else {
  //    pResultRowInfo->curPos = -1;
  //  }
1264 1265
}

H
Haojun Liao 已提交
1266
void initResultRow(SResultRow* pResultRow) {
X
Xiaoyu Wang 已提交
1267
  //  pResultRow->pEntryInfo = (struct SResultRowEntryInfo*)((char*)pResultRow + sizeof(SResultRow));
1268 1269
}

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

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

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

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

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

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

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

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

1314
void doFilter(const SNode* pFilterNode, SSDataBlock* pBlock, const SArray* pColMatchInfo) {
1315
  if (pFilterNode == NULL || pBlock->info.rows == 0) {
S
shenglian zhou 已提交
1316 1317
    return;
  }
1318

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

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

1324
  size_t             numOfCols = taosArrayGetSize(pBlock->pDataBlock);
1325
  SFilterColumnParam param1 = {.numOfCols = numOfCols, .pDataBlock = pBlock->pDataBlock};
1326 1327 1328
  code = filterSetDataFromSlotId(filter, &param1);

  int8_t* rowRes = NULL;
1329

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

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

  if (pColMatchInfo != NULL) {
1337
    for (int32_t i = 0; i < taosArrayGetSize(pColMatchInfo); ++i) {
1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348
      SColMatchInfo* pInfo = taosArrayGet(pColMatchInfo, i);
      if (pInfo->colId == PRIMARYKEY_TIMESTAMP_COL_ID) {
        SColumnInfoData* pColData = taosArrayGet(pBlock->pDataBlock, pInfo->targetSlotId);
        if (pColData->info.type == TSDB_DATA_TYPE_TIMESTAMP) {
          blockDataUpdateTsWindow(pBlock, pInfo->targetSlotId);
          break;
        }
      }
    }
  }

H
Haojun Liao 已提交
1349
  taosMemoryFree(rowRes);
1350 1351
}

H
Haojun Liao 已提交
1352
void extractQualifiedTupleByFilterResult(SSDataBlock* pBlock, const int8_t* rowRes, bool keep) {
1353 1354 1355 1356 1357
  if (keep) {
    return;
  }

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

1361 1362
    size_t numOfCols = taosArrayGetSize(pBlock->pDataBlock);
    for (int32_t i = 0; i < numOfCols; ++i) {
1363 1364
      SColumnInfoData* pSrc = taosArrayGet(px->pDataBlock, i);
      SColumnInfoData* pDst = taosArrayGet(pBlock->pDataBlock, i);
1365
      // it is a reserved column for scalar function, and no data in this column yet.
1366
      if (pDst->pData == NULL || pSrc->pData == NULL) {
1367 1368 1369
        continue;
      }

1370 1371
      colInfoDataCleanup(pDst, pBlock->info.rows);

1372
      int32_t numOfRows = 0;
1373
      for (int32_t j = 0; j < totalRows; ++j) {
D
dapan1121 已提交
1374 1375 1376
        if (rowRes[j] == 0) {
          continue;
        }
1377

D
dapan1121 已提交
1378
        if (colDataIsNull_s(pSrc, j)) {
1379
          colDataAppendNULL(pDst, numOfRows);
D
dapan1121 已提交
1380
        } else {
1381
          colDataAppend(pDst, numOfRows, colDataGetData(pSrc, j), false);
D
dapan1121 已提交
1382
        }
1383
        numOfRows += 1;
H
Haojun Liao 已提交
1384
      }
1385

1386 1387 1388 1389 1390
      if (pBlock->info.rows == totalRows) {
        pBlock->info.rows = numOfRows;
      } else {
        ASSERT(pBlock->info.rows == numOfRows);
      }
1391
    }
1392

dengyihao's avatar
dengyihao 已提交
1393
    blockDataDestroy(px);  // fix memory leak
1394 1395 1396
  } else {
    // do nothing
    pBlock->info.rows = 0;
1397 1398 1399
  }
}

1400
void doSetTableGroupOutputBuf(SOperatorInfo* pOperator, int32_t numOfOutput, uint64_t groupId) {
1401
  // for simple group by query without interval, all the tables belong to one group result.
1402 1403 1404
  SExecTaskInfo*    pTaskInfo = pOperator->pTaskInfo;
  SAggOperatorInfo* pAggInfo = pOperator->info;

1405
  SResultRowInfo* pResultRowInfo = &pAggInfo->binfo.resultRowInfo;
1406 1407
  SqlFunctionCtx* pCtx = pOperator->exprSupp.pCtx;
  int32_t*        rowEntryInfoOffset = pOperator->exprSupp.rowEntryInfoOffset;
1408

1409
  SResultRow* pResultRow = doSetResultOutBufByKey(pAggInfo->aggSup.pResultBuf, pResultRowInfo, (char*)&groupId,
L
Liu Jicong 已提交
1410
                                                  sizeof(groupId), true, groupId, pTaskInfo, false, &pAggInfo->aggSup);
L
Liu Jicong 已提交
1411
  assert(pResultRow != NULL);
1412 1413 1414 1415 1416 1417

  /*
   * 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 已提交
1418 1419
    int32_t ret =
        addNewWindowResultBuf(pResultRow, pAggInfo->aggSup.pResultBuf, groupId, pAggInfo->binfo.pRes->info.rowSize);
1420 1421 1422 1423 1424
    if (ret != TSDB_CODE_SUCCESS) {
      return;
    }
  }

1425
  setResultRowInitCtx(pResultRow, pCtx, numOfOutput, rowEntryInfoOffset);
1426 1427
}

1428 1429 1430
static void setExecutionContext(SOperatorInfo* pOperator, int32_t numOfOutput, uint64_t groupId) {
  SAggOperatorInfo* pAggInfo = pOperator->info;
  if (pAggInfo->groupId != UINT64_MAX && pAggInfo->groupId == groupId) {
1431 1432
    return;
  }
1433 1434

  doSetTableGroupOutputBuf(pOperator, numOfOutput, groupId);
1435 1436

  // record the current active group id
H
Haojun Liao 已提交
1437
  pAggInfo->groupId = groupId;
1438 1439
}

1440 1441
static void doUpdateNumOfRows(SResultRow* pRow, int32_t numOfExprs, const int32_t* rowCellOffset) {
  for (int32_t j = 0; j < numOfExprs; ++j) {
1442
    struct SResultRowEntryInfo* pResInfo = getResultEntryInfo(pRow, j, rowCellOffset);
1443 1444 1445 1446 1447 1448 1449 1450 1451 1452
    if (!isRowEntryInitialized(pResInfo)) {
      continue;
    }

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

1453
// todo extract method with copytoSSDataBlock
1454
int32_t finalizeResultRowIntoResultDataBlock(SDiskbasedBuf* pBuf, SResultRowPosition* resultRowPosition,
S
shenglian zhou 已提交
1455 1456 1457
                                             SqlFunctionCtx* pCtx, SExprInfo* pExprInfo, int32_t numOfExprs,
                                             const int32_t* rowCellOffset, SSDataBlock* pBlock,
                                             SExecTaskInfo* pTaskInfo) {
1458 1459 1460 1461 1462 1463 1464 1465 1466
  SFilePage*  page = getBufPage(pBuf, resultRowPosition->pageId);
  SResultRow* pRow = (SResultRow*)((char*)page + resultRowPosition->offset);

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

1467 1468 1469 1470 1471 1472 1473
  while (pBlock->info.rows + pRow->numOfRows > pBlock->info.capacity) {
    int32_t code = blockDataEnsureCapacity(pBlock, pBlock->info.capacity * 1.25);
    if (TAOS_FAILED(code)) {
      releaseBufPage(pBuf, page);
      qError("%s ensure result data capacity failed, code %s", GET_TASKID(pTaskInfo), tstrerror(code));
      longjmp(pTaskInfo->env, code);
    }
1474 1475 1476 1477 1478
  }

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

1479
    pCtx[j].resultInfo = getResultEntryInfo(pRow, j, rowCellOffset);
1480 1481 1482 1483 1484 1485 1486 1487 1488
    if (pCtx[j].fpSet.finalize) {
      int32_t code = pCtx[j].fpSet.finalize(&pCtx[j], pBlock);
      if (TAOS_FAILED(code)) {
        qError("%s build result data block error, code %s", GET_TASKID(pTaskInfo), tstrerror(code));
        longjmp(pTaskInfo->env, code);
      }
    } else if (strcmp(pCtx[j].pExpr->pExpr->_function.functionName, "_select_value") == 0) {
      // do nothing, todo refactor
    } else {
1489 1490
      // 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.
1491 1492 1493 1494 1495 1496 1497 1498 1499
      SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, slotId);
      char*            in = GET_ROWCELL_INTERBUF(pCtx[j].resultInfo);
      for (int32_t k = 0; k < pRow->numOfRows; ++k) {
        colDataAppend(pColInfoData, pBlock->info.rows + k, in, pCtx[j].resultInfo->isNullRes);
      }
    }
  }

  releaseBufPage(pBuf, page);
1500
  pBlock->info.rows += pRow->numOfRows;
1501 1502 1503 1504

  return 0;
}

X
Xiaoyu Wang 已提交
1505 1506 1507
int32_t doCopyToSDataBlock(SExecTaskInfo* pTaskInfo, SSDataBlock* pBlock, SExprInfo* pExprInfo, SDiskbasedBuf* pBuf,
                           SGroupResInfo* pGroupResInfo, const int32_t* rowCellOffset, SqlFunctionCtx* pCtx,
                           int32_t numOfExprs) {
1508
  int32_t numOfRows = getNumOfTotalRes(pGroupResInfo);
1509
  int32_t start = pGroupResInfo->index;
1510

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

1515
    SResultRow* pRow = (SResultRow*)((char*)page + pPos->pos.offset);
1516 1517

    doUpdateNumOfRows(pRow, numOfExprs, rowCellOffset);
1518 1519
    if (pRow->numOfRows == 0) {
      pGroupResInfo->index += 1;
1520
      releaseBufPage(pBuf, page);
1521 1522 1523
      continue;
    }

1524 1525 1526 1527 1528
    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) {
1529
        releaseBufPage(pBuf, page);
1530 1531 1532 1533
        break;
      }
    }

1534
    if (pBlock->info.rows + pRow->numOfRows > pBlock->info.capacity) {
1535
      releaseBufPage(pBuf, page);
1536 1537 1538 1539 1540
      break;
    }

    pGroupResInfo->index += 1;

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

1544
      pCtx[j].resultInfo = getResultEntryInfo(pRow, j, rowCellOffset);
1545
      if (pCtx[j].fpSet.finalize) {
1546
#ifdef BUF_PAGE_DEBUG
wmmhello's avatar
wmmhello 已提交
1547
        qDebug("\npage_finalize %d", numOfExprs);
1548
#endif
1549
        int32_t code = pCtx[j].fpSet.finalize(&pCtx[j], pBlock);
1550
        if (TAOS_FAILED(code)) {
1551 1552
          qError("%s build result data block error, code %s", GET_TASKID(pTaskInfo), tstrerror(code));
          longjmp(pTaskInfo->env, code);
1553
        }
1554 1555
      } else if (strcmp(pCtx[j].pExpr->pExpr->_function.functionName, "_select_value") == 0) {
        // do nothing, todo refactor
1556
      } else {
1557 1558
        // expand the result into multiple rows. E.g., _wstart, top(k, 20)
        // the _wstart needs to copy to 20 following rows, since the results of top-k expands to 20 different rows.
X
Xiaoyu Wang 已提交
1559 1560
        SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, slotId);
        char*            in = GET_ROWCELL_INTERBUF(pCtx[j].resultInfo);
1561
        if (pCtx[j].increase) {
L
Liu Jicong 已提交
1562
          int64_t ts = *(int64_t*)in;
1563
          for (int32_t k = 0; k < pRow->numOfRows; ++k) {
L
Liu Jicong 已提交
1564
            colDataAppend(pColInfoData, pBlock->info.rows + k, (const char*)&ts, pCtx[j].resultInfo->isNullRes);
1565 1566 1567 1568 1569 1570
            ts++;
          }
        } else {
          for (int32_t k = 0; k < pRow->numOfRows; ++k) {
            colDataAppend(pColInfoData, pBlock->info.rows + k, in, pCtx[j].resultInfo->isNullRes);
          }
X
Xiaoyu Wang 已提交
1571
        }
1572
      }
1573 1574
    }

1575
    releaseBufPage(pBuf, page);
1576
    pBlock->info.rows += pRow->numOfRows;
L
Liu Jicong 已提交
1577 1578 1579
    //    if (pBlock->info.rows >= pBlock->info.capacity) {  // output buffer is full
    //      break;
    //    }
1580 1581
  }

X
Xiaoyu Wang 已提交
1582 1583
  qDebug("%s result generated, rows:%d, groupId:%" PRIu64, GET_TASKID(pTaskInfo), pBlock->info.rows,
         pBlock->info.groupId);
1584
  blockDataUpdateTsWindow(pBlock, 0);
1585 1586 1587
  return 0;
}

X
Xiaoyu Wang 已提交
1588 1589
void doBuildResultDatablock(SOperatorInfo* pOperator, SOptrBasicInfo* pbInfo, SGroupResInfo* pGroupResInfo,
                            SDiskbasedBuf* pBuf) {
1590 1591
  SExprInfo*     pExprInfo = pOperator->exprSupp.pExprInfo;
  int32_t        numOfExprs = pOperator->exprSupp.numOfExprs;
1592 1593
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;

1594
  int32_t*        rowCellOffset = pOperator->exprSupp.rowEntryInfoOffset;
X
Xiaoyu Wang 已提交
1595
  SSDataBlock*    pBlock = pbInfo->pRes;
1596
  SqlFunctionCtx* pCtx = pOperator->exprSupp.pCtx;
1597

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

1601
  blockDataCleanup(pBlock);
1602
  if (!hasRemainResults(pGroupResInfo)) {
1603 1604 1605
    return;
  }

1606 1607
  // clear the existed group id
  pBlock->info.groupId = 0;
1608
  doCopyToSDataBlock(pTaskInfo, pBlock, pExprInfo, pBuf, pGroupResInfo, rowCellOffset, pCtx, numOfExprs);
1609 1610
}

L
Liu Jicong 已提交
1611
static void updateNumOfRowsInResultRows(SqlFunctionCtx* pCtx, int32_t numOfOutput, SResultRowInfo* pResultRowInfo,
1612
                                        int32_t* rowEntryInfoOffset) {
1613
  // update the number of result for each, only update the number of rows for the corresponding window result.
L
Liu Jicong 已提交
1614 1615 1616
  //  if (QUERY_IS_INTERVAL_QUERY(pQueryAttr)) {
  //    return;
  //  }
H
Haojun Liao 已提交
1617
#if 0
1618
  for (int32_t i = 0; i < pResultRowInfo->size; ++i) {
L
Liu Jicong 已提交
1619
    SResultRow* pResult = pResultRowInfo->pResult[i];
1620 1621 1622 1623 1624 1625 1626

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

1627
      SResultRowEntryInfo* pCell = getResultEntryInfo(pResult, j, rowEntryInfoOffset);
1628
      pResult->numOfRows = (uint16_t)(TMAX(pResult->numOfRows, pCell->numOfRes));
1629 1630
    }
  }
H
Haojun Liao 已提交
1631
#endif
1632 1633
}

L
Liu Jicong 已提交
1634
static int32_t compressQueryColData(SColumnInfoData* pColRes, int32_t numOfRows, char* data, int8_t compressed) {
1635 1636
  int32_t colSize = pColRes->info.bytes * numOfRows;
  return (*(tDataTypes[pColRes->info.type].compFunc))(pColRes->pData, colSize, numOfRows, data,
L
Liu Jicong 已提交
1637
                                                      colSize + COMP_OVERFLOW_BYTES, compressed, NULL, 0);
1638 1639
}

L
Liu Jicong 已提交
1640 1641
void queryCostStatis(SExecTaskInfo* pTaskInfo) {
  STaskCostInfo* pSummary = &pTaskInfo->cost;
1642

L
Liu Jicong 已提交
1643 1644 1645
  //  uint64_t hashSize = taosHashGetMemSize(pQInfo->runtimeEnv.pResultRowHashTable);
  //  hashSize += taosHashGetMemSize(pRuntimeEnv->tableqinfoGroupInfo.map);
  //  pSummary->hashSize = hashSize;
1646

L
Liu Jicong 已提交
1647 1648 1649 1650 1651 1652 1653 1654 1655
  //  SResultRowPool* p = pTaskInfo->pool;
  //  if (p != NULL) {
  //    pSummary->winInfoSize = getResultRowPoolMemSize(p);
  //    pSummary->numOfTimeWindows = getNumOfAllocatedResultRows(p);
  //  } else {
  //    pSummary->winInfoSize = 0;
  //    pSummary->numOfTimeWindows = 0;
  //  }

1656 1657
  SFileBlockLoadRecorder* pRecorder = pSummary->pRecoder;
  if (pSummary->pRecoder != NULL) {
1658
    qDebug(
X
Xiaoyu Wang 已提交
1659 1660 1661 1662
        "%s :cost summary: elapsed time:%.2f ms, total blocks:%d, load block SMA:%d, load data block:%d, total "
        "rows:%" PRId64 ", check rows:%" PRId64,
        GET_TASKID(pTaskInfo), pSummary->elapsedTime / 1000.0, pRecorder->totalBlocks, pRecorder->loadBlockStatis,
        pRecorder->loadBlocks, pRecorder->totalRows, pRecorder->totalCheckedRows);
1663
  }
1664

L
Liu Jicong 已提交
1665 1666 1667
  // qDebug("QInfo:0x%"PRIx64" :cost summary: winResPool size:%.2f Kb, numOfWin:%"PRId64", tableInfoSize:%.2f Kb,
  // hashTable:%.2f Kb", pQInfo->qId, pSummary->winInfoSize/1024.0,
  //      pSummary->numOfTimeWindows, pSummary->tableInfoSize/1024.0, pSummary->hashSize/1024.0);
1668 1669
}

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

L
Liu Jicong 已提交
1706 1707
// void skipBlocks(STaskRuntimeEnv *pRuntimeEnv) {
//   STaskAttr *pQueryAttr = pRuntimeEnv->pQueryAttr;
1708
//
L
Liu Jicong 已提交
1709 1710 1711
//   if (pQueryAttr->limit.offset <= 0 || pQueryAttr->numOfFilterCols > 0) {
//     return;
//   }
1712
//
L
Liu Jicong 已提交
1713 1714
//   pQueryAttr->pos = 0;
//   int32_t step = GET_FORWARD_DIRECTION_FACTOR(pQueryAttr->order.order);
1715
//
L
Liu Jicong 已提交
1716 1717
//   STableQueryInfo* pTableQueryInfo = pRuntimeEnv->current;
//   TsdbQueryHandleT pTsdbReadHandle = pRuntimeEnv->pTsdbReadHandle;
1718
//
L
Liu Jicong 已提交
1719 1720 1721 1722 1723
//   SDataBlockInfo blockInfo = SDATA_BLOCK_INITIALIZER;
//   while (tsdbNextDataBlock(pTsdbReadHandle)) {
//     if (isTaskKilled(pRuntimeEnv->qinfo)) {
//       longjmp(pRuntimeEnv->env, TSDB_CODE_TSC_QUERY_CANCELLED);
//     }
1724
//
L
Liu Jicong 已提交
1725
//     tsdbRetrieveDataBlockInfo(pTsdbReadHandle, &blockInfo);
1726
//
L
Liu Jicong 已提交
1727 1728 1729 1730
//     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;
1731
//
L
Liu Jicong 已提交
1732 1733 1734 1735 1736 1737 1738
//       //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;
//     }
//   }
1739
//
L
Liu Jicong 已提交
1740 1741 1742 1743 1744 1745 1746 1747 1748
//   if (terrno != TSDB_CODE_SUCCESS) {
//     longjmp(pRuntimeEnv->env, terrno);
//   }
// }

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

1911
int32_t appendDownstream(SOperatorInfo* p, SOperatorInfo** pDownstream, int32_t num) {
H
Haojun Liao 已提交
1912
  if (p->pDownstream == NULL) {
H
Haojun Liao 已提交
1913
    assert(p->numOfDownstream == 0);
1914 1915
  }

wafwerar's avatar
wafwerar 已提交
1916
  p->pDownstream = taosMemoryCalloc(1, num * POINTER_BYTES);
1917 1918 1919 1920 1921 1922 1923
  if (p->pDownstream == NULL) {
    return TSDB_CODE_OUT_OF_MEMORY;
  }

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

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

1928
static void doTableQueryInfoTimeWindowCheck(SExecTaskInfo* pTaskInfo, STableQueryInfo* pTableQueryInfo, int32_t order) {
H
Haojun Liao 已提交
1929 1930
#if 0
    if (order == TSDB_ORDER_ASC) {
1931 1932
    assert(
        (pTableQueryInfo->win.skey <= pTableQueryInfo->win.ekey) &&
H
Haojun Liao 已提交
1933 1934
        (pTableQueryInfo->lastKey >= pTaskInfo->window.skey) &&
        (pTableQueryInfo->win.skey >= pTaskInfo->window.skey && pTableQueryInfo->win.ekey <= pTaskInfo->window.ekey));
1935 1936 1937
  } else {
    assert(
        (pTableQueryInfo->win.skey >= pTableQueryInfo->win.ekey) &&
H
Haojun Liao 已提交
1938 1939
        (pTableQueryInfo->lastKey <= pTaskInfo->window.skey) &&
        (pTableQueryInfo->win.skey <= pTaskInfo->window.skey && pTableQueryInfo->win.ekey >= pTaskInfo->window.ekey));
1940
  }
H
Haojun Liao 已提交
1941
#endif
1942 1943
}

1944 1945 1946 1947
typedef struct SFetchRspHandleWrapper {
  uint32_t exchangeId;
  int32_t  sourceIndex;
} SFetchRspHandleWrapper;
1948

D
dapan1121 已提交
1949
int32_t loadRemoteDataCallback(void* param, SDataBuf* pMsg, int32_t code) {
X
Xiaoyu Wang 已提交
1950
  SFetchRspHandleWrapper* pWrapper = (SFetchRspHandleWrapper*)param;
1951 1952 1953 1954 1955 1956 1957

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

X
Xiaoyu Wang 已提交
1958
  int32_t          index = pWrapper->sourceIndex;
1959
  SSourceDataInfo* pSourceDataInfo = taosArrayGet(pExchangeInfo->pSourceDataInfo, index);
1960

H
Haojun Liao 已提交
1961 1962
  if (code == TSDB_CODE_SUCCESS) {
    pSourceDataInfo->pRsp = pMsg->pData;
1963

H
Haojun Liao 已提交
1964 1965
    SRetrieveTableRsp* pRsp = pSourceDataInfo->pRsp;
    pRsp->numOfRows = htonl(pRsp->numOfRows);
dengyihao's avatar
dengyihao 已提交
1966
    pRsp->compLen = htonl(pRsp->compLen);
1967
    pRsp->numOfCols = htonl(pRsp->numOfCols);
dengyihao's avatar
dengyihao 已提交
1968
    pRsp->useconds = htobe64(pRsp->useconds);
1969

1970
    ASSERT(pRsp != NULL);
1971
    qDebug("%s fetch rsp received, index:%d, rows:%d", pSourceDataInfo->taskId, index, pRsp->numOfRows);
H
Haojun Liao 已提交
1972 1973
  } else {
    pSourceDataInfo->code = code;
D
dapan1121 已提交
1974
    qDebug("%s fetch rsp received, index:%d, error:%d", pSourceDataInfo->taskId, index, tstrerror(code));
H
Haojun Liao 已提交
1975
  }
H
Haojun Liao 已提交
1976

H
Haojun Liao 已提交
1977
  pSourceDataInfo->status = EX_SOURCE_DATA_READY;
1978 1979 1980 1981

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

wmmhello's avatar
wmmhello 已提交
1982
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
1983 1984
}

D
dapan1121 已提交
1985
void qProcessRspMsg(void* parent, SRpcMsg* pMsg, SEpSet* pEpSet) {
S
Shengliang Guan 已提交
1986 1987
  SMsgSendInfo* pSendInfo = (SMsgSendInfo*)pMsg->info.ahandle;
  assert(pMsg->info.ahandle != NULL);
H
Haojun Liao 已提交
1988 1989 1990 1991

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

  if (pMsg->contLen > 0) {
wafwerar's avatar
wafwerar 已提交
1992
    buf.pData = taosMemoryCalloc(1, pMsg->contLen);
H
Haojun Liao 已提交
1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003
    if (buf.pData == NULL) {
      terrno = TSDB_CODE_OUT_OF_MEMORY;
      pMsg->code = TSDB_CODE_OUT_OF_MEMORY;
    } else {
      memcpy(buf.pData, pMsg->pCont, pMsg->contLen);
    }
  }

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

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

wafwerar's avatar
wafwerar 已提交
2009
  SResFetchReq* pMsg = taosMemoryCalloc(1, sizeof(SResFetchReq));
2010 2011 2012 2013
  if (NULL == pMsg) {
    pTaskInfo->code = TSDB_CODE_QRY_OUT_OF_MEMORY;
    return pTaskInfo->code;
  }
2014

L
Liu Jicong 已提交
2015 2016
  SDownstreamSourceNode* pSource = taosArrayGet(pExchangeInfo->pSources, sourceIndex);
  SSourceDataInfo*       pDataInfo = taosArrayGet(pExchangeInfo->pSourceDataInfo, sourceIndex);
2017

2018 2019
  ASSERT(pDataInfo->status == EX_SOURCE_DATA_NOT_READY);

2020 2021 2022
  qDebug("%s build fetch msg and send to vgId:%d, ep:%s, taskId:0x%" PRIx64 ", execId:%d, %d/%" PRIzu,
         GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->addr.epSet.eps[0].fqdn, pSource->taskId, pSource->execId,
         sourceIndex, totalSources);
2023 2024 2025 2026 2027

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

  // send the fetch remote task result reques
wafwerar's avatar
wafwerar 已提交
2031
  SMsgSendInfo* pMsgSendInfo = taosMemoryCalloc(1, sizeof(SMsgSendInfo));
2032
  if (NULL == pMsgSendInfo) {
wafwerar's avatar
wafwerar 已提交
2033
    taosMemoryFreeClear(pMsg);
2034 2035 2036
    qError("%s prepare message %d failed", GET_TASKID(pTaskInfo), (int32_t)sizeof(SMsgSendInfo));
    pTaskInfo->code = TSDB_CODE_QRY_OUT_OF_MEMORY;
    return pTaskInfo->code;
H
Haojun Liao 已提交
2037 2038
  }

2039
  SFetchRspHandleWrapper* pWrapper = taosMemoryCalloc(1, sizeof(SFetchRspHandleWrapper));
X
Xiaoyu Wang 已提交
2040
  pWrapper->exchangeId = pExchangeInfo->self;
2041 2042 2043
  pWrapper->sourceIndex = sourceIndex;

  pMsgSendInfo->param = pWrapper;
D
dapan1121 已提交
2044
  pMsgSendInfo->paramFreeFp = taosMemoryFree;
2045 2046
  pMsgSendInfo->msgInfo.pData = pMsg;
  pMsgSendInfo->msgInfo.len = sizeof(SResFetchReq);
L
Liu Jicong 已提交
2047
  pMsgSendInfo->msgType = pSource->fetchMsgType;
2048
  pMsgSendInfo->fp = loadRemoteDataCallback;
2049

2050
  int64_t transporterId = 0;
L
Liu Jicong 已提交
2051
  int32_t code = asyncSendMsgToServer(pExchangeInfo->pTransporter, &pSource->addr.epSet, &transporterId, pMsgSendInfo);
2052 2053 2054
  return TSDB_CODE_SUCCESS;
}

2055
int32_t extractDataBlockFromFetchRsp(SSDataBlock* pRes, SLoadRemoteDataInfo* pLoadInfo, int32_t numOfRows, char* pData,
L
Liu Jicong 已提交
2056 2057
                                     int32_t compLen, int32_t numOfOutput, int64_t startTs, uint64_t* total,
                                     SArray* pColList) {
H
Haojun Liao 已提交
2058
  if (pColList == NULL) {  // data from other sources
2059
    blockDataCleanup(pRes);
2060
    //    blockDataEnsureCapacity(pRes, numOfRows);
2061
    blockDecode(pRes, numOfOutput, numOfRows, pData);
H
Haojun Liao 已提交
2062
  } else {  // extract data according to pColList
2063
    ASSERT(numOfOutput == taosArrayGetSize(pColList));
2064 2065 2066 2067 2068
    char* pStart = pData;

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

2069
    // todo refactor:extract method
2070
    SSysTableSchema* pSchema = (SSysTableSchema*)pStart;
dengyihao's avatar
dengyihao 已提交
2071
    for (int32_t i = 0; i < numOfCols; ++i) {
2072 2073 2074 2075 2076 2077 2078
      SSysTableSchema* p = (SSysTableSchema*)pStart;

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

2079
    SSDataBlock* pBlock = createDataBlock();
dengyihao's avatar
dengyihao 已提交
2080
    for (int32_t i = 0; i < numOfCols; ++i) {
2081 2082
      SColumnInfoData idata = createColumnInfoData(pSchema[i].type, pSchema[i].bytes, pSchema[i].colId);
      blockDataAppendColInfo(pBlock, &idata);
2083 2084
    }

2085
    blockDecode(pBlock, numOfCols, numOfRows, pStart);
2086 2087
    blockDataEnsureCapacity(pRes, numOfRows);

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

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

2097
  int64_t el = taosGetTimestampUs() - startTs;
2098

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

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

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

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

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

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

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

  doSetOperatorCompleted(pOperator);
  return NULL;
}

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

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

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

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

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

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

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

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

2193 2194
      taosMemoryFreeClear(pDataInfo->pRsp);

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

      return pExchangeInfo->pResult;
    }

2207
    if (completed == totalSources) {
2208 2209
      return setAllSourcesCompleted(pOperator, startTs);
    }
H
Haojun Liao 已提交
2210 2211

    sched_yield();
2212 2213 2214 2215 2216 2217 2218
  }

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

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

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

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

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

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

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

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

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

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

2258 2259 2260
    doSendFetchDataRequest(pExchangeInfo, pTaskInfo, pExchangeInfo->current);
    tsem_wait(&pExchangeInfo->ready);

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

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

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

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

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

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

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

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

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

2318 2319
  int64_t st = taosGetTimestampUs();

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

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

2333
static SSDataBlock* doLoadRemoteDataImpl(SOperatorInfo* pOperator) {
L
Liu Jicong 已提交
2334 2335
  SExchangeInfo* pExchangeInfo = pOperator->info;
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
2336

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

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

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

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

2359 2360 2361 2362 2363 2364 2365 2366
static SSDataBlock* doLoadRemoteData(SOperatorInfo* pOperator) {
  SExchangeInfo* pExchangeInfo = pOperator->info;
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;

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

L
Liu Jicong 已提交
2367
  while (1) {
2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396
    SSDataBlock* pBlock = doLoadRemoteDataImpl(pOperator);
    if (pBlock == NULL) {
      return NULL;
    }

    ASSERT(pBlock == pExchangeInfo->pResult);

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

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

2397
static int32_t initDataSource(int32_t numOfSources, SExchangeInfo* pInfo, const char* id) {
2398
  pInfo->pSourceDataInfo = taosArrayInit(numOfSources, sizeof(SSourceDataInfo));
H
Haojun Liao 已提交
2399 2400
  if (pInfo->pSourceDataInfo == NULL) {
    return TSDB_CODE_OUT_OF_MEMORY;
2401 2402
  }

L
Liu Jicong 已提交
2403
  for (int32_t i = 0; i < numOfSources; ++i) {
2404
    SSourceDataInfo dataInfo = {0};
H
Haojun Liao 已提交
2405
    dataInfo.status = EX_SOURCE_DATA_NOT_READY;
2406
    dataInfo.taskId = id;
L
Liu Jicong 已提交
2407
    dataInfo.index = i;
X
Xiaoyu Wang 已提交
2408
    SSourceDataInfo* pDs = taosArrayPush(pInfo->pSourceDataInfo, &dataInfo);
2409
    if (pDs == NULL) {
H
Haojun Liao 已提交
2410 2411 2412 2413 2414 2415 2416 2417
      taosArrayDestroy(pInfo->pSourceDataInfo);
      return TSDB_CODE_OUT_OF_MEMORY;
    }
  }

  return TSDB_CODE_SUCCESS;
}

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

2421
  if (numOfSources == 0) {
X
Xiaoyu Wang 已提交
2422
    qError("%s invalid number: %d of sources in exchange operator", id, (int32_t)numOfSources);
2423 2424 2425
    return TSDB_CODE_INVALID_PARA;
  }

H
Haojun Liao 已提交
2426
  pInfo->pSources = taosArrayInit(numOfSources, sizeof(SDownstreamSourceNode));
wmmhello's avatar
wmmhello 已提交
2427
  if (pInfo->pSources == NULL) {
2428
    return TSDB_CODE_OUT_OF_MEMORY;
H
Haojun Liao 已提交
2429 2430
  }

L
Liu Jicong 已提交
2431
  for (int32_t i = 0; i < numOfSources; ++i) {
D
dapan1121 已提交
2432
    SDownstreamSourceNode* pNode = (SDownstreamSourceNode*)nodesListGetNode((SNodeList*)pExNode->pSrcEndPoints, i);
H
Haojun Liao 已提交
2433 2434
    taosArrayPush(pInfo->pSources, pNode);
  }
2435

2436
  initLimitInfo(pExNode->node.pLimit, pExNode->node.pSlimit, &pInfo->limitInfo);
2437 2438
  pInfo->self = taosAddRef(exchangeObjRefPool, pInfo);

2439
  return initDataSource(numOfSources, pInfo, id);
2440 2441 2442 2443 2444 2445
}

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

2449
  int32_t code = initExchangeOperator(pExNode, pInfo, GET_TASKID(pTaskInfo));
2450 2451 2452
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
2453 2454

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

2456
  pInfo->seqLoadData = false;
2457
  pInfo->pTransporter = pTransporter;
2458 2459
  pInfo->pResult = createResDataBlock(pExNode->node.pOutputDataBlockDesc);
  pOperator->name = "ExchangeOperator";
X
Xiaoyu Wang 已提交
2460
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_EXCHANGE;
X
Xiaoyu Wang 已提交
2461
  pOperator->blocking = false;
2462 2463
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
2464
  pOperator->exprSupp.numOfExprs = taosArrayGetSize(pInfo->pResult->pDataBlock);
X
Xiaoyu Wang 已提交
2465
  pOperator->pTaskInfo = pTaskInfo;
2466

L
Liu Jicong 已提交
2467 2468
  pOperator->fpSet = createOperatorFpSet(prepareLoadRemoteData, doLoadRemoteData, NULL, NULL,
                                         destroyExchangeOperatorInfo, NULL, NULL, NULL);
2469
  return pOperator;
H
Haojun Liao 已提交
2470

L
Liu Jicong 已提交
2471
_error:
H
Haojun Liao 已提交
2472
  if (pInfo != NULL) {
2473
    doDestroyExchangeOperatorInfo(pInfo);
H
Haojun Liao 已提交
2474 2475
  }

wafwerar's avatar
wafwerar 已提交
2476
  taosMemoryFreeClear(pOperator);
2477
  pTaskInfo->code = code;
H
Haojun Liao 已提交
2478
  return NULL;
2479 2480
}

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

2484
static void destroySortedMergeOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
2485
  SSortedMergeOperatorInfo* pInfo = (SSortedMergeOperatorInfo*)param;
H
Haojun Liao 已提交
2486
  taosArrayDestroy(pInfo->pSortInfo);
2487 2488 2489
  taosArrayDestroy(pInfo->groupInfo);

  if (pInfo->pSortHandle != NULL) {
H
Haojun Liao 已提交
2490
    tsortDestroySortHandle(pInfo->pSortHandle);
2491 2492
  }

H
Haojun Liao 已提交
2493
  blockDataDestroy(pInfo->binfo.pRes);
H
Haojun Liao 已提交
2494
  cleanupAggSup(&pInfo->aggSup);
L
Liu Jicong 已提交
2495

D
dapan1121 已提交
2496
  taosMemoryFreeClear(param);
2497
}
H
Haojun Liao 已提交
2498

L
Liu Jicong 已提交
2499
static bool needToMerge(SSDataBlock* pBlock, SArray* groupInfo, char** buf, int32_t rowIndex) {
2500 2501 2502 2503
  size_t size = taosArrayGetSize(groupInfo);
  if (size == 0) {
    return true;
  }
2504

2505 2506
  for (int32_t i = 0; i < size; ++i) {
    int32_t* index = taosArrayGet(groupInfo, i);
2507

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

2511 2512 2513
    if ((isNull && buf[i] != NULL) || (!isNull && buf[i] == NULL)) {
      return false;
    }
2514

2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527
    char* pCell = colDataGetData(pColInfo, rowIndex);
    if (IS_VAR_DATA_TYPE(pColInfo->info.type)) {
      if (varDataLen(pCell) != varDataLen(buf[i])) {
        return false;
      } else {
        if (memcmp(varDataVal(pCell), varDataVal(buf[i]), varDataLen(pCell)) != 0) {
          return false;
        }
      }
    } else {
      if (memcmp(pCell, buf[i], pColInfo->info.bytes) != 0) {
        return false;
      }
2528 2529 2530
    }
  }

2531
  return 0;
2532 2533
}

L
Liu Jicong 已提交
2534 2535 2536
static void doMergeResultImpl(SSortedMergeOperatorInfo* pInfo, SqlFunctionCtx* pCtx, int32_t numOfExpr,
                              int32_t rowIndex) {
  for (int32_t j = 0; j < numOfExpr; ++j) {  // TODO set row index
X
Xiaoyu Wang 已提交
2537
                                             //    pCtx[j].startRow = rowIndex;
2538 2539
  }

2540 2541
  for (int32_t j = 0; j < numOfExpr; ++j) {
    int32_t functionId = pCtx[j].functionId;
L
Liu Jicong 已提交
2542 2543 2544 2545 2546 2547 2548 2549 2550
    //    pCtx[j].fpSet->addInput(&pCtx[j]);

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

L
Liu Jicong 已提交
2554 2555
static void doFinalizeResultImpl(SqlFunctionCtx* pCtx, int32_t numOfExpr) {
  for (int32_t j = 0; j < numOfExpr; ++j) {
2556 2557 2558 2559
    int32_t functionId = pCtx[j].functionId;
    //    if (functionId == FUNC_TAG_DUMMY || functionId == FUNC_TS_DUMMY) {
    //      continue;
    //    }
2560

2561 2562 2563 2564
    //    if (functionId < 0) {
    //      SUdfInfo* pUdfInfo = taosArrayGet(pInfo->udfInfo, -1 * functionId - 1);
    //      doInvokeUdf(pUdfInfo, &pCtx[j], 0, TSDB_UDF_FUNC_FINALIZE);
    //    } else {
dengyihao's avatar
dengyihao 已提交
2565
    //    pCtx[j].fpSet.finalize(&pCtx[j]);
2566 2567
  }
}
2568

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

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

2576 2577 2578
    char* data = colDataGetData(pColInfo, rowIndex);
    memcpy(rowColData[i], data, colDataGetLength(pColInfo, rowIndex));
  }
2579

2580 2581
  return true;
}
2582

2583 2584
static void doMergeImpl(SOperatorInfo* pOperator, int32_t numOfExpr, SSDataBlock* pBlock) {
  SSortedMergeOperatorInfo* pInfo = pOperator->info;
2585

2586
  SqlFunctionCtx* pCtx = pOperator->exprSupp.pCtx;
2587

L
Liu Jicong 已提交
2588
  for (int32_t i = 0; i < pBlock->info.rows; ++i) {
2589 2590 2591 2592 2593 2594 2595 2596 2597
    if (!pInfo->hasGroupVal) {
      ASSERT(i == 0);
      doMergeResultImpl(pInfo, pCtx, numOfExpr, i);
      pInfo->hasGroupVal = saveCurrentTuple(pInfo->groupVal, pInfo->groupInfo, pBlock, i);
    } else {
      if (needToMerge(pBlock, pInfo->groupInfo, pInfo->groupVal, i)) {
        doMergeResultImpl(pInfo, pCtx, numOfExpr, i);
      } else {
        doFinalizeResultImpl(pCtx, numOfExpr);
2598 2599
        int32_t numOfRows = getNumOfResult(pOperator->exprSupp.pCtx, pOperator->exprSupp.numOfExprs, NULL);
        //        setTagValueForMultipleRows(pCtx, pOperator->exprSupp.numOfExprs, numOfRows);
2600

2601
        // TODO check for available buffer;
H
Haojun Liao 已提交
2602

2603 2604 2605 2606 2607
        // next group info data
        pInfo->binfo.pRes->info.rows += numOfRows;
        for (int32_t j = 0; j < numOfExpr; ++j) {
          if (pCtx[j].functionId < 0) {
            continue;
2608
          }
2609

H
Haojun Liao 已提交
2610
          pCtx[j].fpSet.process(&pCtx[j]);
2611
        }
2612 2613 2614

        doMergeResultImpl(pInfo, pCtx, numOfExpr, i);
        pInfo->hasGroupVal = saveCurrentTuple(pInfo->groupVal, pInfo->groupInfo, pBlock, i);
H
Haojun Liao 已提交
2615
      }
2616 2617 2618 2619
    }
  }
}

2620 2621
static SSDataBlock* doMerge(SOperatorInfo* pOperator) {
  SSortedMergeOperatorInfo* pInfo = pOperator->info;
L
Liu Jicong 已提交
2622
  SSortHandle*              pHandle = pInfo->pSortHandle;
2623

2624
  SSDataBlock* pDataBlock = createOneDataBlock(pInfo->binfo.pRes, false);
2625
  blockDataEnsureCapacity(pDataBlock, pOperator->resultInfo.capacity);
2626

L
Liu Jicong 已提交
2627
  while (1) {
2628
    blockDataCleanup(pDataBlock);
2629
    while (1) {
H
Haojun Liao 已提交
2630
      STupleHandle* pTupleHandle = tsortNextTuple(pHandle);
2631 2632
      if (pTupleHandle == NULL) {
        break;
2633
      }
2634

2635 2636
      // build datablock for merge for one group
      appendOneRowToDataBlock(pDataBlock, pTupleHandle);
2637
      if (pDataBlock->info.rows >= pOperator->resultInfo.capacity) {
2638 2639
        break;
      }
2640
    }
2641

2642 2643 2644
    if (pDataBlock->info.rows == 0) {
      break;
    }
2645

2646
    setInputDataBlock(pOperator, pOperator->exprSupp.pCtx, pDataBlock, TSDB_ORDER_ASC, MAIN_SCAN, true);
L
Liu Jicong 已提交
2647 2648
    //  updateOutputBuf(&pInfo->binfo, &pAggInfo->bufCapacity, pBlock->info.rows * pAggInfo->resultRowFactor,
    //  pOperator->pRuntimeEnv, true);
2649
    doMergeImpl(pOperator, pOperator->exprSupp.numOfExprs, pDataBlock);
2650 2651
    // flush to tuple store, and after all data have been handled, return to upstream node or sink node
  }
2652

2653 2654 2655
  doFinalizeResultImpl(pOperator->exprSupp.pCtx, pOperator->exprSupp.numOfExprs);
  int32_t numOfRows = getNumOfResult(pOperator->exprSupp.pCtx, pOperator->exprSupp.numOfExprs, NULL);
  //        setTagValueForMultipleRows(pCtx, pOperator->exprSupp.numOfExprs, numOfRows);
2656

2657
  // TODO check for available buffer;
2658

2659 2660
  // next group info data
  pInfo->binfo.pRes->info.rows += numOfRows;
L
Liu Jicong 已提交
2661
  return (pInfo->binfo.pRes->info.rows > 0) ? pInfo->binfo.pRes : NULL;
2662
}
2663

L
Liu Jicong 已提交
2664 2665
SSDataBlock* getSortedMergeBlockData(SSortHandle* pHandle, SSDataBlock* pDataBlock, int32_t capacity,
                                     SArray* pColMatchInfo, SSortedMergeOperatorInfo* pInfo) {
2666 2667 2668 2669 2670 2671 2672 2673 2674 2675
  blockDataCleanup(pDataBlock);

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

  blockDataEnsureCapacity(p, capacity);

  while (1) {
2676
    STupleHandle* pTupleHandle = tsortNextTuple(pHandle);
2677 2678 2679 2680
    if (pTupleHandle == NULL) {
      break;
    }

2681
    appendOneRowToDataBlock(p, pTupleHandle);
2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694
    if (p->info.rows >= capacity) {
      break;
    }
  }

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

      SColumnInfoData* pSrc = taosArrayGet(p->pDataBlock, pmInfo->srcSlotId);
      SColumnInfoData* pDst = taosArrayGet(pDataBlock->pDataBlock, pmInfo->targetSlotId);
2695
      colDataAssign(pDst, pSrc, p->info.rows, &pDataBlock->info);
2696 2697 2698 2699 2700 2701 2702 2703 2704 2705
    }

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

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

2706
static SSDataBlock* doSortedMerge(SOperatorInfo* pOperator) {
2707 2708
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
2709 2710
  }

L
Liu Jicong 已提交
2711
  SExecTaskInfo*            pTaskInfo = pOperator->pTaskInfo;
2712
  SSortedMergeOperatorInfo* pInfo = pOperator->info;
H
Haojun Liao 已提交
2713
  if (pOperator->status == OP_RES_TO_RETURN) {
2714
    return getSortedMergeBlockData(pInfo->pSortHandle, pInfo->binfo.pRes, pOperator->resultInfo.capacity, NULL, pInfo);
2715 2716
  }

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

2721
  tsortSetFetchRawDataFp(pInfo->pSortHandle, loadNextDataBlock, NULL, NULL);
2722

L
Liu Jicong 已提交
2723
  for (int32_t i = 0; i < pOperator->numOfDownstream; ++i) {
wmmhello's avatar
wmmhello 已提交
2724
    SSortSource* ps = taosMemoryCalloc(1, sizeof(SSortSource));
H
Haojun Liao 已提交
2725
    ps->param = pOperator->pDownstream[i];
H
Haojun Liao 已提交
2726
    tsortAddSource(pInfo->pSortHandle, ps);
2727 2728
  }

H
Haojun Liao 已提交
2729
  int32_t code = tsortOpen(pInfo->pSortHandle);
2730
  if (code != TSDB_CODE_SUCCESS) {
2731
    longjmp(pTaskInfo->env, terrno);
2732 2733
  }

H
Haojun Liao 已提交
2734
  pOperator->status = OP_RES_TO_RETURN;
2735
  return doMerge(pOperator);
2736
}
2737

L
Liu Jicong 已提交
2738 2739
static int32_t initGroupCol(SExprInfo* pExprInfo, int32_t numOfCols, SArray* pGroupInfo,
                            SSortedMergeOperatorInfo* pInfo) {
2740 2741
  if (pGroupInfo == NULL || taosArrayGetSize(pGroupInfo) == 0) {
    return 0;
H
Haojun Liao 已提交
2742 2743
  }

2744 2745 2746 2747 2748 2749 2750 2751
  int32_t len = 0;
  SArray* plist = taosArrayInit(3, sizeof(SColumn));
  pInfo->groupInfo = taosArrayInit(3, sizeof(int32_t));

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

L
Liu Jicong 已提交
2752 2753
  size_t numOfGroupCol = taosArrayGetSize(pInfo->groupInfo);
  for (int32_t i = 0; i < numOfGroupCol; ++i) {
2754
    SColumn* pCol = taosArrayGet(pGroupInfo, i);
L
Liu Jicong 已提交
2755
    for (int32_t j = 0; j < numOfCols; ++j) {
H
Haojun Liao 已提交
2756
      SExprInfo* pe = &pExprInfo[j];
2757
      if (pe->base.resSchema.slotId == pCol->colId) {
2758 2759
        taosArrayPush(plist, pCol);
        taosArrayPush(pInfo->groupInfo, &j);
H
Haojun Liao 已提交
2760
        len += pCol->bytes;
2761 2762
        break;
      }
H
Haojun Liao 已提交
2763 2764 2765
    }
  }

2766
  ASSERT(taosArrayGetSize(pGroupInfo) == taosArrayGetSize(plist));
H
Haojun Liao 已提交
2767

wafwerar's avatar
wafwerar 已提交
2768
  pInfo->groupVal = taosMemoryCalloc(1, (POINTER_BYTES * numOfGroupCol + len));
2769 2770 2771 2772
  if (pInfo->groupVal == NULL) {
    taosArrayDestroy(plist);
    return TSDB_CODE_OUT_OF_MEMORY;
  }
H
Haojun Liao 已提交
2773

2774
  int32_t offset = 0;
L
Liu Jicong 已提交
2775 2776
  char*   start = (char*)(pInfo->groupVal + (POINTER_BYTES * numOfGroupCol));
  for (int32_t i = 0; i < numOfGroupCol; ++i) {
2777 2778
    pInfo->groupVal[i] = start + offset;
    SColumn* pCol = taosArrayGet(plist, i);
H
Haojun Liao 已提交
2779
    offset += pCol->bytes;
2780
  }
H
Haojun Liao 已提交
2781

2782
  taosArrayDestroy(plist);
H
Haojun Liao 已提交
2783

2784 2785
  return TSDB_CODE_SUCCESS;
}
H
Haojun Liao 已提交
2786

X
Xiaoyu Wang 已提交
2787
int32_t getTableScanInfo(SOperatorInfo* pOperator, int32_t* order, int32_t* scanFlag) {
2788
  // todo add more information about exchange operation
2789
  int32_t type = pOperator->operatorType;
X
Xiaoyu Wang 已提交
2790
  if (type == QUERY_NODE_PHYSICAL_PLAN_EXCHANGE || type == QUERY_NODE_PHYSICAL_PLAN_SYSTABLE_SCAN ||
2791
      type == QUERY_NODE_PHYSICAL_PLAN_STREAM_SCAN || type == QUERY_NODE_PHYSICAL_PLAN_TAG_SCAN ||
2792
      type == QUERY_NODE_PHYSICAL_PLAN_BLOCK_DIST_SCAN || type == QUERY_NODE_PHYSICAL_PLAN_LAST_ROW_SCAN) {
2793 2794 2795
    *order = TSDB_ORDER_ASC;
    *scanFlag = MAIN_SCAN;
    return TSDB_CODE_SUCCESS;
2796
  } else if (type == QUERY_NODE_PHYSICAL_PLAN_TABLE_SCAN) {
2797 2798 2799 2800
    STableScanInfo* pTableScanInfo = pOperator->info;
    *order = pTableScanInfo->cond.order;
    *scanFlag = pTableScanInfo->scanFlag;
    return TSDB_CODE_SUCCESS;
2801 2802 2803 2804 2805
  } else if (type == QUERY_NODE_PHYSICAL_PLAN_TABLE_MERGE_SCAN) {
    STableMergeScanInfo* pTableScanInfo = pOperator->info;
    *order = pTableScanInfo->cond.order;
    *scanFlag = pTableScanInfo->scanFlag;
    return TSDB_CODE_SUCCESS;
2806
  } else {
H
Haojun Liao 已提交
2807
    if (pOperator->pDownstream == NULL || pOperator->pDownstream[0] == NULL) {
2808
      return TSDB_CODE_INVALID_PARA;
H
Haojun Liao 已提交
2809
    } else {
2810
      return getTableScanInfo(pOperator->pDownstream[0], order, scanFlag);
2811 2812 2813
    }
  }
}
L
Liu Jicong 已提交
2814
#if 0
L
Liu Jicong 已提交
2815
int32_t doPrepareScan(SOperatorInfo* pOperator, uint64_t uid, int64_t ts) {
L
Liu Jicong 已提交
2816
  uint8_t type = pOperator->operatorType;
2817 2818 2819

  pOperator->status = OP_OPENED;

L
Liu Jicong 已提交
2820
  if (type == QUERY_NODE_PHYSICAL_PLAN_STREAM_SCAN) {
2821
    SStreamScanInfo* pScanInfo = pOperator->info;
L
Liu Jicong 已提交
2822
    pScanInfo->blockType = STREAM_INPUT__TABLE_SCAN;
2823

2824
    pScanInfo->pTableScanOp->status = OP_OPENED;
2825

2826
    STableScanInfo* pInfo = pScanInfo->pTableScanOp->info;
2827 2828
    ASSERT(pInfo->scanMode == TABLE_SCAN__TABLE_ORDER);

L
Liu Jicong 已提交
2829 2830 2831 2832
    if (uid == 0) {
      pInfo->noTable = 1;
      return TSDB_CODE_SUCCESS;
    }
2833 2834 2835 2836 2837 2838

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

L
Liu Jicong 已提交
2839 2840
    pInfo->noTable = 0;

2841
    if (pInfo->lastStatus.uid != uid || pInfo->lastStatus.ts != ts) {
L
Liu Jicong 已提交
2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852
      SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;

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

      tsdbSetTableId(pInfo->dataReader, uid);
H
Haojun Liao 已提交
2857 2858 2859 2860
      int64_t oldSkey = pInfo->cond.twindows.skey;
      pInfo->cond.twindows.skey = ts + 1;
      tsdbReaderReset(pInfo->dataReader, &pInfo->cond);
      pInfo->cond.twindows.skey = oldSkey;
2861 2862
      pInfo->scanTimes = 0;

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

L
Liu Jicong 已提交
2867
    return TSDB_CODE_SUCCESS;
2868

L
Liu Jicong 已提交
2869
  } else {
2870 2871 2872 2873 2874
    if (pOperator->numOfDownstream == 1) {
      return doPrepareScan(pOperator->pDownstream[0], uid, ts);
    } else if (pOperator->numOfDownstream == 0) {
      qError("failed to find stream scan operator to set the input data block");
      return TSDB_CODE_QRY_APP_ERROR;
L
Liu Jicong 已提交
2875
    } else {
2876 2877
      qError("join not supported for stream block scan");
      return TSDB_CODE_QRY_APP_ERROR;
L
Liu Jicong 已提交
2878 2879 2880 2881
    }
  }
}

2882 2883 2884
int32_t doGetScanStatus(SOperatorInfo* pOperator, uint64_t* uid, int64_t* ts) {
  int32_t type = pOperator->operatorType;
  if (type == QUERY_NODE_PHYSICAL_PLAN_STREAM_SCAN) {
2885 2886
    SStreamScanInfo* pScanInfo = pOperator->info;
    STableScanInfo*  pSnapShotScanInfo = pScanInfo->pTableScanOp->info;
L
Liu Jicong 已提交
2887 2888
    *uid = pSnapShotScanInfo->lastStatus.uid;
    *ts = pSnapShotScanInfo->lastStatus.ts;
2889 2890 2891 2892 2893 2894 2895 2896 2897 2898
  } else {
    if (pOperator->pDownstream[0] == NULL) {
      return TSDB_CODE_INVALID_PARA;
    } else {
      doGetScanStatus(pOperator->pDownstream[0], uid, ts);
    }
  }

  return TSDB_CODE_SUCCESS;
}
L
Liu Jicong 已提交
2899
#endif
2900

2901
// this is a blocking operator
L
Liu Jicong 已提交
2902
static int32_t doOpenAggregateOptr(SOperatorInfo* pOperator) {
H
Haojun Liao 已提交
2903 2904
  if (OPTR_IS_OPENED(pOperator)) {
    return TSDB_CODE_SUCCESS;
2905 2906
  }

H
Haojun Liao 已提交
2907
  SExecTaskInfo*    pTaskInfo = pOperator->pTaskInfo;
2908
  SAggOperatorInfo* pAggInfo = pOperator->info;
H
Haojun Liao 已提交
2909

2910 2911
  SExprSupp*     pSup = &pOperator->exprSupp;
  SOperatorInfo* downstream = pOperator->pDownstream[0];
2912

2913 2914
  int64_t st = taosGetTimestampUs();

2915 2916 2917
  int32_t order = TSDB_ORDER_ASC;
  int32_t scanFlag = MAIN_SCAN;

H
Haojun Liao 已提交
2918
  while (1) {
2919
    SSDataBlock* pBlock = downstream->fpSet.getNextFn(downstream);
2920 2921 2922 2923
    if (pBlock == NULL) {
      break;
    }

2924 2925 2926 2927
    int32_t code = getTableScanInfo(pOperator, &order, &scanFlag);
    if (code != TSDB_CODE_SUCCESS) {
      longjmp(pTaskInfo->env, code);
    }
2928

2929
    // there is an scalar expression that needs to be calculated before apply the group aggregation.
2930 2931 2932
    if (pAggInfo->scalarExprSup.pExprInfo != NULL) {
      SExprSupp* pSup1 = &pAggInfo->scalarExprSup;
      code = projectApplyFunctions(pSup1->pExprInfo, pBlock, pBlock, pSup1->pCtx, pSup1->numOfExprs, NULL);
2933
      if (code != TSDB_CODE_SUCCESS) {
2934
        longjmp(pTaskInfo->env, code);
2935
      }
2936 2937
    }

2938
    // the pDataBlock are always the same one, no need to call this again
2939
    setExecutionContext(pOperator, pOperator->exprSupp.numOfExprs, pBlock->info.groupId);
2940
    setInputDataBlock(pOperator, pSup->pCtx, pBlock, order, scanFlag, true);
2941
    code = doAggregateImpl(pOperator, pSup->pCtx);
2942 2943 2944
    if (code != 0) {
      longjmp(pTaskInfo->env, code);
    }
2945 2946
  }

2947
  initGroupedResultInfo(&pAggInfo->groupResInfo, pAggInfo->aggSup.pResultRowHashTable, 0);
H
Haojun Liao 已提交
2948
  OPTR_SET_OPENED(pOperator);
2949

2950
  pOperator->cost.openCost = (taosGetTimestampUs() - st) / 1000.0;
H
Haojun Liao 已提交
2951 2952 2953
  return TSDB_CODE_SUCCESS;
}

2954
static SSDataBlock* getAggregateResult(SOperatorInfo* pOperator) {
L
Liu Jicong 已提交
2955
  SAggOperatorInfo* pAggInfo = pOperator->info;
H
Haojun Liao 已提交
2956 2957 2958 2959 2960 2961
  SOptrBasicInfo*   pInfo = &pAggInfo->binfo;

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

L
Liu Jicong 已提交
2962
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
2963
  pTaskInfo->code = pOperator->fpSet._openFn(pOperator);
H
Haojun Liao 已提交
2964
  if (pTaskInfo->code != TSDB_CODE_SUCCESS) {
2965
    doSetOperatorCompleted(pOperator);
H
Haojun Liao 已提交
2966 2967 2968
    return NULL;
  }

H
Haojun Liao 已提交
2969
  blockDataEnsureCapacity(pInfo->pRes, pOperator->resultInfo.capacity);
S
slzhou 已提交
2970 2971
  while (1) {
    doBuildResultDatablock(pOperator, pInfo, &pAggInfo->groupResInfo, pAggInfo->aggSup.pResultBuf);
2972
    doFilter(pAggInfo->pCondition, pInfo->pRes, NULL);
S
slzhou 已提交
2973

2974
    if (!hasRemainResults(&pAggInfo->groupResInfo)) {
S
slzhou 已提交
2975 2976 2977
      doSetOperatorCompleted(pOperator);
      break;
    }
2978

S
slzhou 已提交
2979 2980 2981 2982
    if (pInfo->pRes->info.rows > 0) {
      break;
    }
  }
2983
  size_t rows = blockDataGetNumOfRows(pInfo->pRes);
2984 2985
  pOperator->resultInfo.totalRows += rows;

2986
  return (rows == 0) ? NULL : pInfo->pRes;
2987 2988
}

wmmhello's avatar
wmmhello 已提交
2989
int32_t aggEncodeResultRow(SOperatorInfo* pOperator, char** result, int32_t* length) {
2990
  if (result == NULL || length == NULL) {
wmmhello's avatar
wmmhello 已提交
2991 2992 2993
    return TSDB_CODE_TSC_INVALID_INPUT;
  }
  SOptrBasicInfo* pInfo = (SOptrBasicInfo*)(pOperator->info);
2994 2995 2996 2997 2998
  SAggSupporter*  pSup = (SAggSupporter*)POINTER_SHIFT(pOperator->info, sizeof(SOptrBasicInfo));
  int32_t         size = taosHashGetSize(pSup->pResultRowHashTable);
  size_t          keyLen = sizeof(uint64_t) * 2;  // estimate the key length
  int32_t         totalSize =
      sizeof(int32_t) + sizeof(int32_t) + size * (sizeof(int32_t) + keyLen + sizeof(int32_t) + pSup->resultRowSize);
wmmhello's avatar
wmmhello 已提交
2999

C
Cary Xu 已提交
3000 3001 3002 3003 3004 3005
  // no result
  if (getTotalBufSize(pSup->pResultBuf) == 0) {
    *result = NULL;
    *length = 0;
    return TSDB_CODE_SUCCESS;
  }
3006

wmmhello's avatar
wmmhello 已提交
3007
  *result = (char*)taosMemoryCalloc(1, totalSize);
L
Liu Jicong 已提交
3008
  if (*result == NULL) {
wmmhello's avatar
wmmhello 已提交
3009
    return TSDB_CODE_OUT_OF_MEMORY;
wmmhello's avatar
wmmhello 已提交
3010
  }
wmmhello's avatar
wmmhello 已提交
3011

wmmhello's avatar
wmmhello 已提交
3012
  int32_t offset = sizeof(int32_t);
wmmhello's avatar
wmmhello 已提交
3013 3014
  *(int32_t*)(*result + offset) = size;
  offset += sizeof(int32_t);
3015 3016

  // prepare memory
3017
  SResultRowPosition* pos = &pInfo->resultRowInfo.cur;
dengyihao's avatar
dengyihao 已提交
3018 3019
  void*               pPage = getBufPage(pSup->pResultBuf, pos->pageId);
  SResultRow*         pRow = (SResultRow*)((char*)pPage + pos->offset);
3020 3021 3022
  setBufPageDirty(pPage, true);
  releaseBufPage(pSup->pResultBuf, pPage);

dengyihao's avatar
dengyihao 已提交
3023
  void* pIter = taosHashIterate(pSup->pResultRowHashTable, NULL);
wmmhello's avatar
wmmhello 已提交
3024
  while (pIter) {
dengyihao's avatar
dengyihao 已提交
3025
    void*               key = taosHashGetKey(pIter, &keyLen);
3026
    SResultRowPosition* p1 = (SResultRowPosition*)pIter;
3027

dengyihao's avatar
dengyihao 已提交
3028
    pPage = (SFilePage*)getBufPage(pSup->pResultBuf, p1->pageId);
3029
    pRow = (SResultRow*)((char*)pPage + p1->offset);
3030 3031
    setBufPageDirty(pPage, true);
    releaseBufPage(pSup->pResultBuf, pPage);
wmmhello's avatar
wmmhello 已提交
3032 3033 3034

    // recalculate the result size
    int32_t realTotalSize = offset + sizeof(int32_t) + keyLen + sizeof(int32_t) + pSup->resultRowSize;
L
Liu Jicong 已提交
3035
    if (realTotalSize > totalSize) {
wmmhello's avatar
wmmhello 已提交
3036
      char* tmp = (char*)taosMemoryRealloc(*result, realTotalSize);
L
Liu Jicong 已提交
3037
      if (tmp == NULL) {
wafwerar's avatar
wafwerar 已提交
3038
        taosMemoryFree(*result);
wmmhello's avatar
wmmhello 已提交
3039
        *result = NULL;
wmmhello's avatar
wmmhello 已提交
3040
        return TSDB_CODE_OUT_OF_MEMORY;
L
Liu Jicong 已提交
3041
      } else {
wmmhello's avatar
wmmhello 已提交
3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053
        *result = tmp;
      }
    }
    // save key
    *(int32_t*)(*result + offset) = keyLen;
    offset += sizeof(int32_t);
    memcpy(*result + offset, key, keyLen);
    offset += keyLen;

    // save value
    *(int32_t*)(*result + offset) = pSup->resultRowSize;
    offset += sizeof(int32_t);
3054
    memcpy(*result + offset, pRow, pSup->resultRowSize);
wmmhello's avatar
wmmhello 已提交
3055 3056 3057 3058 3059
    offset += pSup->resultRowSize;

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

wmmhello's avatar
wmmhello 已提交
3060 3061 3062 3063
  *(int32_t*)(*result) = offset;
  *length = offset;

  return TDB_CODE_SUCCESS;
wmmhello's avatar
wmmhello 已提交
3064 3065
}

3066
int32_t aggDecodeResultRow(SOperatorInfo* pOperator, char* result) {
3067
  if (result == NULL) {
wmmhello's avatar
wmmhello 已提交
3068
    return TSDB_CODE_TSC_INVALID_INPUT;
wmmhello's avatar
wmmhello 已提交
3069
  }
wmmhello's avatar
wmmhello 已提交
3070
  SOptrBasicInfo* pInfo = (SOptrBasicInfo*)(pOperator->info);
3071
  SAggSupporter*  pSup = (SAggSupporter*)POINTER_SHIFT(pOperator->info, sizeof(SOptrBasicInfo));
wmmhello's avatar
wmmhello 已提交
3072 3073

  //  int32_t size = taosHashGetSize(pSup->pResultRowHashTable);
3074
  int32_t length = *(int32_t*)(result);
wmmhello's avatar
wmmhello 已提交
3075
  int32_t offset = sizeof(int32_t);
3076 3077 3078 3079

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

L
Liu Jicong 已提交
3080
  while (count-- > 0 && length > offset) {
wmmhello's avatar
wmmhello 已提交
3081 3082 3083
    int32_t keyLen = *(int32_t*)(result + offset);
    offset += sizeof(int32_t);

L
Liu Jicong 已提交
3084
    uint64_t    tableGroupId = *(uint64_t*)(result + offset);
3085
    SResultRow* resultRow = getNewResultRow(pSup->pResultBuf, tableGroupId, pSup->resultRowSize);
L
Liu Jicong 已提交
3086
    if (!resultRow) {
wmmhello's avatar
wmmhello 已提交
3087
      return TSDB_CODE_TSC_INVALID_INPUT;
wmmhello's avatar
wmmhello 已提交
3088
    }
3089

wmmhello's avatar
wmmhello 已提交
3090
    // add a new result set for a new group
3091 3092
    SResultRowPosition pos = {.pageId = resultRow->pageId, .offset = resultRow->offset};
    taosHashPut(pSup->pResultRowHashTable, result + offset, keyLen, &pos, sizeof(SResultRowPosition));
wmmhello's avatar
wmmhello 已提交
3093 3094 3095

    offset += keyLen;
    int32_t valueLen = *(int32_t*)(result + offset);
L
Liu Jicong 已提交
3096
    if (valueLen != pSup->resultRowSize) {
wmmhello's avatar
wmmhello 已提交
3097
      return TSDB_CODE_TSC_INVALID_INPUT;
wmmhello's avatar
wmmhello 已提交
3098 3099 3100 3101 3102 3103 3104 3105 3106 3107
    }
    offset += sizeof(int32_t);
    int32_t pageId = resultRow->pageId;
    int32_t pOffset = resultRow->offset;
    memcpy(resultRow, result + offset, valueLen);
    resultRow->pageId = pageId;
    resultRow->offset = pOffset;
    offset += valueLen;

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

L
Liu Jicong 已提交
3111
  if (offset != length) {
wmmhello's avatar
wmmhello 已提交
3112
    return TSDB_CODE_TSC_INVALID_INPUT;
wmmhello's avatar
wmmhello 已提交
3113
  }
wmmhello's avatar
wmmhello 已提交
3114
  return TDB_CODE_SUCCESS;
wmmhello's avatar
wmmhello 已提交
3115 3116
}

3117 3118 3119 3120 3121
int32_t handleLimitOffset(SOperatorInfo* pOperator, SLimitInfo* pLimitInfo, SSDataBlock* pBlock, bool holdDataInBuf) {
  if (pLimitInfo->remainGroupOffset > 0) {
    if (pLimitInfo->currentGroupId == 0) {  // it is the first group
      pLimitInfo->currentGroupId = pBlock->info.groupId;
      blockDataCleanup(pBlock);
3122
      return PROJECT_RETRIEVE_CONTINUE;
3123 3124 3125
    } else if (pLimitInfo->currentGroupId != pBlock->info.groupId) {
      // now it is the data from a new group
      pLimitInfo->remainGroupOffset -= 1;
3126 3127

      // ignore data block in current group
3128 3129
      if (pLimitInfo->remainGroupOffset > 0) {
        blockDataCleanup(pBlock);
3130 3131 3132 3133 3134
        return PROJECT_RETRIEVE_CONTINUE;
      }
    }

    // set current group id of the project operator
3135
    pLimitInfo->currentGroupId = pBlock->info.groupId;
3136 3137
  }

3138
  // here check for a new group data, we need to handle the data of the previous group.
3139 3140 3141
  if (pLimitInfo->currentGroupId != 0 && pLimitInfo->currentGroupId != pBlock->info.groupId) {
    pLimitInfo->numOfOutputGroups += 1;
    if ((pLimitInfo->slimit.limit > 0) && (pLimitInfo->slimit.limit <= pLimitInfo->numOfOutputGroups)) {
3142
      pOperator->status = OP_EXEC_DONE;
3143
      blockDataCleanup(pBlock);
3144 3145 3146 3147 3148

      return PROJECT_RETRIEVE_DONE;
    }

    // reset the value for a new group data
3149 3150
    pLimitInfo->numOfOutputRows = 0;
    pLimitInfo->remainOffset = pLimitInfo->limit.offset;
3151 3152 3153 3154 3155

    // existing rows that belongs to previous group.
    if (pBlock->info.rows > 0) {
      return PROJECT_RETRIEVE_DONE;
    }
3156 3157 3158 3159 3160
  }

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

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

3163 3164 3165
  if (pLimitInfo->remainOffset >= pBlock->info.rows) {
    pLimitInfo->remainOffset -= pBlock->info.rows;
    blockDataCleanup(pBlock);
3166
    return PROJECT_RETRIEVE_CONTINUE;
3167 3168 3169
  } else if (pLimitInfo->remainOffset < pBlock->info.rows && pLimitInfo->remainOffset > 0) {
    blockDataTrimFirstNRows(pBlock, pLimitInfo->remainOffset);
    pLimitInfo->remainOffset = 0;
3170 3171
  }

3172
  // check for the limitation in each group
3173 3174 3175 3176
  if (pLimitInfo->limit.limit >= 0 && pLimitInfo->numOfOutputRows + pBlock->info.rows >= pLimitInfo->limit.limit) {
    int32_t keepRows = (int32_t)(pLimitInfo->limit.limit - pLimitInfo->numOfOutputRows);
    blockDataKeepFirstNRows(pBlock, keepRows);
    if (pLimitInfo->slimit.limit > 0 && pLimitInfo->slimit.limit <= pLimitInfo->numOfOutputGroups) {
3177 3178 3179
      pOperator->status = OP_EXEC_DONE;
    }

3180
    return PROJECT_RETRIEVE_DONE;
3181
  }
3182

3183
  // todo optimize performance
3184 3185
  // If there are slimit/soffset value exists, multi-round result can not be packed into one group, since the
  // they may not belong to the same group the limit/offset value is not valid in this case.
3186 3187
  if ((!holdDataInBuf) || (pBlock->info.rows >= pOperator->resultInfo.threshold) || pLimitInfo->slimit.offset != -1 ||
      pLimitInfo->slimit.limit != -1) {
3188
    return PROJECT_RETRIEVE_DONE;
L
Liu Jicong 已提交
3189
  } else {  // not full enough, continue to accumulate the output data in the buffer.
3190 3191 3192 3193
    return PROJECT_RETRIEVE_CONTINUE;
  }
}

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

L
Liu Jicong 已提交
3198 3199
  int64_t ekey =
      Q_STATUS_EQUAL(pTaskInfo->status, TASK_COMPLETED) ? pInfo->win.ekey : pInfo->existNewGroupBlock->info.window.ekey;
3200 3201
  taosResetFillInfo(pInfo->pFillInfo, getFillInfoStart(pInfo->pFillInfo));

3202
  taosFillSetStartInfo(pInfo->pFillInfo, pInfo->existNewGroupBlock->info.rows, ekey);
3203 3204
  taosFillSetInputDataBlock(pInfo->pFillInfo, pInfo->existNewGroupBlock);

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

3208
  pInfo->curGroupId = pInfo->existNewGroupBlock->info.groupId;
3209 3210 3211
  pInfo->existNewGroupBlock = NULL;
}

H
Haojun Liao 已提交
3212
static void doHandleRemainBlockFromNewGroup(SFillOperatorInfo* pInfo, SResultInfo* pResultInfo,
L
Liu Jicong 已提交
3213
                                            SExecTaskInfo* pTaskInfo) {
3214
  if (taosFillHasMoreResults(pInfo->pFillInfo)) {
H
Haojun Liao 已提交
3215 3216
    int32_t numOfResultRows = pResultInfo->capacity - pInfo->pRes->info.rows;
    taosFillResultDataBlock(pInfo->pFillInfo, pInfo->pRes, numOfResultRows);
3217 3218
    pInfo->pRes->info.groupId = pInfo->curGroupId;
    return;
3219 3220 3221 3222
  }

  // handle the cached new group data block
  if (pInfo->existNewGroupBlock) {
H
Haojun Liao 已提交
3223
    doHandleRemainBlockForNewGroupImpl(pInfo, pResultInfo, pTaskInfo);
3224 3225 3226
  }
}

S
slzhou 已提交
3227
static SSDataBlock* doFillImpl(SOperatorInfo* pOperator) {
L
Liu Jicong 已提交
3228 3229
  SFillOperatorInfo* pInfo = pOperator->info;
  SExecTaskInfo*     pTaskInfo = pOperator->pTaskInfo;
3230

H
Haojun Liao 已提交
3231
  SResultInfo* pResultInfo = &pOperator->resultInfo;
3232 3233 3234
  SSDataBlock* pResBlock = pInfo->pRes;

  blockDataCleanup(pResBlock);
3235

H
Haojun Liao 已提交
3236
  doHandleRemainBlockFromNewGroup(pInfo, pResultInfo, pTaskInfo);
3237
  if (pResBlock->info.rows > 0) {
3238
    pResBlock->info.groupId = pInfo->curGroupId;
3239
    return pResBlock;
H
Haojun Liao 已提交
3240
  }
3241

H
Haojun Liao 已提交
3242
  SOperatorInfo* pDownstream = pOperator->pDownstream[0];
L
Liu Jicong 已提交
3243
  while (1) {
3244
    SSDataBlock* pBlock = pDownstream->fpSet.getNextFn(pDownstream);
3245 3246 3247 3248 3249
    if (pBlock == NULL) {
      if (pInfo->totalInputRows == 0) {
        pOperator->status = OP_EXEC_DONE;
        return NULL;
      }
3250

3251
      taosFillSetStartInfo(pInfo->pFillInfo, 0, pInfo->win.ekey);
3252
    } else {
3253 3254 3255
      blockDataUpdateTsWindow(pBlock, pInfo->primaryTsCol);

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

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

3260 3261
        taosFillSetStartInfo(pInfo->pFillInfo, pBlock->info.rows, pBlock->info.window.ekey);
        taosFillSetInputDataBlock(pInfo->pFillInfo, pBlock);
L
Liu Jicong 已提交
3262
      } else if (pInfo->curGroupId != pBlock->info.groupId) {  // the new group data block
3263 3264 3265 3266 3267
        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);
3268 3269 3270
      }
    }

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

3273 3274
    int32_t numOfResultRows = pOperator->resultInfo.capacity - pResBlock->info.rows;
    taosFillResultDataBlock(pInfo->pFillInfo, pResBlock, numOfResultRows);
3275 3276

    // current group has no more result to return
3277
    if (pResBlock->info.rows > 0) {
3278 3279
      // 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
3280
      if (pResBlock->info.rows > pResultInfo->threshold || pBlock == NULL || pInfo->existNewGroupBlock != NULL) {
3281
        pResBlock->info.groupId = pInfo->curGroupId;
3282
        return pResBlock;
3283 3284
      }

H
Haojun Liao 已提交
3285
      doHandleRemainBlockFromNewGroup(pInfo, pResultInfo, pTaskInfo);
3286
      if (pResBlock->info.rows >= pOperator->resultInfo.threshold || pBlock == NULL) {
3287
        pResBlock->info.groupId = pInfo->curGroupId;
3288
        return pResBlock;
3289 3290 3291
      }
    } else if (pInfo->existNewGroupBlock) {  // try next group
      assert(pBlock != NULL);
H
Haojun Liao 已提交
3292
      doHandleRemainBlockForNewGroupImpl(pInfo, pResultInfo, pTaskInfo);
3293
      if (pResBlock->info.rows > pResultInfo->threshold) {
3294
        pResBlock->info.groupId = pInfo->curGroupId;
3295
        return pResBlock;
3296 3297 3298 3299 3300 3301 3302
      }
    } else {
      return NULL;
    }
  }
}

S
slzhou 已提交
3303 3304 3305 3306 3307 3308 3309 3310
static SSDataBlock* doFill(SOperatorInfo* pOperator) {
  SFillOperatorInfo* pInfo = pOperator->info;
  SExecTaskInfo*     pTaskInfo = pOperator->pTaskInfo;

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

S
slzhou 已提交
3311
  SSDataBlock* fillResult = NULL;
S
slzhou 已提交
3312
  while (true) {
S
slzhou 已提交
3313
    fillResult = doFillImpl(pOperator);
S
slzhou 已提交
3314 3315 3316 3317 3318
    if (fillResult == NULL) {
      doSetOperatorCompleted(pOperator);
      break;
    }

3319
    doFilter(pInfo->pCondition, fillResult, pInfo->pColMatchColInfo);
S
slzhou 已提交
3320 3321 3322 3323 3324
    if (fillResult->info.rows > 0) {
      break;
    }
  }

S
slzhou 已提交
3325
  if (fillResult != NULL) {
3326
    pOperator->resultInfo.totalRows += fillResult->info.rows;
S
slzhou 已提交
3327
  }
S
slzhou 已提交
3328

S
slzhou 已提交
3329
  return fillResult;
S
slzhou 已提交
3330 3331
}

3332 3333 3334 3335 3336 3337 3338 3339
void destroyExprInfo(SExprInfo* pExpr, int32_t numOfExprs) {
  if (pExpr) {
    for (int32_t i = 0; i < numOfExprs; ++i) {
      SExprInfo* pExprInfo = &pExpr[i];
      for (int32_t j = 0; j < pExprInfo->base.numOfParams; ++j) {
        if (pExprInfo->base.pParam[j].type == FUNC_PARAM_TYPE_COLUMN) {
          taosMemoryFreeClear(pExprInfo->base.pParam[j].pCol);
        }
H
Haojun Liao 已提交
3340 3341
      }

3342 3343 3344
      taosMemoryFree(pExprInfo->base.pParam);
      taosMemoryFree(pExprInfo->pExpr);
    }
H
Haojun Liao 已提交
3345 3346 3347
  }
}

3348 3349 3350 3351 3352
static void destroyOperatorInfo(SOperatorInfo* pOperator) {
  if (pOperator == NULL) {
    return;
  }

3353
  if (pOperator->fpSet.closeFn != NULL) {
3354
    pOperator->fpSet.closeFn(pOperator->info, pOperator->exprSupp.numOfExprs);
3355 3356
  }

H
Haojun Liao 已提交
3357
  if (pOperator->pDownstream != NULL) {
L
Liu Jicong 已提交
3358
    for (int32_t i = 0; i < pOperator->numOfDownstream; ++i) {
H
Haojun Liao 已提交
3359
      destroyOperatorInfo(pOperator->pDownstream[i]);
3360 3361
    }

wafwerar's avatar
wafwerar 已提交
3362
    taosMemoryFreeClear(pOperator->pDownstream);
H
Haojun Liao 已提交
3363
    pOperator->numOfDownstream = 0;
3364 3365
  }

3366
  cleanupExprSupp(&pOperator->exprSupp);
wafwerar's avatar
wafwerar 已提交
3367
  taosMemoryFreeClear(pOperator);
3368 3369
}

3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384
int32_t getBufferPgSize(int32_t rowSize, uint32_t* defaultPgsz, uint32_t* defaultBufsz) {
  *defaultPgsz = 4096;
  while (*defaultPgsz < rowSize * 4) {
    *defaultPgsz <<= 1u;
  }

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

  return 0;
}

dengyihao's avatar
dengyihao 已提交
3385 3386
int32_t doInitAggInfoSup(SAggSupporter* pAggSup, SqlFunctionCtx* pCtx, int32_t numOfOutput, size_t keyBufSize,
                         const char* pKey) {
3387 3388
  _hash_fn_t hashFn = taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY);

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

H
Haojun Liao 已提交
3393
  if (pAggSup->keyBuf == NULL || pAggSup->pResultRowHashTable == NULL) {
3394 3395 3396
    return TSDB_CODE_OUT_OF_MEMORY;
  }

dengyihao's avatar
dengyihao 已提交
3397
  uint32_t defaultPgsz = 0;
3398 3399
  uint32_t defaultBufsz = 0;
  getBufferPgSize(pAggSup->resultRowSize, &defaultPgsz, &defaultBufsz);
H
Haojun Liao 已提交
3400

wafwerar's avatar
wafwerar 已提交
3401 3402 3403 3404 3405 3406
  if (!osTempSpaceAvailable()) {
    terrno = TSDB_CODE_NO_AVAIL_DISK;
    qError("Init stream agg supporter failed since %s", terrstr(terrno));
    return terrno;
  }
  int32_t code = createDiskbasedBuf(&pAggSup->pResultBuf, defaultPgsz, defaultBufsz, pKey, tsTempDir);
H
Haojun Liao 已提交
3407 3408 3409 3410
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

3411 3412 3413
  return TSDB_CODE_SUCCESS;
}

3414
void cleanupAggSup(SAggSupporter* pAggSup) {
wafwerar's avatar
wafwerar 已提交
3415
  taosMemoryFreeClear(pAggSup->keyBuf);
3416
  taosHashCleanup(pAggSup->pResultRowHashTable);
H
Haojun Liao 已提交
3417
  destroyDiskbasedBuf(pAggSup->pResultBuf);
3418 3419
}

L
Liu Jicong 已提交
3420 3421
int32_t initAggInfo(SExprSupp* pSup, SAggSupporter* pAggSup, SExprInfo* pExprInfo, int32_t numOfCols, size_t keyBufSize,
                    const char* pkey) {
3422 3423 3424 3425 3426
  int32_t code = initExprSupp(pSup, pExprInfo, numOfCols);
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

3427
  doInitAggInfoSup(pAggSup, pSup->pCtx, numOfCols, keyBufSize, pkey);
L
Liu Jicong 已提交
3428
  for (int32_t i = 0; i < numOfCols; ++i) {
3429
    pSup->pCtx[i].pBuf = pAggSup->pResultBuf;
3430 3431
  }

3432
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
3433 3434
}

L
Liu Jicong 已提交
3435
void initResultSizeInfo(SResultInfo* pResultInfo, int32_t numOfRows) {
wmmhello's avatar
wmmhello 已提交
3436
  ASSERT(numOfRows != 0);
3437 3438
  pResultInfo->capacity = numOfRows;
  pResultInfo->threshold = numOfRows * 0.75;
3439

3440 3441
  if (pResultInfo->threshold == 0) {
    pResultInfo->threshold = numOfRows;
3442 3443 3444
  }
}

3445 3446 3447 3448 3449
void initBasicInfo(SOptrBasicInfo* pInfo, SSDataBlock* pBlock) {
  pInfo->pRes = pBlock;
  initResultRowInfo(&pInfo->resultRowInfo);
}

5
54liuyao 已提交
3450
void* destroySqlFunctionCtx(SqlFunctionCtx* pCtx, int32_t numOfOutput) {
3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468
  if (pCtx == NULL) {
    return NULL;
  }

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

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

  taosMemoryFreeClear(pCtx);
  return NULL;
}

3469
int32_t initExprSupp(SExprSupp* pSup, SExprInfo* pExprInfo, int32_t numOfExpr) {
3470 3471 3472 3473
  pSup->pExprInfo = pExprInfo;
  pSup->numOfExprs = numOfExpr;
  if (pSup->pExprInfo != NULL) {
    pSup->pCtx = createSqlFunctionCtx(pExprInfo, numOfExpr, &pSup->rowEntryInfoOffset);
3474 3475 3476
    if (pSup->pCtx == NULL) {
      return TSDB_CODE_OUT_OF_MEMORY;
    }
3477
  }
3478 3479

  return TSDB_CODE_SUCCESS;
3480 3481
}

3482 3483 3484 3485
void cleanupExprSupp(SExprSupp* pSupp) {
  destroySqlFunctionCtx(pSupp->pCtx, pSupp->numOfExprs);
  if (pSupp->pExprInfo != NULL) {
    destroyExprInfo(pSupp->pExprInfo, pSupp->numOfExprs);
C
Cary Xu 已提交
3486
    taosMemoryFreeClear(pSupp->pExprInfo);
3487 3488 3489 3490
  }
  taosMemoryFree(pSupp->rowEntryInfoOffset);
}

L
Liu Jicong 已提交
3491
SOperatorInfo* createAggregateOperatorInfo(SOperatorInfo* downstream, SExprInfo* pExprInfo, int32_t numOfCols,
S
slzhou 已提交
3492
                                           SSDataBlock* pResultBlock, SNode* pCondition, SExprInfo* pScalarExprInfo,
wmmhello's avatar
wmmhello 已提交
3493
                                           int32_t numOfScalarExpr, SExecTaskInfo* pTaskInfo) {
wafwerar's avatar
wafwerar 已提交
3494
  SAggOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SAggOperatorInfo));
L
Liu Jicong 已提交
3495
  SOperatorInfo*    pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
3496 3497 3498
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }
H
Haojun Liao 已提交
3499

3500
  int32_t numOfRows = 1024;
dengyihao's avatar
dengyihao 已提交
3501
  size_t  keyBufSize = sizeof(int64_t) + sizeof(int64_t) + POINTER_BYTES;
3502

3503
  initResultSizeInfo(&pOperator->resultInfo, numOfRows);
3504
  int32_t code = initAggInfo(&pOperator->exprSupp, &pInfo->aggSup, pExprInfo, numOfCols, keyBufSize, pTaskInfo->id.str);
L
Liu Jicong 已提交
3505
  if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
3506 3507
    goto _error;
  }
H
Haojun Liao 已提交
3508

3509
  initBasicInfo(&pInfo->binfo, pResultBlock);
3510 3511 3512 3513
  code = initExprSupp(&pInfo->scalarExprSup, pScalarExprInfo, numOfScalarExpr);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
3514

3515
  pInfo->groupId = UINT64_MAX;
S
slzhou 已提交
3516
  pInfo->pCondition = pCondition;
dengyihao's avatar
dengyihao 已提交
3517
  pOperator->name = "TableAggregate";
3518
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_HASH_AGG;
3519
  pOperator->blocking = true;
dengyihao's avatar
dengyihao 已提交
3520 3521 3522
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
  pOperator->pTaskInfo = pTaskInfo;
H
Haojun Liao 已提交
3523

3524 3525
  pOperator->fpSet = createOperatorFpSet(doOpenAggregateOptr, getAggregateResult, NULL, NULL, destroyAggOperatorInfo,
                                         aggEncodeResultRow, aggDecodeResultRow, NULL);
H
Haojun Liao 已提交
3526

3527 3528 3529 3530 3531 3532
  if (downstream->operatorType == QUERY_NODE_PHYSICAL_PLAN_TABLE_SCAN) {
    STableScanInfo* pTableScanInfo = downstream->info;
    pTableScanInfo->pdInfo.pExprSup = &pOperator->exprSupp;
    pTableScanInfo->pdInfo.pAggSup = &pInfo->aggSup;
  }

H
Haojun Liao 已提交
3533 3534 3535 3536
  code = appendDownstream(pOperator, &downstream, 1);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
3537 3538

  return pOperator;
L
Liu Jicong 已提交
3539
_error:
H
Haojun Liao 已提交
3540
  destroyAggOperatorInfo(pInfo, numOfCols);
wafwerar's avatar
wafwerar 已提交
3541 3542
  taosMemoryFreeClear(pInfo);
  taosMemoryFreeClear(pOperator);
H
Haojun Liao 已提交
3543 3544
  pTaskInfo->code = TSDB_CODE_OUT_OF_MEMORY;
  return NULL;
3545 3546
}

3547
void cleanupBasicInfo(SOptrBasicInfo* pInfo) {
3548 3549
  assert(pInfo != NULL);
  cleanupResultRowInfo(&pInfo->resultRowInfo);
H
Haojun Liao 已提交
3550
  pInfo->pRes = blockDataDestroy(pInfo->pRes);
3551 3552
}

H
Haojun Liao 已提交
3553
void destroyBasicOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
3554
  SOptrBasicInfo* pInfo = (SOptrBasicInfo*)param;
3555
  cleanupBasicInfo(pInfo);
L
Liu Jicong 已提交
3556

D
dapan1121 已提交
3557
  taosMemoryFreeClear(param);
3558
}
H
Haojun Liao 已提交
3559

H
Haojun Liao 已提交
3560 3561 3562 3563 3564 3565 3566
static void freeItem(void* pItem) {
  void** p = pItem;
  if (*p != NULL) {
    taosMemoryFreeClear(*p);
  }
}

H
Haojun Liao 已提交
3567
void destroyAggOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
3568
  SAggOperatorInfo* pInfo = (SAggOperatorInfo*)param;
L
Liu Jicong 已提交
3569 3570
  cleanupBasicInfo(&pInfo->binfo);

H
Haojun Liao 已提交
3571
  cleanupAggSup(&pInfo->aggSup);
S
shenglian zhou 已提交
3572
  cleanupExprSupp(&pInfo->scalarExprSup);
H
Haojun Liao 已提交
3573
  cleanupGroupResInfo(&pInfo->groupResInfo);
D
dapan1121 已提交
3574
  taosMemoryFreeClear(param);
3575
}
3576

3577
void destroyFillOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
3578
  SFillOperatorInfo* pInfo = (SFillOperatorInfo*)param;
3579
  pInfo->pFillInfo = taosDestroyFillInfo(pInfo->pFillInfo);
H
Haojun Liao 已提交
3580
  pInfo->pRes = blockDataDestroy(pInfo->pRes);
wafwerar's avatar
wafwerar 已提交
3581
  taosMemoryFreeClear(pInfo->p);
3582
  taosArrayDestroy(pInfo->pColMatchColInfo);
D
dapan1121 已提交
3583
  taosMemoryFreeClear(param);
3584 3585
}

H
Haojun Liao 已提交
3586
void destroyExchangeOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
3587
  SExchangeInfo* pExInfo = (SExchangeInfo*)param;
3588 3589 3590 3591
  taosRemoveRef(exchangeObjRefPool, pExInfo->self);
}

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

H
Haojun Liao 已提交
3594 3595 3596
  taosArrayDestroy(pExInfo->pSources);
  taosArrayDestroy(pExInfo->pSourceDataInfo);
  if (pExInfo->pResult != NULL) {
H
Haojun Liao 已提交
3597
    pExInfo->pResult = blockDataDestroy(pExInfo->pResult);
H
Haojun Liao 已提交
3598 3599 3600
  }

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

D
dapan1121 已提交
3602
  taosMemoryFreeClear(param);
H
Haojun Liao 已提交
3603 3604
}

3605
static int32_t initFillInfo(SFillOperatorInfo* pInfo, SExprInfo* pExpr, int32_t numOfCols, SNodeListNode* pValNode,
3606 3607
                            STimeWindow win, int32_t capacity, const char* id, SInterval* pInterval, int32_t fillType,
                            int32_t order) {
3608
  SFillColInfo* pColInfo = createFillColInfo(pExpr, numOfCols, pValNode);
H
Haojun Liao 已提交
3609

3610
  STimeWindow w = getAlignQueryTimeWindow(pInterval, pInterval->precision, win.skey);
3611
  w = getFirstQualifiedTimeWindow(win.skey, &w, pInterval, TSDB_ORDER_ASC);
H
Haojun Liao 已提交
3612

L
Liu Jicong 已提交
3613
  pInfo->pFillInfo =
3614
      taosCreateFillInfo(w.skey, 0, capacity, numOfCols, pInterval, fillType, pColInfo, pInfo->primaryTsCol, order, id);
H
Haojun Liao 已提交
3615

3616
  pInfo->win = win;
L
Liu Jicong 已提交
3617
  pInfo->p = taosMemoryCalloc(numOfCols, POINTER_BYTES);
3618

H
Haojun Liao 已提交
3619
  if (pInfo->pFillInfo == NULL || pInfo->p == NULL) {
H
Haojun Liao 已提交
3620 3621
    taosMemoryFree(pInfo->pFillInfo);
    taosMemoryFree(pInfo->p);
H
Haojun Liao 已提交
3622 3623 3624 3625 3626 3627
    return TSDB_CODE_OUT_OF_MEMORY;
  } else {
    return TSDB_CODE_SUCCESS;
  }
}

L
Liu Jicong 已提交
3628 3629
SOperatorInfo* createFillOperatorInfo(SOperatorInfo* downstream, SFillPhysiNode* pPhyFillNode,
                                      SExecTaskInfo* pTaskInfo) {
3630 3631 3632 3633 3634 3635
  SFillOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SFillOperatorInfo));
  SOperatorInfo*     pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }

L
Liu Jicong 已提交
3636 3637 3638
  int32_t      num = 0;
  SSDataBlock* pResBlock = createResDataBlock(pPhyFillNode->node.pOutputDataBlockDesc);
  SExprInfo*   pExprInfo = createExprInfo(pPhyFillNode->pTargets, NULL, &num);
3639 3640 3641 3642
  SInterval*   pInterval =
      QUERY_NODE_PHYSICAL_PLAN_MERGE_ALIGNED_INTERVAL == downstream->operatorType
            ? &((SMergeAlignedIntervalAggOperatorInfo*)downstream->info)->intervalAggOperatorInfo->interval
            : &((SIntervalAggOperatorInfo*)downstream->info)->interval;
3643

3644
  int32_t order = (pPhyFillNode->inputTsOrder == ORDER_ASC) ? TSDB_ORDER_ASC : TSDB_ORDER_DESC;
3645
  int32_t type = convertFillType(pPhyFillNode->mode);
3646

H
Haojun Liao 已提交
3647
  SResultInfo* pResultInfo = &pOperator->resultInfo;
3648
  initResultSizeInfo(&pOperator->resultInfo, 4096);
H
Haojun Liao 已提交
3649
  pInfo->primaryTsCol = ((SColumnNode*)pPhyFillNode->pWStartTs)->slotId;
3650

3651
  int32_t numOfOutputCols = 0;
3652 3653
  SArray* pColMatchColInfo = extractColMatchInfo(pPhyFillNode->pTargets, pPhyFillNode->node.pOutputDataBlockDesc,
                                                 &numOfOutputCols, COL_MATCH_FROM_SLOT_ID);
3654

3655
  int32_t code = initFillInfo(pInfo, pExprInfo, num, (SNodeListNode*)pPhyFillNode->pValues, pPhyFillNode->timeRange,
3656
                              pResultInfo->capacity, pTaskInfo->id.str, pInterval, type, order);
3657 3658 3659
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
3660

3661 3662 3663 3664 3665 3666 3667 3668
  pInfo->pRes = pResBlock;
  pInfo->pCondition = pPhyFillNode->node.pConditions;
  pInfo->pColMatchColInfo = pColMatchColInfo;
  pOperator->name = "FillOperator";
  pOperator->blocking = false;
  pOperator->status = OP_NOT_OPENED;
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_FILL;
  pOperator->exprSupp.pExprInfo = pExprInfo;
3669
  pOperator->exprSupp.numOfExprs = num;
3670 3671
  pOperator->info = pInfo;
  pOperator->pTaskInfo = pTaskInfo;
H
Haojun Liao 已提交
3672

L
Liu Jicong 已提交
3673
  pOperator->fpSet =
3674
      createOperatorFpSet(operatorDummyOpenFn, doFill, NULL, NULL, destroyFillOperatorInfo, NULL, NULL, NULL);
3675

3676
  code = appendDownstream(pOperator, &downstream, 1);
3677
  return pOperator;
H
Haojun Liao 已提交
3678

L
Liu Jicong 已提交
3679
_error:
wafwerar's avatar
wafwerar 已提交
3680 3681
  taosMemoryFreeClear(pOperator);
  taosMemoryFreeClear(pInfo);
H
Haojun Liao 已提交
3682
  return NULL;
3683 3684
}

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

3689
  pTaskInfo->schemaInfo.dbname = strdup(dbFName);
3690
  pTaskInfo->cost.created = taosGetTimestampMs();
H
Haojun Liao 已提交
3691
  pTaskInfo->id.queryId = queryId;
dengyihao's avatar
dengyihao 已提交
3692
  pTaskInfo->execModel = model;
H
Haojun Liao 已提交
3693

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

3698 3699
  return pTaskInfo;
}
H
Haojun Liao 已提交
3700

H
Haojun Liao 已提交
3701
static SArray* extractColumnInfo(SNodeList* pNodeList);
3702

H
Haojun Liao 已提交
3703 3704
SSchemaWrapper* extractQueriedColumnSchema(SScanPhysiNode* pScanNode);

3705
int32_t extractTableSchemaInfo(SReadHandle* pHandle, SScanPhysiNode* pScanNode, SExecTaskInfo* pTaskInfo) {
3706 3707
  SMetaReader mr = {0};
  metaReaderInit(&mr, pHandle->meta, 0);
3708
  int32_t code = metaGetTableEntryByUid(&mr, pScanNode->uid);
3709
  if (code != TSDB_CODE_SUCCESS) {
L
Liu Jicong 已提交
3710 3711
    qError("failed to get the table meta, uid:0x%" PRIx64 ", suid:0x%" PRIx64 ", %s", pScanNode->uid, pScanNode->suid,
           GET_TASKID(pTaskInfo));
H
Haojun Liao 已提交
3712

D
dapan1121 已提交
3713
    metaReaderClear(&mr);
3714
    return terrno;
D
dapan1121 已提交
3715
  }
3716

3717 3718
  SSchemaInfo* pSchemaInfo = &pTaskInfo->schemaInfo;
  pSchemaInfo->tablename = strdup(mr.me.name);
3719 3720

  if (mr.me.type == TSDB_SUPER_TABLE) {
3721 3722
    pSchemaInfo->sw = tCloneSSchemaWrapper(&mr.me.stbEntry.schemaRow);
    pSchemaInfo->tversion = mr.me.stbEntry.schemaTag.version;
3723
  } else if (mr.me.type == TSDB_CHILD_TABLE) {
3724 3725
    tDecoderClear(&mr.coder);

3726 3727
    tb_uid_t suid = mr.me.ctbEntry.suid;
    metaGetTableEntryByUid(&mr, suid);
3728 3729
    pSchemaInfo->sw = tCloneSSchemaWrapper(&mr.me.stbEntry.schemaRow);
    pSchemaInfo->tversion = mr.me.stbEntry.schemaTag.version;
3730
  } else {
3731
    pSchemaInfo->sw = tCloneSSchemaWrapper(&mr.me.ntbEntry.schemaRow);
3732
  }
3733 3734

  metaReaderClear(&mr);
3735

H
Haojun Liao 已提交
3736 3737 3738 3739 3740
  pSchemaInfo->qsw = extractQueriedColumnSchema(pScanNode);
  return TSDB_CODE_SUCCESS;
}

SSchemaWrapper* extractQueriedColumnSchema(SScanPhysiNode* pScanNode) {
3741 3742 3743
  int32_t numOfCols = LIST_LENGTH(pScanNode->pScanCols);
  int32_t numOfTags = LIST_LENGTH(pScanNode->pScanPseudoCols);

3744
  SSchemaWrapper* pqSw = taosMemoryCalloc(1, sizeof(SSchemaWrapper));
3745
  pqSw->pSchema = taosMemoryCalloc(numOfCols + numOfTags, sizeof(SSchema));
3746

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

H
Haojun Liao 已提交
3751 3752 3753 3754 3755
    SSchema* pSchema = &pqSw->pSchema[pqSw->nCols++];
    pSchema->colId = pColNode->colId;
    pSchema->type = pColNode->node.resType.type;
    pSchema->type = pColNode->node.resType.bytes;
    strncpy(pSchema->name, pColNode->colName, tListLen(pSchema->name));
3756 3757
  }

3758
  // this the tags and pseudo function columns, we only keep the tag columns
3759
  for (int32_t i = 0; i < numOfTags; ++i) {
3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773
    STargetNode* pNode = (STargetNode*)nodesListGetNode(pScanNode->pScanPseudoCols, i);

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

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

H
Haojun Liao 已提交
3774
  return pqSw;
3775 3776
}

3777 3778
static void cleanupTableSchemaInfo(SSchemaInfo* pSchemaInfo) {
  taosMemoryFreeClear(pSchemaInfo->dbname);
3779
  taosMemoryFreeClear(pSchemaInfo->tablename);
3780 3781
  tDeleteSSchemaWrapper(pSchemaInfo->sw);
  tDeleteSSchemaWrapper(pSchemaInfo->qsw);
3782 3783
}

3784
static int32_t sortTableGroup(STableListInfo* pTableListInfo, int32_t groupNum) {
wmmhello's avatar
wmmhello 已提交
3785
  taosArrayClear(pTableListInfo->pGroupList);
3786 3787
  SArray* sortSupport = taosArrayInit(groupNum, sizeof(uint64_t));
  if (sortSupport == NULL) return TSDB_CODE_OUT_OF_MEMORY;
wmmhello's avatar
wmmhello 已提交
3788 3789
  for (int32_t i = 0; i < taosArrayGetSize(pTableListInfo->pTableList); i++) {
    STableKeyInfo* info = taosArrayGet(pTableListInfo->pTableList, i);
3790
    uint64_t*      groupId = taosHashGet(pTableListInfo->map, &info->uid, sizeof(uint64_t));
wmmhello's avatar
wmmhello 已提交
3791 3792

    int32_t index = taosArraySearchIdx(sortSupport, groupId, compareUint64Val, TD_EQ);
3793 3794 3795 3796
    if (index == -1) {
      void*   p = taosArraySearch(sortSupport, groupId, compareUint64Val, TD_GT);
      SArray* tGroup = taosArrayInit(8, sizeof(STableKeyInfo));
      if (tGroup == NULL) {
wmmhello's avatar
wmmhello 已提交
3797 3798 3799
        taosArrayDestroy(sortSupport);
        return TSDB_CODE_OUT_OF_MEMORY;
      }
3800
      if (taosArrayPush(tGroup, info) == NULL) {
wmmhello's avatar
wmmhello 已提交
3801 3802 3803 3804
        qError("taos push info array error");
        taosArrayDestroy(sortSupport);
        return TSDB_CODE_QRY_APP_ERROR;
      }
3805
      if (p == NULL) {
wmmhello's avatar
wmmhello 已提交
3806
        if (taosArrayPush(sortSupport, groupId) == NULL) {
wmmhello's avatar
wmmhello 已提交
3807 3808 3809 3810
          qError("taos push support array error");
          taosArrayDestroy(sortSupport);
          return TSDB_CODE_QRY_APP_ERROR;
        }
wmmhello's avatar
wmmhello 已提交
3811
        if (taosArrayPush(pTableListInfo->pGroupList, &tGroup) == NULL) {
wmmhello's avatar
wmmhello 已提交
3812 3813 3814 3815
          qError("taos push group array error");
          taosArrayDestroy(sortSupport);
          return TSDB_CODE_QRY_APP_ERROR;
        }
3816
      } else {
wmmhello's avatar
wmmhello 已提交
3817
        int32_t pos = TARRAY_ELEM_IDX(sortSupport, p);
3818
        if (taosArrayInsert(sortSupport, pos, groupId) == NULL) {
wmmhello's avatar
wmmhello 已提交
3819 3820 3821 3822
          qError("taos insert support array error");
          taosArrayDestroy(sortSupport);
          return TSDB_CODE_QRY_APP_ERROR;
        }
3823
        if (taosArrayInsert(pTableListInfo->pGroupList, pos, &tGroup) == NULL) {
wmmhello's avatar
wmmhello 已提交
3824 3825 3826 3827 3828
          qError("taos insert group array error");
          taosArrayDestroy(sortSupport);
          return TSDB_CODE_QRY_APP_ERROR;
        }
      }
3829
    } else {
wmmhello's avatar
wmmhello 已提交
3830
      SArray* tGroup = (SArray*)taosArrayGetP(pTableListInfo->pGroupList, index);
3831
      if (taosArrayPush(tGroup, info) == NULL) {
wmmhello's avatar
wmmhello 已提交
3832 3833 3834 3835 3836 3837 3838 3839 3840 3841
        qError("taos push uid array error");
        taosArrayDestroy(sortSupport);
        return TSDB_CODE_QRY_APP_ERROR;
      }
    }
  }
  taosArrayDestroy(sortSupport);
  return TDB_CODE_SUCCESS;
}

3842
bool groupbyTbname(SNodeList* pGroupList) {
3843
  bool bytbname = false;
H
Haojun Liao 已提交
3844
  if (LIST_LENGTH(pGroupList) > 0) {
3845 3846 3847 3848 3849 3850 3851 3852 3853 3854
    SNode* p = nodesListGetNode(pGroupList, 0);
    if (p->type == QUERY_NODE_FUNCTION) {
      // partition by tbname/group by tbname
      bytbname = (strcmp(((struct SFunctionNode*)p)->functionName, "tbname") == 0);
    }
  }

  return bytbname;
}

wmmhello's avatar
wmmhello 已提交
3855 3856
int32_t generateGroupIdMap(STableListInfo* pTableListInfo, SReadHandle* pHandle, SNodeList* group) {
  if (group == NULL) {
wmmhello's avatar
wmmhello 已提交
3857 3858 3859 3860 3861 3862 3863 3864
    return TDB_CODE_SUCCESS;
  }

  pTableListInfo->map = taosHashInit(32, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), false, HASH_NO_LOCK);
  if (pTableListInfo->map == NULL) {
    return TSDB_CODE_OUT_OF_MEMORY;
  }
  int32_t keyLen = 0;
X
Xiaoyu Wang 已提交
3865
  void*   keyBuf = NULL;
wmmhello's avatar
wmmhello 已提交
3866

3867
  SNode* node;
wmmhello's avatar
wmmhello 已提交
3868
  FOREACH(node, group) {
3869
    SExprNode* pExpr = (SExprNode*)node;
wmmhello's avatar
wmmhello 已提交
3870
    keyLen += pExpr->resType.bytes;
wmmhello's avatar
wmmhello 已提交
3871 3872
  }

wmmhello's avatar
wmmhello 已提交
3873
  int32_t nullFlagSize = sizeof(int8_t) * LIST_LENGTH(group);
wmmhello's avatar
wmmhello 已提交
3874 3875 3876 3877 3878 3879 3880
  keyLen += nullFlagSize;

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

3881 3882
  bool assignUid = groupbyTbname(group);

3883
  int32_t groupNum = 0;
3884
  size_t  numOfTables = taosArrayGetSize(pTableListInfo->pTableList);
3885 3886

  for (int32_t i = 0; i < numOfTables; i++) {
X
Xiaoyu Wang 已提交
3887
    STableKeyInfo* info = taosArrayGet(pTableListInfo->pTableList, i);
3888 3889 3890 3891 3892 3893 3894 3895

    if (assignUid) {
      info->groupId = info->uid;
    } else {
      int32_t code = getGroupIdFromTagsVal(pHandle->meta, info->uid, group, keyBuf, &info->groupId);
      if (code != TSDB_CODE_SUCCESS) {
        return code;
      }
wmmhello's avatar
wmmhello 已提交
3896
    }
3897

3898
    taosHashPut(pTableListInfo->map, &(info->uid), sizeof(uint64_t), &info->groupId, sizeof(uint64_t));
3899
    groupNum++;
wmmhello's avatar
wmmhello 已提交
3900
  }
3901

wmmhello's avatar
wmmhello 已提交
3902
  taosMemoryFree(keyBuf);
3903

3904
  if (pTableListInfo->needSortTableByGroupId) {
wmmhello's avatar
wmmhello 已提交
3905
    return sortTableGroup(pTableListInfo, groupNum);
3906 3907
  }

wmmhello's avatar
wmmhello 已提交
3908 3909 3910
  return TDB_CODE_SUCCESS;
}

3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927
static int32_t initTableblockDistQueryCond(uint64_t uid, SQueryTableDataCond* pCond) {
  memset(pCond, 0, sizeof(SQueryTableDataCond));

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

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

  pCond->twindows = (STimeWindow){.skey = INT64_MIN, .ekey = INT64_MAX};
  pCond->suid = uid;
3928
  pCond->type = TIMEWINDOW_RANGE_CONTAINED;
3929
  pCond->startVersion = -1;
L
Liu Jicong 已提交
3930
  pCond->endVersion = -1;
3931 3932 3933 3934

  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
3935
SOperatorInfo* createOperatorTree(SPhysiNode* pPhyNode, SExecTaskInfo* pTaskInfo, SReadHandle* pHandle,
L
Liu Jicong 已提交
3936 3937
                                  STableListInfo* pTableListInfo, SNode* pTagCond, SNode* pTagIndexCond,
                                  const char* pUser) {
3938 3939
  int32_t type = nodeType(pPhyNode);

X
Xiaoyu Wang 已提交
3940
  if (pPhyNode->pChildren == NULL || LIST_LENGTH(pPhyNode->pChildren) == 0) {
3941
    SOperatorInfo* pOperator = NULL;
H
Haojun Liao 已提交
3942
    if (QUERY_NODE_PHYSICAL_PLAN_TABLE_SCAN == type) {
dengyihao's avatar
dengyihao 已提交
3943
      STableScanPhysiNode* pTableScanNode = (STableScanPhysiNode*)pPhyNode;
H
Haojun Liao 已提交
3944

L
Liu Jicong 已提交
3945 3946 3947
      int32_t code =
          createScanTableListInfo(&pTableScanNode->scan, pTableScanNode->pGroupTags, pTableScanNode->groupSort, pHandle,
                                  pTableListInfo, pTagCond, pTagIndexCond, GET_TASKID(pTaskInfo));
3948
      if (code) {
wmmhello's avatar
wmmhello 已提交
3949
        pTaskInfo->code = code;
D
dapan1121 已提交
3950 3951
        return NULL;
      }
wmmhello's avatar
wmmhello 已提交
3952

3953
      code = extractTableSchemaInfo(pHandle, &pTableScanNode->scan, pTaskInfo);
S
slzhou 已提交
3954
      if (code) {
3955
        pTaskInfo->code = terrno;
wmmhello's avatar
wmmhello 已提交
3956 3957 3958
        return NULL;
      }

3959
      pOperator = createTableScanOperatorInfo(pTableScanNode, pHandle, pTaskInfo);
3960 3961
      STableScanInfo* pScanInfo = pOperator->info;
      pTaskInfo->cost.pRecoder = &pScanInfo->readRecorder;
S
slzhou 已提交
3962 3963
    } else if (QUERY_NODE_PHYSICAL_PLAN_TABLE_MERGE_SCAN == type) {
      STableMergeScanPhysiNode* pTableScanNode = (STableMergeScanPhysiNode*)pPhyNode;
L
Liu Jicong 已提交
3964 3965 3966
      int32_t                   code =
          createScanTableListInfo(&pTableScanNode->scan, pTableScanNode->pGroupTags, pTableScanNode->groupSort, pHandle,
                                  pTableListInfo, pTagCond, pTagIndexCond, GET_TASKID(pTaskInfo));
L
Liu Jicong 已提交
3967
      if (code) {
wmmhello's avatar
wmmhello 已提交
3968
        pTaskInfo->code = code;
wmmhello's avatar
wmmhello 已提交
3969 3970
        return NULL;
      }
3971

3972
      code = extractTableSchemaInfo(pHandle, &pTableScanNode->scan, pTaskInfo);
wmmhello's avatar
wmmhello 已提交
3973 3974 3975 3976
      if (code) {
        pTaskInfo->code = terrno;
        return NULL;
      }
wmmhello's avatar
wmmhello 已提交
3977

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

3980 3981
      STableScanInfo* pScanInfo = pOperator->info;
      pTaskInfo->cost.pRecoder = &pScanInfo->readRecorder;
H
Haojun Liao 已提交
3982
    } else if (QUERY_NODE_PHYSICAL_PLAN_EXCHANGE == type) {
3983
      pOperator = createExchangeOperatorInfo(pHandle->pMsgCb->clientRpc, (SExchangePhysiNode*)pPhyNode, pTaskInfo);
H
Haojun Liao 已提交
3984
    } else if (QUERY_NODE_PHYSICAL_PLAN_STREAM_SCAN == type) {
5
54liuyao 已提交
3985
      STableScanPhysiNode* pTableScanNode = (STableScanPhysiNode*)pPhyNode;
5
54liuyao 已提交
3986
      if (pHandle->vnode) {
L
Liu Jicong 已提交
3987 3988 3989
        int32_t code =
            createScanTableListInfo(&pTableScanNode->scan, pTableScanNode->pGroupTags, pTableScanNode->groupSort,
                                    pHandle, pTableListInfo, pTagCond, pTagIndexCond, GET_TASKID(pTaskInfo));
L
Liu Jicong 已提交
3990
        if (code) {
wmmhello's avatar
wmmhello 已提交
3991 3992 3993
          pTaskInfo->code = code;
          return NULL;
        }
L
Liu Jicong 已提交
3994 3995 3996 3997 3998

#ifndef NDEBUG
        int32_t sz = taosArrayGetSize(pTableListInfo->pTableList);
        for (int32_t i = 0; i < sz; i++) {
          STableKeyInfo* pKeyInfo = taosArrayGet(pTableListInfo->pTableList, i);
S
Shengliang Guan 已提交
3999
          qDebug("creating stream task: add table %" PRId64, pKeyInfo->uid);
L
Liu Jicong 已提交
4000
        }
5
54liuyao 已提交
4001
      }
L
Liu Jicong 已提交
4002
#endif
4003

H
Haojun Liao 已提交
4004
      pTaskInfo->schemaInfo.qsw = extractQueriedColumnSchema(&pTableScanNode->scan);
4005
      pOperator = createStreamScanOperatorInfo(pHandle, pTableScanNode, pTagCond, pTaskInfo);
H
Haojun Liao 已提交
4006
    } else if (QUERY_NODE_PHYSICAL_PLAN_SYSTABLE_SCAN == type) {
L
Liu Jicong 已提交
4007
      SSystemTableScanPhysiNode* pSysScanPhyNode = (SSystemTableScanPhysiNode*)pPhyNode;
4008
      pOperator = createSysTableScanOperatorInfo(pHandle, pSysScanPhyNode, pUser, pTaskInfo);
4009
    } else if (QUERY_NODE_PHYSICAL_PLAN_TAG_SCAN == type) {
X
Xiaoyu Wang 已提交
4010
      STagScanPhysiNode* pScanPhyNode = (STagScanPhysiNode*)pPhyNode;
4011
      int32_t code = getTableList(pHandle->meta, pHandle->vnode, pScanPhyNode, pTagCond, pTagIndexCond, pTableListInfo);
4012
      if (code != TSDB_CODE_SUCCESS) {
4013
        pTaskInfo->code = terrno;
4014 4015 4016
        return NULL;
      }

4017
      pOperator = createTagScanOperatorInfo(pHandle, pScanPhyNode, pTableListInfo, pTaskInfo);
4018
    } else if (QUERY_NODE_PHYSICAL_PLAN_BLOCK_DIST_SCAN == type) {
4019
      SBlockDistScanPhysiNode* pBlockNode = (SBlockDistScanPhysiNode*)pPhyNode;
4020 4021 4022
      pTableListInfo->pTableList = taosArrayInit(4, sizeof(STableKeyInfo));

      if (pBlockNode->tableType == TSDB_SUPER_TABLE) {
4023
        int32_t code = vnodeGetAllTableList(pHandle->vnode, pBlockNode->uid, pTableListInfo->pTableList);
4024 4025 4026 4027 4028
        if (code != TSDB_CODE_SUCCESS) {
          pTaskInfo->code = terrno;
          return NULL;
        }
      } else {  // Create one table group.
4029
        STableKeyInfo info = {.uid = pBlockNode->uid, .groupId = 0};
4030 4031 4032 4033
        taosArrayPush(pTableListInfo->pTableList, &info);
      }

      SQueryTableDataCond cond = {0};
L
Liu Jicong 已提交
4034
      int32_t             code = initTableblockDistQueryCond(pBlockNode->suid, &cond);
4035 4036
      if (code != TSDB_CODE_SUCCESS) {
        return NULL;
4037
      }
H
Haojun Liao 已提交
4038 4039 4040

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

4043
      pOperator = createDataBlockInfoScanOperator(pReader, pHandle, cond.suid, pBlockNode, pTaskInfo);
H
Haojun Liao 已提交
4044 4045 4046
    } else if (QUERY_NODE_PHYSICAL_PLAN_LAST_ROW_SCAN == type) {
      SLastRowScanPhysiNode* pScanNode = (SLastRowScanPhysiNode*)pPhyNode;

L
Liu Jicong 已提交
4047 4048
      int32_t code = createScanTableListInfo(&pScanNode->scan, pScanNode->pGroupTags, true, pHandle, pTableListInfo,
                                             pTagCond, pTagIndexCond, GET_TASKID(pTaskInfo));
4049 4050 4051 4052
      if (code != TSDB_CODE_SUCCESS) {
        pTaskInfo->code = code;
        return NULL;
      }
4053

4054
      code = extractTableSchemaInfo(pHandle, &pScanNode->scan, pTaskInfo);
4055 4056 4057
      if (code != TSDB_CODE_SUCCESS) {
        pTaskInfo->code = code;
        return NULL;
H
Haojun Liao 已提交
4058 4059
      }

4060
      pOperator = createLastrowScanOperator(pScanNode, pHandle, pTaskInfo);
4061
    } else if (QUERY_NODE_PHYSICAL_PLAN_PROJECT == type) {
4062
      pOperator = createProjectOperatorInfo(NULL, (SProjectPhysiNode*)pPhyNode, pTaskInfo);
H
Haojun Liao 已提交
4063 4064
    } else {
      ASSERT(0);
H
Haojun Liao 已提交
4065
    }
4066 4067
    pOperator->resultDataBlockId = pPhyNode->pOutputDataBlockDesc->dataBlockId;
    return pOperator;
H
Haojun Liao 已提交
4068 4069
  }

4070 4071
  int32_t num = 0;
  size_t  size = LIST_LENGTH(pPhyNode->pChildren);
H
Haojun Liao 已提交
4072

4073
  SOperatorInfo** ops = taosMemoryCalloc(size, POINTER_BYTES);
dengyihao's avatar
dengyihao 已提交
4074
  for (int32_t i = 0; i < size; ++i) {
4075
    SPhysiNode* pChildNode = (SPhysiNode*)nodesListGetNode(pPhyNode->pChildren, i);
4076
    ops[i] = createOperatorTree(pChildNode, pTaskInfo, pHandle, pTableListInfo, pTagCond, pTagIndexCond, pUser);
4077
    if (ops[i] == NULL) {
H
Haojun Liao 已提交
4078
      taosMemoryFree(ops);
4079
      return NULL;
4080 4081
    } else {
      ops[i]->resultDataBlockId = pChildNode->pOutputDataBlockDesc->dataBlockId;
4082
    }
4083
  }
H
Haojun Liao 已提交
4084

4085
  SOperatorInfo* pOptr = NULL;
H
Haojun Liao 已提交
4086
  if (QUERY_NODE_PHYSICAL_PLAN_PROJECT == type) {
4087
    pOptr = createProjectOperatorInfo(ops[0], (SProjectPhysiNode*)pPhyNode, pTaskInfo);
4088
  } else if (QUERY_NODE_PHYSICAL_PLAN_HASH_AGG == type) {
H
Haojun Liao 已提交
4089 4090
    SAggPhysiNode* pAggNode = (SAggPhysiNode*)pPhyNode;
    SExprInfo*     pExprInfo = createExprInfo(pAggNode->pAggFuncs, pAggNode->pGroupKeys, &num);
4091
    SSDataBlock*   pResBlock = createResDataBlock(pPhyNode->pOutputDataBlockDesc);
H
Haojun Liao 已提交
4092

dengyihao's avatar
dengyihao 已提交
4093
    int32_t    numOfScalarExpr = 0;
4094 4095 4096 4097 4098
    SExprInfo* pScalarExprInfo = NULL;
    if (pAggNode->pExprs != NULL) {
      pScalarExprInfo = createExprInfo(pAggNode->pExprs, NULL, &numOfScalarExpr);
    }

H
Haojun Liao 已提交
4099 4100
    if (pAggNode->pGroupKeys != NULL) {
      SArray* pColList = extractColumnInfo(pAggNode->pGroupKeys);
dengyihao's avatar
dengyihao 已提交
4101
      pOptr = createGroupOperatorInfo(ops[0], pExprInfo, num, pResBlock, pColList, pAggNode->node.pConditions,
wmmhello's avatar
wmmhello 已提交
4102
                                      pScalarExprInfo, numOfScalarExpr, pTaskInfo);
H
Haojun Liao 已提交
4103
    } else {
L
Liu Jicong 已提交
4104 4105
      pOptr = createAggregateOperatorInfo(ops[0], pExprInfo, num, pResBlock, pAggNode->node.pConditions,
                                          pScalarExprInfo, numOfScalarExpr, pTaskInfo);
H
Haojun Liao 已提交
4106
    }
X
Xiaoyu Wang 已提交
4107
  } else if (QUERY_NODE_PHYSICAL_PLAN_HASH_INTERVAL == type || QUERY_NODE_PHYSICAL_PLAN_STREAM_INTERVAL == type) {
H
Haojun Liao 已提交
4108
    SIntervalPhysiNode* pIntervalPhyNode = (SIntervalPhysiNode*)pPhyNode;
H
Haojun Liao 已提交
4109

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

dengyihao's avatar
dengyihao 已提交
4113 4114 4115 4116 4117 4118
    SInterval interval = {.interval = pIntervalPhyNode->interval,
                          .sliding = pIntervalPhyNode->sliding,
                          .intervalUnit = pIntervalPhyNode->intervalUnit,
                          .slidingUnit = pIntervalPhyNode->slidingUnit,
                          .offset = pIntervalPhyNode->offset,
                          .precision = ((SColumnNode*)pIntervalPhyNode->window.pTspk)->node.resType.precision};
H
Haojun Liao 已提交
4119

X
Xiaoyu Wang 已提交
4120 4121 4122 4123 4124
    STimeWindowAggSupp as = {
        .waterMark = pIntervalPhyNode->window.watermark,
        .calTrigger = pIntervalPhyNode->window.triggerType,
        .maxTs = INT64_MIN,
    };
4125
    ASSERT(as.calTrigger != STREAM_TRIGGER_MAX_DELAY);
4126

4127
    int32_t tsSlotId = ((SColumnNode*)pIntervalPhyNode->window.pTspk)->slotId;
L
Liu Jicong 已提交
4128
    bool    isStream = (QUERY_NODE_PHYSICAL_PLAN_STREAM_INTERVAL == type);
4129 4130
    pOptr = createIntervalOperatorInfo(ops[0], pExprInfo, num, pResBlock, &interval, tsSlotId, &as, pIntervalPhyNode,
                                       pTaskInfo, isStream);
4131

4132 4133
  } else if (QUERY_NODE_PHYSICAL_PLAN_MERGE_ALIGNED_INTERVAL == type) {
    SMergeAlignedIntervalPhysiNode* pIntervalPhyNode = (SMergeAlignedIntervalPhysiNode*)pPhyNode;
S
shenglian zhou 已提交
4134 4135 4136 4137 4138 4139 4140 4141 4142 4143

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

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

S
shenglian zhou 已提交
4145
    int32_t tsSlotId = ((SColumnNode*)pIntervalPhyNode->window.pTspk)->slotId;
L
Liu Jicong 已提交
4146 4147
    pOptr = createMergeAlignedIntervalOperatorInfo(ops[0], pExprInfo, num, pResBlock, &interval, tsSlotId,
                                                   pPhyNode->pConditions, pTaskInfo);
S
shenglian zhou 已提交
4148
  } else if (QUERY_NODE_PHYSICAL_PLAN_MERGE_INTERVAL == type) {
X
Xiaoyu Wang 已提交
4149
    SMergeIntervalPhysiNode* pIntervalPhyNode = (SMergeIntervalPhysiNode*)pPhyNode;
S
shenglian zhou 已提交
4150 4151 4152 4153 4154 4155 4156 4157 4158 4159

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

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

S
shenglian zhou 已提交
4161 4162
    int32_t tsSlotId = ((SColumnNode*)pIntervalPhyNode->window.pTspk)->slotId;
    pOptr = createMergeIntervalOperatorInfo(ops[0], pExprInfo, num, pResBlock, &interval, tsSlotId, pTaskInfo);
5
54liuyao 已提交
4163
  } else if (QUERY_NODE_PHYSICAL_PLAN_STREAM_SEMI_INTERVAL == type) {
4164
    int32_t children = 0;
5
54liuyao 已提交
4165 4166
    pOptr = createStreamFinalIntervalOperatorInfo(ops[0], pPhyNode, pTaskInfo, children);
  } else if (QUERY_NODE_PHYSICAL_PLAN_STREAM_FINAL_INTERVAL == type) {
5
54liuyao 已提交
4167
    int32_t children = pHandle->numOfVgroups;
5
54liuyao 已提交
4168
    pOptr = createStreamFinalIntervalOperatorInfo(ops[0], pPhyNode, pTaskInfo, children);
H
Haojun Liao 已提交
4169
  } else if (QUERY_NODE_PHYSICAL_PLAN_SORT == type) {
4170
    pOptr = createSortOperatorInfo(ops[0], (SSortPhysiNode*)pPhyNode, pTaskInfo);
S
shenglian zhou 已提交
4171 4172
  } else if (QUERY_NODE_PHYSICAL_PLAN_GROUP_SORT == type) {
    pOptr = createGroupSortOperatorInfo(ops[0], (SGroupSortPhysiNode*)pPhyNode, pTaskInfo);
X
Xiaoyu Wang 已提交
4173
  } else if (QUERY_NODE_PHYSICAL_PLAN_MERGE == type) {
4174
    SMergePhysiNode* pMergePhyNode = (SMergePhysiNode*)pPhyNode;
4175
    pOptr = createMultiwayMergeOperatorInfo(ops, size, pMergePhyNode, pTaskInfo);
4176
  } else if (QUERY_NODE_PHYSICAL_PLAN_MERGE_SESSION == type) {
H
Haojun Liao 已提交
4177
    SSessionWinodwPhysiNode* pSessionNode = (SSessionWinodwPhysiNode*)pPhyNode;
H
Haojun Liao 已提交
4178
    pOptr = createSessionAggOperatorInfo(ops[0], pSessionNode, pTaskInfo);
4179
  } else if (QUERY_NODE_PHYSICAL_PLAN_STREAM_SESSION == type) {
4180 4181 4182 4183 4184 4185 4186
    pOptr = createStreamSessionAggOperatorInfo(ops[0], pPhyNode, pTaskInfo);
  } else if (QUERY_NODE_PHYSICAL_PLAN_STREAM_SEMI_SESSION == type) {
    int32_t children = 0;
    pOptr = createStreamFinalSessionAggOperatorInfo(ops[0], pPhyNode, pTaskInfo, children);
  } else if (QUERY_NODE_PHYSICAL_PLAN_STREAM_FINAL_SESSION == type) {
    int32_t children = 1;
    pOptr = createStreamFinalSessionAggOperatorInfo(ops[0], pPhyNode, pTaskInfo, children);
H
Haojun Liao 已提交
4187
  } else if (QUERY_NODE_PHYSICAL_PLAN_PARTITION == type) {
4188
    pOptr = createPartitionOperatorInfo(ops[0], (SPartitionPhysiNode*)pPhyNode, pTaskInfo);
4189
  } else if (QUERY_NODE_PHYSICAL_PLAN_MERGE_STATE == type) {
dengyihao's avatar
dengyihao 已提交
4190
    SStateWinodwPhysiNode* pStateNode = (SStateWinodwPhysiNode*)pPhyNode;
4191

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

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

4198
    SColumnNode* pColNode = (SColumnNode*)((STargetNode*)pStateNode->pStateKey)->pExpr;
X
Xiaoyu Wang 已提交
4199
    SColumn      col = extractColumnFromColumnNode(pColNode);
L
Liu Jicong 已提交
4200 4201
    pOptr = createStatewindowOperatorInfo(ops[0], pExprInfo, num, pResBlock, &as, tsSlotId, &col, pPhyNode->pConditions,
                                          pTaskInfo);
4202
  } else if (QUERY_NODE_PHYSICAL_PLAN_STREAM_STATE == type) {
5
54liuyao 已提交
4203
    pOptr = createStreamStateAggOperatorInfo(ops[0], pPhyNode, pTaskInfo);
4204
  } else if (QUERY_NODE_PHYSICAL_PLAN_MERGE_JOIN == type) {
4205
    pOptr = createMergeJoinOperatorInfo(ops, size, (SSortMergeJoinPhysiNode*)pPhyNode, pTaskInfo);
4206
  } else if (QUERY_NODE_PHYSICAL_PLAN_FILL == type) {
H
Haojun Liao 已提交
4207
    pOptr = createFillOperatorInfo(ops[0], (SFillPhysiNode*)pPhyNode, pTaskInfo);
H
Haojun Liao 已提交
4208 4209
  } else if (QUERY_NODE_PHYSICAL_PLAN_INDEF_ROWS_FUNC == type) {
    pOptr = createIndefinitOutputOperatorInfo(ops[0], pPhyNode, pTaskInfo);
4210 4211
  } else if (QUERY_NODE_PHYSICAL_PLAN_INTERP_FUNC == type) {
    pOptr = createTimeSliceOperatorInfo(ops[0], pPhyNode, pTaskInfo);
H
Haojun Liao 已提交
4212 4213
  } else {
    ASSERT(0);
H
Haojun Liao 已提交
4214
  }
4215
  taosMemoryFree(ops);
4216 4217

  pOptr->resultDataBlockId = pPhyNode->pOutputDataBlockDesc->dataBlockId;
4218
  return pOptr;
4219
}
H
Haojun Liao 已提交
4220

H
Haojun Liao 已提交
4221
SArray* extractColumnInfo(SNodeList* pNodeList) {
L
Liu Jicong 已提交
4222
  size_t  numOfCols = LIST_LENGTH(pNodeList);
H
Haojun Liao 已提交
4223 4224 4225 4226 4227 4228
  SArray* pList = taosArrayInit(numOfCols, sizeof(SColumn));
  if (pList == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

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

4232 4233 4234
    if (nodeType(pNode->pExpr) == QUERY_NODE_COLUMN) {
      SColumnNode* pColNode = (SColumnNode*)pNode->pExpr;

4235
      SColumn c = extractColumnFromColumnNode(pColNode);
4236 4237
      taosArrayPush(pList, &c);
    } else if (nodeType(pNode->pExpr) == QUERY_NODE_VALUE) {
L
Liu Jicong 已提交
4238 4239
      SValueNode* pValNode = (SValueNode*)pNode->pExpr;
      SColumn     c = {0};
4240
      c.slotId = pNode->slotId;
L
Liu Jicong 已提交
4241 4242 4243 4244
      c.colId = pNode->slotId;
      c.type = pValNode->node.type;
      c.bytes = pValNode->node.resType.bytes;
      c.scale = pValNode->node.resType.scale;
4245 4246 4247 4248
      c.precision = pValNode->node.resType.precision;

      taosArrayPush(pList, &c);
    }
H
Haojun Liao 已提交
4249 4250 4251 4252 4253
  }

  return pList;
}

4254
#if 0
L
Liu Jicong 已提交
4255 4256
STsdbReader* doCreateDataReader(STableScanPhysiNode* pTableScanNode, SReadHandle* pHandle,
                                STableListInfo* pTableListInfo, const char* idstr) {
4257
  int32_t code = getTableList(pHandle->meta, pHandle->vnode, &pTableScanNode->scan, pTableListInfo);
wmmhello's avatar
wmmhello 已提交
4258 4259 4260 4261 4262 4263
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }

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

4268
  SQueryTableDataCond cond = {0};
wmmhello's avatar
wmmhello 已提交
4269
  code = initQueryTableDataCond(&cond, pTableScanNode);
4270
  if (code != TSDB_CODE_SUCCESS) {
wmmhello's avatar
wmmhello 已提交
4271
    goto _error;
X
Xiaoyu Wang 已提交
4272
  }
4273

H
Hongze Cheng 已提交
4274
  STsdbReader* pReader;
H
Haojun Liao 已提交
4275
  code = tsdbReaderOpen(pHandle->vnode, &cond, pTableListInfo->pTableList, &pReader, idstr);
H
Haojun Liao 已提交
4276 4277 4278 4279
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }

4280
  cleanupQueryTableDataCond(&cond);
H
Haojun Liao 已提交
4281 4282

  return pReader;
wmmhello's avatar
wmmhello 已提交
4283 4284 4285 4286

_error:
  terrno = code;
  return NULL;
H
Haojun Liao 已提交
4287
}
4288
#endif
H
Haojun Liao 已提交
4289

L
Liu Jicong 已提交
4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302
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 {
4303 4304 4305
    SStreamScanInfo* pInfo = pOperator->info;
    ASSERT(pInfo->pTableScanOp->operatorType == QUERY_NODE_PHYSICAL_PLAN_TABLE_SCAN);
    *ppInfo = pInfo->pTableScanOp->info;
L
Liu Jicong 已提交
4306 4307 4308 4309
    return 0;
  }
}

4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331
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;
}

4332
#if 0
L
Liu Jicong 已提交
4333 4334 4335 4336 4337
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;
  }
4338

L
Liu Jicong 已提交
4339 4340 4341 4342
  STableScanPhysiNode* pNode = NULL;
  if (extractTableScanNode(plan->pNode, &pNode) < 0) {
    ASSERT(0);
  }
4343

H
Haojun Liao 已提交
4344
  tsdbReaderClose(pTableScanInfo->dataReader);
4345

L
Liu Jicong 已提交
4346
  STableListInfo info = {0};
H
Haojun Liao 已提交
4347
  pTableScanInfo->dataReader = doCreateDataReader(pNode, pHandle, &info, NULL);
L
Liu Jicong 已提交
4348 4349 4350 4351
  if (pTableScanInfo->dataReader == NULL) {
    ASSERT(0);
    qError("failed to create data reader");
    return TSDB_CODE_QRY_APP_ERROR;
4352
  }
L
Liu Jicong 已提交
4353
  // TODO: set uid and ts to data reader
4354 4355
  return 0;
}
4356
#endif
4357

C
Cary Xu 已提交
4358
int32_t encodeOperator(SOperatorInfo* ops, char** result, int32_t* length, int32_t* nOptrWithVal) {
wmmhello's avatar
wmmhello 已提交
4359
  int32_t code = TDB_CODE_SUCCESS;
4360
  char*   pCurrent = NULL;
wmmhello's avatar
wmmhello 已提交
4361
  int32_t currLength = 0;
4362
  if (ops->fpSet.encodeResultRow) {
C
Cary Xu 已提交
4363
    if (result == NULL || length == NULL || nOptrWithVal == NULL) {
wmmhello's avatar
wmmhello 已提交
4364 4365 4366
      return TSDB_CODE_TSC_INVALID_INPUT;
    }
    code = ops->fpSet.encodeResultRow(ops, &pCurrent, &currLength);
wmmhello's avatar
wmmhello 已提交
4367

4368 4369
    if (code != TDB_CODE_SUCCESS) {
      if (*result != NULL) {
wmmhello's avatar
wmmhello 已提交
4370 4371 4372 4373
        taosMemoryFree(*result);
        *result = NULL;
      }
      return code;
C
Cary Xu 已提交
4374 4375 4376
    } else if (currLength == 0) {
      ASSERT(!pCurrent);
      goto _downstream;
wmmhello's avatar
wmmhello 已提交
4377
    }
wmmhello's avatar
wmmhello 已提交
4378

C
Cary Xu 已提交
4379 4380
    ++(*nOptrWithVal);

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

4383
    if (*result == NULL) {
wmmhello's avatar
wmmhello 已提交
4384
      *result = (char*)taosMemoryCalloc(1, currLength + sizeof(int32_t));
wmmhello's avatar
wmmhello 已提交
4385 4386 4387 4388 4389 4390
      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);
4391
    } else {
wmmhello's avatar
wmmhello 已提交
4392
      int32_t sizePre = *(int32_t*)(*result);
4393
      char*   tmp = (char*)taosMemoryRealloc(*result, sizePre + currLength);
wmmhello's avatar
wmmhello 已提交
4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405
      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 已提交
4406 4407
  }

C
Cary Xu 已提交
4408
_downstream:
wmmhello's avatar
wmmhello 已提交
4409
  for (int32_t i = 0; i < ops->numOfDownstream; ++i) {
C
Cary Xu 已提交
4410
    code = encodeOperator(ops->pDownstream[i], result, length, nOptrWithVal);
4411
    if (code != TDB_CODE_SUCCESS) {
wmmhello's avatar
wmmhello 已提交
4412
      return code;
wmmhello's avatar
wmmhello 已提交
4413 4414
    }
  }
wmmhello's avatar
wmmhello 已提交
4415
  return TDB_CODE_SUCCESS;
wmmhello's avatar
wmmhello 已提交
4416 4417
}

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

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

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

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

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

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

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

D
dapan1121 已提交
4458
  switch (pNode->type) {
D
dapan1121 已提交
4459 4460 4461 4462 4463 4464
    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 已提交
4465

D
dapan1121 已提交
4466 4467 4468
      *pParam = pInserterParam;
      break;
    }
D
dapan1121 已提交
4469
    case QUERY_NODE_PHYSICAL_PLAN_DELETE: {
4470
      SDeleterParam* pDeleterParam = taosMemoryCalloc(1, sizeof(SDeleterParam));
D
dapan1121 已提交
4471 4472 4473 4474
      if (NULL == pDeleterParam) {
        return TSDB_CODE_OUT_OF_MEMORY;
      }
      int32_t tbNum = taosArrayGetSize(pTask->tableqinfoList.pTableList);
D
dapan1121 已提交
4475
      pDeleterParam->suid = pTask->tableqinfoList.suid;
D
dapan1121 已提交
4476 4477 4478 4479 4480 4481
      pDeleterParam->pUidList = taosArrayInit(tbNum, sizeof(uint64_t));
      if (NULL == pDeleterParam->pUidList) {
        taosMemoryFree(pDeleterParam);
        return TSDB_CODE_OUT_OF_MEMORY;
      }
      for (int32_t i = 0; i < tbNum; ++i) {
4482
        STableKeyInfo* pTable = taosArrayGet(pTask->tableqinfoList.pTableList, i);
D
dapan1121 已提交
4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495
        taosArrayPush(pDeleterParam->pUidList, &pTable->uid);
      }

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

  return TSDB_CODE_SUCCESS;
}

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

H
Haojun Liao 已提交
4500
  int32_t code = TSDB_CODE_SUCCESS;
D
dapan1121 已提交
4501
  *pTaskInfo = createExecTaskInfo(queryId, taskId, model, pPlan->dbFName);
H
Haojun Liao 已提交
4502 4503 4504 4505
  if (*pTaskInfo == NULL) {
    code = TSDB_CODE_QRY_OUT_OF_MEMORY;
    goto _complete;
  }
H
Haojun Liao 已提交
4506

4507
  (*pTaskInfo)->sql = sql;
4508
  (*pTaskInfo)->pSubplan = pPlan;
L
Liu Jicong 已提交
4509 4510
  (*pTaskInfo)->pRoot = createOperatorTree(pPlan->pNode, *pTaskInfo, pHandle, &(*pTaskInfo)->tableqinfoList,
                                           pPlan->pTagCond, pPlan->pTagIndexCond, pPlan->user);
L
Liu Jicong 已提交
4511

D
dapan1121 已提交
4512
  if (NULL == (*pTaskInfo)->pRoot) {
4513
    code = (*pTaskInfo)->code;
D
dapan1121 已提交
4514
    goto _complete;
4515 4516
  }

H
Haojun Liao 已提交
4517 4518
  return code;

H
Haojun Liao 已提交
4519
_complete:
H
Haojun Liao 已提交
4520
  doDestroyTask(*pTaskInfo);
H
Haojun Liao 已提交
4521 4522
  terrno = code;
  return code;
H
Haojun Liao 已提交
4523 4524
}

wmmhello's avatar
wmmhello 已提交
4525 4526 4527
static void doDestroyTableList(STableListInfo* pTableqinfoList) {
  taosArrayDestroy(pTableqinfoList->pTableList);
  taosHashCleanup(pTableqinfoList->map);
4528 4529
  if (pTableqinfoList->needSortTableByGroupId) {
    for (int32_t i = 0; i < taosArrayGetSize(pTableqinfoList->pGroupList); i++) {
wmmhello's avatar
wmmhello 已提交
4530
      SArray* tmp = taosArrayGetP(pTableqinfoList->pGroupList, i);
4531 4532 4533
      if (tmp == pTableqinfoList->pTableList) {
        continue;
      }
wmmhello's avatar
wmmhello 已提交
4534 4535 4536 4537
      taosArrayDestroy(tmp);
    }
  }
  taosArrayDestroy(pTableqinfoList->pGroupList);
4538

wmmhello's avatar
wmmhello 已提交
4539 4540
  pTableqinfoList->pTableList = NULL;
  pTableqinfoList->map = NULL;
4541 4542
}

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

wmmhello's avatar
wmmhello 已提交
4546
  doDestroyTableList(&pTaskInfo->tableqinfoList);
H
Haojun Liao 已提交
4547
  destroyOperatorInfo(pTaskInfo->pRoot);
4548 4549 4550
  cleanupTableSchemaInfo(&pTaskInfo->schemaInfo);

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

wafwerar's avatar
wafwerar 已提交
4552 4553 4554
  taosMemoryFreeClear(pTaskInfo->sql);
  taosMemoryFreeClear(pTaskInfo->id.str);
  taosMemoryFreeClear(pTaskInfo);
4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566
}

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

  if (IS_VAR_DATA_TYPE(type)) {
    // Binary data overflows for sort of unknown reasons. Let trim the overflow data
    if (varDataTLen(val) > bytes) {
      int32_t maxLen = bytes - VARSTR_HEADER_SIZE;
L
Liu Jicong 已提交
4567
      int32_t len = (varDataLen(val) > maxLen) ? maxLen : varDataLen(val);
4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579
      memcpy(varDataVal(output), varDataVal(val), len);
      varDataSetLen(output, len);
    } else {
      varDataCopy(output, val);
    }
  } else {
    memcpy(output, val, bytes);
  }
}

static int64_t getQuerySupportBufSize(size_t numOfTables) {
  size_t s1 = sizeof(STableQueryInfo);
L
Liu Jicong 已提交
4580 4581
  //  size_t s3 = sizeof(STableCheckInfo);  buffer consumption in tsdb
  return (int64_t)(s1 * 1.5 * numOfTables);
4582 4583 4584 4585 4586 4587 4588
}

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 已提交
4589
    while (1) {
4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615
      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 已提交
4616

H
Haojun Liao 已提交
4617
int32_t getOperatorExplainExecInfo(SOperatorInfo* operatorInfo, SArray* pExecInfoList) {
4618
  SExplainExecInfo  execInfo = {0};
H
Haojun Liao 已提交
4619
  SExplainExecInfo* pExplainInfo = taosArrayPush(pExecInfoList, &execInfo);
4620

H
Haojun Liao 已提交
4621 4622 4623 4624 4625
  pExplainInfo->numOfRows = operatorInfo->resultInfo.totalRows;
  pExplainInfo->startupCost = operatorInfo->cost.openCost;
  pExplainInfo->totalCost = operatorInfo->cost.totalCost;
  pExplainInfo->verboseLen = 0;
  pExplainInfo->verboseInfo = NULL;
D
dapan1121 已提交
4626

4627
  if (operatorInfo->fpSet.getExplainFn) {
4628 4629
    int32_t code =
        operatorInfo->fpSet.getExplainFn(operatorInfo, &pExplainInfo->verboseInfo, &pExplainInfo->verboseLen);
D
dapan1121 已提交
4630
    if (code) {
4631
      qError("%s operator getExplainFn failed, code:%s", GET_TASKID(operatorInfo->pTaskInfo), tstrerror(code));
D
dapan1121 已提交
4632 4633 4634
      return code;
    }
  }
dengyihao's avatar
dengyihao 已提交
4635

D
dapan1121 已提交
4636
  int32_t code = 0;
D
dapan1121 已提交
4637
  for (int32_t i = 0; i < operatorInfo->numOfDownstream; ++i) {
H
Haojun Liao 已提交
4638 4639
    code = getOperatorExplainExecInfo(operatorInfo->pDownstream[i], pExecInfoList);
    if (code != TSDB_CODE_SUCCESS) {
4640
      //      taosMemoryFreeClear(*pRes);
D
dapan1121 已提交
4641 4642 4643 4644 4645
      return TSDB_CODE_QRY_OUT_OF_MEMORY;
    }
  }

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

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

4660
  pSup->pScanBlock = createSpecialDataBlock(STREAM_CLEAR);
5
54liuyao 已提交
4661 4662 4663 4664 4665 4666 4667 4668 4669
  int32_t pageSize = 4096;
  while (pageSize < pSup->resultRowSize * 4) {
    pageSize <<= 1u;
  }
  // at least four pages need to be in buffer
  int32_t bufSize = 4096 * 256;
  if (bufSize <= pageSize) {
    bufSize = pageSize * 4;
  }
wafwerar's avatar
wafwerar 已提交
4670 4671 4672 4673 4674 4675
  if (!osTempSpaceAvailable()) {
    terrno = TSDB_CODE_NO_AVAIL_DISK;
    qError("Init stream agg supporter failed since %s", terrstr(terrno));
    return terrno;
  }
  int32_t code = createDiskbasedBuf(&pSup->pResultBuf, pageSize, bufSize, pKey, tsTempDir);
L
Liu Jicong 已提交
4676
  for (int32_t i = 0; i < numOfOutput; ++i) {
4677 4678 4679
    pCtx[i].pBuf = pSup->pResultBuf;
  }
  return code;
5
54liuyao 已提交
4680
}