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

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

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

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

H
Haojun Liao 已提交
39
#define IS_MAIN_SCAN(runtime)          ((runtime)->scanFlag == MAIN_SCAN)
40 41
#define IS_REVERSE_SCAN(runtime)       ((runtime)->scanFlag == REVERSE_SCAN)
#define IS_REPEAT_SCAN(runtime)        ((runtime)->scanFlag == REPEAT_SCAN)
L
Liu Jicong 已提交
42
#define SET_MAIN_SCAN_FLAG(runtime)    ((runtime)->scanFlag = MAIN_SCAN)
43 44
#define SET_REVERSE_SCAN_FLAG(runtime) ((runtime)->scanFlag = REVERSE_SCAN)

L
Liu Jicong 已提交
45 46
#define SDATA_BLOCK_INITIALIZER \
  (SDataBlockInfo) { {0}, 0 }
47 48 49 50

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

enum {
L
Liu Jicong 已提交
51 52
  TS_JOIN_TS_EQUAL = 0,
  TS_JOIN_TS_NOT_EQUALS = 1,
53 54 55 56 57
  TS_JOIN_TAG_NOT_EQUALS = 2,
};

#if 0
static UNUSED_FUNC void *u_malloc (size_t __size) {
wafwerar's avatar
wafwerar 已提交
58
  uint32_t v = taosRand();
59 60 61 62

  if (v % 1000 <= 0) {
    return NULL;
  } else {
wafwerar's avatar
wafwerar 已提交
63
    return taosMemoryMalloc(__size);
64 65 66 67
  }
}

static UNUSED_FUNC void* u_calloc(size_t num, size_t __size) {
wafwerar's avatar
wafwerar 已提交
68
  uint32_t v = taosRand();
69 70 71
  if (v % 1000 <= 0) {
    return NULL;
  } else {
wafwerar's avatar
wafwerar 已提交
72
    return taosMemoryCalloc(num, __size);
73 74 75 76
  }
}

static UNUSED_FUNC void* u_realloc(void* p, size_t __size) {
wafwerar's avatar
wafwerar 已提交
77
  uint32_t v = taosRand();
78 79 80
  if (v % 5 <= 1) {
    return NULL;
  } else {
wafwerar's avatar
wafwerar 已提交
81
    return taosMemoryRealloc(p, __size);
82 83 84 85 86 87 88 89
  }
}

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

dengyihao's avatar
dengyihao 已提交
90
#define CLEAR_QUERY_STATUS(q, st) ((q)->status &= (~(st)))
wmmhello's avatar
wmmhello 已提交
91
//#define GET_NUM_OF_TABLEGROUP(q)    taosArrayGetSize((q)->tableqinfoGroupInfo.pGroupList)
92 93
#define QUERY_IS_INTERVAL_QUERY(_q) ((_q)->interval.interval > 0)

L
Liu Jicong 已提交
94 95 96
int32_t getMaximumIdleDurationSec() { return tsShellActivityTimer * 2; }

static int32_t getExprFunctionId(SExprInfo* pExprInfo) {
97
  assert(pExprInfo != NULL && pExprInfo->pExpr != NULL && pExprInfo->pExpr->nodeType == TEXPR_UNARYEXPR_NODE);
98
  return 0;
99 100 101 102
}

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

103
static void setBlockStatisInfo(SqlFunctionCtx* pCtx, SExprInfo* pExpr, SSDataBlock* pSDataBlock);
104

L
Liu Jicong 已提交
105
static void destroyTableQueryInfoImpl(STableQueryInfo* pTableQueryInfo);
106 107 108

static SColumnInfo* extractColumnFilterInfo(SExprInfo* pExpr, int32_t numOfOutput, int32_t* numOfFilterCols);

X
Xiaoyu Wang 已提交
109
static void releaseQueryBuf(size_t numOfTables);
110 111 112 113 114 115

static void destroySFillOperatorInfo(void* param, int32_t numOfOutput);
static void destroyProjectOperatorInfo(void* param, int32_t numOfOutput);
static void destroyTagScanOperatorInfo(void* param, int32_t numOfOutput);
static void destroyOrderOperatorInfo(void* param, int32_t numOfOutput);
static void destroyAggOperatorInfo(void* param, int32_t numOfOutput);
X
Xiaoyu Wang 已提交
116

H
Haojun Liao 已提交
117
static void destroyIntervalOperatorInfo(void* param, int32_t numOfOutput);
H
Haojun Liao 已提交
118 119
static void destroyExchangeOperatorInfo(void* param, int32_t numOfOutput);

120
static void destroyOperatorInfo(SOperatorInfo* pOperator);
121
static void destroySysTableScannerOperatorInfo(void* param, int32_t numOfOutput);
122

123
void doSetOperatorCompleted(SOperatorInfo* pOperator) {
124
  pOperator->status = OP_EXEC_DONE;
125

126
  pOperator->cost.totalCost = (taosGetTimestampUs() - pOperator->pTaskInfo->cost.start * 1000) / 1000.0;
H
Haojun Liao 已提交
127
  if (pOperator->pTaskInfo != NULL) {
128
    setTaskStatus(pOperator->pTaskInfo, TASK_COMPLETED);
129 130
  }
}
131

H
Haojun Liao 已提交
132
int32_t operatorDummyOpenFn(SOperatorInfo* pOperator) {
133
  OPTR_SET_OPENED(pOperator);
134
  pOperator->cost.openCost = 0;
H
Haojun Liao 已提交
135
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
136 137
}

138
SOperatorFpSet createOperatorFpSet(__optr_open_fn_t openFn, __optr_fn_t nextFn, __optr_fn_t streamFn,
L
Liu Jicong 已提交
139
                                   __optr_fn_t cleanup, __optr_close_fn_t closeFn, __optr_encode_fn_t encode,
140
                                   __optr_decode_fn_t decode, __optr_explain_fn_t explain) {
141 142 143 144 145 146 147 148 149 150 151 152 153 154
  SOperatorFpSet fpSet = {
      ._openFn = openFn,
      .getNextFn = nextFn,
      .getStreamResFn = streamFn,
      .cleanupFn = cleanup,
      .closeFn = closeFn,
      .encodeResultRow = encode,
      .decodeResultRow = decode,
      .getExplainFn = explain,
  };

  return fpSet;
}

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

X
Xiaoyu Wang 已提交
157 158 159
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 已提交
160

161
static void initCtxOutputBuffer(SqlFunctionCtx* pCtx, int32_t size);
H
Haojun Liao 已提交
162
static void setResultBufSize(STaskAttr* pQueryAttr, SResultInfo* pResultInfo);
dengyihao's avatar
dengyihao 已提交
163 164
static void doSetTableGroupOutputBuf(SAggOperatorInfo* pAggInfo, int32_t numOfOutput, uint64_t groupId,
                                     SExecTaskInfo* pTaskInfo);
165

H
Haojun Liao 已提交
166
SArray* getOrderCheckColumns(STaskAttr* pQuery);
167 168

typedef struct SRowCompSupporter {
L
Liu Jicong 已提交
169 170 171
  STaskRuntimeEnv* pRuntimeEnv;
  int16_t          dataOffset;
  __compar_fn_t    comFunc;
172 173
} SRowCompSupporter;

L
Liu Jicong 已提交
174 175 176
static int compareRowData(const void* a, const void* b, const void* userData) {
  const SResultRow* pRow1 = (const SResultRow*)a;
  const SResultRow* pRow2 = (const SResultRow*)b;
177

L
Liu Jicong 已提交
178 179
  SRowCompSupporter* supporter = (SRowCompSupporter*)userData;
  STaskRuntimeEnv*   pRuntimeEnv = supporter->pRuntimeEnv;
180

L
Liu Jicong 已提交
181 182
  SFilePage* page1 = getBufPage(pRuntimeEnv->pResultBuf, pRow1->pageId);
  SFilePage* page2 = getBufPage(pRuntimeEnv->pResultBuf, pRow2->pageId);
183 184

  int16_t offset = supporter->dataOffset;
185
  return 0;
X
Xiaoyu Wang 已提交
186 187
  //  char*   in1 = getPosInResultPage(pRuntimeEnv->pQueryAttr, page1, pRow1->offset, offset);
  //  char*   in2 = getPosInResultPage(pRuntimeEnv->pQueryAttr, page2, pRow2->offset, offset);
188

X
Xiaoyu Wang 已提交
189
  //  return (in1 != NULL && in2 != NULL) ? supporter->comFunc(in1, in2) : 0;
190 191
}

L
Liu Jicong 已提交
192
// setup the output buffer for each operator
193
SSDataBlock* createResDataBlock(SDataBlockDescNode* pNode) {
H
Haojun Liao 已提交
194
  int32_t numOfCols = LIST_LENGTH(pNode->pSlots);
H
Haojun Liao 已提交
195

wafwerar's avatar
wafwerar 已提交
196
  SSDataBlock* pBlock = taosMemoryCalloc(1, sizeof(SSDataBlock));
H
Haojun Liao 已提交
197 198
  pBlock->pDataBlock = taosArrayInit(numOfCols, sizeof(SColumnInfoData));

H
Haojun Liao 已提交
199
  pBlock->info.blockId = pNode->dataBlockId;
dengyihao's avatar
dengyihao 已提交
200
  pBlock->info.rowSize = pNode->totalRowSize;  // todo ??
5
54liuyao 已提交
201
  pBlock->info.type = STREAM_INVALID;
H
Haojun Liao 已提交
202

L
Liu Jicong 已提交
203
  for (int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
204
    SColumnInfoData idata = {{0}};
L
Liu Jicong 已提交
205
    SSlotDescNode*  pDescNode = nodesListGetNode(pNode->pSlots, i);
X
Xiaoyu Wang 已提交
206 207 208
    //    if (!pDescNode->output) {  // todo disable it temporarily
    //      continue;
    //    }
H
Haojun Liao 已提交
209

dengyihao's avatar
dengyihao 已提交
210
    idata.info.type = pDescNode->dataType.type;
L
Liu Jicong 已提交
211 212
    idata.info.bytes = pDescNode->dataType.bytes;
    idata.info.scale = pDescNode->dataType.scale;
H
Haojun Liao 已提交
213
    idata.info.slotId = pDescNode->slotId;
H
Haojun Liao 已提交
214 215
    idata.info.precision = pDescNode->dataType.precision;

H
Hongze Cheng 已提交
216 217 218 219
    if (IS_VAR_DATA_TYPE(idata.info.type)) {
      pBlock->info.hasVarCol = true;
    }

H
Haojun Liao 已提交
220
    taosArrayPush(pBlock->pDataBlock, &idata);
H
Haojun Liao 已提交
221
  }
H
Haojun Liao 已提交
222

223
  pBlock->info.numOfCols = taosArrayGetSize(pBlock->pDataBlock);
H
Haojun Liao 已提交
224
  return pBlock;
H
Haojun Liao 已提交
225 226
}

L
Liu Jicong 已提交
227
static bool hasNull(SColumn* pColumn, SColumnDataAgg* pStatis) {
dengyihao's avatar
dengyihao 已提交
228 229
  if (TSDB_COL_IS_TAG(pColumn->flag) || TSDB_COL_IS_UD_COL(pColumn->flag) ||
      pColumn->colId == PRIMARYKEY_TIMESTAMP_COL_ID) {
230 231 232 233 234 235 236 237 238 239
    return false;
  }

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

  return true;
}

L
Liu Jicong 已提交
240 241
static bool chkResultRowFromKey(STaskRuntimeEnv* pRuntimeEnv, SResultRowInfo* pResultRowInfo, char* pData,
                                int16_t bytes, bool masterscan, uint64_t uid) {
242 243 244
  bool existed = false;
  SET_RES_WINDOW_KEY(pRuntimeEnv->keyBuf, pData, bytes, uid);

L
Liu Jicong 已提交
245 246
  SResultRow** p1 =
      (SResultRow**)taosHashGet(pRuntimeEnv->pResultRowHashTable, pRuntimeEnv->keyBuf, GET_RES_WINDOW_KEY_LEN(bytes));
247 248 249 250 251 252 253 254 255 256 257

  // 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 已提交
258
        //        existed = (pResultRowInfo->pResult[0] == (*p1));
259 260
      } else {  // check if current pResultRowInfo contains the existed pResultRow
        SET_RES_EXT_WINDOW_KEY(pRuntimeEnv->keyBuf, pData, bytes, uid, pResultRowInfo);
L
Liu Jicong 已提交
261 262
        int64_t* index =
            taosHashGet(pRuntimeEnv->pResultRowListSet, pRuntimeEnv->keyBuf, GET_RES_EXT_WINDOW_KEY_LEN(bytes));
263 264 265 266 267 268 269 270 271 272 273 274 275 276
        if (index != NULL) {
          existed = true;
        } else {
          existed = false;
        }
      }
    }

    return existed;
  }

  return p1 != NULL;
}

277
SResultRow* getNewResultRow(SDiskbasedBuf* pResultBuf, int64_t tableGroupId, int32_t interBufSize) {
L
Liu Jicong 已提交
278
  SFilePage* pData = NULL;
279 280 281 282 283 284 285 286 287 288 289 290 291

  // 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 已提交
292
    if (pData->num + interBufSize > getBufPageSize(pResultBuf)) {
293 294 295 296 297 298 299 300 301 302 303 304 305 306
      // 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;
  }

307 308
  setBufPageDirty(pData, true);

309 310 311 312 313
  // 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 已提交
314
  pData->num += interBufSize;
315 316 317 318

  return pResultRow;
}

319 320 321 322 323 324 325
/**
 * the struct of key in hash table
 * +----------+---------------+
 * | group id |   key data    |
 * | 8 bytes  | actual length |
 * +----------+---------------+
 */
326 327 328
SResultRow* doSetResultOutBufByKey(SDiskbasedBuf* pResultBuf, SResultRowInfo* pResultRowInfo, char* pData,
                                   int16_t bytes, bool masterscan, uint64_t groupId, SExecTaskInfo* pTaskInfo,
                                   bool isIntervalQuery, SAggSupporter* pSup) {
329
  SET_RES_WINDOW_KEY(pSup->keyBuf, pData, bytes, groupId);
H
Haojun Liao 已提交
330

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

334 335
  SResultRow* pResult = NULL;

H
Haojun Liao 已提交
336 337
  // in case of repeat scan/reverse scan, no new time window added.
  if (isIntervalQuery) {
338 339
    if (masterscan && p1 != NULL) {  // the *p1 may be NULL in case of sliding+offset exists.
      pResult = getResultRowByPos(pResultBuf, p1);
340
      ASSERT(pResult->pageId == p1->pageId && pResult->offset == p1->offset);
H
Haojun Liao 已提交
341 342
    }
  } else {
dengyihao's avatar
dengyihao 已提交
343 344
    // In case of group by column query, the required SResultRow object must be existInCurrentResusltRowInfo in the
    // pResultRowInfo object.
H
Haojun Liao 已提交
345
    if (p1 != NULL) {
346
      // todo
347
      pResult = getResultRowByPos(pResultBuf, p1);
348
      ASSERT(pResult->pageId == p1->pageId && pResult->offset == p1->offset);
H
Haojun Liao 已提交
349 350 351
    }
  }

L
Liu Jicong 已提交
352
  // 1. close current opened time window
353
  if (pResultRowInfo->cur.pageId != -1 && ((pResult == NULL) || (pResult->pageId != pResultRowInfo->cur.pageId &&
L
Liu Jicong 已提交
354
                                                                 pResult->offset != pResultRowInfo->cur.offset))) {
355
    SResultRowPosition pos = pResultRowInfo->cur;
X
Xiaoyu Wang 已提交
356
    SFilePage*         pPage = getBufPage(pResultBuf, pos.pageId);
357 358 359 360 361
    releaseBufPage(pResultBuf, pPage);
  }

  // allocate a new buffer page
  if (pResult == NULL) {
H
Haojun Liao 已提交
362
    ASSERT(pSup->resultRowSize > 0);
363 364
    pResult = getNewResultRow(pResultBuf, groupId, pSup->resultRowSize);

365
    initResultRow(pResult);
H
Haojun Liao 已提交
366

367 368
    // add a new result set for a new group
    SResultRowPosition pos = {.pageId = pResult->pageId, .offset = pResult->offset};
X
Xiaoyu Wang 已提交
369 370
    taosHashPut(pSup->pResultRowHashTable, pSup->keyBuf, GET_RES_WINDOW_KEY_LEN(bytes), &pos,
                sizeof(SResultRowPosition));
H
Haojun Liao 已提交
371 372
  }

373 374 375
  // 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 已提交
376
  // too many time window in query
377
  if (taosHashGetSize(pSup->pResultRowHashTable) > MAX_INTERVAL_TIME_WINDOW) {
H
Haojun Liao 已提交
378 379 380
    longjmp(pTaskInfo->env, TSDB_CODE_QRY_TOO_MANY_TIMEWINDOW);
  }

H
Haojun Liao 已提交
381
  return pResult;
H
Haojun Liao 已提交
382 383
}

384
// get the correct time window according to the handled timestamp
L
Liu Jicong 已提交
385
static STimeWindow getCurrentActiveTimeWindow(SResultRowInfo* pResultRowInfo, int64_t ts, STaskAttr* pQueryAttr) {
386
  STimeWindow w = {0};
H
Haojun Liao 已提交
387
#if 0
L
Liu Jicong 已提交
388 389
  if (pResultRowInfo->curPos == -1) {  // the first window, from the previous stored value
                                       //    getInitialStartTimeWindow(pQueryAttr, ts, &w);
390 391

    if (pQueryAttr->interval.intervalUnit == 'n' || pQueryAttr->interval.intervalUnit == 'y') {
L
Liu Jicong 已提交
392 393 394
      w.ekey =
          taosTimeAdd(w.skey, pQueryAttr->interval.interval, pQueryAttr->interval.intervalUnit, pQueryAttr->precision) -
          1;
395 396 397 398
    } else {
      w.ekey = w.skey + pQueryAttr->interval.interval - 1;
    }
  } else {
H
Haojun Liao 已提交
399
    w = pRow->win;
400 401 402 403 404 405 406 407 408
  }

  /*
   * query border check, skey should not be bounded by the query time range, since the value skey will
   * be used as the time window index value. So we only change ekey of time window accordingly.
   */
  if (w.ekey > pQueryAttr->window.ekey && QUERY_IS_ASC_QUERY(pQueryAttr)) {
    w.ekey = pQueryAttr->window.ekey;
  }
H
Haojun Liao 已提交
409
#endif
410 411 412 413 414

  return w;
}

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

L
Liu Jicong 已提交
420
  SFilePage* pData = NULL;
421 422 423 424 425 426

  // 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 已提交
427
    pData = getNewBufPage(pResultBuf, tid, &pageId);
428
    pData->num = sizeof(SFilePage);
429 430
  } else {
    SPageInfo* pi = getLastPageInfo(list);
431
    pData = getBufPage(pResultBuf, getPageId(pi));
432
    pageId = getPageId(pi);
433

434
    if (pData->num + size > getBufPageSize(pResultBuf)) {
435
      // release current page first, and prepare the next one
436
      releaseBufPageInfo(pResultBuf, pi);
437

H
Haojun Liao 已提交
438
      pData = getNewBufPage(pResultBuf, tid, &pageId);
439
      if (pData != NULL) {
440
        pData->num = sizeof(SFilePage);
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
      }
    }
  }

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

L
Liu Jicong 已提交
461 462 463
static bool chkWindowOutputBufByKey(STaskRuntimeEnv* pRuntimeEnv, SResultRowInfo* pResultRowInfo, STimeWindow* win,
                                    bool masterscan, SResultRow** pResult, int64_t groupId, SqlFunctionCtx* pCtx,
                                    int32_t numOfOutput, int32_t* rowCellInfoOffset) {
464
  assert(win->skey <= win->ekey);
L
Liu Jicong 已提交
465
  return chkResultRowFromKey(pRuntimeEnv, pResultRowInfo, (char*)&win->skey, TSDB_KEYSIZE, masterscan, groupId);
466 467
}

dengyihao's avatar
dengyihao 已提交
468 469
static void doUpdateResultRowIndex(SResultRowInfo* pResultRowInfo, TSKEY lastKey, bool ascQuery,
                                   bool timeWindowInterpo) {
470
  int64_t skey = TSKEY_INITIAL_VAL;
H
Haojun Liao 已提交
471
#if 0
472 473
  int32_t i = 0;
  for (i = pResultRowInfo->size - 1; i >= 0; --i) {
L
Liu Jicong 已提交
474
    SResultRow* pResult = pResultRowInfo->pResult[i];
475 476 477 478 479 480
    if (pResult->closed) {
      break;
    }

    // new closed result rows
    if (timeWindowInterpo) {
L
Liu Jicong 已提交
481 482 483
      if (pResult->endInterp &&
          ((pResult->win.skey <= lastKey && ascQuery) || (pResult->win.skey >= lastKey && !ascQuery))) {
        if (i > 0) {  // the first time window, the startInterp is false.
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
          assert(pResult->startInterp);
        }

        closeResultRow(pResultRowInfo, i);
      } else {
        skey = pResult->win.skey;
      }
    } else {
      if ((pResult->win.ekey <= lastKey && ascQuery) || (pResult->win.skey >= lastKey && !ascQuery)) {
        closeResultRow(pResultRowInfo, i);
      } else {
        skey = pResult->win.skey;
      }
    }
  }

  // all result rows are closed, set the last one to be the skey
  if (skey == TSKEY_INITIAL_VAL) {
    if (pResultRowInfo->size == 0) {
L
Liu Jicong 已提交
503
      //      assert(pResultRowInfo->current == NULL);
504 505 506 507 508 509 510
      assert(pResultRowInfo->curPos == -1);
      pResultRowInfo->curPos = -1;
    } else {
      pResultRowInfo->curPos = pResultRowInfo->size - 1;
    }
  } else {
    for (i = pResultRowInfo->size - 1; i >= 0; --i) {
L
Liu Jicong 已提交
511
      SResultRow* pResult = pResultRowInfo->pResult[i];
512 513 514 515 516 517 518 519 520 521 522
      if (pResult->closed) {
        break;
      }
    }

    if (i == pResultRowInfo->size - 1) {
      pResultRowInfo->curPos = i;
    } else {
      pResultRowInfo->curPos = i + 1;  // current not closed result object
    }
  }
H
Haojun Liao 已提交
523
#endif
524
}
525
//
dengyihao's avatar
dengyihao 已提交
526
// static void updateResultRowInfoActiveIndex(SResultRowInfo* pResultRowInfo, const STimeWindow* pWin, TSKEY lastKey,
527 528 529 530 531 532 533 534 535
//                                           bool ascQuery, bool interp) {
//  if ((lastKey > pWin->ekey && ascQuery) || (lastKey < pWin->ekey && (!ascQuery))) {
//    closeAllResultRows(pResultRowInfo);
//    pResultRowInfo->curPos = pResultRowInfo->size - 1;
//  } else {
//    int32_t step = ascQuery ? 1 : -1;
//    doUpdateResultRowIndex(pResultRowInfo, lastKey - step, ascQuery, interp);
//  }
//}
536

537
//  query_range_start, query_range_end, window_duration, window_start, window_end
538
void initExecTimeWindowInfo(SColumnInfoData* pColData, STimeWindow* pQueryWindow) {
539 540 541
  pColData->info.type = TSDB_DATA_TYPE_TIMESTAMP;
  pColData->info.bytes = sizeof(int64_t);

542
  colInfoDataEnsureCapacity(pColData, 0, 5);
543 544 545 546 547 548 549 550 551
  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);
}

X
Xiaoyu Wang 已提交
552 553 554
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) {
555
  for (int32_t k = 0; k < numOfOutput; ++k) {
H
Haojun Liao 已提交
556
    // keep it temporarily
557
    // todo no need this??
dengyihao's avatar
dengyihao 已提交
558 559
    bool    hasAgg = pCtx[k].input.colDataAggIsSet;
    int32_t numOfRows = pCtx[k].input.numOfRows;
H
Haojun Liao 已提交
560
    int32_t startOffset = pCtx[k].input.startRowIndex;
561

562
    pCtx[k].input.startRowIndex = offset;
563
    pCtx[k].input.numOfRows = forwardStep;
564 565

    if (tsCol != NULL) {
H
Haojun Liao 已提交
566
      pCtx[k].ptsList = tsCol;
567 568 569 570
    }

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

575 576
    if (fmIsWindowPseudoColumnFunc(pCtx[k].functionId)) {
      SResultRowEntryInfo* pEntryInfo = GET_RES_INFO(&pCtx[k]);
577 578

      char* p = GET_ROWCELL_INTERBUF(pEntryInfo);
579

580
      SColumnInfoData idata = {0};
dengyihao's avatar
dengyihao 已提交
581
      idata.info.type = TSDB_DATA_TYPE_BIGINT;
582
      idata.info.bytes = tDataTypes[TSDB_DATA_TYPE_BIGINT].bytes;
dengyihao's avatar
dengyihao 已提交
583
      idata.pData = p;
584 585 586 587

      SScalarParam out = {.columnData = &idata};
      SScalarParam tw = {.numOfRows = 5, .columnData = pTimeWindowData};
      pCtx[k].sfp.process(&tw, 1, &out);
588
      pEntryInfo->numOfRes = 1;
589 590 591 592 593 594 595 596 597 598
    } 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);
        }
599
      }
600

601 602 603 604 605
      // restore it
      pCtx[k].input.colDataAggIsSet = hasAgg;
      pCtx[k].input.startRowIndex = startOffset;
      pCtx[k].input.numOfRows = numOfRows;
    }
606 607 608
  }
}

L
Liu Jicong 已提交
609
static FORCE_INLINE TSKEY reviseWindowEkey(STaskAttr* pQueryAttr, STimeWindow* pWindow) {
dengyihao's avatar
dengyihao 已提交
610
  TSKEY   ekey = -1;
611 612
  int32_t order = TSDB_ORDER_ASC;
  if (order == TSDB_ORDER_ASC) {
613 614 615 616 617 618 619 620 621 622 623 624 625 626
    ekey = pWindow->ekey;
    if (ekey > pQueryAttr->window.ekey) {
      ekey = pQueryAttr->window.ekey;
    }
  } else {
    ekey = pWindow->skey;
    if (ekey < pQueryAttr->window.ekey) {
      ekey = pQueryAttr->window.ekey;
    }
  }

  return ekey;
}

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

dengyihao's avatar
dengyihao 已提交
630 631
static void doSetInputDataBlockInfo(SOperatorInfo* pOperator, SqlFunctionCtx* pCtx, SSDataBlock* pBlock,
                                    int32_t order) {
632
  for (int32_t i = 0; i < pOperator->numOfExprs; ++i) {
633
    pCtx[i].order = order;
634
    pCtx[i].input.numOfRows = pBlock->info.rows;
635
    setBlockStatisInfo(&pCtx[i], &pOperator->pExpr[i], pBlock);
636 637 638
  }
}

X
Xiaoyu Wang 已提交
639 640
void setInputDataBlock(SOperatorInfo* pOperator, SqlFunctionCtx* pCtx, SSDataBlock* pBlock, int32_t order,
                       int32_t scanFlag, bool createDummyCol) {
641
  if (pBlock->pBlockAgg != NULL) {
H
Haojun Liao 已提交
642
    doSetInputDataBlockInfo(pOperator, pCtx, pBlock, order);
643
  } else {
644
    doSetInputDataBlock(pOperator, pCtx, pBlock, order, scanFlag, createDummyCol);
H
Haojun Liao 已提交
645
  }
646 647
}

L
Liu Jicong 已提交
648 649
static int32_t doCreateConstantValColumnInfo(SInputColumnInfoData* pInput, SFunctParam* pFuncParam, int32_t paramIndex,
                                             int32_t numOfRows) {
650 651 652 653 654 655 656 657
  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)
658 659
    pColInfo->info.type = pFuncParam->param.nType;
    pColInfo->info.bytes = pFuncParam->param.nLen;
660 661

    pInput->pData[paramIndex] = pColInfo;
662 663
  } else {
    pColInfo = pInput->pData[paramIndex];
664 665
  }

666
  colInfoDataEnsureCapacity(pColInfo, 0, numOfRows);
667

668
  int8_t type = pFuncParam->param.nType;
669 670
  if (type == TSDB_DATA_TYPE_BIGINT || type == TSDB_DATA_TYPE_UBIGINT) {
    int64_t v = pFuncParam->param.i;
dengyihao's avatar
dengyihao 已提交
671
    for (int32_t i = 0; i < numOfRows; ++i) {
672 673 674 675
      colDataAppendInt64(pColInfo, i, &v);
    }
  } else if (type == TSDB_DATA_TYPE_DOUBLE) {
    double v = pFuncParam->param.d;
dengyihao's avatar
dengyihao 已提交
676
    for (int32_t i = 0; i < numOfRows; ++i) {
677 678
      colDataAppendDouble(pColInfo, i, &v);
    }
679
  } else if (type == TSDB_DATA_TYPE_VARCHAR) {
L
Liu Jicong 已提交
680
    char* tmp = taosMemoryMalloc(pFuncParam->param.nLen + VARSTR_HEADER_SIZE);
681
    STR_WITH_SIZE_TO_VARSTR(tmp, pFuncParam->param.pz, pFuncParam->param.nLen);
L
Liu Jicong 已提交
682
    for (int32_t i = 0; i < numOfRows; ++i) {
683 684
      colDataAppend(pColInfo, i, tmp, false);
    }
685 686 687 688 689
  }

  return TSDB_CODE_SUCCESS;
}

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

694
  for (int32_t i = 0; i < pOperator->numOfExprs; ++i) {
L
Liu Jicong 已提交
695
    pCtx[i].order = order;
696 697
    pCtx[i].input.numOfRows = pBlock->info.rows;

L
Liu Jicong 已提交
698
    pCtx[i].pSrcBlock = pBlock;
X
Xiaoyu Wang 已提交
699
    pCtx[i].scanFlag = scanFlag;
H
Haojun Liao 已提交
700

701
    SInputColumnInfoData* pInput = &pCtx[i].input;
702
    pInput->uid = pBlock->info.uid;
C
Cary Xu 已提交
703
    pInput->colDataAggIsSet = false;
704

705 706
    SExprInfo* pOneExpr = &pOperator->pExpr[i];
    for (int32_t j = 0; j < pOneExpr->base.numOfParams; ++j) {
dengyihao's avatar
dengyihao 已提交
707
      SFunctParam* pFuncParam = &pOneExpr->base.pParam[j];
G
Ganlin Zhao 已提交
708 709
      if (pFuncParam->type == FUNC_PARAM_TYPE_COLUMN) {
        int32_t slotId = pFuncParam->pCol->slotId;
dengyihao's avatar
dengyihao 已提交
710
        pInput->pData[j] = taosArrayGet(pBlock->pDataBlock, slotId);
711 712 713
        pInput->totalRows = pBlock->info.rows;
        pInput->numOfRows = pBlock->info.rows;
        pInput->startRowIndex = 0;
714

715
        // NOTE: the last parameter is the primary timestamp column
716 717 718
        if (fmIsTimelineFunc(pCtx[i].functionId) && (j == pOneExpr->base.numOfParams - 1)) {
          pInput->pPTS = pInput->pData[j];
        }
719 720
        ASSERT(pInput->pData[j] != NULL);
      } else if (pFuncParam->type == FUNC_PARAM_TYPE_VALUE) {
721 722 723
        // 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) {
724 725 726 727
          pInput->totalRows = pBlock->info.rows;
          pInput->numOfRows = pBlock->info.rows;
          pInput->startRowIndex = 0;

728
          code = doCreateConstantValColumnInfo(pInput, pFuncParam, j, pBlock->info.rows);
729 730 731
          if (code != TSDB_CODE_SUCCESS) {
            return code;
          }
732
        }
G
Ganlin Zhao 已提交
733 734
      }
    }
H
Haojun Liao 已提交
735
  }
736 737

  return code;
H
Haojun Liao 已提交
738 739
}

740
static int32_t doAggregateImpl(SOperatorInfo* pOperator, TSKEY startTs, SqlFunctionCtx* pCtx) {
741
  for (int32_t k = 0; k < pOperator->numOfExprs; ++k) {
H
Haojun Liao 已提交
742
    if (functionNeedToExecute(&pCtx[k])) {
743
      // todo add a dummy funtion to avoid process check
744 745 746 747 748 749 750 751
      if (pCtx[k].fpSet.process == NULL) {
        continue;
      }

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

  return TSDB_CODE_SUCCESS;
757 758
}

H
Haojun Liao 已提交
759
static void setPseudoOutputColInfo(SSDataBlock* pResult, SqlFunctionCtx* pCtx, SArray* pPseudoList) {
dengyihao's avatar
dengyihao 已提交
760
  size_t num = (pPseudoList != NULL) ? taosArrayGetSize(pPseudoList) : 0;
H
Haojun Liao 已提交
761 762 763 764 765
  for (int32_t i = 0; i < num; ++i) {
    pCtx[i].pOutput = taosArrayGet(pResult->pDataBlock, i);
  }
}

766
int32_t projectApplyFunctions(SExprInfo* pExpr, SSDataBlock* pResult, SSDataBlock* pSrcBlock, SqlFunctionCtx* pCtx,
X
Xiaoyu Wang 已提交
767
                              int32_t numOfOutput, SArray* pPseudoList) {
H
Haojun Liao 已提交
768
  setPseudoOutputColInfo(pResult, pCtx, pPseudoList);
H
Haojun Liao 已提交
769
  pResult->info.groupId = pSrcBlock->info.groupId;
H
Haojun Liao 已提交
770

dengyihao's avatar
dengyihao 已提交
771 772
  // if the source equals to the destination, it is to create a new column as the result of scalar function or some
  // operators.
773 774
  bool createNewColModel = (pResult == pSrcBlock);

775 776
  int32_t numOfRows = 0;

777
  for (int32_t k = 0; k < numOfOutput; ++k) {
dengyihao's avatar
dengyihao 已提交
778
    int32_t         outputSlotId = pExpr[k].base.resSchema.slotId;
779 780
    SqlFunctionCtx* pfCtx = &pCtx[k];

L
Liu Jicong 已提交
781
    if (pExpr[k].pExpr->nodeType == QUERY_NODE_COLUMN) {  // it is a project query
782
      SColumnInfoData* pColInfoData = taosArrayGet(pResult->pDataBlock, outputSlotId);
783
      if (pResult->info.rows > 0 && !createNewColModel) {
X
Xiaoyu Wang 已提交
784 785
        colDataMergeCol(pColInfoData, pResult->info.rows, &pResult->info.capacity, pfCtx->input.pData[0],
                        pfCtx->input.numOfRows);
786 787 788
      } else {
        colDataAssign(pColInfoData, pfCtx->input.pData[0], pfCtx->input.numOfRows);
      }
789

790
      numOfRows = pfCtx->input.numOfRows;
791
    } else if (pExpr[k].pExpr->nodeType == QUERY_NODE_VALUE) {
792
      SColumnInfoData* pColInfoData = taosArrayGet(pResult->pDataBlock, outputSlotId);
793

dengyihao's avatar
dengyihao 已提交
794
      int32_t offset = createNewColModel ? 0 : pResult->info.rows;
795
      for (int32_t i = 0; i < pSrcBlock->info.rows; ++i) {
dengyihao's avatar
dengyihao 已提交
796 797 798
        colDataAppend(pColInfoData, i + offset,
                      taosVariantGet(&pExpr[k].base.pParam[0].param, pExpr[k].base.pParam[0].param.nType),
                      TSDB_DATA_TYPE_NULL == pExpr[k].base.pParam[0].param.nType);
799
      }
800 801

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

806
      SColumnInfoData* pResColData = taosArrayGet(pResult->pDataBlock, outputSlotId);
807
      SColumnInfoData  idata = {.info = pResColData->info, .hasNull = true};
808

809
      SScalarParam dest = {.columnData = &idata};
X
Xiaoyu Wang 已提交
810
      int32_t      code = scalarCalculate(pExpr[k].pExpr->_optrRoot.pRootNode, pBlockList, &dest);
811 812 813 814
      if (code != TSDB_CODE_SUCCESS) {
        taosArrayDestroy(pBlockList);
        return code;
      }
815

dengyihao's avatar
dengyihao 已提交
816
      int32_t startOffset = createNewColModel ? 0 : pResult->info.rows;
817
      colInfoDataEnsureCapacity(pResColData, startOffset, pResult->info.capacity);
818
      colDataMergeCol(pResColData, startOffset, &pResult->info.capacity, &idata, dest.numOfRows);
819 820

      numOfRows = dest.numOfRows;
821 822
      taosArrayDestroy(pBlockList);
    } else if (pExpr[k].pExpr->nodeType == QUERY_NODE_FUNCTION) {
823
      ASSERT(!fmIsAggFunc(pfCtx->functionId));
824

825 826
      // _rowts/_c0, not tbname column
      if (fmIsPseudoColumnFunc(pfCtx->functionId) && (!fmIsScanPseudoColumnFunc(pfCtx->functionId))) {
H
Haojun Liao 已提交
827
        // do nothing
X
Xiaoyu Wang 已提交
828
      } else if (fmIsIndefiniteRowsFunc(pfCtx->functionId)) {
dengyihao's avatar
dengyihao 已提交
829
        SResultRowEntryInfo* pResInfo = GET_RES_INFO(&pCtx[k]);
830
        pfCtx->fpSet.init(&pCtx[k], pResInfo);
831

832
        pfCtx->pOutput = taosArrayGet(pResult->pDataBlock, outputSlotId);
dengyihao's avatar
dengyihao 已提交
833
        pfCtx->offset = createNewColModel ? 0 : pResult->info.rows;  // set the start offset
H
Haojun Liao 已提交
834

835
        // set the timestamp(_rowts) output buffer
836 837
        if (taosArrayGetSize(pPseudoList) > 0) {
          int32_t* outputColIndex = taosArrayGet(pPseudoList, 0);
838
          pfCtx->pTsOutput = (SColumnInfoData*)pCtx[*outputColIndex].pOutput;
839
        }
H
Haojun Liao 已提交
840

841
        numOfRows = pfCtx->fpSet.process(pfCtx);
H
Haojun Liao 已提交
842 843 844
      } else {
        SArray* pBlockList = taosArrayInit(4, POINTER_BYTES);
        taosArrayPush(pBlockList, &pSrcBlock);
G
Ganlin Zhao 已提交
845

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

849
        SScalarParam dest = {.columnData = &idata};
X
Xiaoyu Wang 已提交
850
        int32_t      code = scalarCalculate((SNode*)pExpr[k].pExpr->_function.pFunctNode, pBlockList, &dest);
851 852 853 854
        if (code != TSDB_CODE_SUCCESS) {
          taosArrayDestroy(pBlockList);
          return code;
        }
855

dengyihao's avatar
dengyihao 已提交
856
        int32_t startOffset = createNewColModel ? 0 : pResult->info.rows;
857
        colInfoDataEnsureCapacity(pResColData, startOffset, pResult->info.capacity);
858
        colDataMergeCol(pResColData, startOffset, &pResult->info.capacity, &idata, dest.numOfRows);
859 860

        numOfRows = dest.numOfRows;
H
Haojun Liao 已提交
861 862
        taosArrayDestroy(pBlockList);
      }
863
    } else {
864
      ASSERT(0);
865 866
    }
  }
867

868 869 870
  if (!createNewColModel) {
    pResult->info.rows += numOfRows;
  }
871 872

  return TSDB_CODE_SUCCESS;
873 874
}

875 876 877
static void setResultRowKey(SResultRow* pResultRow, char* pData, int16_t type) {
  if (IS_VAR_DATA_TYPE(type)) {
    // todo disable this
878

879 880 881 882 883 884 885 886 887
    //    if (pResultRow->key == NULL) {
    //      pResultRow->key = taosMemoryMalloc(varDataTLen(pData));
    //      varDataCopy(pResultRow->key, pData);
    //    } else {
    //      ASSERT(memcmp(pResultRow->key, pData, varDataTLen(pData)) == 0);
    //    }
  } else {
    int64_t v = -1;
    GET_TYPED_DATA(v, int64_t, type, pData);
888

889 890
    pResultRow->win.skey = v;
    pResultRow->win.ekey = v;
891 892 893
  }
}

894 895 896 897 898
int32_t setGroupResultOutputBuf(SOptrBasicInfo* binfo, int32_t numOfCols, char* pData, int16_t type, int16_t bytes,
                                int32_t groupId, SDiskbasedBuf* pBuf, SExecTaskInfo* pTaskInfo,
                                SAggSupporter* pAggSup) {
  SResultRowInfo* pResultRowInfo = &binfo->resultRowInfo;
  SqlFunctionCtx* pCtx = binfo->pCtx;
899

900 901 902
  SResultRow* pResultRow =
      doSetResultOutBufByKey(pBuf, pResultRowInfo, (char*)pData, bytes, true, groupId, pTaskInfo, false, pAggSup);
  assert(pResultRow != NULL);
903

904
  setResultRowKey(pResultRow, pData, type);
905
  setResultRowInitCtx(pResultRow, pCtx, numOfCols, binfo->rowCellInfoOffset);
906
  return TSDB_CODE_SUCCESS;
907 908
}

5
54liuyao 已提交
909
bool functionNeedToExecute(SqlFunctionCtx* pCtx) {
910
  struct SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
911

912 913 914 915 916
  // in case of timestamp column, always generated results.
  int32_t functionId = pCtx->functionId;
  if (functionId == -1) {
    return false;
  }
917

918 919
  if (pCtx->scanFlag == REPEAT_SCAN) {
    return fmIsRepeatScanFunc(pCtx->functionId);
920 921
  }

922 923
  if (isRowEntryCompleted(pResInfo)) {
    return false;
924 925
  }

X
Xiaoyu Wang 已提交
926 927 928 929 930 931 932 933
  //  if (functionId == FUNCTION_FIRST_DST || functionId == FUNCTION_FIRST) {
  //    //    return QUERY_IS_ASC_QUERY(pQueryAttr);
  //  }
  //
  //  // denote the order type
  //  if ((functionId == FUNCTION_LAST_DST || functionId == FUNCTION_LAST)) {
  //    //    return pCtx->param[0].i == pQueryAttr->order.order;
  //  }
934

935 936 937 938 939
  // in the reverse table scan, only the following functions need to be executed
  //  if (IS_REVERSE_SCAN(pRuntimeEnv) ||
  //      (pRuntimeEnv->scanFlag == REPEAT_SCAN && functionId != FUNCTION_STDDEV && functionId != FUNCTION_PERCT)) {
  //    return false;
  //  }
940 941 942 943

  return true;
}

944 945 946 947 948 949 950
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;
    }
951

952 953 954
    // Set the correct column info (data type and bytes)
    pInput->pData[paramIndex]->info.type = type;
    pInput->pData[paramIndex]->info.bytes = tDataTypes[type].bytes;
955
  }
H
Haojun Liao 已提交
956

957 958 959 960 961 962
  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;
963 964
    }
  } else {
965
    da = pInput->pColumnDataAgg[paramIndex];
966 967
  }

968
  ASSERT(!IS_VAR_DATA_TYPE(type));
969

970 971 972 973 974 975
  if (type == TSDB_DATA_TYPE_BIGINT) {
    int64_t v = pFuncParam->param.i;
    *da = (SColumnDataAgg){.numOfNull = 0, .min = v, .max = v, .maxIndex = 0, .minIndex = 0, .sum = v * numOfRows};
  } else if (type == TSDB_DATA_TYPE_DOUBLE) {
    double v = pFuncParam->param.d;
    *da = (SColumnDataAgg){.numOfNull = 0, .maxIndex = 0, .minIndex = 0};
976

977 978 979 980 981 982 983 984 985 986 987 988
    *(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;

    *da = (SColumnDataAgg){.numOfNull = 0, .maxIndex = 0, .minIndex = 0};
    *(bool*)&da->min = 0;
    *(bool*)&da->max = v;
    *(bool*)&da->sum = v * numOfRows;
  } else if (type == TSDB_DATA_TYPE_TIMESTAMP) {
    // do nothing
989
  } else {
990
    ASSERT(0);
991 992
  }

993 994
  return TSDB_CODE_SUCCESS;
}
995 996 997 998 999 1000 1001 1002 1003 1004 1005

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;

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

1009 1010
      if (pFuncParam->type == FUNC_PARAM_TYPE_COLUMN) {
        int32_t slotId = pFuncParam->pCol->slotId;
1011 1012 1013 1014
        pInput->pColumnDataAgg[j] = pBlock->pBlockAgg[slotId];
        if (pInput->pColumnDataAgg[j] == NULL) {
          pInput->colDataAggIsSet = false;
        }
1015 1016 1017 1018

        // 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);
1019 1020
      } else if (pFuncParam->type == FUNC_PARAM_TYPE_VALUE) {
        doCreateConstantValColumnAggInfo(pInput, pFuncParam, pFuncParam->param.nType, j, pBlock->info.rows);
1021 1022
      }
    }
1023
  } else {
1024
    pInput->colDataAggIsSet = false;
1025 1026 1027
  }

  // set the statistics data for primary time stamp column
1028 1029 1030 1031 1032
  //  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;
  //  }
1033 1034 1035
}

// set the output buffer for the selectivity + tag query
1036
static int32_t setSelectValueColumnInfo(SqlFunctionCtx* pCtx, int32_t numOfOutput) {
1037 1038
  int32_t num = 0;

H
Haojun Liao 已提交
1039
  SqlFunctionCtx*  p = NULL;
1040 1041
  SqlFunctionCtx** pValCtx = taosMemoryCalloc(numOfOutput, POINTER_BYTES);
  if (pValCtx == NULL) {
1042 1043 1044 1045
    return TSDB_CODE_QRY_OUT_OF_MEMORY;
  }

  for (int32_t i = 0; i < numOfOutput; ++i) {
1046 1047
    if (strcmp(pCtx[i].pExpr->pExpr->_function.functionName, "_select_value") == 0) {
      pValCtx[num++] = &pCtx[i];
X
Xiaoyu Wang 已提交
1048
    } else if (fmIsSelectFunc(pCtx[i].functionId)) {
1049
      p = &pCtx[i];
1050
    }
X
Xiaoyu Wang 已提交
1051 1052 1053 1054 1055 1056 1057 1058 1059 1060
    //    if (functionId == FUNCTION_TAG_DUMMY || functionId == FUNCTION_TS_DUMMY) {
    //      tagLen += pCtx[i].resDataInfo.bytes;
    //      pTagCtx[num++] = &pCtx[i];
    //    } else if (functionId == FUNCTION_TS || functionId == FUNCTION_TAG) {
    //      // tag function may be the group by tag column
    //      // ts may be the required primary timestamp column
    //      continue;
    //    } else {
    //      // the column may be the normal column, group by normal_column, the functionId is FUNCTION_PRJ
    //    }
1061
  }
1062

1063
  if (p != NULL) {
1064
    p->subsidiaries.pCtx = pValCtx;
1065
    p->subsidiaries.num = num;
1066
  } else {
1067
    taosMemoryFreeClear(pValCtx);
1068 1069 1070 1071 1072
  }

  return TSDB_CODE_SUCCESS;
}

1073
SqlFunctionCtx* createSqlFunctionCtx(SExprInfo* pExprInfo, int32_t numOfOutput, int32_t** rowCellInfoOffset) {
L
Liu Jicong 已提交
1074
  SqlFunctionCtx* pFuncCtx = (SqlFunctionCtx*)taosMemoryCalloc(numOfOutput, sizeof(SqlFunctionCtx));
H
Haojun Liao 已提交
1075 1076 1077 1078
  if (pFuncCtx == NULL) {
    return NULL;
  }

wafwerar's avatar
wafwerar 已提交
1079
  *rowCellInfoOffset = taosMemoryCalloc(numOfOutput, sizeof(int32_t));
H
Haojun Liao 已提交
1080
  if (*rowCellInfoOffset == 0) {
wafwerar's avatar
wafwerar 已提交
1081
    taosMemoryFreeClear(pFuncCtx);
H
Haojun Liao 已提交
1082 1083 1084 1085
    return NULL;
  }

  for (int32_t i = 0; i < numOfOutput; ++i) {
H
Haojun Liao 已提交
1086
    SExprInfo* pExpr = &pExprInfo[i];
H
Haojun Liao 已提交
1087

L
Liu Jicong 已提交
1088
    SExprBasicInfo* pFunct = &pExpr->base;
H
Haojun Liao 已提交
1089
    SqlFunctionCtx* pCtx = &pFuncCtx[i];
H
Haojun Liao 已提交
1090

1091
    pCtx->functionId = -1;
1092
    pCtx->curBufPage = -1;
L
Liu Jicong 已提交
1093
    pCtx->pExpr = pExpr;
1094

H
Haojun Liao 已提交
1095
    if (pExpr->pExpr->nodeType == QUERY_NODE_FUNCTION) {
H
Haojun Liao 已提交
1096
      SFuncExecEnv env = {0};
H
Haojun Liao 已提交
1097 1098
      pCtx->functionId = pExpr->pExpr->_function.pFunctNode->funcId;

X
Xiaoyu Wang 已提交
1099
      if (fmIsAggFunc(pCtx->functionId) || fmIsIndefiniteRowsFunc(pCtx->functionId)) {
1100 1101 1102 1103
        bool isUdaf = fmIsUserDefinedFunc(pCtx->functionId);
        if (!isUdaf) {
          fmGetFuncExecFuncs(pCtx->functionId, &pCtx->fpSet);
        } else {
1104
          char* udfName = pExpr->pExpr->_function.pFunctNode->functionName;
1105 1106 1107
          strncpy(pCtx->udfName, udfName, strlen(udfName));
          fmGetUdafExecFuncs(pCtx->functionId, &pCtx->fpSet);
        }
1108 1109 1110
        pCtx->fpSet.getEnv(pExpr->pExpr->_function.pFunctNode, &env);
      } else {
        fmGetScalarFuncExecFuncs(pCtx->functionId, &pCtx->sfp);
1111 1112 1113
        if (pCtx->sfp.getEnv != NULL) {
          pCtx->sfp.getEnv(pExpr->pExpr->_function.pFunctNode, &env);
        }
1114
      }
H
Haojun Liao 已提交
1115
      pCtx->resDataInfo.interBufSize = env.calcMemSize;
1116 1117
    } else if (pExpr->pExpr->nodeType == QUERY_NODE_COLUMN || pExpr->pExpr->nodeType == QUERY_NODE_OPERATOR ||
               pExpr->pExpr->nodeType == QUERY_NODE_VALUE) {
H
Haojun Liao 已提交
1118
      // for simple column, the result buffer needs to hold at least one element.
1119
      pCtx->resDataInfo.interBufSize = pFunct->resSchema.bytes;
H
Haojun Liao 已提交
1120
    }
H
Haojun Liao 已提交
1121

H
Haojun Liao 已提交
1122
    pCtx->input.numOfInputCols = pFunct->numOfParams;
wafwerar's avatar
wafwerar 已提交
1123 1124
    pCtx->input.pData = taosMemoryCalloc(pFunct->numOfParams, POINTER_BYTES);
    pCtx->input.pColumnDataAgg = taosMemoryCalloc(pFunct->numOfParams, POINTER_BYTES);
H
Haojun Liao 已提交
1125

1126
    pCtx->pTsOutput = NULL;
L
Liu Jicong 已提交
1127
    pCtx->resDataInfo.bytes = pFunct->resSchema.bytes;
1128
    pCtx->resDataInfo.type = pFunct->resSchema.type;
L
Liu Jicong 已提交
1129
    pCtx->order = TSDB_ORDER_ASC;
1130
    pCtx->start.key = INT64_MIN;
L
Liu Jicong 已提交
1131
    pCtx->end.key = INT64_MIN;
1132
    pCtx->numOfParams = pExpr->base.numOfParams;
1133
    pCtx->increase = false;
H
Haojun Liao 已提交
1134

1135
    pCtx->param = pFunct->pParam;
dengyihao's avatar
dengyihao 已提交
1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169
    //    for (int32_t j = 0; j < pCtx->numOfParams; ++j) {
    //      // set the order information for top/bottom query
    //      int32_t functionId = pCtx->functionId;
    //      if (functionId == FUNCTION_TOP || functionId == FUNCTION_BOTTOM || functionId == FUNCTION_DIFF) {
    //        int32_t f = getExprFunctionId(&pExpr[0]);
    //        assert(f == FUNCTION_TS || f == FUNCTION_TS_DUMMY);
    //
    //        //      pCtx->param[2].i = pQueryAttr->order.order;
    //        //      pCtx->param[2].nType = TSDB_DATA_TYPE_BIGINT;
    //        //      pCtx->param[3].i = functionId;
    //        //      pCtx->param[3].nType = TSDB_DATA_TYPE_BIGINT;
    //
    //        //      pCtx->param[1].i = pQueryAttr->order.col.info.colId;
    //      } else if (functionId == FUNCTION_INTERP) {
    //        //      pCtx->param[2].i = (int8_t)pQueryAttr->fillType;
    //        //      if (pQueryAttr->fillVal != NULL) {
    //        //        if (isNull((const char *)&pQueryAttr->fillVal[i], pCtx->inputType)) {
    //        //          pCtx->param[1].nType = TSDB_DATA_TYPE_NULL;
    //        //        } else {  // todo refactor, taosVariantCreateFromBinary should handle the NULL value
    //        //          if (pCtx->inputType != TSDB_DATA_TYPE_BINARY && pCtx->inputType != TSDB_DATA_TYPE_NCHAR) {
    //        //            taosVariantCreateFromBinary(&pCtx->param[1], (char *)&pQueryAttr->fillVal[i],
    //        pCtx->inputBytes, pCtx->inputType);
    //        //          }
    //        //        }
    //        //      }
    //      } else if (functionId == FUNCTION_TWA) {
    //        //      pCtx->param[1].i = pQueryAttr->window.skey;
    //        //      pCtx->param[1].nType = TSDB_DATA_TYPE_BIGINT;
    //        //      pCtx->param[2].i = pQueryAttr->window.ekey;
    //        //      pCtx->param[2].nType = TSDB_DATA_TYPE_BIGINT;
    //      } else if (functionId == FUNCTION_ARITHM) {
    //        //      pCtx->param[1].pz = (char*) getScalarFuncSupport(pRuntimeEnv->scalarSup, i);
    //      }
    //    }
H
Haojun Liao 已提交
1170 1171
  }

L
Liu Jicong 已提交
1172 1173 1174
  for (int32_t i = 1; i < numOfOutput; ++i) {
    (*rowCellInfoOffset)[i] =
        (int32_t)((*rowCellInfoOffset)[i - 1] + sizeof(SResultRowEntryInfo) + pFuncCtx[i - 1].resDataInfo.interBufSize);
H
Haojun Liao 已提交
1175
  }
H
Haojun Liao 已提交
1176

1177
  setSelectValueColumnInfo(pFuncCtx, numOfOutput);
H
Haojun Liao 已提交
1178 1179 1180
  return pFuncCtx;
}

1181
static void* destroySqlFunctionCtx(SqlFunctionCtx* pCtx, int32_t numOfOutput) {
1182 1183 1184 1185 1186 1187
  if (pCtx == NULL) {
    return NULL;
  }

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

1191
    taosMemoryFreeClear(pCtx[i].subsidiaries.pCtx);
H
Haojun Liao 已提交
1192 1193
    taosMemoryFree(pCtx[i].input.pData);
    taosMemoryFree(pCtx[i].input.pColumnDataAgg);
1194 1195
  }

wafwerar's avatar
wafwerar 已提交
1196
  taosMemoryFreeClear(pCtx);
1197 1198 1199
  return NULL;
}

L
Liu Jicong 已提交
1200
bool isTaskKilled(SExecTaskInfo* pTaskInfo) {
1201 1202
  // query has been executed more than tsShellActivityTimer, and the retrieve has not arrived
  // abort current query execution.
L
Liu Jicong 已提交
1203 1204
  if (pTaskInfo->owner != 0 &&
      ((taosGetTimestampSec() - pTaskInfo->cost.start / 1000) > 10 * getMaximumIdleDurationSec())
1205 1206
      /*(!needBuildResAfterQueryComplete(pTaskInfo))*/) {
    assert(pTaskInfo->cost.start != 0);
L
Liu Jicong 已提交
1207 1208 1209
    //    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;
1210 1211 1212 1213 1214
  }

  return false;
}

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

L
Liu Jicong 已提交
1217
static bool isCachedLastQuery(STaskAttr* pQueryAttr) {
1218 1219
  for (int32_t i = 0; i < pQueryAttr->numOfOutput; ++i) {
    int32_t functionId = getExprFunctionId(&pQueryAttr->pExpr1[i]);
X
Xiaoyu Wang 已提交
1220 1221 1222
    //    if (functionId == FUNCTION_LAST || functionId == FUNCTION_LAST_DST) {
    //      continue;
    //    }
1223 1224 1225 1226

    return false;
  }

1227 1228
  int32_t order = TSDB_ORDER_ASC;
  if (order != TSDB_ORDER_DESC || !TSWINDOW_IS_EQUAL(pQueryAttr->window, TSWINDOW_DESC_INITIALIZER)) {
1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247
    return false;
  }

  if (pQueryAttr->groupbyColumn) {
    return false;
  }

  if (pQueryAttr->interval.interval > 0) {
    return false;
  }

  if (pQueryAttr->numOfFilterCols > 0 || pQueryAttr->havingNum > 0) {
    return false;
  }

  return true;
}

/////////////////////////////////////////////////////////////////////////////////////////////
L
Liu Jicong 已提交
1248
// todo refactor : return window
1249
void getAlignQueryTimeWindow(SInterval* pInterval, int32_t precision, int64_t key, STimeWindow* win) {
H
Haojun Liao 已提交
1250
  win->skey = taosTimeTruncate(key, pInterval, precision);
1251 1252

  /*
H
Haojun Liao 已提交
1253
   * if the realSkey > INT64_MAX - pInterval->interval, the query duration between
1254 1255
   * realSkey and realEkey must be less than one interval.Therefore, no need to adjust the query ranges.
   */
1256 1257
  win->ekey = taosTimeAdd(win->skey, pInterval->interval, pInterval->intervalUnit, precision) - 1;
  if (win->ekey < win->skey) {
1258 1259 1260 1261
    win->ekey = INT64_MAX;
  }
}

L
Liu Jicong 已提交
1262
static int32_t updateBlockLoadStatus(STaskAttr* pQuery, int32_t status) {
1263 1264 1265
  bool hasFirstLastFunc = false;
  bool hasOtherFunc = false;

1266
  if (status == BLK_DATA_DATA_LOAD || status == BLK_DATA_FILTEROUT) {
1267 1268 1269 1270 1271
    return status;
  }

  for (int32_t i = 0; i < pQuery->numOfOutput; ++i) {
    int32_t functionId = getExprFunctionId(&pQuery->pExpr1[i]);
1272
#if 0
1273 1274 1275 1276 1277 1278 1279 1280 1281 1282
    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;
    }
1283
#endif
1284 1285
  }

1286
  if (hasFirstLastFunc && status == BLK_DATA_NOT_LOAD) {
L
Liu Jicong 已提交
1287
    if (!hasOtherFunc) {
1288
      return BLK_DATA_FILTEROUT;
1289
    } else {
1290
      return BLK_DATA_DATA_LOAD;
1291 1292 1293 1294 1295 1296
    }
  }

  return status;
}

L
Liu Jicong 已提交
1297 1298
// static void updateDataCheckOrder(SQInfo *pQInfo, SQueryTableReq* pQueryMsg, bool stableQuery) {
//   STaskAttr* pQueryAttr = pQInfo->runtimeEnv.pQueryAttr;
H
Haojun Liao 已提交
1299
//
L
Liu Jicong 已提交
1300 1301 1302 1303
//   // 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 已提交
1304
//
L
Liu Jicong 已提交
1305 1306 1307 1308 1309
//   // 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 已提交
1310
//
L
Liu Jicong 已提交
1311 1312
//     pQueryAttr->order.order = TSDB_ORDER_ASC;
//     if (pQueryAttr->window.skey > pQueryAttr->window.ekey) {
wafwerar's avatar
wafwerar 已提交
1313
//       TSWAP(pQueryAttr->window.skey, pQueryAttr->window.ekey);
L
Liu Jicong 已提交
1314
//     }
H
Haojun Liao 已提交
1315
//
L
Liu Jicong 已提交
1316 1317 1318
//     pQueryAttr->needReverseScan = false;
//     return;
//   }
H
Haojun Liao 已提交
1319
//
L
Liu Jicong 已提交
1320 1321 1322
//   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 已提交
1323
//       TSWAP(pQueryAttr->window.skey, pQueryAttr->window.ekey);
L
Liu Jicong 已提交
1324
//     }
H
Haojun Liao 已提交
1325
//
L
Liu Jicong 已提交
1326 1327 1328 1329
//     pQueryAttr->needReverseScan = false;
//     doUpdateLastKey(pQueryAttr);
//     return;
//   }
H
Haojun Liao 已提交
1330
//
L
Liu Jicong 已提交
1331 1332 1333 1334 1335 1336
//   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 已提交
1337
//
L
Liu Jicong 已提交
1338 1339 1340
//     pQueryAttr->order.order = TSDB_ORDER_ASC;
//     return;
//   }
H
Haojun Liao 已提交
1341
//
L
Liu Jicong 已提交
1342 1343 1344 1345
//   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 已提交
1346 1347
////               pQueryAttr->window.ekey, pQueryAttr->window.ekey, pQueryAttr->window.skey);
//
wafwerar's avatar
wafwerar 已提交
1348
//        TSWAP(pQueryAttr->window.skey, pQueryAttr->window.ekey);
H
Haojun Liao 已提交
1349 1350 1351 1352 1353 1354 1355 1356 1357 1358
//        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 已提交
1359
//        TSWAP(pQueryAttr->window.skey, pQueryAttr->window.ekey);
H
Haojun Liao 已提交
1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371
//        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 已提交
1372 1373
////                 pQueryAttr->window.skey, pQueryAttr->window.ekey, pQueryAttr->window.ekey,
/// pQueryAttr->window.skey);
H
Haojun Liao 已提交
1374
//
wafwerar's avatar
wafwerar 已提交
1375
//          TSWAP(pQueryAttr->window.skey, pQueryAttr->window.ekey);
H
Haojun Liao 已提交
1376 1377 1378 1379 1380 1381 1382 1383
//          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 已提交
1384 1385
////                 pQueryAttr->window.skey, pQueryAttr->window.ekey, pQueryAttr->window.ekey,
/// pQueryAttr->window.skey);
H
Haojun Liao 已提交
1386
//
wafwerar's avatar
wafwerar 已提交
1387
//          TSWAP(pQueryAttr->window.skey, pQueryAttr->window.ekey);
H
Haojun Liao 已提交
1388 1389 1390 1391 1392 1393 1394 1395 1396
//          doUpdateLastKey(pQueryAttr);
//        }
//
//        pQueryAttr->order.order = TSDB_ORDER_DESC;
//        pQueryAttr->needReverseScan = false;
//      }
//    }
//  }
//}
1397

L
Liu Jicong 已提交
1398 1399 1400
// static FORCE_INLINE bool doFilterByBlockStatistics(STaskRuntimeEnv* pRuntimeEnv, SDataStatis *pDataStatis,
// SqlFunctionCtx *pCtx, int32_t numOfRows) {
//   STaskAttr* pQueryAttr = pRuntimeEnv->pQueryAttr;
1401
//
L
Liu Jicong 已提交
1402 1403 1404
//   if (pDataStatis == NULL || pQueryAttr->pFilters == NULL) {
//     return true;
//   }
1405
//
L
Liu Jicong 已提交
1406 1407
//   return filterRangeExecute(pQueryAttr->pFilters, pDataStatis, pQueryAttr->numOfCols, numOfRows);
// }
1408

H
Haojun Liao 已提交
1409
static bool overlapWithTimeWindow(STaskAttr* pQueryAttr, SDataBlockInfo* pBlockInfo) {
1410 1411
  STimeWindow w = {0};

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

1415
  if (true) {
L
Liu Jicong 已提交
1416
    //    getAlignQueryTimeWindow(pQueryAttr, pBlockInfo->window.skey, sk, ek, &w);
1417 1418 1419 1420 1421 1422
    assert(w.ekey >= pBlockInfo->window.skey);

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

L
Liu Jicong 已提交
1423 1424
    while (1) {
      //      getNextTimeWindow(pQueryAttr, &w);
1425 1426 1427 1428 1429 1430 1431 1432 1433 1434
      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 已提交
1435
    //    getAlignQueryTimeWindow(pQueryAttr, pBlockInfo->window.ekey, sk, ek, &w);
1436 1437 1438 1439 1440 1441
    assert(w.skey <= pBlockInfo->window.ekey);

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

L
Liu Jicong 已提交
1442 1443
    while (1) {
      //      getNextTimeWindow(pQueryAttr, &w);
1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507
      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;
}

void doCompactSDataBlock(SSDataBlock* pBlock, int32_t numOfRows, int8_t* p) {
  int32_t len = 0;
  int32_t start = 0;
  for (int32_t j = 0; j < numOfRows; ++j) {
    if (p[j] == 1) {
      len++;
    } else {
      if (len > 0) {
        int32_t cstart = j - len;
        for (int32_t i = 0; i < pBlock->info.numOfCols; ++i) {
          SColumnInfoData* pColumnInfoData = taosArrayGet(pBlock->pDataBlock, i);

          int16_t bytes = pColumnInfoData->info.bytes;
          memmove(((char*)pColumnInfoData->pData) + start * bytes, pColumnInfoData->pData + cstart * bytes,
                  len * bytes);
        }

        start += len;
        len = 0;
      }
    }
  }

  if (len > 0) {
    int32_t cstart = numOfRows - len;
    for (int32_t i = 0; i < pBlock->info.numOfCols; ++i) {
      SColumnInfoData* pColumnInfoData = taosArrayGet(pBlock->pDataBlock, i);

      int16_t bytes = pColumnInfoData->info.bytes;
      memmove(pColumnInfoData->pData + start * bytes, pColumnInfoData->pData + cstart * bytes, len * bytes);
    }

    start += len;
    len = 0;
  }

  pBlock->info.rows = start;
  pBlock->pBlockAgg = NULL;  // clean the block statistics info

  if (start > 0) {
    SColumnInfoData* pColumnInfoData = taosArrayGet(pBlock->pDataBlock, 0);
    if (pColumnInfoData->info.type == TSDB_DATA_TYPE_TIMESTAMP &&
        pColumnInfoData->info.colId == PRIMARYKEY_TIMESTAMP_COL_ID) {
      pBlock->info.window.skey = *(int64_t*)pColumnInfoData->pData;
      pBlock->info.window.ekey = *(int64_t*)(pColumnInfoData->pData + TSDB_KEYSIZE * (start - 1));
    }
  }
}

static uint32_t doFilterByBlockTimeWindow(STableScanInfo* pTableScanInfo, SSDataBlock* pBlock) {
H
Haojun Liao 已提交
1508
  SqlFunctionCtx* pCtx = pTableScanInfo->pCtx;
1509
  uint32_t        status = BLK_DATA_NOT_LOAD;
1510 1511 1512 1513

  int32_t numOfOutput = pTableScanInfo->numOfOutput;
  for (int32_t i = 0; i < numOfOutput; ++i) {
    int32_t functionId = pCtx[i].functionId;
H
Haojun Liao 已提交
1514
    int32_t colId = pTableScanInfo->pExpr[i].base.pParam[0].pCol->colId;
1515 1516 1517

    // group by + first/last should not apply the first/last block filter
    if (functionId < 0) {
1518
      status |= BLK_DATA_DATA_LOAD;
1519 1520
      return status;
    } else {
L
Liu Jicong 已提交
1521
      //      status |= aAggs[functionId].dataReqFunc(&pTableScanInfo->pCtx[i], &pBlock->info.window, colId);
1522
      //      if ((status & BLK_DATA_DATA_LOAD) == BLK_DATA_DATA_LOAD) {
L
Liu Jicong 已提交
1523 1524
      //        return status;
      //      }
1525 1526 1527 1528 1529 1530
    }
  }

  return status;
}

L
Liu Jicong 已提交
1531 1532
int32_t loadDataBlockOnDemand(SExecTaskInfo* pTaskInfo, STableScanInfo* pTableScanInfo, SSDataBlock* pBlock,
                              uint32_t* status) {
1533
  *status = BLK_DATA_NOT_LOAD;
1534

H
Haojun Liao 已提交
1535
  pBlock->pDataBlock = NULL;
L
Liu Jicong 已提交
1536
  pBlock->pBlockAgg = NULL;
H
Haojun Liao 已提交
1537

L
Liu Jicong 已提交
1538 1539
  //  int64_t groupId = pRuntimeEnv->current->groupIndex;
  //  bool    ascQuery = QUERY_IS_ASC_QUERY(pQueryAttr);
1540

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

1543 1544
//  pCost->totalBlocks += 1;
//  pCost->totalRows += pBlock->info.rows;
H
Haojun Liao 已提交
1545
#if 0
1546 1547 1548
  // 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 已提交
1549
      (QUERY_IS_INTERVAL_QUERY(pQueryAttr) && overlapWithTimeWindow(pTaskInfo, &pBlock->info))) {
1550
    (*status) = BLK_DATA_DATA_LOAD;
1551 1552 1553
  }

  // check if this data block is required to load
1554
  if ((*status) != BLK_DATA_DATA_LOAD) {
1555 1556 1557 1558 1559 1560 1561
    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 已提交
1562
      bool  masterScan = IS_MAIN_SCAN(pRuntimeEnv);
1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585
      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,
                                    pTableScanInfo->rowCellInfoOffset);
      } else {
        if (setResultOutputBufByKey(pRuntimeEnv, pTableScanInfo->pResultRowInfo, pBlock->info.uid, &win, masterScan, &pResult, groupId,
                                    pTableScanInfo->pCtx, pTableScanInfo->numOfOutput,
                                    pTableScanInfo->rowCellInfoOffset) != TSDB_CODE_SUCCESS) {
          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,
                               pTableScanInfo->rowCellInfoOffset, pTableScanInfo->numOfOutput,
                               pRuntimeEnv->current->groupIndex);
    }

    if (needFilter) {
      (*status) = doFilterByBlockTimeWindow(pTableScanInfo, pBlock);
    } else {
1586
      (*status) = BLK_DATA_DATA_LOAD;
1587 1588 1589 1590
    }
  }

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

1593
  if ((*status) == BLK_DATA_NOT_LOAD || (*status) == BLK_DATA_FILTEROUT) {
1594 1595
    //qDebug("QInfo:0x%"PRIx64" data block discard, brange:%" PRId64 "-%" PRId64 ", rows:%d", pQInfo->qId, pBlockInfo->window.skey,
//           pBlockInfo->window.ekey, pBlockInfo->rows);
1596
    pCost->skipBlocks += 1;
1597
  } else if ((*status) == BLK_DATA_SMA_LOAD) {
1598 1599
    // this function never returns error?
    pCost->loadBlockStatis += 1;
1600
//    tsdbRetrieveDataBlockStatisInfo(pTableScanInfo->pTsdbReadHandle, &pBlock->pBlockAgg);
1601 1602

    if (pBlock->pBlockAgg == NULL) {  // data block statistics does not exist, load data block
1603
//      pBlock->pDataBlock = tsdbRetrieveDataBlock(pTableScanInfo->pTsdbReadHandle, NULL);
1604 1605 1606
      pCost->totalCheckedRows += pBlock->info.rows;
    }
  } else {
1607
    assert((*status) == BLK_DATA_DATA_LOAD);
1608 1609 1610

    // load the data block statistics to perform further filter
    pCost->loadBlockStatis += 1;
1611
//    tsdbRetrieveDataBlockStatisInfo(pTableScanInfo->pTsdbReadHandle, &pBlock->pBlockAgg);
1612 1613 1614 1615 1616 1617

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

H
Haojun Liao 已提交
1618
          bool  masterScan = IS_MAIN_SCAN(pRuntimeEnv);
1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635
          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,
                                      pTableScanInfo->rowCellInfoOffset) != TSDB_CODE_SUCCESS) {
            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
1636
            pCost->skipBlocks += 1;
1637 1638
            //qDebug("QInfo:0x%"PRIx64" data block discard, brange:%" PRId64 "-%" PRId64 ", rows:%d", pQInfo->qId,
//                   pBlockInfo->window.skey, pBlockInfo->window.ekey, pBlockInfo->rows);
1639
            (*status) = BLK_DATA_FILTEROUT;
1640 1641 1642 1643 1644 1645 1646 1647
            return TSDB_CODE_SUCCESS;
          }
        }
      }
    }

    // current block has been discard due to filter applied
//    if (!doFilterByBlockStatistics(pRuntimeEnv, pBlock->pBlockAgg, pTableScanInfo->pCtx, pBlockInfo->rows)) {
1648
//      pCost->skipBlocks += 1;
1649 1650
//      qDebug("QInfo:0x%"PRIx64" data block discard, brange:%" PRId64 "-%" PRId64 ", rows:%d", pQInfo->qId, pBlockInfo->window.skey,
//             pBlockInfo->window.ekey, pBlockInfo->rows);
1651
//      (*status) = BLK_DATA_FILTEROUT;
1652 1653 1654 1655 1656
//      return TSDB_CODE_SUCCESS;
//    }

    pCost->totalCheckedRows += pBlockInfo->rows;
    pCost->loadBlocks += 1;
1657
//    pBlock->pDataBlock = tsdbRetrieveDataBlock(pTableScanInfo->pTsdbReadHandle, NULL);
1658 1659 1660 1661 1662 1663 1664
//    if (pBlock->pDataBlock == NULL) {
//      return terrno;
//    }

//    if (pQueryAttr->pFilters != NULL) {
//      filterSetColFieldData(pQueryAttr->pFilters, pBlock->info.numOfCols, pBlock->pDataBlock);
//    }
1665

1666 1667 1668 1669
//    if (pQueryAttr->pFilters != NULL || pRuntimeEnv->pTsBuf != NULL) {
//      filterColRowsInDataBlock(pRuntimeEnv, pBlock, ascQuery);
//    }
  }
H
Haojun Liao 已提交
1670
#endif
1671 1672 1673
  return TSDB_CODE_SUCCESS;
}

L
Liu Jicong 已提交
1674
static void updateTableQueryInfoForReverseScan(STableQueryInfo* pTableQueryInfo) {
1675 1676 1677 1678
  if (pTableQueryInfo == NULL) {
    return;
  }

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

L
Liu Jicong 已提交
1682 1683
  //  SWITCH_ORDER(pTableQueryInfo->cur.order);
  //  pTableQueryInfo->cur.vgroupIndex = -1;
1684 1685

  // set the index to be the end slot of result rows array
dengyihao's avatar
dengyihao 已提交
1686 1687 1688 1689 1690 1691
  //  SResultRowInfo* pResultRowInfo = &pTableQueryInfo->resInfo;
  //  if (pResultRowInfo->size > 0) {
  //    pResultRowInfo->curPos = pResultRowInfo->size - 1;
  //  } else {
  //    pResultRowInfo->curPos = -1;
  //  }
1692 1693
}

H
Haojun Liao 已提交
1694
void initResultRow(SResultRow* pResultRow) {
X
Xiaoyu Wang 已提交
1695
  //  pResultRow->pEntryInfo = (struct SResultRowEntryInfo*)((char*)pResultRow + sizeof(SResultRow));
1696 1697 1698 1699 1700
}

/*
 * The start of each column SResultRowEntryInfo is denote by RowCellInfoOffset.
 * Note that in case of top/bottom query, the whole multiple rows of result is treated as only one row of results.
H
Haojun Liao 已提交
1701 1702 1703
 * +------------+-----------------result column 1------------+------------------result column 2-----------+
 * | SResultRow | SResultRowEntryInfo | intermediate buffer1 | SResultRowEntryInfo | intermediate buffer 2|
 * +------------+--------------------------------------------+--------------------------------------------+
1704 1705
 *           offset[0]                                  offset[1]                                   offset[2]
 */
1706
// TODO refactor: some function move away
X
Xiaoyu Wang 已提交
1707 1708
void setFunctionResultOutput(SOptrBasicInfo* pInfo, SAggSupporter* pSup, int32_t stage, int32_t numOfExprs,
                             SExecTaskInfo* pTaskInfo) {
L
Liu Jicong 已提交
1709 1710 1711
  SqlFunctionCtx* pCtx = pInfo->pCtx;
  SSDataBlock*    pDataBlock = pInfo->pRes;
  int32_t*        rowCellInfoOffset = pInfo->rowCellInfoOffset;
H
Haojun Liao 已提交
1712

H
Haojun Liao 已提交
1713
  SResultRowInfo* pResultRowInfo = &pInfo->resultRowInfo;
H
Haojun Liao 已提交
1714
  initResultRowInfo(pResultRowInfo, 16);
H
Haojun Liao 已提交
1715

L
Liu Jicong 已提交
1716 1717
  int64_t     tid = 0;
  int64_t     groupId = 0;
1718 1719
  SResultRow* pRow = doSetResultOutBufByKey(pSup->pResultBuf, pResultRowInfo, (char*)&tid, sizeof(tid), true, groupId,
                                            pTaskInfo, false, pSup);
H
Haojun Liao 已提交
1720

1721
  for (int32_t i = 0; i < numOfExprs; ++i) {
H
Haojun Liao 已提交
1722 1723 1724
    struct SResultRowEntryInfo* pEntry = getResultCell(pRow, i, rowCellInfoOffset);
    cleanupResultRowEntry(pEntry);

L
Liu Jicong 已提交
1725
    pCtx[i].resultInfo = pEntry;
1726
    pCtx[i].scanFlag = stage;
H
Haojun Liao 已提交
1727 1728
  }

1729
  initCtxOutputBuffer(pCtx, numOfExprs);
H
Haojun Liao 已提交
1730 1731
}

L
Liu Jicong 已提交
1732
void updateOutputBuf(SOptrBasicInfo* pBInfo, int32_t* bufCapacity, int32_t numOfInputRows) {
1733 1734
  SSDataBlock* pDataBlock = pBInfo->pRes;

L
Liu Jicong 已提交
1735
  int32_t newSize = pDataBlock->info.rows + numOfInputRows + 5;  // extra output buffer
1736
  if ((*bufCapacity) < newSize) {
L
Liu Jicong 已提交
1737 1738
    for (int32_t i = 0; i < pDataBlock->info.numOfCols; ++i) {
      SColumnInfoData* pColInfo = taosArrayGet(pDataBlock->pDataBlock, i);
1739

wafwerar's avatar
wafwerar 已提交
1740
      char* p = taosMemoryRealloc(pColInfo->pData, newSize * pColInfo->info.bytes);
1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753
      if (p != NULL) {
        pColInfo->pData = p;

        // it starts from the tail of the previously generated results.
        pBInfo->pCtx[i].pOutput = pColInfo->pData;
        (*bufCapacity) = newSize;
      } else {
        // longjmp
      }
    }
  }

  for (int32_t i = 0; i < pDataBlock->info.numOfCols; ++i) {
L
Liu Jicong 已提交
1754
    SColumnInfoData* pColInfo = taosArrayGet(pDataBlock->pDataBlock, i);
1755 1756 1757 1758
    pBInfo->pCtx[i].pOutput = pColInfo->pData + pColInfo->info.bytes * pDataBlock->info.rows;

    // set the correct pointer after the memory buffer reallocated.
    int32_t functionId = pBInfo->pCtx[i].functionId;
1759
#if 0
L
Liu Jicong 已提交
1760 1761
    if (functionId == FUNCTION_TOP || functionId == FUNCTION_BOTTOM || functionId == FUNCTION_DIFF ||
        functionId == FUNCTION_DERIVATIVE) {
dengyihao's avatar
dengyihao 已提交
1762
      //      if (i > 0) pBInfo->pCtx[i].pTsOutput = pBInfo->pCtx[i - 1].pOutput;
1763
    }
1764
#endif
1765 1766 1767
  }
}

H
Haojun Liao 已提交
1768
void initCtxOutputBuffer(SqlFunctionCtx* pCtx, int32_t size) {
1769 1770
  for (int32_t j = 0; j < size; ++j) {
    struct SResultRowEntryInfo* pResInfo = GET_RES_INFO(&pCtx[j]);
dengyihao's avatar
dengyihao 已提交
1771 1772
    if (isRowEntryInitialized(pResInfo) || fmIsPseudoColumnFunc(pCtx[j].functionId) || pCtx[j].functionId == -1 ||
        fmIsScalarFunc(pCtx[j].functionId)) {
1773 1774 1775
      continue;
    }

H
Haojun Liao 已提交
1776
    pCtx[j].fpSet.init(&pCtx[j], pCtx[j].resultInfo);
1777 1778 1779
  }
}

L
Liu Jicong 已提交
1780
void setTaskStatus(SExecTaskInfo* pTaskInfo, int8_t status) {
1781
  if (status == TASK_NOT_COMPLETED) {
H
Haojun Liao 已提交
1782
    pTaskInfo->status = status;
1783 1784
  } else {
    // QUERY_NOT_COMPLETED is not compatible with any other status, so clear its position first
1785
    CLEAR_QUERY_STATUS(pTaskInfo, TASK_NOT_COMPLETED);
H
Haojun Liao 已提交
1786
    pTaskInfo->status |= status;
1787 1788 1789
  }
}

L
Liu Jicong 已提交
1790
void destroyTableQueryInfoImpl(STableQueryInfo* pTableQueryInfo) {
1791 1792 1793 1794
  if (pTableQueryInfo == NULL) {
    return;
  }

L
Liu Jicong 已提交
1795
  //  taosVariantDestroy(&pTableQueryInfo->tag);
dengyihao's avatar
dengyihao 已提交
1796
  //  cleanupResultRowInfo(&pTableQueryInfo->resInfo);
1797 1798
}

1799
void setResultRowInitCtx(SResultRow* pResult, SqlFunctionCtx* pCtx, int32_t numOfOutput, int32_t* rowCellInfoOffset) {
1800 1801 1802 1803 1804 1805 1806
  for (int32_t i = 0; i < numOfOutput; ++i) {
    pCtx[i].resultInfo = getResultCell(pResult, i, rowCellInfoOffset);

    struct SResultRowEntryInfo* pResInfo = pCtx[i].resultInfo;
    if (isRowEntryCompleted(pResInfo) && isRowEntryInitialized(pResInfo)) {
      continue;
    }
1807 1808 1809 1810 1811

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

1812 1813 1814 1815 1816 1817
    if (!pResInfo->initialized) {
      if (pCtx[i].functionId != -1) {
        pCtx[i].fpSet.init(&pCtx[i], pResInfo);
      } else {
        pResInfo->initialized = true;
      }
1818 1819 1820 1821
    }
  }
}

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

wmmhello's avatar
wmmhello 已提交
1824
void doFilter(const SNode* pFilterNode, SSDataBlock* pBlock, bool needFree) {
1825 1826 1827 1828 1829
  if (pFilterNode == NULL) {
    return;
  }

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

H
Haojun Liao 已提交
1831
  // todo move to the initialization function
H
Haojun Liao 已提交
1832
  int32_t code = filterInitFromNode((SNode*)pFilterNode, &filter, 0);
1833 1834 1835 1836 1837

  SFilterColumnParam param1 = {.numOfCols = pBlock->info.numOfCols, .pDataBlock = pBlock->pDataBlock};
  code = filterSetDataFromSlotId(filter, &param1);

  int8_t* rowRes = NULL;
1838

1839
  // todo the keep seems never to be True??
1840
  bool keep = filterExecute(filter, pBlock, &rowRes, NULL, param1.numOfCols);
D
dapan1121 已提交
1841
  filterFreeInfo(filter);
1842

H
Haojun Liao 已提交
1843
  extractQualifiedTupleByFilterResult(pBlock, rowRes, keep);
1844
  blockDataUpdateTsWindow(pBlock, 0);
1845 1846
}

H
Haojun Liao 已提交
1847
void extractQualifiedTupleByFilterResult(SSDataBlock* pBlock, const int8_t* rowRes, bool keep) {
1848 1849 1850 1851 1852 1853 1854 1855
  if (keep) {
    return;
  }

  if (rowRes != NULL) {
    SSDataBlock* px = createOneDataBlock(pBlock, false);
    blockDataEnsureCapacity(px, pBlock->info.rows);

1856 1857
    int32_t totalRows = pBlock->info.rows;

1858 1859 1860 1861
    for (int32_t i = 0; i < pBlock->info.numOfCols; ++i) {
      SColumnInfoData* pDst = taosArrayGet(px->pDataBlock, i);
      SColumnInfoData* pSrc = taosArrayGet(pBlock->pDataBlock, i);

1862 1863 1864 1865 1866
      // it is a reserved column for scalar function, and no data in this column yet.
      if (pSrc->pData == NULL) {
        continue;
      }

1867
      int32_t numOfRows = 0;
1868
      for (int32_t j = 0; j < totalRows; ++j) {
D
dapan1121 已提交
1869 1870 1871
        if (rowRes[j] == 0) {
          continue;
        }
1872

D
dapan1121 已提交
1873
        if (colDataIsNull_s(pSrc, j)) {
1874
          colDataAppendNULL(pDst, numOfRows);
D
dapan1121 已提交
1875
        } else {
1876
          colDataAppend(pDst, numOfRows, colDataGetData(pSrc, j), false);
D
dapan1121 已提交
1877
        }
1878
        numOfRows += 1;
H
Haojun Liao 已提交
1879
      }
1880

1881 1882 1883 1884 1885 1886
      if (pBlock->info.rows == totalRows) {
        pBlock->info.rows = numOfRows;
      } else {
        ASSERT(pBlock->info.rows == numOfRows);
      }

H
Haojun Liao 已提交
1887
      // write back
1888
      colDataAssign(pSrc, pDst, pBlock->info.rows);
1889
    }
dengyihao's avatar
dengyihao 已提交
1890
    blockDataDestroy(px);  // fix memory leak
1891 1892 1893
  } else {
    // do nothing
    pBlock->info.rows = 0;
1894 1895 1896
  }
}

dengyihao's avatar
dengyihao 已提交
1897 1898
void doSetTableGroupOutputBuf(SAggOperatorInfo* pAggInfo, int32_t numOfOutput, uint64_t groupId,
                              SExecTaskInfo* pTaskInfo) {
1899 1900 1901
  // for simple group by query without interval, all the tables belong to one group result.
  int64_t uid = 0;

1902 1903
  SResultRowInfo* pResultRowInfo = &pAggInfo->binfo.resultRowInfo;
  SqlFunctionCtx* pCtx = pAggInfo->binfo.pCtx;
L
Liu Jicong 已提交
1904
  int32_t*        rowCellInfoOffset = pAggInfo->binfo.rowCellInfoOffset;
1905

1906
  SResultRow* pResultRow = doSetResultOutBufByKey(pAggInfo->aggSup.pResultBuf, pResultRowInfo, (char*)&groupId,
L
Liu Jicong 已提交
1907
                                                  sizeof(groupId), true, groupId, pTaskInfo, false, &pAggInfo->aggSup);
L
Liu Jicong 已提交
1908
  assert(pResultRow != NULL);
1909 1910 1911 1912 1913 1914

  /*
   * 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 已提交
1915 1916
    int32_t ret =
        addNewWindowResultBuf(pResultRow, pAggInfo->aggSup.pResultBuf, groupId, pAggInfo->binfo.pRes->info.rowSize);
1917 1918 1919 1920 1921
    if (ret != TSDB_CODE_SUCCESS) {
      return;
    }
  }

1922
  setResultRowInitCtx(pResultRow, pCtx, numOfOutput, rowCellInfoOffset);
1923 1924
}

H
Haojun Liao 已提交
1925 1926
void setExecutionContext(int32_t numOfOutput, uint64_t groupId, SExecTaskInfo* pTaskInfo, SAggOperatorInfo* pAggInfo) {
  if (pAggInfo->groupId != INT32_MIN && pAggInfo->groupId == groupId) {
1927 1928 1929
    return;
  }

H
Haojun Liao 已提交
1930
  doSetTableGroupOutputBuf(pAggInfo, numOfOutput, groupId, pTaskInfo);
1931 1932

  // record the current active group id
H
Haojun Liao 已提交
1933
  pAggInfo->groupId = groupId;
1934 1935
}

1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948
static void doUpdateNumOfRows(SResultRow* pRow, int32_t numOfExprs, const int32_t* rowCellOffset) {
  for (int32_t j = 0; j < numOfExprs; ++j) {
    struct SResultRowEntryInfo* pResInfo = getResultCell(pRow, j, rowCellOffset);
    if (!isRowEntryInitialized(pResInfo)) {
      continue;
    }

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

X
Xiaoyu Wang 已提交
1949 1950 1951
int32_t doCopyToSDataBlock(SExecTaskInfo* pTaskInfo, SSDataBlock* pBlock, SExprInfo* pExprInfo, SDiskbasedBuf* pBuf,
                           SGroupResInfo* pGroupResInfo, const int32_t* rowCellOffset, SqlFunctionCtx* pCtx,
                           int32_t numOfExprs) {
1952
  int32_t numOfRows = getNumOfTotalRes(pGroupResInfo);
1953
  int32_t start = pGroupResInfo->index;
1954

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

1959
    SResultRow* pRow = (SResultRow*)((char*)page + pPos->pos.offset);
1960 1961

    doUpdateNumOfRows(pRow, numOfExprs, rowCellOffset);
1962 1963
    if (pRow->numOfRows == 0) {
      pGroupResInfo->index += 1;
1964
      releaseBufPage(pBuf, page);
1965 1966 1967
      continue;
    }

1968 1969 1970 1971 1972
    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) {
1973
        releaseBufPage(pBuf, page);
1974 1975 1976 1977
        break;
      }
    }

1978
    if (pBlock->info.rows + pRow->numOfRows > pBlock->info.capacity) {
1979
      releaseBufPage(pBuf, page);
1980 1981 1982 1983 1984
      break;
    }

    pGroupResInfo->index += 1;

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

1988
      pCtx[j].resultInfo = getResultCell(pRow, j, rowCellOffset);
1989
      if (pCtx[j].fpSet.finalize) {
1990
        int32_t code = pCtx[j].fpSet.finalize(&pCtx[j], pBlock);
1991
        if (TAOS_FAILED(code)) {
1992 1993
          qError("%s build result data block error, code %s", GET_TASKID(pTaskInfo), tstrerror(code));
          longjmp(pTaskInfo->env, code);
1994
        }
1995 1996
      } else if (strcmp(pCtx[j].pExpr->pExpr->_function.functionName, "_select_value") == 0) {
        // do nothing, todo refactor
1997
      } else {
1998 1999
        // expand the result into multiple rows. E.g., _wstartts, top(k, 20)
        // the _wstartts needs to copy to 20 following rows, since the results of top-k expands to 20 different rows.
X
Xiaoyu Wang 已提交
2000 2001
        SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, slotId);
        char*            in = GET_ROWCELL_INTERBUF(pCtx[j].resultInfo);
2002 2003 2004 2005 2006 2007 2008 2009 2010 2011
        if (pCtx[j].increase) {
          int64_t ts = *(int64_t*) in;
          for (int32_t k = 0; k < pRow->numOfRows; ++k) {
            colDataAppend(pColInfoData, pBlock->info.rows + k, (const char *)&ts, pCtx[j].resultInfo->isNullRes);
            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 已提交
2012
        }
2013
      }
2014 2015
    }

2016
    releaseBufPage(pBuf, page);
2017 2018
    pBlock->info.rows += pRow->numOfRows;
    if (pBlock->info.rows >= pBlock->info.capacity) {  // output buffer is full
2019 2020 2021 2022
      break;
    }
  }

X
Xiaoyu Wang 已提交
2023 2024
  qDebug("%s result generated, rows:%d, groupId:%" PRIu64, GET_TASKID(pTaskInfo), pBlock->info.rows,
         pBlock->info.groupId);
2025
  blockDataUpdateTsWindow(pBlock, 0);
2026 2027 2028
  return 0;
}

X
Xiaoyu Wang 已提交
2029 2030 2031 2032
void doBuildResultDatablock(SOperatorInfo* pOperator, SOptrBasicInfo* pbInfo, SGroupResInfo* pGroupResInfo,
                            SDiskbasedBuf* pBuf) {
  SExprInfo*     pExprInfo = pOperator->pExpr;
  int32_t        numOfExprs = pOperator->numOfExprs;
2033 2034
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;

X
Xiaoyu Wang 已提交
2035 2036 2037
  int32_t*        rowCellOffset = pbInfo->rowCellInfoOffset;
  SSDataBlock*    pBlock = pbInfo->pRes;
  SqlFunctionCtx* pCtx = pbInfo->pCtx;
2038

2039
  blockDataCleanup(pBlock);
2040
  if (!hashRemainDataInGroupInfo(pGroupResInfo)) {
2041 2042 2043
    return;
  }

2044 2045
  // clear the existed group id
  pBlock->info.groupId = 0;
2046
  doCopyToSDataBlock(pTaskInfo, pBlock, pExprInfo, pBuf, pGroupResInfo, rowCellOffset, pCtx, numOfExprs);
2047 2048
}

L
Liu Jicong 已提交
2049 2050
static void updateNumOfRowsInResultRows(SqlFunctionCtx* pCtx, int32_t numOfOutput, SResultRowInfo* pResultRowInfo,
                                        int32_t* rowCellInfoOffset) {
2051
  // update the number of result for each, only update the number of rows for the corresponding window result.
L
Liu Jicong 已提交
2052 2053 2054
  //  if (QUERY_IS_INTERVAL_QUERY(pQueryAttr)) {
  //    return;
  //  }
H
Haojun Liao 已提交
2055
#if 0
2056
  for (int32_t i = 0; i < pResultRowInfo->size; ++i) {
L
Liu Jicong 已提交
2057
    SResultRow* pResult = pResultRowInfo->pResult[i];
2058 2059 2060 2061 2062 2063 2064

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

2065 2066
      SResultRowEntryInfo* pCell = getResultCell(pResult, j, rowCellInfoOffset);
      pResult->numOfRows = (uint16_t)(TMAX(pResult->numOfRows, pCell->numOfRes));
2067 2068
    }
  }
H
Haojun Liao 已提交
2069
#endif
2070 2071
}

L
Liu Jicong 已提交
2072
static int32_t compressQueryColData(SColumnInfoData* pColRes, int32_t numOfRows, char* data, int8_t compressed) {
2073 2074
  int32_t colSize = pColRes->info.bytes * numOfRows;
  return (*(tDataTypes[pColRes->info.type].compFunc))(pColRes->pData, colSize, numOfRows, data,
L
Liu Jicong 已提交
2075
                                                      colSize + COMP_OVERFLOW_BYTES, compressed, NULL, 0);
2076 2077
}

2078 2079 2080
int32_t doFillTimeIntervalGapsInResults(struct SFillInfo* pFillInfo, SSDataBlock* pBlock, int32_t capacity) {
  int32_t numOfRows = (int32_t)taosFillResultDataBlock(pFillInfo, pBlock, capacity - pBlock->info.rows);
  pBlock->info.rows += numOfRows;
2081

2082
  return pBlock->info.rows;
2083 2084
}

L
Liu Jicong 已提交
2085 2086
void queryCostStatis(SExecTaskInfo* pTaskInfo) {
  STaskCostInfo* pSummary = &pTaskInfo->cost;
2087

L
Liu Jicong 已提交
2088 2089 2090
  //  uint64_t hashSize = taosHashGetMemSize(pQInfo->runtimeEnv.pResultRowHashTable);
  //  hashSize += taosHashGetMemSize(pRuntimeEnv->tableqinfoGroupInfo.map);
  //  pSummary->hashSize = hashSize;
2091 2092 2093 2094

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

L
Liu Jicong 已提交
2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105
  //  SResultRowPool* p = pTaskInfo->pool;
  //  if (p != NULL) {
  //    pSummary->winInfoSize = getResultRowPoolMemSize(p);
  //    pSummary->numOfTimeWindows = getNumOfAllocatedResultRows(p);
  //  } else {
  //    pSummary->winInfoSize = 0;
  //    pSummary->numOfTimeWindows = 0;
  //  }
  //
  //  calculateOperatorProfResults(pQInfo);

2106 2107
  SFileBlockLoadRecorder* pRecorder = pSummary->pRecoder;
  if (pSummary->pRecoder != NULL) {
X
Xiaoyu Wang 已提交
2108 2109
    qDebug("%s :cost summary: elapsed time:%" PRId64 " us, first merge:%" PRId64
           " us, total blocks:%d, "
2110 2111 2112 2113
           "load block statis:%d, load data block:%d, total rows:%" PRId64 ", check rows:%" PRId64,
           GET_TASKID(pTaskInfo), pSummary->elapsedTime, pSummary->firstStageMergeTime, pRecorder->totalBlocks,
           pRecorder->loadBlockStatis, pRecorder->loadBlocks, pRecorder->totalRows, pRecorder->totalCheckedRows);
  }
L
Liu Jicong 已提交
2114 2115 2116
  // 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);
2117 2118
}

L
Liu Jicong 已提交
2119 2120 2121
// static void updateOffsetVal(STaskRuntimeEnv *pRuntimeEnv, SDataBlockInfo *pBlockInfo) {
//   STaskAttr *pQueryAttr = pRuntimeEnv->pQueryAttr;
//   STableQueryInfo* pTableQueryInfo = pRuntimeEnv->current;
2122
//
L
Liu Jicong 已提交
2123
//   int32_t step = GET_FORWARD_DIRECTION_FACTOR(pQueryAttr->order.order);
2124
//
L
Liu Jicong 已提交
2125 2126 2127 2128
//   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;
//   }
2129
//
L
Liu Jicong 已提交
2130 2131 2132 2133 2134
//   if (QUERY_IS_ASC_QUERY(pQueryAttr)) {
//     pQueryAttr->pos = (int32_t)pQueryAttr->limit.offset;
//   } else {
//     pQueryAttr->pos = pBlockInfo->rows - (int32_t)pQueryAttr->limit.offset - 1;
//   }
2135
//
L
Liu Jicong 已提交
2136
//   assert(pQueryAttr->pos >= 0 && pQueryAttr->pos <= pBlockInfo->rows - 1);
2137
//
L
Liu Jicong 已提交
2138 2139
//   SArray *         pDataBlock = tsdbRetrieveDataBlock(pRuntimeEnv->pTsdbReadHandle, NULL);
//   SColumnInfoData *pColInfoData = taosArrayGet(pDataBlock, 0);
2140
//
L
Liu Jicong 已提交
2141 2142
//   // update the pQueryAttr->limit.offset value, and pQueryAttr->pos value
//   TSKEY *keys = (TSKEY *) pColInfoData->pData;
2143
//
L
Liu Jicong 已提交
2144 2145 2146
//   // update the offset value
//   pTableQueryInfo->lastKey = keys[pQueryAttr->pos];
//   pQueryAttr->limit.offset = 0;
2147
//
L
Liu Jicong 已提交
2148
//   int32_t numOfRes = tableApplyFunctionsOnBlock(pRuntimeEnv, pBlockInfo, NULL, binarySearchForKey, pDataBlock);
2149
//
L
Liu Jicong 已提交
2150 2151 2152 2153
//   //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);
// }
2154

L
Liu Jicong 已提交
2155 2156
// void skipBlocks(STaskRuntimeEnv *pRuntimeEnv) {
//   STaskAttr *pQueryAttr = pRuntimeEnv->pQueryAttr;
2157
//
L
Liu Jicong 已提交
2158 2159 2160
//   if (pQueryAttr->limit.offset <= 0 || pQueryAttr->numOfFilterCols > 0) {
//     return;
//   }
2161
//
L
Liu Jicong 已提交
2162 2163
//   pQueryAttr->pos = 0;
//   int32_t step = GET_FORWARD_DIRECTION_FACTOR(pQueryAttr->order.order);
2164
//
L
Liu Jicong 已提交
2165 2166
//   STableQueryInfo* pTableQueryInfo = pRuntimeEnv->current;
//   TsdbQueryHandleT pTsdbReadHandle = pRuntimeEnv->pTsdbReadHandle;
2167
//
L
Liu Jicong 已提交
2168 2169 2170 2171 2172
//   SDataBlockInfo blockInfo = SDATA_BLOCK_INITIALIZER;
//   while (tsdbNextDataBlock(pTsdbReadHandle)) {
//     if (isTaskKilled(pRuntimeEnv->qinfo)) {
//       longjmp(pRuntimeEnv->env, TSDB_CODE_TSC_QUERY_CANCELLED);
//     }
2173
//
L
Liu Jicong 已提交
2174
//     tsdbRetrieveDataBlockInfo(pTsdbReadHandle, &blockInfo);
2175
//
L
Liu Jicong 已提交
2176 2177 2178 2179
//     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;
2180
//
L
Liu Jicong 已提交
2181 2182 2183 2184 2185 2186 2187
//       //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;
//     }
//   }
2188
//
L
Liu Jicong 已提交
2189 2190 2191 2192 2193 2194 2195 2196 2197
//   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;
2198
//
L
Liu Jicong 已提交
2199 2200 2201
//   assert(pQueryAttr->limit.offset == 0);
//   STimeWindow tw = *win;
//   getNextTimeWindow(pQueryAttr, &tw);
2202
//
L
Liu Jicong 已提交
2203 2204
//   if ((tw.skey <= pBlockInfo->window.ekey && QUERY_IS_ASC_QUERY(pQueryAttr)) ||
//       (tw.ekey >= pBlockInfo->window.skey && !QUERY_IS_ASC_QUERY(pQueryAttr))) {
2205
//
L
Liu Jicong 已提交
2206 2207 2208 2209
//     // 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);
2210
//
L
Liu Jicong 已提交
2211 2212 2213 2214
//     tw = *win;
//     int32_t startPos =
//         getNextQualifiedWindow(pQueryAttr, &tw, pBlockInfo, pColInfoData->pData, binarySearchForKey, -1);
//     assert(startPos >= 0);
2215
//
L
Liu Jicong 已提交
2216 2217
//     // set the abort info
//     pQueryAttr->pos = startPos;
2218
//
L
Liu Jicong 已提交
2219 2220 2221 2222
//     // reset the query start timestamp
//     pTableQueryInfo->win.skey = ((TSKEY *)pColInfoData->pData)[startPos];
//     pQueryAttr->window.skey = pTableQueryInfo->win.skey;
//     TSKEY key = pTableQueryInfo->win.skey;
2223
//
L
Liu Jicong 已提交
2224 2225
//     pWindowResInfo->prevSKey = tw.skey;
//     int32_t index = pRuntimeEnv->resultRowInfo.curIndex;
2226
//
L
Liu Jicong 已提交
2227 2228
//     int32_t numOfRes = tableApplyFunctionsOnBlock(pRuntimeEnv, pBlockInfo, NULL, binarySearchForKey, pDataBlock);
//     pRuntimeEnv->resultRowInfo.curIndex = index;  // restore the window index
2229
//
L
Liu Jicong 已提交
2230 2231 2232 2233
//     //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);
2234
//
L
Liu Jicong 已提交
2235 2236 2237 2238 2239
//     return key;
//   } else {  // do nothing
//     pQueryAttr->window.skey      = tw.skey;
//     pWindowResInfo->prevSKey = tw.skey;
//     pTableQueryInfo->lastKey = tw.skey;
2240
//
L
Liu Jicong 已提交
2241 2242
//     return tw.skey;
//   }
2243
//
L
Liu Jicong 已提交
2244 2245 2246 2247 2248 2249 2250 2251 2252 2253
//   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);
//   }
2254
//
L
Liu Jicong 已提交
2255 2256 2257 2258 2259
//   // 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;
//   }
2260
//
L
Liu Jicong 已提交
2261 2262 2263 2264 2265 2266 2267
//   /*
//    * 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);
2268
//
L
Liu Jicong 已提交
2269 2270
//   STimeWindow w = TSWINDOW_INITIALIZER;
//   bool ascQuery = QUERY_IS_ASC_QUERY(pQueryAttr);
2271
//
L
Liu Jicong 已提交
2272 2273
//   SResultRowInfo *pWindowResInfo = &pRuntimeEnv->resultRowInfo;
//   STableQueryInfo *pTableQueryInfo = pRuntimeEnv->current;
2274
//
L
Liu Jicong 已提交
2275 2276 2277
//   SDataBlockInfo blockInfo = SDATA_BLOCK_INITIALIZER;
//   while (tsdbNextDataBlock(pRuntimeEnv->pTsdbReadHandle)) {
//     tsdbRetrieveDataBlockInfo(pRuntimeEnv->pTsdbReadHandle, &blockInfo);
2278
//
L
Liu Jicong 已提交
2279 2280 2281 2282 2283 2284 2285 2286 2287
//     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;
//     }
2288
//
L
Liu Jicong 已提交
2289 2290
//     // the first time window
//     STimeWindow win = getActiveTimeWindow(pWindowResInfo, pWindowResInfo->prevSKey, pQueryAttr);
2291
//
L
Liu Jicong 已提交
2292 2293
//     while (pQueryAttr->limit.offset > 0) {
//       STimeWindow tw = win;
2294
//
L
Liu Jicong 已提交
2295 2296 2297
//       if ((win.ekey <= blockInfo.window.ekey && ascQuery) || (win.ekey >= blockInfo.window.skey && !ascQuery)) {
//         pQueryAttr->limit.offset -= 1;
//         pWindowResInfo->prevSKey = win.skey;
2298
//
L
Liu Jicong 已提交
2299 2300 2301 2302 2303 2304
//         // 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;
//         }
//       }
2305
//
L
Liu Jicong 已提交
2306 2307 2308 2309
//       if (pQueryAttr->limit.offset == 0) {
//         *start = doSkipIntervalProcess(pRuntimeEnv, &win, &blockInfo, pTableQueryInfo);
//         return true;
//       }
2310
//
L
Liu Jicong 已提交
2311 2312
//       // current window does not ended in current data block, try next data block
//       getNextTimeWindow(pQueryAttr, &tw);
2313
//
L
Liu Jicong 已提交
2314 2315 2316 2317 2318 2319 2320 2321 2322
//       /*
//        * 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)) {
2323
//
L
Liu Jicong 已提交
2324 2325
//         SArray *pDataBlock = tsdbRetrieveDataBlock(pRuntimeEnv->pTsdbReadHandle, NULL);
//         SColumnInfoData *pColInfoData = taosArrayGet(pDataBlock, 0);
2326
//
L
Liu Jicong 已提交
2327 2328 2329
//         if ((win.ekey > blockInfo.window.ekey && ascQuery) || (win.ekey < blockInfo.window.skey && !ascQuery)) {
//           pQueryAttr->limit.offset -= 1;
//         }
2330
//
L
Liu Jicong 已提交
2331 2332 2333 2334 2335 2336 2337 2338
//         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);
2339
//
L
Liu Jicong 已提交
2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350
//           // 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.
//       }
//     }
//   }
2351
//
L
Liu Jicong 已提交
2352 2353 2354 2355
//   // check for error
//   if (terrno != TSDB_CODE_SUCCESS) {
//     longjmp(pRuntimeEnv->env, terrno);
//   }
2356
//
L
Liu Jicong 已提交
2357 2358
//   return true;
// }
2359

2360
int32_t appendDownstream(SOperatorInfo* p, SOperatorInfo** pDownstream, int32_t num) {
H
Haojun Liao 已提交
2361
  if (p->pDownstream == NULL) {
H
Haojun Liao 已提交
2362
    assert(p->numOfDownstream == 0);
2363 2364
  }

wafwerar's avatar
wafwerar 已提交
2365
  p->pDownstream = taosMemoryCalloc(1, num * POINTER_BYTES);
2366 2367 2368 2369 2370 2371 2372
  if (p->pDownstream == NULL) {
    return TSDB_CODE_OUT_OF_MEMORY;
  }

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

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

2377
static void doTableQueryInfoTimeWindowCheck(SExecTaskInfo* pTaskInfo, STableQueryInfo* pTableQueryInfo, int32_t order) {
H
Haojun Liao 已提交
2378 2379
#if 0
    if (order == TSDB_ORDER_ASC) {
2380 2381
    assert(
        (pTableQueryInfo->win.skey <= pTableQueryInfo->win.ekey) &&
H
Haojun Liao 已提交
2382 2383
        (pTableQueryInfo->lastKey >= pTaskInfo->window.skey) &&
        (pTableQueryInfo->win.skey >= pTaskInfo->window.skey && pTableQueryInfo->win.ekey <= pTaskInfo->window.ekey));
2384 2385 2386
  } else {
    assert(
        (pTableQueryInfo->win.skey >= pTableQueryInfo->win.ekey) &&
H
Haojun Liao 已提交
2387 2388
        (pTableQueryInfo->lastKey <= pTaskInfo->window.skey) &&
        (pTableQueryInfo->win.skey <= pTaskInfo->window.skey && pTableQueryInfo->win.ekey >= pTaskInfo->window.ekey));
2389
  }
H
Haojun Liao 已提交
2390
#endif
2391 2392
}

L
Liu Jicong 已提交
2393 2394 2395 2396
// static void updateTableIdInfo(STableQueryInfo* pTableQueryInfo, SSDataBlock* pBlock, SHashObj* pTableIdInfo, int32_t
// order) {
//   int32_t step = GET_FORWARD_DIRECTION_FACTOR(order);
//   pTableQueryInfo->lastKey = ((order == TSDB_ORDER_ASC)? pBlock->info.window.ekey:pBlock->info.window.skey) + step;
2397
//
L
Liu Jicong 已提交
2398 2399 2400
//   if (pTableQueryInfo->pTable == NULL) {
//     return;
//   }
2401
//
L
Liu Jicong 已提交
2402 2403 2404 2405 2406 2407 2408 2409 2410
//   STableIdInfo tidInfo = createTableIdInfo(pTableQueryInfo);
//   STableIdInfo *idinfo = taosHashGet(pTableIdInfo, &tidInfo.tid, sizeof(tidInfo.tid));
//   if (idinfo != NULL) {
//     assert(idinfo->tid == tidInfo.tid && idinfo->uid == tidInfo.uid);
//     idinfo->key = tidInfo.key;
//   } else {
//     taosHashPut(pTableIdInfo, &tidInfo.tid, sizeof(tidInfo.tid), &tidInfo, sizeof(STableIdInfo));
//   }
// }
2411

2412
int32_t loadRemoteDataCallback(void* param, const SDataBuf* pMsg, int32_t code) {
L
Liu Jicong 已提交
2413
  SSourceDataInfo* pSourceDataInfo = (SSourceDataInfo*)param;
H
Haojun Liao 已提交
2414 2415
  if (code == TSDB_CODE_SUCCESS) {
    pSourceDataInfo->pRsp = pMsg->pData;
2416

H
Haojun Liao 已提交
2417 2418
    SRetrieveTableRsp* pRsp = pSourceDataInfo->pRsp;
    pRsp->numOfRows = htonl(pRsp->numOfRows);
dengyihao's avatar
dengyihao 已提交
2419
    pRsp->compLen = htonl(pRsp->compLen);
2420
    pRsp->numOfCols = htonl(pRsp->numOfCols);
dengyihao's avatar
dengyihao 已提交
2421
    pRsp->useconds = htobe64(pRsp->useconds);
2422 2423 2424

    ASSERT(pSourceDataInfo->pRsp != NULL);
    qDebug("fetch rsp received, index:%d, rows:%d", pSourceDataInfo->index, pRsp->numOfRows);
H
Haojun Liao 已提交
2425 2426 2427
  } else {
    pSourceDataInfo->code = code;
  }
H
Haojun Liao 已提交
2428

H
Haojun Liao 已提交
2429
  pSourceDataInfo->status = EX_SOURCE_DATA_READY;
2430
  tsem_post(&pSourceDataInfo->pEx->ready);
wmmhello's avatar
wmmhello 已提交
2431
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
2432 2433 2434 2435
}

static void destroySendMsgInfo(SMsgSendInfo* pMsgBody) {
  assert(pMsgBody != NULL);
wafwerar's avatar
wafwerar 已提交
2436 2437
  taosMemoryFreeClear(pMsgBody->msgInfo.pData);
  taosMemoryFreeClear(pMsgBody);
H
Haojun Liao 已提交
2438 2439
}

S
Shengliang Guan 已提交
2440
void qProcessFetchRsp(void* parent, SRpcMsg* pMsg, SEpSet* pEpSet) {
S
Shengliang Guan 已提交
2441 2442
  SMsgSendInfo* pSendInfo = (SMsgSendInfo*)pMsg->info.ahandle;
  assert(pMsg->info.ahandle != NULL);
H
Haojun Liao 已提交
2443 2444 2445 2446

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

  if (pMsg->contLen > 0) {
wafwerar's avatar
wafwerar 已提交
2447
    buf.pData = taosMemoryCalloc(1, pMsg->contLen);
H
Haojun Liao 已提交
2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458
    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);
2459 2460
}

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

wafwerar's avatar
wafwerar 已提交
2464
  SResFetchReq* pMsg = taosMemoryCalloc(1, sizeof(SResFetchReq));
2465 2466 2467 2468
  if (NULL == pMsg) {
    pTaskInfo->code = TSDB_CODE_QRY_OUT_OF_MEMORY;
    return pTaskInfo->code;
  }
2469

L
Liu Jicong 已提交
2470 2471
  SDownstreamSourceNode* pSource = taosArrayGet(pExchangeInfo->pSources, sourceIndex);
  SSourceDataInfo*       pDataInfo = taosArrayGet(pExchangeInfo->pSourceDataInfo, sourceIndex);
2472

2473 2474
  ASSERT(pDataInfo->status == EX_SOURCE_DATA_NOT_READY);

L
Liu Jicong 已提交
2475 2476
  qDebug("%s build fetch msg and send to vgId:%d, ep:%s, taskId:0x%" PRIx64 ", %d/%" PRIzu, GET_TASKID(pTaskInfo),
         pSource->addr.nodeId, pSource->addr.epSet.eps[0].fqdn, pSource->taskId, sourceIndex, totalSources);
2477 2478 2479 2480 2481 2482 2483

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

  // send the fetch remote task result reques
wafwerar's avatar
wafwerar 已提交
2484
  SMsgSendInfo* pMsgSendInfo = taosMemoryCalloc(1, sizeof(SMsgSendInfo));
2485
  if (NULL == pMsgSendInfo) {
wafwerar's avatar
wafwerar 已提交
2486
    taosMemoryFreeClear(pMsg);
2487 2488 2489
    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 已提交
2490 2491
  }

2492 2493 2494 2495 2496
  pMsgSendInfo->param = pDataInfo;
  pMsgSendInfo->msgInfo.pData = pMsg;
  pMsgSendInfo->msgInfo.len = sizeof(SResFetchReq);
  pMsgSendInfo->msgType = TDMT_VND_FETCH;
  pMsgSendInfo->fp = loadRemoteDataCallback;
2497

2498
  int64_t transporterId = 0;
L
Liu Jicong 已提交
2499
  int32_t code = asyncSendMsgToServer(pExchangeInfo->pTransporter, &pSource->addr.epSet, &transporterId, pMsgSendInfo);
2500 2501 2502
  return TSDB_CODE_SUCCESS;
}

2503
// NOTE: sources columns are more than the destination SSDatablock columns.
2504
void relocateColumnData(SSDataBlock* pBlock, const SArray* pColMatchInfo, SArray* pCols) {
2505 2506 2507
  size_t numOfSrcCols = taosArrayGetSize(pCols);

  int32_t i = 0, j = 0;
L
Liu Jicong 已提交
2508
  while (i < numOfSrcCols && j < taosArrayGetSize(pColMatchInfo)) {
2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527
    SColumnInfoData* p = taosArrayGet(pCols, i);
    SColMatchInfo*   pmInfo = taosArrayGet(pColMatchInfo, j);
    if (!pmInfo->output) {
      j++;
      continue;
    }

    if (p->info.colId == pmInfo->colId) {
      taosArraySet(pBlock->pDataBlock, pmInfo->targetSlotId, p);
      i++;
      j++;
    } else if (p->info.colId < pmInfo->colId) {
      i++;
    } else {
      ASSERT(0);
    }
  }
}

2528
int32_t setDataBlockFromFetchRsp(SSDataBlock* pRes, SLoadRemoteDataInfo* pLoadInfo, int32_t numOfRows, char* pData,
X
Xiaoyu Wang 已提交
2529 2530
                                 int32_t compLen, int32_t numOfOutput, int64_t startTs, uint64_t* total,
                                 SArray* pColList) {
H
Haojun Liao 已提交
2531
  if (pColList == NULL) {  // data from other sources
2532
    blockCompressDecode(pRes, numOfOutput, numOfRows, pData);
H
Haojun Liao 已提交
2533
  } else {  // extract data according to pColList
2534
    ASSERT(numOfOutput == taosArrayGetSize(pColList));
2535 2536 2537 2538 2539
    char* pStart = pData;

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

2540
    // todo refactor:extract method
2541
    SSysTableSchema* pSchema = (SSysTableSchema*)pStart;
dengyihao's avatar
dengyihao 已提交
2542
    for (int32_t i = 0; i < numOfCols; ++i) {
2543 2544 2545 2546 2547 2548 2549
      SSysTableSchema* p = (SSysTableSchema*)pStart;

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

H
Haojun Liao 已提交
2550 2551 2552 2553
    SSDataBlock* pBlock = taosMemoryCalloc(1, sizeof(SSDataBlock));
    pBlock->pDataBlock = taosArrayInit(numOfCols, sizeof(SColumnInfoData));
    pBlock->info.numOfCols = numOfCols;

dengyihao's avatar
dengyihao 已提交
2554
    for (int32_t i = 0; i < numOfCols; ++i) {
2555
      SColumnInfoData idata = {0};
2556

X
Xiaoyu Wang 已提交
2557
      idata.info.type = pSchema[i].type;
2558 2559
      idata.info.bytes = pSchema[i].bytes;
      idata.info.colId = pSchema[i].colId;
X
Xiaoyu Wang 已提交
2560
      idata.hasNull = true;
2561

H
Haojun Liao 已提交
2562
      taosArrayPush(pBlock->pDataBlock, &idata);
2563
      if (IS_VAR_DATA_TYPE(idata.info.type)) {
H
Haojun Liao 已提交
2564
        pBlock->info.hasVarCol = true;
2565 2566 2567
      }
    }

2568
    blockCompressDecode(pBlock, numOfCols, numOfRows, pStart);
H
Haojun Liao 已提交
2569
    // data from mnode
H
Haojun Liao 已提交
2570 2571 2572
    relocateColumnData(pRes, pColList, pBlock->pDataBlock);
    taosArrayDestroy(pBlock->pDataBlock);
    taosMemoryFree(pBlock);
X
Xiaoyu Wang 已提交
2573
    //    blockDataDestroy(pBlock);
2574
  }
2575

H
Haojun Liao 已提交
2576
  pRes->info.rows = numOfRows;
2577 2578 2579

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

2581
  int64_t el = taosGetTimestampUs() - startTs;
2582

H
Haojun Liao 已提交
2583 2584
  pLoadInfo->totalRows += numOfRows;
  pLoadInfo->totalSize += compLen;
2585

H
Haojun Liao 已提交
2586 2587 2588
  if (total != NULL) {
    *total += numOfRows;
  }
2589

H
Haojun Liao 已提交
2590
  pLoadInfo->totalElapsed += el;
2591 2592
  return TSDB_CODE_SUCCESS;
}
2593

L
Liu Jicong 已提交
2594 2595
static void* setAllSourcesCompleted(SOperatorInfo* pOperator, int64_t startTs) {
  SExchangeInfo* pExchangeInfo = pOperator->info;
2596
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
H
Haojun Liao 已提交
2597

2598
  int64_t              el = taosGetTimestampUs() - startTs;
H
Haojun Liao 已提交
2599
  SLoadRemoteDataInfo* pLoadInfo = &pExchangeInfo->loadInfo;
2600

H
Haojun Liao 已提交
2601
  pLoadInfo->totalElapsed += el;
H
Haojun Liao 已提交
2602

2603
  size_t totalSources = taosArrayGetSize(pExchangeInfo->pSources);
L
Liu Jicong 已提交
2604 2605 2606
  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);
2607 2608 2609 2610 2611

  doSetOperatorCompleted(pOperator);
  return NULL;
}

L
Liu Jicong 已提交
2612 2613
static SSDataBlock* concurrentlyLoadRemoteDataImpl(SOperatorInfo* pOperator, SExchangeInfo* pExchangeInfo,
                                                   SExecTaskInfo* pTaskInfo) {
2614 2615 2616 2617 2618 2619 2620 2621
  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);
2622
      if (pDataInfo->status == EX_SOURCE_DATA_EXHAUSTED) {
2623
        completed += 1;
H
Haojun Liao 已提交
2624 2625
        continue;
      }
2626

2627
      if (pDataInfo->status != EX_SOURCE_DATA_READY) {
2628 2629 2630
        continue;
      }

2631 2632 2633 2634 2635
      if (pDataInfo->code != TSDB_CODE_SUCCESS) {
        code = pDataInfo->code;
        goto _error;
      }

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

L
Liu Jicong 已提交
2639
      SSDataBlock*         pRes = pExchangeInfo->pResult;
H
Haojun Liao 已提交
2640
      SLoadRemoteDataInfo* pLoadInfo = &pExchangeInfo->loadInfo;
2641
      if (pRsp->numOfRows == 0) {
L
Liu Jicong 已提交
2642 2643
        qDebug("%s vgId:%d, taskID:0x%" PRIx64 " index:%d completed, rowsOfSource:%" PRIu64 ", totalRows:%" PRIu64
               " try next",
2644
               GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->taskId, i + 1, pDataInfo->totalRows,
H
Haojun Liao 已提交
2645
               pExchangeInfo->loadInfo.totalRows);
2646
        pDataInfo->status = EX_SOURCE_DATA_EXHAUSTED;
2647
        completed += 1;
D
dapan1121 已提交
2648
        taosMemoryFreeClear(pDataInfo->pRsp);
2649 2650
        continue;
      }
H
Haojun Liao 已提交
2651

H
Haojun Liao 已提交
2652
      SRetrieveTableRsp* pTableRsp = pDataInfo->pRsp;
2653
      code = setDataBlockFromFetchRsp(pExchangeInfo->pResult, pLoadInfo, pTableRsp->numOfRows, pTableRsp->data,
X
Xiaoyu Wang 已提交
2654
                                      pTableRsp->compLen, pTableRsp->numOfCols, startTs, &pDataInfo->totalRows, NULL);
2655
      if (code != 0) {
2656
        taosMemoryFreeClear(pDataInfo->pRsp);
2657 2658 2659
        goto _error;
      }

2660 2661 2662
      if (pRsp->completed == 1) {
        qDebug("%s fetch msg rsp from vgId:%d, taskId:0x%" PRIx64 " numOfRows:%d, rowsOfSource:%" PRIu64
               ", totalRows:%" PRIu64 ", totalBytes:%" PRIu64 " try next %d/%" PRIzu,
L
Liu Jicong 已提交
2663 2664
               GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->taskId, pRes->info.rows, pDataInfo->totalRows,
               pLoadInfo->totalRows, pLoadInfo->totalSize, i + 1, totalSources);
2665
        pDataInfo->status = EX_SOURCE_DATA_EXHAUSTED;
2666
      } else {
dengyihao's avatar
dengyihao 已提交
2667 2668
        qDebug("%s fetch msg rsp from vgId:%d, taskId:0x%" PRIx64 " numOfRows:%d, totalRows:%" PRIu64
               ", totalBytes:%" PRIu64,
H
Haojun Liao 已提交
2669 2670
               GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->taskId, pRes->info.rows, pLoadInfo->totalRows,
               pLoadInfo->totalSize);
2671 2672
      }

2673 2674
      taosMemoryFreeClear(pDataInfo->pRsp);

2675 2676
      if (pDataInfo->status != EX_SOURCE_DATA_EXHAUSTED) {
        pDataInfo->status = EX_SOURCE_DATA_NOT_READY;
2677 2678
        code = doSendFetchDataRequest(pExchangeInfo, pTaskInfo, i);
        if (code != TSDB_CODE_SUCCESS) {
2679
          taosMemoryFreeClear(pDataInfo->pRsp);
2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696
          goto _error;
        }
      }

      return pExchangeInfo->pResult;
    }

    if (completed == totalSources) {
      return setAllSourcesCompleted(pOperator, startTs);
    }
  }

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

L
Liu Jicong 已提交
2697 2698 2699
static int32_t prepareConcurrentlyLoad(SOperatorInfo* pOperator) {
  SExchangeInfo* pExchangeInfo = pOperator->info;
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
2700

L
Liu Jicong 已提交
2701
  size_t  totalSources = taosArrayGetSize(pExchangeInfo->pSources);
2702 2703 2704
  int64_t startTs = taosGetTimestampUs();

  // Asynchronously send all fetch requests to all sources.
L
Liu Jicong 已提交
2705
  for (int32_t i = 0; i < totalSources; ++i) {
2706 2707
    int32_t code = doSendFetchDataRequest(pExchangeInfo, pTaskInfo, i);
    if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
2708 2709
      pTaskInfo->code = code;
      return code;
2710 2711 2712 2713
    }
  }

  int64_t endTs = taosGetTimestampUs();
2714
  qDebug("%s send all fetch requests to %" PRIzu " sources completed, elapsed:%" PRId64, GET_TASKID(pTaskInfo),
L
Liu Jicong 已提交
2715
         totalSources, endTs - startTs);
2716 2717

  tsem_wait(&pExchangeInfo->ready);
2718
  pOperator->status = OP_RES_TO_RETURN;
H
Haojun Liao 已提交
2719
  pOperator->cost.openCost = taosGetTimestampUs() - startTs;
2720

H
Haojun Liao 已提交
2721
  return TSDB_CODE_SUCCESS;
2722 2723
}

L
Liu Jicong 已提交
2724 2725 2726
static SSDataBlock* seqLoadRemoteData(SOperatorInfo* pOperator) {
  SExchangeInfo* pExchangeInfo = pOperator->info;
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
2727

L
Liu Jicong 已提交
2728
  size_t  totalSources = taosArrayGetSize(pExchangeInfo->pSources);
2729
  int64_t startTs = taosGetTimestampUs();
2730

L
Liu Jicong 已提交
2731
  while (1) {
2732 2733
    if (pExchangeInfo->current >= totalSources) {
      return setAllSourcesCompleted(pOperator, startTs);
2734
    }
2735

2736 2737 2738
    doSendFetchDataRequest(pExchangeInfo, pTaskInfo, pExchangeInfo->current);
    tsem_wait(&pExchangeInfo->ready);

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

H
Haojun Liao 已提交
2742
    if (pDataInfo->code != TSDB_CODE_SUCCESS) {
dengyihao's avatar
dengyihao 已提交
2743 2744
      qError("%s vgId:%d, taskID:0x%" PRIx64 " error happens, code:%s", GET_TASKID(pTaskInfo), pSource->addr.nodeId,
             pSource->taskId, tstrerror(pDataInfo->code));
H
Haojun Liao 已提交
2745 2746 2747 2748
      pOperator->pTaskInfo->code = pDataInfo->code;
      return NULL;
    }

L
Liu Jicong 已提交
2749
    SRetrieveTableRsp*   pRsp = pDataInfo->pRsp;
H
Haojun Liao 已提交
2750
    SLoadRemoteDataInfo* pLoadInfo = &pExchangeInfo->loadInfo;
2751
    if (pRsp->numOfRows == 0) {
dengyihao's avatar
dengyihao 已提交
2752 2753
      qDebug("%s vgId:%d, taskID:0x%" PRIx64 " %d of total completed, rowsOfSource:%" PRIu64 ", totalRows:%" PRIu64
             " try next",
2754
             GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->taskId, pExchangeInfo->current + 1,
H
Haojun Liao 已提交
2755
             pDataInfo->totalRows, pLoadInfo->totalRows);
H
Haojun Liao 已提交
2756

2757
      pDataInfo->status = EX_SOURCE_DATA_EXHAUSTED;
2758
      pExchangeInfo->current += 1;
D
dapan1121 已提交
2759
      taosMemoryFreeClear(pDataInfo->pRsp);
2760 2761
      continue;
    }
H
Haojun Liao 已提交
2762

L
Liu Jicong 已提交
2763
    SSDataBlock*       pRes = pExchangeInfo->pResult;
H
Haojun Liao 已提交
2764
    SRetrieveTableRsp* pTableRsp = pDataInfo->pRsp;
L
Liu Jicong 已提交
2765
    int32_t            code =
2766
        setDataBlockFromFetchRsp(pExchangeInfo->pResult, pLoadInfo, pTableRsp->numOfRows, pTableRsp->data,
X
Xiaoyu Wang 已提交
2767
                                 pTableRsp->compLen, pTableRsp->numOfCols, startTs, &pDataInfo->totalRows, NULL);
2768 2769

    if (pRsp->completed == 1) {
H
Haojun Liao 已提交
2770
      qDebug("%s fetch msg rsp from vgId:%d, taskId:0x%" PRIx64 " numOfRows:%d, rowsOfSource:%" PRIu64
L
Liu Jicong 已提交
2771 2772 2773
             ", totalRows:%" PRIu64 ", totalBytes:%" PRIu64 " try next %d/%" PRIzu,
             GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->taskId, pRes->info.rows, pDataInfo->totalRows,
             pLoadInfo->totalRows, pLoadInfo->totalSize, pExchangeInfo->current + 1, totalSources);
2774

2775
      pDataInfo->status = EX_SOURCE_DATA_EXHAUSTED;
2776 2777
      pExchangeInfo->current += 1;
    } else {
L
Liu Jicong 已提交
2778 2779 2780 2781
      qDebug("%s fetch msg rsp from vgId:%d, taskId:0x%" PRIx64 " numOfRows:%d, totalRows:%" PRIu64
             ", totalBytes:%" PRIu64,
             GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->taskId, pRes->info.rows, pLoadInfo->totalRows,
             pLoadInfo->totalSize);
2782 2783
    }

2784
    pOperator->resultInfo.totalRows += pRes->info.rows;
2785
    taosMemoryFreeClear(pDataInfo->pRsp);
2786 2787
    return pExchangeInfo->pResult;
  }
2788 2789
}

L
Liu Jicong 已提交
2790
static int32_t prepareLoadRemoteData(SOperatorInfo* pOperator) {
2791
  if (OPTR_IS_OPENED(pOperator)) {
H
Haojun Liao 已提交
2792 2793 2794
    return TSDB_CODE_SUCCESS;
  }

2795 2796
  int64_t st = taosGetTimestampUs();

L
Liu Jicong 已提交
2797
  SExchangeInfo* pExchangeInfo = pOperator->info;
2798
  if (!pExchangeInfo->seqLoadData) {
H
Haojun Liao 已提交
2799 2800 2801 2802 2803 2804
    int32_t code = prepareConcurrentlyLoad(pOperator);
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }
  }

2805
  OPTR_SET_OPENED(pOperator);
2806
  pOperator->cost.openCost = (taosGetTimestampUs() - st) / 1000.0;
H
Haojun Liao 已提交
2807 2808 2809
  return TSDB_CODE_SUCCESS;
}

2810
static SSDataBlock* doLoadRemoteData(SOperatorInfo* pOperator) {
L
Liu Jicong 已提交
2811 2812
  SExchangeInfo* pExchangeInfo = pOperator->info;
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
2813

2814
  pTaskInfo->code = pOperator->fpSet._openFn(pOperator);
2815
  if (pTaskInfo->code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
2816 2817
    return NULL;
  }
2818

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

2822
  if (pOperator->status == OP_EXEC_DONE) {
L
Liu Jicong 已提交
2823 2824 2825
    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);
2826 2827 2828 2829 2830 2831
    return NULL;
  }

  if (pExchangeInfo->seqLoadData) {
    return seqLoadRemoteData(pOperator);
  } else {
2832
    return concurrentlyLoadRemoteDataImpl(pOperator, pExchangeInfo, pTaskInfo);
X
Xiaoyu Wang 已提交
2833
    //    return concurrentlyLoadRemoteData(pOperator);
2834
  }
H
Haojun Liao 已提交
2835
}
2836

H
Haojun Liao 已提交
2837
static int32_t initDataSource(int32_t numOfSources, SExchangeInfo* pInfo) {
2838
  pInfo->pSourceDataInfo = taosArrayInit(numOfSources, sizeof(SSourceDataInfo));
H
Haojun Liao 已提交
2839 2840
  if (pInfo->pSourceDataInfo == NULL) {
    return TSDB_CODE_OUT_OF_MEMORY;
2841 2842
  }

L
Liu Jicong 已提交
2843
  for (int32_t i = 0; i < numOfSources; ++i) {
2844
    SSourceDataInfo dataInfo = {0};
H
Haojun Liao 已提交
2845
    dataInfo.status = EX_SOURCE_DATA_NOT_READY;
L
Liu Jicong 已提交
2846 2847
    dataInfo.pEx = pInfo;
    dataInfo.index = i;
2848

H
Haojun Liao 已提交
2849 2850 2851 2852 2853 2854 2855 2856 2857 2858
    void* ret = taosArrayPush(pInfo->pSourceDataInfo, &dataInfo);
    if (ret == NULL) {
      taosArrayDestroy(pInfo->pSourceDataInfo);
      return TSDB_CODE_OUT_OF_MEMORY;
    }
  }

  return TSDB_CODE_SUCCESS;
}

2859 2860
static int32_t initExchangeOperator(SExchangePhysiNode* pExNode, SExchangeInfo* pInfo) {
  size_t numOfSources = LIST_LENGTH(pExNode->pSrcEndPoints);
H
Haojun Liao 已提交
2861

H
Haojun Liao 已提交
2862
  pInfo->pSources = taosArrayInit(numOfSources, sizeof(SDownstreamSourceNode));
H
Haojun Liao 已提交
2863 2864
  pInfo->pSourceDataInfo = taosArrayInit(numOfSources, sizeof(SSourceDataInfo));
  if (pInfo->pSourceDataInfo == NULL || pInfo->pSources == NULL) {
2865
    return TSDB_CODE_OUT_OF_MEMORY;
H
Haojun Liao 已提交
2866 2867
  }

L
Liu Jicong 已提交
2868
  for (int32_t i = 0; i < numOfSources; ++i) {
2869
    SNodeListNode* pNode = nodesListGetNode((SNodeList*)pExNode->pSrcEndPoints, i);
H
Haojun Liao 已提交
2870 2871
    taosArrayPush(pInfo->pSources, pNode);
  }
2872

2873 2874 2875 2876 2877 2878 2879
  return initDataSource(numOfSources, pInfo);
}

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 已提交
2880
    goto _error;
2881
  }
H
Haojun Liao 已提交
2882

2883 2884 2885 2886
  int32_t code = initExchangeOperator(pExNode, pInfo);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
2887

X
Xiaoyu Wang 已提交
2888
  pInfo->seqLoadData = false;
2889
  pInfo->pTransporter = pTransporter;
X
Xiaoyu Wang 已提交
2890
  pInfo->pResult = createResDataBlock(pExNode->node.pOutputDataBlockDesc);
2891
  tsem_init(&pInfo->ready, 0, 0);
2892

X
Xiaoyu Wang 已提交
2893
  pOperator->name = "ExchangeOperator";
X
Xiaoyu Wang 已提交
2894
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_EXCHANGE;
X
Xiaoyu Wang 已提交
2895 2896 2897 2898 2899
  pOperator->blocking = false;
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
  pOperator->numOfExprs = pInfo->pResult->info.numOfCols;
  pOperator->pTaskInfo = pTaskInfo;
2900

L
Liu Jicong 已提交
2901 2902
  pOperator->fpSet = createOperatorFpSet(prepareLoadRemoteData, doLoadRemoteData, NULL, NULL,
                                         destroyExchangeOperatorInfo, NULL, NULL, NULL);
2903
  return pOperator;
H
Haojun Liao 已提交
2904

L
Liu Jicong 已提交
2905
_error:
H
Haojun Liao 已提交
2906
  if (pInfo != NULL) {
2907
    destroyExchangeOperatorInfo(pInfo, LIST_LENGTH(pExNode->pSrcEndPoints));
H
Haojun Liao 已提交
2908 2909
  }

wafwerar's avatar
wafwerar 已提交
2910 2911
  taosMemoryFreeClear(pInfo);
  taosMemoryFreeClear(pOperator);
H
Haojun Liao 已提交
2912
  pTaskInfo->code = TSDB_CODE_OUT_OF_MEMORY;
H
Haojun Liao 已提交
2913
  return NULL;
2914 2915
}

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

2919
static void destroySortedMergeOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
2920
  SSortedMergeOperatorInfo* pInfo = (SSortedMergeOperatorInfo*)param;
H
Haojun Liao 已提交
2921
  taosArrayDestroy(pInfo->pSortInfo);
2922 2923 2924
  taosArrayDestroy(pInfo->groupInfo);

  if (pInfo->pSortHandle != NULL) {
H
Haojun Liao 已提交
2925
    tsortDestroySortHandle(pInfo->pSortHandle);
2926 2927
  }

H
Haojun Liao 已提交
2928
  blockDataDestroy(pInfo->binfo.pRes);
H
Haojun Liao 已提交
2929
  cleanupAggSup(&pInfo->aggSup);
2930
}
H
Haojun Liao 已提交
2931

L
Liu Jicong 已提交
2932
static bool needToMerge(SSDataBlock* pBlock, SArray* groupInfo, char** buf, int32_t rowIndex) {
2933 2934 2935 2936
  size_t size = taosArrayGetSize(groupInfo);
  if (size == 0) {
    return true;
  }
2937

2938 2939
  for (int32_t i = 0; i < size; ++i) {
    int32_t* index = taosArrayGet(groupInfo, i);
2940

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

2944 2945 2946
    if ((isNull && buf[i] != NULL) || (!isNull && buf[i] == NULL)) {
      return false;
    }
2947

2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960
    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;
      }
2961 2962 2963
    }
  }

2964
  return 0;
2965 2966
}

L
Liu Jicong 已提交
2967 2968 2969
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 已提交
2970
                                             //    pCtx[j].startRow = rowIndex;
2971 2972
  }

2973 2974
  for (int32_t j = 0; j < numOfExpr; ++j) {
    int32_t functionId = pCtx[j].functionId;
L
Liu Jicong 已提交
2975 2976 2977 2978 2979 2980 2981 2982 2983
    //    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]);
    //    }
2984
  }
2985
}
2986

L
Liu Jicong 已提交
2987 2988
static void doFinalizeResultImpl(SqlFunctionCtx* pCtx, int32_t numOfExpr) {
  for (int32_t j = 0; j < numOfExpr; ++j) {
2989 2990 2991 2992
    int32_t functionId = pCtx[j].functionId;
    //    if (functionId == FUNC_TAG_DUMMY || functionId == FUNC_TS_DUMMY) {
    //      continue;
    //    }
2993

2994 2995 2996 2997
    //    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 已提交
2998
    //    pCtx[j].fpSet.finalize(&pCtx[j]);
2999 3000
  }
}
3001

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

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

3009 3010 3011
    char* data = colDataGetData(pColInfo, rowIndex);
    memcpy(rowColData[i], data, colDataGetLength(pColInfo, rowIndex));
  }
3012

3013 3014
  return true;
}
3015

3016 3017
static void doMergeImpl(SOperatorInfo* pOperator, int32_t numOfExpr, SSDataBlock* pBlock) {
  SSortedMergeOperatorInfo* pInfo = pOperator->info;
3018

3019
  SqlFunctionCtx* pCtx = pInfo->binfo.pCtx;
L
Liu Jicong 已提交
3020
  for (int32_t i = 0; i < pBlock->info.numOfCols; ++i) {
X
Xiaoyu Wang 已提交
3021
    //    pCtx[i].size = 1;
3022
  }
3023

L
Liu Jicong 已提交
3024
  for (int32_t i = 0; i < pBlock->info.rows; ++i) {
3025 3026 3027 3028 3029 3030 3031 3032 3033
    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);
3034 3035
        int32_t numOfRows = getNumOfResult(pInfo->binfo.pCtx, pOperator->numOfExprs, NULL);
        //        setTagValueForMultipleRows(pCtx, pOperator->numOfExprs, numOfRows);
3036

3037
        // TODO check for available buffer;
H
Haojun Liao 已提交
3038

3039 3040 3041 3042 3043
        // next group info data
        pInfo->binfo.pRes->info.rows += numOfRows;
        for (int32_t j = 0; j < numOfExpr; ++j) {
          if (pCtx[j].functionId < 0) {
            continue;
3044
          }
3045

H
Haojun Liao 已提交
3046
          pCtx[j].fpSet.process(&pCtx[j]);
3047
        }
3048 3049 3050

        doMergeResultImpl(pInfo, pCtx, numOfExpr, i);
        pInfo->hasGroupVal = saveCurrentTuple(pInfo->groupVal, pInfo->groupInfo, pBlock, i);
H
Haojun Liao 已提交
3051
      }
3052 3053 3054 3055
    }
  }
}

3056 3057
static SSDataBlock* doMerge(SOperatorInfo* pOperator) {
  SSortedMergeOperatorInfo* pInfo = pOperator->info;
L
Liu Jicong 已提交
3058
  SSortHandle*              pHandle = pInfo->pSortHandle;
3059

3060
  SSDataBlock* pDataBlock = createOneDataBlock(pInfo->binfo.pRes, false);
3061
  blockDataEnsureCapacity(pDataBlock, pOperator->resultInfo.capacity);
3062

L
Liu Jicong 已提交
3063
  while (1) {
3064
    blockDataCleanup(pDataBlock);
3065
    while (1) {
H
Haojun Liao 已提交
3066
      STupleHandle* pTupleHandle = tsortNextTuple(pHandle);
3067 3068
      if (pTupleHandle == NULL) {
        break;
3069
      }
3070

3071 3072
      // build datablock for merge for one group
      appendOneRowToDataBlock(pDataBlock, pTupleHandle);
3073
      if (pDataBlock->info.rows >= pOperator->resultInfo.capacity) {
3074 3075
        break;
      }
3076
    }
3077

3078 3079 3080
    if (pDataBlock->info.rows == 0) {
      break;
    }
3081

3082
    setInputDataBlock(pOperator, pInfo->binfo.pCtx, pDataBlock, TSDB_ORDER_ASC, MAIN_SCAN, true);
L
Liu Jicong 已提交
3083 3084
    //  updateOutputBuf(&pInfo->binfo, &pAggInfo->bufCapacity, pBlock->info.rows * pAggInfo->resultRowFactor,
    //  pOperator->pRuntimeEnv, true);
3085
    doMergeImpl(pOperator, pOperator->numOfExprs, pDataBlock);
3086 3087
    // flush to tuple store, and after all data have been handled, return to upstream node or sink node
  }
3088

3089 3090 3091
  doFinalizeResultImpl(pInfo->binfo.pCtx, pOperator->numOfExprs);
  int32_t numOfRows = getNumOfResult(pInfo->binfo.pCtx, pOperator->numOfExprs, NULL);
  //        setTagValueForMultipleRows(pCtx, pOperator->numOfExprs, numOfRows);
3092

3093
  // TODO check for available buffer;
3094

3095 3096
  // next group info data
  pInfo->binfo.pRes->info.rows += numOfRows;
L
Liu Jicong 已提交
3097
  return (pInfo->binfo.pRes->info.rows > 0) ? pInfo->binfo.pRes : NULL;
3098
}
3099

3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161
SSDataBlock* getSortedMergeBlockData(SSortHandle* pHandle, SSDataBlock* pDataBlock, int32_t capacity, SArray* pColMatchInfo,
                                SSortedMergeOperatorInfo *pInfo) {
  blockDataCleanup(pDataBlock);

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

  blockDataEnsureCapacity(p, capacity);

  while (1) {
    STupleHandle* pTupleHandle = NULL;
    if (pInfo->prefetchedTuple == NULL) {
      pTupleHandle = tsortNextTuple(pHandle);
    } else {
      pTupleHandle = pInfo->prefetchedTuple;
      pInfo->groupId = tsortGetGroupId(pTupleHandle);
      pInfo->prefetchedTuple = NULL;
    }

    if (pTupleHandle == NULL) {
      break;
    }

    uint64_t tupleGroupId = tsortGetGroupId(pTupleHandle);
    if (!pInfo->hasGroupId) {
      pInfo->groupId = tupleGroupId;
      pInfo->hasGroupId = true;
      appendOneRowToDataBlock(p, pTupleHandle);
    } else if (pInfo->groupId == tupleGroupId) {
      appendOneRowToDataBlock(p, pTupleHandle);
    } else {
      pInfo->prefetchedTuple = pTupleHandle;
      break;
    }

    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);
      colDataAssign(pDst, pSrc, p->info.rows);
    }

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

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

3162
static SSDataBlock* doSortedMerge(SOperatorInfo* pOperator) {
3163 3164
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
3165 3166
  }

L
Liu Jicong 已提交
3167
  SExecTaskInfo*            pTaskInfo = pOperator->pTaskInfo;
3168
  SSortedMergeOperatorInfo* pInfo = pOperator->info;
H
Haojun Liao 已提交
3169
  if (pOperator->status == OP_RES_TO_RETURN) {
3170
    return getSortedMergeBlockData(pInfo->pSortHandle, pInfo->binfo.pRes, pOperator->resultInfo.capacity, NULL, pInfo);
3171 3172
  }

3173
  int32_t numOfBufPage = pInfo->sortBufSize / pInfo->bufPageSize;
dengyihao's avatar
dengyihao 已提交
3174 3175
  pInfo->pSortHandle = tsortCreateSortHandle(pInfo->pSortInfo, NULL, SORT_MULTISOURCE_MERGE, pInfo->bufPageSize,
                                             numOfBufPage, pInfo->binfo.pRes, "GET_TASKID(pTaskInfo)");
H
Haojun Liao 已提交
3176

3177
  tsortSetFetchRawDataFp(pInfo->pSortHandle, loadNextDataBlock, NULL, NULL);
3178

L
Liu Jicong 已提交
3179
  for (int32_t i = 0; i < pOperator->numOfDownstream; ++i) {
wmmhello's avatar
wmmhello 已提交
3180
    SSortSource* ps = taosMemoryCalloc(1, sizeof(SSortSource));
H
Haojun Liao 已提交
3181
    ps->param = pOperator->pDownstream[i];
H
Haojun Liao 已提交
3182
    tsortAddSource(pInfo->pSortHandle, ps);
3183 3184
  }

H
Haojun Liao 已提交
3185
  int32_t code = tsortOpen(pInfo->pSortHandle);
3186
  if (code != TSDB_CODE_SUCCESS) {
3187
    longjmp(pTaskInfo->env, terrno);
3188 3189
  }

H
Haojun Liao 已提交
3190
  pOperator->status = OP_RES_TO_RETURN;
3191
  return doMerge(pOperator);
3192
}
3193

L
Liu Jicong 已提交
3194 3195
static int32_t initGroupCol(SExprInfo* pExprInfo, int32_t numOfCols, SArray* pGroupInfo,
                            SSortedMergeOperatorInfo* pInfo) {
3196 3197
  if (pGroupInfo == NULL || taosArrayGetSize(pGroupInfo) == 0) {
    return 0;
H
Haojun Liao 已提交
3198 3199
  }

3200 3201 3202 3203 3204 3205 3206 3207
  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 已提交
3208 3209
  size_t numOfGroupCol = taosArrayGetSize(pInfo->groupInfo);
  for (int32_t i = 0; i < numOfGroupCol; ++i) {
3210
    SColumn* pCol = taosArrayGet(pGroupInfo, i);
L
Liu Jicong 已提交
3211
    for (int32_t j = 0; j < numOfCols; ++j) {
H
Haojun Liao 已提交
3212
      SExprInfo* pe = &pExprInfo[j];
3213
      if (pe->base.resSchema.slotId == pCol->colId) {
3214 3215
        taosArrayPush(plist, pCol);
        taosArrayPush(pInfo->groupInfo, &j);
H
Haojun Liao 已提交
3216
        len += pCol->bytes;
3217 3218
        break;
      }
H
Haojun Liao 已提交
3219 3220 3221
    }
  }

3222
  ASSERT(taosArrayGetSize(pGroupInfo) == taosArrayGetSize(plist));
H
Haojun Liao 已提交
3223

wafwerar's avatar
wafwerar 已提交
3224
  pInfo->groupVal = taosMemoryCalloc(1, (POINTER_BYTES * numOfGroupCol + len));
3225 3226 3227 3228
  if (pInfo->groupVal == NULL) {
    taosArrayDestroy(plist);
    return TSDB_CODE_OUT_OF_MEMORY;
  }
H
Haojun Liao 已提交
3229

3230
  int32_t offset = 0;
L
Liu Jicong 已提交
3231 3232
  char*   start = (char*)(pInfo->groupVal + (POINTER_BYTES * numOfGroupCol));
  for (int32_t i = 0; i < numOfGroupCol; ++i) {
3233 3234
    pInfo->groupVal[i] = start + offset;
    SColumn* pCol = taosArrayGet(plist, i);
H
Haojun Liao 已提交
3235
    offset += pCol->bytes;
3236
  }
H
Haojun Liao 已提交
3237

3238
  taosArrayDestroy(plist);
H
Haojun Liao 已提交
3239

3240 3241
  return TSDB_CODE_SUCCESS;
}
H
Haojun Liao 已提交
3242

L
Liu Jicong 已提交
3243 3244 3245
SOperatorInfo* createSortedMergeOperatorInfo(SOperatorInfo** downstream, int32_t numOfDownstream, SExprInfo* pExprInfo,
                                             int32_t num, SArray* pSortInfo, SArray* pGroupInfo,
                                             SExecTaskInfo* pTaskInfo) {
wafwerar's avatar
wafwerar 已提交
3246
  SSortedMergeOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SSortedMergeOperatorInfo));
L
Liu Jicong 已提交
3247
  SOperatorInfo*            pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
3248
  if (pInfo == NULL || pOperator == NULL) {
3249
    goto _error;
3250
  }
H
Haojun Liao 已提交
3251

3252
  pInfo->binfo.pCtx = createSqlFunctionCtx(pExprInfo, num, &pInfo->binfo.rowCellInfoOffset);
3253
  initResultRowInfo(&pInfo->binfo.resultRowInfo, (int32_t)1);
H
Haojun Liao 已提交
3254

3255 3256 3257
  if (pInfo->binfo.pCtx == NULL || pInfo->binfo.pRes == NULL) {
    goto _error;
  }
H
Haojun Liao 已提交
3258

dengyihao's avatar
dengyihao 已提交
3259
  size_t  keyBufSize = sizeof(int64_t) + sizeof(int64_t) + POINTER_BYTES;
3260
  int32_t code = doInitAggInfoSup(&pInfo->aggSup, pInfo->binfo.pCtx, num, keyBufSize, pTaskInfo->id.str);
3261 3262 3263
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
H
Haojun Liao 已提交
3264

H
Haojun Liao 已提交
3265
  setFunctionResultOutput(&pInfo->binfo, &pInfo->aggSup, MAIN_SCAN, num, pTaskInfo);
H
Haojun Liao 已提交
3266
  code = initGroupCol(pExprInfo, num, pGroupInfo, pInfo);
3267 3268 3269
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
H
Haojun Liao 已提交
3270

L
Liu Jicong 已提交
3271 3272 3273 3274 3275
  //  pInfo->resultRowFactor = (int32_t)(getRowNumForMultioutput(pRuntimeEnv->pQueryAttr,
  //      pRuntimeEnv->pQueryAttr->topBotQuery, false));
  pInfo->sortBufSize = 1024 * 16;  // 1MB
  pInfo->bufPageSize = 1024;
  pInfo->pSortInfo = pSortInfo;
H
Haojun Liao 已提交
3276

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

L
Liu Jicong 已提交
3279
  pOperator->name = "SortedMerge";
X
Xiaoyu Wang 已提交
3280
  // pOperator->operatorType = OP_SortedMerge;
3281
  pOperator->blocking = true;
L
Liu Jicong 已提交
3282 3283
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
3284
  pOperator->numOfExprs = num;
L
Liu Jicong 已提交
3285
  pOperator->pExpr = pExprInfo;
H
Haojun Liao 已提交
3286

L
Liu Jicong 已提交
3287
  pOperator->pTaskInfo = pTaskInfo;
H
Haojun Liao 已提交
3288

3289 3290
  pOperator->fpSet = createOperatorFpSet(operatorDummyOpenFn, doSortedMerge, NULL, NULL, destroySortedMergeOperatorInfo,
                                         NULL, NULL, NULL);
3291 3292 3293
  code = appendDownstream(pOperator, downstream, numOfDownstream);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
3294
  }
H
Haojun Liao 已提交
3295

3296
  return pOperator;
H
Haojun Liao 已提交
3297

L
Liu Jicong 已提交
3298
_error:
3299
  if (pInfo != NULL) {
H
Haojun Liao 已提交
3300
    destroySortedMergeOperatorInfo(pInfo, num);
H
Haojun Liao 已提交
3301 3302
  }

wafwerar's avatar
wafwerar 已提交
3303 3304
  taosMemoryFreeClear(pInfo);
  taosMemoryFreeClear(pOperator);
3305 3306
  terrno = TSDB_CODE_QRY_OUT_OF_MEMORY;
  return NULL;
H
Haojun Liao 已提交
3307 3308
}

X
Xiaoyu Wang 已提交
3309
int32_t getTableScanInfo(SOperatorInfo* pOperator, int32_t* order, int32_t* scanFlag) {
3310
  // todo add more information about exchange operation
3311
  int32_t type = pOperator->operatorType;
X
Xiaoyu Wang 已提交
3312
  if (type == QUERY_NODE_PHYSICAL_PLAN_EXCHANGE || type == QUERY_NODE_PHYSICAL_PLAN_SYSTABLE_SCAN ||
3313
      type == QUERY_NODE_PHYSICAL_PLAN_STREAM_SCAN || type == QUERY_NODE_PHYSICAL_PLAN_TAG_SCAN) {
3314 3315 3316
    *order = TSDB_ORDER_ASC;
    *scanFlag = MAIN_SCAN;
    return TSDB_CODE_SUCCESS;
3317
  } else if (type == QUERY_NODE_PHYSICAL_PLAN_TABLE_SCAN) {
3318 3319 3320 3321 3322
    STableScanInfo* pTableScanInfo = pOperator->info;
    *order = pTableScanInfo->cond.order;
    *scanFlag = pTableScanInfo->scanFlag;
    return TSDB_CODE_SUCCESS;
  } else {
H
Haojun Liao 已提交
3323
    if (pOperator->pDownstream == NULL || pOperator->pDownstream[0] == NULL) {
3324
      return TSDB_CODE_INVALID_PARA;
H
Haojun Liao 已提交
3325
    } else {
3326
      return getTableScanInfo(pOperator->pDownstream[0], order, scanFlag);
3327 3328 3329
    }
  }
}
3330 3331

// this is a blocking operator
L
Liu Jicong 已提交
3332
static int32_t doOpenAggregateOptr(SOperatorInfo* pOperator) {
H
Haojun Liao 已提交
3333 3334
  if (OPTR_IS_OPENED(pOperator)) {
    return TSDB_CODE_SUCCESS;
3335 3336
  }

H
Haojun Liao 已提交
3337
  SExecTaskInfo*    pTaskInfo = pOperator->pTaskInfo;
3338
  SAggOperatorInfo* pAggInfo = pOperator->info;
H
Haojun Liao 已提交
3339

dengyihao's avatar
dengyihao 已提交
3340
  SOptrBasicInfo* pInfo = &pAggInfo->binfo;
X
Xiaoyu Wang 已提交
3341
  SOperatorInfo*  downstream = pOperator->pDownstream[0];
3342

3343 3344
  int64_t st = taosGetTimestampUs();

3345 3346 3347
  int32_t order = TSDB_ORDER_ASC;
  int32_t scanFlag = MAIN_SCAN;

H
Haojun Liao 已提交
3348
  while (1) {
3349
    SSDataBlock* pBlock = downstream->fpSet.getNextFn(downstream);
3350 3351 3352 3353
    if (pBlock == NULL) {
      break;
    }

3354 3355 3356 3357
    int32_t code = getTableScanInfo(pOperator, &order, &scanFlag);
    if (code != TSDB_CODE_SUCCESS) {
      longjmp(pTaskInfo->env, code);
    }
3358

3359 3360
    // there is an scalar expression that needs to be calculated before apply the group aggregation.
    if (pAggInfo->pScalarExprInfo != NULL) {
3361
      code = projectApplyFunctions(pAggInfo->pScalarExprInfo, pBlock, pBlock, pAggInfo->pScalarCtx,
3362
                                   pAggInfo->numOfScalarExpr, NULL);
3363
      if (code != TSDB_CODE_SUCCESS) {
3364
        longjmp(pTaskInfo->env, code);
3365
      }
3366 3367
    }

3368
    // the pDataBlock are always the same one, no need to call this again
3369
    setExecutionContext(pOperator->numOfExprs, pBlock->info.groupId, pTaskInfo, pAggInfo);
3370
    setInputDataBlock(pOperator, pInfo->pCtx, pBlock, order, scanFlag, true);
3371 3372 3373 3374
    code = doAggregateImpl(pOperator, 0, pInfo->pCtx);
    if (code != 0) {
      longjmp(pTaskInfo->env, code);
    }
3375

dengyihao's avatar
dengyihao 已提交
3376
#if 0  // test for encode/decode result info
3377
    if(pOperator->fpSet.encodeResultRow){
3378 3379
      char *result = NULL;
      int32_t length = 0;
3380 3381
      pOperator->fpSet.encodeResultRow(pOperator, &result, &length);
      SAggSupporter* pSup = &pAggInfo->aggSup;
3382 3383
      taosHashClear(pSup->pResultRowHashTable);
      pInfo->resultRowInfo.size = 0;
3384
      pOperator->fpSet.decodeResultRow(pOperator, result);
3385 3386 3387
      if(result){
        taosMemoryFree(result);
      }
3388
    }
3389
#endif
3390 3391
  }

H
Haojun Liao 已提交
3392
  closeAllResultRows(&pAggInfo->binfo.resultRowInfo);
3393
  initGroupedResultInfo(&pAggInfo->groupResInfo, pAggInfo->aggSup.pResultRowHashTable, 0);
H
Haojun Liao 已提交
3394
  OPTR_SET_OPENED(pOperator);
3395

3396
  pOperator->cost.openCost = (taosGetTimestampUs() - st) / 1000.0;
H
Haojun Liao 已提交
3397 3398 3399
  return TSDB_CODE_SUCCESS;
}

3400
static SSDataBlock* getAggregateResult(SOperatorInfo* pOperator) {
L
Liu Jicong 已提交
3401
  SAggOperatorInfo* pAggInfo = pOperator->info;
H
Haojun Liao 已提交
3402 3403 3404 3405 3406 3407
  SOptrBasicInfo*   pInfo = &pAggInfo->binfo;

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

L
Liu Jicong 已提交
3408
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
3409
  pTaskInfo->code = pOperator->fpSet._openFn(pOperator);
H
Haojun Liao 已提交
3410
  if (pTaskInfo->code != TSDB_CODE_SUCCESS) {
3411
    doSetOperatorCompleted(pOperator);
H
Haojun Liao 已提交
3412 3413 3414
    return NULL;
  }

H
Haojun Liao 已提交
3415
  blockDataEnsureCapacity(pInfo->pRes, pOperator->resultInfo.capacity);
3416
  doBuildResultDatablock(pOperator, pInfo, &pAggInfo->groupResInfo, pAggInfo->aggSup.pResultBuf);
3417
  if (pInfo->pRes->info.rows == 0 || !hashRemainDataInGroupInfo(&pAggInfo->groupResInfo)) {
H
Haojun Liao 已提交
3418 3419
    doSetOperatorCompleted(pOperator);
  }
3420

3421
  size_t rows = blockDataGetNumOfRows(pInfo->pRes);  // pInfo->pRes : NULL;
3422 3423
  pOperator->resultInfo.totalRows += rows;

3424
  return (rows == 0) ? NULL : pInfo->pRes;
3425 3426
}

wmmhello's avatar
wmmhello 已提交
3427
int32_t aggEncodeResultRow(SOperatorInfo* pOperator, char** result, int32_t* length) {
3428
  if (result == NULL || length == NULL) {
wmmhello's avatar
wmmhello 已提交
3429 3430 3431
    return TSDB_CODE_TSC_INVALID_INPUT;
  }
  SOptrBasicInfo* pInfo = (SOptrBasicInfo*)(pOperator->info);
3432 3433 3434 3435 3436
  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 已提交
3437

wmmhello's avatar
wmmhello 已提交
3438
  *result = (char*)taosMemoryCalloc(1, totalSize);
L
Liu Jicong 已提交
3439
  if (*result == NULL) {
wmmhello's avatar
wmmhello 已提交
3440
    return TSDB_CODE_OUT_OF_MEMORY;
wmmhello's avatar
wmmhello 已提交
3441
  }
wmmhello's avatar
wmmhello 已提交
3442

wmmhello's avatar
wmmhello 已提交
3443
  int32_t offset = sizeof(int32_t);
wmmhello's avatar
wmmhello 已提交
3444 3445
  *(int32_t*)(*result + offset) = size;
  offset += sizeof(int32_t);
3446 3447

  // prepare memory
3448
  SResultRowPosition* pos = &pInfo->resultRowInfo.cur;
dengyihao's avatar
dengyihao 已提交
3449 3450
  void*               pPage = getBufPage(pSup->pResultBuf, pos->pageId);
  SResultRow*         pRow = (SResultRow*)((char*)pPage + pos->offset);
3451 3452 3453
  setBufPageDirty(pPage, true);
  releaseBufPage(pSup->pResultBuf, pPage);

dengyihao's avatar
dengyihao 已提交
3454
  void* pIter = taosHashIterate(pSup->pResultRowHashTable, NULL);
wmmhello's avatar
wmmhello 已提交
3455
  while (pIter) {
dengyihao's avatar
dengyihao 已提交
3456
    void*               key = taosHashGetKey(pIter, &keyLen);
3457
    SResultRowPosition* p1 = (SResultRowPosition*)pIter;
3458

dengyihao's avatar
dengyihao 已提交
3459
    pPage = (SFilePage*)getBufPage(pSup->pResultBuf, p1->pageId);
3460
    pRow = (SResultRow*)((char*)pPage + p1->offset);
3461 3462
    setBufPageDirty(pPage, true);
    releaseBufPage(pSup->pResultBuf, pPage);
wmmhello's avatar
wmmhello 已提交
3463 3464 3465

    // recalculate the result size
    int32_t realTotalSize = offset + sizeof(int32_t) + keyLen + sizeof(int32_t) + pSup->resultRowSize;
L
Liu Jicong 已提交
3466
    if (realTotalSize > totalSize) {
wmmhello's avatar
wmmhello 已提交
3467
      char* tmp = (char*)taosMemoryRealloc(*result, realTotalSize);
L
Liu Jicong 已提交
3468
      if (tmp == NULL) {
wafwerar's avatar
wafwerar 已提交
3469
        taosMemoryFree(*result);
wmmhello's avatar
wmmhello 已提交
3470
        *result = NULL;
wmmhello's avatar
wmmhello 已提交
3471
        return TSDB_CODE_OUT_OF_MEMORY;
L
Liu Jicong 已提交
3472
      } else {
wmmhello's avatar
wmmhello 已提交
3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484
        *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);
3485
    memcpy(*result + offset, pRow, pSup->resultRowSize);
wmmhello's avatar
wmmhello 已提交
3486 3487 3488 3489 3490
    offset += pSup->resultRowSize;

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

wmmhello's avatar
wmmhello 已提交
3491 3492 3493 3494
  *(int32_t*)(*result) = offset;
  *length = offset;

  return TDB_CODE_SUCCESS;
wmmhello's avatar
wmmhello 已提交
3495 3496
}

3497
int32_t aggDecodeResultRow(SOperatorInfo* pOperator, char* result) {
3498
  if (result == NULL) {
wmmhello's avatar
wmmhello 已提交
3499
    return TSDB_CODE_TSC_INVALID_INPUT;
wmmhello's avatar
wmmhello 已提交
3500
  }
wmmhello's avatar
wmmhello 已提交
3501
  SOptrBasicInfo* pInfo = (SOptrBasicInfo*)(pOperator->info);
3502
  SAggSupporter*  pSup = (SAggSupporter*)POINTER_SHIFT(pOperator->info, sizeof(SOptrBasicInfo));
wmmhello's avatar
wmmhello 已提交
3503 3504

  //  int32_t size = taosHashGetSize(pSup->pResultRowHashTable);
3505
  int32_t length = *(int32_t*)(result);
wmmhello's avatar
wmmhello 已提交
3506
  int32_t offset = sizeof(int32_t);
3507 3508 3509 3510

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

L
Liu Jicong 已提交
3511
  while (count-- > 0 && length > offset) {
wmmhello's avatar
wmmhello 已提交
3512 3513 3514
    int32_t keyLen = *(int32_t*)(result + offset);
    offset += sizeof(int32_t);

L
Liu Jicong 已提交
3515
    uint64_t    tableGroupId = *(uint64_t*)(result + offset);
3516
    SResultRow* resultRow = getNewResultRow(pSup->pResultBuf, tableGroupId, pSup->resultRowSize);
L
Liu Jicong 已提交
3517
    if (!resultRow) {
wmmhello's avatar
wmmhello 已提交
3518
      return TSDB_CODE_TSC_INVALID_INPUT;
wmmhello's avatar
wmmhello 已提交
3519
    }
3520

wmmhello's avatar
wmmhello 已提交
3521
    // add a new result set for a new group
3522 3523
    SResultRowPosition pos = {.pageId = resultRow->pageId, .offset = resultRow->offset};
    taosHashPut(pSup->pResultRowHashTable, result + offset, keyLen, &pos, sizeof(SResultRowPosition));
wmmhello's avatar
wmmhello 已提交
3524 3525 3526

    offset += keyLen;
    int32_t valueLen = *(int32_t*)(result + offset);
L
Liu Jicong 已提交
3527
    if (valueLen != pSup->resultRowSize) {
wmmhello's avatar
wmmhello 已提交
3528
      return TSDB_CODE_TSC_INVALID_INPUT;
wmmhello's avatar
wmmhello 已提交
3529 3530 3531 3532 3533 3534 3535 3536 3537 3538
    }
    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 已提交
3539
    pInfo->resultRowInfo.cur = (SResultRowPosition){.pageId = resultRow->pageId, .offset = resultRow->offset};
wmmhello's avatar
wmmhello 已提交
3540 3541
  }

L
Liu Jicong 已提交
3542
  if (offset != length) {
wmmhello's avatar
wmmhello 已提交
3543
    return TSDB_CODE_TSC_INVALID_INPUT;
wmmhello's avatar
wmmhello 已提交
3544
  }
wmmhello's avatar
wmmhello 已提交
3545
  return TDB_CODE_SUCCESS;
wmmhello's avatar
wmmhello 已提交
3546 3547
}

3548 3549
enum {
  PROJECT_RETRIEVE_CONTINUE = 0x1,
L
Liu Jicong 已提交
3550
  PROJECT_RETRIEVE_DONE = 0x2,
3551 3552 3553 3554 3555
};

static int32_t handleLimitOffset(SOperatorInfo* pOperator, SSDataBlock* pBlock) {
  SProjectOperatorInfo* pProjectInfo = pOperator->info;
  SOptrBasicInfo*       pInfo = &pProjectInfo->binfo;
L
Liu Jicong 已提交
3556
  SSDataBlock*          pRes = pInfo->pRes;
3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604

  if (pProjectInfo->curSOffset > 0) {
    if (pProjectInfo->groupId == 0) {  // it is the first group
      pProjectInfo->groupId = pBlock->info.groupId;
      blockDataCleanup(pInfo->pRes);
      return PROJECT_RETRIEVE_CONTINUE;
    } else if (pProjectInfo->groupId != pBlock->info.groupId) {
      pProjectInfo->curSOffset -= 1;

      // ignore data block in current group
      if (pProjectInfo->curSOffset > 0) {
        blockDataCleanup(pInfo->pRes);
        return PROJECT_RETRIEVE_CONTINUE;
      }
    }

    // set current group id of the project operator
    pProjectInfo->groupId = pBlock->info.groupId;
  }

  if (pProjectInfo->groupId != 0 && pProjectInfo->groupId != pBlock->info.groupId) {
    pProjectInfo->curGroupOutput += 1;
    if ((pProjectInfo->slimit.limit > 0) && (pProjectInfo->slimit.limit <= pProjectInfo->curGroupOutput)) {
      pOperator->status = OP_EXEC_DONE;
      blockDataCleanup(pRes);

      return PROJECT_RETRIEVE_DONE;
    }

    // reset the value for a new group data
    pProjectInfo->curOffset = 0;
    pProjectInfo->curOutput = 0;
  }

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

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

  if (pProjectInfo->curOffset >= pRes->info.rows) {
    pProjectInfo->curOffset -= pRes->info.rows;
    blockDataCleanup(pRes);
    return PROJECT_RETRIEVE_CONTINUE;
  } else if (pProjectInfo->curOffset < pRes->info.rows && pProjectInfo->curOffset > 0) {
    blockDataTrimFirstNRows(pRes, pProjectInfo->curOffset);
    pProjectInfo->curOffset = 0;
  }

3605 3606 3607
  // check for the limitation in each group
  if (pProjectInfo->limit.limit > 0 && pProjectInfo->curOutput + pRes->info.rows >= pProjectInfo->limit.limit) {
    pRes->info.rows = (int32_t)(pProjectInfo->limit.limit - pProjectInfo->curOutput);
3608 3609 3610 3611 3612

    if (pProjectInfo->slimit.limit == -1 || pProjectInfo->slimit.limit <= pProjectInfo->curGroupOutput) {
      pOperator->status = OP_EXEC_DONE;
    }

3613
    return PROJECT_RETRIEVE_DONE;
3614
  }
3615

3616
  // todo optimize performance
3617 3618
  // 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.
L
Liu Jicong 已提交
3619 3620
  if (pRes->info.rows >= pOperator->resultInfo.threshold || pProjectInfo->slimit.offset != -1 ||
      pProjectInfo->slimit.limit != -1) {
3621
    return PROJECT_RETRIEVE_DONE;
L
Liu Jicong 已提交
3622
  } else {  // not full enough, continue to accumulate the output data in the buffer.
3623 3624 3625 3626
    return PROJECT_RETRIEVE_CONTINUE;
  }
}

3627
static SSDataBlock* doProjectOperation(SOperatorInfo* pOperator) {
3628
  SProjectOperatorInfo* pProjectInfo = pOperator->info;
L
Liu Jicong 已提交
3629
  SOptrBasicInfo*       pInfo = &pProjectInfo->binfo;
3630 3631

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

3634
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
3635 3636 3637
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }
dengyihao's avatar
dengyihao 已提交
3638

H
Haojun Liao 已提交
3639
#if 0
3640 3641 3642 3643 3644
  if (pProjectInfo->existDataBlock) {  // TODO refactor
    SSDataBlock* pBlock = pProjectInfo->existDataBlock;
    pProjectInfo->existDataBlock = NULL;

    // the pDataBlock are always the same one, no need to call this again
H
Haojun Liao 已提交
3645
    setInputDataBlock(pOperator, pInfo->pCtx, pBlock, TSDB_ORDER_ASC);
3646

H
Haojun Liao 已提交
3647
    blockDataEnsureCapacity(pInfo->pRes, pBlock->info.rows);
3648
    projectApplyFunctions(pOperator->pExpr, pInfo->pRes, pBlock, pInfo->pCtx, pOperator->numOfExprs);
L
Liu Jicong 已提交
3649
    if (pRes->info.rows >= pProjectInfo->binfo.capacity * 0.8) {
3650 3651
      copyTsColoum(pRes, pInfo->pCtx, pOperator->numOfExprs);
      resetResultRowEntryResult(pInfo->pCtx, pOperator->numOfExprs);
3652 3653 3654
      return pRes;
    }
  }
H
Haojun Liao 已提交
3655
#endif
3656

3657
  int64_t st = 0;
3658 3659 3660
  int32_t order = 0;
  int32_t scanFlag = 0;

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

H
Haojun Liao 已提交
3665 3666
  SOperatorInfo* downstream = pOperator->pDownstream[0];

L
Liu Jicong 已提交
3667
  while (1) {
H
Haojun Liao 已提交
3668
    // The downstream exec may change the value of the newgroup, so use a local variable instead.
3669
    SSDataBlock* pBlock = downstream->fpSet.getNextFn(downstream);
3670
    if (pBlock == NULL) {
3671
      doSetOperatorCompleted(pOperator);
3672 3673 3674 3675
      break;
    }

    // the pDataBlock are always the same one, no need to call this again
3676
    int32_t code = getTableScanInfo(pOperator->pDownstream[0], &order, &scanFlag);
3677 3678 3679
    if (code != TSDB_CODE_SUCCESS) {
      longjmp(pTaskInfo->env, code);
    }
3680

wmmhello's avatar
wmmhello 已提交
3681
    doFilter(pProjectInfo->pFilterNode, pBlock, true);
3682

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

X
Xiaoyu Wang 已提交
3686 3687
    code = projectApplyFunctions(pOperator->pExpr, pInfo->pRes, pBlock, pInfo->pCtx, pOperator->numOfExprs,
                                 pProjectInfo->pPseudoColInfo);
3688 3689
    if (code != TSDB_CODE_SUCCESS) {
      longjmp(pTaskInfo->env, code);
3690 3691
    }

3692 3693
    int32_t status = handleLimitOffset(pOperator, pBlock);
    if (status == PROJECT_RETRIEVE_CONTINUE) {
H
Haojun Liao 已提交
3694
      continue;
L
Liu Jicong 已提交
3695
    } else if (status == PROJECT_RETRIEVE_DONE) {
3696 3697 3698
      break;
    }
  }
dengyihao's avatar
dengyihao 已提交
3699

H
Haojun Liao 已提交
3700
  pProjectInfo->curOutput += pInfo->pRes->info.rows;
H
Haojun Liao 已提交
3701

3702 3703 3704 3705
  size_t rows = pInfo->pRes->info.rows;
  pOperator->resultInfo.totalRows += rows;

  if (pOperator->cost.openCost == 0) {
3706
    pOperator->cost.openCost = (taosGetTimestampUs() - st) / 1000.0;
3707 3708
  }

3709
  return (rows > 0) ? pInfo->pRes : NULL;
3710 3711
}

L
Liu Jicong 已提交
3712 3713
static void doHandleRemainBlockForNewGroupImpl(SFillOperatorInfo* pInfo, SResultInfo* pResultInfo, bool* newgroup,
                                               SExecTaskInfo* pTaskInfo) {
3714
  pInfo->totalInputRows = pInfo->existNewGroupBlock->info.rows;
H
Haojun Liao 已提交
3715

L
Liu Jicong 已提交
3716 3717
  int64_t ekey = Q_STATUS_EQUAL(pTaskInfo->status, TASK_COMPLETED) ? pTaskInfo->window.ekey
                                                                   : pInfo->existNewGroupBlock->info.window.ekey;
3718 3719
  taosResetFillInfo(pInfo->pFillInfo, getFillInfoStart(pInfo->pFillInfo));

3720
  taosFillSetStartInfo(pInfo->pFillInfo, pInfo->existNewGroupBlock->info.rows, ekey);
3721 3722
  taosFillSetInputDataBlock(pInfo->pFillInfo, pInfo->existNewGroupBlock);

3723
  doFillTimeIntervalGapsInResults(pInfo->pFillInfo, pInfo->pRes, pResultInfo->capacity);
3724 3725 3726 3727
  pInfo->existNewGroupBlock = NULL;
  *newgroup = true;
}

L
Liu Jicong 已提交
3728 3729
static void doHandleRemainBlockFromNewGroup(SFillOperatorInfo* pInfo, SResultInfo* pResultInfo, bool* newgroup,
                                            SExecTaskInfo* pTaskInfo) {
3730 3731
  if (taosFillHasMoreResults(pInfo->pFillInfo)) {
    *newgroup = false;
3732
    doFillTimeIntervalGapsInResults(pInfo->pFillInfo, pInfo->pRes, (int32_t)pResultInfo->capacity);
H
Haojun Liao 已提交
3733
    if (pInfo->pRes->info.rows > pResultInfo->threshold || (!pInfo->multigroupResult)) {
3734 3735 3736 3737 3738 3739
      return;
    }
  }

  // handle the cached new group data block
  if (pInfo->existNewGroupBlock) {
3740
    doHandleRemainBlockForNewGroupImpl(pInfo, pResultInfo, newgroup, pTaskInfo);
3741 3742 3743
  }
}

3744
static SSDataBlock* doFill(SOperatorInfo* pOperator) {
L
Liu Jicong 已提交
3745 3746
  SFillOperatorInfo* pInfo = pOperator->info;
  SExecTaskInfo*     pTaskInfo = pOperator->pTaskInfo;
3747

H
Haojun Liao 已提交
3748
  SResultInfo* pResultInfo = &pOperator->resultInfo;
3749 3750 3751
  SSDataBlock* pResBlock = pInfo->pRes;

  blockDataCleanup(pResBlock);
3752 3753 3754 3755
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

3756
  // todo handle different group data interpolation
X
Xiaoyu Wang 已提交
3757 3758
  bool  n = false;
  bool* newgroup = &n;
3759
  doHandleRemainBlockFromNewGroup(pInfo, pResultInfo, newgroup, pTaskInfo);
3760 3761
  if (pResBlock->info.rows > pResultInfo->threshold || (!pInfo->multigroupResult && pResBlock->info.rows > 0)) {
    return pResBlock;
H
Haojun Liao 已提交
3762
  }
3763

H
Haojun Liao 已提交
3764
  SOperatorInfo* pDownstream = pOperator->pDownstream[0];
L
Liu Jicong 已提交
3765
  while (1) {
3766
    SSDataBlock* pBlock = pDownstream->fpSet.getNextFn(pDownstream);
3767 3768 3769 3770 3771 3772 3773 3774 3775 3776
    if (*newgroup) {
      assert(pBlock != NULL);
    }

    if (*newgroup && pInfo->totalInputRows > 0) {  // there are already processed current group data block
      pInfo->existNewGroupBlock = pBlock;
      *newgroup = false;

      // Fill the previous group data block, before handle the data block of new group.
      // Close the fill operation for previous group data block
3777
      taosFillSetStartInfo(pInfo->pFillInfo, 0, pTaskInfo->window.ekey);
3778 3779 3780 3781 3782 3783 3784
    } else {
      if (pBlock == NULL) {
        if (pInfo->totalInputRows == 0) {
          pOperator->status = OP_EXEC_DONE;
          return NULL;
        }

3785
        taosFillSetStartInfo(pInfo->pFillInfo, 0, pTaskInfo->window.ekey);
3786 3787 3788 3789 3790 3791 3792
      } else {
        pInfo->totalInputRows += pBlock->info.rows;
        taosFillSetStartInfo(pInfo->pFillInfo, pBlock->info.rows, pBlock->info.window.ekey);
        taosFillSetInputDataBlock(pInfo->pFillInfo, pBlock);
      }
    }

3793 3794
    blockDataEnsureCapacity(pResBlock, pOperator->resultInfo.capacity);
    doFillTimeIntervalGapsInResults(pInfo->pFillInfo, pResBlock, pOperator->resultInfo.capacity);
3795 3796

    // current group has no more result to return
3797
    if (pResBlock->info.rows > 0) {
3798 3799
      // 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
3800 3801
      if (pResBlock->info.rows > pResultInfo->threshold || pBlock == NULL || (!pInfo->multigroupResult)) {
        return pResBlock;
3802 3803
      }

3804
      doHandleRemainBlockFromNewGroup(pInfo, pResultInfo, newgroup, pTaskInfo);
3805 3806
      if (pResBlock->info.rows > pOperator->resultInfo.threshold || pBlock == NULL) {
        return pResBlock;
3807 3808 3809
      }
    } else if (pInfo->existNewGroupBlock) {  // try next group
      assert(pBlock != NULL);
3810
      doHandleRemainBlockForNewGroupImpl(pInfo, pResultInfo, newgroup, pTaskInfo);
3811 3812
      if (pResBlock->info.rows > pResultInfo->threshold) {
        return pResBlock;
3813 3814 3815 3816 3817 3818 3819
      }
    } else {
      return NULL;
    }
  }
}

H
Haojun Liao 已提交
3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830
static void destroyExprInfo(SExprInfo* pExpr, int32_t numOfExprs) {
  for (int32_t i = 0; i < numOfExprs; ++i) {
    SExprInfo* pExprInfo = &pExpr[i];
    if (pExprInfo->pExpr->nodeType == QUERY_NODE_COLUMN) {
      taosMemoryFree(pExprInfo->base.pParam[0].pCol);
    }
    taosMemoryFree(pExprInfo->base.pParam);
    taosMemoryFree(pExprInfo->pExpr);
  }
}

3831 3832 3833 3834 3835
static void destroyOperatorInfo(SOperatorInfo* pOperator) {
  if (pOperator == NULL) {
    return;
  }

3836
  if (pOperator->fpSet.closeFn != NULL) {
3837
    pOperator->fpSet.closeFn(pOperator->info, pOperator->numOfExprs);
3838 3839
  }

H
Haojun Liao 已提交
3840
  if (pOperator->pDownstream != NULL) {
L
Liu Jicong 已提交
3841
    for (int32_t i = 0; i < pOperator->numOfDownstream; ++i) {
H
Haojun Liao 已提交
3842
      destroyOperatorInfo(pOperator->pDownstream[i]);
3843 3844
    }

wafwerar's avatar
wafwerar 已提交
3845
    taosMemoryFreeClear(pOperator->pDownstream);
H
Haojun Liao 已提交
3846
    pOperator->numOfDownstream = 0;
3847 3848
  }

H
Haojun Liao 已提交
3849
  if (pOperator->pExpr != NULL) {
H
Haojun Liao 已提交
3850
    destroyExprInfo(pOperator->pExpr, pOperator->numOfExprs);
H
Haojun Liao 已提交
3851 3852
  }

D
fix bug  
dapan 已提交
3853
  taosMemoryFreeClear(pOperator->pExpr);
wafwerar's avatar
wafwerar 已提交
3854 3855
  taosMemoryFreeClear(pOperator->info);
  taosMemoryFreeClear(pOperator);
3856 3857
}

3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872
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 已提交
3873 3874
int32_t doInitAggInfoSup(SAggSupporter* pAggSup, SqlFunctionCtx* pCtx, int32_t numOfOutput, size_t keyBufSize,
                         const char* pKey) {
3875 3876
  _hash_fn_t hashFn = taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY);

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

H
Haojun Liao 已提交
3881
  if (pAggSup->keyBuf == NULL || pAggSup->pResultRowHashTable == NULL) {
3882 3883 3884
    return TSDB_CODE_OUT_OF_MEMORY;
  }

dengyihao's avatar
dengyihao 已提交
3885
  uint32_t defaultPgsz = 0;
3886 3887
  uint32_t defaultBufsz = 0;
  getBufferPgSize(pAggSup->resultRowSize, &defaultPgsz, &defaultBufsz);
H
Haojun Liao 已提交
3888

3889
  int32_t code = createDiskbasedBuf(&pAggSup->pResultBuf, defaultPgsz, defaultBufsz, pKey, TD_TMP_DIR_PATH);
H
Haojun Liao 已提交
3890 3891 3892 3893
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

3894 3895 3896
  return TSDB_CODE_SUCCESS;
}

3897
void cleanupAggSup(SAggSupporter* pAggSup) {
wafwerar's avatar
wafwerar 已提交
3898
  taosMemoryFreeClear(pAggSup->keyBuf);
3899
  taosHashCleanup(pAggSup->pResultRowHashTable);
H
Haojun Liao 已提交
3900
  destroyDiskbasedBuf(pAggSup->pResultBuf);
3901 3902
}

H
Haojun Liao 已提交
3903
int32_t initAggInfo(SOptrBasicInfo* pBasicInfo, SAggSupporter* pAggSup, SExprInfo* pExprInfo, int32_t numOfCols,
3904
                    SSDataBlock* pResultBlock, size_t keyBufSize, const char* pkey) {
3905
  pBasicInfo->pCtx = createSqlFunctionCtx(pExprInfo, numOfCols, &pBasicInfo->rowCellInfoOffset);
H
Haojun Liao 已提交
3906 3907
  pBasicInfo->pRes = pResultBlock;

3908
  doInitAggInfoSup(pAggSup, pBasicInfo->pCtx, numOfCols, keyBufSize, pkey);
3909

L
Liu Jicong 已提交
3910
  for (int32_t i = 0; i < numOfCols; ++i) {
3911 3912 3913
    pBasicInfo->pCtx[i].pBuf = pAggSup->pResultBuf;
  }

3914
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
3915 3916
}

3917 3918 3919 3920 3921 3922 3923 3924 3925
void initResultSizeInfo(SOperatorInfo* pOperator, int32_t numOfRows) {
  pOperator->resultInfo.capacity = numOfRows;
  pOperator->resultInfo.threshold = numOfRows * 0.75;

  if (pOperator->resultInfo.threshold == 0) {
    pOperator->resultInfo.capacity = numOfRows;
  }
}

dengyihao's avatar
dengyihao 已提交
3926
// static STableQueryInfo* initTableQueryInfo(const STableListInfo* pTableListInfo) {
wmmhello's avatar
wmmhello 已提交
3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945
//  int32_t size = taosArrayGetSize(pTableListInfo->pTableList);
//  if (size == 0) {
//    return NULL;
//  }
//
//  STableQueryInfo* pTableQueryInfo = taosMemoryCalloc(size, sizeof(STableQueryInfo));
//  if (pTableQueryInfo == NULL) {
//    return NULL;
//  }
//
//  for (int32_t j = 0; j < size; ++j) {
//    STableKeyInfo*   pk = taosArrayGet(pTableListInfo->pTableList, j);
//    STableQueryInfo* pTQueryInfo = &pTableQueryInfo[j];
//    pTQueryInfo->lastKey = pk->lastKey;
//  }
//
//  pTableQueryInfo->lastKey = 0;
//  return pTableQueryInfo;
//}
H
Haojun Liao 已提交
3946

L
Liu Jicong 已提交
3947
SOperatorInfo* createAggregateOperatorInfo(SOperatorInfo* downstream, SExprInfo* pExprInfo, int32_t numOfCols,
3948
                                           SSDataBlock* pResultBlock, SExprInfo* pScalarExprInfo,
wmmhello's avatar
wmmhello 已提交
3949
                                           int32_t numOfScalarExpr, SExecTaskInfo* pTaskInfo) {
wafwerar's avatar
wafwerar 已提交
3950
  SAggOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SAggOperatorInfo));
L
Liu Jicong 已提交
3951
  SOperatorInfo*    pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
3952 3953 3954
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }
H
Haojun Liao 已提交
3955

3956
  int32_t numOfRows = 1024;
dengyihao's avatar
dengyihao 已提交
3957
  size_t  keyBufSize = sizeof(int64_t) + sizeof(int64_t) + POINTER_BYTES;
3958 3959

  initResultSizeInfo(pOperator, numOfRows);
dengyihao's avatar
dengyihao 已提交
3960 3961
  int32_t code =
      initAggInfo(&pInfo->binfo, &pInfo->aggSup, pExprInfo, numOfCols, pResultBlock, keyBufSize, pTaskInfo->id.str);
L
Liu Jicong 已提交
3962
  if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
3963 3964
    goto _error;
  }
H
Haojun Liao 已提交
3965

H
Haojun Liao 已提交
3966 3967 3968 3969
  int32_t numOfGroup = 10;  // todo replaced with true value
  pInfo->groupId = INT32_MIN;
  initResultRowInfo(&pInfo->binfo.resultRowInfo, numOfGroup);

3970 3971
  pInfo->pScalarExprInfo = pScalarExprInfo;
  pInfo->numOfScalarExpr = numOfScalarExpr;
3972
  if (pInfo->pScalarExprInfo != NULL) {
3973
    pInfo->pScalarCtx = createSqlFunctionCtx(pScalarExprInfo, numOfScalarExpr, &pInfo->rowCellInfoOffset);
3974
  }
3975

dengyihao's avatar
dengyihao 已提交
3976
  pOperator->name = "TableAggregate";
3977
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_HASH_AGG;
3978
  pOperator->blocking = true;
dengyihao's avatar
dengyihao 已提交
3979 3980 3981
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
  pOperator->pExpr = pExprInfo;
3982
  pOperator->numOfExprs = numOfCols;
dengyihao's avatar
dengyihao 已提交
3983
  pOperator->pTaskInfo = pTaskInfo;
H
Haojun Liao 已提交
3984

3985 3986
  pOperator->fpSet = createOperatorFpSet(doOpenAggregateOptr, getAggregateResult, NULL, NULL, destroyAggOperatorInfo,
                                         aggEncodeResultRow, aggDecodeResultRow, NULL);
H
Haojun Liao 已提交
3987 3988 3989 3990 3991

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

  return pOperator;
L
Liu Jicong 已提交
3994
_error:
H
Haojun Liao 已提交
3995
  destroyAggOperatorInfo(pInfo, numOfCols);
wafwerar's avatar
wafwerar 已提交
3996 3997
  taosMemoryFreeClear(pInfo);
  taosMemoryFreeClear(pOperator);
H
Haojun Liao 已提交
3998 3999
  pTaskInfo->code = TSDB_CODE_OUT_OF_MEMORY;
  return NULL;
4000 4001
}

H
Haojun Liao 已提交
4002
void doDestroyBasicInfo(SOptrBasicInfo* pInfo, int32_t numOfOutput) {
4003 4004
  assert(pInfo != NULL);

4005
  destroySqlFunctionCtx(pInfo->pCtx, numOfOutput);
wafwerar's avatar
wafwerar 已提交
4006
  taosMemoryFreeClear(pInfo->rowCellInfoOffset);
4007 4008

  cleanupResultRowInfo(&pInfo->resultRowInfo);
H
Haojun Liao 已提交
4009
  pInfo->pRes = blockDataDestroy(pInfo->pRes);
4010 4011
}

H
Haojun Liao 已提交
4012
void destroyBasicOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
4013
  SOptrBasicInfo* pInfo = (SOptrBasicInfo*)param;
4014 4015
  doDestroyBasicInfo(pInfo, numOfOutput);
}
H
Haojun Liao 已提交
4016 4017

void destroyAggOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
4018
  SAggOperatorInfo* pInfo = (SAggOperatorInfo*)param;
4019 4020
  doDestroyBasicInfo(&pInfo->binfo, numOfOutput);
}
4021

H
Haojun Liao 已提交
4022
void destroySFillOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
4023
  SFillOperatorInfo* pInfo = (SFillOperatorInfo*)param;
4024
  pInfo->pFillInfo = taosDestroyFillInfo(pInfo->pFillInfo);
H
Haojun Liao 已提交
4025
  pInfo->pRes = blockDataDestroy(pInfo->pRes);
wafwerar's avatar
wafwerar 已提交
4026
  taosMemoryFreeClear(pInfo->p);
4027 4028
}

H
Haojun Liao 已提交
4029
static void destroyProjectOperatorInfo(void* param, int32_t numOfOutput) {
D
fix bug  
dapan 已提交
4030 4031 4032
  if (NULL == param) {
    return;
  }
L
Liu Jicong 已提交
4033
  SProjectOperatorInfo* pInfo = (SProjectOperatorInfo*)param;
4034
  doDestroyBasicInfo(&pInfo->binfo, numOfOutput);
H
Haojun Liao 已提交
4035
  cleanupAggSup(&pInfo->aggSup);
H
Haojun Liao 已提交
4036
  taosArrayDestroy(pInfo->pPseudoColInfo);
4037 4038
}

H
Haojun Liao 已提交
4039
static void destroyIndefinitOperatorInfo(void* param, int32_t numOfOutput) {
4040
  SIndefOperatorInfo* pInfo = (SIndefOperatorInfo*)param;
H
Haojun Liao 已提交
4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051
  doDestroyBasicInfo(&pInfo->binfo, numOfOutput);

  taosArrayDestroy(pInfo->pPseudoColInfo);
  cleanupAggSup(&pInfo->aggSup);

  destroySqlFunctionCtx(pInfo->pScalarCtx, numOfOutput);
  destroyExprInfo(pInfo->pScalarExpr, pInfo->numOfScalarExpr);

  taosMemoryFree(pInfo->rowCellInfoOffset);
}

H
Haojun Liao 已提交
4052
void destroyExchangeOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
4053
  SExchangeInfo* pExInfo = (SExchangeInfo*)param;
H
Haojun Liao 已提交
4054 4055 4056 4057 4058 4059 4060 4061 4062
  taosArrayDestroy(pExInfo->pSources);
  taosArrayDestroy(pExInfo->pSourceDataInfo);
  if (pExInfo->pResult != NULL) {
    blockDataDestroy(pExInfo->pResult);
  }

  tsem_destroy(&pExInfo->ready);
}

H
Haojun Liao 已提交
4063 4064
static SArray* setRowTsColumnOutputInfo(SqlFunctionCtx* pCtx, int32_t numOfCols) {
  SArray* pList = taosArrayInit(4, sizeof(int32_t));
dengyihao's avatar
dengyihao 已提交
4065
  for (int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
4066 4067 4068 4069 4070 4071 4072 4073
    if (fmIsPseudoColumnFunc(pCtx[i].functionId)) {
      taosArrayPush(pList, &i);
    }
  }

  return pList;
}

L
Liu Jicong 已提交
4074
SOperatorInfo* createProjectOperatorInfo(SOperatorInfo* downstream, SExprInfo* pExprInfo, int32_t num,
4075
                                         SSDataBlock* pResBlock, SLimit* pLimit, SLimit* pSlimit, SNode* pCondition,
dengyihao's avatar
dengyihao 已提交
4076
                                         SExecTaskInfo* pTaskInfo) {
wafwerar's avatar
wafwerar 已提交
4077
  SProjectOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SProjectOperatorInfo));
L
Liu Jicong 已提交
4078
  SOperatorInfo*        pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
4079 4080 4081
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }
4082

X
Xiaoyu Wang 已提交
4083 4084 4085
  pInfo->limit = *pLimit;
  pInfo->slimit = *pSlimit;
  pInfo->curOffset = pLimit->offset;
H
Haojun Liao 已提交
4086
  pInfo->curSOffset = pSlimit->offset;
H
Haojun Liao 已提交
4087
  pInfo->binfo.pRes = pResBlock;
X
Xiaoyu Wang 已提交
4088
  pInfo->pFilterNode = pCondition;
H
Haojun Liao 已提交
4089 4090 4091

  int32_t numOfCols = num;
  int32_t numOfRows = 4096;
dengyihao's avatar
dengyihao 已提交
4092
  size_t  keyBufSize = sizeof(int64_t) + sizeof(int64_t) + POINTER_BYTES;
4093

4094 4095 4096 4097 4098
  // Make sure the size of SSDataBlock will never exceed the size of 2MB.
  int32_t TWOMB = 2 * 1024 * 1024;
  if (numOfRows * pResBlock->info.rowSize > TWOMB) {
    numOfRows = TWOMB / pResBlock->info.rowSize;
  }
4099
  initResultSizeInfo(pOperator, numOfRows);
4100

4101
  initAggInfo(&pInfo->binfo, &pInfo->aggSup, pExprInfo, numOfCols, pResBlock, keyBufSize, pTaskInfo->id.str);
H
Haojun Liao 已提交
4102
  setFunctionResultOutput(&pInfo->binfo, &pInfo->aggSup, MAIN_SCAN, numOfCols, pTaskInfo);
4103

X
Xiaoyu Wang 已提交
4104 4105
  pInfo->pPseudoColInfo = setRowTsColumnOutputInfo(pInfo->binfo.pCtx, numOfCols);
  pOperator->name = "ProjectOperator";
H
Haojun Liao 已提交
4106
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_PROJECT;
X
Xiaoyu Wang 已提交
4107 4108 4109 4110 4111 4112
  pOperator->blocking = false;
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
  pOperator->pExpr = pExprInfo;
  pOperator->numOfExprs = num;
  pOperator->pTaskInfo = pTaskInfo;
4113

L
Liu Jicong 已提交
4114 4115
  pOperator->fpSet = createOperatorFpSet(operatorDummyOpenFn, doProjectOperation, NULL, NULL,
                                         destroyProjectOperatorInfo, NULL, NULL, NULL);
L
Liu Jicong 已提交
4116

4117
  int32_t code = appendDownstream(pOperator, &downstream, 1);
H
Haojun Liao 已提交
4118
  if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
4119 4120
    goto _error;
  }
4121 4122

  return pOperator;
H
Haojun Liao 已提交
4123

L
Liu Jicong 已提交
4124
_error:
H
Haojun Liao 已提交
4125 4126
  pTaskInfo->code = TSDB_CODE_OUT_OF_MEMORY;
  return NULL;
4127 4128
}

H
Haojun Liao 已提交
4129 4130
static SSDataBlock* doApplyIndefinitFunction(SOperatorInfo* pOperator) {
  SIndefOperatorInfo* pIndefInfo = pOperator->info;
4131
  SOptrBasicInfo*     pInfo = &pIndefInfo->binfo;
H
Haojun Liao 已提交
4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176

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

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

  int64_t st = 0;
  int32_t order = 0;
  int32_t scanFlag = 0;

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

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

  while (1) {
    // The downstream exec may change the value of the newgroup, so use a local variable instead.
    SSDataBlock* pBlock = downstream->fpSet.getNextFn(downstream);
    if (pBlock == NULL) {
      doSetOperatorCompleted(pOperator);
      break;
    }

    // the pDataBlock are always the same one, no need to call this again
    int32_t code = getTableScanInfo(pOperator->pDownstream[0], &order, &scanFlag);
    if (code != TSDB_CODE_SUCCESS) {
      longjmp(pTaskInfo->env, code);
    }

    // there is an scalar expression that needs to be calculated before apply the group aggregation.
    if (pIndefInfo->pScalarExpr != NULL) {
      code = projectApplyFunctions(pIndefInfo->pScalarExpr, pBlock, pBlock, pIndefInfo->pScalarCtx,
                                   pIndefInfo->numOfScalarExpr, pIndefInfo->pPseudoColInfo);
      if (code != TSDB_CODE_SUCCESS) {
        longjmp(pTaskInfo->env, code);
      }
    }

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

4177 4178
    code = projectApplyFunctions(pOperator->pExpr, pInfo->pRes, pBlock, pInfo->pCtx, pOperator->numOfExprs,
                                 pIndefInfo->pPseudoColInfo);
H
Haojun Liao 已提交
4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193
    if (code != TSDB_CODE_SUCCESS) {
      longjmp(pTaskInfo->env, code);
    }
  }

  size_t rows = pInfo->pRes->info.rows;
  pOperator->resultInfo.totalRows += rows;

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

  return (rows > 0) ? pInfo->pRes : NULL;
}

4194 4195
SOperatorInfo* createIndefinitOutputOperatorInfo(SOperatorInfo* downstream, SPhysiNode* pNode,
                                                 SExecTaskInfo* pTaskInfo) {
H
Haojun Liao 已提交
4196
  SIndefOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SIndefOperatorInfo));
4197
  SOperatorInfo*      pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }

  SIndefRowsFuncPhysiNode* pPhyNode = (SIndefRowsFuncPhysiNode*)pNode;

  int32_t    numOfExpr = 0;
  SExprInfo* pExprInfo = createExprInfo(pPhyNode->pVectorFuncs, NULL, &numOfExpr);

  int32_t numOfScalarExpr = 0;
  if (pPhyNode->pExprs != NULL) {
    pInfo->pScalarExpr = createExprInfo(pPhyNode->pExprs, NULL, &numOfScalarExpr);
4210
    pInfo->pScalarCtx = createSqlFunctionCtx(pInfo->pScalarExpr, numOfScalarExpr, &pInfo->rowCellInfoOffset);
H
Haojun Liao 已提交
4211 4212
  }

4213 4214
  SSDataBlock* pResBlock = createResDataBlock(pPhyNode->node.pOutputDataBlockDesc);
  ;
H
Haojun Liao 已提交
4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228

  int32_t numOfRows = 4096;
  size_t  keyBufSize = sizeof(int64_t) + sizeof(int64_t) + POINTER_BYTES;

  // Make sure the size of SSDataBlock will never exceed the size of 2MB.
  int32_t TWOMB = 2 * 1024 * 1024;
  if (numOfRows * pResBlock->info.rowSize > TWOMB) {
    numOfRows = TWOMB / pResBlock->info.rowSize;
  }
  initResultSizeInfo(pOperator, numOfRows);

  initAggInfo(&pInfo->binfo, &pInfo->aggSup, pExprInfo, numOfExpr, pResBlock, keyBufSize, pTaskInfo->id.str);
  setFunctionResultOutput(&pInfo->binfo, &pInfo->aggSup, MAIN_SCAN, numOfExpr, pTaskInfo);

4229 4230 4231
  pInfo->binfo.pRes = pResBlock;
  pInfo->numOfScalarExpr = numOfScalarExpr;
  pInfo->pPseudoColInfo = setRowTsColumnOutputInfo(pInfo->binfo.pCtx, numOfExpr);
H
Haojun Liao 已提交
4232

4233
  pOperator->name = "IndefinitOperator";
H
Haojun Liao 已提交
4234
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_PROJECT;
4235 4236 4237 4238 4239 4240
  pOperator->blocking = false;
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
  pOperator->pExpr = pExprInfo;
  pOperator->numOfExprs = numOfExpr;
  pOperator->pTaskInfo = pTaskInfo;
H
Haojun Liao 已提交
4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251

  pOperator->fpSet = createOperatorFpSet(operatorDummyOpenFn, doApplyIndefinitFunction, NULL, NULL,
                                         destroyIndefinitOperatorInfo, NULL, NULL, NULL);

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

  return pOperator;

4252
_error:
H
Haojun Liao 已提交
4253 4254 4255 4256 4257 4258
  taosMemoryFree(pInfo);
  taosMemoryFree(pOperator);
  pTaskInfo->code = TSDB_CODE_OUT_OF_MEMORY;
  return NULL;
}

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

  STimeWindow w = TSWINDOW_INITIALIZER;
4264
  getAlignQueryTimeWindow(pInterval, pInterval->precision, win.skey, &w);
H
Haojun Liao 已提交
4265 4266

  int32_t order = TSDB_ORDER_ASC;
4267
  pInfo->pFillInfo = taosCreateFillInfo(order, w.skey, 0, capacity, numOfCols, pInterval, fillType, pColInfo, id);
H
Haojun Liao 已提交
4268

wafwerar's avatar
wafwerar 已提交
4269
  pInfo->p = taosMemoryCalloc(numOfCols, POINTER_BYTES);
H
Haojun Liao 已提交
4270 4271 4272 4273 4274 4275 4276
  if (pInfo->pFillInfo == NULL || pInfo->p == NULL) {
    return TSDB_CODE_OUT_OF_MEMORY;
  } else {
    return TSDB_CODE_SUCCESS;
  }
}

L
Liu Jicong 已提交
4277
SOperatorInfo* createFillOperatorInfo(SOperatorInfo* downstream, SExprInfo* pExpr, int32_t numOfCols,
X
Xiaoyu Wang 已提交
4278 4279 4280
                                      SInterval* pInterval, STimeWindow* pWindow, SSDataBlock* pResBlock,
                                      int32_t fillType, SNodeListNode* pValueNode, bool multigroupResult,
                                      SExecTaskInfo* pTaskInfo) {
wafwerar's avatar
wafwerar 已提交
4281
  SFillOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SFillOperatorInfo));
L
Liu Jicong 已提交
4282
  SOperatorInfo*     pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
4283

L
Liu Jicong 已提交
4284
  pInfo->pRes = pResBlock;
4285 4286
  pInfo->multigroupResult = multigroupResult;

4287 4288
  int32_t type = TSDB_FILL_NONE;
  switch (fillType) {
dengyihao's avatar
dengyihao 已提交
4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306
    case FILL_MODE_PREV:
      type = TSDB_FILL_PREV;
      break;
    case FILL_MODE_NONE:
      type = TSDB_FILL_NONE;
      break;
    case FILL_MODE_NULL:
      type = TSDB_FILL_NULL;
      break;
    case FILL_MODE_NEXT:
      type = TSDB_FILL_NEXT;
      break;
    case FILL_MODE_VALUE:
      type = TSDB_FILL_SET_VALUE;
      break;
    case FILL_MODE_LINEAR:
      type = TSDB_FILL_LINEAR;
      break;
4307 4308 4309 4310
    default:
      type = TSDB_FILL_NONE;
  }

H
Haojun Liao 已提交
4311
  SResultInfo* pResultInfo = &pOperator->resultInfo;
4312 4313
  initResultSizeInfo(pOperator, 4096);

X
Xiaoyu Wang 已提交
4314 4315
  int32_t code = initFillInfo(pInfo, pExpr, numOfCols, pValueNode, *pWindow, pResultInfo->capacity, pTaskInfo->id.str,
                              pInterval, type);
4316 4317 4318
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
4319

dengyihao's avatar
dengyihao 已提交
4320
  pOperator->name = "FillOperator";
4321
  pOperator->blocking = false;
dengyihao's avatar
dengyihao 已提交
4322
  pOperator->status = OP_NOT_OPENED;
4323
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_FILL;
dengyihao's avatar
dengyihao 已提交
4324
  pOperator->pExpr = pExpr;
4325
  pOperator->numOfExprs = numOfCols;
dengyihao's avatar
dengyihao 已提交
4326
  pOperator->info = pInfo;
H
Haojun Liao 已提交
4327

L
Liu Jicong 已提交
4328 4329
  pOperator->fpSet =
      createOperatorFpSet(operatorDummyOpenFn, doFill, NULL, NULL, destroySFillOperatorInfo, NULL, NULL, NULL);
4330
  pOperator->pTaskInfo = pTaskInfo;
4331
  code = appendDownstream(pOperator, &downstream, 1);
4332
  return pOperator;
H
Haojun Liao 已提交
4333

L
Liu Jicong 已提交
4334
_error:
wafwerar's avatar
wafwerar 已提交
4335 4336
  taosMemoryFreeClear(pOperator);
  taosMemoryFreeClear(pInfo);
H
Haojun Liao 已提交
4337
  return NULL;
4338 4339
}

L
Liu Jicong 已提交
4340 4341
static SResSchema createResSchema(int32_t type, int32_t bytes, int32_t slotId, int32_t scale, int32_t precision,
                                  const char* name) {
H
Haojun Liao 已提交
4342
  SResSchema s = {0};
dengyihao's avatar
dengyihao 已提交
4343 4344 4345 4346
  s.scale = scale;
  s.type = type;
  s.bytes = bytes;
  s.slotId = slotId;
H
Haojun Liao 已提交
4347
  s.precision = precision;
H
Haojun Liao 已提交
4348 4349 4350 4351
  strncpy(s.name, name, tListLen(s.name));

  return s;
}
H
Haojun Liao 已提交
4352

4353
static SColumn* createColumn(int32_t blockId, int32_t slotId, int32_t colId, SDataType* pType) {
H
Haojun Liao 已提交
4354 4355 4356 4357 4358 4359
  SColumn* pCol = taosMemoryCalloc(1, sizeof(SColumn));
  if (pCol == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

dengyihao's avatar
dengyihao 已提交
4360
  pCol->slotId = slotId;
X
Xiaoyu Wang 已提交
4361 4362 4363 4364
  pCol->colId = colId;
  pCol->bytes = pType->bytes;
  pCol->type = pType->type;
  pCol->scale = pType->scale;
dengyihao's avatar
dengyihao 已提交
4365
  pCol->precision = pType->precision;
H
Haojun Liao 已提交
4366 4367 4368 4369 4370
  pCol->dataBlockId = blockId;

  return pCol;
}

H
Haojun Liao 已提交
4371
SExprInfo* createExprInfo(SNodeList* pNodeList, SNodeList* pGroupKeys, int32_t* numOfExprs) {
H
Haojun Liao 已提交
4372
  int32_t numOfFuncs = LIST_LENGTH(pNodeList);
H
Haojun Liao 已提交
4373 4374 4375 4376
  int32_t numOfGroupKeys = 0;
  if (pGroupKeys != NULL) {
    numOfGroupKeys = LIST_LENGTH(pGroupKeys);
  }
H
Haojun Liao 已提交
4377

H
Haojun Liao 已提交
4378
  *numOfExprs = numOfFuncs + numOfGroupKeys;
wafwerar's avatar
wafwerar 已提交
4379
  SExprInfo* pExprs = taosMemoryCalloc(*numOfExprs, sizeof(SExprInfo));
H
Haojun Liao 已提交
4380

L
Liu Jicong 已提交
4381
  for (int32_t i = 0; i < (*numOfExprs); ++i) {
H
Haojun Liao 已提交
4382 4383 4384 4385 4386 4387
    STargetNode* pTargetNode = NULL;
    if (i < numOfFuncs) {
      pTargetNode = (STargetNode*)nodesListGetNode(pNodeList, i);
    } else {
      pTargetNode = (STargetNode*)nodesListGetNode(pGroupKeys, i - numOfFuncs);
    }
H
Haojun Liao 已提交
4388

4389
    SExprInfo* pExp = &pExprs[i];
H
Haojun Liao 已提交
4390

wafwerar's avatar
wafwerar 已提交
4391
    pExp->pExpr = taosMemoryCalloc(1, sizeof(tExprNode));
H
Haojun Liao 已提交
4392
    pExp->pExpr->_function.num = 1;
H
Haojun Liao 已提交
4393
    pExp->pExpr->_function.functionId = -1;
H
Haojun Liao 已提交
4394

4395
    int32_t type = nodeType(pTargetNode->pExpr);
H
Haojun Liao 已提交
4396
    // it is a project query, or group by column
4397
    if (type == QUERY_NODE_COLUMN) {
H
Haojun Liao 已提交
4398
      pExp->pExpr->nodeType = QUERY_NODE_COLUMN;
L
Liu Jicong 已提交
4399
      SColumnNode* pColNode = (SColumnNode*)pTargetNode->pExpr;
H
Haojun Liao 已提交
4400

G
Ganlin Zhao 已提交
4401 4402 4403
      pExp->base.pParam = taosMemoryCalloc(1, sizeof(SFunctParam));
      pExp->base.numOfParams = 1;

H
Haojun Liao 已提交
4404
      SDataType* pType = &pColNode->node.resType;
dengyihao's avatar
dengyihao 已提交
4405 4406
      pExp->base.resSchema = createResSchema(pType->type, pType->bytes, pTargetNode->slotId, pType->scale,
                                             pType->precision, pColNode->colName);
4407
      pExp->base.pParam[0].pCol = createColumn(pColNode->dataBlockId, pColNode->slotId, pColNode->colId, pType);
H
Haojun Liao 已提交
4408
      pExp->base.pParam[0].type = FUNC_PARAM_TYPE_COLUMN;
4409
    } else if (type == QUERY_NODE_VALUE) {
4410 4411 4412 4413 4414 4415 4416
      pExp->pExpr->nodeType = QUERY_NODE_VALUE;
      SValueNode* pValNode = (SValueNode*)pTargetNode->pExpr;

      pExp->base.pParam = taosMemoryCalloc(1, sizeof(SFunctParam));
      pExp->base.numOfParams = 1;

      SDataType* pType = &pValNode->node.resType;
dengyihao's avatar
dengyihao 已提交
4417 4418
      pExp->base.resSchema = createResSchema(pType->type, pType->bytes, pTargetNode->slotId, pType->scale,
                                             pType->precision, pValNode->node.aliasName);
4419
      pExp->base.pParam[0].type = FUNC_PARAM_TYPE_VALUE;
X
Xiaoyu Wang 已提交
4420
      nodesValueNodeToVariant(pValNode, &pExp->base.pParam[0].param);
4421
    } else if (type == QUERY_NODE_FUNCTION) {
H
Haojun Liao 已提交
4422
      pExp->pExpr->nodeType = QUERY_NODE_FUNCTION;
H
Haojun Liao 已提交
4423 4424 4425
      SFunctionNode* pFuncNode = (SFunctionNode*)pTargetNode->pExpr;

      SDataType* pType = &pFuncNode->node.resType;
dengyihao's avatar
dengyihao 已提交
4426 4427
      pExp->base.resSchema = createResSchema(pType->type, pType->bytes, pTargetNode->slotId, pType->scale,
                                             pType->precision, pFuncNode->node.aliasName);
H
Haojun Liao 已提交
4428

H
Haojun Liao 已提交
4429
      pExp->pExpr->_function.functionId = pFuncNode->funcId;
H
Haojun Liao 已提交
4430
      pExp->pExpr->_function.pFunctNode = pFuncNode;
4431

dengyihao's avatar
dengyihao 已提交
4432 4433
      strncpy(pExp->pExpr->_function.functionName, pFuncNode->functionName,
              tListLen(pExp->pExpr->_function.functionName));
4434 4435 4436 4437 4438
#if 1
      // todo refactor: add the parameter for tbname function
      if (strcmp(pExp->pExpr->_function.functionName, "tbname") == 0) {
        pFuncNode->pParameterList = nodesMakeList();
        ASSERT(LIST_LENGTH(pFuncNode->pParameterList) == 0);
X
Xiaoyu Wang 已提交
4439 4440
        SValueNode* res = (SValueNode*)nodesMakeNode(QUERY_NODE_VALUE);
        if (NULL == res) {  // todo handle error
4441
        } else {
X
Xiaoyu Wang 已提交
4442
          res->node.resType = (SDataType){.bytes = sizeof(int64_t), .type = TSDB_DATA_TYPE_BIGINT};
4443 4444 4445 4446
          nodesListAppend(pFuncNode->pParameterList, res);
        }
      }
#endif
H
Haojun Liao 已提交
4447 4448

      int32_t numOfParam = LIST_LENGTH(pFuncNode->pParameterList);
G
Ganlin Zhao 已提交
4449 4450 4451 4452

      pExp->base.pParam = taosMemoryCalloc(numOfParam, sizeof(SFunctParam));
      pExp->base.numOfParams = numOfParam;

H
Haojun Liao 已提交
4453
      for (int32_t j = 0; j < numOfParam; ++j) {
4454
        SNode* p1 = nodesListGetNode(pFuncNode->pParameterList, j);
G
Ganlin Zhao 已提交
4455
        if (p1->type == QUERY_NODE_COLUMN) {
dengyihao's avatar
dengyihao 已提交
4456
          SColumnNode* pcn = (SColumnNode*)p1;
G
Ganlin Zhao 已提交
4457 4458

          pExp->base.pParam[j].type = FUNC_PARAM_TYPE_COLUMN;
4459
          pExp->base.pParam[j].pCol = createColumn(pcn->dataBlockId, pcn->slotId, pcn->colId, &pcn->node.resType);
G
Ganlin Zhao 已提交
4460 4461 4462
        } else if (p1->type == QUERY_NODE_VALUE) {
          SValueNode* pvn = (SValueNode*)p1;
          pExp->base.pParam[j].type = FUNC_PARAM_TYPE_VALUE;
X
Xiaoyu Wang 已提交
4463
          nodesValueNodeToVariant(pvn, &pExp->base.pParam[j].param);
G
Ganlin Zhao 已提交
4464
        }
H
Haojun Liao 已提交
4465
      }
4466
    } else if (type == QUERY_NODE_OPERATOR) {
H
Haojun Liao 已提交
4467
      pExp->pExpr->nodeType = QUERY_NODE_OPERATOR;
L
Liu Jicong 已提交
4468
      SOperatorNode* pNode = (SOperatorNode*)pTargetNode->pExpr;
4469

G
Ganlin Zhao 已提交
4470 4471 4472
      pExp->base.pParam = taosMemoryCalloc(1, sizeof(SFunctParam));
      pExp->base.numOfParams = 1;

4473
      SDataType* pType = &pNode->node.resType;
dengyihao's avatar
dengyihao 已提交
4474 4475
      pExp->base.resSchema = createResSchema(pType->type, pType->bytes, pTargetNode->slotId, pType->scale,
                                             pType->precision, pNode->node.aliasName);
4476 4477 4478
      pExp->pExpr->_optrRoot.pRootNode = pTargetNode->pExpr;
    } else {
      ASSERT(0);
H
Haojun Liao 已提交
4479 4480 4481
    }
  }

H
Haojun Liao 已提交
4482
  return pExprs;
H
Haojun Liao 已提交
4483 4484
}

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

D
dapan1121 已提交
4489
  pTaskInfo->schemaVer.dbname = strdup(dbFName);
4490
  pTaskInfo->cost.created = taosGetTimestampMs();
H
Haojun Liao 已提交
4491
  pTaskInfo->id.queryId = queryId;
dengyihao's avatar
dengyihao 已提交
4492
  pTaskInfo->execModel = model;
H
Haojun Liao 已提交
4493

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

4498 4499
  return pTaskInfo;
}
H
Haojun Liao 已提交
4500

L
Liu Jicong 已提交
4501
static tsdbReaderT doCreateDataReader(STableScanPhysiNode* pTableScanNode, SReadHandle* pHandle,
dengyihao's avatar
dengyihao 已提交
4502 4503
                                      STableListInfo* pTableGroupInfo, uint64_t queryId, uint64_t taskId,
                                      SNode* pTagCond);
H
Haojun Liao 已提交
4504

dengyihao's avatar
dengyihao 已提交
4505 4506
static int32_t getTableList(void* metaHandle, int32_t tableType, uint64_t tableUid, STableListInfo* pListInfo,
                            SNode* pTagCond);
wmmhello's avatar
wmmhello 已提交
4507
static SArray* extractTableIdList(const STableListInfo* pTableGroupInfo);
H
Haojun Liao 已提交
4508
static SArray* extractColumnInfo(SNodeList* pNodeList);
4509

4510
static SArray* createSortInfo(SNodeList* pNodeList);
4511
static SArray* extractPartitionColInfo(SNodeList* pNodeList);
4512

X
Xiaoyu Wang 已提交
4513
void extractTableSchemaVersion(SReadHandle* pHandle, uint64_t uid, SExecTaskInfo* pTaskInfo) {
4514 4515 4516 4517 4518 4519 4520
  SMetaReader mr = {0};
  metaReaderInit(&mr, pHandle->meta, 0);
  metaGetTableEntryByUid(&mr, uid);

  pTaskInfo->schemaVer.tablename = strdup(mr.me.name);

  if (mr.me.type == TSDB_SUPER_TABLE) {
4521 4522
    pTaskInfo->schemaVer.sversion = mr.me.stbEntry.schemaRow.version;
    pTaskInfo->schemaVer.tversion = mr.me.stbEntry.schemaTag.version;
4523 4524 4525
  } else if (mr.me.type == TSDB_CHILD_TABLE) {
    tb_uid_t suid = mr.me.ctbEntry.suid;
    metaGetTableEntryByUid(&mr, suid);
4526 4527
    pTaskInfo->schemaVer.sversion = mr.me.stbEntry.schemaRow.version;
    pTaskInfo->schemaVer.tversion = mr.me.stbEntry.schemaTag.version;
4528
  } else {
4529
    pTaskInfo->schemaVer.sversion = mr.me.ntbEntry.schemaRow.version;
4530
  }
4531 4532

  metaReaderClear(&mr);
4533 4534
}

H
Haojun Liao 已提交
4535
SOperatorInfo* createOperatorTree(SPhysiNode* pPhyNode, SExecTaskInfo* pTaskInfo, SReadHandle* pHandle,
wmmhello's avatar
wmmhello 已提交
4536
                                  uint64_t queryId, uint64_t taskId, STableListInfo* pTableListInfo, SNode* pTagCond) {
4537 4538
  int32_t type = nodeType(pPhyNode);

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

dengyihao's avatar
dengyihao 已提交
4543
      tsdbReaderT pDataReader =
dengyihao's avatar
dengyihao 已提交
4544
          doCreateDataReader(pTableScanNode, pHandle, pTableListInfo, (uint64_t)queryId, taskId, pTagCond);
4545
      if (pDataReader == NULL && terrno != 0) {
4546 4547
        return NULL;
      }
wmmhello's avatar
wmmhello 已提交
4548
      SArray* groupKyes = extractPartitionColInfo(pTableScanNode->pPartitionKeys);
4549
      extractTableSchemaVersion(pHandle, pTableScanNode->scan.uid, pTaskInfo);
X
Xiaoyu Wang 已提交
4550 4551
      SOperatorInfo* pOperator =
          createTableScanOperatorInfo(pTableScanNode, pDataReader, pHandle, groupKyes, pTaskInfo);
4552

4553 4554
      STableScanInfo* pScanInfo = pOperator->info;
      pTaskInfo->cost.pRecoder = &pScanInfo->readRecorder;
4555

4556
      return pOperator;
H
Haojun Liao 已提交
4557
    } else if (QUERY_NODE_PHYSICAL_PLAN_EXCHANGE == type) {
4558
      return createExchangeOperatorInfo(pHandle->pMsgCb->clientRpc, (SExchangePhysiNode*)pPhyNode, pTaskInfo);
H
Haojun Liao 已提交
4559
    } else if (QUERY_NODE_PHYSICAL_PLAN_STREAM_SCAN == type) {
X
Xiaoyu Wang 已提交
4560
      SScanPhysiNode*      pScanPhyNode = (SScanPhysiNode*)pPhyNode;  // simple child table.
5
54liuyao 已提交
4561
      STableScanPhysiNode* pTableScanNode = (STableScanPhysiNode*)pPhyNode;
4562
      STimeWindowAggSupp   twSup = {
dengyihao's avatar
dengyihao 已提交
4563
          .waterMark = pTableScanNode->watermark, .calTrigger = pTableScanNode->triggerType, .maxTs = INT64_MIN};
5
54liuyao 已提交
4564 4565
      tsdbReaderT pDataReader = NULL;
      if (pHandle->vnode) {
wmmhello's avatar
wmmhello 已提交
4566
        pDataReader = doCreateDataReader(pTableScanNode, pHandle, pTableListInfo, (uint64_t)queryId, taskId, pTagCond);
wmmhello's avatar
wmmhello 已提交
4567 4568
      } else {
        getTableList(pHandle->meta, pScanPhyNode->tableType, pScanPhyNode->uid, pTableListInfo, pTagCond);
5
54liuyao 已提交
4569
      }
4570

5
54liuyao 已提交
4571
      if (pDataReader == NULL && terrno != 0) {
4572
        qDebug("%s pDataReader is NULL", GET_TASKID(pTaskInfo));
5
54liuyao 已提交
4573 4574
        // return NULL;
      } else {
4575
        qDebug("%s pDataReader is not NULL", GET_TASKID(pTaskInfo));
5
54liuyao 已提交
4576
      }
X
Xiaoyu Wang 已提交
4577
      SArray* tableIdList = extractTableIdList(pTableListInfo);
4578

X
Xiaoyu Wang 已提交
4579 4580
      SOperatorInfo* pOperator =
          createStreamScanOperatorInfo(pDataReader, pHandle, tableIdList, pTableScanNode, pTaskInfo, &twSup);
4581

4582
      taosArrayDestroy(tableIdList);
H
Haojun Liao 已提交
4583
      return pOperator;
H
Haojun Liao 已提交
4584
    } else if (QUERY_NODE_PHYSICAL_PLAN_SYSTABLE_SCAN == type) {
L
Liu Jicong 已提交
4585
      SSystemTableScanPhysiNode* pSysScanPhyNode = (SSystemTableScanPhysiNode*)pPhyNode;
4586
      return createSysTableScanOperatorInfo(pHandle, pSysScanPhyNode, pTaskInfo);
4587
    } else if (QUERY_NODE_PHYSICAL_PLAN_TAG_SCAN == type) {
X
Xiaoyu Wang 已提交
4588
      STagScanPhysiNode* pScanPhyNode = (STagScanPhysiNode*)pPhyNode;
4589

4590
      int32_t code = getTableList(pHandle->meta, pScanPhyNode->tableType, pScanPhyNode->uid, pTableListInfo, pScanPhyNode->node.pConditions);
4591 4592 4593 4594
      if (code != TSDB_CODE_SUCCESS) {
        return NULL;
      }

4595
      return createTagScanOperatorInfo(pHandle, pScanPhyNode, pTableListInfo, pTaskInfo);
H
Haojun Liao 已提交
4596 4597
    } else {
      ASSERT(0);
H
Haojun Liao 已提交
4598 4599 4600
    }
  }

4601 4602
  int32_t num = 0;
  size_t  size = LIST_LENGTH(pPhyNode->pChildren);
H
Haojun Liao 已提交
4603

4604
  SOperatorInfo** ops = taosMemoryCalloc(size, POINTER_BYTES);
dengyihao's avatar
dengyihao 已提交
4605
  for (int32_t i = 0; i < size; ++i) {
4606
    SPhysiNode* pChildNode = (SPhysiNode*)nodesListGetNode(pPhyNode->pChildren, i);
wmmhello's avatar
wmmhello 已提交
4607
    ops[i] = createOperatorTree(pChildNode, pTaskInfo, pHandle, queryId, taskId, pTableListInfo, pTagCond);
4608 4609 4610
    if (ops[i] == NULL) {
      return NULL;
    }
4611
  }
H
Haojun Liao 已提交
4612

4613
  SOperatorInfo* pOptr = NULL;
H
Haojun Liao 已提交
4614
  if (QUERY_NODE_PHYSICAL_PLAN_PROJECT == type) {
dengyihao's avatar
dengyihao 已提交
4615 4616
    SProjectPhysiNode* pProjPhyNode = (SProjectPhysiNode*)pPhyNode;
    SExprInfo*         pExprInfo = createExprInfo(pProjPhyNode->pProjections, NULL, &num);
H
Haojun Liao 已提交
4617

4618
    SSDataBlock* pResBlock = createResDataBlock(pPhyNode->pOutputDataBlockDesc);
dengyihao's avatar
dengyihao 已提交
4619 4620
    SLimit       limit = {.limit = pProjPhyNode->limit, .offset = pProjPhyNode->offset};
    SLimit       slimit = {.limit = pProjPhyNode->slimit, .offset = pProjPhyNode->soffset};
X
Xiaoyu Wang 已提交
4621 4622
    pOptr = createProjectOperatorInfo(ops[0], pExprInfo, num, pResBlock, &limit, &slimit,
                                      pProjPhyNode->node.pConditions, pTaskInfo);
4623
  } else if (QUERY_NODE_PHYSICAL_PLAN_HASH_AGG == type) {
H
Haojun Liao 已提交
4624 4625
    SAggPhysiNode* pAggNode = (SAggPhysiNode*)pPhyNode;
    SExprInfo*     pExprInfo = createExprInfo(pAggNode->pAggFuncs, pAggNode->pGroupKeys, &num);
4626
    SSDataBlock*   pResBlock = createResDataBlock(pPhyNode->pOutputDataBlockDesc);
H
Haojun Liao 已提交
4627

dengyihao's avatar
dengyihao 已提交
4628
    int32_t    numOfScalarExpr = 0;
4629 4630 4631 4632 4633
    SExprInfo* pScalarExprInfo = NULL;
    if (pAggNode->pExprs != NULL) {
      pScalarExprInfo = createExprInfo(pAggNode->pExprs, NULL, &numOfScalarExpr);
    }

H
Haojun Liao 已提交
4634 4635
    if (pAggNode->pGroupKeys != NULL) {
      SArray* pColList = extractColumnInfo(pAggNode->pGroupKeys);
dengyihao's avatar
dengyihao 已提交
4636
      pOptr = createGroupOperatorInfo(ops[0], pExprInfo, num, pResBlock, pColList, pAggNode->node.pConditions,
wmmhello's avatar
wmmhello 已提交
4637
                                      pScalarExprInfo, numOfScalarExpr, pTaskInfo);
H
Haojun Liao 已提交
4638
    } else {
dengyihao's avatar
dengyihao 已提交
4639 4640
      pOptr =
          createAggregateOperatorInfo(ops[0], pExprInfo, num, pResBlock, pScalarExprInfo, numOfScalarExpr, pTaskInfo);
H
Haojun Liao 已提交
4641
    }
X
Xiaoyu Wang 已提交
4642
  } else if (QUERY_NODE_PHYSICAL_PLAN_HASH_INTERVAL == type || QUERY_NODE_PHYSICAL_PLAN_STREAM_INTERVAL == type) {
H
Haojun Liao 已提交
4643
    SIntervalPhysiNode* pIntervalPhyNode = (SIntervalPhysiNode*)pPhyNode;
H
Haojun Liao 已提交
4644

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

dengyihao's avatar
dengyihao 已提交
4648 4649 4650 4651 4652 4653
    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 已提交
4654

X
Xiaoyu Wang 已提交
4655 4656 4657 4658 4659 4660
    STimeWindowAggSupp as = {
        .waterMark = pIntervalPhyNode->window.watermark,
        .calTrigger = pIntervalPhyNode->window.triggerType,
        .maxTs = INT64_MIN,
        .winMap = NULL,
    };
5
54liuyao 已提交
4661 4662 4663 4664 4665 4666
    if (isSmaStream(pIntervalPhyNode->window.triggerType)) {
      if (FLT_LESS(pIntervalPhyNode->window.filesFactor, 1.000000)) {
        as.calTrigger = STREAM_TRIGGER_AT_ONCE_SMA;
      } else {
        _hash_fn_t hashFn = taosGetDefaultHashFunction(TSDB_DATA_TYPE_TIMESTAMP);
        as.winMap = taosHashInit(64, hashFn, true, HASH_NO_LOCK);
X
Xiaoyu Wang 已提交
4667
        as.waterMark = getSmaWaterMark(interval.interval, pIntervalPhyNode->window.filesFactor);
5
54liuyao 已提交
4668 4669 4670
        as.calTrigger = STREAM_TRIGGER_WINDOW_CLOSE_SMA;
      }
    }
4671

4672
    int32_t tsSlotId = ((SColumnNode*)pIntervalPhyNode->window.pTspk)->slotId;
4673 4674
    bool isStream = (QUERY_NODE_PHYSICAL_PLAN_STREAM_INTERVAL == type);
    pOptr = createIntervalOperatorInfo(ops[0], pExprInfo, num, pResBlock, &interval, tsSlotId, &as, pTaskInfo, isStream);
4675

5
54liuyao 已提交
4676 4677 4678 4679 4680 4681
  } else if (QUERY_NODE_PHYSICAL_PLAN_STREAM_SEMI_INTERVAL == type) {
    int32_t children = 8;
    pOptr = createStreamFinalIntervalOperatorInfo(ops[0], pPhyNode, pTaskInfo, children);
  } else if (QUERY_NODE_PHYSICAL_PLAN_STREAM_FINAL_INTERVAL == type) {
    int32_t children = 0;
    pOptr = createStreamFinalIntervalOperatorInfo(ops[0], pPhyNode, pTaskInfo, children);
H
Haojun Liao 已提交
4682
  } else if (QUERY_NODE_PHYSICAL_PLAN_SORT == type) {
H
Haojun Liao 已提交
4683
    SSortPhysiNode* pSortPhyNode = (SSortPhysiNode*)pPhyNode;
H
Haojun Liao 已提交
4684

4685 4686 4687
    SDataBlockDescNode* pDescNode = pPhyNode->pOutputDataBlockDesc;

    SSDataBlock* pResBlock = createResDataBlock(pDescNode);
4688
    SArray*      info = createSortInfo(pSortPhyNode->pSortKeys);
4689 4690

    int32_t    numOfCols = 0;
4691 4692 4693
    SExprInfo* pExprInfo = createExprInfo(pSortPhyNode->pExprs, NULL, &numOfCols);

    int32_t numOfOutputCols = 0;
X
Xiaoyu Wang 已提交
4694 4695
    SArray* pColList =
        extractColMatchInfo(pSortPhyNode->pTargets, pDescNode, &numOfOutputCols, pTaskInfo, COL_MATCH_FROM_SLOT_ID);
4696

4697
    pOptr = createSortOperatorInfo(ops[0], pResBlock, info, pExprInfo, numOfCols, pColList, pTaskInfo);
X
Xiaoyu Wang 已提交
4698
  } else if (QUERY_NODE_PHYSICAL_PLAN_MERGE == type) {
4699 4700 4701
    SMergePhysiNode* pMergePhyNode = (SMergePhysiNode*)pPhyNode;

    SDataBlockDescNode* pDescNode = pPhyNode->pOutputDataBlockDesc;
X
Xiaoyu Wang 已提交
4702
    SSDataBlock*        pResBlock = createResDataBlock(pDescNode);
4703

X
Xiaoyu Wang 已提交
4704
    SArray* sortInfo = createSortInfo(pMergePhyNode->pMergeKeys);
4705
    int32_t numOfOutputCols = 0;
X
Xiaoyu Wang 已提交
4706 4707
    SArray* pColList =
        extractColMatchInfo(pMergePhyNode->pTargets, pDescNode, &numOfOutputCols, pTaskInfo, COL_MATCH_FROM_SLOT_ID);
4708 4709 4710
    SPhysiNode* pChildNode = (SPhysiNode*)nodesListGetNode(pPhyNode->pChildren, 0);
    SSDataBlock* pInputDataBlock = createResDataBlock(pChildNode->pOutputDataBlockDesc);
    pOptr = createMultiwaySortMergeOperatorInfo(ops, size, pInputDataBlock, pResBlock, sortInfo, pColList, pTaskInfo);
4711
  } else if (QUERY_NODE_PHYSICAL_PLAN_MERGE_SESSION == type) {
H
Haojun Liao 已提交
4712 4713
    SSessionWinodwPhysiNode* pSessionNode = (SSessionWinodwPhysiNode*)pPhyNode;

X
Xiaoyu Wang 已提交
4714 4715
    STimeWindowAggSupp as = {.waterMark = pSessionNode->window.watermark,
                             .calTrigger = pSessionNode->window.triggerType};
4716

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

X
Xiaoyu Wang 已提交
4721 4722
    pOptr =
        createSessionAggOperatorInfo(ops[0], pExprInfo, num, pResBlock, pSessionNode->gap, tsSlotId, &as, pTaskInfo);
4723
  } else if (QUERY_NODE_PHYSICAL_PLAN_STREAM_SESSION == type) {
5
54liuyao 已提交
4724 4725 4726 4727 4728 4729 4730 4731 4732
    SSessionWinodwPhysiNode* pSessionNode = (SSessionWinodwPhysiNode*)pPhyNode;

    STimeWindowAggSupp as = {.waterMark = pSessionNode->window.watermark,
                             .calTrigger = pSessionNode->window.triggerType};

    SExprInfo*   pExprInfo = createExprInfo(pSessionNode->window.pFuncs, NULL, &num);
    SSDataBlock* pResBlock = createResDataBlock(pPhyNode->pOutputDataBlockDesc);
    int32_t      tsSlotId = ((SColumnNode*)pSessionNode->window.pTspk)->slotId;

4733 4734
    pOptr = createStreamSessionAggOperatorInfo(ops[0], pExprInfo, num, pResBlock, pSessionNode->gap, tsSlotId, &as,
                                               pTaskInfo);
5
54liuyao 已提交
4735

H
Haojun Liao 已提交
4736
  } else if (QUERY_NODE_PHYSICAL_PLAN_PARTITION == type) {
dengyihao's avatar
dengyihao 已提交
4737 4738 4739
    SPartitionPhysiNode* pPartNode = (SPartitionPhysiNode*)pPhyNode;
    SArray*              pColList = extractPartitionColInfo(pPartNode->pPartitionKeys);
    SSDataBlock*         pResBlock = createResDataBlock(pPhyNode->pOutputDataBlockDesc);
4740 4741

    SExprInfo* pExprInfo = createExprInfo(pPartNode->pTargets, NULL, &num);
wmmhello's avatar
wmmhello 已提交
4742
    pOptr = createPartitionOperatorInfo(ops[0], pExprInfo, num, pResBlock, pColList, pTaskInfo);
4743
  } else if (QUERY_NODE_PHYSICAL_PLAN_MERGE_STATE == type) {
dengyihao's avatar
dengyihao 已提交
4744
    SStateWinodwPhysiNode* pStateNode = (SStateWinodwPhysiNode*)pPhyNode;
4745

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

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

4752
    SColumnNode* pColNode = (SColumnNode*)((STargetNode*)pStateNode->pStateKey)->pExpr;
X
Xiaoyu Wang 已提交
4753
    SColumn      col = extractColumnFromColumnNode(pColNode);
4754
    pOptr = createStatewindowOperatorInfo(ops[0], pExprInfo, num, pResBlock, &as, tsSlotId, &col, pTaskInfo);
4755
  } else if (QUERY_NODE_PHYSICAL_PLAN_STREAM_STATE == type) {
5
54liuyao 已提交
4756
    pOptr = createStreamStateAggOperatorInfo(ops[0], pPhyNode, pTaskInfo);
4757
  } else if (QUERY_NODE_PHYSICAL_PLAN_MERGE_JOIN == type) {
dengyihao's avatar
dengyihao 已提交
4758 4759
    SJoinPhysiNode* pJoinNode = (SJoinPhysiNode*)pPhyNode;
    SSDataBlock*    pResBlock = createResDataBlock(pPhyNode->pOutputDataBlockDesc);
4760 4761

    SExprInfo* pExprInfo = createExprInfo(pJoinNode->pTargets, NULL, &num);
H
Haojun Liao 已提交
4762
    pOptr = createMergeJoinOperatorInfo(ops, size, pExprInfo, num, pResBlock, pJoinNode->pOnConditions, pTaskInfo);
4763 4764
  } else if (QUERY_NODE_PHYSICAL_PLAN_FILL == type) {
    SFillPhysiNode* pFillNode = (SFillPhysiNode*)pPhyNode;
X
Xiaoyu Wang 已提交
4765 4766
    SSDataBlock*    pResBlock = createResDataBlock(pPhyNode->pOutputDataBlockDesc);
    SExprInfo*      pExprInfo = createExprInfo(pFillNode->pTargets, NULL, &num);
4767

4768
    SInterval* pInterval = &((SIntervalAggOperatorInfo*)ops[0]->info)->interval;
X
Xiaoyu Wang 已提交
4769 4770
    pOptr = createFillOperatorInfo(ops[0], pExprInfo, num, pInterval, &pFillNode->timeRange, pResBlock, pFillNode->mode,
                                   (SNodeListNode*)pFillNode->pValues, false, pTaskInfo);
H
Haojun Liao 已提交
4771 4772
  } else if (QUERY_NODE_PHYSICAL_PLAN_INDEF_ROWS_FUNC == type) {
    pOptr = createIndefinitOutputOperatorInfo(ops[0], pPhyNode, pTaskInfo);
H
Haojun Liao 已提交
4773 4774
  } else {
    ASSERT(0);
H
Haojun Liao 已提交
4775
  }
4776 4777 4778

  taosMemoryFree(ops);
  return pOptr;
4779
}
H
Haojun Liao 已提交
4780

4781
int32_t compareTimeWindow(const void* p1, const void* p2, const void* param) {
dengyihao's avatar
dengyihao 已提交
4782 4783 4784
  const SQueryTableDataCond* pCond = param;
  const STimeWindow*         pWin1 = p1;
  const STimeWindow*         pWin2 = p2;
4785 4786 4787 4788 4789 4790 4791 4792
  if (pCond->order == TSDB_ORDER_ASC) {
    return pWin1->skey - pWin2->skey;
  } else if (pCond->order == TSDB_ORDER_DESC) {
    return pWin2->skey - pWin1->skey;
  }
  return 0;
}

4793
int32_t initQueryTableDataCond(SQueryTableDataCond* pCond, const STableScanPhysiNode* pTableScanNode) {
4794 4795 4796 4797 4798 4799
  pCond->loadExternalRows = false;

  pCond->order = pTableScanNode->scanSeq[0] > 0 ? TSDB_ORDER_ASC : TSDB_ORDER_DESC;
  pCond->numOfCols = LIST_LENGTH(pTableScanNode->scan.pScanCols);
  pCond->colList = taosMemoryCalloc(pCond->numOfCols, sizeof(SColumnInfo));
  if (pCond->colList == NULL) {
H
Haojun Liao 已提交
4800
    terrno = TSDB_CODE_QRY_OUT_OF_MEMORY;
4801 4802 4803
    return terrno;
  }

dengyihao's avatar
dengyihao 已提交
4804 4805
  // pCond->twindow = pTableScanNode->scanRange;
  // TODO: get it from stable scan node
4806 4807 4808
  pCond->numOfTWindows = 1;
  pCond->twindows = taosMemoryCalloc(pCond->numOfTWindows, sizeof(STimeWindow));
  pCond->twindows[0] = pTableScanNode->scanRange;
H
more  
Hongze Cheng 已提交
4809
  pCond->suid = pTableScanNode->scan.suid;
4810 4811

#if 1
L
Liu Jicong 已提交
4812
  // todo work around a problem, remove it later
4813 4814 4815 4816 4817
  for (int32_t i = 0; i < pCond->numOfTWindows; ++i) {
    if ((pCond->order == TSDB_ORDER_ASC && pCond->twindows[i].skey > pCond->twindows[i].ekey) ||
        (pCond->order == TSDB_ORDER_DESC && pCond->twindows[i].skey < pCond->twindows[i].ekey)) {
      TSWAP(pCond->twindows[i].skey, pCond->twindows[i].ekey);
    }
H
Haojun Liao 已提交
4818
  }
4819
#endif
H
Haojun Liao 已提交
4820

4821 4822 4823 4824 4825 4826
  for (int32_t i = 0; i < pCond->numOfTWindows; ++i) {
    if ((pCond->order == TSDB_ORDER_ASC && pCond->twindows[i].skey > pCond->twindows[i].ekey) ||
        (pCond->order == TSDB_ORDER_DESC && pCond->twindows[i].skey < pCond->twindows[i].ekey)) {
      TSWAP(pCond->twindows[i].skey, pCond->twindows[i].ekey);
    }
  }
dengyihao's avatar
dengyihao 已提交
4827
  taosqsort(pCond->twindows, pCond->numOfTWindows, sizeof(STimeWindow), pCond, compareTimeWindow);
4828

4829 4830
  pCond->type = BLOCK_LOAD_OFFSET_SEQ_ORDER;
  //  pCond->type = pTableScanNode->scanFlag;
H
Haojun Liao 已提交
4831

H
Haojun Liao 已提交
4832
  int32_t j = 0;
4833
  for (int32_t i = 0; i < pCond->numOfCols; ++i) {
H
Haojun Liao 已提交
4834 4835
    STargetNode* pNode = (STargetNode*)nodesListGetNode(pTableScanNode->scan.pScanCols, i);
    SColumnNode* pColNode = (SColumnNode*)pNode->pExpr;
H
Haojun Liao 已提交
4836 4837 4838
    if (pColNode->colType == COLUMN_TYPE_TAG) {
      continue;
    }
H
Haojun Liao 已提交
4839

4840 4841 4842
    pCond->colList[j].type = pColNode->node.resType.type;
    pCond->colList[j].bytes = pColNode->node.resType.bytes;
    pCond->colList[j].colId = pColNode->colId;
H
Haojun Liao 已提交
4843
    j += 1;
H
Haojun Liao 已提交
4844 4845
  }

4846 4847
  pCond->numOfCols = j;
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
4848
}
H
Haojun Liao 已提交
4849

4850 4851
SColumn extractColumnFromColumnNode(SColumnNode* pColNode) {
  SColumn c = {0};
X
Xiaoyu Wang 已提交
4852 4853 4854 4855 4856
  c.slotId = pColNode->slotId;
  c.colId = pColNode->colId;
  c.type = pColNode->node.resType.type;
  c.bytes = pColNode->node.resType.bytes;
  c.scale = pColNode->node.resType.scale;
4857 4858 4859 4860
  c.precision = pColNode->node.resType.precision;
  return c;
}

H
Haojun Liao 已提交
4861
SArray* extractColumnInfo(SNodeList* pNodeList) {
L
Liu Jicong 已提交
4862
  size_t  numOfCols = LIST_LENGTH(pNodeList);
H
Haojun Liao 已提交
4863 4864 4865 4866 4867 4868
  SArray* pList = taosArrayInit(numOfCols, sizeof(SColumn));
  if (pList == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

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

4872 4873 4874
    if (nodeType(pNode->pExpr) == QUERY_NODE_COLUMN) {
      SColumnNode* pColNode = (SColumnNode*)pNode->pExpr;

4875
      SColumn c = extractColumnFromColumnNode(pColNode);
4876 4877
      taosArrayPush(pList, &c);
    } else if (nodeType(pNode->pExpr) == QUERY_NODE_VALUE) {
L
Liu Jicong 已提交
4878 4879
      SValueNode* pValNode = (SValueNode*)pNode->pExpr;
      SColumn     c = {0};
4880
      c.slotId = pNode->slotId;
L
Liu Jicong 已提交
4881 4882 4883 4884
      c.colId = pNode->slotId;
      c.type = pValNode->node.type;
      c.bytes = pValNode->node.resType.bytes;
      c.scale = pValNode->node.resType.scale;
4885 4886 4887 4888
      c.precision = pValNode->node.resType.precision;

      taosArrayPush(pList, &c);
    }
H
Haojun Liao 已提交
4889 4890 4891 4892 4893
  }

  return pList;
}

4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907
SArray* extractPartitionColInfo(SNodeList* pNodeList) {
  size_t  numOfCols = LIST_LENGTH(pNodeList);
  SArray* pList = taosArrayInit(numOfCols, sizeof(SColumn));
  if (pList == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

  for (int32_t i = 0; i < numOfCols; ++i) {
    SColumnNode* pColNode = (SColumnNode*)nodesListGetNode(pNodeList, i);

    // todo extract method
    SColumn c = {0};
    c.slotId = pColNode->slotId;
dengyihao's avatar
dengyihao 已提交
4908 4909 4910
    c.colId = pColNode->colId;
    c.type = pColNode->node.resType.type;
    c.bytes = pColNode->node.resType.bytes;
4911 4912 4913 4914 4915 4916 4917 4918 4919
    c.precision = pColNode->node.resType.precision;
    c.scale = pColNode->node.resType.scale;

    taosArrayPush(pList, &c);
  }

  return pList;
}

4920
SArray* createSortInfo(SNodeList* pNodeList) {
L
Liu Jicong 已提交
4921
  size_t  numOfCols = LIST_LENGTH(pNodeList);
H
Haojun Liao 已提交
4922 4923 4924 4925 4926 4927
  SArray* pList = taosArrayInit(numOfCols, sizeof(SBlockOrderInfo));
  if (pList == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return pList;
  }

L
Liu Jicong 已提交
4928
  for (int32_t i = 0; i < numOfCols; ++i) {
4929
    SOrderByExprNode* pSortKey = (SOrderByExprNode*)nodesListGetNode(pNodeList, i);
L
Liu Jicong 已提交
4930 4931
    SBlockOrderInfo   bi = {0};
    bi.order = (pSortKey->order == ORDER_ASC) ? TSDB_ORDER_ASC : TSDB_ORDER_DESC;
H
Haojun Liao 已提交
4932 4933 4934
    bi.nullFirst = (pSortKey->nullOrder == NULL_ORDER_FIRST);

    SColumnNode* pColNode = (SColumnNode*)pSortKey->pExpr;
4935
    bi.slotId = pColNode->slotId;
H
Haojun Liao 已提交
4936 4937 4938 4939 4940 4941
    taosArrayPush(pList, &bi);
  }

  return pList;
}

X
Xiaoyu Wang 已提交
4942
SArray* extractColMatchInfo(SNodeList* pNodeList, SDataBlockDescNode* pOutputNodeList, int32_t* numOfOutputCols,
4943
                            SExecTaskInfo* pTaskInfo, int32_t type) {
L
Liu Jicong 已提交
4944
  size_t  numOfCols = LIST_LENGTH(pNodeList);
H
Haojun Liao 已提交
4945 4946 4947 4948 4949 4950
  SArray* pList = taosArrayInit(numOfCols, sizeof(SColMatchInfo));
  if (pList == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

L
Liu Jicong 已提交
4951 4952 4953
  for (int32_t i = 0; i < numOfCols; ++i) {
    STargetNode* pNode = (STargetNode*)nodesListGetNode(pNodeList, i);
    SColumnNode* pColNode = (SColumnNode*)pNode->pExpr;
H
Haojun Liao 已提交
4954 4955

    SColMatchInfo c = {0};
X
Xiaoyu Wang 已提交
4956 4957 4958 4959
    c.output = true;
    c.colId = pColNode->colId;
    c.srcSlotId = pColNode->slotId;
    c.matchType = type;
H
Haojun Liao 已提交
4960 4961 4962 4963
    c.targetSlotId = pNode->slotId;
    taosArrayPush(pList, &c);
  }

H
Haojun Liao 已提交
4964 4965
  *numOfOutputCols = 0;
  int32_t num = LIST_LENGTH(pOutputNodeList->pSlots);
L
Liu Jicong 已提交
4966 4967
  for (int32_t i = 0; i < num; ++i) {
    SSlotDescNode* pNode = (SSlotDescNode*)nodesListGetNode(pOutputNodeList->pSlots, i);
4968

4969
    // todo: add reserve flag check
4970 4971
    // it is a column reserved for the arithmetic expression calculation
    if (pNode->slotId >= numOfCols) {
4972 4973 4974 4975
      (*numOfOutputCols) += 1;
      continue;
    }

H
Haojun Liao 已提交
4976
    SColMatchInfo* info = taosArrayGet(pList, pNode->slotId);
H
Haojun Liao 已提交
4977 4978 4979 4980 4981
    if (pNode->output) {
      (*numOfOutputCols) += 1;
    } else {
      info->output = false;
    }
H
Haojun Liao 已提交
4982 4983
  }

H
Haojun Liao 已提交
4984 4985 4986
  return pList;
}

dengyihao's avatar
dengyihao 已提交
4987 4988
int32_t getTableList(void* metaHandle, int32_t tableType, uint64_t tableUid, STableListInfo* pListInfo,
                     SNode* pTagCond) {
wmmhello's avatar
wmmhello 已提交
4989
  int32_t code = TSDB_CODE_SUCCESS;
wmmhello's avatar
wmmhello 已提交
4990
  pListInfo->pTableList = taosArrayInit(8, sizeof(STableKeyInfo));
wmmhello's avatar
wmmhello 已提交
4991

wmmhello's avatar
wmmhello 已提交
4992
  if (tableType == TSDB_SUPER_TABLE) {
dengyihao's avatar
dengyihao 已提交
4993
    if (pTagCond) {
dengyihao's avatar
dengyihao 已提交
4994 4995
      SIndexMetaArg metaArg = {
          .metaEx = metaHandle, .idx = tsdbGetIdx(metaHandle), .ivtIdx = tsdbGetIvtIdx(metaHandle), .suid = tableUid};
dengyihao's avatar
dengyihao 已提交
4996

wmmhello's avatar
wmmhello 已提交
4997
      SArray* res = taosArrayInit(8, sizeof(uint64_t));
dengyihao's avatar
dengyihao 已提交
4998
      code = doFilterTag(pTagCond, &metaArg, res);
wmmhello's avatar
wmmhello 已提交
4999
      if (code != TSDB_CODE_SUCCESS) {
dengyihao's avatar
dengyihao 已提交
5000
        qError("failed  to  get tableIds, reason: %s, suid: %" PRIu64 "", tstrerror(code), tableUid);
wmmhello's avatar
wmmhello 已提交
5001
        taosArrayDestroy(res);
wmmhello's avatar
wmmhello 已提交
5002
        terrno = code;
wmmhello's avatar
wmmhello 已提交
5003
        return code;
dengyihao's avatar
dengyihao 已提交
5004
      } else {
dengyihao's avatar
dengyihao 已提交
5005
        qDebug("sucess to  get tableIds, size: %d, suid: %" PRIu64 "", (int)taosArrayGetSize(res), tableUid);
wmmhello's avatar
wmmhello 已提交
5006
      }
dengyihao's avatar
dengyihao 已提交
5007
      for (int i = 0; i < taosArrayGetSize(res); i++) {
wmmhello's avatar
wmmhello 已提交
5008 5009 5010 5011
        STableKeyInfo info = {.lastKey = TSKEY_INITIAL_VAL, .uid = *(uint64_t*)taosArrayGet(res, i)};
        taosArrayPush(pListInfo->pTableList, &info);
      }
      taosArrayDestroy(res);
dengyihao's avatar
dengyihao 已提交
5012
    } else {
wmmhello's avatar
wmmhello 已提交
5013
      code = tsdbGetAllTableList(metaHandle, tableUid, pListInfo->pTableList);
wmmhello's avatar
wmmhello 已提交
5014
    }
H
Haojun Liao 已提交
5015
  } else {  // Create one table group.
wmmhello's avatar
wmmhello 已提交
5016 5017
    STableKeyInfo info = {.lastKey = 0, .uid = tableUid};
    taosArrayPush(pListInfo->pTableList, &info);
5018 5019 5020 5021
  }

  return code;
}
H
Haojun Liao 已提交
5022

wmmhello's avatar
wmmhello 已提交
5023
SArray* extractTableIdList(const STableListInfo* pTableGroupInfo) {
5024 5025
  SArray* tableIdList = taosArrayInit(4, sizeof(uint64_t));

wmmhello's avatar
wmmhello 已提交
5026 5027 5028 5029
  // Transfer the Array of STableKeyInfo into uid list.
  for (int32_t i = 0; i < taosArrayGetSize(pTableGroupInfo->pTableList); ++i) {
    STableKeyInfo* pkeyInfo = taosArrayGet(pTableGroupInfo->pTableList, i);
    taosArrayPush(tableIdList, &pkeyInfo->uid);
5030 5031 5032 5033 5034
  }

  return tableIdList;
}

L
Liu Jicong 已提交
5035
tsdbReaderT doCreateDataReader(STableScanPhysiNode* pTableScanNode, SReadHandle* pHandle,
wmmhello's avatar
wmmhello 已提交
5036
                               STableListInfo* pTableListInfo, uint64_t queryId, uint64_t taskId, SNode* pTagCond) {
dengyihao's avatar
dengyihao 已提交
5037 5038
  int32_t code =
      getTableList(pHandle->meta, pTableScanNode->scan.tableType, pTableScanNode->scan.uid, pTableListInfo, pTagCond);
wmmhello's avatar
wmmhello 已提交
5039 5040 5041 5042 5043 5044 5045 5046 5047 5048
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }

  if (taosArrayGetSize(pTableListInfo->pTableList) == 0) {
    code = 0;
    qDebug("no table qualified for query, TID:0x%" PRIx64 ", QID:0x%" PRIx64, taskId, queryId);
    goto _error;
  }

5049
  SQueryTableDataCond cond = {0};
wmmhello's avatar
wmmhello 已提交
5050
  code = initQueryTableDataCond(&cond, pTableScanNode);
5051
  if (code != TSDB_CODE_SUCCESS) {
wmmhello's avatar
wmmhello 已提交
5052
    goto _error;
X
Xiaoyu Wang 已提交
5053
  }
5054

wmmhello's avatar
wmmhello 已提交
5055
  return tsdbQueryTables(pHandle->vnode, &cond, pTableListInfo, queryId, taskId);
wmmhello's avatar
wmmhello 已提交
5056 5057 5058 5059

_error:
  terrno = code;
  return NULL;
H
Haojun Liao 已提交
5060 5061
}

5062
int32_t encodeOperator(SOperatorInfo* ops, char** result, int32_t* length) {
wmmhello's avatar
wmmhello 已提交
5063
  int32_t code = TDB_CODE_SUCCESS;
5064
  char*   pCurrent = NULL;
wmmhello's avatar
wmmhello 已提交
5065
  int32_t currLength = 0;
5066 5067
  if (ops->fpSet.encodeResultRow) {
    if (result == NULL || length == NULL) {
wmmhello's avatar
wmmhello 已提交
5068 5069 5070
      return TSDB_CODE_TSC_INVALID_INPUT;
    }
    code = ops->fpSet.encodeResultRow(ops, &pCurrent, &currLength);
wmmhello's avatar
wmmhello 已提交
5071

5072 5073
    if (code != TDB_CODE_SUCCESS) {
      if (*result != NULL) {
wmmhello's avatar
wmmhello 已提交
5074 5075 5076 5077 5078
        taosMemoryFree(*result);
        *result = NULL;
      }
      return code;
    }
wmmhello's avatar
wmmhello 已提交
5079

5080
    if (*result == NULL) {
wmmhello's avatar
wmmhello 已提交
5081
      *result = (char*)taosMemoryCalloc(1, currLength + sizeof(int32_t));
wmmhello's avatar
wmmhello 已提交
5082 5083 5084 5085 5086 5087
      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);
5088
    } else {
wmmhello's avatar
wmmhello 已提交
5089
      int32_t sizePre = *(int32_t*)(*result);
5090
      char*   tmp = (char*)taosMemoryRealloc(*result, sizePre + currLength);
wmmhello's avatar
wmmhello 已提交
5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102
      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 已提交
5103 5104
  }

wmmhello's avatar
wmmhello 已提交
5105 5106
  for (int32_t i = 0; i < ops->numOfDownstream; ++i) {
    code = encodeOperator(ops->pDownstream[i], result, length);
5107
    if (code != TDB_CODE_SUCCESS) {
wmmhello's avatar
wmmhello 已提交
5108
      return code;
wmmhello's avatar
wmmhello 已提交
5109 5110
    }
  }
wmmhello's avatar
wmmhello 已提交
5111
  return TDB_CODE_SUCCESS;
wmmhello's avatar
wmmhello 已提交
5112 5113
}

5114
int32_t decodeOperator(SOperatorInfo* ops, char* result, int32_t length) {
wmmhello's avatar
wmmhello 已提交
5115
  int32_t code = TDB_CODE_SUCCESS;
5116 5117
  if (ops->fpSet.decodeResultRow) {
    if (result == NULL) {
wmmhello's avatar
wmmhello 已提交
5118 5119
      return TSDB_CODE_TSC_INVALID_INPUT;
    }
5120 5121 5122
    ASSERT(length == *(int32_t*)result);
    char* data = result + sizeof(int32_t);
    code = ops->fpSet.decodeResultRow(ops, data);
5123
    if (code != TDB_CODE_SUCCESS) {
wmmhello's avatar
wmmhello 已提交
5124 5125
      return code;
    }
wmmhello's avatar
wmmhello 已提交
5126

wmmhello's avatar
wmmhello 已提交
5127
    int32_t totalLength = *(int32_t*)result;
5128 5129
    int32_t dataLength = *(int32_t*)data;

5130
    if (totalLength == dataLength + sizeof(int32_t)) {  // the last data
wmmhello's avatar
wmmhello 已提交
5131 5132
      result = NULL;
      length = 0;
5133
    } else {
wmmhello's avatar
wmmhello 已提交
5134 5135 5136 5137
      result += dataLength;
      *(int32_t*)(result) = totalLength - dataLength;
      length = totalLength - dataLength;
    }
wmmhello's avatar
wmmhello 已提交
5138 5139
  }

wmmhello's avatar
wmmhello 已提交
5140 5141
  for (int32_t i = 0; i < ops->numOfDownstream; ++i) {
    code = decodeOperator(ops->pDownstream[i], result, length);
5142
    if (code != TDB_CODE_SUCCESS) {
wmmhello's avatar
wmmhello 已提交
5143
      return code;
wmmhello's avatar
wmmhello 已提交
5144 5145
    }
  }
wmmhello's avatar
wmmhello 已提交
5146
  return TDB_CODE_SUCCESS;
wmmhello's avatar
wmmhello 已提交
5147 5148
}

5149
int32_t createDataSinkParam(SDataSinkNode* pNode, void** pParam, qTaskInfo_t* pTaskInfo) {
D
dapan1121 已提交
5150
  SExecTaskInfo* pTask = *(SExecTaskInfo**)pTaskInfo;
5151

D
dapan1121 已提交
5152 5153
  switch (pNode->type) {
    case QUERY_NODE_PHYSICAL_PLAN_DELETE: {
5154
      SDeleterParam* pDeleterParam = taosMemoryCalloc(1, sizeof(SDeleterParam));
D
dapan1121 已提交
5155 5156 5157 5158 5159 5160 5161 5162 5163 5164
      if (NULL == pDeleterParam) {
        return TSDB_CODE_OUT_OF_MEMORY;
      }
      int32_t tbNum = taosArrayGetSize(pTask->tableqinfoList.pTableList);
      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) {
5165
        STableKeyInfo* pTable = taosArrayGet(pTask->tableqinfoList.pTableList, i);
D
dapan1121 已提交
5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178
        taosArrayPush(pDeleterParam->pUidList, &pTable->uid);
      }

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

  return TSDB_CODE_SUCCESS;
}

dengyihao's avatar
dengyihao 已提交
5179 5180
int32_t createExecTaskInfoImpl(SSubplan* pPlan, SExecTaskInfo** pTaskInfo, SReadHandle* pHandle, uint64_t taskId,
                               EOPTR_EXEC_MODEL model) {
H
Haojun Liao 已提交
5181 5182
  uint64_t queryId = pPlan->id.queryId;

H
Haojun Liao 已提交
5183
  int32_t code = TSDB_CODE_SUCCESS;
D
dapan1121 已提交
5184
  *pTaskInfo = createExecTaskInfo(queryId, taskId, model, pPlan->dbFName);
H
Haojun Liao 已提交
5185 5186 5187 5188
  if (*pTaskInfo == NULL) {
    code = TSDB_CODE_QRY_OUT_OF_MEMORY;
    goto _complete;
  }
H
Haojun Liao 已提交
5189

dengyihao's avatar
dengyihao 已提交
5190
  (*pTaskInfo)->pRoot = createOperatorTree(pPlan->pNode, *pTaskInfo, pHandle, queryId, taskId,
dengyihao's avatar
dengyihao 已提交
5191
                                           &(*pTaskInfo)->tableqinfoList, pPlan->pTagCond);
D
dapan1121 已提交
5192
  if (NULL == (*pTaskInfo)->pRoot) {
L
Liu Jicong 已提交
5193
    code = terrno;
D
dapan1121 已提交
5194 5195
    goto _complete;
  }
H
Haojun Liao 已提交
5196

5197
  if ((*pTaskInfo)->pRoot == NULL) {
H
Haojun Liao 已提交
5198
    code = TSDB_CODE_QRY_OUT_OF_MEMORY;
H
Haojun Liao 已提交
5199
    goto _complete;
5200 5201
  }

H
Haojun Liao 已提交
5202 5203
  return code;

H
Haojun Liao 已提交
5204
_complete:
wafwerar's avatar
wafwerar 已提交
5205
  taosMemoryFreeClear(*pTaskInfo);
H
Haojun Liao 已提交
5206 5207 5208

  terrno = code;
  return code;
H
Haojun Liao 已提交
5209 5210
}

wmmhello's avatar
wmmhello 已提交
5211 5212 5213
static void doDestroyTableList(STableListInfo* pTableqinfoList) {
  taosArrayDestroy(pTableqinfoList->pTableList);
  taosHashCleanup(pTableqinfoList->map);
5214

wmmhello's avatar
wmmhello 已提交
5215 5216
  pTableqinfoList->pTableList = NULL;
  pTableqinfoList->map = NULL;
5217 5218
}

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

wmmhello's avatar
wmmhello 已提交
5222
  doDestroyTableList(&pTaskInfo->tableqinfoList);
H
Haojun Liao 已提交
5223
  destroyOperatorInfo(pTaskInfo->pRoot);
L
Liu Jicong 已提交
5224 5225
  //  taosArrayDestroy(pTaskInfo->summary.queryProfEvents);
  //  taosHashCleanup(pTaskInfo->summary.operatorProfResults);
5226

5227 5228
  taosMemoryFree(pTaskInfo->schemaVer.dbname);
  taosMemoryFree(pTaskInfo->schemaVer.tablename);
wafwerar's avatar
wafwerar 已提交
5229 5230 5231
  taosMemoryFreeClear(pTaskInfo->sql);
  taosMemoryFreeClear(pTaskInfo->id.str);
  taosMemoryFreeClear(pTaskInfo);
5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243
}

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 已提交
5244
      int32_t len = (varDataLen(val) > maxLen) ? maxLen : varDataLen(val);
5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256
      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 已提交
5257 5258
  //  size_t s3 = sizeof(STableCheckInfo);  buffer consumption in tsdb
  return (int64_t)(s1 * 1.5 * numOfTables);
5259 5260 5261 5262 5263 5264 5265
}

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 已提交
5266
    while (1) {
5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292
      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 已提交
5293

dengyihao's avatar
dengyihao 已提交
5294 5295
int32_t getOperatorExplainExecInfo(SOperatorInfo* operatorInfo, SExplainExecInfo** pRes, int32_t* capacity,
                                   int32_t* resNum) {
D
dapan1121 已提交
5296 5297
  if (*resNum >= *capacity) {
    *capacity += 10;
dengyihao's avatar
dengyihao 已提交
5298

D
dapan1121 已提交
5299 5300
    *pRes = taosMemoryRealloc(*pRes, (*capacity) * sizeof(SExplainExecInfo));
    if (NULL == *pRes) {
D
dapan1121 已提交
5301
      qError("malloc %d failed", (*capacity) * (int32_t)sizeof(SExplainExecInfo));
D
dapan1121 已提交
5302 5303 5304 5305
      return TSDB_CODE_QRY_OUT_OF_MEMORY;
    }
  }

5306 5307 5308 5309 5310
  SExplainExecInfo* pInfo = &(*pRes)[*resNum];

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

5312
  if (operatorInfo->fpSet.getExplainFn) {
5313
    int32_t code = operatorInfo->fpSet.getExplainFn(operatorInfo, &pInfo->verboseInfo, &pInfo->verboseLen);
D
dapan1121 已提交
5314
    if (code) {
5315
      qError("%s operator getExplainFn failed, code:%s", GET_TASKID(operatorInfo->pTaskInfo), tstrerror(code));
D
dapan1121 已提交
5316 5317
      return code;
    }
5318 5319 5320
  } else {
    pInfo->verboseLen = 0;
    pInfo->verboseInfo = NULL;
D
dapan1121 已提交
5321
  }
dengyihao's avatar
dengyihao 已提交
5322

D
dapan1121 已提交
5323
  ++(*resNum);
dengyihao's avatar
dengyihao 已提交
5324

D
dapan1121 已提交
5325
  int32_t code = 0;
D
dapan1121 已提交
5326 5327
  for (int32_t i = 0; i < operatorInfo->numOfDownstream; ++i) {
    code = getOperatorExplainExecInfo(operatorInfo->pDownstream[i], pRes, capacity, resNum);
D
dapan1121 已提交
5328 5329 5330 5331 5332 5333 5334
    if (code) {
      taosMemoryFreeClear(*pRes);
      return TSDB_CODE_QRY_OUT_OF_MEMORY;
    }
  }

  return TSDB_CODE_SUCCESS;
D
dapan1121 已提交
5335
}
5
54liuyao 已提交
5336

5337 5338
int32_t initStreamAggSupporter(SStreamAggSupporter* pSup, const char* pKey, SqlFunctionCtx* pCtx, int32_t numOfOutput, size_t size) {
  pSup->resultRowSize = getResultRowSize(pCtx, numOfOutput);
5
54liuyao 已提交
5339 5340
  pSup->keySize = sizeof(int64_t) + sizeof(TSKEY);
  pSup->pKeyBuf = taosMemoryCalloc(1, pSup->keySize);
5
54liuyao 已提交
5341
  pSup->pResultRows = taosArrayInit(1024, size);
5
54liuyao 已提交
5342 5343 5344 5345
  if (pSup->pKeyBuf == NULL || pSup->pResultRows == NULL) {
    return TSDB_CODE_OUT_OF_MEMORY;
  }

5
54liuyao 已提交
5346 5347
  pSup->pScanWindow = taosArrayInit(4, sizeof(STimeWindow));

5
54liuyao 已提交
5348 5349 5350 5351 5352 5353 5354 5355 5356
  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;
  }
5357 5358 5359 5360 5361
  int32_t code = createDiskbasedBuf(&pSup->pResultBuf, pageSize, bufSize, pKey, TD_TMP_DIR_PATH);
  for(int32_t i = 0; i < numOfOutput; ++i) {
    pCtx[i].pBuf = pSup->pResultBuf;
  }
  return code;
5
54liuyao 已提交
5362 5363
}

5
54liuyao 已提交
5364 5365
int64_t getSmaWaterMark(int64_t interval, double filesFactor) {
  int64_t waterMark = 0;
X
Xiaoyu Wang 已提交
5366
  ASSERT(FLT_GREATEREQUAL(filesFactor, 0.000000));
5
54liuyao 已提交
5367 5368 5369 5370 5371
  waterMark = -1 * filesFactor;
  return waterMark;
}

bool isSmaStream(int8_t triggerType) {
X
Xiaoyu Wang 已提交
5372
  if (triggerType == STREAM_TRIGGER_AT_ONCE || triggerType == STREAM_TRIGGER_WINDOW_CLOSE) {
5
54liuyao 已提交
5373 5374 5375 5376
    return false;
  }
  return true;
}