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

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

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

31
#include "executorimpl.h"
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 90 91 92 93
  }
}

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

#define CLEAR_QUERY_STATUS(q, st)   ((q)->status &= (~(st)))
#define GET_NUM_OF_TABLEGROUP(q)    taosArrayGetSize((q)->tableqinfoGroupInfo.pGroupList)
#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
}

static void doSetTagValueToResultBuf(char* output, const char* val, int16_t type, int16_t bytes);
L
Liu Jicong 已提交
102
static bool functionNeedToExecute(SqlFunctionCtx* pCtx);
103

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

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

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

L
Liu Jicong 已提交
110
static void    releaseQueryBuf(size_t numOfTables);
111

H
Haojun Liao 已提交
112
static int32_t getNumOfScanTimes(STaskAttr* pQueryAttr);
113 114 115 116 117 118

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 已提交
119

H
Haojun Liao 已提交
120
static void destroyIntervalOperatorInfo(void* param, int32_t numOfOutput);
H
Haojun Liao 已提交
121 122
static void destroyExchangeOperatorInfo(void* param, int32_t numOfOutput);

123
static void destroyOperatorInfo(SOperatorInfo* pOperator);
124
static void destroySysTableScannerOperatorInfo(void* param, int32_t numOfOutput);
125

126
void doSetOperatorCompleted(SOperatorInfo* pOperator) {
127
  pOperator->status = OP_EXEC_DONE;
H
Haojun Liao 已提交
128
  if (pOperator->pTaskInfo != NULL) {
129
    setTaskStatus(pOperator->pTaskInfo, TASK_COMPLETED);
130 131
  }
}
132

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

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

  return fpSet;
}

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

158 159
static int32_t doCopyToSDataBlock(SExecTaskInfo* taskInfo, SSDataBlock* pBlock, SExprInfo* pExprInfo, SDiskbasedBuf* pBuf, SGroupResInfo* pGroupResInfo,
                                  int32_t orderType, 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;
L
Liu Jicong 已提交
185 186
  char*   in1 = getPosInResultPage(pRuntimeEnv->pQueryAttr, page1, pRow1->offset, offset);
  char*   in2 = getPosInResultPage(pRuntimeEnv->pQueryAttr, page2, pRow2->offset, offset);
187 188 189 190

  return (in1 != NULL && in2 != NULL) ? supporter->comFunc(in1, in2) : 0;
}

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

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

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

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

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

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

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

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

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

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

  return true;
}

H
Haojun Liao 已提交
239
static void prepareResultListBuffer(SResultRowInfo* pResultRowInfo, jmp_buf env) {
240 241
  int64_t newCapacity = 0;

242 243 244 245 246 247 248 249 250 251 252
  // more than the capacity, reallocate the resources
  if (pResultRowInfo->size < pResultRowInfo->capacity) {
    return;
  }

  if (pResultRowInfo->capacity > 10000) {
    newCapacity = (int64_t)(pResultRowInfo->capacity * 1.25);
  } else {
    newCapacity = (int64_t)(pResultRowInfo->capacity * 1.5);
  }

253
  if (newCapacity <= pResultRowInfo->capacity) {
H
Haojun Liao 已提交
254 255 256
    newCapacity += 4;
  }

257 258 259 260 261 262
  char* p = taosMemoryRealloc(pResultRowInfo->pPosition, newCapacity * sizeof(SResultRowPosition));
  if (p == NULL) {
    longjmp(env, TSDB_CODE_OUT_OF_MEMORY);
  }

  pResultRowInfo->pPosition = (SResultRowPosition*)p;
263 264

  int32_t inc = (int32_t)newCapacity - pResultRowInfo->capacity;
wmmhello's avatar
wmmhello 已提交
265
  memset(&pResultRowInfo->pPosition[pResultRowInfo->capacity], 0, sizeof(SResultRowPosition) * inc);
266 267 268
  pResultRowInfo->capacity = (int32_t)newCapacity;
}

L
Liu Jicong 已提交
269 270
static bool chkResultRowFromKey(STaskRuntimeEnv* pRuntimeEnv, SResultRowInfo* pResultRowInfo, char* pData,
                                int16_t bytes, bool masterscan, uint64_t uid) {
271 272 273
  bool existed = false;
  SET_RES_WINDOW_KEY(pRuntimeEnv->keyBuf, pData, bytes, uid);

L
Liu Jicong 已提交
274 275
  SResultRow** p1 =
      (SResultRow**)taosHashGet(pRuntimeEnv->pResultRowHashTable, pRuntimeEnv->keyBuf, GET_RES_WINDOW_KEY_LEN(bytes));
276 277 278 279 280 281 282 283 284 285 286

  // 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 已提交
287
        //        existed = (pResultRowInfo->pResult[0] == (*p1));
288 289
      } else {  // check if current pResultRowInfo contains the existed pResultRow
        SET_RES_EXT_WINDOW_KEY(pRuntimeEnv->keyBuf, pData, bytes, uid, pResultRowInfo);
L
Liu Jicong 已提交
290 291
        int64_t* index =
            taosHashGet(pRuntimeEnv->pResultRowListSet, pRuntimeEnv->keyBuf, GET_RES_EXT_WINDOW_KEY_LEN(bytes));
292 293 294 295 296 297 298 299 300 301 302 303 304 305
        if (index != NULL) {
          existed = true;
        } else {
          existed = false;
        }
      }
    }

    return existed;
  }

  return p1 != NULL;
}

306
SResultRow* getNewResultRow_rv(SDiskbasedBuf* pResultBuf, int64_t tableGroupId, int32_t interBufSize) {
L
Liu Jicong 已提交
307
  SFilePage* pData = NULL;
308 309 310 311 312 313 314 315 316 317 318 319 320

  // 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 已提交
321
    if (pData->num + interBufSize > getBufPageSize(pResultBuf)) {
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
      // 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;
  }

  // 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 已提交
341
  pData->num += interBufSize;
342 343 344 345

  return pResultRow;
}

5
54liuyao 已提交
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367
void doClearWindow(SIntervalAggOperatorInfo* pInfo, char* pData, int16_t bytes,
    uint64_t groupId, int32_t numOfOutput) {
  SAggSupporter* pSup = &pInfo->aggSup;
  SET_RES_WINDOW_KEY(pSup->keyBuf, pData, bytes, groupId);
  SResultRowPosition* p1 =
      (SResultRowPosition*)taosHashGet(pSup->pResultRowHashTable, pSup->keyBuf,
          GET_RES_WINDOW_KEY_LEN(bytes));
  SResultRow* pResult = getResultRowByPos(pSup->pResultBuf, p1);
  SqlFunctionCtx* pCtx = pInfo->binfo.pCtx;
  for (int32_t i = 0; i < numOfOutput; ++i) {
    pCtx[i].resultInfo = getResultCell(pResult, i, pInfo->binfo.rowCellInfoOffset);
    struct SResultRowEntryInfo* pResInfo = pCtx[i].resultInfo;
    if (fmIsWindowPseudoColumnFunc(pCtx[i].functionId)) {
      continue;
    }
    pResInfo->initialized = false;
    if (pCtx[i].functionId != -1) {
      pCtx[i].fpSet.init(&pCtx[i], pResInfo);
    }
  }
}

368 369 370 371 372 373 374
/**
 * the struct of key in hash table
 * +----------+---------------+
 * | group id |   key data    |
 * | 8 bytes  | actual length |
 * +----------+---------------+
 */
375 376 377
SResultRow* doSetResultOutBufByKey(SDiskbasedBuf* pResultBuf, SResultRowInfo* pResultRowInfo, char* pData,
                                   int16_t bytes, bool masterscan, uint64_t groupId, SExecTaskInfo* pTaskInfo,
                                   bool isIntervalQuery, SAggSupporter* pSup) {
378
  SET_RES_WINDOW_KEY(pSup->keyBuf, pData, bytes, groupId);
H
Haojun Liao 已提交
379

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

383 384
  SResultRow* pResult = NULL;

H
Haojun Liao 已提交
385 386
  // in case of repeat scan/reverse scan, no new time window added.
  if (isIntervalQuery) {
387 388
    if (masterscan && p1 != NULL) {  // the *p1 may be NULL in case of sliding+offset exists.
      pResult = getResultRowByPos(pResultBuf, p1);
H
Haojun Liao 已提交
389 390
    }
  } else {
dengyihao's avatar
dengyihao 已提交
391 392
    // In case of group by column query, the required SResultRow object must be existInCurrentResusltRowInfo in the
    // pResultRowInfo object.
H
Haojun Liao 已提交
393
    if (p1 != NULL) {
394
      pResult = getResultRowByPos(pResultBuf, p1);
H
Haojun Liao 已提交
395 396 397
    }
  }

L
Liu Jicong 已提交
398
  // 1. close current opened time window
399
  if (pResultRowInfo->cur.pageId != -1 && ((pResult == NULL) || (pResult->pageId != pResultRowInfo->cur.pageId &&
L
Liu Jicong 已提交
400
                                                                 pResult->offset != pResultRowInfo->cur.offset))) {
401 402 403 404 405 406 407 408 409 410 411
    // todo extract function
    SResultRowPosition pos = pResultRowInfo->cur;
    SFilePage*         pPage = getBufPage(pResultBuf, pos.pageId);
    SResultRow*        pRow = (SResultRow*)((char*)pPage + pos.offset);
    closeResultRow(pRow);
    releaseBufPage(pResultBuf, pPage);
  }

  // allocate a new buffer page
  prepareResultListBuffer(pResultRowInfo, pTaskInfo->env);
  if (pResult == NULL) {
H
Haojun Liao 已提交
412
    ASSERT(pSup->resultRowSize > 0);
413 414
    pResult = getNewResultRow_rv(pResultBuf, groupId, pSup->resultRowSize);
    initResultRow(pResult);
H
Haojun Liao 已提交
415

416 417
    // add a new result set for a new group
    SResultRowPosition pos = {.pageId = pResult->pageId, .offset = pResult->offset};
L
Liu Jicong 已提交
418 419
    taosHashPut(pSup->pResultRowHashTable, pSup->keyBuf, GET_RES_WINDOW_KEY_LEN(bytes), &pos,
                sizeof(SResultRowPosition));
H
Haojun Liao 已提交
420 421
  }

422 423 424 425 426
  // 2. set the new time window to be the new active time window
  pResultRowInfo->pPosition[pResultRowInfo->size++] =
      (SResultRowPosition){.pageId = pResult->pageId, .offset = pResult->offset};
  pResultRowInfo->cur = (SResultRowPosition){.pageId = pResult->pageId, .offset = pResult->offset};

H
Haojun Liao 已提交
427 428 429 430 431
  // too many time window in query
  if (pResultRowInfo->size > MAX_INTERVAL_TIME_WINDOW) {
    longjmp(pTaskInfo->env, TSDB_CODE_QRY_TOO_MANY_TIMEWINDOW);
  }

H
Haojun Liao 已提交
432
  return pResult;
H
Haojun Liao 已提交
433 434
}

435
// get the correct time window according to the handled timestamp
L
Liu Jicong 已提交
436
static STimeWindow getCurrentActiveTimeWindow(SResultRowInfo* pResultRowInfo, int64_t ts, STaskAttr* pQueryAttr) {
437
  STimeWindow w = {0};
H
Haojun Liao 已提交
438
#if 0
L
Liu Jicong 已提交
439 440
  if (pResultRowInfo->curPos == -1) {  // the first window, from the previous stored value
                                       //    getInitialStartTimeWindow(pQueryAttr, ts, &w);
441 442

    if (pQueryAttr->interval.intervalUnit == 'n' || pQueryAttr->interval.intervalUnit == 'y') {
L
Liu Jicong 已提交
443 444 445
      w.ekey =
          taosTimeAdd(w.skey, pQueryAttr->interval.interval, pQueryAttr->interval.intervalUnit, pQueryAttr->precision) -
          1;
446 447 448 449
    } else {
      w.ekey = w.skey + pQueryAttr->interval.interval - 1;
    }
  } else {
H
Haojun Liao 已提交
450
    w = pRow->win;
451 452 453 454 455 456 457 458 459
  }

  /*
   * 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 已提交
460
#endif
461 462 463 464 465

  return w;
}

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

L
Liu Jicong 已提交
471
  SFilePage* pData = NULL;
472 473 474 475 476 477

  // 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 已提交
478
    pData = getNewBufPage(pResultBuf, tid, &pageId);
479
    pData->num = sizeof(SFilePage);
480 481
  } else {
    SPageInfo* pi = getLastPageInfo(list);
482
    pData = getBufPage(pResultBuf, getPageId(pi));
483
    pageId = getPageId(pi);
484

485
    if (pData->num + size > getBufPageSize(pResultBuf)) {
486
      // release current page first, and prepare the next one
487
      releaseBufPageInfo(pResultBuf, pi);
488

H
Haojun Liao 已提交
489
      pData = getNewBufPage(pResultBuf, tid, &pageId);
490
      if (pData != NULL) {
491
        pData->num = sizeof(SFilePage);
492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511
      }
    }
  }

  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 已提交
512 513 514
static bool chkWindowOutputBufByKey(STaskRuntimeEnv* pRuntimeEnv, SResultRowInfo* pResultRowInfo, STimeWindow* win,
                                    bool masterscan, SResultRow** pResult, int64_t groupId, SqlFunctionCtx* pCtx,
                                    int32_t numOfOutput, int32_t* rowCellInfoOffset) {
515
  assert(win->skey <= win->ekey);
L
Liu Jicong 已提交
516
  return chkResultRowFromKey(pRuntimeEnv, pResultRowInfo, (char*)&win->skey, TSDB_KEYSIZE, masterscan, groupId);
517 518
}

dengyihao's avatar
dengyihao 已提交
519 520
static void doUpdateResultRowIndex(SResultRowInfo* pResultRowInfo, TSKEY lastKey, bool ascQuery,
                                   bool timeWindowInterpo) {
521
  int64_t skey = TSKEY_INITIAL_VAL;
H
Haojun Liao 已提交
522
#if 0
523 524
  int32_t i = 0;
  for (i = pResultRowInfo->size - 1; i >= 0; --i) {
L
Liu Jicong 已提交
525
    SResultRow* pResult = pResultRowInfo->pResult[i];
526 527 528 529 530 531
    if (pResult->closed) {
      break;
    }

    // new closed result rows
    if (timeWindowInterpo) {
L
Liu Jicong 已提交
532 533 534
      if (pResult->endInterp &&
          ((pResult->win.skey <= lastKey && ascQuery) || (pResult->win.skey >= lastKey && !ascQuery))) {
        if (i > 0) {  // the first time window, the startInterp is false.
535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553
          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 已提交
554
      //      assert(pResultRowInfo->current == NULL);
555 556 557 558 559 560 561
      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 已提交
562
      SResultRow* pResult = pResultRowInfo->pResult[i];
563 564 565 566 567 568 569 570 571 572 573
      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 已提交
574
#endif
575
}
576
//
dengyihao's avatar
dengyihao 已提交
577
// static void updateResultRowInfoActiveIndex(SResultRowInfo* pResultRowInfo, const STimeWindow* pWin, TSKEY lastKey,
578 579 580 581 582 583 584 585 586
//                                           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);
//  }
//}
587

588
//  query_range_start, query_range_end, window_duration, window_start, window_end
589
void initExecTimeWindowInfo(SColumnInfoData* pColData, STimeWindow* pQueryWindow) {
590 591 592
  pColData->info.type = TSDB_DATA_TYPE_TIMESTAMP;
  pColData->info.bytes = sizeof(int64_t);

593
  colInfoDataEnsureCapacity(pColData, 0, 5);
594 595 596 597 598 599 600 601 602
  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);
}

603
void doApplyFunctions(SExecTaskInfo* taskInfo, SqlFunctionCtx* pCtx, STimeWindow* pWin, SColumnInfoData* pTimeWindowData, int32_t offset,
dengyihao's avatar
dengyihao 已提交
604
                      int32_t forwardStep, TSKEY* tsCol, int32_t numOfTotal, int32_t numOfOutput, int32_t order) {
605 606 607
  for (int32_t k = 0; k < numOfOutput; ++k) {
    pCtx[k].startTs = pWin->skey;

H
Haojun Liao 已提交
608
    // keep it temporarily
dengyihao's avatar
dengyihao 已提交
609 610
    bool    hasAgg = pCtx[k].input.colDataAggIsSet;
    int32_t numOfRows = pCtx[k].input.numOfRows;
H
Haojun Liao 已提交
611
    int32_t startOffset = pCtx[k].input.startRowIndex;
612

H
Haojun Liao 已提交
613
    int32_t pos = (order == TSDB_ORDER_ASC) ? offset : offset - (forwardStep - 1);
614 615
    pCtx[k].input.startRowIndex = pos;
    pCtx[k].input.numOfRows = forwardStep;
616 617

    if (tsCol != NULL) {
H
Haojun Liao 已提交
618
      pCtx[k].ptsList = tsCol;
619 620 621 622 623 624 625 626
    }

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

627 628
    if (fmIsWindowPseudoColumnFunc(pCtx[k].functionId)) {
      SResultRowEntryInfo* pEntryInfo = GET_RES_INFO(&pCtx[k]);
dengyihao's avatar
dengyihao 已提交
629
      char*                p = GET_ROWCELL_INTERBUF(pEntryInfo);
630

631
      SColumnInfoData idata = {0};
dengyihao's avatar
dengyihao 已提交
632
      idata.info.type = TSDB_DATA_TYPE_BIGINT;
633
      idata.info.bytes = tDataTypes[TSDB_DATA_TYPE_BIGINT].bytes;
dengyihao's avatar
dengyihao 已提交
634
      idata.pData = p;
635 636 637 638

      SScalarParam out = {.columnData = &idata};
      SScalarParam tw = {.numOfRows = 5, .columnData = pTimeWindowData};
      pCtx[k].sfp.process(&tw, 1, &out);
639 640 641
      pEntryInfo->numOfRes = 1;
      continue;
    }
642
    int32_t code = TSDB_CODE_SUCCESS;
643
    if (functionNeedToExecute(&pCtx[k]) && pCtx[k].fpSet.process != NULL) {
644 645 646 647 648 649
      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);
      }
650 651 652
    }

    // restore it
653 654 655
    pCtx[k].input.colDataAggIsSet = hasAgg;
    pCtx[k].input.startRowIndex = startOffset;
    pCtx[k].input.numOfRows = numOfRows;
656 657 658
  }
}

L
Liu Jicong 已提交
659
static FORCE_INLINE TSKEY reviseWindowEkey(STaskAttr* pQueryAttr, STimeWindow* pWindow) {
dengyihao's avatar
dengyihao 已提交
660
  TSKEY   ekey = -1;
661 662
  int32_t order = TSDB_ORDER_ASC;
  if (order == TSDB_ORDER_ASC) {
663 664 665 666 667 668 669 670 671 672 673 674 675 676
    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 已提交
677
static int32_t doSetInputDataBlock(SOperatorInfo* pOperator, SqlFunctionCtx* pCtx, SSDataBlock* pBlock, int32_t order,
678
                                   int32_t scanFlag, bool createDummyCol);
679

dengyihao's avatar
dengyihao 已提交
680 681
static void doSetInputDataBlockInfo(SOperatorInfo* pOperator, SqlFunctionCtx* pCtx, SSDataBlock* pBlock,
                                    int32_t order) {
682
  for (int32_t i = 0; i < pOperator->numOfExprs; ++i) {
683
    pCtx[i].order = order;
L
Liu Jicong 已提交
684
    pCtx[i].size = pBlock->info.rows;
685
    setBlockStatisInfo(&pCtx[i], &pOperator->pExpr[i], pBlock);
686 687 688
  }
}

689
void setInputDataBlock(SOperatorInfo* pOperator, SqlFunctionCtx* pCtx, SSDataBlock* pBlock, int32_t order, int32_t scanFlag,
dengyihao's avatar
dengyihao 已提交
690
                       bool createDummyCol) {
691
  if (pBlock->pBlockAgg != NULL) {
H
Haojun Liao 已提交
692
    doSetInputDataBlockInfo(pOperator, pCtx, pBlock, order);
693
  } else {
694
    doSetInputDataBlock(pOperator, pCtx, pBlock, order, scanFlag, createDummyCol);
H
Haojun Liao 已提交
695
  }
696 697
}

L
Liu Jicong 已提交
698 699
static int32_t doCreateConstantValColumnInfo(SInputColumnInfoData* pInput, SFunctParam* pFuncParam, int32_t paramIndex,
                                             int32_t numOfRows) {
700 701 702 703 704 705 706 707
  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)
708 709
    pColInfo->info.type = pFuncParam->param.nType;
    pColInfo->info.bytes = pFuncParam->param.nLen;
710 711

    pInput->pData[paramIndex] = pColInfo;
712 713
  } else {
    pColInfo = pInput->pData[paramIndex];
714 715
  }

716
  colInfoDataEnsureCapacity(pColInfo, 0, numOfRows);
717

718
  int8_t type = pFuncParam->param.nType;
719 720
  if (type == TSDB_DATA_TYPE_BIGINT || type == TSDB_DATA_TYPE_UBIGINT) {
    int64_t v = pFuncParam->param.i;
dengyihao's avatar
dengyihao 已提交
721
    for (int32_t i = 0; i < numOfRows; ++i) {
722 723 724 725
      colDataAppendInt64(pColInfo, i, &v);
    }
  } else if (type == TSDB_DATA_TYPE_DOUBLE) {
    double v = pFuncParam->param.d;
dengyihao's avatar
dengyihao 已提交
726
    for (int32_t i = 0; i < numOfRows; ++i) {
727 728
      colDataAppendDouble(pColInfo, i, &v);
    }
729
  } else if (type == TSDB_DATA_TYPE_VARCHAR) {
L
Liu Jicong 已提交
730
    char* tmp = taosMemoryMalloc(pFuncParam->param.nLen + VARSTR_HEADER_SIZE);
731
    STR_WITH_SIZE_TO_VARSTR(tmp, pFuncParam->param.pz, pFuncParam->param.nLen);
L
Liu Jicong 已提交
732
    for (int32_t i = 0; i < numOfRows; ++i) {
733 734
      colDataAppend(pColInfo, i, tmp, false);
    }
735 736 737 738 739
  }

  return TSDB_CODE_SUCCESS;
}

dengyihao's avatar
dengyihao 已提交
740
static int32_t doSetInputDataBlock(SOperatorInfo* pOperator, SqlFunctionCtx* pCtx, SSDataBlock* pBlock, int32_t order,
741
    int32_t scanFlag, bool createDummyCol) {
742 743
  int32_t code = TSDB_CODE_SUCCESS;

744
  for (int32_t i = 0; i < pOperator->numOfExprs; ++i) {
L
Liu Jicong 已提交
745 746 747
    pCtx[i].order = order;
    pCtx[i].size = pBlock->info.rows;
    pCtx[i].pSrcBlock = pBlock;
748
    pCtx[i].scanFlag  = scanFlag;
H
Haojun Liao 已提交
749

750
    SInputColumnInfoData* pInput = &pCtx[i].input;
751
    pInput->uid = pBlock->info.uid;
C
Cary Xu 已提交
752
    pInput->colDataAggIsSet = false;
753

754 755
    SExprInfo* pOneExpr = &pOperator->pExpr[i];
    for (int32_t j = 0; j < pOneExpr->base.numOfParams; ++j) {
dengyihao's avatar
dengyihao 已提交
756
      SFunctParam* pFuncParam = &pOneExpr->base.pParam[j];
G
Ganlin Zhao 已提交
757 758
      if (pFuncParam->type == FUNC_PARAM_TYPE_COLUMN) {
        int32_t slotId = pFuncParam->pCol->slotId;
dengyihao's avatar
dengyihao 已提交
759
        pInput->pData[j] = taosArrayGet(pBlock->pDataBlock, slotId);
760 761 762
        pInput->totalRows = pBlock->info.rows;
        pInput->numOfRows = pBlock->info.rows;
        pInput->startRowIndex = 0;
763

764
        // NOTE: the last parameter is the primary timestamp column
765 766 767
        if (fmIsTimelineFunc(pCtx[i].functionId) && (j == pOneExpr->base.numOfParams - 1)) {
          pInput->pPTS = pInput->pData[j];
        }
768 769
        ASSERT(pInput->pData[j] != NULL);
      } else if (pFuncParam->type == FUNC_PARAM_TYPE_VALUE) {
770 771 772
        // 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) {
773 774 775 776
          pInput->totalRows = pBlock->info.rows;
          pInput->numOfRows = pBlock->info.rows;
          pInput->startRowIndex = 0;

777
          code = doCreateConstantValColumnInfo(pInput, pFuncParam, j, pBlock->info.rows);
778 779 780
          if (code != TSDB_CODE_SUCCESS) {
            return code;
          }
781
        }
G
Ganlin Zhao 已提交
782 783
      }
    }
H
Haojun Liao 已提交
784

H
Haojun Liao 已提交
785
    //    setBlockStatisInfo(&pCtx[i], pBlock, pOperator->pExpr[i].base.pColumns);
H
Haojun Liao 已提交
786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823
    //      uint32_t flag = pOperator->pExpr[i].base.pParam[0].pCol->flag;
    //      if (TSDB_COL_IS_NORMAL_COL(flag) /*|| (pCtx[i].functionId == FUNCTION_BLKINFO) ||
    //          (TSDB_COL_IS_TAG(flag) && pOperator->pRuntimeEnv->scanFlag == MERGE_STAGE)*/) {

    //        SColumn* pCol = pOperator->pExpr[i].base.pParam[0].pCol;
    //        if (pCtx[i].columnIndex == -1) {
    //          for(int32_t j = 0; j < pBlock->info.numOfCols; ++j) {
    //            SColumnInfoData* pColData = taosArrayGet(pBlock->pDataBlock, j);
    //            if (pColData->info.colId == pCol->colId) {
    //              pCtx[i].columnIndex = j;
    //              break;
    //            }
    //          }
    //        }

    //        uint32_t status = aAggs[pCtx[i].functionId].status;
    //        if ((status & (FUNCSTATE_SELECTIVITY | FUNCSTATE_NEED_TS)) != 0) {
    //          SColumnInfoData* tsInfo = taosArrayGet(pBlock->pDataBlock, 0);
    // In case of the top/bottom query again the nest query result, which has no timestamp column
    // don't set the ptsList attribute.
    //          if (tsInfo->info.type == TSDB_DATA_TYPE_TIMESTAMP) {
    //            pCtx[i].ptsList = (int64_t*) tsInfo->pData;
    //          } else {
    //            pCtx[i].ptsList = NULL;
    //          }
    //        }
    //      } else if (TSDB_COL_IS_UD_COL(pCol->flag) && (pOperator->pRuntimeEnv->scanFlag == MERGE_STAGE)) {
    //        SColIndex*       pColIndex = &pOperator->pExpr[i].base.colInfo;
    //        SColumnInfoData* p = taosArrayGet(pBlock->pDataBlock, pColIndex->colIndex);
    //
    //        pCtx[i].pInput = p->pData;
    //        assert(p->info.colId == pColIndex->info.colId && pCtx[i].inputType == p->info.type);
    //        for(int32_t j = 0; j < pBlock->info.rows; ++j) {
    //          char* dst = p->pData + j * p->info.bytes;
    //          taosVariantDump(&pOperator->pExpr[i].base.param[1], dst, p->info.type, true);
    //        }
    //      }
  }
824 825

  return code;
H
Haojun Liao 已提交
826 827
}

828
static int32_t doAggregateImpl(SOperatorInfo* pOperator, TSKEY startTs, SqlFunctionCtx* pCtx) {
829
  for (int32_t k = 0; k < pOperator->numOfExprs; ++k) {
H
Haojun Liao 已提交
830
    if (functionNeedToExecute(&pCtx[k])) {
831 832 833
      pCtx[k].startTs = startTs;
      // todo add a dummy funtion to avoid process check
      if (pCtx[k].fpSet.process != NULL) {
834 835
        int32_t code = pCtx[k].fpSet.process(&pCtx[k]);
        if (code != TSDB_CODE_SUCCESS) {
836 837
          qError("%s aggregate function error happens, code: %s", GET_TASKID(pOperator->pTaskInfo), tstrerror(code));
          return code;
838
        }
839
      }
840 841
    }
  }
842 843

  return TSDB_CODE_SUCCESS;
844 845
}

H
Haojun Liao 已提交
846
static void setPseudoOutputColInfo(SSDataBlock* pResult, SqlFunctionCtx* pCtx, SArray* pPseudoList) {
dengyihao's avatar
dengyihao 已提交
847
  size_t num = (pPseudoList != NULL) ? taosArrayGetSize(pPseudoList) : 0;
H
Haojun Liao 已提交
848 849 850 851 852
  for (int32_t i = 0; i < num; ++i) {
    pCtx[i].pOutput = taosArrayGet(pResult->pDataBlock, i);
  }
}

853
int32_t projectApplyFunctions(SExprInfo* pExpr, SSDataBlock* pResult, SSDataBlock* pSrcBlock, SqlFunctionCtx* pCtx,
X
Xiaoyu Wang 已提交
854
                              int32_t numOfOutput, SArray* pPseudoList) {
H
Haojun Liao 已提交
855
  setPseudoOutputColInfo(pResult, pCtx, pPseudoList);
H
Haojun Liao 已提交
856
  pResult->info.groupId = pSrcBlock->info.groupId;
H
Haojun Liao 已提交
857

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

862 863
  int32_t numOfRows = 0;

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

L
Liu Jicong 已提交
868
    if (pExpr[k].pExpr->nodeType == QUERY_NODE_COLUMN) {  // it is a project query
869
      SColumnInfoData* pColInfoData = taosArrayGet(pResult->pDataBlock, outputSlotId);
870
      if (pResult->info.rows > 0 && !createNewColModel) {
X
Xiaoyu Wang 已提交
871 872
        colDataMergeCol(pColInfoData, pResult->info.rows, &pResult->info.capacity, pfCtx->input.pData[0],
                        pfCtx->input.numOfRows);
873 874 875
      } else {
        colDataAssign(pColInfoData, pfCtx->input.pData[0], pfCtx->input.numOfRows);
      }
876

877
      numOfRows = pfCtx->input.numOfRows;
878
    } else if (pExpr[k].pExpr->nodeType == QUERY_NODE_VALUE) {
879
      SColumnInfoData* pColInfoData = taosArrayGet(pResult->pDataBlock, outputSlotId);
880

dengyihao's avatar
dengyihao 已提交
881
      int32_t offset = createNewColModel ? 0 : pResult->info.rows;
882
      for (int32_t i = 0; i < pSrcBlock->info.rows; ++i) {
dengyihao's avatar
dengyihao 已提交
883 884 885
        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);
886
      }
887 888

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

893
      SColumnInfoData* pResColData = taosArrayGet(pResult->pDataBlock, outputSlotId);
894
      SColumnInfoData  idata = {.info = pResColData->info, .hasNull = true};
895

896
      SScalarParam dest = {.columnData = &idata};
897 898
      scalarCalculate(pExpr[k].pExpr->_optrRoot.pRootNode, pBlockList, &dest);

dengyihao's avatar
dengyihao 已提交
899
      int32_t startOffset = createNewColModel ? 0 : pResult->info.rows;
900
      colInfoDataEnsureCapacity(pResColData, startOffset, pResult->info.capacity);
901
      colDataMergeCol(pResColData, startOffset, &pResult->info.capacity, &idata, dest.numOfRows);
902 903

      numOfRows = dest.numOfRows;
904 905
      taosArrayDestroy(pBlockList);
    } else if (pExpr[k].pExpr->nodeType == QUERY_NODE_FUNCTION) {
906
      ASSERT(!fmIsAggFunc(pfCtx->functionId));
907

908 909
      // _rowts/_c0, not tbname column
      if (fmIsPseudoColumnFunc(pfCtx->functionId) && (!fmIsScanPseudoColumnFunc(pfCtx->functionId))) {
H
Haojun Liao 已提交
910
        // do nothing
911
      } else if (fmIsNonstandardSQLFunc(pfCtx->functionId)) {
dengyihao's avatar
dengyihao 已提交
912
        SResultRowEntryInfo* pResInfo = GET_RES_INFO(&pCtx[k]);
913
        pfCtx->fpSet.init(&pCtx[k], pResInfo);
914

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

918
        // set the timestamp(_rowts) output buffer
919 920
        if (taosArrayGetSize(pPseudoList) > 0) {
          int32_t* outputColIndex = taosArrayGet(pPseudoList, 0);
921
          pfCtx->pTsOutput = (SColumnInfoData*)pCtx[*outputColIndex].pOutput;
922
        }
H
Haojun Liao 已提交
923

924
        numOfRows = pfCtx->fpSet.process(pfCtx);
H
Haojun Liao 已提交
925 926 927
      } else {
        SArray* pBlockList = taosArrayInit(4, POINTER_BYTES);
        taosArrayPush(pBlockList, &pSrcBlock);
G
Ganlin Zhao 已提交
928

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

932
        SScalarParam dest = {.columnData = &idata};
X
Xiaoyu Wang 已提交
933
        int32_t      code = scalarCalculate((SNode*)pExpr[k].pExpr->_function.pFunctNode, pBlockList, &dest);
934 935 936 937
        if (code != TSDB_CODE_SUCCESS) {
          taosArrayDestroy(pBlockList);
          return code;
        }
938

dengyihao's avatar
dengyihao 已提交
939
        int32_t startOffset = createNewColModel ? 0 : pResult->info.rows;
940
        colInfoDataEnsureCapacity(pResColData, startOffset, pResult->info.capacity);
941
        colDataMergeCol(pResColData, startOffset, &pResult->info.capacity, &idata, dest.numOfRows);
942 943

        numOfRows = dest.numOfRows;
H
Haojun Liao 已提交
944 945
        taosArrayDestroy(pBlockList);
      }
946
    } else {
947
      ASSERT(0);
948 949
    }
  }
950

951 952 953
  if (!createNewColModel) {
    pResult->info.rows += numOfRows;
  }
954 955

  return TSDB_CODE_SUCCESS;
956 957
}

958 959 960
static void setResultRowKey(SResultRow* pResultRow, char* pData, int16_t type) {
  if (IS_VAR_DATA_TYPE(type)) {
    // todo disable this
961

962 963 964 965 966 967 968 969 970
    //    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);
971

972 973
    pResultRow->win.skey = v;
    pResultRow->win.ekey = v;
974 975 976
  }
}

977 978 979 980 981
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;
982

983 984 985
  SResultRow* pResultRow =
      doSetResultOutBufByKey(pBuf, pResultRowInfo, (char*)pData, bytes, true, groupId, pTaskInfo, false, pAggSup);
  assert(pResultRow != NULL);
986

987
  setResultRowKey(pResultRow, pData, type);
988
  setResultRowInitCtx(pResultRow, pCtx, numOfCols, binfo->rowCellInfoOffset);
989
  return TSDB_CODE_SUCCESS;
990 991
}

992 993
static bool functionNeedToExecute(SqlFunctionCtx* pCtx) {
  struct SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
994

995 996 997 998 999
  // in case of timestamp column, always generated results.
  int32_t functionId = pCtx->functionId;
  if (functionId == -1) {
    return false;
  }
1000

1001 1002
  if (pCtx->scanFlag == REPEAT_SCAN) {
    return fmIsRepeatScanFunc(pCtx->functionId);
1003 1004
  }

1005 1006
  if (isRowEntryCompleted(pResInfo)) {
    return false;
1007 1008
  }

1009 1010 1011 1012 1013 1014 1015 1016
//  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;
//  }
1017

1018 1019 1020 1021 1022
  // 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;
  //  }
1023 1024 1025 1026

  return true;
}

1027 1028 1029 1030 1031 1032 1033
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;
    }
1034

1035 1036 1037
    // Set the correct column info (data type and bytes)
    pInput->pData[paramIndex]->info.type = type;
    pInput->pData[paramIndex]->info.bytes = tDataTypes[type].bytes;
1038
  }
H
Haojun Liao 已提交
1039

1040 1041 1042 1043 1044 1045
  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;
1046 1047
    }
  } else {
1048
    da = pInput->pColumnDataAgg[paramIndex];
1049 1050
  }

1051
  ASSERT(!IS_VAR_DATA_TYPE(type));
1052

1053 1054 1055 1056 1057 1058
  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};
1059

1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
    *(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
1072
  } else {
1073
    ASSERT(0);
1074 1075
  }

1076 1077
  return TSDB_CODE_SUCCESS;
}
1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088

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;

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

1092 1093
      if (pFuncParam->type == FUNC_PARAM_TYPE_COLUMN) {
        int32_t slotId = pFuncParam->pCol->slotId;
1094 1095 1096 1097
        pInput->pColumnDataAgg[j] = pBlock->pBlockAgg[slotId];
        if (pInput->pColumnDataAgg[j] == NULL) {
          pInput->colDataAggIsSet = false;
        }
1098 1099 1100 1101

        // 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);
1102 1103
      } else if (pFuncParam->type == FUNC_PARAM_TYPE_VALUE) {
        doCreateConstantValColumnAggInfo(pInput, pFuncParam, pFuncParam->param.nType, j, pBlock->info.rows);
1104 1105
      }
    }
1106
  } else {
1107
    pInput->colDataAggIsSet = false;
1108 1109 1110
  }

  // set the statistics data for primary time stamp column
1111 1112 1113 1114 1115
  //  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;
  //  }
1116 1117 1118
}

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

H
Haojun Liao 已提交
1122
  SqlFunctionCtx*  p = NULL;
1123 1124
  SqlFunctionCtx** pValCtx = taosMemoryCalloc(numOfOutput, POINTER_BYTES);
  if (pValCtx == NULL) {
1125 1126 1127 1128
    return TSDB_CODE_QRY_OUT_OF_MEMORY;
  }

  for (int32_t i = 0; i < numOfOutput; ++i) {
1129 1130
    if (strcmp(pCtx[i].pExpr->pExpr->_function.functionName, "_select_value") == 0) {
      pValCtx[num++] = &pCtx[i];
1131
    } else if (fmIsAggFunc(pCtx[i].functionId)) {
1132
      p = &pCtx[i];
1133
    }
1134 1135 1136 1137 1138 1139 1140 1141 1142 1143
//    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
//    }
1144
  }
1145

1146
  if (p != NULL) {
1147
    p->subsidiaries.pCtx = pValCtx;
1148
    p->subsidiaries.num = num;
1149
  } else {
1150
    taosMemoryFreeClear(pValCtx);
1151 1152 1153 1154 1155
  }

  return TSDB_CODE_SUCCESS;
}

1156
SqlFunctionCtx* createSqlFunctionCtx(SExprInfo* pExprInfo, int32_t numOfOutput, int32_t** rowCellInfoOffset) {
L
Liu Jicong 已提交
1157
  SqlFunctionCtx* pFuncCtx = (SqlFunctionCtx*)taosMemoryCalloc(numOfOutput, sizeof(SqlFunctionCtx));
H
Haojun Liao 已提交
1158 1159 1160 1161
  if (pFuncCtx == NULL) {
    return NULL;
  }

wafwerar's avatar
wafwerar 已提交
1162
  *rowCellInfoOffset = taosMemoryCalloc(numOfOutput, sizeof(int32_t));
H
Haojun Liao 已提交
1163
  if (*rowCellInfoOffset == 0) {
wafwerar's avatar
wafwerar 已提交
1164
    taosMemoryFreeClear(pFuncCtx);
H
Haojun Liao 已提交
1165 1166 1167 1168
    return NULL;
  }

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

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

1174
    pCtx->functionId = -1;
1175
    pCtx->curBufPage = -1;
L
Liu Jicong 已提交
1176
    pCtx->pExpr = pExpr;
1177

H
Haojun Liao 已提交
1178
    if (pExpr->pExpr->nodeType == QUERY_NODE_FUNCTION) {
H
Haojun Liao 已提交
1179
      SFuncExecEnv env = {0};
H
Haojun Liao 已提交
1180 1181
      pCtx->functionId = pExpr->pExpr->_function.pFunctNode->funcId;

H
Haojun Liao 已提交
1182
      if (fmIsAggFunc(pCtx->functionId) || fmIsNonstandardSQLFunc(pCtx->functionId)) {
1183 1184 1185 1186
        bool isUdaf = fmIsUserDefinedFunc(pCtx->functionId);
        if (!isUdaf) {
          fmGetFuncExecFuncs(pCtx->functionId, &pCtx->fpSet);
        } else {
1187
          char* udfName = pExpr->pExpr->_function.pFunctNode->functionName;
1188 1189 1190
          strncpy(pCtx->udfName, udfName, strlen(udfName));
          fmGetUdafExecFuncs(pCtx->functionId, &pCtx->fpSet);
        }
1191 1192 1193
        pCtx->fpSet.getEnv(pExpr->pExpr->_function.pFunctNode, &env);
      } else {
        fmGetScalarFuncExecFuncs(pCtx->functionId, &pCtx->sfp);
1194 1195 1196
        if (pCtx->sfp.getEnv != NULL) {
          pCtx->sfp.getEnv(pExpr->pExpr->_function.pFunctNode, &env);
        }
1197
      }
H
Haojun Liao 已提交
1198
      pCtx->resDataInfo.interBufSize = env.calcMemSize;
1199 1200
    } else if (pExpr->pExpr->nodeType == QUERY_NODE_COLUMN || pExpr->pExpr->nodeType == QUERY_NODE_OPERATOR ||
               pExpr->pExpr->nodeType == QUERY_NODE_VALUE) {
H
Haojun Liao 已提交
1201
      // for simple column, the result buffer needs to hold at least one element.
1202
      pCtx->resDataInfo.interBufSize = pFunct->resSchema.bytes;
H
Haojun Liao 已提交
1203
    }
H
Haojun Liao 已提交
1204

H
Haojun Liao 已提交
1205
    pCtx->input.numOfInputCols = pFunct->numOfParams;
wafwerar's avatar
wafwerar 已提交
1206 1207
    pCtx->input.pData = taosMemoryCalloc(pFunct->numOfParams, POINTER_BYTES);
    pCtx->input.pColumnDataAgg = taosMemoryCalloc(pFunct->numOfParams, POINTER_BYTES);
H
Haojun Liao 已提交
1208

1209
    pCtx->pTsOutput = NULL;
L
Liu Jicong 已提交
1210
    pCtx->resDataInfo.bytes = pFunct->resSchema.bytes;
1211
    pCtx->resDataInfo.type = pFunct->resSchema.type;
L
Liu Jicong 已提交
1212
    pCtx->order = TSDB_ORDER_ASC;
1213
    pCtx->start.key = INT64_MIN;
L
Liu Jicong 已提交
1214
    pCtx->end.key = INT64_MIN;
1215
    pCtx->numOfParams = pExpr->base.numOfParams;
H
Haojun Liao 已提交
1216

1217
    pCtx->param = pFunct->pParam;
dengyihao's avatar
dengyihao 已提交
1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251
    //    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 已提交
1252 1253
  }

L
Liu Jicong 已提交
1254 1255 1256
  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 已提交
1257
  }
H
Haojun Liao 已提交
1258

1259
  setSelectValueColumnInfo(pFuncCtx, numOfOutput);
H
Haojun Liao 已提交
1260 1261 1262
  return pFuncCtx;
}

1263
static void* destroySqlFunctionCtx(SqlFunctionCtx* pCtx, int32_t numOfOutput) {
1264 1265 1266 1267 1268 1269
  if (pCtx == NULL) {
    return NULL;
  }

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

    taosVariantDestroy(&pCtx[i].tag);
1274
    taosMemoryFreeClear(pCtx[i].subsidiaries.pCtx);
H
Haojun Liao 已提交
1275 1276
    taosMemoryFree(pCtx[i].input.pData);
    taosMemoryFree(pCtx[i].input.pColumnDataAgg);
1277 1278
  }

wafwerar's avatar
wafwerar 已提交
1279
  taosMemoryFreeClear(pCtx);
1280 1281 1282
  return NULL;
}

L
Liu Jicong 已提交
1283
bool isTaskKilled(SExecTaskInfo* pTaskInfo) {
1284 1285
  // query has been executed more than tsShellActivityTimer, and the retrieve has not arrived
  // abort current query execution.
L
Liu Jicong 已提交
1286 1287
  if (pTaskInfo->owner != 0 &&
      ((taosGetTimestampSec() - pTaskInfo->cost.start / 1000) > 10 * getMaximumIdleDurationSec())
1288 1289
      /*(!needBuildResAfterQueryComplete(pTaskInfo))*/) {
    assert(pTaskInfo->cost.start != 0);
L
Liu Jicong 已提交
1290 1291 1292
    //    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;
1293 1294 1295 1296 1297
  }

  return false;
}

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

L
Liu Jicong 已提交
1300
static bool isCachedLastQuery(STaskAttr* pQueryAttr) {
1301 1302 1303 1304 1305 1306 1307 1308 1309
  for (int32_t i = 0; i < pQueryAttr->numOfOutput; ++i) {
    int32_t functionId = getExprFunctionId(&pQueryAttr->pExpr1[i]);
    if (functionId == FUNCTION_LAST || functionId == FUNCTION_LAST_DST) {
      continue;
    }

    return false;
  }

1310 1311
  int32_t order = TSDB_ORDER_ASC;
  if (order != TSDB_ORDER_DESC || !TSWINDOW_IS_EQUAL(pQueryAttr->window, TSWINDOW_DESC_INITIALIZER)) {
1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330
    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 已提交
1331
// todo refactor : return window
1332
void getAlignQueryTimeWindow(SInterval* pInterval, int32_t precision, int64_t key, STimeWindow* win) {
H
Haojun Liao 已提交
1333
  win->skey = taosTimeTruncate(key, pInterval, precision);
1334 1335

  /*
H
Haojun Liao 已提交
1336
   * if the realSkey > INT64_MAX - pInterval->interval, the query duration between
1337 1338
   * realSkey and realEkey must be less than one interval.Therefore, no need to adjust the query ranges.
   */
1339 1340
  win->ekey = taosTimeAdd(win->skey, pInterval->interval, pInterval->intervalUnit, precision) - 1;
  if (win->ekey < win->skey) {
1341 1342 1343 1344
    win->ekey = INT64_MAX;
  }
}

L
Liu Jicong 已提交
1345
static int32_t updateBlockLoadStatus(STaskAttr* pQuery, int32_t status) {
1346 1347 1348
  bool hasFirstLastFunc = false;
  bool hasOtherFunc = false;

1349
  if (status == BLK_DATA_DATA_LOAD || status == BLK_DATA_FILTEROUT) {
1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367
    return status;
  }

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

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

1368
  if (hasFirstLastFunc && status == BLK_DATA_NOT_LOAD) {
L
Liu Jicong 已提交
1369
    if (!hasOtherFunc) {
1370
      return BLK_DATA_FILTEROUT;
1371
    } else {
1372
      return BLK_DATA_DATA_LOAD;
1373 1374 1375 1376 1377 1378
    }
  }

  return status;
}

L
Liu Jicong 已提交
1379 1380
// static void updateDataCheckOrder(SQInfo *pQInfo, SQueryTableReq* pQueryMsg, bool stableQuery) {
//   STaskAttr* pQueryAttr = pQInfo->runtimeEnv.pQueryAttr;
H
Haojun Liao 已提交
1381
//
L
Liu Jicong 已提交
1382 1383 1384 1385
//   // 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 已提交
1386
//
L
Liu Jicong 已提交
1387 1388 1389 1390 1391
//   // 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 已提交
1392
//
L
Liu Jicong 已提交
1393 1394
//     pQueryAttr->order.order = TSDB_ORDER_ASC;
//     if (pQueryAttr->window.skey > pQueryAttr->window.ekey) {
wafwerar's avatar
wafwerar 已提交
1395
//       TSWAP(pQueryAttr->window.skey, pQueryAttr->window.ekey);
L
Liu Jicong 已提交
1396
//     }
H
Haojun Liao 已提交
1397
//
L
Liu Jicong 已提交
1398 1399 1400
//     pQueryAttr->needReverseScan = false;
//     return;
//   }
H
Haojun Liao 已提交
1401
//
L
Liu Jicong 已提交
1402 1403 1404
//   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 已提交
1405
//       TSWAP(pQueryAttr->window.skey, pQueryAttr->window.ekey);
L
Liu Jicong 已提交
1406
//     }
H
Haojun Liao 已提交
1407
//
L
Liu Jicong 已提交
1408 1409 1410 1411
//     pQueryAttr->needReverseScan = false;
//     doUpdateLastKey(pQueryAttr);
//     return;
//   }
H
Haojun Liao 已提交
1412
//
L
Liu Jicong 已提交
1413 1414 1415 1416 1417 1418
//   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 已提交
1419
//
L
Liu Jicong 已提交
1420 1421 1422
//     pQueryAttr->order.order = TSDB_ORDER_ASC;
//     return;
//   }
H
Haojun Liao 已提交
1423
//
L
Liu Jicong 已提交
1424 1425 1426 1427
//   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 已提交
1428 1429
////               pQueryAttr->window.ekey, pQueryAttr->window.ekey, pQueryAttr->window.skey);
//
wafwerar's avatar
wafwerar 已提交
1430
//        TSWAP(pQueryAttr->window.skey, pQueryAttr->window.ekey);
H
Haojun Liao 已提交
1431 1432 1433 1434 1435 1436 1437 1438 1439 1440
//        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 已提交
1441
//        TSWAP(pQueryAttr->window.skey, pQueryAttr->window.ekey);
H
Haojun Liao 已提交
1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453
//        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 已提交
1454 1455
////                 pQueryAttr->window.skey, pQueryAttr->window.ekey, pQueryAttr->window.ekey,
/// pQueryAttr->window.skey);
H
Haojun Liao 已提交
1456
//
wafwerar's avatar
wafwerar 已提交
1457
//          TSWAP(pQueryAttr->window.skey, pQueryAttr->window.ekey);
H
Haojun Liao 已提交
1458 1459 1460 1461 1462 1463 1464 1465
//          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 已提交
1466 1467
////                 pQueryAttr->window.skey, pQueryAttr->window.ekey, pQueryAttr->window.ekey,
/// pQueryAttr->window.skey);
H
Haojun Liao 已提交
1468
//
wafwerar's avatar
wafwerar 已提交
1469
//          TSWAP(pQueryAttr->window.skey, pQueryAttr->window.ekey);
H
Haojun Liao 已提交
1470 1471 1472 1473 1474 1475 1476 1477 1478
//          doUpdateLastKey(pQueryAttr);
//        }
//
//        pQueryAttr->order.order = TSDB_ORDER_DESC;
//        pQueryAttr->needReverseScan = false;
//      }
//    }
//  }
//}
1479

H
Haojun Liao 已提交
1480 1481
static void getIntermediateBufInfo(STaskRuntimeEnv* pRuntimeEnv, int32_t* ps, int32_t* rowsize) {
  STaskAttr* pQueryAttr = pRuntimeEnv->pQueryAttr;
L
Liu Jicong 已提交
1482
  int32_t    MIN_ROWS_PER_PAGE = 4;
1483

L
Liu Jicong 已提交
1484 1485
  *rowsize = (int32_t)(pQueryAttr->resultRowSize *
                       getRowNumForMultioutput(pQueryAttr, pQueryAttr->topBotQuery, pQueryAttr->stableQuery));
1486 1487 1488 1489
  int32_t overhead = sizeof(SFilePage);

  // one page contains at least two rows
  *ps = DEFAULT_INTERN_BUF_PAGE_SIZE;
L
Liu Jicong 已提交
1490
  while (((*rowsize) * MIN_ROWS_PER_PAGE) > (*ps) - overhead) {
1491 1492 1493 1494
    *ps = ((*ps) << 1u);
  }
}

L
Liu Jicong 已提交
1495 1496 1497
// static FORCE_INLINE bool doFilterByBlockStatistics(STaskRuntimeEnv* pRuntimeEnv, SDataStatis *pDataStatis,
// SqlFunctionCtx *pCtx, int32_t numOfRows) {
//   STaskAttr* pQueryAttr = pRuntimeEnv->pQueryAttr;
1498
//
L
Liu Jicong 已提交
1499 1500 1501
//   if (pDataStatis == NULL || pQueryAttr->pFilters == NULL) {
//     return true;
//   }
1502
//
L
Liu Jicong 已提交
1503 1504
//   return filterRangeExecute(pQueryAttr->pFilters, pDataStatis, pQueryAttr->numOfCols, numOfRows);
// }
1505

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

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

1512
  if (true) {
L
Liu Jicong 已提交
1513
    //    getAlignQueryTimeWindow(pQueryAttr, pBlockInfo->window.skey, sk, ek, &w);
1514 1515 1516 1517 1518 1519
    assert(w.ekey >= pBlockInfo->window.skey);

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

L
Liu Jicong 已提交
1520 1521
    while (1) {
      //      getNextTimeWindow(pQueryAttr, &w);
1522 1523 1524 1525 1526 1527 1528 1529 1530 1531
      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 已提交
1532
    //    getAlignQueryTimeWindow(pQueryAttr, pBlockInfo->window.ekey, sk, ek, &w);
1533 1534 1535 1536 1537 1538
    assert(w.skey <= pBlockInfo->window.ekey);

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

L
Liu Jicong 已提交
1539 1540
    while (1) {
      //      getNextTimeWindow(pQueryAttr, &w);
1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604
      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 SColumnInfo* doGetTagColumnInfoById(SColumnInfo* pTagColList, int32_t numOfTags, int16_t colId);
L
Liu Jicong 已提交
1605
static void         doSetTagValueInParam(void* pTable, int32_t tagColId, SVariant* tag, int16_t type, int16_t bytes);
1606 1607

static uint32_t doFilterByBlockTimeWindow(STableScanInfo* pTableScanInfo, SSDataBlock* pBlock) {
H
Haojun Liao 已提交
1608
  SqlFunctionCtx* pCtx = pTableScanInfo->pCtx;
1609
  uint32_t        status = BLK_DATA_NOT_LOAD;
1610 1611 1612 1613

  int32_t numOfOutput = pTableScanInfo->numOfOutput;
  for (int32_t i = 0; i < numOfOutput; ++i) {
    int32_t functionId = pCtx[i].functionId;
H
Haojun Liao 已提交
1614
    int32_t colId = pTableScanInfo->pExpr[i].base.pParam[0].pCol->colId;
1615 1616 1617

    // group by + first/last should not apply the first/last block filter
    if (functionId < 0) {
1618
      status |= BLK_DATA_DATA_LOAD;
1619 1620
      return status;
    } else {
L
Liu Jicong 已提交
1621
      //      status |= aAggs[functionId].dataReqFunc(&pTableScanInfo->pCtx[i], &pBlock->info.window, colId);
1622
      //      if ((status & BLK_DATA_DATA_LOAD) == BLK_DATA_DATA_LOAD) {
L
Liu Jicong 已提交
1623 1624
      //        return status;
      //      }
1625 1626 1627 1628 1629 1630
    }
  }

  return status;
}

L
Liu Jicong 已提交
1631 1632
int32_t loadDataBlockOnDemand(SExecTaskInfo* pTaskInfo, STableScanInfo* pTableScanInfo, SSDataBlock* pBlock,
                              uint32_t* status) {
1633
  *status = BLK_DATA_NOT_LOAD;
1634

H
Haojun Liao 已提交
1635
  pBlock->pDataBlock = NULL;
L
Liu Jicong 已提交
1636
  pBlock->pBlockAgg = NULL;
H
Haojun Liao 已提交
1637

L
Liu Jicong 已提交
1638 1639
  //  int64_t groupId = pRuntimeEnv->current->groupIndex;
  //  bool    ascQuery = QUERY_IS_ASC_QUERY(pQueryAttr);
1640

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

1643 1644
//  pCost->totalBlocks += 1;
//  pCost->totalRows += pBlock->info.rows;
H
Haojun Liao 已提交
1645
#if 0
1646 1647 1648
  // 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 已提交
1649
      (QUERY_IS_INTERVAL_QUERY(pQueryAttr) && overlapWithTimeWindow(pTaskInfo, &pBlock->info))) {
1650
    (*status) = BLK_DATA_DATA_LOAD;
1651 1652 1653
  }

  // check if this data block is required to load
1654
  if ((*status) != BLK_DATA_DATA_LOAD) {
1655 1656 1657 1658 1659 1660 1661
    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 已提交
1662
      bool  masterScan = IS_MAIN_SCAN(pRuntimeEnv);
1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685
      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 {
1686
      (*status) = BLK_DATA_DATA_LOAD;
1687 1688 1689 1690
    }
  }

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

1693
  if ((*status) == BLK_DATA_NOT_LOAD || (*status) == BLK_DATA_FILTEROUT) {
1694 1695
    //qDebug("QInfo:0x%"PRIx64" data block discard, brange:%" PRId64 "-%" PRId64 ", rows:%d", pQInfo->qId, pBlockInfo->window.skey,
//           pBlockInfo->window.ekey, pBlockInfo->rows);
1696
    pCost->skipBlocks += 1;
1697
  } else if ((*status) == BLK_DATA_SMA_LOAD) {
1698 1699
    // this function never returns error?
    pCost->loadBlockStatis += 1;
1700
//    tsdbRetrieveDataBlockStatisInfo(pTableScanInfo->pTsdbReadHandle, &pBlock->pBlockAgg);
1701 1702

    if (pBlock->pBlockAgg == NULL) {  // data block statistics does not exist, load data block
1703
//      pBlock->pDataBlock = tsdbRetrieveDataBlock(pTableScanInfo->pTsdbReadHandle, NULL);
1704 1705 1706
      pCost->totalCheckedRows += pBlock->info.rows;
    }
  } else {
1707
    assert((*status) == BLK_DATA_DATA_LOAD);
1708 1709 1710

    // load the data block statistics to perform further filter
    pCost->loadBlockStatis += 1;
1711
//    tsdbRetrieveDataBlockStatisInfo(pTableScanInfo->pTsdbReadHandle, &pBlock->pBlockAgg);
1712 1713 1714 1715 1716 1717

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

H
Haojun Liao 已提交
1718
          bool  masterScan = IS_MAIN_SCAN(pRuntimeEnv);
1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735
          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
1736
            pCost->skipBlocks += 1;
1737 1738
            //qDebug("QInfo:0x%"PRIx64" data block discard, brange:%" PRId64 "-%" PRId64 ", rows:%d", pQInfo->qId,
//                   pBlockInfo->window.skey, pBlockInfo->window.ekey, pBlockInfo->rows);
1739
            (*status) = BLK_DATA_FILTEROUT;
1740 1741 1742 1743 1744 1745 1746 1747
            return TSDB_CODE_SUCCESS;
          }
        }
      }
    }

    // current block has been discard due to filter applied
//    if (!doFilterByBlockStatistics(pRuntimeEnv, pBlock->pBlockAgg, pTableScanInfo->pCtx, pBlockInfo->rows)) {
1748
//      pCost->skipBlocks += 1;
1749 1750
//      qDebug("QInfo:0x%"PRIx64" data block discard, brange:%" PRId64 "-%" PRId64 ", rows:%d", pQInfo->qId, pBlockInfo->window.skey,
//             pBlockInfo->window.ekey, pBlockInfo->rows);
1751
//      (*status) = BLK_DATA_FILTEROUT;
1752 1753 1754 1755 1756
//      return TSDB_CODE_SUCCESS;
//    }

    pCost->totalCheckedRows += pBlockInfo->rows;
    pCost->loadBlocks += 1;
1757
//    pBlock->pDataBlock = tsdbRetrieveDataBlock(pTableScanInfo->pTsdbReadHandle, NULL);
1758 1759 1760 1761 1762 1763 1764
//    if (pBlock->pDataBlock == NULL) {
//      return terrno;
//    }

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

1766 1767 1768 1769
//    if (pQueryAttr->pFilters != NULL || pRuntimeEnv->pTsBuf != NULL) {
//      filterColRowsInDataBlock(pRuntimeEnv, pBlock, ascQuery);
//    }
  }
H
Haojun Liao 已提交
1770
#endif
1771 1772 1773 1774
  return TSDB_CODE_SUCCESS;
}

/*
H
Haojun Liao 已提交
1775
 * set tag value in SqlFunctionCtx
1776 1777
 * e.g.,tag information into input buffer
 */
L
Liu Jicong 已提交
1778
static void doSetTagValueInParam(void* pTable, int32_t tagColId, SVariant* tag, int16_t type, int16_t bytes) {
1779 1780 1781
  taosVariantDestroy(tag);

  char* val = NULL;
L
Liu Jicong 已提交
1782 1783 1784 1785 1786 1787
  //  if (tagColId == TSDB_TBNAME_COLUMN_INDEX) {
  //    val = tsdbGetTableName(pTable);
  //    assert(val != NULL);
  //  } else {
  //    val = tsdbGetTableTagVal(pTable, tagColId, type, bytes);
  //  }
1788 1789 1790 1791 1792 1793 1794 1795

  if (val == NULL || isNull(val, type)) {
    tag->nType = TSDB_DATA_TYPE_NULL;
    return;
  }

  if (type == TSDB_DATA_TYPE_BINARY || type == TSDB_DATA_TYPE_NCHAR) {
    int32_t maxLen = bytes - VARSTR_HEADER_SIZE;
L
Liu Jicong 已提交
1796
    int32_t len = (varDataLen(val) > maxLen) ? maxLen : varDataLen(val);
1797
    taosVariantCreateFromBinary(tag, varDataVal(val), len, type);
L
Liu Jicong 已提交
1798
    // taosVariantCreateFromBinary(tag, varDataVal(val), varDataLen(val), type);
1799 1800 1801 1802 1803 1804 1805 1806
  } else {
    taosVariantCreateFromBinary(tag, val, bytes, type);
  }
}

static SColumnInfo* doGetTagColumnInfoById(SColumnInfo* pTagColList, int32_t numOfTags, int16_t colId) {
  assert(pTagColList != NULL && numOfTags > 0);

L
Liu Jicong 已提交
1807
  for (int32_t i = 0; i < numOfTags; ++i) {
1808 1809 1810 1811 1812 1813 1814 1815
    if (pTagColList[i].colId == colId) {
      return &pTagColList[i];
    }
  }

  return NULL;
}

L
Liu Jicong 已提交
1816 1817
void setTagValue(SOperatorInfo* pOperatorInfo, void* pTable, SqlFunctionCtx* pCtx, int32_t numOfOutput) {
  SExprInfo* pExpr = pOperatorInfo->pExpr;
1818
  SExprInfo* pExprInfo = &pExpr[0];
L
Liu Jicong 已提交
1819
  int32_t    functionId = getExprFunctionId(pExprInfo);
1820
#if 0
1821 1822 1823
  if (pQueryAttr->numOfOutput == 1 && functionId == FUNCTION_TS_COMP && pQueryAttr->stableQuery) {
    assert(pExprInfo->base.numOfParams == 1);

L
Liu Jicong 已提交
1824
    //    int16_t      tagColId = (int16_t)pExprInfo->base.param[0].i;
H
Haojun Liao 已提交
1825
    int16_t      tagColId = -1;
1826 1827 1828
    SColumnInfo* pColInfo = doGetTagColumnInfoById(pQueryAttr->tagColList, pQueryAttr->numOfTags, tagColId);

    doSetTagValueInParam(pTable, tagColId, &pCtx[0].tag, pColInfo->type, pColInfo->bytes);
H
Haojun Liao 已提交
1829

1830 1831 1832 1833 1834 1835 1836 1837 1838
  } else {
    // set tag value, by which the results are aggregated.
    int32_t offset = 0;
    memset(pRuntimeEnv->tagVal, 0, pQueryAttr->tagLen);

    for (int32_t idx = 0; idx < numOfOutput; ++idx) {
      SExprInfo* pLocalExprInfo = &pExpr[idx];

      // ts_comp column required the tag value for join filter
H
Haojun Liao 已提交
1839
      if (!TSDB_COL_IS_TAG(pLocalExprInfo->base.pParam[0].pCol->flag)) {
1840 1841 1842 1843
        continue;
      }

      // todo use tag column index to optimize performance
L
Liu Jicong 已提交
1844 1845
      doSetTagValueInParam(pTable, pLocalExprInfo->base.pParam[0].pCol->colId, &pCtx[idx].tag,
                           pLocalExprInfo->base.resSchema.type, pLocalExprInfo->base.resSchema.bytes);
1846

L
Liu Jicong 已提交
1847 1848 1849
      if (IS_NUMERIC_TYPE(pLocalExprInfo->base.resSchema.type) ||
          pLocalExprInfo->base.resSchema.type == TSDB_DATA_TYPE_BOOL ||
          pLocalExprInfo->base.resSchema.type == TSDB_DATA_TYPE_TIMESTAMP) {
1850 1851 1852 1853
        memcpy(pRuntimeEnv->tagVal + offset, &pCtx[idx].tag.i, pLocalExprInfo->base.resSchema.bytes);
      } else {
        if (pCtx[idx].tag.pz != NULL) {
          memcpy(pRuntimeEnv->tagVal + offset, pCtx[idx].tag.pz, pCtx[idx].tag.nLen);
L
Liu Jicong 已提交
1854
        }
1855 1856 1857 1858 1859 1860 1861 1862 1863 1864
      }

      offset += pLocalExprInfo->base.resSchema.bytes;
    }
  }

  // set the tsBuf start position before check each data block
  if (pRuntimeEnv->pTsBuf != NULL) {
    setCtxTagForJoin(pRuntimeEnv, &pCtx[0], pExprInfo, pTable);
  }
1865
#endif
1866 1867
}

H
Haojun Liao 已提交
1868
void copyToSDataBlock(SSDataBlock* pBlock, int32_t* offset, SGroupResInfo* pGroupResInfo, SDiskbasedBuf* pResBuf) {
1869 1870 1871 1872 1873 1874 1875
  pBlock->info.rows = 0;

  int32_t code = TSDB_CODE_SUCCESS;
  while (pGroupResInfo->currentGroup < pGroupResInfo->totalGroup) {
    // all results in current group have been returned to client, try next group
    if ((pGroupResInfo->pRows == NULL) || taosArrayGetSize(pGroupResInfo->pRows) == 0) {
      assert(pGroupResInfo->index == 0);
L
Liu Jicong 已提交
1876 1877 1878
      //      if ((code = mergeIntoGroupResult(&pGroupResInfo, pRuntimeEnv, offset)) != TSDB_CODE_SUCCESS) {
      return;
      //      }
1879 1880
    }

L
Liu Jicong 已提交
1881
    //    doCopyToSDataBlock(pResBuf, pGroupResInfo, TSDB_ORDER_ASC, pBlock, );
1882 1883 1884 1885 1886 1887 1888 1889 1890 1891

    // current data are all dumped to result buffer, clear it
    if (!hasRemainDataInCurrentGroup(pGroupResInfo)) {
      cleanupGroupResInfo(pGroupResInfo);
      if (!incNextGroup(pGroupResInfo)) {
        break;
      }
    }

    // enough results in data buffer, return
L
Liu Jicong 已提交
1892 1893 1894
    //    if (pBlock->info.rows >= threshold) {
    //      break;
    //    }
1895 1896 1897
  }
}

L
Liu Jicong 已提交
1898
static void updateTableQueryInfoForReverseScan(STableQueryInfo* pTableQueryInfo) {
1899 1900 1901 1902
  if (pTableQueryInfo == NULL) {
    return;
  }

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

L
Liu Jicong 已提交
1906 1907
  //  SWITCH_ORDER(pTableQueryInfo->cur.order);
  //  pTableQueryInfo->cur.vgroupIndex = -1;
1908 1909

  // set the index to be the end slot of result rows array
dengyihao's avatar
dengyihao 已提交
1910 1911 1912 1913 1914 1915
  //  SResultRowInfo* pResultRowInfo = &pTableQueryInfo->resInfo;
  //  if (pResultRowInfo->size > 0) {
  //    pResultRowInfo->curPos = pResultRowInfo->size - 1;
  //  } else {
  //    pResultRowInfo->curPos = -1;
  //  }
1916 1917
}

H
Haojun Liao 已提交
1918
void initResultRow(SResultRow* pResultRow) {
X
Xiaoyu Wang 已提交
1919
  //  pResultRow->pEntryInfo = (struct SResultRowEntryInfo*)((char*)pResultRow + sizeof(SResultRow));
1920 1921 1922 1923 1924
}

/*
 * 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 已提交
1925 1926 1927
 * +------------+-----------------result column 1------------+------------------result column 2-----------+
 * | SResultRow | SResultRowEntryInfo | intermediate buffer1 | SResultRowEntryInfo | intermediate buffer 2|
 * +------------+--------------------------------------------+--------------------------------------------+
1928 1929
 *           offset[0]                                  offset[1]                                   offset[2]
 */
1930
// TODO refactor: some function move away
X
Xiaoyu Wang 已提交
1931 1932
void setFunctionResultOutput(SOptrBasicInfo* pInfo, SAggSupporter* pSup, int32_t stage, int32_t numOfExprs,
                             SExecTaskInfo* pTaskInfo) {
L
Liu Jicong 已提交
1933 1934 1935
  SqlFunctionCtx* pCtx = pInfo->pCtx;
  SSDataBlock*    pDataBlock = pInfo->pRes;
  int32_t*        rowCellInfoOffset = pInfo->rowCellInfoOffset;
H
Haojun Liao 已提交
1936

H
Haojun Liao 已提交
1937
  SResultRowInfo* pResultRowInfo = &pInfo->resultRowInfo;
H
Haojun Liao 已提交
1938
  initResultRowInfo(pResultRowInfo, 16);
H
Haojun Liao 已提交
1939

L
Liu Jicong 已提交
1940 1941
  int64_t     tid = 0;
  int64_t     groupId = 0;
1942 1943
  SResultRow* pRow = doSetResultOutBufByKey(pSup->pResultBuf, pResultRowInfo, (char*)&tid, sizeof(tid), true, groupId,
                                            pTaskInfo, false, pSup);
H
Haojun Liao 已提交
1944

H
Haojun Liao 已提交
1945
  ASSERT(pDataBlock->info.numOfCols == numOfExprs);
H
Haojun Liao 已提交
1946 1947 1948 1949
  for (int32_t i = 0; i < pDataBlock->info.numOfCols; ++i) {
    struct SResultRowEntryInfo* pEntry = getResultCell(pRow, i, rowCellInfoOffset);
    cleanupResultRowEntry(pEntry);

L
Liu Jicong 已提交
1950
    pCtx[i].resultInfo = pEntry;
1951
    pCtx[i].scanFlag = stage;
H
Haojun Liao 已提交
1952 1953

    // set the timestamp output buffer for top/bottom/diff query
L
Liu Jicong 已提交
1954 1955
    //    int32_t fid = pCtx[i].functionId;
    //    if (fid == FUNCTION_TOP || fid == FUNCTION_BOTTOM || fid == FUNCTION_DIFF || fid == FUNCTION_DERIVATIVE) {
H
Haojun Liao 已提交
1956
    //      if (i > 0) pCtx[i].pTsOutput = pCtx[i-1].pOutput;
L
Liu Jicong 已提交
1957
    //    }
H
Haojun Liao 已提交
1958 1959 1960 1961 1962
  }

  initCtxOutputBuffer(pCtx, pDataBlock->info.numOfCols);
}

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

L
Liu Jicong 已提交
1966
  int32_t newSize = pDataBlock->info.rows + numOfInputRows + 5;  // extra output buffer
1967
  if ((*bufCapacity) < newSize) {
L
Liu Jicong 已提交
1968 1969
    for (int32_t i = 0; i < pDataBlock->info.numOfCols; ++i) {
      SColumnInfoData* pColInfo = taosArrayGet(pDataBlock->pDataBlock, i);
1970

wafwerar's avatar
wafwerar 已提交
1971
      char* p = taosMemoryRealloc(pColInfo->pData, newSize * pColInfo->info.bytes);
1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984
      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 已提交
1985
    SColumnInfoData* pColInfo = taosArrayGet(pDataBlock->pDataBlock, i);
1986 1987 1988 1989 1990
    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;

L
Liu Jicong 已提交
1991 1992
    if (functionId == FUNCTION_TOP || functionId == FUNCTION_BOTTOM || functionId == FUNCTION_DIFF ||
        functionId == FUNCTION_DERIVATIVE) {
dengyihao's avatar
dengyihao 已提交
1993
      //      if (i > 0) pBInfo->pCtx[i].pTsOutput = pBInfo->pCtx[i - 1].pOutput;
1994 1995 1996 1997
    }
  }
}

H
Haojun Liao 已提交
1998
void copyTsColoum(SSDataBlock* pRes, SqlFunctionCtx* pCtx, int32_t numOfOutput) {
1999 2000
  bool    needCopyTs = false;
  int32_t tsNum = 0;
L
Liu Jicong 已提交
2001
  char*   src = NULL;
2002 2003 2004 2005
  for (int32_t i = 0; i < numOfOutput; i++) {
    int32_t functionId = pCtx[i].functionId;
    if (functionId == FUNCTION_DIFF || functionId == FUNCTION_DERIVATIVE) {
      needCopyTs = true;
L
Liu Jicong 已提交
2006 2007
      if (i > 0 && pCtx[i - 1].functionId == FUNCTION_TS_DUMMY) {
        SColumnInfoData* pColRes = taosArrayGet(pRes->pDataBlock, i - 1);  // find ts data
2008 2009
        src = pColRes->pData;
      }
L
Liu Jicong 已提交
2010
    } else if (functionId == FUNCTION_TS_DUMMY) {
2011 2012 2013 2014 2015 2016 2017 2018 2019 2020
      tsNum++;
    }
  }

  if (!needCopyTs) return;
  if (tsNum < 2) return;
  if (src == NULL) return;

  for (int32_t i = 0; i < numOfOutput; i++) {
    int32_t functionId = pCtx[i].functionId;
L
Liu Jicong 已提交
2021
    if (functionId == FUNCTION_TS_DUMMY) {
2022 2023 2024 2025 2026 2027
      SColumnInfoData* pColRes = taosArrayGet(pRes->pDataBlock, i);
      memcpy(pColRes->pData, src, pColRes->info.bytes * pRes->info.rows);
    }
  }
}

H
Haojun Liao 已提交
2028
void initCtxOutputBuffer(SqlFunctionCtx* pCtx, int32_t size) {
2029 2030
  for (int32_t j = 0; j < size; ++j) {
    struct SResultRowEntryInfo* pResInfo = GET_RES_INFO(&pCtx[j]);
dengyihao's avatar
dengyihao 已提交
2031 2032
    if (isRowEntryInitialized(pResInfo) || fmIsPseudoColumnFunc(pCtx[j].functionId) || pCtx[j].functionId == -1 ||
        fmIsScalarFunc(pCtx[j].functionId)) {
2033 2034 2035
      continue;
    }

H
Haojun Liao 已提交
2036
    pCtx[j].fpSet.init(&pCtx[j], pCtx[j].resultInfo);
2037 2038 2039
  }
}

L
Liu Jicong 已提交
2040
void setTaskStatus(SExecTaskInfo* pTaskInfo, int8_t status) {
2041
  if (status == TASK_NOT_COMPLETED) {
H
Haojun Liao 已提交
2042
    pTaskInfo->status = status;
2043 2044
  } else {
    // QUERY_NOT_COMPLETED is not compatible with any other status, so clear its position first
2045
    CLEAR_QUERY_STATUS(pTaskInfo, TASK_NOT_COMPLETED);
H
Haojun Liao 已提交
2046
    pTaskInfo->status |= status;
2047 2048 2049
  }
}

2050
// todo merged with the build group result.
2051 2052
void finalizeMultiTupleQueryResult(int32_t numOfOutput, SDiskbasedBuf* pBuf, SResultRowInfo* pResultRowInfo,
                                   int32_t* rowCellInfoOffset) {
2053 2054 2055
  for (int32_t i = 0; i < pResultRowInfo->size; ++i) {
    SResultRowPosition* pPos = &pResultRowInfo->pPosition[i];

L
Liu Jicong 已提交
2056
    SFilePage*  bufPage = getBufPage(pBuf, pPos->pageId);
2057
    SResultRow* pRow = (SResultRow*)((char*)bufPage + pPos->offset);
H
Haojun Liao 已提交
2058 2059

    // TODO ignore the close status anyway.
dengyihao's avatar
dengyihao 已提交
2060 2061 2062
    //    if (!isResultRowClosed(pRow)) {
    //      continue;
    //    }
2063

2064
    for (int32_t j = 0; j < numOfOutput; ++j) {
2065
      struct SResultRowEntryInfo* pResInfo = getResultCell(pRow, j, rowCellInfoOffset);
H
Haojun Liao 已提交
2066
      if (!isRowEntryInitialized(pResInfo)) {
2067 2068 2069 2070 2071 2072
        continue;
      }

      if (pRow->numOfRows < pResInfo->numOfRes) {
        pRow->numOfRows = pResInfo->numOfRes;
      }
2073
    }
2074 2075 2076

    releaseBufPage(pBuf, bufPage);
  }
2077 2078
}

2079
STableQueryInfo* createTableQueryInfo(void* buf, STimeWindow win) {
L
Liu Jicong 已提交
2080
  STableQueryInfo* pTableQueryInfo = buf;
2081 2082 2083 2084
  pTableQueryInfo->lastKey = win.skey;
  return pTableQueryInfo;
}

L
Liu Jicong 已提交
2085
void destroyTableQueryInfoImpl(STableQueryInfo* pTableQueryInfo) {
2086 2087 2088 2089
  if (pTableQueryInfo == NULL) {
    return;
  }

L
Liu Jicong 已提交
2090
  //  taosVariantDestroy(&pTableQueryInfo->tag);
dengyihao's avatar
dengyihao 已提交
2091
  //  cleanupResultRowInfo(&pTableQueryInfo->resInfo);
2092 2093
}

2094
void setResultRowInitCtx(SResultRow* pResult, SqlFunctionCtx* pCtx, int32_t numOfOutput, int32_t* rowCellInfoOffset) {
2095 2096 2097 2098 2099 2100 2101
  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;
    }
2102 2103 2104 2105 2106

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

2107 2108 2109 2110 2111 2112
    if (!pResInfo->initialized) {
      if (pCtx[i].functionId != -1) {
        pCtx[i].fpSet.init(&pCtx[i], pResInfo);
      } else {
        pResInfo->initialized = true;
      }
2113 2114 2115 2116
    }
  }
}

2117
static void extractQualifiedTupleByFilterResult(SSDataBlock* pBlock, const int8_t* rowRes, bool keep);
2118 2119 2120 2121 2122 2123
void doFilter(const SNode* pFilterNode, SSDataBlock* pBlock) {
  if (pFilterNode == NULL) {
    return;
  }

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

H
Haojun Liao 已提交
2125
  // todo move to the initialization function
H
Haojun Liao 已提交
2126
  int32_t code = filterInitFromNode((SNode*)pFilterNode, &filter, 0);
2127 2128 2129 2130 2131

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

  int8_t* rowRes = NULL;
2132
  // todo the keep seems never to be True??
2133
  bool    keep = filterExecute(filter, pBlock, &rowRes, NULL, param1.numOfCols);
D
dapan1121 已提交
2134
  filterFreeInfo(filter);
2135

2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148
  extractQualifiedTupleByFilterResult(pBlock, rowRes, keep);
  blockDataUpdateTsWindow(pBlock);
}

void extractQualifiedTupleByFilterResult(SSDataBlock* pBlock, const int8_t* rowRes, bool keep) {
  if (keep) {
    return;
  }

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

2149 2150
    int32_t totalRows = pBlock->info.rows;

2151 2152 2153 2154 2155 2156 2157 2158 2159 2160
    for (int32_t i = 0; i < pBlock->info.numOfCols; ++i) {
      SColumnInfoData* pDst = taosArrayGet(px->pDataBlock, i);
      SColumnInfoData* pSrc = taosArrayGet(pBlock->pDataBlock, i);

      // For the reserved column, the value is not filled yet, so the whole column data may be NULL.
      if (pSrc->pData == NULL) {
        continue;
      }

      int32_t numOfRows = 0;
2161
      for (int32_t j = 0; j < totalRows; ++j) {
D
dapan1121 已提交
2162 2163 2164
        if (rowRes[j] == 0) {
          continue;
        }
2165

D
dapan1121 已提交
2166
        if (colDataIsNull_s(pSrc, j)) {
2167
          colDataAppendNULL(pDst, numOfRows);
D
dapan1121 已提交
2168
        } else {
2169
          colDataAppend(pDst, numOfRows, colDataGetData(pSrc, j), false);
D
dapan1121 已提交
2170
        }
2171
        numOfRows += 1;
H
Haojun Liao 已提交
2172
      }
2173

2174 2175 2176 2177 2178 2179
      if (pBlock->info.rows == totalRows) {
        pBlock->info.rows = numOfRows;
      } else {
        ASSERT(pBlock->info.rows == numOfRows);
      }

2180 2181 2182 2183 2184
      *pSrc = *pDst;
    }
  } else {
    // do nothing
    pBlock->info.rows = 0;
2185 2186 2187
  }
}

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

2193 2194
  SResultRowInfo* pResultRowInfo = &pAggInfo->binfo.resultRowInfo;
  SqlFunctionCtx* pCtx = pAggInfo->binfo.pCtx;
L
Liu Jicong 已提交
2195
  int32_t*        rowCellInfoOffset = pAggInfo->binfo.rowCellInfoOffset;
2196

2197
  SResultRow* pResultRow = doSetResultOutBufByKey(pAggInfo->aggSup.pResultBuf, pResultRowInfo, (char*)&groupId,
L
Liu Jicong 已提交
2198
                                                  sizeof(groupId), true, groupId, pTaskInfo, false, &pAggInfo->aggSup);
L
Liu Jicong 已提交
2199
  assert(pResultRow != NULL);
2200 2201 2202 2203 2204 2205

  /*
   * 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 已提交
2206 2207
    int32_t ret =
        addNewWindowResultBuf(pResultRow, pAggInfo->aggSup.pResultBuf, groupId, pAggInfo->binfo.pRes->info.rowSize);
2208 2209 2210 2211 2212
    if (ret != TSDB_CODE_SUCCESS) {
      return;
    }
  }

2213
  setResultRowInitCtx(pResultRow, pCtx, numOfOutput, rowCellInfoOffset);
2214 2215
}

H
Haojun Liao 已提交
2216 2217
void setExecutionContext(int32_t numOfOutput, uint64_t groupId, SExecTaskInfo* pTaskInfo, SAggOperatorInfo* pAggInfo) {
  if (pAggInfo->groupId != INT32_MIN && pAggInfo->groupId == groupId) {
2218 2219 2220
    return;
  }

H
Haojun Liao 已提交
2221
  doSetTableGroupOutputBuf(pAggInfo, numOfOutput, groupId, pTaskInfo);
2222 2223

  // record the current active group id
H
Haojun Liao 已提交
2224
  pAggInfo->groupId = groupId;
2225 2226 2227 2228 2229 2230 2231 2232 2233 2234
}

/**
 * For interval query of both super table and table, copy the data in ascending order, since the output results are
 * ordered in SWindowResutl already. While handling the group by query for both table and super table,
 * all group result are completed already.
 *
 * @param pQInfo
 * @param result
 */
2235
int32_t doCopyToSDataBlock(SExecTaskInfo* taskInfo, SSDataBlock* pBlock, SExprInfo* pExprInfo, SDiskbasedBuf* pBuf, SGroupResInfo* pGroupResInfo,
2236
                           int32_t orderType, int32_t* rowCellOffset, SqlFunctionCtx* pCtx, int32_t numOfExprs) {
2237
  int32_t numOfRows = getNumOfTotalRes(pGroupResInfo);
L
Liu Jicong 已提交
2238
  int32_t numOfResult = pBlock->info.rows;  // there are already exists result rows
2239 2240

  int32_t start = 0;
2241
  int32_t step = 1;
2242

L
Liu Jicong 已提交
2243
  // qDebug("QInfo:0x%"PRIx64" start to copy data from windowResInfo to output buf", GET_TASKID(pRuntimeEnv));
2244 2245 2246 2247 2248 2249 2250 2251 2252
  assert(orderType == TSDB_ORDER_ASC || orderType == TSDB_ORDER_DESC);

  if (orderType == TSDB_ORDER_ASC) {
    start = pGroupResInfo->index;
  } else {  // desc order copy all data
    start = numOfRows - pGroupResInfo->index - 1;
  }

  for (int32_t i = start; (i < numOfRows) && (i >= 0); i += step) {
L
Liu Jicong 已提交
2253 2254
    SResKeyPos* pPos = taosArrayGetP(pGroupResInfo->pRows, i);
    SFilePage*  page = getBufPage(pBuf, pPos->pos.pageId);
2255

2256
    SResultRow* pRow = (SResultRow*)((char*)page + pPos->pos.offset);
2257 2258 2259 2260 2261
    if (pRow->numOfRows == 0) {
      pGroupResInfo->index += 1;
      continue;
    }

2262
    // TODO copy multiple rows?
2263
    int32_t numOfRowsToCopy = pRow->numOfRows;
2264
    if (numOfResult + numOfRowsToCopy >= pBlock->info.capacity) {
2265 2266 2267 2268 2269
      break;
    }

    pGroupResInfo->index += 1;

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

2273
      pCtx[j].resultInfo = getResultCell(pRow, j, rowCellOffset);
2274
      if (pCtx[j].fpSet.finalize) {
2275
        int32_t code = pCtx[j].fpSet.finalize(&pCtx[j], pBlock);
2276
        if (TAOS_FAILED(code)) {
2277 2278 2279 2280
          qError("%s build result data block error, code %s", GET_TASKID(taskInfo), tstrerror(code));
          taskInfo->code = code;
          longjmp(taskInfo->env, code);
        }
2281 2282
      } else if (strcmp(pCtx[j].pExpr->pExpr->_function.functionName, "_select_value") == 0) {
        // do nothing, todo refactor
2283
      } else {
2284 2285 2286 2287 2288 2289 2290
        // 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.
          SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, slotId);
          char* in = GET_ROWCELL_INTERBUF(pCtx[j].resultInfo);
          for(int32_t k = 0; k < pRow->numOfRows; ++k) {
            colDataAppend(pColInfoData, pBlock->info.rows + k, in, pCtx[j].resultInfo->isNullRes);
          }
2291
      }
2292 2293
    }

2294 2295
    releaseBufPage(pBuf, page);

2296 2297
    pBlock->info.rows += pRow->numOfRows;
    if (pBlock->info.rows >= pBlock->info.capacity) {  // output buffer is full
2298 2299 2300 2301
      break;
    }
  }

L
Liu Jicong 已提交
2302
  // qDebug("QInfo:0x%"PRIx64" copy data to query buf completed", GET_TASKID(pRuntimeEnv));
2303
  blockDataUpdateTsWindow(pBlock);
2304 2305 2306
  return 0;
}

2307
void doBuildResultDatablock(SOperatorInfo* pOperator, SOptrBasicInfo* pbInfo, SGroupResInfo* pGroupResInfo, SDiskbasedBuf* pBuf) {
2308 2309
  assert(pGroupResInfo->currentGroup <= pGroupResInfo->totalGroup);

2310 2311 2312 2313
  SExprInfo* pExprInfo = pOperator->pExpr;
  int32_t numOfExprs = pOperator->numOfExprs;
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;

X
Xiaoyu Wang 已提交
2314 2315 2316
  int32_t*        rowCellOffset = pbInfo->rowCellInfoOffset;
  SSDataBlock*    pBlock = pbInfo->pRes;
  SqlFunctionCtx* pCtx = pbInfo->pCtx;
2317

2318
  blockDataCleanup(pBlock);
2319 2320 2321 2322
  if (!hasRemainDataInCurrentGroup(pGroupResInfo)) {
    return;
  }

2323
  int32_t orderType = TSDB_ORDER_ASC;
2324
  doCopyToSDataBlock(pTaskInfo, pBlock, pExprInfo, pBuf, pGroupResInfo, orderType, rowCellOffset, pCtx, numOfExprs);
2325

H
Haojun Liao 已提交
2326 2327
  // add condition (pBlock->info.rows >= 1) just to runtime happy
  blockDataUpdateTsWindow(pBlock);
2328 2329
}

L
Liu Jicong 已提交
2330 2331
static void updateNumOfRowsInResultRows(SqlFunctionCtx* pCtx, int32_t numOfOutput, SResultRowInfo* pResultRowInfo,
                                        int32_t* rowCellInfoOffset) {
2332
  // update the number of result for each, only update the number of rows for the corresponding window result.
L
Liu Jicong 已提交
2333 2334 2335
  //  if (QUERY_IS_INTERVAL_QUERY(pQueryAttr)) {
  //    return;
  //  }
H
Haojun Liao 已提交
2336
#if 0
2337
  for (int32_t i = 0; i < pResultRowInfo->size; ++i) {
L
Liu Jicong 已提交
2338
    SResultRow* pResult = pResultRowInfo->pResult[i];
2339 2340 2341 2342 2343 2344 2345

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

2346 2347
      SResultRowEntryInfo* pCell = getResultCell(pResult, j, rowCellInfoOffset);
      pResult->numOfRows = (uint16_t)(TMAX(pResult->numOfRows, pCell->numOfRes));
2348 2349
    }
  }
H
Haojun Liao 已提交
2350
#endif
2351 2352
}

L
Liu Jicong 已提交
2353
static int32_t compressQueryColData(SColumnInfoData* pColRes, int32_t numOfRows, char* data, int8_t compressed) {
2354 2355
  int32_t colSize = pColRes->info.bytes * numOfRows;
  return (*(tDataTypes[pColRes->info.type].compFunc))(pColRes->pData, colSize, numOfRows, data,
L
Liu Jicong 已提交
2356
                                                      colSize + COMP_OVERFLOW_BYTES, compressed, NULL, 0);
2357 2358
}

2359
int32_t doFillTimeIntervalGapsInResults(struct SFillInfo* pFillInfo, SSDataBlock* pBlock, int32_t capacity) {
L
Liu Jicong 已提交
2360 2361 2362 2363
  //  for(int32_t i = 0; i < pFillInfo->numOfCols; ++i) {
  //    SColumnInfoData* pColInfoData = taosArrayGet(pOutput->pDataBlock, i);
  //    p[i] = pColInfoData->pData + (pColInfoData->info.bytes * pOutput->info.rows);
  //  }
2364

2365 2366
  int32_t numOfRows = (int32_t)taosFillResultDataBlock(pFillInfo, pBlock, capacity - pBlock->info.rows);
  pBlock->info.rows += numOfRows;
2367

2368
  return pBlock->info.rows;
2369 2370
}

2371
void publishOperatorProfEvent(SOperatorInfo* pOperator, EQueryProfEventType eventType) {
2372 2373
  SQueryProfEvent event = {0};

L
Liu Jicong 已提交
2374 2375
  event.eventType = eventType;
  event.eventTime = taosGetTimestampUs();
2376
  event.operatorType = pOperator->operatorType;
dengyihao's avatar
dengyihao 已提交
2377 2378 2379
  //    if (pQInfo->summary.queryProfEvents) {
  //      taosArrayPush(pQInfo->summary.queryProfEvents, &event);
  //    }
2380 2381
}

L
Liu Jicong 已提交
2382
void publishQueryAbortEvent(SExecTaskInfo* pTaskInfo, int32_t code) {
2383 2384 2385 2386 2387
  SQueryProfEvent event;
  event.eventType = QUERY_PROF_QUERY_ABORT;
  event.eventTime = taosGetTimestampUs();
  event.abortCode = code;

2388 2389
  if (pTaskInfo->cost.queryProfEvents) {
    taosArrayPush(pTaskInfo->cost.queryProfEvents, &event);
2390 2391 2392
  }
}

L
Liu Jicong 已提交
2393
typedef struct {
2394 2395 2396 2397 2398 2399 2400
  uint8_t operatorType;
  int64_t beginTime;
  int64_t endTime;
  int64_t selfTime;
  int64_t descendantsTime;
} SOperatorStackItem;

L
Liu Jicong 已提交
2401 2402
static void doOperatorExecProfOnce(SOperatorStackItem* item, SQueryProfEvent* event, SArray* opStack,
                                   SHashObj* profResults) {
2403 2404 2405 2406 2407 2408 2409 2410
  item->endTime = event->eventTime;
  item->selfTime = (item->endTime - item->beginTime) - (item->descendantsTime);

  for (int32_t j = 0; j < taosArrayGetSize(opStack); ++j) {
    SOperatorStackItem* ancestor = taosArrayGet(opStack, j);
    ancestor->descendantsTime += item->selfTime;
  }

L
Liu Jicong 已提交
2411
  uint8_t              operatorType = item->operatorType;
2412 2413 2414 2415 2416 2417 2418 2419 2420
  SOperatorProfResult* result = taosHashGet(profResults, &operatorType, sizeof(operatorType));
  if (result != NULL) {
    result->sumRunTimes++;
    result->sumSelfTime += item->selfTime;
  } else {
    SOperatorProfResult opResult;
    opResult.operatorType = operatorType;
    opResult.sumSelfTime = item->selfTime;
    opResult.sumRunTimes = 1;
L
Liu Jicong 已提交
2421
    taosHashPut(profResults, &(operatorType), sizeof(operatorType), &opResult, sizeof(opResult));
2422 2423 2424
  }
}

2425
void calculateOperatorProfResults(void) {
dengyihao's avatar
dengyihao 已提交
2426 2427 2428 2429 2430 2431 2432 2433 2434
  //  if (pQInfo->summary.queryProfEvents == NULL) {
  //    // qDebug("QInfo:0x%"PRIx64" query prof events array is null", pQInfo->qId);
  //    return;
  //  }
  //
  //  if (pQInfo->summary.operatorProfResults == NULL) {
  //    // qDebug("QInfo:0x%"PRIx64" operator prof results hash is null", pQInfo->qId);
  //    return;
  //  }
2435 2436 2437 2438 2439

  SArray* opStack = taosArrayInit(32, sizeof(SOperatorStackItem));
  if (opStack == NULL) {
    return;
  }
2440
#if 0
L
Liu Jicong 已提交
2441
  size_t    size = taosArrayGetSize(pQInfo->summary.queryProfEvents);
2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462
  SHashObj* profResults = pQInfo->summary.operatorProfResults;

  for (int i = 0; i < size; ++i) {
    SQueryProfEvent* event = taosArrayGet(pQInfo->summary.queryProfEvents, i);
    if (event->eventType == QUERY_PROF_BEFORE_OPERATOR_EXEC) {
      SOperatorStackItem opItem;
      opItem.operatorType = event->operatorType;
      opItem.beginTime = event->eventTime;
      opItem.descendantsTime = 0;
      taosArrayPush(opStack, &opItem);
    } else if (event->eventType == QUERY_PROF_AFTER_OPERATOR_EXEC) {
      SOperatorStackItem* item = taosArrayPop(opStack);
      assert(item->operatorType == event->operatorType);
      doOperatorExecProfOnce(item, event, opStack, profResults);
    } else if (event->eventType == QUERY_PROF_QUERY_ABORT) {
      SOperatorStackItem* item;
      while ((item = taosArrayPop(opStack)) != NULL) {
        doOperatorExecProfOnce(item, event, opStack, profResults);
      }
    }
  }
2463
#endif
2464 2465 2466
  taosArrayDestroy(opStack);
}

L
Liu Jicong 已提交
2467 2468
void queryCostStatis(SExecTaskInfo* pTaskInfo) {
  STaskCostInfo* pSummary = &pTaskInfo->cost;
2469

L
Liu Jicong 已提交
2470 2471 2472
  //  uint64_t hashSize = taosHashGetMemSize(pQInfo->runtimeEnv.pResultRowHashTable);
  //  hashSize += taosHashGetMemSize(pRuntimeEnv->tableqinfoGroupInfo.map);
  //  pSummary->hashSize = hashSize;
2473 2474 2475 2476

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

L
Liu Jicong 已提交
2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487
  //  SResultRowPool* p = pTaskInfo->pool;
  //  if (p != NULL) {
  //    pSummary->winInfoSize = getResultRowPoolMemSize(p);
  //    pSummary->numOfTimeWindows = getNumOfAllocatedResultRows(p);
  //  } else {
  //    pSummary->winInfoSize = 0;
  //    pSummary->numOfTimeWindows = 0;
  //  }
  //
  //  calculateOperatorProfResults(pQInfo);

2488 2489
  SFileBlockLoadRecorder* pRecorder = pSummary->pRecoder;
  if (pSummary->pRecoder != NULL) {
X
Xiaoyu Wang 已提交
2490 2491
    qDebug("%s :cost summary: elapsed time:%" PRId64 " us, first merge:%" PRId64
           " us, total blocks:%d, "
2492 2493 2494 2495
           "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 已提交
2496 2497 2498
  // 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);
2499 2500 2501 2502

  if (pSummary->operatorProfResults) {
    SOperatorProfResult* opRes = taosHashIterate(pSummary->operatorProfResults, NULL);
    while (opRes != NULL) {
L
Liu Jicong 已提交
2503 2504
      // qDebug("QInfo:0x%" PRIx64 " :cost summary: operator : %d, exec times: %" PRId64 ", self time: %" PRId64,
      //             pQInfo->qId, opRes->operatorType, opRes->sumRunTimes, opRes->sumSelfTime);
2505 2506 2507 2508 2509
      opRes = taosHashIterate(pSummary->operatorProfResults, opRes);
    }
  }
}

L
Liu Jicong 已提交
2510 2511 2512
// static void updateOffsetVal(STaskRuntimeEnv *pRuntimeEnv, SDataBlockInfo *pBlockInfo) {
//   STaskAttr *pQueryAttr = pRuntimeEnv->pQueryAttr;
//   STableQueryInfo* pTableQueryInfo = pRuntimeEnv->current;
2513
//
L
Liu Jicong 已提交
2514
//   int32_t step = GET_FORWARD_DIRECTION_FACTOR(pQueryAttr->order.order);
2515
//
L
Liu Jicong 已提交
2516 2517 2518 2519
//   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;
//   }
2520
//
L
Liu Jicong 已提交
2521 2522 2523 2524 2525
//   if (QUERY_IS_ASC_QUERY(pQueryAttr)) {
//     pQueryAttr->pos = (int32_t)pQueryAttr->limit.offset;
//   } else {
//     pQueryAttr->pos = pBlockInfo->rows - (int32_t)pQueryAttr->limit.offset - 1;
//   }
2526
//
L
Liu Jicong 已提交
2527
//   assert(pQueryAttr->pos >= 0 && pQueryAttr->pos <= pBlockInfo->rows - 1);
2528
//
L
Liu Jicong 已提交
2529 2530
//   SArray *         pDataBlock = tsdbRetrieveDataBlock(pRuntimeEnv->pTsdbReadHandle, NULL);
//   SColumnInfoData *pColInfoData = taosArrayGet(pDataBlock, 0);
2531
//
L
Liu Jicong 已提交
2532 2533
//   // update the pQueryAttr->limit.offset value, and pQueryAttr->pos value
//   TSKEY *keys = (TSKEY *) pColInfoData->pData;
2534
//
L
Liu Jicong 已提交
2535 2536 2537
//   // update the offset value
//   pTableQueryInfo->lastKey = keys[pQueryAttr->pos];
//   pQueryAttr->limit.offset = 0;
2538
//
L
Liu Jicong 已提交
2539
//   int32_t numOfRes = tableApplyFunctionsOnBlock(pRuntimeEnv, pBlockInfo, NULL, binarySearchForKey, pDataBlock);
2540
//
L
Liu Jicong 已提交
2541 2542 2543 2544
//   //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);
// }
2545

L
Liu Jicong 已提交
2546 2547
// void skipBlocks(STaskRuntimeEnv *pRuntimeEnv) {
//   STaskAttr *pQueryAttr = pRuntimeEnv->pQueryAttr;
2548
//
L
Liu Jicong 已提交
2549 2550 2551
//   if (pQueryAttr->limit.offset <= 0 || pQueryAttr->numOfFilterCols > 0) {
//     return;
//   }
2552
//
L
Liu Jicong 已提交
2553 2554
//   pQueryAttr->pos = 0;
//   int32_t step = GET_FORWARD_DIRECTION_FACTOR(pQueryAttr->order.order);
2555
//
L
Liu Jicong 已提交
2556 2557
//   STableQueryInfo* pTableQueryInfo = pRuntimeEnv->current;
//   TsdbQueryHandleT pTsdbReadHandle = pRuntimeEnv->pTsdbReadHandle;
2558
//
L
Liu Jicong 已提交
2559 2560 2561 2562 2563
//   SDataBlockInfo blockInfo = SDATA_BLOCK_INITIALIZER;
//   while (tsdbNextDataBlock(pTsdbReadHandle)) {
//     if (isTaskKilled(pRuntimeEnv->qinfo)) {
//       longjmp(pRuntimeEnv->env, TSDB_CODE_TSC_QUERY_CANCELLED);
//     }
2564
//
L
Liu Jicong 已提交
2565
//     tsdbRetrieveDataBlockInfo(pTsdbReadHandle, &blockInfo);
2566
//
L
Liu Jicong 已提交
2567 2568 2569 2570
//     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;
2571
//
L
Liu Jicong 已提交
2572 2573 2574 2575 2576 2577 2578
//       //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;
//     }
//   }
2579
//
L
Liu Jicong 已提交
2580 2581 2582 2583 2584 2585 2586 2587 2588
//   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;
2589
//
L
Liu Jicong 已提交
2590 2591 2592
//   assert(pQueryAttr->limit.offset == 0);
//   STimeWindow tw = *win;
//   getNextTimeWindow(pQueryAttr, &tw);
2593
//
L
Liu Jicong 已提交
2594 2595
//   if ((tw.skey <= pBlockInfo->window.ekey && QUERY_IS_ASC_QUERY(pQueryAttr)) ||
//       (tw.ekey >= pBlockInfo->window.skey && !QUERY_IS_ASC_QUERY(pQueryAttr))) {
2596
//
L
Liu Jicong 已提交
2597 2598 2599 2600
//     // 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);
2601
//
L
Liu Jicong 已提交
2602 2603 2604 2605
//     tw = *win;
//     int32_t startPos =
//         getNextQualifiedWindow(pQueryAttr, &tw, pBlockInfo, pColInfoData->pData, binarySearchForKey, -1);
//     assert(startPos >= 0);
2606
//
L
Liu Jicong 已提交
2607 2608
//     // set the abort info
//     pQueryAttr->pos = startPos;
2609
//
L
Liu Jicong 已提交
2610 2611 2612 2613
//     // reset the query start timestamp
//     pTableQueryInfo->win.skey = ((TSKEY *)pColInfoData->pData)[startPos];
//     pQueryAttr->window.skey = pTableQueryInfo->win.skey;
//     TSKEY key = pTableQueryInfo->win.skey;
2614
//
L
Liu Jicong 已提交
2615 2616
//     pWindowResInfo->prevSKey = tw.skey;
//     int32_t index = pRuntimeEnv->resultRowInfo.curIndex;
2617
//
L
Liu Jicong 已提交
2618 2619
//     int32_t numOfRes = tableApplyFunctionsOnBlock(pRuntimeEnv, pBlockInfo, NULL, binarySearchForKey, pDataBlock);
//     pRuntimeEnv->resultRowInfo.curIndex = index;  // restore the window index
2620
//
L
Liu Jicong 已提交
2621 2622 2623 2624
//     //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);
2625
//
L
Liu Jicong 已提交
2626 2627 2628 2629 2630
//     return key;
//   } else {  // do nothing
//     pQueryAttr->window.skey      = tw.skey;
//     pWindowResInfo->prevSKey = tw.skey;
//     pTableQueryInfo->lastKey = tw.skey;
2631
//
L
Liu Jicong 已提交
2632 2633
//     return tw.skey;
//   }
2634
//
L
Liu Jicong 已提交
2635 2636 2637 2638 2639 2640 2641 2642 2643 2644
//   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);
//   }
2645
//
L
Liu Jicong 已提交
2646 2647 2648 2649 2650
//   // 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;
//   }
2651
//
L
Liu Jicong 已提交
2652 2653 2654 2655 2656 2657 2658
//   /*
//    * 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);
2659
//
L
Liu Jicong 已提交
2660 2661
//   STimeWindow w = TSWINDOW_INITIALIZER;
//   bool ascQuery = QUERY_IS_ASC_QUERY(pQueryAttr);
2662
//
L
Liu Jicong 已提交
2663 2664
//   SResultRowInfo *pWindowResInfo = &pRuntimeEnv->resultRowInfo;
//   STableQueryInfo *pTableQueryInfo = pRuntimeEnv->current;
2665
//
L
Liu Jicong 已提交
2666 2667 2668
//   SDataBlockInfo blockInfo = SDATA_BLOCK_INITIALIZER;
//   while (tsdbNextDataBlock(pRuntimeEnv->pTsdbReadHandle)) {
//     tsdbRetrieveDataBlockInfo(pRuntimeEnv->pTsdbReadHandle, &blockInfo);
2669
//
L
Liu Jicong 已提交
2670 2671 2672 2673 2674 2675 2676 2677 2678
//     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;
//     }
2679
//
L
Liu Jicong 已提交
2680 2681
//     // the first time window
//     STimeWindow win = getActiveTimeWindow(pWindowResInfo, pWindowResInfo->prevSKey, pQueryAttr);
2682
//
L
Liu Jicong 已提交
2683 2684
//     while (pQueryAttr->limit.offset > 0) {
//       STimeWindow tw = win;
2685
//
L
Liu Jicong 已提交
2686 2687 2688
//       if ((win.ekey <= blockInfo.window.ekey && ascQuery) || (win.ekey >= blockInfo.window.skey && !ascQuery)) {
//         pQueryAttr->limit.offset -= 1;
//         pWindowResInfo->prevSKey = win.skey;
2689
//
L
Liu Jicong 已提交
2690 2691 2692 2693 2694 2695
//         // 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;
//         }
//       }
2696
//
L
Liu Jicong 已提交
2697 2698 2699 2700
//       if (pQueryAttr->limit.offset == 0) {
//         *start = doSkipIntervalProcess(pRuntimeEnv, &win, &blockInfo, pTableQueryInfo);
//         return true;
//       }
2701
//
L
Liu Jicong 已提交
2702 2703
//       // current window does not ended in current data block, try next data block
//       getNextTimeWindow(pQueryAttr, &tw);
2704
//
L
Liu Jicong 已提交
2705 2706 2707 2708 2709 2710 2711 2712 2713
//       /*
//        * 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)) {
2714
//
L
Liu Jicong 已提交
2715 2716
//         SArray *pDataBlock = tsdbRetrieveDataBlock(pRuntimeEnv->pTsdbReadHandle, NULL);
//         SColumnInfoData *pColInfoData = taosArrayGet(pDataBlock, 0);
2717
//
L
Liu Jicong 已提交
2718 2719 2720
//         if ((win.ekey > blockInfo.window.ekey && ascQuery) || (win.ekey < blockInfo.window.skey && !ascQuery)) {
//           pQueryAttr->limit.offset -= 1;
//         }
2721
//
L
Liu Jicong 已提交
2722 2723 2724 2725 2726 2727 2728 2729
//         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);
2730
//
L
Liu Jicong 已提交
2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741
//           // 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.
//       }
//     }
//   }
2742
//
L
Liu Jicong 已提交
2743 2744 2745 2746
//   // check for error
//   if (terrno != TSDB_CODE_SUCCESS) {
//     longjmp(pRuntimeEnv->env, terrno);
//   }
2747
//
L
Liu Jicong 已提交
2748 2749
//   return true;
// }
2750

2751
int32_t appendDownstream(SOperatorInfo* p, SOperatorInfo** pDownstream, int32_t num) {
H
Haojun Liao 已提交
2752
  if (p->pDownstream == NULL) {
H
Haojun Liao 已提交
2753
    assert(p->numOfDownstream == 0);
2754 2755
  }

wafwerar's avatar
wafwerar 已提交
2756
  p->pDownstream = taosMemoryCalloc(1, num * POINTER_BYTES);
2757 2758 2759 2760 2761 2762 2763
  if (p->pDownstream == NULL) {
    return TSDB_CODE_OUT_OF_MEMORY;
  }

  memcpy(p->pDownstream, pDownstream, num * POINTER_BYTES);
  p->numOfDownstream = num;
  return TSDB_CODE_SUCCESS;
2764 2765 2766 2767
}

static void doDestroyTableQueryInfo(STableGroupInfo* pTableqinfoGroupInfo);

2768
static void doTableQueryInfoTimeWindowCheck(SExecTaskInfo* pTaskInfo, STableQueryInfo* pTableQueryInfo, int32_t order) {
H
Haojun Liao 已提交
2769 2770
#if 0
    if (order == TSDB_ORDER_ASC) {
2771 2772
    assert(
        (pTableQueryInfo->win.skey <= pTableQueryInfo->win.ekey) &&
H
Haojun Liao 已提交
2773 2774
        (pTableQueryInfo->lastKey >= pTaskInfo->window.skey) &&
        (pTableQueryInfo->win.skey >= pTaskInfo->window.skey && pTableQueryInfo->win.ekey <= pTaskInfo->window.ekey));
2775 2776 2777
  } else {
    assert(
        (pTableQueryInfo->win.skey >= pTableQueryInfo->win.ekey) &&
H
Haojun Liao 已提交
2778 2779
        (pTableQueryInfo->lastKey <= pTaskInfo->window.skey) &&
        (pTableQueryInfo->win.skey <= pTaskInfo->window.skey && pTableQueryInfo->win.ekey >= pTaskInfo->window.ekey));
2780
  }
H
Haojun Liao 已提交
2781
#endif
2782 2783
}

L
Liu Jicong 已提交
2784 2785 2786 2787
// 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;
2788
//
L
Liu Jicong 已提交
2789 2790 2791
//   if (pTableQueryInfo->pTable == NULL) {
//     return;
//   }
2792
//
L
Liu Jicong 已提交
2793 2794 2795 2796 2797 2798 2799 2800 2801
//   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));
//   }
// }
2802

2803
int32_t loadRemoteDataCallback(void* param, const SDataBuf* pMsg, int32_t code) {
L
Liu Jicong 已提交
2804
  SSourceDataInfo* pSourceDataInfo = (SSourceDataInfo*)param;
H
Haojun Liao 已提交
2805 2806
  if (code == TSDB_CODE_SUCCESS) {
    pSourceDataInfo->pRsp = pMsg->pData;
2807

H
Haojun Liao 已提交
2808 2809
    SRetrieveTableRsp* pRsp = pSourceDataInfo->pRsp;
    pRsp->numOfRows = htonl(pRsp->numOfRows);
dengyihao's avatar
dengyihao 已提交
2810
    pRsp->compLen = htonl(pRsp->compLen);
2811
    pRsp->numOfCols = htonl(pRsp->numOfCols);
dengyihao's avatar
dengyihao 已提交
2812
    pRsp->useconds = htobe64(pRsp->useconds);
H
Haojun Liao 已提交
2813 2814 2815
  } else {
    pSourceDataInfo->code = code;
  }
H
Haojun Liao 已提交
2816

H
Haojun Liao 已提交
2817
  pSourceDataInfo->status = EX_SOURCE_DATA_READY;
2818
  tsem_post(&pSourceDataInfo->pEx->ready);
wmmhello's avatar
wmmhello 已提交
2819
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
2820 2821 2822 2823
}

static void destroySendMsgInfo(SMsgSendInfo* pMsgBody) {
  assert(pMsgBody != NULL);
wafwerar's avatar
wafwerar 已提交
2824 2825
  taosMemoryFreeClear(pMsgBody->msgInfo.pData);
  taosMemoryFreeClear(pMsgBody);
H
Haojun Liao 已提交
2826 2827
}

S
Shengliang Guan 已提交
2828
void qProcessFetchRsp(void* parent, SRpcMsg* pMsg, SEpSet* pEpSet) {
L
Liu Jicong 已提交
2829
  SMsgSendInfo* pSendInfo = (SMsgSendInfo*)pMsg->ahandle;
H
Haojun Liao 已提交
2830 2831 2832 2833 2834
  assert(pMsg->ahandle != NULL);

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

  if (pMsg->contLen > 0) {
wafwerar's avatar
wafwerar 已提交
2835
    buf.pData = taosMemoryCalloc(1, pMsg->contLen);
H
Haojun Liao 已提交
2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846
    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);
2847 2848
}

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

wafwerar's avatar
wafwerar 已提交
2852
  SResFetchReq* pMsg = taosMemoryCalloc(1, sizeof(SResFetchReq));
2853 2854 2855 2856
  if (NULL == pMsg) {
    pTaskInfo->code = TSDB_CODE_QRY_OUT_OF_MEMORY;
    return pTaskInfo->code;
  }
2857

L
Liu Jicong 已提交
2858 2859
  SDownstreamSourceNode* pSource = taosArrayGet(pExchangeInfo->pSources, sourceIndex);
  SSourceDataInfo*       pDataInfo = taosArrayGet(pExchangeInfo->pSourceDataInfo, sourceIndex);
2860

L
Liu Jicong 已提交
2861 2862
  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);
2863 2864 2865 2866 2867 2868 2869

  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 已提交
2870
  SMsgSendInfo* pMsgSendInfo = taosMemoryCalloc(1, sizeof(SMsgSendInfo));
2871
  if (NULL == pMsgSendInfo) {
wafwerar's avatar
wafwerar 已提交
2872
    taosMemoryFreeClear(pMsg);
2873 2874 2875
    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 已提交
2876 2877
  }

2878 2879 2880 2881 2882
  pMsgSendInfo->param = pDataInfo;
  pMsgSendInfo->msgInfo.pData = pMsg;
  pMsgSendInfo->msgInfo.len = sizeof(SResFetchReq);
  pMsgSendInfo->msgType = TDMT_VND_FETCH;
  pMsgSendInfo->fp = loadRemoteDataCallback;
2883

2884
  int64_t transporterId = 0;
L
Liu Jicong 已提交
2885
  int32_t code = asyncSendMsgToServer(pExchangeInfo->pTransporter, &pSource->addr.epSet, &transporterId, pMsgSendInfo);
2886 2887 2888
  return TSDB_CODE_SUCCESS;
}

2889
// NOTE: sources columns are more than the destination SSDatablock columns.
2890
void relocateColumnData(SSDataBlock* pBlock, const SArray* pColMatchInfo, SArray* pCols) {
2891 2892 2893
  size_t numOfSrcCols = taosArrayGetSize(pCols);

  int32_t i = 0, j = 0;
L
Liu Jicong 已提交
2894
  while (i < numOfSrcCols && j < taosArrayGetSize(pColMatchInfo)) {
2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913
    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);
    }
  }
}

2914
int32_t setSDataBlockFromFetchRsp(SSDataBlock* pRes, SLoadRemoteDataInfo* pLoadInfo, int32_t numOfRows, char* pData,
dengyihao's avatar
dengyihao 已提交
2915 2916
                                  int32_t compLen, int32_t numOfOutput, int64_t startTs, uint64_t* total,
                                  SArray* pColList) {
H
Haojun Liao 已提交
2917
  if (pColList == NULL) {  // data from other sources
H
Haojun Liao 已提交
2918 2919
    blockDataEnsureCapacity(pRes, numOfRows);

L
Liu Jicong 已提交
2920
    int32_t dataLen = *(int32_t*)pData;
2921 2922
    pData += sizeof(int32_t);

L
Liu Jicong 已提交
2923
    pRes->info.groupId = *(uint64_t*)pData;
2924 2925
    pData += sizeof(uint64_t);

H
Haojun Liao 已提交
2926 2927
    int32_t* colLen = (int32_t*)pData;

2928
    char* pStart = pData + sizeof(int32_t) * numOfOutput;
2929
    for (int32_t i = 0; i < numOfOutput; ++i) {
H
Haojun Liao 已提交
2930
      colLen[i] = htonl(colLen[i]);
2931
      ASSERT(colLen[i] >= 0);
H
Haojun Liao 已提交
2932

2933
      SColumnInfoData* pColInfoData = taosArrayGet(pRes->pDataBlock, i);
H
Haojun Liao 已提交
2934 2935 2936
      if (IS_VAR_DATA_TYPE(pColInfoData->info.type)) {
        pColInfoData->varmeta.length = colLen[i];
        pColInfoData->varmeta.allocLen = colLen[i];
2937

L
Liu Jicong 已提交
2938 2939
        memcpy(pColInfoData->varmeta.offset, pStart, sizeof(int32_t) * numOfRows);
        pStart += sizeof(int32_t) * numOfRows;
H
Haojun Liao 已提交
2940

2941 2942 2943
        if (colLen[i] > 0) {
          pColInfoData->pData = taosMemoryMalloc(colLen[i]);
        }
H
Haojun Liao 已提交
2944 2945 2946
      } else {
        memcpy(pColInfoData->nullbitmap, pStart, BitmapLen(numOfRows));
        pStart += BitmapLen(numOfRows);
2947
      }
H
Haojun Liao 已提交
2948

2949 2950 2951 2952
      if (colLen[i] > 0) {
        memcpy(pColInfoData->pData, pStart, colLen[i]);
      }

L
Liu Jicong 已提交
2953 2954
      // TODO setting this flag to true temporarily so aggregate function on stable will
      // examine NULL value for non-primary key column
2955
      pColInfoData->hasNull = true;
H
Haojun Liao 已提交
2956
      pStart += colLen[i];
2957
    }
H
Haojun Liao 已提交
2958
  } else {  // extract data according to pColList
2959
    ASSERT(numOfOutput == taosArrayGetSize(pColList));
2960 2961 2962 2963 2964
    char* pStart = pData;

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

2965
    // todo refactor:extract method
2966
    SSysTableSchema* pSchema = (SSysTableSchema*)pStart;
dengyihao's avatar
dengyihao 已提交
2967
    for (int32_t i = 0; i < numOfCols; ++i) {
2968 2969 2970 2971 2972 2973 2974
      SSysTableSchema* p = (SSysTableSchema*)pStart;

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

H
Haojun Liao 已提交
2975 2976 2977 2978
    SSDataBlock* pBlock = taosMemoryCalloc(1, sizeof(SSDataBlock));
    pBlock->pDataBlock = taosArrayInit(numOfCols, sizeof(SColumnInfoData));
    pBlock->info.numOfCols = numOfCols;

dengyihao's avatar
dengyihao 已提交
2979
    for (int32_t i = 0; i < numOfCols; ++i) {
2980 2981 2982 2983 2984
      SColumnInfoData idata = {0};
      idata.info.type = pSchema[i].type;
      idata.info.bytes = pSchema[i].bytes;
      idata.info.colId = pSchema[i].colId;

H
Haojun Liao 已提交
2985
      taosArrayPush(pBlock->pDataBlock, &idata);
2986
      if (IS_VAR_DATA_TYPE(idata.info.type)) {
H
Haojun Liao 已提交
2987
        pBlock->info.hasVarCol = true;
2988 2989 2990
      }
    }

H
Haojun Liao 已提交
2991
    blockDataEnsureCapacity(pBlock, numOfRows);
2992

L
Liu Jicong 已提交
2993 2994
    int32_t  dataLen = *(int32_t*)pStart;
    uint64_t groupId = *(uint64_t*)(pStart + sizeof(int32_t));
2995 2996
    pStart += sizeof(int32_t) + sizeof(uint64_t);

L
Liu Jicong 已提交
2997
    int32_t* colLen = (int32_t*)(pStart);
2998 2999 3000 3001
    pStart += sizeof(int32_t) * numOfCols;

    for (int32_t i = 0; i < numOfCols; ++i) {
      colLen[i] = htonl(colLen[i]);
3002
      ASSERT(colLen[i] >= 0);
3003

H
Haojun Liao 已提交
3004
      SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, i);
3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020
      if (IS_VAR_DATA_TYPE(pColInfoData->info.type)) {
        pColInfoData->varmeta.length = colLen[i];
        pColInfoData->varmeta.allocLen = colLen[i];

        memcpy(pColInfoData->varmeta.offset, pStart, sizeof(int32_t) * numOfRows);
        pStart += sizeof(int32_t) * numOfRows;

        pColInfoData->pData = taosMemoryMalloc(colLen[i]);
      } else {
        memcpy(pColInfoData->nullbitmap, pStart, BitmapLen(numOfRows));
        pStart += BitmapLen(numOfRows);
      }

      memcpy(pColInfoData->pData, pStart, colLen[i]);
      pStart += colLen[i];
    }
H
Haojun Liao 已提交
3021 3022

    // data from mnode
H
Haojun Liao 已提交
3023 3024 3025
    relocateColumnData(pRes, pColList, pBlock->pDataBlock);
    taosArrayDestroy(pBlock->pDataBlock);
    taosMemoryFree(pBlock);
X
Xiaoyu Wang 已提交
3026
    //    blockDataDestroy(pBlock);
3027
  }
3028

H
Haojun Liao 已提交
3029
  pRes->info.rows = numOfRows;
3030
  blockDataUpdateTsWindow(pRes);
3031

3032
  int64_t el = taosGetTimestampUs() - startTs;
3033

H
Haojun Liao 已提交
3034 3035
  pLoadInfo->totalRows += numOfRows;
  pLoadInfo->totalSize += compLen;
3036

H
Haojun Liao 已提交
3037 3038 3039
  if (total != NULL) {
    *total += numOfRows;
  }
3040

H
Haojun Liao 已提交
3041
  pLoadInfo->totalElapsed += el;
3042 3043
  return TSDB_CODE_SUCCESS;
}
3044

L
Liu Jicong 已提交
3045 3046
static void* setAllSourcesCompleted(SOperatorInfo* pOperator, int64_t startTs) {
  SExchangeInfo* pExchangeInfo = pOperator->info;
3047
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
H
Haojun Liao 已提交
3048

L
Liu Jicong 已提交
3049
  int64_t              el = taosGetTimestampUs() - startTs;
H
Haojun Liao 已提交
3050 3051
  SLoadRemoteDataInfo* pLoadInfo = &pExchangeInfo->loadInfo;
  pLoadInfo->totalElapsed += el;
H
Haojun Liao 已提交
3052

3053
  size_t totalSources = taosArrayGetSize(pExchangeInfo->pSources);
L
Liu Jicong 已提交
3054 3055 3056
  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);
3057 3058 3059 3060 3061

  doSetOperatorCompleted(pOperator);
  return NULL;
}

L
Liu Jicong 已提交
3062 3063
static SSDataBlock* concurrentlyLoadRemoteDataImpl(SOperatorInfo* pOperator, SExchangeInfo* pExchangeInfo,
                                                   SExecTaskInfo* pTaskInfo) {
3064 3065 3066 3067 3068 3069 3070 3071 3072
  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);

3073
      if (pDataInfo->status == EX_SOURCE_DATA_EXHAUSTED) {
3074
        completed += 1;
H
Haojun Liao 已提交
3075 3076
        continue;
      }
3077

3078
      if (pDataInfo->status != EX_SOURCE_DATA_READY) {
3079 3080 3081
        continue;
      }

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

L
Liu Jicong 已提交
3085
      SSDataBlock*         pRes = pExchangeInfo->pResult;
H
Haojun Liao 已提交
3086
      SLoadRemoteDataInfo* pLoadInfo = &pExchangeInfo->loadInfo;
3087
      if (pRsp->numOfRows == 0) {
L
Liu Jicong 已提交
3088 3089
        qDebug("%s vgId:%d, taskID:0x%" PRIx64 " index:%d completed, rowsOfSource:%" PRIu64 ", totalRows:%" PRIu64
               " try next",
3090
               GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->taskId, i + 1, pDataInfo->totalRows,
H
Haojun Liao 已提交
3091
               pExchangeInfo->loadInfo.totalRows);
3092
        pDataInfo->status = EX_SOURCE_DATA_EXHAUSTED;
3093 3094 3095
        completed += 1;
        continue;
      }
H
Haojun Liao 已提交
3096

H
Haojun Liao 已提交
3097
      SRetrieveTableRsp* pTableRsp = pDataInfo->pRsp;
X
Xiaoyu Wang 已提交
3098 3099
      code = setSDataBlockFromFetchRsp(pExchangeInfo->pResult, pLoadInfo, pTableRsp->numOfRows, pTableRsp->data,
                                       pTableRsp->compLen, pTableRsp->numOfCols, startTs, &pDataInfo->totalRows, NULL);
3100
      if (code != 0) {
3101 3102 3103
        goto _error;
      }

3104 3105 3106
      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 已提交
3107 3108
               GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->taskId, pRes->info.rows, pDataInfo->totalRows,
               pLoadInfo->totalRows, pLoadInfo->totalSize, i + 1, totalSources);
3109
        pDataInfo->status = EX_SOURCE_DATA_EXHAUSTED;
3110
      } else {
dengyihao's avatar
dengyihao 已提交
3111 3112
        qDebug("%s fetch msg rsp from vgId:%d, taskId:0x%" PRIx64 " numOfRows:%d, totalRows:%" PRIu64
               ", totalBytes:%" PRIu64,
H
Haojun Liao 已提交
3113 3114
               GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->taskId, pRes->info.rows, pLoadInfo->totalRows,
               pLoadInfo->totalSize);
3115 3116
      }

3117 3118
      if (pDataInfo->status != EX_SOURCE_DATA_EXHAUSTED) {
        pDataInfo->status = EX_SOURCE_DATA_NOT_READY;
3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137
        code = doSendFetchDataRequest(pExchangeInfo, pTaskInfo, i);
        if (code != TSDB_CODE_SUCCESS) {
          goto _error;
        }
      }

      return pExchangeInfo->pResult;
    }

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

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

L
Liu Jicong 已提交
3138 3139 3140
static SSDataBlock* concurrentlyLoadRemoteData(SOperatorInfo* pOperator) {
  SExchangeInfo* pExchangeInfo = pOperator->info;
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
H
Haojun Liao 已提交
3141

H
Haojun Liao 已提交
3142 3143 3144
  if (pOperator->status == OP_RES_TO_RETURN) {
    return concurrentlyLoadRemoteDataImpl(pOperator, pExchangeInfo, pTaskInfo);
  }
3145

L
Liu Jicong 已提交
3146
  size_t  totalSources = taosArrayGetSize(pExchangeInfo->pSources);
3147 3148 3149
  int64_t startTs = taosGetTimestampUs();

  // Asynchronously send all fetch requests to all sources.
L
Liu Jicong 已提交
3150
  for (int32_t i = 0; i < totalSources; ++i) {
3151 3152
    int32_t code = doSendFetchDataRequest(pExchangeInfo, pTaskInfo, i);
    if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
3153
      return NULL;
3154 3155 3156 3157
    }
  }

  int64_t endTs = taosGetTimestampUs();
L
Liu Jicong 已提交
3158 3159
  qDebug("%s send all fetch request to %" PRIzu " sources completed, elapsed:%" PRId64, GET_TASKID(pTaskInfo),
         totalSources, endTs - startTs);
3160 3161

  tsem_wait(&pExchangeInfo->ready);
H
Haojun Liao 已提交
3162 3163
  pOperator->status = OP_RES_TO_RETURN;
  return concurrentlyLoadRemoteDataImpl(pOperator, pExchangeInfo, pTaskInfo);
3164 3165
}

L
Liu Jicong 已提交
3166 3167 3168
static int32_t prepareConcurrentlyLoad(SOperatorInfo* pOperator) {
  SExchangeInfo* pExchangeInfo = pOperator->info;
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
3169

L
Liu Jicong 已提交
3170
  size_t  totalSources = taosArrayGetSize(pExchangeInfo->pSources);
3171 3172 3173
  int64_t startTs = taosGetTimestampUs();

  // Asynchronously send all fetch requests to all sources.
L
Liu Jicong 已提交
3174
  for (int32_t i = 0; i < totalSources; ++i) {
3175 3176
    int32_t code = doSendFetchDataRequest(pExchangeInfo, pTaskInfo, i);
    if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
3177 3178
      pTaskInfo->code = code;
      return code;
3179 3180 3181 3182
    }
  }

  int64_t endTs = taosGetTimestampUs();
L
Liu Jicong 已提交
3183 3184
  qDebug("%s send all fetch request to %" PRIzu " sources completed, elapsed:%" PRId64, GET_TASKID(pTaskInfo),
         totalSources, endTs - startTs);
3185 3186

  tsem_wait(&pExchangeInfo->ready);
H
Haojun Liao 已提交
3187
  pOperator->cost.openCost = taosGetTimestampUs() - startTs;
3188

H
Haojun Liao 已提交
3189
  return TSDB_CODE_SUCCESS;
3190 3191
}

L
Liu Jicong 已提交
3192 3193 3194
static SSDataBlock* seqLoadRemoteData(SOperatorInfo* pOperator) {
  SExchangeInfo* pExchangeInfo = pOperator->info;
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
3195

L
Liu Jicong 已提交
3196
  size_t  totalSources = taosArrayGetSize(pExchangeInfo->pSources);
3197
  int64_t startTs = taosGetTimestampUs();
3198

L
Liu Jicong 已提交
3199
  while (1) {
3200 3201
    if (pExchangeInfo->current >= totalSources) {
      return setAllSourcesCompleted(pOperator, startTs);
3202
    }
3203

3204 3205 3206
    doSendFetchDataRequest(pExchangeInfo, pTaskInfo, pExchangeInfo->current);
    tsem_wait(&pExchangeInfo->ready);

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

H
Haojun Liao 已提交
3210
    if (pDataInfo->code != TSDB_CODE_SUCCESS) {
dengyihao's avatar
dengyihao 已提交
3211 3212
      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 已提交
3213 3214 3215 3216
      pOperator->pTaskInfo->code = pDataInfo->code;
      return NULL;
    }

L
Liu Jicong 已提交
3217
    SRetrieveTableRsp*   pRsp = pDataInfo->pRsp;
H
Haojun Liao 已提交
3218
    SLoadRemoteDataInfo* pLoadInfo = &pExchangeInfo->loadInfo;
3219
    if (pRsp->numOfRows == 0) {
dengyihao's avatar
dengyihao 已提交
3220 3221
      qDebug("%s vgId:%d, taskID:0x%" PRIx64 " %d of total completed, rowsOfSource:%" PRIu64 ", totalRows:%" PRIu64
             " try next",
3222
             GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->taskId, pExchangeInfo->current + 1,
H
Haojun Liao 已提交
3223
             pDataInfo->totalRows, pLoadInfo->totalRows);
H
Haojun Liao 已提交
3224

3225
      pDataInfo->status = EX_SOURCE_DATA_EXHAUSTED;
3226 3227 3228
      pExchangeInfo->current += 1;
      continue;
    }
H
Haojun Liao 已提交
3229

L
Liu Jicong 已提交
3230
    SSDataBlock*       pRes = pExchangeInfo->pResult;
H
Haojun Liao 已提交
3231
    SRetrieveTableRsp* pTableRsp = pDataInfo->pRsp;
L
Liu Jicong 已提交
3232 3233
    int32_t            code =
        setSDataBlockFromFetchRsp(pExchangeInfo->pResult, pLoadInfo, pTableRsp->numOfRows, pTableRsp->data,
3234
                                  pTableRsp->compLen, pTableRsp->numOfCols, startTs, &pDataInfo->totalRows, NULL);
3235 3236

    if (pRsp->completed == 1) {
H
Haojun Liao 已提交
3237
      qDebug("%s fetch msg rsp from vgId:%d, taskId:0x%" PRIx64 " numOfRows:%d, rowsOfSource:%" PRIu64
L
Liu Jicong 已提交
3238 3239 3240
             ", 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);
3241

3242
      pDataInfo->status = EX_SOURCE_DATA_EXHAUSTED;
3243 3244
      pExchangeInfo->current += 1;
    } else {
L
Liu Jicong 已提交
3245 3246 3247 3248
      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);
3249 3250 3251 3252
    }

    return pExchangeInfo->pResult;
  }
3253 3254
}

L
Liu Jicong 已提交
3255
static int32_t prepareLoadRemoteData(SOperatorInfo* pOperator) {
3256
  if (OPTR_IS_OPENED(pOperator)) {
H
Haojun Liao 已提交
3257 3258 3259
    return TSDB_CODE_SUCCESS;
  }

L
Liu Jicong 已提交
3260
  SExchangeInfo* pExchangeInfo = pOperator->info;
H
Haojun Liao 已提交
3261 3262 3263 3264 3265 3266 3267 3268 3269
  if (pExchangeInfo->seqLoadData) {
    // do nothing for sequentially load data
  } else {
    int32_t code = prepareConcurrentlyLoad(pOperator);
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }
  }

3270
  OPTR_SET_OPENED(pOperator);
H
Haojun Liao 已提交
3271 3272 3273
  return TSDB_CODE_SUCCESS;
}

3274
static SSDataBlock* doLoadRemoteData(SOperatorInfo* pOperator) {
L
Liu Jicong 已提交
3275 3276
  SExchangeInfo* pExchangeInfo = pOperator->info;
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
3277

3278
  pTaskInfo->code = pOperator->fpSet._openFn(pOperator);
3279
  if (pTaskInfo->code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
3280 3281
    return NULL;
  }
3282

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

3286
  if (pOperator->status == OP_EXEC_DONE) {
L
Liu Jicong 已提交
3287 3288 3289
    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);
3290 3291 3292 3293 3294 3295
    return NULL;
  }

  if (pExchangeInfo->seqLoadData) {
    return seqLoadRemoteData(pOperator);
  } else {
H
Haojun Liao 已提交
3296
    return concurrentlyLoadRemoteData(pOperator);
3297
  }
H
Haojun Liao 已提交
3298

3299
#if 0
H
Haojun Liao 已提交
3300
  _error:
wafwerar's avatar
wafwerar 已提交
3301 3302
  taosMemoryFreeClear(pMsg);
  taosMemoryFreeClear(pMsgSendInfo);
H
Haojun Liao 已提交
3303 3304 3305

  terrno = pTaskInfo->code;
  return NULL;
3306
#endif
H
Haojun Liao 已提交
3307
}
3308

H
Haojun Liao 已提交
3309
static int32_t initDataSource(int32_t numOfSources, SExchangeInfo* pInfo) {
3310
  pInfo->pSourceDataInfo = taosArrayInit(numOfSources, sizeof(SSourceDataInfo));
H
Haojun Liao 已提交
3311 3312
  if (pInfo->pSourceDataInfo == NULL) {
    return TSDB_CODE_OUT_OF_MEMORY;
3313 3314
  }

L
Liu Jicong 已提交
3315
  for (int32_t i = 0; i < numOfSources; ++i) {
3316
    SSourceDataInfo dataInfo = {0};
H
Haojun Liao 已提交
3317
    dataInfo.status = EX_SOURCE_DATA_NOT_READY;
L
Liu Jicong 已提交
3318 3319
    dataInfo.pEx = pInfo;
    dataInfo.index = i;
3320

H
Haojun Liao 已提交
3321 3322 3323 3324 3325 3326 3327 3328 3329 3330
    void* ret = taosArrayPush(pInfo->pSourceDataInfo, &dataInfo);
    if (ret == NULL) {
      taosArrayDestroy(pInfo->pSourceDataInfo);
      return TSDB_CODE_OUT_OF_MEMORY;
    }
  }

  return TSDB_CODE_SUCCESS;
}

3331
SOperatorInfo* createExchangeOperatorInfo(void *pTransporter, const SNodeList* pSources, SSDataBlock* pBlock,
3332
                                          SExecTaskInfo* pTaskInfo) {
L
Liu Jicong 已提交
3333
  SExchangeInfo* pInfo = taosMemoryCalloc(1, sizeof(SExchangeInfo));
wafwerar's avatar
wafwerar 已提交
3334
  SOperatorInfo* pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
3335 3336

  if (pInfo == NULL || pOperator == NULL) {
wafwerar's avatar
wafwerar 已提交
3337 3338
    taosMemoryFreeClear(pInfo);
    taosMemoryFreeClear(pOperator);
H
Haojun Liao 已提交
3339 3340
    terrno = TSDB_CODE_QRY_OUT_OF_MEMORY;
    return NULL;
H
Haojun Liao 已提交
3341 3342
  }

H
Haojun Liao 已提交
3343
  size_t numOfSources = LIST_LENGTH(pSources);
H
Haojun Liao 已提交
3344
  pInfo->pSources = taosArrayInit(numOfSources, sizeof(SDownstreamSourceNode));
H
Haojun Liao 已提交
3345 3346 3347
  pInfo->pSourceDataInfo = taosArrayInit(numOfSources, sizeof(SSourceDataInfo));
  if (pInfo->pSourceDataInfo == NULL || pInfo->pSources == NULL) {
    goto _error;
H
Haojun Liao 已提交
3348 3349
  }

L
Liu Jicong 已提交
3350 3351
  for (int32_t i = 0; i < numOfSources; ++i) {
    SNodeListNode* pNode = nodesListGetNode((SNodeList*)pSources, i);
H
Haojun Liao 已提交
3352 3353
    taosArrayPush(pInfo->pSources, pNode);
  }
3354

H
Haojun Liao 已提交
3355 3356 3357
  int32_t code = initDataSource(numOfSources, pInfo);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
3358
  }
H
Haojun Liao 已提交
3359

dengyihao's avatar
dengyihao 已提交
3360
  pInfo->pResult = pBlock;
3361 3362 3363
  pInfo->seqLoadData = true;

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

dengyihao's avatar
dengyihao 已提交
3365
  pOperator->name = "ExchangeOperator";
X
Xiaoyu Wang 已提交
3366
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_EXCHANGE;
3367
  pOperator->blocking = false;
dengyihao's avatar
dengyihao 已提交
3368 3369
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
3370
  pOperator->numOfExprs = pBlock->info.numOfCols;
dengyihao's avatar
dengyihao 已提交
3371
  pOperator->pTaskInfo = pTaskInfo;
3372

L
Liu Jicong 已提交
3373 3374
  pOperator->fpSet = createOperatorFpSet(prepareLoadRemoteData, doLoadRemoteData, NULL, NULL,
                                         destroyExchangeOperatorInfo, NULL, NULL, NULL);
3375
  pInfo->pTransporter = pTransporter;
3376

3377
  return pOperator;
H
Haojun Liao 已提交
3378

L
Liu Jicong 已提交
3379
_error:
H
Haojun Liao 已提交
3380
  if (pInfo != NULL) {
H
Haojun Liao 已提交
3381
    destroyExchangeOperatorInfo(pInfo, numOfSources);
H
Haojun Liao 已提交
3382 3383
  }

wafwerar's avatar
wafwerar 已提交
3384 3385
  taosMemoryFreeClear(pInfo);
  taosMemoryFreeClear(pOperator);
H
Haojun Liao 已提交
3386
  pTaskInfo->code = TSDB_CODE_OUT_OF_MEMORY;
H
Haojun Liao 已提交
3387
  return NULL;
3388 3389
}

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

3393
static void destroySortedMergeOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
3394
  SSortedMergeOperatorInfo* pInfo = (SSortedMergeOperatorInfo*)param;
H
Haojun Liao 已提交
3395
  taosArrayDestroy(pInfo->pSortInfo);
3396 3397 3398
  taosArrayDestroy(pInfo->groupInfo);

  if (pInfo->pSortHandle != NULL) {
H
Haojun Liao 已提交
3399
    tsortDestroySortHandle(pInfo->pSortHandle);
3400 3401
  }

H
Haojun Liao 已提交
3402
  blockDataDestroy(pInfo->binfo.pRes);
H
Haojun Liao 已提交
3403
  cleanupAggSup(&pInfo->aggSup);
3404
}
H
Haojun Liao 已提交
3405

L
Liu Jicong 已提交
3406
static bool needToMerge(SSDataBlock* pBlock, SArray* groupInfo, char** buf, int32_t rowIndex) {
3407 3408 3409 3410
  size_t size = taosArrayGetSize(groupInfo);
  if (size == 0) {
    return true;
  }
3411

3412 3413
  for (int32_t i = 0; i < size; ++i) {
    int32_t* index = taosArrayGet(groupInfo, i);
3414

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

3418 3419 3420
    if ((isNull && buf[i] != NULL) || (!isNull && buf[i] == NULL)) {
      return false;
    }
3421

3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434
    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;
      }
3435 3436 3437
    }
  }

3438
  return 0;
3439 3440
}

L
Liu Jicong 已提交
3441 3442 3443
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
3444
    pCtx[j].startRow = rowIndex;
3445 3446
  }

3447 3448
  for (int32_t j = 0; j < numOfExpr; ++j) {
    int32_t functionId = pCtx[j].functionId;
L
Liu Jicong 已提交
3449 3450 3451 3452 3453 3454 3455 3456 3457
    //    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]);
    //    }
3458
  }
3459
}
3460

L
Liu Jicong 已提交
3461 3462
static void doFinalizeResultImpl(SqlFunctionCtx* pCtx, int32_t numOfExpr) {
  for (int32_t j = 0; j < numOfExpr; ++j) {
3463 3464 3465 3466
    int32_t functionId = pCtx[j].functionId;
    //    if (functionId == FUNC_TAG_DUMMY || functionId == FUNC_TS_DUMMY) {
    //      continue;
    //    }
3467

3468 3469 3470 3471
    //    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 已提交
3472
    //    pCtx[j].fpSet.finalize(&pCtx[j]);
3473 3474
  }
}
3475

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

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

3483 3484 3485
    char* data = colDataGetData(pColInfo, rowIndex);
    memcpy(rowColData[i], data, colDataGetLength(pColInfo, rowIndex));
  }
3486

3487 3488
  return true;
}
3489

3490 3491
static void doMergeImpl(SOperatorInfo* pOperator, int32_t numOfExpr, SSDataBlock* pBlock) {
  SSortedMergeOperatorInfo* pInfo = pOperator->info;
3492

3493
  SqlFunctionCtx* pCtx = pInfo->binfo.pCtx;
L
Liu Jicong 已提交
3494
  for (int32_t i = 0; i < pBlock->info.numOfCols; ++i) {
3495 3496
    pCtx[i].size = 1;
  }
3497

L
Liu Jicong 已提交
3498
  for (int32_t i = 0; i < pBlock->info.rows; ++i) {
3499 3500 3501 3502 3503 3504 3505 3506 3507
    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);
3508 3509
        int32_t numOfRows = getNumOfResult(pInfo->binfo.pCtx, pOperator->numOfExprs, NULL);
        //        setTagValueForMultipleRows(pCtx, pOperator->numOfExprs, numOfRows);
3510

3511
        // TODO check for available buffer;
H
Haojun Liao 已提交
3512

3513 3514 3515 3516 3517
        // next group info data
        pInfo->binfo.pRes->info.rows += numOfRows;
        for (int32_t j = 0; j < numOfExpr; ++j) {
          if (pCtx[j].functionId < 0) {
            continue;
3518
          }
3519

H
Haojun Liao 已提交
3520
          pCtx[j].fpSet.process(&pCtx[j]);
3521
        }
3522 3523 3524

        doMergeResultImpl(pInfo, pCtx, numOfExpr, i);
        pInfo->hasGroupVal = saveCurrentTuple(pInfo->groupVal, pInfo->groupInfo, pBlock, i);
H
Haojun Liao 已提交
3525
      }
3526 3527 3528 3529
    }
  }
}

3530 3531
static SSDataBlock* doMerge(SOperatorInfo* pOperator) {
  SSortedMergeOperatorInfo* pInfo = pOperator->info;
L
Liu Jicong 已提交
3532
  SSortHandle*              pHandle = pInfo->pSortHandle;
3533

3534
  SSDataBlock* pDataBlock = createOneDataBlock(pInfo->binfo.pRes, false);
3535
  blockDataEnsureCapacity(pDataBlock, pOperator->resultInfo.capacity);
3536

L
Liu Jicong 已提交
3537
  while (1) {
3538
    blockDataCleanup(pDataBlock);
3539
    while (1) {
H
Haojun Liao 已提交
3540
      STupleHandle* pTupleHandle = tsortNextTuple(pHandle);
3541 3542
      if (pTupleHandle == NULL) {
        break;
3543
      }
3544

3545 3546
      // build datablock for merge for one group
      appendOneRowToDataBlock(pDataBlock, pTupleHandle);
3547
      if (pDataBlock->info.rows >= pOperator->resultInfo.capacity) {
3548 3549
        break;
      }
3550
    }
3551

3552 3553 3554
    if (pDataBlock->info.rows == 0) {
      break;
    }
3555

3556
    setInputDataBlock(pOperator, pInfo->binfo.pCtx, pDataBlock, TSDB_ORDER_ASC, MAIN_SCAN, true);
L
Liu Jicong 已提交
3557 3558
    //  updateOutputBuf(&pInfo->binfo, &pAggInfo->bufCapacity, pBlock->info.rows * pAggInfo->resultRowFactor,
    //  pOperator->pRuntimeEnv, true);
3559
    doMergeImpl(pOperator, pOperator->numOfExprs, pDataBlock);
3560 3561
    // flush to tuple store, and after all data have been handled, return to upstream node or sink node
  }
3562

3563 3564 3565
  doFinalizeResultImpl(pInfo->binfo.pCtx, pOperator->numOfExprs);
  int32_t numOfRows = getNumOfResult(pInfo->binfo.pCtx, pOperator->numOfExprs, NULL);
  //        setTagValueForMultipleRows(pCtx, pOperator->numOfExprs, numOfRows);
3566

3567
  // TODO check for available buffer;
3568

3569 3570
  // next group info data
  pInfo->binfo.pRes->info.rows += numOfRows;
L
Liu Jicong 已提交
3571
  return (pInfo->binfo.pRes->info.rows > 0) ? pInfo->binfo.pRes : NULL;
3572
}
3573

3574
static SSDataBlock* doSortedMerge(SOperatorInfo* pOperator) {
3575 3576
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
3577 3578
  }

L
Liu Jicong 已提交
3579
  SExecTaskInfo*            pTaskInfo = pOperator->pTaskInfo;
3580
  SSortedMergeOperatorInfo* pInfo = pOperator->info;
H
Haojun Liao 已提交
3581
  if (pOperator->status == OP_RES_TO_RETURN) {
3582
    return getSortedBlockData(pInfo->pSortHandle, pInfo->binfo.pRes, pOperator->resultInfo.capacity, NULL);
3583 3584
  }

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

3589
  tsortSetFetchRawDataFp(pInfo->pSortHandle, loadNextDataBlock, NULL, NULL);
3590

L
Liu Jicong 已提交
3591
  for (int32_t i = 0; i < pOperator->numOfDownstream; ++i) {
wmmhello's avatar
wmmhello 已提交
3592
    SSortSource* ps = taosMemoryCalloc(1, sizeof(SSortSource));
H
Haojun Liao 已提交
3593
    ps->param = pOperator->pDownstream[i];
H
Haojun Liao 已提交
3594
    tsortAddSource(pInfo->pSortHandle, ps);
3595 3596
  }

H
Haojun Liao 已提交
3597
  int32_t code = tsortOpen(pInfo->pSortHandle);
3598
  if (code != TSDB_CODE_SUCCESS) {
3599
    longjmp(pTaskInfo->env, terrno);
3600 3601
  }

H
Haojun Liao 已提交
3602
  pOperator->status = OP_RES_TO_RETURN;
3603
  return doMerge(pOperator);
3604
}
3605

L
Liu Jicong 已提交
3606 3607
static int32_t initGroupCol(SExprInfo* pExprInfo, int32_t numOfCols, SArray* pGroupInfo,
                            SSortedMergeOperatorInfo* pInfo) {
3608 3609
  if (pGroupInfo == NULL || taosArrayGetSize(pGroupInfo) == 0) {
    return 0;
H
Haojun Liao 已提交
3610 3611
  }

3612 3613 3614 3615 3616 3617 3618 3619
  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 已提交
3620 3621
  size_t numOfGroupCol = taosArrayGetSize(pInfo->groupInfo);
  for (int32_t i = 0; i < numOfGroupCol; ++i) {
3622
    SColumn* pCol = taosArrayGet(pGroupInfo, i);
L
Liu Jicong 已提交
3623
    for (int32_t j = 0; j < numOfCols; ++j) {
H
Haojun Liao 已提交
3624
      SExprInfo* pe = &pExprInfo[j];
3625
      if (pe->base.resSchema.slotId == pCol->colId) {
3626 3627
        taosArrayPush(plist, pCol);
        taosArrayPush(pInfo->groupInfo, &j);
H
Haojun Liao 已提交
3628
        len += pCol->bytes;
3629 3630
        break;
      }
H
Haojun Liao 已提交
3631 3632 3633
    }
  }

3634
  ASSERT(taosArrayGetSize(pGroupInfo) == taosArrayGetSize(plist));
H
Haojun Liao 已提交
3635

wafwerar's avatar
wafwerar 已提交
3636
  pInfo->groupVal = taosMemoryCalloc(1, (POINTER_BYTES * numOfGroupCol + len));
3637 3638 3639 3640
  if (pInfo->groupVal == NULL) {
    taosArrayDestroy(plist);
    return TSDB_CODE_OUT_OF_MEMORY;
  }
H
Haojun Liao 已提交
3641

3642
  int32_t offset = 0;
L
Liu Jicong 已提交
3643 3644
  char*   start = (char*)(pInfo->groupVal + (POINTER_BYTES * numOfGroupCol));
  for (int32_t i = 0; i < numOfGroupCol; ++i) {
3645 3646
    pInfo->groupVal[i] = start + offset;
    SColumn* pCol = taosArrayGet(plist, i);
H
Haojun Liao 已提交
3647
    offset += pCol->bytes;
3648
  }
H
Haojun Liao 已提交
3649

3650
  taosArrayDestroy(plist);
H
Haojun Liao 已提交
3651

3652 3653
  return TSDB_CODE_SUCCESS;
}
H
Haojun Liao 已提交
3654

L
Liu Jicong 已提交
3655 3656 3657
SOperatorInfo* createSortedMergeOperatorInfo(SOperatorInfo** downstream, int32_t numOfDownstream, SExprInfo* pExprInfo,
                                             int32_t num, SArray* pSortInfo, SArray* pGroupInfo,
                                             SExecTaskInfo* pTaskInfo) {
wafwerar's avatar
wafwerar 已提交
3658
  SSortedMergeOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SSortedMergeOperatorInfo));
L
Liu Jicong 已提交
3659
  SOperatorInfo*            pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
3660
  if (pInfo == NULL || pOperator == NULL) {
3661
    goto _error;
3662
  }
H
Haojun Liao 已提交
3663

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

3667 3668 3669
  if (pInfo->binfo.pCtx == NULL || pInfo->binfo.pRes == NULL) {
    goto _error;
  }
H
Haojun Liao 已提交
3670

dengyihao's avatar
dengyihao 已提交
3671
  size_t  keyBufSize = sizeof(int64_t) + sizeof(int64_t) + POINTER_BYTES;
3672
  int32_t code = doInitAggInfoSup(&pInfo->aggSup, pInfo->binfo.pCtx, num, keyBufSize, pTaskInfo->id.str);
3673 3674 3675
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
H
Haojun Liao 已提交
3676

H
Haojun Liao 已提交
3677
  setFunctionResultOutput(&pInfo->binfo, &pInfo->aggSup, MAIN_SCAN, num, pTaskInfo);
H
Haojun Liao 已提交
3678
  code = initGroupCol(pExprInfo, num, pGroupInfo, pInfo);
3679 3680 3681
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
H
Haojun Liao 已提交
3682

L
Liu Jicong 已提交
3683 3684 3685 3686 3687
  //  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 已提交
3688

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

L
Liu Jicong 已提交
3691
  pOperator->name = "SortedMerge";
X
Xiaoyu Wang 已提交
3692
  // pOperator->operatorType = OP_SortedMerge;
3693
  pOperator->blocking = true;
L
Liu Jicong 已提交
3694 3695
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
3696
  pOperator->numOfExprs = num;
L
Liu Jicong 已提交
3697
  pOperator->pExpr = pExprInfo;
H
Haojun Liao 已提交
3698

L
Liu Jicong 已提交
3699
  pOperator->pTaskInfo = pTaskInfo;
H
Haojun Liao 已提交
3700

3701 3702
  pOperator->fpSet = createOperatorFpSet(operatorDummyOpenFn, doSortedMerge, NULL, NULL, destroySortedMergeOperatorInfo,
                                         NULL, NULL, NULL);
3703 3704 3705
  code = appendDownstream(pOperator, downstream, numOfDownstream);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
3706
  }
H
Haojun Liao 已提交
3707

3708
  return pOperator;
H
Haojun Liao 已提交
3709

L
Liu Jicong 已提交
3710
_error:
3711
  if (pInfo != NULL) {
H
Haojun Liao 已提交
3712
    destroySortedMergeOperatorInfo(pInfo, num);
H
Haojun Liao 已提交
3713 3714
  }

wafwerar's avatar
wafwerar 已提交
3715 3716
  taosMemoryFreeClear(pInfo);
  taosMemoryFreeClear(pOperator);
3717 3718
  terrno = TSDB_CODE_QRY_OUT_OF_MEMORY;
  return NULL;
H
Haojun Liao 已提交
3719 3720
}

3721
int32_t getTableScanInfo(SOperatorInfo* pOperator, int32_t *order, int32_t* scanFlag) {
3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732
  // todo add more information about exchange operation
  if (pOperator->operatorType == QUERY_NODE_PHYSICAL_PLAN_EXCHANGE) {
    *order = TSDB_ORDER_ASC;
    *scanFlag = MAIN_SCAN;
    return TSDB_CODE_SUCCESS;
  } else if (pOperator->operatorType == QUERY_NODE_PHYSICAL_PLAN_TABLE_SCAN) {
    STableScanInfo* pTableScanInfo = pOperator->info;
    *order = pTableScanInfo->cond.order;
    *scanFlag = pTableScanInfo->scanFlag;
    return TSDB_CODE_SUCCESS;
  } else {
H
Haojun Liao 已提交
3733
    if (pOperator->pDownstream == NULL || pOperator->pDownstream[0] == NULL) {
3734
      return TSDB_CODE_INVALID_PARA;
H
Haojun Liao 已提交
3735
    } else {
3736
      return getTableScanInfo(pOperator->pDownstream[0], order, scanFlag);
3737 3738 3739
    }
  }
}
3740 3741

// this is a blocking operator
L
Liu Jicong 已提交
3742
static int32_t doOpenAggregateOptr(SOperatorInfo* pOperator) {
H
Haojun Liao 已提交
3743 3744
  if (OPTR_IS_OPENED(pOperator)) {
    return TSDB_CODE_SUCCESS;
3745 3746
  }

H
Haojun Liao 已提交
3747
  SExecTaskInfo*    pTaskInfo = pOperator->pTaskInfo;
3748
  SAggOperatorInfo* pAggInfo = pOperator->info;
H
Haojun Liao 已提交
3749

dengyihao's avatar
dengyihao 已提交
3750
  SOptrBasicInfo* pInfo = &pAggInfo->binfo;
H
Haojun Liao 已提交
3751
  SOperatorInfo* downstream = pOperator->pDownstream[0];
3752

3753 3754 3755
  int32_t order = TSDB_ORDER_ASC;
  int32_t scanFlag = MAIN_SCAN;

H
Haojun Liao 已提交
3756
  while (1) {
H
Haojun Liao 已提交
3757
    publishOperatorProfEvent(downstream, QUERY_PROF_BEFORE_OPERATOR_EXEC);
3758
    SSDataBlock* pBlock = downstream->fpSet.getNextFn(downstream);
H
Haojun Liao 已提交
3759
    publishOperatorProfEvent(downstream, QUERY_PROF_AFTER_OPERATOR_EXEC);
3760 3761 3762 3763 3764

    if (pBlock == NULL) {
      break;
    }

3765 3766 3767 3768
    int32_t code = getTableScanInfo(pOperator, &order, &scanFlag);
    if (code != TSDB_CODE_SUCCESS) {
      longjmp(pTaskInfo->env, code);
    }
3769

3770 3771
    // there is an scalar expression that needs to be calculated before apply the group aggregation.
    if (pAggInfo->pScalarExprInfo != NULL) {
3772
      code = projectApplyFunctions(pAggInfo->pScalarExprInfo, pBlock, pBlock, pAggInfo->pScalarCtx,
3773
                                   pAggInfo->numOfScalarExpr, NULL);
3774
      if (code != TSDB_CODE_SUCCESS) {
3775
        longjmp(pTaskInfo->env, code);
3776
      }
3777 3778
    }

3779
    // the pDataBlock are always the same one, no need to call this again
3780
    setExecutionContext(pOperator->numOfExprs, pBlock->info.groupId, pTaskInfo, pAggInfo);
3781
    setInputDataBlock(pOperator, pInfo->pCtx, pBlock, order, scanFlag, true);
3782 3783 3784 3785
    code = doAggregateImpl(pOperator, 0, pInfo->pCtx);
    if (code != 0) {
      longjmp(pTaskInfo->env, code);
    }
3786

dengyihao's avatar
dengyihao 已提交
3787
#if 0  // test for encode/decode result info
3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798
    if(pOperator->encodeResultRow){
      char *result = NULL;
      int32_t length = 0;
      SAggSupporter   *pSup = &pAggInfo->aggSup;
      pOperator->encodeResultRow(pOperator, pSup, pInfo, &result, &length);
      taosHashClear(pSup->pResultRowHashTable);
      pInfo->resultRowInfo.size = 0;
      pOperator->decodeResultRow(pOperator, pSup, pInfo, result, length);
      if(result){
        taosMemoryFree(result);
      }
3799
    }
3800
#endif
3801 3802
  }

H
Haojun Liao 已提交
3803
  closeAllResultRows(&pAggInfo->binfo.resultRowInfo);
3804 3805
  finalizeMultiTupleQueryResult(pOperator->numOfExprs, pAggInfo->aggSup.pResultBuf, &pAggInfo->binfo.resultRowInfo,
                                pAggInfo->binfo.rowCellInfoOffset);
H
Haojun Liao 已提交
3806

3807
  initGroupedResultInfo(&pAggInfo->groupResInfo, pAggInfo->aggSup.pResultRowHashTable, false);
H
Haojun Liao 已提交
3808 3809 3810 3811
  OPTR_SET_OPENED(pOperator);
  return TSDB_CODE_SUCCESS;
}

3812
static SSDataBlock* getAggregateResult(SOperatorInfo* pOperator) {
L
Liu Jicong 已提交
3813
  SAggOperatorInfo* pAggInfo = pOperator->info;
H
Haojun Liao 已提交
3814 3815 3816 3817 3818 3819
  SOptrBasicInfo*   pInfo = &pAggInfo->binfo;

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

L
Liu Jicong 已提交
3820
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
3821
  pTaskInfo->code = pOperator->fpSet._openFn(pOperator);
H
Haojun Liao 已提交
3822 3823 3824 3825
  if (pTaskInfo->code != TSDB_CODE_SUCCESS) {
    return NULL;
  }

H
Haojun Liao 已提交
3826
  blockDataEnsureCapacity(pInfo->pRes, pOperator->resultInfo.capacity);
3827
  doBuildResultDatablock(pOperator, pInfo, &pAggInfo->groupResInfo, pAggInfo->aggSup.pResultBuf);
H
Haojun Liao 已提交
3828 3829 3830
  if (pInfo->pRes->info.rows == 0 || !hasRemainDataInCurrentGroup(&pAggInfo->groupResInfo)) {
    doSetOperatorCompleted(pOperator);
  }
3831

H
Haojun Liao 已提交
3832
  doSetOperatorCompleted(pOperator);
L
Liu Jicong 已提交
3833
  return (blockDataGetNumOfRows(pInfo->pRes) != 0) ? pInfo->pRes : NULL;
3834 3835
}

dengyihao's avatar
dengyihao 已提交
3836 3837
void aggEncodeResultRow(SOperatorInfo* pOperator, SAggSupporter* pSup, SOptrBasicInfo* pInfo, char** result,
                        int32_t* length) {
wmmhello's avatar
wmmhello 已提交
3838
  int32_t size = taosHashGetSize(pSup->pResultRowHashTable);
3839
  size_t  keyLen = sizeof(uint64_t) * 2;  // estimate the key length
wmmhello's avatar
wmmhello 已提交
3840
  int32_t totalSize = sizeof(int32_t) + size * (sizeof(int32_t) + keyLen + sizeof(int32_t) + pSup->resultRowSize);
wafwerar's avatar
wafwerar 已提交
3841
  *result = taosMemoryCalloc(1, totalSize);
L
Liu Jicong 已提交
3842
  if (*result == NULL) {
3843
    longjmp(pOperator->pTaskInfo->env, TSDB_CODE_OUT_OF_MEMORY);
wmmhello's avatar
wmmhello 已提交
3844 3845 3846
  }
  *(int32_t*)(*result) = size;
  int32_t offset = sizeof(int32_t);
3847 3848

  // prepare memory
3849
  SResultRowPosition* pos = &pInfo->resultRowInfo.cur;
dengyihao's avatar
dengyihao 已提交
3850 3851
  void*               pPage = getBufPage(pSup->pResultBuf, pos->pageId);
  SResultRow*         pRow = (SResultRow*)((char*)pPage + pos->offset);
3852 3853 3854
  setBufPageDirty(pPage, true);
  releaseBufPage(pSup->pResultBuf, pPage);

dengyihao's avatar
dengyihao 已提交
3855
  void* pIter = taosHashIterate(pSup->pResultRowHashTable, NULL);
wmmhello's avatar
wmmhello 已提交
3856
  while (pIter) {
dengyihao's avatar
dengyihao 已提交
3857
    void*               key = taosHashGetKey(pIter, &keyLen);
3858
    SResultRowPosition* p1 = (SResultRowPosition*)pIter;
3859

dengyihao's avatar
dengyihao 已提交
3860
    pPage = (SFilePage*)getBufPage(pSup->pResultBuf, p1->pageId);
3861
    pRow = (SResultRow*)((char*)pPage + p1->offset);
3862 3863
    setBufPageDirty(pPage, true);
    releaseBufPage(pSup->pResultBuf, pPage);
wmmhello's avatar
wmmhello 已提交
3864 3865 3866

    // recalculate the result size
    int32_t realTotalSize = offset + sizeof(int32_t) + keyLen + sizeof(int32_t) + pSup->resultRowSize;
L
Liu Jicong 已提交
3867 3868 3869
    if (realTotalSize > totalSize) {
      char* tmp = taosMemoryRealloc(*result, realTotalSize);
      if (tmp == NULL) {
wmmhello's avatar
wmmhello 已提交
3870
        terrno = TSDB_CODE_OUT_OF_MEMORY;
wafwerar's avatar
wafwerar 已提交
3871
        taosMemoryFree(*result);
wmmhello's avatar
wmmhello 已提交
3872
        *result = NULL;
3873
        longjmp(pOperator->pTaskInfo->env, TSDB_CODE_OUT_OF_MEMORY);
L
Liu Jicong 已提交
3874
      } else {
wmmhello's avatar
wmmhello 已提交
3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886
        *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);
3887
    memcpy(*result + offset, pRow, pSup->resultRowSize);
wmmhello's avatar
wmmhello 已提交
3888 3889 3890 3891 3892
    offset += pSup->resultRowSize;

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

L
Liu Jicong 已提交
3893
  if (length) {
wmmhello's avatar
wmmhello 已提交
3894 3895 3896 3897 3898
    *length = offset;
  }
  return;
}

dengyihao's avatar
dengyihao 已提交
3899 3900
bool aggDecodeResultRow(SOperatorInfo* pOperator, SAggSupporter* pSup, SOptrBasicInfo* pInfo, char* result,
                        int32_t length) {
L
Liu Jicong 已提交
3901
  if (!result || length <= 0) {
wmmhello's avatar
wmmhello 已提交
3902 3903 3904 3905 3906 3907 3908
    return false;
  }

  //  int32_t size = taosHashGetSize(pSup->pResultRowHashTable);
  int32_t count = *(int32_t*)(result);

  int32_t offset = sizeof(int32_t);
L
Liu Jicong 已提交
3909
  while (count-- > 0 && length > offset) {
wmmhello's avatar
wmmhello 已提交
3910 3911 3912
    int32_t keyLen = *(int32_t*)(result + offset);
    offset += sizeof(int32_t);

L
Liu Jicong 已提交
3913 3914 3915
    uint64_t    tableGroupId = *(uint64_t*)(result + offset);
    SResultRow* resultRow = getNewResultRow_rv(pSup->pResultBuf, tableGroupId, pSup->resultRowSize);
    if (!resultRow) {
3916
      longjmp(pOperator->pTaskInfo->env, TSDB_CODE_TSC_INVALID_INPUT);
wmmhello's avatar
wmmhello 已提交
3917
    }
3918

wmmhello's avatar
wmmhello 已提交
3919
    // add a new result set for a new group
3920 3921
    SResultRowPosition pos = {.pageId = resultRow->pageId, .offset = resultRow->offset};
    taosHashPut(pSup->pResultRowHashTable, result + offset, keyLen, &pos, sizeof(SResultRowPosition));
wmmhello's avatar
wmmhello 已提交
3922 3923 3924

    offset += keyLen;
    int32_t valueLen = *(int32_t*)(result + offset);
L
Liu Jicong 已提交
3925
    if (valueLen != pSup->resultRowSize) {
3926
      longjmp(pOperator->pTaskInfo->env, TSDB_CODE_TSC_INVALID_INPUT);
wmmhello's avatar
wmmhello 已提交
3927 3928 3929 3930 3931 3932 3933 3934 3935 3936
    }
    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);
3937
    prepareResultListBuffer(&pInfo->resultRowInfo, pOperator->pTaskInfo->env);
dengyihao's avatar
dengyihao 已提交
3938
    //    pInfo->resultRowInfo.cur = pInfo->resultRowInfo.size;
L
Liu Jicong 已提交
3939 3940
    //    pInfo->resultRowInfo.pPosition[pInfo->resultRowInfo.size++] =
    //        (SResultRowPosition){.pageId = resultRow->pageId, .offset = resultRow->offset};
dengyihao's avatar
dengyihao 已提交
3941
    pInfo->resultRowInfo.cur = (SResultRowPosition){.pageId = resultRow->pageId, .offset = resultRow->offset};
wmmhello's avatar
wmmhello 已提交
3942 3943
  }

L
Liu Jicong 已提交
3944
  if (offset != length) {
3945
    longjmp(pOperator->pTaskInfo->env, TSDB_CODE_TSC_INVALID_INPUT);
wmmhello's avatar
wmmhello 已提交
3946 3947 3948 3949
  }
  return true;
}

3950 3951
enum {
  PROJECT_RETRIEVE_CONTINUE = 0x1,
L
Liu Jicong 已提交
3952
  PROJECT_RETRIEVE_DONE = 0x2,
3953 3954 3955 3956 3957
};

static int32_t handleLimitOffset(SOperatorInfo* pOperator, SSDataBlock* pBlock) {
  SProjectOperatorInfo* pProjectInfo = pOperator->info;
  SOptrBasicInfo*       pInfo = &pProjectInfo->binfo;
L
Liu Jicong 已提交
3958
  SSDataBlock*          pRes = pInfo->pRes;
3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006

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

4007 4008 4009
  // 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);
4010 4011 4012 4013 4014

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

4015
    return PROJECT_RETRIEVE_DONE;
4016
  }
4017

4018
  // todo optimize performance
4019 4020
  // 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 已提交
4021 4022
  if (pRes->info.rows >= pOperator->resultInfo.threshold || pProjectInfo->slimit.offset != -1 ||
      pProjectInfo->slimit.limit != -1) {
4023
    return PROJECT_RETRIEVE_DONE;
L
Liu Jicong 已提交
4024
  } else {  // not full enough, continue to accumulate the output data in the buffer.
4025 4026 4027 4028
    return PROJECT_RETRIEVE_CONTINUE;
  }
}

4029
static SSDataBlock* doProjectOperation(SOperatorInfo* pOperator) {
4030
  SProjectOperatorInfo* pProjectInfo = pOperator->info;
L
Liu Jicong 已提交
4031
  SOptrBasicInfo*       pInfo = &pProjectInfo->binfo;
4032 4033

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

4036
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
4037 4038 4039
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }
dengyihao's avatar
dengyihao 已提交
4040

H
Haojun Liao 已提交
4041
#if 0
4042 4043 4044 4045 4046 4047
  if (pProjectInfo->existDataBlock) {  // TODO refactor
    SSDataBlock* pBlock = pProjectInfo->existDataBlock;
    pProjectInfo->existDataBlock = NULL;
    *newgroup = true;

    // todo dynamic set tags
L
Liu Jicong 已提交
4048
    //    if (pTableQueryInfo != NULL) {
4049
    //      setTagValue(pOperator, pTableQueryInfo->pTable, pInfo->pCtx, pOperator->numOfExprs);
L
Liu Jicong 已提交
4050
    //    }
4051 4052

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

H
Haojun Liao 已提交
4055
    blockDataEnsureCapacity(pInfo->pRes, pBlock->info.rows);
4056
    projectApplyFunctions(pOperator->pExpr, pInfo->pRes, pBlock, pInfo->pCtx, pOperator->numOfExprs);
L
Liu Jicong 已提交
4057
    if (pRes->info.rows >= pProjectInfo->binfo.capacity * 0.8) {
4058 4059
      copyTsColoum(pRes, pInfo->pCtx, pOperator->numOfExprs);
      resetResultRowEntryResult(pInfo->pCtx, pOperator->numOfExprs);
4060 4061 4062
      return pRes;
    }
  }
H
Haojun Liao 已提交
4063
#endif
4064

4065 4066 4067
  int32_t order = 0;
  int32_t scanFlag = 0;

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

L
Liu Jicong 已提交
4070
  while (1) {
H
Haojun Liao 已提交
4071
    // The downstream exec may change the value of the newgroup, so use a local variable instead.
H
Haojun Liao 已提交
4072
    publishOperatorProfEvent(downstream, QUERY_PROF_BEFORE_OPERATOR_EXEC);
4073
    SSDataBlock* pBlock = downstream->fpSet.getNextFn(downstream);
H
Haojun Liao 已提交
4074
    publishOperatorProfEvent(downstream, QUERY_PROF_AFTER_OPERATOR_EXEC);
4075 4076

    if (pBlock == NULL) {
4077
      setTaskStatus(pOperator->pTaskInfo, TASK_COMPLETED);
4078 4079 4080 4081
      break;
    }

    // Return result of the previous group in the firstly.
4082
    if (false) {
4083 4084 4085
      if (pRes->info.rows > 0) {
        pProjectInfo->existDataBlock = pBlock;
        break;
L
Liu Jicong 已提交
4086
      } else {  // init output buffer for a new group data
4087
        initCtxOutputBuffer(pInfo->pCtx, pOperator->numOfExprs);
4088 4089 4090
      }
    }

4091 4092
    // todo set tags

H
Haojun Liao 已提交
4093 4094
    //    STableQueryInfo* pTableQueryInfo = pRuntimeEnv->current;
    //    if (pTableQueryInfo != NULL) {
4095
    //      setTagValue(pOperator, pTableQueryInfo->pTable, pInfo->pCtx, pOperator->numOfExprs);
H
Haojun Liao 已提交
4096
    //    }
4097 4098

    // the pDataBlock are always the same one, no need to call this again
4099
    int32_t code = getTableScanInfo(pOperator->pDownstream[0], &order, &scanFlag);
4100

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

4104 4105 4106
    code = projectApplyFunctions(pOperator->pExpr, pInfo->pRes, pBlock, pInfo->pCtx, pOperator->numOfExprs, pProjectInfo->pPseudoColInfo);
    if (code != TSDB_CODE_SUCCESS) {
      longjmp(pTaskInfo->env, code);
4107 4108
    }

4109 4110
    int32_t status = handleLimitOffset(pOperator, pBlock);
    if (status == PROJECT_RETRIEVE_CONTINUE) {
H
Haojun Liao 已提交
4111
      continue;
L
Liu Jicong 已提交
4112
    } else if (status == PROJECT_RETRIEVE_DONE) {
4113 4114 4115
      break;
    }
  }
dengyihao's avatar
dengyihao 已提交
4116

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

4119
  //  copyTsColoum(pRes, pInfo->pCtx, pOperator->numOfExprs);
L
Liu Jicong 已提交
4120
  return (pInfo->pRes->info.rows > 0) ? pInfo->pRes : NULL;
4121 4122
}

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

L
Liu Jicong 已提交
4127 4128
  int64_t ekey = Q_STATUS_EQUAL(pTaskInfo->status, TASK_COMPLETED) ? pTaskInfo->window.ekey
                                                                   : pInfo->existNewGroupBlock->info.window.ekey;
4129 4130
  taosResetFillInfo(pInfo->pFillInfo, getFillInfoStart(pInfo->pFillInfo));

4131
  taosFillSetStartInfo(pInfo->pFillInfo, pInfo->existNewGroupBlock->info.rows, ekey);
4132 4133
  taosFillSetInputDataBlock(pInfo->pFillInfo, pInfo->existNewGroupBlock);

4134
  doFillTimeIntervalGapsInResults(pInfo->pFillInfo, pInfo->pRes, pResultInfo->capacity);
4135 4136 4137 4138
  pInfo->existNewGroupBlock = NULL;
  *newgroup = true;
}

L
Liu Jicong 已提交
4139 4140
static void doHandleRemainBlockFromNewGroup(SFillOperatorInfo* pInfo, SResultInfo* pResultInfo, bool* newgroup,
                                            SExecTaskInfo* pTaskInfo) {
4141 4142
  if (taosFillHasMoreResults(pInfo->pFillInfo)) {
    *newgroup = false;
4143
    doFillTimeIntervalGapsInResults(pInfo->pFillInfo, pInfo->pRes, (int32_t)pResultInfo->capacity);
H
Haojun Liao 已提交
4144
    if (pInfo->pRes->info.rows > pResultInfo->threshold || (!pInfo->multigroupResult)) {
4145 4146 4147 4148 4149 4150
      return;
    }
  }

  // handle the cached new group data block
  if (pInfo->existNewGroupBlock) {
4151
    doHandleRemainBlockForNewGroupImpl(pInfo, pResultInfo, newgroup, pTaskInfo);
4152 4153 4154
  }
}

4155
static SSDataBlock* doFill(SOperatorInfo* pOperator) {
L
Liu Jicong 已提交
4156 4157
  SFillOperatorInfo* pInfo = pOperator->info;
  SExecTaskInfo*     pTaskInfo = pOperator->pTaskInfo;
4158

H
Haojun Liao 已提交
4159
  SResultInfo* pResultInfo = &pOperator->resultInfo;
4160 4161 4162
  SSDataBlock* pResBlock = pInfo->pRes;

  blockDataCleanup(pResBlock);
4163 4164 4165 4166
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

4167
  // todo handle different group data interpolation
X
Xiaoyu Wang 已提交
4168 4169
  bool  n = false;
  bool* newgroup = &n;
4170
  doHandleRemainBlockFromNewGroup(pInfo, pResultInfo, newgroup, pTaskInfo);
4171 4172
  if (pResBlock->info.rows > pResultInfo->threshold || (!pInfo->multigroupResult && pResBlock->info.rows > 0)) {
    return pResBlock;
H
Haojun Liao 已提交
4173
  }
4174

H
Haojun Liao 已提交
4175
  SOperatorInfo* pDownstream = pOperator->pDownstream[0];
L
Liu Jicong 已提交
4176
  while (1) {
H
Haojun Liao 已提交
4177
    publishOperatorProfEvent(pDownstream, QUERY_PROF_BEFORE_OPERATOR_EXEC);
4178
    SSDataBlock* pBlock = pDownstream->fpSet.getNextFn(pDownstream);
H
Haojun Liao 已提交
4179
    publishOperatorProfEvent(pDownstream, QUERY_PROF_AFTER_OPERATOR_EXEC);
4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190

    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
4191
      taosFillSetStartInfo(pInfo->pFillInfo, 0, pTaskInfo->window.ekey);
4192 4193 4194 4195 4196 4197 4198
    } else {
      if (pBlock == NULL) {
        if (pInfo->totalInputRows == 0) {
          pOperator->status = OP_EXEC_DONE;
          return NULL;
        }

4199
        taosFillSetStartInfo(pInfo->pFillInfo, 0, pTaskInfo->window.ekey);
4200 4201 4202 4203 4204 4205 4206
      } else {
        pInfo->totalInputRows += pBlock->info.rows;
        taosFillSetStartInfo(pInfo->pFillInfo, pBlock->info.rows, pBlock->info.window.ekey);
        taosFillSetInputDataBlock(pInfo->pFillInfo, pBlock);
      }
    }

4207 4208
    blockDataEnsureCapacity(pResBlock, pOperator->resultInfo.capacity);
    doFillTimeIntervalGapsInResults(pInfo->pFillInfo, pResBlock, pOperator->resultInfo.capacity);
4209 4210

    // current group has no more result to return
4211
    if (pResBlock->info.rows > 0) {
4212 4213
      // 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
4214 4215
      if (pResBlock->info.rows > pResultInfo->threshold || pBlock == NULL || (!pInfo->multigroupResult)) {
        return pResBlock;
4216 4217
      }

4218
      doHandleRemainBlockFromNewGroup(pInfo, pResultInfo, newgroup, pTaskInfo);
4219 4220
      if (pResBlock->info.rows > pOperator->resultInfo.threshold || pBlock == NULL) {
        return pResBlock;
4221 4222 4223
      }
    } else if (pInfo->existNewGroupBlock) {  // try next group
      assert(pBlock != NULL);
4224
      doHandleRemainBlockForNewGroupImpl(pInfo, pResultInfo, newgroup, pTaskInfo);
4225 4226
      if (pResBlock->info.rows > pResultInfo->threshold) {
        return pResBlock;
4227 4228 4229 4230 4231 4232 4233 4234
      }
    } else {
      return NULL;
    }
  }
}

// todo set the attribute of query scan count
H
Haojun Liao 已提交
4235
static int32_t getNumOfScanTimes(STaskAttr* pQueryAttr) {
L
Liu Jicong 已提交
4236
  for (int32_t i = 0; i < pQueryAttr->numOfOutput; ++i) {
4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250
    int32_t functionId = getExprFunctionId(&pQueryAttr->pExpr1[i]);
    if (functionId == FUNCTION_STDDEV || functionId == FUNCTION_PERCT) {
      return 2;
    }
  }

  return 1;
}

static void destroyOperatorInfo(SOperatorInfo* pOperator) {
  if (pOperator == NULL) {
    return;
  }

4251
  if (pOperator->fpSet.closeFn != NULL) {
4252
    pOperator->fpSet.closeFn(pOperator->info, pOperator->numOfExprs);
4253 4254
  }

H
Haojun Liao 已提交
4255
  if (pOperator->pDownstream != NULL) {
L
Liu Jicong 已提交
4256
    for (int32_t i = 0; i < pOperator->numOfDownstream; ++i) {
H
Haojun Liao 已提交
4257
      destroyOperatorInfo(pOperator->pDownstream[i]);
4258 4259
    }

wafwerar's avatar
wafwerar 已提交
4260
    taosMemoryFreeClear(pOperator->pDownstream);
H
Haojun Liao 已提交
4261
    pOperator->numOfDownstream = 0;
4262 4263
  }

H
Haojun Liao 已提交
4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274
  if (pOperator->pExpr != NULL) {
    for (int32_t i = 0; i < pOperator->numOfExprs; ++i) {
      SExprInfo* pExprInfo = &pOperator->pExpr[i];
      if (pExprInfo->pExpr->nodeType == QUERY_NODE_COLUMN) {
        taosMemoryFree(pExprInfo->base.pParam[0].pCol);
      }
      taosMemoryFree(pExprInfo->base.pParam);
      taosMemoryFree(pExprInfo->pExpr);
    }
  }

D
fix bug  
dapan 已提交
4275
  taosMemoryFreeClear(pOperator->pExpr);
wafwerar's avatar
wafwerar 已提交
4276 4277
  taosMemoryFreeClear(pOperator->info);
  taosMemoryFreeClear(pOperator);
4278 4279
}

dengyihao's avatar
dengyihao 已提交
4280 4281
int32_t doInitAggInfoSup(SAggSupporter* pAggSup, SqlFunctionCtx* pCtx, int32_t numOfOutput, size_t keyBufSize,
                         const char* pKey) {
4282 4283
  _hash_fn_t hashFn = taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY);

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

H
Haojun Liao 已提交
4288
  if (pAggSup->keyBuf == NULL || pAggSup->pResultRowHashTable == NULL) {
4289 4290 4291
    return TSDB_CODE_OUT_OF_MEMORY;
  }

H
Haojun Liao 已提交
4292
  uint32_t defaultPgsz = 4096;
X
Xiaoyu Wang 已提交
4293
  while (defaultPgsz < pAggSup->resultRowSize * 4) {
H
Haojun Liao 已提交
4294 4295 4296 4297 4298 4299 4300 4301 4302 4303
    defaultPgsz <<= 1u;
  }

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

  int32_t code = createDiskbasedBuf(&pAggSup->pResultBuf, defaultPgsz, defaultBufsz, pKey, "/tmp/");
H
Haojun Liao 已提交
4304 4305 4306 4307
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

4308 4309 4310
  return TSDB_CODE_SUCCESS;
}

4311
void cleanupAggSup(SAggSupporter* pAggSup) {
wafwerar's avatar
wafwerar 已提交
4312
  taosMemoryFreeClear(pAggSup->keyBuf);
4313
  taosHashCleanup(pAggSup->pResultRowHashTable);
H
Haojun Liao 已提交
4314
  destroyDiskbasedBuf(pAggSup->pResultBuf);
4315 4316
}

H
Haojun Liao 已提交
4317
int32_t initAggInfo(SOptrBasicInfo* pBasicInfo, SAggSupporter* pAggSup, SExprInfo* pExprInfo, int32_t numOfCols,
4318
                    SSDataBlock* pResultBlock, size_t keyBufSize, const char* pkey) {
4319
  pBasicInfo->pCtx = createSqlFunctionCtx(pExprInfo, numOfCols, &pBasicInfo->rowCellInfoOffset);
H
Haojun Liao 已提交
4320 4321
  pBasicInfo->pRes = pResultBlock;

4322
  doInitAggInfoSup(pAggSup, pBasicInfo->pCtx, numOfCols, keyBufSize, pkey);
4323

L
Liu Jicong 已提交
4324
  for (int32_t i = 0; i < numOfCols; ++i) {
4325 4326 4327
    pBasicInfo->pCtx[i].pBuf = pAggSup->pResultBuf;
  }

4328
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
4329 4330
}

4331 4332 4333 4334 4335 4336 4337 4338 4339
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;
  }
}

H
Haojun Liao 已提交
4340
static STableQueryInfo* initTableQueryInfo(const STableGroupInfo* pTableGroupInfo) {
L
Liu Jicong 已提交
4341 4342 4343 4344
  if (pTableGroupInfo->numOfTables == 0) {
    return NULL;
  }

wafwerar's avatar
wafwerar 已提交
4345
  STableQueryInfo* pTableQueryInfo = taosMemoryCalloc(pTableGroupInfo->numOfTables, sizeof(STableQueryInfo));
H
Haojun Liao 已提交
4346 4347
  if (pTableQueryInfo == NULL) {
    return NULL;
H
Haojun Liao 已提交
4348
  }
H
Haojun Liao 已提交
4349 4350

  int32_t index = 0;
L
Liu Jicong 已提交
4351
  for (int32_t i = 0; i < taosArrayGetSize(pTableGroupInfo->pGroupList); ++i) {
H
Haojun Liao 已提交
4352
    SArray* pa = taosArrayGetP(pTableGroupInfo->pGroupList, i);
L
Liu Jicong 已提交
4353
    for (int32_t j = 0; j < taosArrayGetSize(pa); ++j) {
H
Haojun Liao 已提交
4354
      STableKeyInfo* pk = taosArrayGet(pa, j);
H
Haojun Liao 已提交
4355
      STableQueryInfo* pTQueryInfo = &pTableQueryInfo[index++];
L
Liu Jicong 已提交
4356
      pTQueryInfo->lastKey = pk->lastKey;
H
Haojun Liao 已提交
4357 4358
    }
  }
H
Haojun Liao 已提交
4359 4360

  STimeWindow win = {0, INT64_MAX};
4361
  createTableQueryInfo(pTableQueryInfo, win);
H
Haojun Liao 已提交
4362
  return pTableQueryInfo;
H
Haojun Liao 已提交
4363 4364
}

L
Liu Jicong 已提交
4365
SOperatorInfo* createAggregateOperatorInfo(SOperatorInfo* downstream, SExprInfo* pExprInfo, int32_t numOfCols,
4366
                                           SSDataBlock* pResultBlock, SExprInfo* pScalarExprInfo,
L
Liu Jicong 已提交
4367 4368
                                           int32_t numOfScalarExpr, SExecTaskInfo* pTaskInfo,
                                           const STableGroupInfo* pTableGroupInfo) {
wafwerar's avatar
wafwerar 已提交
4369
  SAggOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SAggOperatorInfo));
L
Liu Jicong 已提交
4370
  SOperatorInfo*    pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
4371 4372 4373
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }
H
Haojun Liao 已提交
4374

4375
  int32_t numOfRows = 10;
dengyihao's avatar
dengyihao 已提交
4376
  size_t  keyBufSize = sizeof(int64_t) + sizeof(int64_t) + POINTER_BYTES;
4377 4378

  initResultSizeInfo(pOperator, numOfRows);
dengyihao's avatar
dengyihao 已提交
4379 4380
  int32_t code =
      initAggInfo(&pInfo->binfo, &pInfo->aggSup, pExprInfo, numOfCols, pResultBlock, keyBufSize, pTaskInfo->id.str);
H
Haojun Liao 已提交
4381
  pInfo->pTableQueryInfo = initTableQueryInfo(pTableGroupInfo);
L
Liu Jicong 已提交
4382
  if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
4383 4384
    goto _error;
  }
H
Haojun Liao 已提交
4385

H
Haojun Liao 已提交
4386 4387 4388 4389
  int32_t numOfGroup = 10;  // todo replaced with true value
  pInfo->groupId = INT32_MIN;
  initResultRowInfo(&pInfo->binfo.resultRowInfo, numOfGroup);

4390 4391
  pInfo->pScalarExprInfo = pScalarExprInfo;
  pInfo->numOfScalarExpr = numOfScalarExpr;
4392 4393 4394
  if (pInfo->pScalarExprInfo != NULL) {
    pInfo->pScalarCtx = createSqlFunctionCtx(pScalarExprInfo, numOfCols, &pInfo->rowCellInfoOffset);
  }
4395

dengyihao's avatar
dengyihao 已提交
4396
  pOperator->name = "TableAggregate";
X
Xiaoyu Wang 已提交
4397
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_AGG;
4398
  pOperator->blocking = true;
dengyihao's avatar
dengyihao 已提交
4399 4400 4401
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
  pOperator->pExpr = pExprInfo;
4402
  pOperator->numOfExprs = numOfCols;
dengyihao's avatar
dengyihao 已提交
4403
  pOperator->pTaskInfo = pTaskInfo;
H
Haojun Liao 已提交
4404

4405 4406
  pOperator->fpSet = createOperatorFpSet(doOpenAggregateOptr, getAggregateResult, NULL, NULL, destroyAggOperatorInfo,
                                         aggEncodeResultRow, aggDecodeResultRow, NULL);
H
Haojun Liao 已提交
4407 4408 4409 4410 4411

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

  return pOperator;
L
Liu Jicong 已提交
4414
_error:
H
Haojun Liao 已提交
4415
  destroyAggOperatorInfo(pInfo, numOfCols);
wafwerar's avatar
wafwerar 已提交
4416 4417
  taosMemoryFreeClear(pInfo);
  taosMemoryFreeClear(pOperator);
H
Haojun Liao 已提交
4418 4419
  pTaskInfo->code = TSDB_CODE_OUT_OF_MEMORY;
  return NULL;
4420 4421
}

H
Haojun Liao 已提交
4422
void doDestroyBasicInfo(SOptrBasicInfo* pInfo, int32_t numOfOutput) {
4423 4424
  assert(pInfo != NULL);

4425
  destroySqlFunctionCtx(pInfo->pCtx, numOfOutput);
wafwerar's avatar
wafwerar 已提交
4426
  taosMemoryFreeClear(pInfo->rowCellInfoOffset);
4427 4428

  cleanupResultRowInfo(&pInfo->resultRowInfo);
H
Haojun Liao 已提交
4429
  pInfo->pRes = blockDataDestroy(pInfo->pRes);
4430 4431
}

H
Haojun Liao 已提交
4432
void destroyBasicOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
4433
  SOptrBasicInfo* pInfo = (SOptrBasicInfo*)param;
4434 4435
  doDestroyBasicInfo(pInfo, numOfOutput);
}
H
Haojun Liao 已提交
4436

H
Haojun Liao 已提交
4437
void destroyMergeJoinOperator(void* param, int32_t numOfOutput) {
X
Xiaoyu Wang 已提交
4438
  SJoinOperatorInfo* pJoinOperator = (SJoinOperatorInfo*)param;
H
Haojun Liao 已提交
4439 4440
}

H
Haojun Liao 已提交
4441
void destroyAggOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
4442
  SAggOperatorInfo* pInfo = (SAggOperatorInfo*)param;
4443 4444
  doDestroyBasicInfo(&pInfo->binfo, numOfOutput);
}
4445

H
Haojun Liao 已提交
4446
void destroySFillOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
4447
  SFillOperatorInfo* pInfo = (SFillOperatorInfo*)param;
4448
  pInfo->pFillInfo = taosDestroyFillInfo(pInfo->pFillInfo);
H
Haojun Liao 已提交
4449
  pInfo->pRes = blockDataDestroy(pInfo->pRes);
wafwerar's avatar
wafwerar 已提交
4450
  taosMemoryFreeClear(pInfo->p);
4451 4452
}

H
Haojun Liao 已提交
4453
static void destroyProjectOperatorInfo(void* param, int32_t numOfOutput) {
D
fix bug  
dapan 已提交
4454 4455 4456
  if (NULL == param) {
    return;
  }
L
Liu Jicong 已提交
4457
  SProjectOperatorInfo* pInfo = (SProjectOperatorInfo*)param;
4458
  doDestroyBasicInfo(&pInfo->binfo, numOfOutput);
H
Haojun Liao 已提交
4459
  cleanupAggSup(&pInfo->aggSup);
H
Haojun Liao 已提交
4460
  taosArrayDestroy(pInfo->pPseudoColInfo);
4461 4462
}

H
Haojun Liao 已提交
4463
void destroyExchangeOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
4464
  SExchangeInfo* pExInfo = (SExchangeInfo*)param;
H
Haojun Liao 已提交
4465 4466 4467 4468 4469 4470 4471 4472 4473
  taosArrayDestroy(pExInfo->pSources);
  taosArrayDestroy(pExInfo->pSourceDataInfo);
  if (pExInfo->pResult != NULL) {
    blockDataDestroy(pExInfo->pResult);
  }

  tsem_destroy(&pExInfo->ready);
}

H
Haojun Liao 已提交
4474 4475
static SArray* setRowTsColumnOutputInfo(SqlFunctionCtx* pCtx, int32_t numOfCols) {
  SArray* pList = taosArrayInit(4, sizeof(int32_t));
dengyihao's avatar
dengyihao 已提交
4476
  for (int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
4477 4478 4479 4480 4481 4482 4483 4484
    if (fmIsPseudoColumnFunc(pCtx[i].functionId)) {
      taosArrayPush(pList, &i);
    }
  }

  return pList;
}

L
Liu Jicong 已提交
4485
SOperatorInfo* createProjectOperatorInfo(SOperatorInfo* downstream, SExprInfo* pExprInfo, int32_t num,
dengyihao's avatar
dengyihao 已提交
4486 4487
                                         SSDataBlock* pResBlock, SLimit* pLimit, SLimit* pSlimit,
                                         SExecTaskInfo* pTaskInfo) {
wafwerar's avatar
wafwerar 已提交
4488
  SProjectOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SProjectOperatorInfo));
L
Liu Jicong 已提交
4489
  SOperatorInfo*        pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
4490 4491 4492
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }
4493

dengyihao's avatar
dengyihao 已提交
4494 4495 4496
  pInfo->limit = *pLimit;
  pInfo->slimit = *pSlimit;
  pInfo->curOffset = pLimit->offset;
H
Haojun Liao 已提交
4497 4498
  pInfo->curSOffset = pSlimit->offset;

H
Haojun Liao 已提交
4499
  pInfo->binfo.pRes = pResBlock;
H
Haojun Liao 已提交
4500 4501 4502

  int32_t numOfCols = num;
  int32_t numOfRows = 4096;
dengyihao's avatar
dengyihao 已提交
4503
  size_t  keyBufSize = sizeof(int64_t) + sizeof(int64_t) + POINTER_BYTES;
4504 4505 4506

  initResultSizeInfo(pOperator, numOfRows);
  initAggInfo(&pInfo->binfo, &pInfo->aggSup, pExprInfo, numOfCols, pResBlock, keyBufSize, pTaskInfo->id.str);
H
Haojun Liao 已提交
4507
  setFunctionResultOutput(&pInfo->binfo, &pInfo->aggSup, MAIN_SCAN, numOfCols, pTaskInfo);
H
Haojun Liao 已提交
4508
  pInfo->pPseudoColInfo = setRowTsColumnOutputInfo(pInfo->binfo.pCtx, numOfCols);
4509

dengyihao's avatar
dengyihao 已提交
4510
  pOperator->name = "ProjectOperator";
H
Haojun Liao 已提交
4511
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_PROJECT;
4512
  pOperator->blocking = false;
dengyihao's avatar
dengyihao 已提交
4513 4514 4515
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
  pOperator->pExpr = pExprInfo;
4516
  pOperator->numOfExprs = num;
4517

L
Liu Jicong 已提交
4518 4519
  pOperator->fpSet = createOperatorFpSet(operatorDummyOpenFn, doProjectOperation, NULL, NULL,
                                         destroyProjectOperatorInfo, NULL, NULL, NULL);
L
Liu Jicong 已提交
4520 4521

  pOperator->pTaskInfo = pTaskInfo;
4522
  int32_t code = appendDownstream(pOperator, &downstream, 1);
H
Haojun Liao 已提交
4523
  if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
4524 4525
    goto _error;
  }
4526 4527

  return pOperator;
H
Haojun Liao 已提交
4528

L
Liu Jicong 已提交
4529
_error:
H
Haojun Liao 已提交
4530 4531
  pTaskInfo->code = TSDB_CODE_OUT_OF_MEMORY;
  return NULL;
4532 4533
}

4534
static int32_t initFillInfo(SFillOperatorInfo* pInfo, SExprInfo* pExpr, int32_t numOfCols, SNodeListNode* pValNode,
L
Liu Jicong 已提交
4535
                            STimeWindow win, int32_t capacity, const char* id, SInterval* pInterval, int32_t fillType) {
4536
  SFillColInfo* pColInfo = createFillColInfo(pExpr, numOfCols, pValNode);
H
Haojun Liao 已提交
4537 4538

  STimeWindow w = TSWINDOW_INITIALIZER;
4539
  getAlignQueryTimeWindow(pInterval, pInterval->precision, win.skey, &w);
H
Haojun Liao 已提交
4540 4541

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

wafwerar's avatar
wafwerar 已提交
4544
  pInfo->p = taosMemoryCalloc(numOfCols, POINTER_BYTES);
H
Haojun Liao 已提交
4545 4546 4547 4548 4549 4550 4551
  if (pInfo->pFillInfo == NULL || pInfo->p == NULL) {
    return TSDB_CODE_OUT_OF_MEMORY;
  } else {
    return TSDB_CODE_SUCCESS;
  }
}

L
Liu Jicong 已提交
4552
SOperatorInfo* createFillOperatorInfo(SOperatorInfo* downstream, SExprInfo* pExpr, int32_t numOfCols,
X
Xiaoyu Wang 已提交
4553 4554 4555
                                      SInterval* pInterval, STimeWindow* pWindow, SSDataBlock* pResBlock,
                                      int32_t fillType, SNodeListNode* pValueNode, bool multigroupResult,
                                      SExecTaskInfo* pTaskInfo) {
wafwerar's avatar
wafwerar 已提交
4556
  SFillOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SFillOperatorInfo));
L
Liu Jicong 已提交
4557
  SOperatorInfo*     pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
4558

L
Liu Jicong 已提交
4559
  pInfo->pRes = pResBlock;
4560 4561
  pInfo->multigroupResult = multigroupResult;

4562 4563
  int32_t type = TSDB_FILL_NONE;
  switch (fillType) {
dengyihao's avatar
dengyihao 已提交
4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581
    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;
4582 4583 4584 4585
    default:
      type = TSDB_FILL_NONE;
  }

H
Haojun Liao 已提交
4586
  SResultInfo* pResultInfo = &pOperator->resultInfo;
4587 4588
  initResultSizeInfo(pOperator, 4096);

X
Xiaoyu Wang 已提交
4589 4590
  int32_t code = initFillInfo(pInfo, pExpr, numOfCols, pValueNode, *pWindow, pResultInfo->capacity, pTaskInfo->id.str,
                              pInterval, type);
4591 4592 4593
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
4594

dengyihao's avatar
dengyihao 已提交
4595
  pOperator->name = "FillOperator";
4596
  pOperator->blocking = false;
dengyihao's avatar
dengyihao 已提交
4597
  pOperator->status = OP_NOT_OPENED;
4598
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_FILL;
dengyihao's avatar
dengyihao 已提交
4599
  pOperator->pExpr = pExpr;
4600
  pOperator->numOfExprs = numOfCols;
dengyihao's avatar
dengyihao 已提交
4601
  pOperator->info = pInfo;
H
Haojun Liao 已提交
4602

L
Liu Jicong 已提交
4603 4604
  pOperator->fpSet =
      createOperatorFpSet(operatorDummyOpenFn, doFill, NULL, NULL, destroySFillOperatorInfo, NULL, NULL, NULL);
4605
  pOperator->pTaskInfo = pTaskInfo;
4606
  code = appendDownstream(pOperator, &downstream, 1);
4607
  return pOperator;
H
Haojun Liao 已提交
4608

L
Liu Jicong 已提交
4609
_error:
wafwerar's avatar
wafwerar 已提交
4610 4611
  taosMemoryFreeClear(pOperator);
  taosMemoryFreeClear(pInfo);
H
Haojun Liao 已提交
4612
  return NULL;
4613 4614
}

L
Liu Jicong 已提交
4615 4616
static SResSchema createResSchema(int32_t type, int32_t bytes, int32_t slotId, int32_t scale, int32_t precision,
                                  const char* name) {
H
Haojun Liao 已提交
4617
  SResSchema s = {0};
dengyihao's avatar
dengyihao 已提交
4618 4619 4620 4621
  s.scale = scale;
  s.type = type;
  s.bytes = bytes;
  s.slotId = slotId;
H
Haojun Liao 已提交
4622
  s.precision = precision;
H
Haojun Liao 已提交
4623 4624 4625 4626
  strncpy(s.name, name, tListLen(s.name));

  return s;
}
H
Haojun Liao 已提交
4627

4628
static SColumn* createColumn(int32_t blockId, int32_t slotId, int32_t colId, SDataType* pType) {
H
Haojun Liao 已提交
4629 4630 4631 4632 4633 4634
  SColumn* pCol = taosMemoryCalloc(1, sizeof(SColumn));
  if (pCol == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

dengyihao's avatar
dengyihao 已提交
4635
  pCol->slotId = slotId;
4636 4637 4638 4639
  pCol->colId  = colId;
  pCol->bytes  = pType->bytes;
  pCol->type   = pType->type;
  pCol->scale  = pType->scale;
dengyihao's avatar
dengyihao 已提交
4640
  pCol->precision = pType->precision;
H
Haojun Liao 已提交
4641 4642 4643 4644 4645
  pCol->dataBlockId = blockId;

  return pCol;
}

H
Haojun Liao 已提交
4646
SExprInfo* createExprInfo(SNodeList* pNodeList, SNodeList* pGroupKeys, int32_t* numOfExprs) {
H
Haojun Liao 已提交
4647
  int32_t numOfFuncs = LIST_LENGTH(pNodeList);
H
Haojun Liao 已提交
4648 4649 4650 4651
  int32_t numOfGroupKeys = 0;
  if (pGroupKeys != NULL) {
    numOfGroupKeys = LIST_LENGTH(pGroupKeys);
  }
H
Haojun Liao 已提交
4652

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

L
Liu Jicong 已提交
4656
  for (int32_t i = 0; i < (*numOfExprs); ++i) {
H
Haojun Liao 已提交
4657 4658 4659 4660 4661 4662
    STargetNode* pTargetNode = NULL;
    if (i < numOfFuncs) {
      pTargetNode = (STargetNode*)nodesListGetNode(pNodeList, i);
    } else {
      pTargetNode = (STargetNode*)nodesListGetNode(pGroupKeys, i - numOfFuncs);
    }
H
Haojun Liao 已提交
4663

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

wafwerar's avatar
wafwerar 已提交
4666
    pExp->pExpr = taosMemoryCalloc(1, sizeof(tExprNode));
H
Haojun Liao 已提交
4667
    pExp->pExpr->_function.num = 1;
H
Haojun Liao 已提交
4668
    pExp->pExpr->_function.functionId = -1;
H
Haojun Liao 已提交
4669

4670
    int32_t type = nodeType(pTargetNode->pExpr);
H
Haojun Liao 已提交
4671
    // it is a project query, or group by column
4672
    if (type == QUERY_NODE_COLUMN) {
H
Haojun Liao 已提交
4673
      pExp->pExpr->nodeType = QUERY_NODE_COLUMN;
L
Liu Jicong 已提交
4674
      SColumnNode* pColNode = (SColumnNode*)pTargetNode->pExpr;
H
Haojun Liao 已提交
4675

G
Ganlin Zhao 已提交
4676 4677 4678
      pExp->base.pParam = taosMemoryCalloc(1, sizeof(SFunctParam));
      pExp->base.numOfParams = 1;

H
Haojun Liao 已提交
4679
      SDataType* pType = &pColNode->node.resType;
dengyihao's avatar
dengyihao 已提交
4680 4681
      pExp->base.resSchema = createResSchema(pType->type, pType->bytes, pTargetNode->slotId, pType->scale,
                                             pType->precision, pColNode->colName);
4682
      pExp->base.pParam[0].pCol = createColumn(pColNode->dataBlockId, pColNode->slotId, pColNode->colId, pType);
H
Haojun Liao 已提交
4683
      pExp->base.pParam[0].type = FUNC_PARAM_TYPE_COLUMN;
4684
    } else if (type == QUERY_NODE_VALUE) {
4685 4686 4687 4688 4689 4690 4691
      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 已提交
4692 4693
      pExp->base.resSchema = createResSchema(pType->type, pType->bytes, pTargetNode->slotId, pType->scale,
                                             pType->precision, pValNode->node.aliasName);
4694 4695
      pExp->base.pParam[0].type = FUNC_PARAM_TYPE_VALUE;
      valueNodeToVariant(pValNode, &pExp->base.pParam[0].param);
4696
    } else if (type == QUERY_NODE_FUNCTION) {
H
Haojun Liao 已提交
4697
      pExp->pExpr->nodeType = QUERY_NODE_FUNCTION;
H
Haojun Liao 已提交
4698 4699 4700
      SFunctionNode* pFuncNode = (SFunctionNode*)pTargetNode->pExpr;

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

H
Haojun Liao 已提交
4704
      pExp->pExpr->_function.functionId = pFuncNode->funcId;
H
Haojun Liao 已提交
4705
      pExp->pExpr->_function.pFunctNode = pFuncNode;
4706

dengyihao's avatar
dengyihao 已提交
4707 4708
      strncpy(pExp->pExpr->_function.functionName, pFuncNode->functionName,
              tListLen(pExp->pExpr->_function.functionName));
4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721
#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);
        SValueNode *res = (SValueNode *)nodesMakeNode(QUERY_NODE_VALUE);
        if (NULL == res) { // todo handle error
        } else {
          res->node.resType = (SDataType) {.bytes = sizeof(int64_t), .type = TSDB_DATA_TYPE_BIGINT};
          nodesListAppend(pFuncNode->pParameterList, res);
        }
      }
#endif
H
Haojun Liao 已提交
4722 4723

      int32_t numOfParam = LIST_LENGTH(pFuncNode->pParameterList);
G
Ganlin Zhao 已提交
4724 4725 4726 4727

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

H
Haojun Liao 已提交
4728
      for (int32_t j = 0; j < numOfParam; ++j) {
4729
        SNode* p1 = nodesListGetNode(pFuncNode->pParameterList, j);
G
Ganlin Zhao 已提交
4730
        if (p1->type == QUERY_NODE_COLUMN) {
dengyihao's avatar
dengyihao 已提交
4731
          SColumnNode* pcn = (SColumnNode*)p1;
G
Ganlin Zhao 已提交
4732 4733

          pExp->base.pParam[j].type = FUNC_PARAM_TYPE_COLUMN;
4734
          pExp->base.pParam[j].pCol = createColumn(pcn->dataBlockId, pcn->slotId, pcn->colId, &pcn->node.resType);
G
Ganlin Zhao 已提交
4735 4736 4737
        } else if (p1->type == QUERY_NODE_VALUE) {
          SValueNode* pvn = (SValueNode*)p1;
          pExp->base.pParam[j].type = FUNC_PARAM_TYPE_VALUE;
4738
          valueNodeToVariant(pvn, &pExp->base.pParam[j].param);
G
Ganlin Zhao 已提交
4739
        }
H
Haojun Liao 已提交
4740
      }
4741
    } else if (type == QUERY_NODE_OPERATOR) {
H
Haojun Liao 已提交
4742
      pExp->pExpr->nodeType = QUERY_NODE_OPERATOR;
L
Liu Jicong 已提交
4743
      SOperatorNode* pNode = (SOperatorNode*)pTargetNode->pExpr;
4744

G
Ganlin Zhao 已提交
4745 4746 4747
      pExp->base.pParam = taosMemoryCalloc(1, sizeof(SFunctParam));
      pExp->base.numOfParams = 1;

4748
      SDataType* pType = &pNode->node.resType;
dengyihao's avatar
dengyihao 已提交
4749 4750
      pExp->base.resSchema = createResSchema(pType->type, pType->bytes, pTargetNode->slotId, pType->scale,
                                             pType->precision, pNode->node.aliasName);
4751 4752 4753
      pExp->pExpr->_optrRoot.pRootNode = pTargetNode->pExpr;
    } else {
      ASSERT(0);
H
Haojun Liao 已提交
4754 4755 4756
    }
  }

H
Haojun Liao 已提交
4757
  return pExprs;
H
Haojun Liao 已提交
4758 4759
}

4760
static SExecTaskInfo* createExecTaskInfo(uint64_t queryId, uint64_t taskId, EOPTR_EXEC_MODEL model) {
wafwerar's avatar
wafwerar 已提交
4761
  SExecTaskInfo* pTaskInfo = taosMemoryCalloc(1, sizeof(SExecTaskInfo));
4762
  setTaskStatus(pTaskInfo, TASK_NOT_COMPLETED);
H
Haojun Liao 已提交
4763

4764
  pTaskInfo->cost.created = taosGetTimestampMs();
H
Haojun Liao 已提交
4765
  pTaskInfo->id.queryId = queryId;
dengyihao's avatar
dengyihao 已提交
4766
  pTaskInfo->execModel = model;
H
Haojun Liao 已提交
4767

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

4772 4773
  return pTaskInfo;
}
H
Haojun Liao 已提交
4774

L
Liu Jicong 已提交
4775 4776
static tsdbReaderT doCreateDataReader(STableScanPhysiNode* pTableScanNode, SReadHandle* pHandle,
                                      STableGroupInfo* pTableGroupInfo, uint64_t queryId, uint64_t taskId);
H
Haojun Liao 已提交
4777

L
Liu Jicong 已提交
4778 4779
static int32_t doCreateTableGroup(void* metaHandle, int32_t tableType, uint64_t tableUid, STableGroupInfo* pGroupInfo,
                                  uint64_t queryId, uint64_t taskId);
4780
static SArray* extractTableIdList(const STableGroupInfo* pTableGroupInfo);
H
Haojun Liao 已提交
4781
static SArray* extractColumnInfo(SNodeList* pNodeList);
4782

4783
static SArray* createSortInfo(SNodeList* pNodeList);
4784
static SArray* extractPartitionColInfo(SNodeList* pNodeList);
4785
static void    setJoinColumnInfo(SColumnInfo* pColumn, const SColumnNode* pColumnNode);
4786

H
Haojun Liao 已提交
4787
SOperatorInfo* createOperatorTree(SPhysiNode* pPhyNode, SExecTaskInfo* pTaskInfo, SReadHandle* pHandle,
4788
                                  uint64_t queryId, uint64_t taskId, STableGroupInfo* pTableGroupInfo) {
4789 4790
  int32_t type = nodeType(pPhyNode);

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

H
Haojun Liao 已提交
4795
      tsdbReaderT pDataReader = doCreateDataReader(pTableScanNode, pHandle, pTableGroupInfo, (uint64_t)queryId, taskId);
4796
      if (pDataReader == NULL && terrno != 0) {
4797 4798
        return NULL;
      }
4799

4800
      SOperatorInfo* pOperator = createTableScanOperatorInfo(pTableScanNode, pDataReader, pHandle, pTaskInfo);
4801

4802 4803
      STableScanInfo* pScanInfo = pOperator->info;
      pTaskInfo->cost.pRecoder = &pScanInfo->readRecorder;
4804

4805
      return pOperator;
H
Haojun Liao 已提交
4806
    } else if (QUERY_NODE_PHYSICAL_PLAN_EXCHANGE == type) {
H
Haojun Liao 已提交
4807
      SExchangePhysiNode* pExchange = (SExchangePhysiNode*)pPhyNode;
4808
      SSDataBlock*        pResBlock = createResDataBlock(pExchange->node.pOutputDataBlockDesc);
4809
      return createExchangeOperatorInfo(pHandle->pMsgCb->clientRpc, pExchange->pSrcEndPoints, pResBlock, pTaskInfo);
H
Haojun Liao 已提交
4810
    } else if (QUERY_NODE_PHYSICAL_PLAN_STREAM_SCAN == type) {
H
Haojun Liao 已提交
4811
      SScanPhysiNode* pScanPhyNode = (SScanPhysiNode*)pPhyNode;  // simple child table.
5
54liuyao 已提交
4812
      STableScanPhysiNode* pTableScanNode = (STableScanPhysiNode*)pPhyNode;
4813

4814
      int32_t numOfCols = 0;
5
54liuyao 已提交
4815 4816 4817 4818 4819 4820 4821 4822

      tsdbReaderT pDataReader = NULL;
      if (pHandle->vnode) {
        pDataReader = doCreateDataReader(pTableScanNode, pHandle, pTableGroupInfo, (uint64_t)queryId, taskId);
      } else {
        doCreateTableGroup(pHandle->meta, pScanPhyNode->tableType, pScanPhyNode->uid, pTableGroupInfo, 
            queryId, taskId);
      }
4823

5
54liuyao 已提交
4824 4825 4826 4827 4828 4829
      if (pDataReader == NULL && terrno != 0) {
        qDebug("pDataReader is     NULL");
        // return NULL;
      } else {
        qDebug("pDataReader is not NULL");
      }
H
Haojun Liao 已提交
4830

4831
      SDataBlockDescNode* pDescNode = pScanPhyNode->node.pOutputDataBlockDesc;
4832
      SOperatorInfo* pOperatorDumy = createTableScanOperatorInfo(pTableScanNode, pDataReader, pHandle, pTaskInfo);
5
54liuyao 已提交
4833 4834

      SArray* tableIdList = extractTableIdList(pTableGroupInfo);
X
Xiaoyu Wang 已提交
4835
      SSDataBlock*        pResBlock = createResDataBlock(pDescNode);
4836

X
Xiaoyu Wang 已提交
4837
      SArray*        pCols = extractColMatchInfo(pScanPhyNode->pScanCols, pDescNode, &numOfCols, COL_MATCH_FROM_COL_ID);
5
54liuyao 已提交
4838
      SOperatorInfo* pOperator = createStreamScanOperatorInfo(pHandle->reader, pDataReader, pResBlock, pCols, tableIdList, pTaskInfo,
5
54liuyao 已提交
4839
                                                              pScanPhyNode->node.pConditions, pOperatorDumy);
4840
      taosArrayDestroy(tableIdList);
H
Haojun Liao 已提交
4841
      return pOperator;
H
Haojun Liao 已提交
4842
    } else if (QUERY_NODE_PHYSICAL_PLAN_SYSTABLE_SCAN == type) {
L
Liu Jicong 已提交
4843
      SSystemTableScanPhysiNode* pSysScanPhyNode = (SSystemTableScanPhysiNode*)pPhyNode;
L
Liu Jicong 已提交
4844
      SScanPhysiNode*            pScanNode = &pSysScanPhyNode->scan;
H
Haojun Liao 已提交
4845

4846 4847 4848
      SDataBlockDescNode* pDescNode = pScanNode->node.pOutputDataBlockDesc;

      SSDataBlock* pResBlock = createResDataBlock(pDescNode);
4849

4850
      int32_t numOfOutputCols = 0;
4851
      SArray* colList = extractColMatchInfo(pScanNode->pScanCols, pDescNode, &numOfOutputCols, COL_MATCH_FROM_COL_ID);
L
Liu Jicong 已提交
4852
      SOperatorInfo* pOperator = createSysTableScanOperatorInfo(
L
Liu Jicong 已提交
4853 4854
          pHandle, pResBlock, &pScanNode->tableName, pScanNode->node.pConditions, pSysScanPhyNode->mgmtEpSet, colList,
          pTaskInfo, pSysScanPhyNode->showRewrite, pSysScanPhyNode->accountId);
H
Haojun Liao 已提交
4855
      return pOperator;
4856
    } else if (QUERY_NODE_PHYSICAL_PLAN_TAG_SCAN == type) {
X
Xiaoyu Wang 已提交
4857
      STagScanPhysiNode* pScanPhyNode = (STagScanPhysiNode*)pPhyNode;
4858 4859 4860 4861

      SDataBlockDescNode* pDescNode = pScanPhyNode->node.pOutputDataBlockDesc;

      SSDataBlock* pResBlock = createResDataBlock(pDescNode);
4862

X
Xiaoyu Wang 已提交
4863 4864
      int32_t code = doCreateTableGroup(pHandle->meta, pScanPhyNode->tableType, pScanPhyNode->uid, pTableGroupInfo,
                                        queryId, taskId);
4865 4866 4867 4868
      if (code != TSDB_CODE_SUCCESS) {
        return NULL;
      }

X
Xiaoyu Wang 已提交
4869
      int32_t    num = 0;
4870 4871 4872
      SExprInfo* pExprInfo = createExprInfo(pScanPhyNode->pScanPseudoCols, NULL, &num);

      int32_t numOfOutputCols = 0;
X
Xiaoyu Wang 已提交
4873 4874
      SArray* colList =
          extractColMatchInfo(pScanPhyNode->pScanPseudoCols, pDescNode, &numOfOutputCols, COL_MATCH_FROM_COL_ID);
4875

X
Xiaoyu Wang 已提交
4876 4877
      SOperatorInfo* pOperator =
          createTagScanOperatorInfo(pHandle, pExprInfo, num, pResBlock, colList, pTableGroupInfo, pTaskInfo);
4878
      return pOperator;
H
Haojun Liao 已提交
4879 4880
    } else {
      ASSERT(0);
H
Haojun Liao 已提交
4881 4882 4883
    }
  }

4884 4885
  int32_t num = 0;
  size_t  size = LIST_LENGTH(pPhyNode->pChildren);
H
Haojun Liao 已提交
4886

4887
  SOperatorInfo** ops = taosMemoryCalloc(size, POINTER_BYTES);
dengyihao's avatar
dengyihao 已提交
4888
  for (int32_t i = 0; i < size; ++i) {
4889 4890
    SPhysiNode* pChildNode = (SPhysiNode*)nodesListGetNode(pPhyNode->pChildren, i);
    ops[i] = createOperatorTree(pChildNode, pTaskInfo, pHandle, queryId, taskId, pTableGroupInfo);
4891 4892 4893
    if (ops[i] == NULL) {
      return NULL;
    }
4894
  }
H
Haojun Liao 已提交
4895

4896
  SOperatorInfo* pOptr = NULL;
H
Haojun Liao 已提交
4897
  if (QUERY_NODE_PHYSICAL_PLAN_PROJECT == type) {
dengyihao's avatar
dengyihao 已提交
4898 4899
    SProjectPhysiNode* pProjPhyNode = (SProjectPhysiNode*)pPhyNode;
    SExprInfo*         pExprInfo = createExprInfo(pProjPhyNode->pProjections, NULL, &num);
H
Haojun Liao 已提交
4900

4901
    SSDataBlock* pResBlock = createResDataBlock(pPhyNode->pOutputDataBlockDesc);
dengyihao's avatar
dengyihao 已提交
4902 4903
    SLimit       limit = {.limit = pProjPhyNode->limit, .offset = pProjPhyNode->offset};
    SLimit       slimit = {.limit = pProjPhyNode->slimit, .offset = pProjPhyNode->soffset};
4904
    pOptr = createProjectOperatorInfo(ops[0], pExprInfo, num, pResBlock, &limit, &slimit, pTaskInfo);
H
Haojun Liao 已提交
4905 4906 4907
  } else if (QUERY_NODE_PHYSICAL_PLAN_AGG == type) {
    SAggPhysiNode* pAggNode = (SAggPhysiNode*)pPhyNode;
    SExprInfo*     pExprInfo = createExprInfo(pAggNode->pAggFuncs, pAggNode->pGroupKeys, &num);
4908
    SSDataBlock*   pResBlock = createResDataBlock(pPhyNode->pOutputDataBlockDesc);
H
Haojun Liao 已提交
4909

dengyihao's avatar
dengyihao 已提交
4910
    int32_t    numOfScalarExpr = 0;
4911 4912 4913 4914 4915
    SExprInfo* pScalarExprInfo = NULL;
    if (pAggNode->pExprs != NULL) {
      pScalarExprInfo = createExprInfo(pAggNode->pExprs, NULL, &numOfScalarExpr);
    }

H
Haojun Liao 已提交
4916 4917
    if (pAggNode->pGroupKeys != NULL) {
      SArray* pColList = extractColumnInfo(pAggNode->pGroupKeys);
dengyihao's avatar
dengyihao 已提交
4918 4919
      pOptr = createGroupOperatorInfo(ops[0], pExprInfo, num, pResBlock, pColList, pAggNode->node.pConditions,
                                      pScalarExprInfo, numOfScalarExpr, pTaskInfo, NULL);
H
Haojun Liao 已提交
4920
    } else {
dengyihao's avatar
dengyihao 已提交
4921 4922
      pOptr = createAggregateOperatorInfo(ops[0], pExprInfo, num, pResBlock, pScalarExprInfo, numOfScalarExpr,
                                          pTaskInfo, pTableGroupInfo);
H
Haojun Liao 已提交
4923
    }
X
Xiaoyu Wang 已提交
4924
  } else if (QUERY_NODE_PHYSICAL_PLAN_INTERVAL == type || QUERY_NODE_PHYSICAL_PLAN_STREAM_INTERVAL == type) {
H
Haojun Liao 已提交
4925
    SIntervalPhysiNode* pIntervalPhyNode = (SIntervalPhysiNode*)pPhyNode;
H
Haojun Liao 已提交
4926

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

dengyihao's avatar
dengyihao 已提交
4930 4931 4932 4933 4934 4935
    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 已提交
4936

dengyihao's avatar
dengyihao 已提交
4937 4938
    STimeWindowAggSupp as = {.waterMark = pIntervalPhyNode->window.watermark,
                             .calTrigger = pIntervalPhyNode->window.triggerType};
4939

4940 4941 4942 4943
    int32_t tsSlotId = ((SColumnNode*)pIntervalPhyNode->window.pTspk)->slotId;
    pOptr = createIntervalOperatorInfo(ops[0], pExprInfo, num, pResBlock, &interval, tsSlotId, &as, pTableGroupInfo,
                                       pTaskInfo);

H
Haojun Liao 已提交
4944
  } else if (QUERY_NODE_PHYSICAL_PLAN_SORT == type) {
H
Haojun Liao 已提交
4945
    SSortPhysiNode* pSortPhyNode = (SSortPhysiNode*)pPhyNode;
H
Haojun Liao 已提交
4946

4947 4948 4949
    SDataBlockDescNode* pDescNode = pPhyNode->pOutputDataBlockDesc;

    SSDataBlock* pResBlock = createResDataBlock(pDescNode);
4950
    SArray*      info = createSortInfo(pSortPhyNode->pSortKeys);
4951 4952

    int32_t    numOfCols = 0;
4953 4954 4955
    SExprInfo* pExprInfo = createExprInfo(pSortPhyNode->pExprs, NULL, &numOfCols);

    int32_t numOfOutputCols = 0;
4956
    SArray* pColList = extractColMatchInfo(pSortPhyNode->pTargets, pDescNode, &numOfOutputCols, COL_MATCH_FROM_SLOT_ID);
4957

4958
    pOptr = createSortOperatorInfo(ops[0], pResBlock, info, pExprInfo, numOfCols, pColList, pTaskInfo);
H
Haojun Liao 已提交
4959
  } else if (QUERY_NODE_PHYSICAL_PLAN_SESSION_WINDOW == type) {
H
Haojun Liao 已提交
4960 4961
    SSessionWinodwPhysiNode* pSessionNode = (SSessionWinodwPhysiNode*)pPhyNode;

X
Xiaoyu Wang 已提交
4962 4963
    STimeWindowAggSupp as = {.waterMark = pSessionNode->window.watermark,
                             .calTrigger = pSessionNode->window.triggerType};
4964

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

X
Xiaoyu Wang 已提交
4969 4970
    pOptr =
        createSessionAggOperatorInfo(ops[0], pExprInfo, num, pResBlock, pSessionNode->gap, tsSlotId, &as, pTaskInfo);
H
Haojun Liao 已提交
4971
  } else if (QUERY_NODE_PHYSICAL_PLAN_PARTITION == type) {
dengyihao's avatar
dengyihao 已提交
4972 4973 4974
    SPartitionPhysiNode* pPartNode = (SPartitionPhysiNode*)pPhyNode;
    SArray*              pColList = extractPartitionColInfo(pPartNode->pPartitionKeys);
    SSDataBlock*         pResBlock = createResDataBlock(pPhyNode->pOutputDataBlockDesc);
4975 4976

    SExprInfo* pExprInfo = createExprInfo(pPartNode->pTargets, NULL, &num);
4977
    pOptr = createPartitionOperatorInfo(ops[0], pExprInfo, num, pResBlock, pColList, pTaskInfo, NULL);
4978
  } else if (QUERY_NODE_PHYSICAL_PLAN_STATE_WINDOW == type) {
dengyihao's avatar
dengyihao 已提交
4979
    SStateWinodwPhysiNode* pStateNode = (SStateWinodwPhysiNode*)pPhyNode;
4980

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

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

4987 4988 4989
    SColumnNode* pColNode = (SColumnNode*)((STargetNode*)pStateNode->pStateKey)->pExpr;
    SColumn col = extractColumnFromColumnNode(pColNode);
    pOptr = createStatewindowOperatorInfo(ops[0], pExprInfo, num, pResBlock, &as, tsSlotId, &col, pTaskInfo);
4990
  } else if (QUERY_NODE_PHYSICAL_PLAN_JOIN == type) {
dengyihao's avatar
dengyihao 已提交
4991 4992
    SJoinPhysiNode* pJoinNode = (SJoinPhysiNode*)pPhyNode;
    SSDataBlock*    pResBlock = createResDataBlock(pPhyNode->pOutputDataBlockDesc);
4993 4994

    SExprInfo* pExprInfo = createExprInfo(pJoinNode->pTargets, NULL, &num);
H
Haojun Liao 已提交
4995
    pOptr = createMergeJoinOperatorInfo(ops, size, pExprInfo, num, pResBlock, pJoinNode->pOnConditions, pTaskInfo);
4996 4997
  } else if (QUERY_NODE_PHYSICAL_PLAN_FILL == type) {
    SFillPhysiNode* pFillNode = (SFillPhysiNode*)pPhyNode;
X
Xiaoyu Wang 已提交
4998 4999
    SSDataBlock*    pResBlock = createResDataBlock(pPhyNode->pOutputDataBlockDesc);
    SExprInfo*      pExprInfo = createExprInfo(pFillNode->pTargets, NULL, &num);
5000

5001
    SInterval* pInterval = &((SIntervalAggOperatorInfo*)ops[0]->info)->interval;
X
Xiaoyu Wang 已提交
5002 5003
    pOptr = createFillOperatorInfo(ops[0], pExprInfo, num, pInterval, &pFillNode->timeRange, pResBlock, pFillNode->mode,
                                   (SNodeListNode*)pFillNode->pValues, false, pTaskInfo);
H
Haojun Liao 已提交
5004 5005
  } else {
    ASSERT(0);
H
Haojun Liao 已提交
5006
  }
5007 5008 5009

  taosMemoryFree(ops);
  return pOptr;
5010
}
H
Haojun Liao 已提交
5011

5012
int32_t initQueryTableDataCond(SQueryTableDataCond* pCond, const STableScanPhysiNode* pTableScanNode) {
5013 5014 5015 5016 5017 5018
  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 已提交
5019
    terrno = TSDB_CODE_QRY_OUT_OF_MEMORY;
5020 5021 5022 5023 5024 5025
    return terrno;
  }

  pCond->twindow = pTableScanNode->scanRange;

#if 1
L
Liu Jicong 已提交
5026
  // todo work around a problem, remove it later
5027 5028
  if ((pCond->order == TSDB_ORDER_ASC && pCond->twindow.skey > pCond->twindow.ekey) ||
      (pCond->order == TSDB_ORDER_DESC && pCond->twindow.skey < pCond->twindow.ekey)) {
wafwerar's avatar
wafwerar 已提交
5029
    TSWAP(pCond->twindow.skey, pCond->twindow.ekey);
H
Haojun Liao 已提交
5030
  }
5031
#endif
H
Haojun Liao 已提交
5032

5033 5034
  pCond->type = BLOCK_LOAD_OFFSET_SEQ_ORDER;
  //  pCond->type = pTableScanNode->scanFlag;
H
Haojun Liao 已提交
5035

H
Haojun Liao 已提交
5036
  int32_t j = 0;
5037
  for (int32_t i = 0; i < pCond->numOfCols; ++i) {
H
Haojun Liao 已提交
5038 5039
    STargetNode* pNode = (STargetNode*)nodesListGetNode(pTableScanNode->scan.pScanCols, i);
    SColumnNode* pColNode = (SColumnNode*)pNode->pExpr;
H
Haojun Liao 已提交
5040 5041 5042
    if (pColNode->colType == COLUMN_TYPE_TAG) {
      continue;
    }
H
Haojun Liao 已提交
5043

5044 5045 5046
    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 已提交
5047
    j += 1;
H
Haojun Liao 已提交
5048 5049
  }

5050 5051
  pCond->numOfCols = j;
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
5052
}
H
Haojun Liao 已提交
5053

5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064
SColumn extractColumnFromColumnNode(SColumnNode* pColNode) {
  SColumn c = {0};
  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;
  c.precision = pColNode->node.resType.precision;
  return c;
}

H
Haojun Liao 已提交
5065
SArray* extractColumnInfo(SNodeList* pNodeList) {
L
Liu Jicong 已提交
5066
  size_t  numOfCols = LIST_LENGTH(pNodeList);
H
Haojun Liao 已提交
5067 5068 5069 5070 5071 5072
  SArray* pList = taosArrayInit(numOfCols, sizeof(SColumn));
  if (pList == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

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

5076 5077 5078
    if (nodeType(pNode->pExpr) == QUERY_NODE_COLUMN) {
      SColumnNode* pColNode = (SColumnNode*)pNode->pExpr;

5079
      SColumn c = extractColumnFromColumnNode(pColNode);
5080 5081
      taosArrayPush(pList, &c);
    } else if (nodeType(pNode->pExpr) == QUERY_NODE_VALUE) {
L
Liu Jicong 已提交
5082 5083
      SValueNode* pValNode = (SValueNode*)pNode->pExpr;
      SColumn     c = {0};
5084
      c.slotId = pNode->slotId;
L
Liu Jicong 已提交
5085 5086 5087 5088
      c.colId = pNode->slotId;
      c.type = pValNode->node.type;
      c.bytes = pValNode->node.resType.bytes;
      c.scale = pValNode->node.resType.scale;
5089 5090 5091 5092
      c.precision = pValNode->node.resType.precision;

      taosArrayPush(pList, &c);
    }
H
Haojun Liao 已提交
5093 5094 5095 5096 5097
  }

  return pList;
}

5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111
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 已提交
5112 5113 5114
    c.colId = pColNode->colId;
    c.type = pColNode->node.resType.type;
    c.bytes = pColNode->node.resType.bytes;
5115 5116 5117 5118 5119 5120 5121 5122 5123
    c.precision = pColNode->node.resType.precision;
    c.scale = pColNode->node.resType.scale;

    taosArrayPush(pList, &c);
  }

  return pList;
}

5124
SArray* createSortInfo(SNodeList* pNodeList) {
L
Liu Jicong 已提交
5125
  size_t  numOfCols = LIST_LENGTH(pNodeList);
H
Haojun Liao 已提交
5126 5127 5128 5129 5130 5131
  SArray* pList = taosArrayInit(numOfCols, sizeof(SBlockOrderInfo));
  if (pList == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return pList;
  }

L
Liu Jicong 已提交
5132
  for (int32_t i = 0; i < numOfCols; ++i) {
5133
    SOrderByExprNode* pSortKey = (SOrderByExprNode*)nodesListGetNode(pNodeList, i);
L
Liu Jicong 已提交
5134 5135
    SBlockOrderInfo   bi = {0};
    bi.order = (pSortKey->order == ORDER_ASC) ? TSDB_ORDER_ASC : TSDB_ORDER_DESC;
H
Haojun Liao 已提交
5136 5137 5138
    bi.nullFirst = (pSortKey->nullOrder == NULL_ORDER_FIRST);

    SColumnNode* pColNode = (SColumnNode*)pSortKey->pExpr;
5139
    bi.slotId = pColNode->slotId;
H
Haojun Liao 已提交
5140 5141 5142 5143 5144 5145
    taosArrayPush(pList, &bi);
  }

  return pList;
}

X
Xiaoyu Wang 已提交
5146 5147
SArray* extractColMatchInfo(SNodeList* pNodeList, SDataBlockDescNode* pOutputNodeList, int32_t* numOfOutputCols,
                            int32_t type) {
L
Liu Jicong 已提交
5148
  size_t  numOfCols = LIST_LENGTH(pNodeList);
H
Haojun Liao 已提交
5149 5150 5151 5152 5153 5154
  SArray* pList = taosArrayInit(numOfCols, sizeof(SColMatchInfo));
  if (pList == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

L
Liu Jicong 已提交
5155 5156 5157
  for (int32_t i = 0; i < numOfCols; ++i) {
    STargetNode* pNode = (STargetNode*)nodesListGetNode(pNodeList, i);
    SColumnNode* pColNode = (SColumnNode*)pNode->pExpr;
H
Haojun Liao 已提交
5158 5159

    SColMatchInfo c = {0};
X
Xiaoyu Wang 已提交
5160 5161 5162 5163
    c.output = true;
    c.colId = pColNode->colId;
    c.srcSlotId = pColNode->slotId;
    c.matchType = type;
H
Haojun Liao 已提交
5164 5165 5166 5167
    c.targetSlotId = pNode->slotId;
    taosArrayPush(pList, &c);
  }

H
Haojun Liao 已提交
5168 5169
  *numOfOutputCols = 0;
  int32_t num = LIST_LENGTH(pOutputNodeList->pSlots);
L
Liu Jicong 已提交
5170 5171
  for (int32_t i = 0; i < num; ++i) {
    SSlotDescNode* pNode = (SSlotDescNode*)nodesListGetNode(pOutputNodeList->pSlots, i);
5172

5173
    // todo: add reserve flag check
5174 5175
    // it is a column reserved for the arithmetic expression calculation
    if (pNode->slotId >= numOfCols) {
5176 5177 5178 5179
      (*numOfOutputCols) += 1;
      continue;
    }

H
Haojun Liao 已提交
5180
    SColMatchInfo* info = taosArrayGet(pList, pNode->slotId);
H
Haojun Liao 已提交
5181 5182 5183 5184 5185
    if (pNode->output) {
      (*numOfOutputCols) += 1;
    } else {
      info->output = false;
    }
H
Haojun Liao 已提交
5186 5187
  }

H
Haojun Liao 已提交
5188 5189 5190
  return pList;
}

dengyihao's avatar
dengyihao 已提交
5191 5192
int32_t doCreateTableGroup(void* metaHandle, int32_t tableType, uint64_t tableUid, STableGroupInfo* pGroupInfo,
                           uint64_t queryId, uint64_t taskId) {
5193
  int32_t code = 0;
H
Haojun Liao 已提交
5194
  if (tableType == TSDB_SUPER_TABLE) {
H
Haojun Liao 已提交
5195
    code = tsdbQuerySTableByTagCond(metaHandle, tableUid, 0, NULL, 0, 0, NULL, pGroupInfo, NULL, 0, queryId, taskId);
H
Haojun Liao 已提交
5196
  } else {  // Create one table group.
H
Haojun Liao 已提交
5197
    code = tsdbGetOneTableGroup(metaHandle, tableUid, 0, pGroupInfo);
5198 5199 5200 5201
  }

  return code;
}
H
Haojun Liao 已提交
5202

5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220
SArray* extractTableIdList(const STableGroupInfo* pTableGroupInfo) {
  SArray* tableIdList = taosArrayInit(4, sizeof(uint64_t));

  if (pTableGroupInfo->numOfTables > 0) {
    SArray* pa = taosArrayGetP(pTableGroupInfo->pGroupList, 0);
    ASSERT(taosArrayGetSize(pTableGroupInfo->pGroupList) == 1);

    // Transfer the Array of STableKeyInfo into uid list.
    size_t numOfTables = taosArrayGetSize(pa);
    for (int32_t i = 0; i < numOfTables; ++i) {
      STableKeyInfo* pkeyInfo = taosArrayGet(pa, i);
      taosArrayPush(tableIdList, &pkeyInfo->uid);
    }
  }

  return tableIdList;
}

L
Liu Jicong 已提交
5221 5222
tsdbReaderT doCreateDataReader(STableScanPhysiNode* pTableScanNode, SReadHandle* pHandle,
                               STableGroupInfo* pTableGroupInfo, uint64_t queryId, uint64_t taskId) {
5223
  uint64_t uid = pTableScanNode->scan.uid;
L
Liu Jicong 已提交
5224 5225
  int32_t  code =
      doCreateTableGroup(pHandle->meta, pTableScanNode->scan.tableType, uid, pTableGroupInfo, queryId, taskId);
5226 5227
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
H
Haojun Liao 已提交
5228
  }
H
Haojun Liao 已提交
5229

H
Haojun Liao 已提交
5230
  if (pTableGroupInfo->numOfTables == 0) {
H
Haojun Liao 已提交
5231
    code = 0;
L
Liu Jicong 已提交
5232
    qDebug("no table qualified for query, TID:0x%" PRIx64 ", QID:0x%" PRIx64, taskId, queryId);
H
Haojun Liao 已提交
5233 5234
    goto _error;
  }
H
Haojun Liao 已提交
5235

5236 5237 5238 5239
  SQueryTableDataCond cond = {0};
  code = initQueryTableDataCond(&cond, pTableScanNode);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
X
Xiaoyu Wang 已提交
5240
  }
5241

5242
  return tsdbQueryTables(pHandle->vnode, &cond, pTableGroupInfo, queryId, taskId);
H
Haojun Liao 已提交
5243

L
Liu Jicong 已提交
5244
_error:
H
Haojun Liao 已提交
5245 5246 5247 5248
  terrno = code;
  return NULL;
}

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

H
Haojun Liao 已提交
5253
  int32_t code = TSDB_CODE_SUCCESS;
5254
  *pTaskInfo = createExecTaskInfo(queryId, taskId, model);
H
Haojun Liao 已提交
5255 5256 5257 5258
  if (*pTaskInfo == NULL) {
    code = TSDB_CODE_QRY_OUT_OF_MEMORY;
    goto _complete;
  }
H
Haojun Liao 已提交
5259

L
Liu Jicong 已提交
5260 5261
  (*pTaskInfo)->pRoot =
      createOperatorTree(pPlan->pNode, *pTaskInfo, pHandle, queryId, taskId, &(*pTaskInfo)->tableqinfoGroupInfo);
D
dapan1121 已提交
5262
  if (NULL == (*pTaskInfo)->pRoot) {
L
Liu Jicong 已提交
5263
    code = terrno;
D
dapan1121 已提交
5264 5265
    goto _complete;
  }
H
Haojun Liao 已提交
5266

5267
  if ((*pTaskInfo)->pRoot == NULL) {
H
Haojun Liao 已提交
5268
    code = TSDB_CODE_QRY_OUT_OF_MEMORY;
H
Haojun Liao 已提交
5269
    goto _complete;
5270 5271
  }

H
Haojun Liao 已提交
5272 5273
  return code;

H
Haojun Liao 已提交
5274
_complete:
wafwerar's avatar
wafwerar 已提交
5275
  taosMemoryFreeClear(*pTaskInfo);
H
Haojun Liao 已提交
5276 5277 5278

  terrno = code;
  return code;
H
Haojun Liao 已提交
5279 5280
}

H
Haojun Liao 已提交
5281
void setResultBufSize(STaskAttr* pQueryAttr, SResultInfo* pResultInfo) {
5282 5283 5284 5285 5286 5287 5288 5289
  const int32_t DEFAULT_RESULT_MSG_SIZE = 1024 * (1024 + 512);

  // the minimum number of rows for projection query
  const int32_t MIN_ROWS_FOR_PRJ_QUERY = 8192;
  const int32_t DEFAULT_MIN_ROWS = 4096;

  const float THRESHOLD_RATIO = 0.85f;

dengyihao's avatar
dengyihao 已提交
5290 5291 5292 5293 5294 5295 5296 5297 5298 5299
  //  if (isProjQuery(pQueryAttr)) {
  //    int32_t numOfRes = DEFAULT_RESULT_MSG_SIZE / pQueryAttr->resultRowSize;
  //    if (numOfRes < MIN_ROWS_FOR_PRJ_QUERY) {
  //      numOfRes = MIN_ROWS_FOR_PRJ_QUERY;
  //    }
  //
  //    pResultInfo->capacity = numOfRes;
  //  } else {  // in case of non-prj query, a smaller output buffer will be used.
  //    pResultInfo->capacity = DEFAULT_MIN_ROWS;
  //  }
5300 5301

  pResultInfo->threshold = (int32_t)(pResultInfo->capacity * THRESHOLD_RATIO);
H
Haojun Liao 已提交
5302
  pResultInfo->totalRows = 0;
5303 5304
}

L
Liu Jicong 已提交
5305
// TODO refactor
5306
void freeColumnFilterInfo(SColumnFilterInfo* pFilter, int32_t numOfFilters) {
L
Liu Jicong 已提交
5307 5308 5309
  if (pFilter == NULL || numOfFilters == 0) {
    return;
  }
5310

L
Liu Jicong 已提交
5311 5312 5313
  for (int32_t i = 0; i < numOfFilters; i++) {
    if (pFilter[i].filterstr && pFilter[i].pz) {
      taosMemoryFree((void*)(pFilter[i].pz));
5314
    }
L
Liu Jicong 已提交
5315
  }
5316

L
Liu Jicong 已提交
5317
  taosMemoryFree(pFilter);
5318 5319 5320 5321
}

static void doDestroyTableQueryInfo(STableGroupInfo* pTableqinfoGroupInfo) {
  if (pTableqinfoGroupInfo->pGroupList != NULL) {
L
Liu Jicong 已提交
5322
    int32_t numOfGroups = (int32_t)taosArrayGetSize(pTableqinfoGroupInfo->pGroupList);
5323
    for (int32_t i = 0; i < numOfGroups; ++i) {
L
Liu Jicong 已提交
5324
      SArray* p = taosArrayGetP(pTableqinfoGroupInfo->pGroupList, i);
5325 5326

      size_t num = taosArrayGetSize(p);
L
Liu Jicong 已提交
5327
      for (int32_t j = 0; j < num; ++j) {
5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343
        STableQueryInfo* item = taosArrayGetP(p, j);
        destroyTableQueryInfoImpl(item);
      }

      taosArrayDestroy(p);
    }
  }

  taosArrayDestroy(pTableqinfoGroupInfo->pGroupList);
  taosHashCleanup(pTableqinfoGroupInfo->map);

  pTableqinfoGroupInfo->pGroupList = NULL;
  pTableqinfoGroupInfo->map = NULL;
  pTableqinfoGroupInfo->numOfTables = 0;
}

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

H
Haojun Liao 已提交
5347
  doDestroyTableQueryInfo(&pTaskInfo->tableqinfoGroupInfo);
H
Haojun Liao 已提交
5348
  destroyOperatorInfo(pTaskInfo->pRoot);
L
Liu Jicong 已提交
5349 5350
  //  taosArrayDestroy(pTaskInfo->summary.queryProfEvents);
  //  taosHashCleanup(pTaskInfo->summary.operatorProfResults);
5351

wafwerar's avatar
wafwerar 已提交
5352 5353 5354
  taosMemoryFreeClear(pTaskInfo->sql);
  taosMemoryFreeClear(pTaskInfo->id.str);
  taosMemoryFreeClear(pTaskInfo);
5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366
}

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 已提交
5367
      int32_t len = (varDataLen(val) > maxLen) ? maxLen : varDataLen(val);
5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379
      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 已提交
5380 5381
  //  size_t s3 = sizeof(STableCheckInfo);  buffer consumption in tsdb
  return (int64_t)(s1 * 1.5 * numOfTables);
5382 5383 5384 5385 5386 5387 5388
}

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 已提交
5389
    while (1) {
5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415
      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 已提交
5416

dengyihao's avatar
dengyihao 已提交
5417 5418
int32_t getOperatorExplainExecInfo(SOperatorInfo* operatorInfo, SExplainExecInfo** pRes, int32_t* capacity,
                                   int32_t* resNum) {
D
dapan1121 已提交
5419 5420
  if (*resNum >= *capacity) {
    *capacity += 10;
dengyihao's avatar
dengyihao 已提交
5421

D
dapan1121 已提交
5422 5423
    *pRes = taosMemoryRealloc(*pRes, (*capacity) * sizeof(SExplainExecInfo));
    if (NULL == *pRes) {
D
dapan1121 已提交
5424
      qError("malloc %d failed", (*capacity) * (int32_t)sizeof(SExplainExecInfo));
D
dapan1121 已提交
5425 5426 5427 5428
      return TSDB_CODE_QRY_OUT_OF_MEMORY;
    }
  }

D
dapan1121 已提交
5429 5430 5431 5432
  (*pRes)[*resNum].numOfRows = operatorInfo->resultInfo.totalRows;
  (*pRes)[*resNum].startupCost = operatorInfo->cost.openCost;
  (*pRes)[*resNum].totalCost = operatorInfo->cost.totalCost;

5433 5434
  if (operatorInfo->fpSet.getExplainFn) {
    int32_t code = (*operatorInfo->fpSet.getExplainFn)(operatorInfo, &(*pRes)->verboseInfo);
D
dapan1121 已提交
5435 5436 5437 5438 5439
    if (code) {
      qError("operator getExplainFn failed, error:%s", tstrerror(code));
      return code;
    }
  }
dengyihao's avatar
dengyihao 已提交
5440

D
dapan1121 已提交
5441
  ++(*resNum);
dengyihao's avatar
dengyihao 已提交
5442

D
dapan1121 已提交
5443
  int32_t code = 0;
D
dapan1121 已提交
5444 5445
  for (int32_t i = 0; i < operatorInfo->numOfDownstream; ++i) {
    code = getOperatorExplainExecInfo(operatorInfo->pDownstream[i], pRes, capacity, resNum);
D
dapan1121 已提交
5446 5447 5448 5449 5450 5451 5452
    if (code) {
      taosMemoryFreeClear(*pRes);
      return TSDB_CODE_QRY_OUT_OF_MEMORY;
    }
  }

  return TSDB_CODE_SUCCESS;
D
dapan1121 已提交
5453 5454
}

5455
static SSDataBlock* doMergeJoin(struct SOperatorInfo* pOperator) {
5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467
  SJoinOperatorInfo* pJoinInfo = pOperator->info;

  SSDataBlock* pRes = pJoinInfo->pRes;
  blockDataCleanup(pRes);
  blockDataEnsureCapacity(pRes, 4096);

  int32_t nrows = 0;

  while (1) {
    if (pJoinInfo->pLeft == NULL || pJoinInfo->leftPos >= pJoinInfo->pLeft->info.rows) {
      SOperatorInfo* ds1 = pOperator->pDownstream[0];
      publishOperatorProfEvent(ds1, QUERY_PROF_BEFORE_OPERATOR_EXEC);
5468
      pJoinInfo->pLeft = ds1->fpSet.getNextFn(ds1);
5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480
      publishOperatorProfEvent(ds1, QUERY_PROF_AFTER_OPERATOR_EXEC);

      pJoinInfo->leftPos = 0;
      if (pJoinInfo->pLeft == NULL) {
        setTaskStatus(pOperator->pTaskInfo, TASK_COMPLETED);
        break;
      }
    }

    if (pJoinInfo->pRight == NULL || pJoinInfo->rightPos >= pJoinInfo->pRight->info.rows) {
      SOperatorInfo* ds2 = pOperator->pDownstream[1];
      publishOperatorProfEvent(ds2, QUERY_PROF_BEFORE_OPERATOR_EXEC);
5481
      pJoinInfo->pRight = ds2->fpSet.getNextFn(ds2);
5482 5483 5484 5485 5486 5487 5488 5489 5490 5491
      publishOperatorProfEvent(ds2, QUERY_PROF_AFTER_OPERATOR_EXEC);

      pJoinInfo->rightPos = 0;
      if (pJoinInfo->pRight == NULL) {
        setTaskStatus(pOperator->pTaskInfo, TASK_COMPLETED);
        break;
      }
    }

    SColumnInfoData* pLeftCol = taosArrayGet(pJoinInfo->pLeft->pDataBlock, pJoinInfo->leftCol.slotId);
dengyihao's avatar
dengyihao 已提交
5492
    char*            pLeftVal = colDataGetData(pLeftCol, pJoinInfo->leftPos);
5493 5494

    SColumnInfoData* pRightCol = taosArrayGet(pJoinInfo->pRight->pDataBlock, pJoinInfo->rightCol.slotId);
dengyihao's avatar
dengyihao 已提交
5495
    char*            pRightVal = colDataGetData(pRightCol, pJoinInfo->rightPos);
5496 5497

    // only the timestamp match support for ordinary table
dengyihao's avatar
dengyihao 已提交
5498 5499
    ASSERT(pLeftCol->info.type == TSDB_DATA_TYPE_TIMESTAMP);
    if (*(int64_t*)pLeftVal == *(int64_t*)pRightVal) {
5500
      for (int32_t i = 0; i < pOperator->numOfExprs; ++i) {
dengyihao's avatar
dengyihao 已提交
5501
        SColumnInfoData* pDst = taosArrayGet(pRes->pDataBlock, i);
5502

dengyihao's avatar
dengyihao 已提交
5503
        SExprInfo* pExprInfo = &pOperator->pExpr[i];
5504

dengyihao's avatar
dengyihao 已提交
5505 5506
        int32_t blockId = pExprInfo->base.pParam[0].pCol->dataBlockId;
        int32_t slotId = pExprInfo->base.pParam[0].pCol->slotId;
5507

dengyihao's avatar
dengyihao 已提交
5508 5509 5510 5511 5512 5513
        SColumnInfoData* pSrc = NULL;
        if (pJoinInfo->pLeft->info.blockId == blockId) {
          pSrc = taosArrayGet(pJoinInfo->pLeft->pDataBlock, slotId);
        } else {
          pSrc = taosArrayGet(pJoinInfo->pRight->pDataBlock, slotId);
        }
5514

dengyihao's avatar
dengyihao 已提交
5515 5516 5517 5518 5519
        if (colDataIsNull_s(pSrc, pJoinInfo->leftPos)) {
          colDataAppendNULL(pDst, nrows);
        } else {
          char* p = colDataGetData(pSrc, pJoinInfo->leftPos);
          colDataAppend(pDst, nrows, p, false);
5520
        }
dengyihao's avatar
dengyihao 已提交
5521
      }
5522

dengyihao's avatar
dengyihao 已提交
5523 5524
      pJoinInfo->leftPos += 1;
      pJoinInfo->rightPos += 1;
5525

dengyihao's avatar
dengyihao 已提交
5526 5527 5528
      nrows += 1;
    } else if (*(int64_t*)pLeftVal < *(int64_t*)pRightVal) {
      pJoinInfo->leftPos += 1;
D
dapan1121 已提交
5529

dengyihao's avatar
dengyihao 已提交
5530 5531
      if (pJoinInfo->leftPos >= pJoinInfo->pLeft->info.rows) {
        continue;
5532
      }
dengyihao's avatar
dengyihao 已提交
5533 5534 5535 5536
    } else if (*(int64_t*)pLeftVal > *(int64_t*)pRightVal) {
      pJoinInfo->rightPos += 1;
      if (pJoinInfo->rightPos >= pJoinInfo->pRight->info.rows) {
        continue;
5537
      }
dengyihao's avatar
dengyihao 已提交
5538
    }
5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549

    // the pDataBlock are always the same one, no need to call this again
    pRes->info.rows = nrows;
    if (pRes->info.rows >= pOperator->resultInfo.threshold) {
      break;
    }
  }

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

H
Haojun Liao 已提交
5550
SOperatorInfo* createMergeJoinOperatorInfo(SOperatorInfo** pDownstream, int32_t numOfDownstream, SExprInfo* pExprInfo,
X
Xiaoyu Wang 已提交
5551 5552
                                           int32_t numOfCols, SSDataBlock* pResBlock, SNode* pOnCondition,
                                           SExecTaskInfo* pTaskInfo) {
5553
  SJoinOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SJoinOperatorInfo));
dengyihao's avatar
dengyihao 已提交
5554
  SOperatorInfo*     pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
5555 5556 5557 5558
  if (pOperator == NULL || pInfo == NULL) {
    goto _error;
  }

5559
  initResultSizeInfo(pOperator, 4096);
5560

X
Xiaoyu Wang 已提交
5561 5562
  pInfo->pRes = pResBlock;
  pOperator->name = "MergeJoinOperator";
5563
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_JOIN;
X
Xiaoyu Wang 已提交
5564 5565 5566
  pOperator->blocking = false;
  pOperator->status = OP_NOT_OPENED;
  pOperator->pExpr = pExprInfo;
5567
  pOperator->numOfExprs = numOfCols;
X
Xiaoyu Wang 已提交
5568
  pOperator->info = pInfo;
dengyihao's avatar
dengyihao 已提交
5569
  pOperator->pTaskInfo = pTaskInfo;
5570

5571 5572 5573 5574
  SOperatorNode* pNode = (SOperatorNode*)pOnCondition;
  setJoinColumnInfo(&pInfo->leftCol, (SColumnNode*)pNode->pLeft);
  setJoinColumnInfo(&pInfo->rightCol, (SColumnNode*)pNode->pRight);

L
Liu Jicong 已提交
5575
  pOperator->fpSet =
H
Haojun Liao 已提交
5576
      createOperatorFpSet(operatorDummyOpenFn, doMergeJoin, NULL, NULL, destroyMergeJoinOperator, NULL, NULL, NULL);
5577
  int32_t code = appendDownstream(pOperator, pDownstream, numOfDownstream);
5578 5579 5580 5581
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }

5582 5583
  return pOperator;

dengyihao's avatar
dengyihao 已提交
5584
_error:
5585 5586 5587 5588
  taosMemoryFree(pInfo);
  taosMemoryFree(pOperator);
  pTaskInfo->code = TSDB_CODE_OUT_OF_MEMORY;
  return NULL;
dengyihao's avatar
dengyihao 已提交
5589
}
5590 5591

void setJoinColumnInfo(SColumnInfo* pColumn, const SColumnNode* pColumnNode) {
X
Xiaoyu Wang 已提交
5592 5593 5594
  pColumn->slotId = pColumnNode->slotId;
  pColumn->type = pColumnNode->node.resType.type;
  pColumn->bytes = pColumnNode->node.resType.bytes;
5595
  pColumn->precision = pColumnNode->node.resType.precision;
X
Xiaoyu Wang 已提交
5596
  pColumn->scale = pColumnNode->node.resType.scale;
5597
}