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

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

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

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

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

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

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

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

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

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

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

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

#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 已提交
93 94 95
int32_t getMaximumIdleDurationSec() { return tsShellActivityTimer * 2; }

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

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

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

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

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

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

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

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

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

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

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

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

138
SOperatorFpSet createOperatorFpSet(__optr_open_fn_t openFn, __optr_fn_t nextFn, __optr_fn_t streamFn,
L
Liu Jicong 已提交
139 140
                                   __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) {
141 142 143 144 145 146 147 148 149 150 151 152 153 154
  SOperatorFpSet fpSet = {
      ._openFn = openFn,
      .getNextFn = nextFn,
      .getStreamResFn = streamFn,
      .cleanupFn = cleanup,
      .closeFn = closeFn,
      .encodeResultRow = encode,
      .decodeResultRow = decode,
      .getExplainFn = explain,
  };

  return fpSet;
}

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

157
static int32_t doCopyToSDataBlock(SExecTaskInfo* taskInfo, SSDataBlock* pBlock, SExprInfo* pExprInfo, SDiskbasedBuf* pBuf, SGroupResInfo* pGroupResInfo,
158
                                  int32_t* rowCellOffset, SqlFunctionCtx* pCtx, int32_t numOfExprs);
H
Haojun Liao 已提交
159

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

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

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

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

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

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

  int16_t offset = supporter->dataOffset;
L
Liu Jicong 已提交
184 185
  char*   in1 = getPosInResultPage(pRuntimeEnv->pQueryAttr, page1, pRow1->offset, offset);
  char*   in2 = getPosInResultPage(pRuntimeEnv->pQueryAttr, page2, pRow2->offset, offset);
186 187 188 189

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

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

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

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

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

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

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

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

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

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

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

  return true;
}

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

241 242 243 244 245 246 247 248 249 250 251
  // 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);
  }

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

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

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

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

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

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

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

    return existed;
  }

  return p1 != NULL;
}

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

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

  return pResultRow;
}

345 346 347 348 349 350 351
/**
 * the struct of key in hash table
 * +----------+---------------+
 * | group id |   key data    |
 * | 8 bytes  | actual length |
 * +----------+---------------+
 */
352 353 354
SResultRow* doSetResultOutBufByKey(SDiskbasedBuf* pResultBuf, SResultRowInfo* pResultRowInfo, char* pData,
                                   int16_t bytes, bool masterscan, uint64_t groupId, SExecTaskInfo* pTaskInfo,
                                   bool isIntervalQuery, SAggSupporter* pSup) {
355
  SET_RES_WINDOW_KEY(pSup->keyBuf, pData, bytes, groupId);
H
Haojun Liao 已提交
356

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

360 361
  SResultRow* pResult = NULL;

H
Haojun Liao 已提交
362 363
  // in case of repeat scan/reverse scan, no new time window added.
  if (isIntervalQuery) {
364 365
    if (masterscan && p1 != NULL) {  // the *p1 may be NULL in case of sliding+offset exists.
      pResult = getResultRowByPos(pResultBuf, p1);
H
Haojun Liao 已提交
366 367
    }
  } else {
dengyihao's avatar
dengyihao 已提交
368 369
    // In case of group by column query, the required SResultRow object must be existInCurrentResusltRowInfo in the
    // pResultRowInfo object.
H
Haojun Liao 已提交
370
    if (p1 != NULL) {
371
      pResult = getResultRowByPos(pResultBuf, p1);
H
Haojun Liao 已提交
372 373 374
    }
  }

L
Liu Jicong 已提交
375
  // 1. close current opened time window
376
  if (pResultRowInfo->cur.pageId != -1 && ((pResult == NULL) || (pResult->pageId != pResultRowInfo->cur.pageId &&
L
Liu Jicong 已提交
377
                                                                 pResult->offset != pResultRowInfo->cur.offset))) {
378 379 380 381 382 383 384 385 386 387 388
    // 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 已提交
389
    ASSERT(pSup->resultRowSize > 0);
390 391
    pResult = getNewResultRow_rv(pResultBuf, groupId, pSup->resultRowSize);
    initResultRow(pResult);
H
Haojun Liao 已提交
392

393 394
    // add a new result set for a new group
    SResultRowPosition pos = {.pageId = pResult->pageId, .offset = pResult->offset};
L
Liu Jicong 已提交
395 396
    taosHashPut(pSup->pResultRowHashTable, pSup->keyBuf, GET_RES_WINDOW_KEY_LEN(bytes), &pos,
                sizeof(SResultRowPosition));
H
Haojun Liao 已提交
397 398
  }

399 400 401 402 403
  // 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 已提交
404 405 406 407 408
  // 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 已提交
409
  return pResult;
H
Haojun Liao 已提交
410 411
}

412
// get the correct time window according to the handled timestamp
L
Liu Jicong 已提交
413
static STimeWindow getCurrentActiveTimeWindow(SResultRowInfo* pResultRowInfo, int64_t ts, STaskAttr* pQueryAttr) {
414
  STimeWindow w = {0};
H
Haojun Liao 已提交
415
#if 0
L
Liu Jicong 已提交
416 417
  if (pResultRowInfo->curPos == -1) {  // the first window, from the previous stored value
                                       //    getInitialStartTimeWindow(pQueryAttr, ts, &w);
418 419

    if (pQueryAttr->interval.intervalUnit == 'n' || pQueryAttr->interval.intervalUnit == 'y') {
L
Liu Jicong 已提交
420 421 422
      w.ekey =
          taosTimeAdd(w.skey, pQueryAttr->interval.interval, pQueryAttr->interval.intervalUnit, pQueryAttr->precision) -
          1;
423 424 425 426
    } else {
      w.ekey = w.skey + pQueryAttr->interval.interval - 1;
    }
  } else {
H
Haojun Liao 已提交
427
    w = pRow->win;
428 429 430 431 432 433 434 435 436
  }

  /*
   * 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 已提交
437
#endif
438 439 440 441 442

  return w;
}

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

L
Liu Jicong 已提交
448
  SFilePage* pData = NULL;
449 450 451 452 453 454

  // 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 已提交
455
    pData = getNewBufPage(pResultBuf, tid, &pageId);
456
    pData->num = sizeof(SFilePage);
457 458
  } else {
    SPageInfo* pi = getLastPageInfo(list);
459
    pData = getBufPage(pResultBuf, getPageId(pi));
460
    pageId = getPageId(pi);
461

462
    if (pData->num + size > getBufPageSize(pResultBuf)) {
463
      // release current page first, and prepare the next one
464
      releaseBufPageInfo(pResultBuf, pi);
465

H
Haojun Liao 已提交
466
      pData = getNewBufPage(pResultBuf, tid, &pageId);
467
      if (pData != NULL) {
468
        pData->num = sizeof(SFilePage);
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
      }
    }
  }

  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 已提交
489 490 491
static bool chkWindowOutputBufByKey(STaskRuntimeEnv* pRuntimeEnv, SResultRowInfo* pResultRowInfo, STimeWindow* win,
                                    bool masterscan, SResultRow** pResult, int64_t groupId, SqlFunctionCtx* pCtx,
                                    int32_t numOfOutput, int32_t* rowCellInfoOffset) {
492
  assert(win->skey <= win->ekey);
L
Liu Jicong 已提交
493
  return chkResultRowFromKey(pRuntimeEnv, pResultRowInfo, (char*)&win->skey, TSDB_KEYSIZE, masterscan, groupId);
494 495
}

dengyihao's avatar
dengyihao 已提交
496 497
static void doUpdateResultRowIndex(SResultRowInfo* pResultRowInfo, TSKEY lastKey, bool ascQuery,
                                   bool timeWindowInterpo) {
498
  int64_t skey = TSKEY_INITIAL_VAL;
H
Haojun Liao 已提交
499
#if 0
500 501
  int32_t i = 0;
  for (i = pResultRowInfo->size - 1; i >= 0; --i) {
L
Liu Jicong 已提交
502
    SResultRow* pResult = pResultRowInfo->pResult[i];
503 504 505 506 507 508
    if (pResult->closed) {
      break;
    }

    // new closed result rows
    if (timeWindowInterpo) {
L
Liu Jicong 已提交
509 510 511
      if (pResult->endInterp &&
          ((pResult->win.skey <= lastKey && ascQuery) || (pResult->win.skey >= lastKey && !ascQuery))) {
        if (i > 0) {  // the first time window, the startInterp is false.
512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530
          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 已提交
531
      //      assert(pResultRowInfo->current == NULL);
532 533 534 535 536 537 538
      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 已提交
539
      SResultRow* pResult = pResultRowInfo->pResult[i];
540 541 542 543 544 545 546 547 548 549 550
      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 已提交
551
#endif
552
}
553
//
dengyihao's avatar
dengyihao 已提交
554
// static void updateResultRowInfoActiveIndex(SResultRowInfo* pResultRowInfo, const STimeWindow* pWin, TSKEY lastKey,
555 556 557 558 559 560 561 562 563
//                                           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);
//  }
//}
564

565
//  query_range_start, query_range_end, window_duration, window_start, window_end
566
void initExecTimeWindowInfo(SColumnInfoData* pColData, STimeWindow* pQueryWindow) {
567 568 569
  pColData->info.type = TSDB_DATA_TYPE_TIMESTAMP;
  pColData->info.bytes = sizeof(int64_t);

570
  colInfoDataEnsureCapacity(pColData, 0, 5);
571 572 573 574 575 576 577 578 579
  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);
}

580
void doApplyFunctions(SExecTaskInfo* taskInfo, SqlFunctionCtx* pCtx, STimeWindow* pWin, SColumnInfoData* pTimeWindowData, int32_t offset,
dengyihao's avatar
dengyihao 已提交
581
                      int32_t forwardStep, TSKEY* tsCol, int32_t numOfTotal, int32_t numOfOutput, int32_t order) {
582
  for (int32_t k = 0; k < numOfOutput; ++k) {
H
Haojun Liao 已提交
583
    // keep it temporarily
dengyihao's avatar
dengyihao 已提交
584 585
    bool    hasAgg = pCtx[k].input.colDataAggIsSet;
    int32_t numOfRows = pCtx[k].input.numOfRows;
H
Haojun Liao 已提交
586
    int32_t startOffset = pCtx[k].input.startRowIndex;
587

H
Haojun Liao 已提交
588
    int32_t pos = (order == TSDB_ORDER_ASC) ? offset : offset - (forwardStep - 1);
589 590
    pCtx[k].input.startRowIndex = pos;
    pCtx[k].input.numOfRows = forwardStep;
591 592

    if (tsCol != NULL) {
H
Haojun Liao 已提交
593
      pCtx[k].ptsList = tsCol;
594 595 596 597
    }

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

602 603
    if (fmIsWindowPseudoColumnFunc(pCtx[k].functionId)) {
      SResultRowEntryInfo* pEntryInfo = GET_RES_INFO(&pCtx[k]);
dengyihao's avatar
dengyihao 已提交
604
      char*                p = GET_ROWCELL_INTERBUF(pEntryInfo);
605

606
      SColumnInfoData idata = {0};
dengyihao's avatar
dengyihao 已提交
607
      idata.info.type = TSDB_DATA_TYPE_BIGINT;
608
      idata.info.bytes = tDataTypes[TSDB_DATA_TYPE_BIGINT].bytes;
dengyihao's avatar
dengyihao 已提交
609
      idata.pData = p;
610 611 612 613

      SScalarParam out = {.columnData = &idata};
      SScalarParam tw = {.numOfRows = 5, .columnData = pTimeWindowData};
      pCtx[k].sfp.process(&tw, 1, &out);
614 615 616
      pEntryInfo->numOfRes = 1;
      continue;
    }
617
    int32_t code = TSDB_CODE_SUCCESS;
618
    if (functionNeedToExecute(&pCtx[k]) && pCtx[k].fpSet.process != NULL) {
619 620 621 622 623 624
      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);
      }
625 626 627
    }

    // restore it
628 629 630
    pCtx[k].input.colDataAggIsSet = hasAgg;
    pCtx[k].input.startRowIndex = startOffset;
    pCtx[k].input.numOfRows = numOfRows;
631 632 633
  }
}

L
Liu Jicong 已提交
634
static FORCE_INLINE TSKEY reviseWindowEkey(STaskAttr* pQueryAttr, STimeWindow* pWindow) {
dengyihao's avatar
dengyihao 已提交
635
  TSKEY   ekey = -1;
636 637
  int32_t order = TSDB_ORDER_ASC;
  if (order == TSDB_ORDER_ASC) {
638 639 640 641 642 643 644 645 646 647 648 649 650 651
    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 已提交
652
static int32_t doSetInputDataBlock(SOperatorInfo* pOperator, SqlFunctionCtx* pCtx, SSDataBlock* pBlock, int32_t order,
653
                                   int32_t scanFlag, bool createDummyCol);
654

dengyihao's avatar
dengyihao 已提交
655 656
static void doSetInputDataBlockInfo(SOperatorInfo* pOperator, SqlFunctionCtx* pCtx, SSDataBlock* pBlock,
                                    int32_t order) {
657
  for (int32_t i = 0; i < pOperator->numOfExprs; ++i) {
658
    pCtx[i].order = order;
659
    pCtx[i].input.numOfRows = pBlock->info.rows;
660
    setBlockStatisInfo(&pCtx[i], &pOperator->pExpr[i], pBlock);
661 662 663
  }
}

664
void setInputDataBlock(SOperatorInfo* pOperator, SqlFunctionCtx* pCtx, SSDataBlock* pBlock, int32_t order, int32_t scanFlag,
dengyihao's avatar
dengyihao 已提交
665
                       bool createDummyCol) {
666
  if (pBlock->pBlockAgg != NULL) {
H
Haojun Liao 已提交
667
    doSetInputDataBlockInfo(pOperator, pCtx, pBlock, order);
668
  } else {
669
    doSetInputDataBlock(pOperator, pCtx, pBlock, order, scanFlag, createDummyCol);
H
Haojun Liao 已提交
670
  }
671 672
}

L
Liu Jicong 已提交
673 674
static int32_t doCreateConstantValColumnInfo(SInputColumnInfoData* pInput, SFunctParam* pFuncParam, int32_t paramIndex,
                                             int32_t numOfRows) {
675 676 677 678 679 680 681 682
  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)
683 684
    pColInfo->info.type = pFuncParam->param.nType;
    pColInfo->info.bytes = pFuncParam->param.nLen;
685 686

    pInput->pData[paramIndex] = pColInfo;
687 688
  } else {
    pColInfo = pInput->pData[paramIndex];
689 690
  }

691
  colInfoDataEnsureCapacity(pColInfo, 0, numOfRows);
692

693
  int8_t type = pFuncParam->param.nType;
694 695
  if (type == TSDB_DATA_TYPE_BIGINT || type == TSDB_DATA_TYPE_UBIGINT) {
    int64_t v = pFuncParam->param.i;
dengyihao's avatar
dengyihao 已提交
696
    for (int32_t i = 0; i < numOfRows; ++i) {
697 698 699 700
      colDataAppendInt64(pColInfo, i, &v);
    }
  } else if (type == TSDB_DATA_TYPE_DOUBLE) {
    double v = pFuncParam->param.d;
dengyihao's avatar
dengyihao 已提交
701
    for (int32_t i = 0; i < numOfRows; ++i) {
702 703
      colDataAppendDouble(pColInfo, i, &v);
    }
704
  } else if (type == TSDB_DATA_TYPE_VARCHAR) {
L
Liu Jicong 已提交
705
    char* tmp = taosMemoryMalloc(pFuncParam->param.nLen + VARSTR_HEADER_SIZE);
706
    STR_WITH_SIZE_TO_VARSTR(tmp, pFuncParam->param.pz, pFuncParam->param.nLen);
L
Liu Jicong 已提交
707
    for (int32_t i = 0; i < numOfRows; ++i) {
708 709
      colDataAppend(pColInfo, i, tmp, false);
    }
710 711 712 713 714
  }

  return TSDB_CODE_SUCCESS;
}

dengyihao's avatar
dengyihao 已提交
715
static int32_t doSetInputDataBlock(SOperatorInfo* pOperator, SqlFunctionCtx* pCtx, SSDataBlock* pBlock, int32_t order,
716
    int32_t scanFlag, bool createDummyCol) {
717 718
  int32_t code = TSDB_CODE_SUCCESS;

719
  for (int32_t i = 0; i < pOperator->numOfExprs; ++i) {
L
Liu Jicong 已提交
720
    pCtx[i].order = order;
721 722
    pCtx[i].input.numOfRows = pBlock->info.rows;

L
Liu Jicong 已提交
723
    pCtx[i].pSrcBlock = pBlock;
724
    pCtx[i].scanFlag  = scanFlag;
H
Haojun Liao 已提交
725

726
    SInputColumnInfoData* pInput = &pCtx[i].input;
727
    pInput->uid = pBlock->info.uid;
C
Cary Xu 已提交
728
    pInput->colDataAggIsSet = false;
729

730 731
    SExprInfo* pOneExpr = &pOperator->pExpr[i];
    for (int32_t j = 0; j < pOneExpr->base.numOfParams; ++j) {
dengyihao's avatar
dengyihao 已提交
732
      SFunctParam* pFuncParam = &pOneExpr->base.pParam[j];
G
Ganlin Zhao 已提交
733 734
      if (pFuncParam->type == FUNC_PARAM_TYPE_COLUMN) {
        int32_t slotId = pFuncParam->pCol->slotId;
dengyihao's avatar
dengyihao 已提交
735
        pInput->pData[j] = taosArrayGet(pBlock->pDataBlock, slotId);
736 737 738
        pInput->totalRows = pBlock->info.rows;
        pInput->numOfRows = pBlock->info.rows;
        pInput->startRowIndex = 0;
739

740
        // NOTE: the last parameter is the primary timestamp column
741 742 743
        if (fmIsTimelineFunc(pCtx[i].functionId) && (j == pOneExpr->base.numOfParams - 1)) {
          pInput->pPTS = pInput->pData[j];
        }
744 745
        ASSERT(pInput->pData[j] != NULL);
      } else if (pFuncParam->type == FUNC_PARAM_TYPE_VALUE) {
746 747 748
        // 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) {
749 750 751 752
          pInput->totalRows = pBlock->info.rows;
          pInput->numOfRows = pBlock->info.rows;
          pInput->startRowIndex = 0;

753
          code = doCreateConstantValColumnInfo(pInput, pFuncParam, j, pBlock->info.rows);
754 755 756
          if (code != TSDB_CODE_SUCCESS) {
            return code;
          }
757
        }
G
Ganlin Zhao 已提交
758 759
      }
    }
H
Haojun Liao 已提交
760

H
Haojun Liao 已提交
761
    //    setBlockStatisInfo(&pCtx[i], pBlock, pOperator->pExpr[i].base.pColumns);
H
Haojun Liao 已提交
762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799
    //      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);
    //        }
    //      }
  }
800 801

  return code;
H
Haojun Liao 已提交
802 803
}

804
static int32_t doAggregateImpl(SOperatorInfo* pOperator, TSKEY startTs, SqlFunctionCtx* pCtx) {
805
  for (int32_t k = 0; k < pOperator->numOfExprs; ++k) {
H
Haojun Liao 已提交
806
    if (functionNeedToExecute(&pCtx[k])) {
807 808
      // todo add a dummy funtion to avoid process check
      if (pCtx[k].fpSet.process != NULL) {
809 810
        int32_t code = pCtx[k].fpSet.process(&pCtx[k]);
        if (code != TSDB_CODE_SUCCESS) {
811 812
          qError("%s aggregate function error happens, code: %s", GET_TASKID(pOperator->pTaskInfo), tstrerror(code));
          return code;
813
        }
814
      }
815 816
    }
  }
817 818

  return TSDB_CODE_SUCCESS;
819 820
}

H
Haojun Liao 已提交
821
static void setPseudoOutputColInfo(SSDataBlock* pResult, SqlFunctionCtx* pCtx, SArray* pPseudoList) {
dengyihao's avatar
dengyihao 已提交
822
  size_t num = (pPseudoList != NULL) ? taosArrayGetSize(pPseudoList) : 0;
H
Haojun Liao 已提交
823 824 825 826 827
  for (int32_t i = 0; i < num; ++i) {
    pCtx[i].pOutput = taosArrayGet(pResult->pDataBlock, i);
  }
}

828
int32_t projectApplyFunctions(SExprInfo* pExpr, SSDataBlock* pResult, SSDataBlock* pSrcBlock, SqlFunctionCtx* pCtx,
X
Xiaoyu Wang 已提交
829
                              int32_t numOfOutput, SArray* pPseudoList) {
H
Haojun Liao 已提交
830
  setPseudoOutputColInfo(pResult, pCtx, pPseudoList);
H
Haojun Liao 已提交
831
  pResult->info.groupId = pSrcBlock->info.groupId;
H
Haojun Liao 已提交
832

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

837 838
  int32_t numOfRows = 0;

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

L
Liu Jicong 已提交
843
    if (pExpr[k].pExpr->nodeType == QUERY_NODE_COLUMN) {  // it is a project query
844
      SColumnInfoData* pColInfoData = taosArrayGet(pResult->pDataBlock, outputSlotId);
845
      if (pResult->info.rows > 0 && !createNewColModel) {
X
Xiaoyu Wang 已提交
846 847
        colDataMergeCol(pColInfoData, pResult->info.rows, &pResult->info.capacity, pfCtx->input.pData[0],
                        pfCtx->input.numOfRows);
848 849 850
      } else {
        colDataAssign(pColInfoData, pfCtx->input.pData[0], pfCtx->input.numOfRows);
      }
851

852
      numOfRows = pfCtx->input.numOfRows;
853
    } else if (pExpr[k].pExpr->nodeType == QUERY_NODE_VALUE) {
854
      SColumnInfoData* pColInfoData = taosArrayGet(pResult->pDataBlock, outputSlotId);
855

dengyihao's avatar
dengyihao 已提交
856
      int32_t offset = createNewColModel ? 0 : pResult->info.rows;
857
      for (int32_t i = 0; i < pSrcBlock->info.rows; ++i) {
dengyihao's avatar
dengyihao 已提交
858 859 860
        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);
861
      }
862 863

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

868
      SColumnInfoData* pResColData = taosArrayGet(pResult->pDataBlock, outputSlotId);
869
      SColumnInfoData  idata = {.info = pResColData->info, .hasNull = true};
870

871
      SScalarParam dest = {.columnData = &idata};
872 873
      scalarCalculate(pExpr[k].pExpr->_optrRoot.pRootNode, pBlockList, &dest);

dengyihao's avatar
dengyihao 已提交
874
      int32_t startOffset = createNewColModel ? 0 : pResult->info.rows;
875
      colInfoDataEnsureCapacity(pResColData, startOffset, pResult->info.capacity);
876
      colDataMergeCol(pResColData, startOffset, &pResult->info.capacity, &idata, dest.numOfRows);
877 878

      numOfRows = dest.numOfRows;
879 880
      taosArrayDestroy(pBlockList);
    } else if (pExpr[k].pExpr->nodeType == QUERY_NODE_FUNCTION) {
881
      ASSERT(!fmIsAggFunc(pfCtx->functionId));
882

883 884
      // _rowts/_c0, not tbname column
      if (fmIsPseudoColumnFunc(pfCtx->functionId) && (!fmIsScanPseudoColumnFunc(pfCtx->functionId))) {
H
Haojun Liao 已提交
885
        // do nothing
886
      } else if (fmIsNonstandardSQLFunc(pfCtx->functionId)) {
dengyihao's avatar
dengyihao 已提交
887
        SResultRowEntryInfo* pResInfo = GET_RES_INFO(&pCtx[k]);
888
        pfCtx->fpSet.init(&pCtx[k], pResInfo);
889

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

893
        // set the timestamp(_rowts) output buffer
894 895
        if (taosArrayGetSize(pPseudoList) > 0) {
          int32_t* outputColIndex = taosArrayGet(pPseudoList, 0);
896
          pfCtx->pTsOutput = (SColumnInfoData*)pCtx[*outputColIndex].pOutput;
897
        }
H
Haojun Liao 已提交
898

899
        numOfRows = pfCtx->fpSet.process(pfCtx);
H
Haojun Liao 已提交
900 901 902
      } else {
        SArray* pBlockList = taosArrayInit(4, POINTER_BYTES);
        taosArrayPush(pBlockList, &pSrcBlock);
G
Ganlin Zhao 已提交
903

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

907
        SScalarParam dest = {.columnData = &idata};
X
Xiaoyu Wang 已提交
908
        int32_t      code = scalarCalculate((SNode*)pExpr[k].pExpr->_function.pFunctNode, pBlockList, &dest);
909 910 911 912
        if (code != TSDB_CODE_SUCCESS) {
          taosArrayDestroy(pBlockList);
          return code;
        }
913

dengyihao's avatar
dengyihao 已提交
914
        int32_t startOffset = createNewColModel ? 0 : pResult->info.rows;
915
        colInfoDataEnsureCapacity(pResColData, startOffset, pResult->info.capacity);
916
        colDataMergeCol(pResColData, startOffset, &pResult->info.capacity, &idata, dest.numOfRows);
917 918

        numOfRows = dest.numOfRows;
H
Haojun Liao 已提交
919 920
        taosArrayDestroy(pBlockList);
      }
921
    } else {
922
      ASSERT(0);
923 924
    }
  }
925

926 927 928
  if (!createNewColModel) {
    pResult->info.rows += numOfRows;
  }
929 930

  return TSDB_CODE_SUCCESS;
931 932
}

933 934 935
static void setResultRowKey(SResultRow* pResultRow, char* pData, int16_t type) {
  if (IS_VAR_DATA_TYPE(type)) {
    // todo disable this
936

937 938 939 940 941 942 943 944 945
    //    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);
946

947 948
    pResultRow->win.skey = v;
    pResultRow->win.ekey = v;
949 950 951
  }
}

952 953 954 955 956
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;
957

958 959 960
  SResultRow* pResultRow =
      doSetResultOutBufByKey(pBuf, pResultRowInfo, (char*)pData, bytes, true, groupId, pTaskInfo, false, pAggSup);
  assert(pResultRow != NULL);
961

962
  setResultRowKey(pResultRow, pData, type);
963
  setResultRowInitCtx(pResultRow, pCtx, numOfCols, binfo->rowCellInfoOffset);
964
  return TSDB_CODE_SUCCESS;
965 966
}

967 968
static bool functionNeedToExecute(SqlFunctionCtx* pCtx) {
  struct SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
969

970 971 972 973 974
  // in case of timestamp column, always generated results.
  int32_t functionId = pCtx->functionId;
  if (functionId == -1) {
    return false;
  }
975

976 977
  if (pCtx->scanFlag == REPEAT_SCAN) {
    return fmIsRepeatScanFunc(pCtx->functionId);
978 979
  }

980 981
  if (isRowEntryCompleted(pResInfo)) {
    return false;
982 983
  }

984 985 986 987 988 989 990 991
//  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;
//  }
992

993 994 995 996 997
  // 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;
  //  }
998 999 1000 1001

  return true;
}

1002 1003 1004 1005 1006 1007 1008
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;
    }
1009

1010 1011 1012
    // Set the correct column info (data type and bytes)
    pInput->pData[paramIndex]->info.type = type;
    pInput->pData[paramIndex]->info.bytes = tDataTypes[type].bytes;
1013
  }
H
Haojun Liao 已提交
1014

1015 1016 1017 1018 1019 1020
  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;
1021 1022
    }
  } else {
1023
    da = pInput->pColumnDataAgg[paramIndex];
1024 1025
  }

1026
  ASSERT(!IS_VAR_DATA_TYPE(type));
1027

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

1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046
    *(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
1047
  } else {
1048
    ASSERT(0);
1049 1050
  }

1051 1052
  return TSDB_CODE_SUCCESS;
}
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063

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;

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

1067 1068
      if (pFuncParam->type == FUNC_PARAM_TYPE_COLUMN) {
        int32_t slotId = pFuncParam->pCol->slotId;
1069 1070 1071 1072
        pInput->pColumnDataAgg[j] = pBlock->pBlockAgg[slotId];
        if (pInput->pColumnDataAgg[j] == NULL) {
          pInput->colDataAggIsSet = false;
        }
1073 1074 1075 1076

        // 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);
1077 1078
      } else if (pFuncParam->type == FUNC_PARAM_TYPE_VALUE) {
        doCreateConstantValColumnAggInfo(pInput, pFuncParam, pFuncParam->param.nType, j, pBlock->info.rows);
1079 1080
      }
    }
1081
  } else {
1082
    pInput->colDataAggIsSet = false;
1083 1084 1085
  }

  // set the statistics data for primary time stamp column
1086 1087 1088 1089 1090
  //  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;
  //  }
1091 1092 1093
}

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

H
Haojun Liao 已提交
1097
  SqlFunctionCtx*  p = NULL;
1098 1099
  SqlFunctionCtx** pValCtx = taosMemoryCalloc(numOfOutput, POINTER_BYTES);
  if (pValCtx == NULL) {
1100 1101 1102 1103
    return TSDB_CODE_QRY_OUT_OF_MEMORY;
  }

  for (int32_t i = 0; i < numOfOutput; ++i) {
1104 1105
    if (strcmp(pCtx[i].pExpr->pExpr->_function.functionName, "_select_value") == 0) {
      pValCtx[num++] = &pCtx[i];
1106
    } else if (fmIsAggFunc(pCtx[i].functionId)) {
1107
      p = &pCtx[i];
1108
    }
1109 1110 1111 1112 1113 1114 1115 1116 1117 1118
//    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
//    }
1119
  }
1120

1121
  if (p != NULL) {
1122
    p->subsidiaries.pCtx = pValCtx;
1123
    p->subsidiaries.num = num;
1124
  } else {
1125
    taosMemoryFreeClear(pValCtx);
1126 1127 1128 1129 1130
  }

  return TSDB_CODE_SUCCESS;
}

1131
SqlFunctionCtx* createSqlFunctionCtx(SExprInfo* pExprInfo, int32_t numOfOutput, int32_t** rowCellInfoOffset) {
L
Liu Jicong 已提交
1132
  SqlFunctionCtx* pFuncCtx = (SqlFunctionCtx*)taosMemoryCalloc(numOfOutput, sizeof(SqlFunctionCtx));
H
Haojun Liao 已提交
1133 1134 1135 1136
  if (pFuncCtx == NULL) {
    return NULL;
  }

wafwerar's avatar
wafwerar 已提交
1137
  *rowCellInfoOffset = taosMemoryCalloc(numOfOutput, sizeof(int32_t));
H
Haojun Liao 已提交
1138
  if (*rowCellInfoOffset == 0) {
wafwerar's avatar
wafwerar 已提交
1139
    taosMemoryFreeClear(pFuncCtx);
H
Haojun Liao 已提交
1140 1141 1142 1143
    return NULL;
  }

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

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

1149
    pCtx->functionId = -1;
1150
    pCtx->curBufPage = -1;
L
Liu Jicong 已提交
1151
    pCtx->pExpr = pExpr;
1152

H
Haojun Liao 已提交
1153
    if (pExpr->pExpr->nodeType == QUERY_NODE_FUNCTION) {
H
Haojun Liao 已提交
1154
      SFuncExecEnv env = {0};
H
Haojun Liao 已提交
1155 1156
      pCtx->functionId = pExpr->pExpr->_function.pFunctNode->funcId;

H
Haojun Liao 已提交
1157
      if (fmIsAggFunc(pCtx->functionId) || fmIsNonstandardSQLFunc(pCtx->functionId)) {
1158 1159 1160 1161
        bool isUdaf = fmIsUserDefinedFunc(pCtx->functionId);
        if (!isUdaf) {
          fmGetFuncExecFuncs(pCtx->functionId, &pCtx->fpSet);
        } else {
1162
          char* udfName = pExpr->pExpr->_function.pFunctNode->functionName;
1163 1164 1165
          strncpy(pCtx->udfName, udfName, strlen(udfName));
          fmGetUdafExecFuncs(pCtx->functionId, &pCtx->fpSet);
        }
1166 1167 1168
        pCtx->fpSet.getEnv(pExpr->pExpr->_function.pFunctNode, &env);
      } else {
        fmGetScalarFuncExecFuncs(pCtx->functionId, &pCtx->sfp);
1169 1170 1171
        if (pCtx->sfp.getEnv != NULL) {
          pCtx->sfp.getEnv(pExpr->pExpr->_function.pFunctNode, &env);
        }
1172
      }
H
Haojun Liao 已提交
1173
      pCtx->resDataInfo.interBufSize = env.calcMemSize;
1174 1175
    } else if (pExpr->pExpr->nodeType == QUERY_NODE_COLUMN || pExpr->pExpr->nodeType == QUERY_NODE_OPERATOR ||
               pExpr->pExpr->nodeType == QUERY_NODE_VALUE) {
H
Haojun Liao 已提交
1176
      // for simple column, the result buffer needs to hold at least one element.
1177
      pCtx->resDataInfo.interBufSize = pFunct->resSchema.bytes;
H
Haojun Liao 已提交
1178
    }
H
Haojun Liao 已提交
1179

H
Haojun Liao 已提交
1180
    pCtx->input.numOfInputCols = pFunct->numOfParams;
wafwerar's avatar
wafwerar 已提交
1181 1182
    pCtx->input.pData = taosMemoryCalloc(pFunct->numOfParams, POINTER_BYTES);
    pCtx->input.pColumnDataAgg = taosMemoryCalloc(pFunct->numOfParams, POINTER_BYTES);
H
Haojun Liao 已提交
1183

1184
    pCtx->pTsOutput = NULL;
L
Liu Jicong 已提交
1185
    pCtx->resDataInfo.bytes = pFunct->resSchema.bytes;
1186
    pCtx->resDataInfo.type = pFunct->resSchema.type;
L
Liu Jicong 已提交
1187
    pCtx->order = TSDB_ORDER_ASC;
1188
    pCtx->start.key = INT64_MIN;
L
Liu Jicong 已提交
1189
    pCtx->end.key = INT64_MIN;
1190
    pCtx->numOfParams = pExpr->base.numOfParams;
H
Haojun Liao 已提交
1191

1192
    pCtx->param = pFunct->pParam;
dengyihao's avatar
dengyihao 已提交
1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226
    //    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 已提交
1227 1228
  }

L
Liu Jicong 已提交
1229 1230 1231
  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 已提交
1232
  }
H
Haojun Liao 已提交
1233

1234
  setSelectValueColumnInfo(pFuncCtx, numOfOutput);
H
Haojun Liao 已提交
1235 1236 1237
  return pFuncCtx;
}

1238
static void* destroySqlFunctionCtx(SqlFunctionCtx* pCtx, int32_t numOfOutput) {
1239 1240 1241 1242 1243 1244
  if (pCtx == NULL) {
    return NULL;
  }

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

    taosVariantDestroy(&pCtx[i].tag);
1249
    taosMemoryFreeClear(pCtx[i].subsidiaries.pCtx);
H
Haojun Liao 已提交
1250 1251
    taosMemoryFree(pCtx[i].input.pData);
    taosMemoryFree(pCtx[i].input.pColumnDataAgg);
1252 1253
  }

wafwerar's avatar
wafwerar 已提交
1254
  taosMemoryFreeClear(pCtx);
1255 1256 1257
  return NULL;
}

L
Liu Jicong 已提交
1258
bool isTaskKilled(SExecTaskInfo* pTaskInfo) {
1259 1260
  // query has been executed more than tsShellActivityTimer, and the retrieve has not arrived
  // abort current query execution.
L
Liu Jicong 已提交
1261 1262
  if (pTaskInfo->owner != 0 &&
      ((taosGetTimestampSec() - pTaskInfo->cost.start / 1000) > 10 * getMaximumIdleDurationSec())
1263 1264
      /*(!needBuildResAfterQueryComplete(pTaskInfo))*/) {
    assert(pTaskInfo->cost.start != 0);
L
Liu Jicong 已提交
1265 1266 1267
    //    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;
1268 1269 1270 1271 1272
  }

  return false;
}

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

L
Liu Jicong 已提交
1275
static bool isCachedLastQuery(STaskAttr* pQueryAttr) {
1276 1277 1278 1279 1280 1281 1282 1283 1284
  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;
  }

1285 1286
  int32_t order = TSDB_ORDER_ASC;
  if (order != TSDB_ORDER_DESC || !TSWINDOW_IS_EQUAL(pQueryAttr->window, TSWINDOW_DESC_INITIALIZER)) {
1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305
    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 已提交
1306
// todo refactor : return window
1307
void getAlignQueryTimeWindow(SInterval* pInterval, int32_t precision, int64_t key, STimeWindow* win) {
H
Haojun Liao 已提交
1308
  win->skey = taosTimeTruncate(key, pInterval, precision);
1309 1310

  /*
H
Haojun Liao 已提交
1311
   * if the realSkey > INT64_MAX - pInterval->interval, the query duration between
1312 1313
   * realSkey and realEkey must be less than one interval.Therefore, no need to adjust the query ranges.
   */
1314 1315
  win->ekey = taosTimeAdd(win->skey, pInterval->interval, pInterval->intervalUnit, precision) - 1;
  if (win->ekey < win->skey) {
1316 1317 1318 1319
    win->ekey = INT64_MAX;
  }
}

L
Liu Jicong 已提交
1320
static int32_t updateBlockLoadStatus(STaskAttr* pQuery, int32_t status) {
1321 1322 1323
  bool hasFirstLastFunc = false;
  bool hasOtherFunc = false;

1324
  if (status == BLK_DATA_DATA_LOAD || status == BLK_DATA_FILTEROUT) {
1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342
    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;
    }
  }

1343
  if (hasFirstLastFunc && status == BLK_DATA_NOT_LOAD) {
L
Liu Jicong 已提交
1344
    if (!hasOtherFunc) {
1345
      return BLK_DATA_FILTEROUT;
1346
    } else {
1347
      return BLK_DATA_DATA_LOAD;
1348 1349 1350 1351 1352 1353
    }
  }

  return status;
}

L
Liu Jicong 已提交
1354 1355
// static void updateDataCheckOrder(SQInfo *pQInfo, SQueryTableReq* pQueryMsg, bool stableQuery) {
//   STaskAttr* pQueryAttr = pQInfo->runtimeEnv.pQueryAttr;
H
Haojun Liao 已提交
1356
//
L
Liu Jicong 已提交
1357 1358 1359 1360
//   // 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 已提交
1361
//
L
Liu Jicong 已提交
1362 1363 1364 1365 1366
//   // 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 已提交
1367
//
L
Liu Jicong 已提交
1368 1369
//     pQueryAttr->order.order = TSDB_ORDER_ASC;
//     if (pQueryAttr->window.skey > pQueryAttr->window.ekey) {
wafwerar's avatar
wafwerar 已提交
1370
//       TSWAP(pQueryAttr->window.skey, pQueryAttr->window.ekey);
L
Liu Jicong 已提交
1371
//     }
H
Haojun Liao 已提交
1372
//
L
Liu Jicong 已提交
1373 1374 1375
//     pQueryAttr->needReverseScan = false;
//     return;
//   }
H
Haojun Liao 已提交
1376
//
L
Liu Jicong 已提交
1377 1378 1379
//   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 已提交
1380
//       TSWAP(pQueryAttr->window.skey, pQueryAttr->window.ekey);
L
Liu Jicong 已提交
1381
//     }
H
Haojun Liao 已提交
1382
//
L
Liu Jicong 已提交
1383 1384 1385 1386
//     pQueryAttr->needReverseScan = false;
//     doUpdateLastKey(pQueryAttr);
//     return;
//   }
H
Haojun Liao 已提交
1387
//
L
Liu Jicong 已提交
1388 1389 1390 1391 1392 1393
//   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 已提交
1394
//
L
Liu Jicong 已提交
1395 1396 1397
//     pQueryAttr->order.order = TSDB_ORDER_ASC;
//     return;
//   }
H
Haojun Liao 已提交
1398
//
L
Liu Jicong 已提交
1399 1400 1401 1402
//   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 已提交
1403 1404
////               pQueryAttr->window.ekey, pQueryAttr->window.ekey, pQueryAttr->window.skey);
//
wafwerar's avatar
wafwerar 已提交
1405
//        TSWAP(pQueryAttr->window.skey, pQueryAttr->window.ekey);
H
Haojun Liao 已提交
1406 1407 1408 1409 1410 1411 1412 1413 1414 1415
//        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 已提交
1416
//        TSWAP(pQueryAttr->window.skey, pQueryAttr->window.ekey);
H
Haojun Liao 已提交
1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428
//        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 已提交
1429 1430
////                 pQueryAttr->window.skey, pQueryAttr->window.ekey, pQueryAttr->window.ekey,
/// pQueryAttr->window.skey);
H
Haojun Liao 已提交
1431
//
wafwerar's avatar
wafwerar 已提交
1432
//          TSWAP(pQueryAttr->window.skey, pQueryAttr->window.ekey);
H
Haojun Liao 已提交
1433 1434 1435 1436 1437 1438 1439 1440
//          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 已提交
1441 1442
////                 pQueryAttr->window.skey, pQueryAttr->window.ekey, pQueryAttr->window.ekey,
/// pQueryAttr->window.skey);
H
Haojun Liao 已提交
1443
//
wafwerar's avatar
wafwerar 已提交
1444
//          TSWAP(pQueryAttr->window.skey, pQueryAttr->window.ekey);
H
Haojun Liao 已提交
1445 1446 1447 1448 1449 1450 1451 1452 1453
//          doUpdateLastKey(pQueryAttr);
//        }
//
//        pQueryAttr->order.order = TSDB_ORDER_DESC;
//        pQueryAttr->needReverseScan = false;
//      }
//    }
//  }
//}
1454

H
Haojun Liao 已提交
1455 1456
static void getIntermediateBufInfo(STaskRuntimeEnv* pRuntimeEnv, int32_t* ps, int32_t* rowsize) {
  STaskAttr* pQueryAttr = pRuntimeEnv->pQueryAttr;
L
Liu Jicong 已提交
1457
  int32_t    MIN_ROWS_PER_PAGE = 4;
1458

L
Liu Jicong 已提交
1459 1460
  *rowsize = (int32_t)(pQueryAttr->resultRowSize *
                       getRowNumForMultioutput(pQueryAttr, pQueryAttr->topBotQuery, pQueryAttr->stableQuery));
1461 1462 1463 1464
  int32_t overhead = sizeof(SFilePage);

  // one page contains at least two rows
  *ps = DEFAULT_INTERN_BUF_PAGE_SIZE;
L
Liu Jicong 已提交
1465
  while (((*rowsize) * MIN_ROWS_PER_PAGE) > (*ps) - overhead) {
1466 1467 1468 1469
    *ps = ((*ps) << 1u);
  }
}

L
Liu Jicong 已提交
1470 1471 1472
// static FORCE_INLINE bool doFilterByBlockStatistics(STaskRuntimeEnv* pRuntimeEnv, SDataStatis *pDataStatis,
// SqlFunctionCtx *pCtx, int32_t numOfRows) {
//   STaskAttr* pQueryAttr = pRuntimeEnv->pQueryAttr;
1473
//
L
Liu Jicong 已提交
1474 1475 1476
//   if (pDataStatis == NULL || pQueryAttr->pFilters == NULL) {
//     return true;
//   }
1477
//
L
Liu Jicong 已提交
1478 1479
//   return filterRangeExecute(pQueryAttr->pFilters, pDataStatis, pQueryAttr->numOfCols, numOfRows);
// }
1480

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

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

1487
  if (true) {
L
Liu Jicong 已提交
1488
    //    getAlignQueryTimeWindow(pQueryAttr, pBlockInfo->window.skey, sk, ek, &w);
1489 1490 1491 1492 1493 1494
    assert(w.ekey >= pBlockInfo->window.skey);

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

L
Liu Jicong 已提交
1495 1496
    while (1) {
      //      getNextTimeWindow(pQueryAttr, &w);
1497 1498 1499 1500 1501 1502 1503 1504 1505 1506
      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 已提交
1507
    //    getAlignQueryTimeWindow(pQueryAttr, pBlockInfo->window.ekey, sk, ek, &w);
1508 1509 1510 1511 1512 1513
    assert(w.skey <= pBlockInfo->window.ekey);

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

L
Liu Jicong 已提交
1514 1515
    while (1) {
      //      getNextTimeWindow(pQueryAttr, &w);
1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 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
      if (w.ekey < pBlockInfo->window.skey) {
        break;
      }

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

  return false;
}

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

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

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

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

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

    start += len;
    len = 0;
  }

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

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

static uint32_t doFilterByBlockTimeWindow(STableScanInfo* pTableScanInfo, SSDataBlock* pBlock) {
H
Haojun Liao 已提交
1580
  SqlFunctionCtx* pCtx = pTableScanInfo->pCtx;
1581
  uint32_t        status = BLK_DATA_NOT_LOAD;
1582 1583 1584 1585

  int32_t numOfOutput = pTableScanInfo->numOfOutput;
  for (int32_t i = 0; i < numOfOutput; ++i) {
    int32_t functionId = pCtx[i].functionId;
H
Haojun Liao 已提交
1586
    int32_t colId = pTableScanInfo->pExpr[i].base.pParam[0].pCol->colId;
1587 1588 1589

    // group by + first/last should not apply the first/last block filter
    if (functionId < 0) {
1590
      status |= BLK_DATA_DATA_LOAD;
1591 1592
      return status;
    } else {
L
Liu Jicong 已提交
1593
      //      status |= aAggs[functionId].dataReqFunc(&pTableScanInfo->pCtx[i], &pBlock->info.window, colId);
1594
      //      if ((status & BLK_DATA_DATA_LOAD) == BLK_DATA_DATA_LOAD) {
L
Liu Jicong 已提交
1595 1596
      //        return status;
      //      }
1597 1598 1599 1600 1601 1602
    }
  }

  return status;
}

L
Liu Jicong 已提交
1603 1604
int32_t loadDataBlockOnDemand(SExecTaskInfo* pTaskInfo, STableScanInfo* pTableScanInfo, SSDataBlock* pBlock,
                              uint32_t* status) {
1605
  *status = BLK_DATA_NOT_LOAD;
1606

H
Haojun Liao 已提交
1607
  pBlock->pDataBlock = NULL;
L
Liu Jicong 已提交
1608
  pBlock->pBlockAgg = NULL;
H
Haojun Liao 已提交
1609

L
Liu Jicong 已提交
1610 1611
  //  int64_t groupId = pRuntimeEnv->current->groupIndex;
  //  bool    ascQuery = QUERY_IS_ASC_QUERY(pQueryAttr);
1612

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

1615 1616
//  pCost->totalBlocks += 1;
//  pCost->totalRows += pBlock->info.rows;
H
Haojun Liao 已提交
1617
#if 0
1618 1619 1620
  // 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 已提交
1621
      (QUERY_IS_INTERVAL_QUERY(pQueryAttr) && overlapWithTimeWindow(pTaskInfo, &pBlock->info))) {
1622
    (*status) = BLK_DATA_DATA_LOAD;
1623 1624 1625
  }

  // check if this data block is required to load
1626
  if ((*status) != BLK_DATA_DATA_LOAD) {
1627 1628 1629 1630 1631 1632 1633
    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 已提交
1634
      bool  masterScan = IS_MAIN_SCAN(pRuntimeEnv);
1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657
      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 {
1658
      (*status) = BLK_DATA_DATA_LOAD;
1659 1660 1661 1662
    }
  }

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

1665
  if ((*status) == BLK_DATA_NOT_LOAD || (*status) == BLK_DATA_FILTEROUT) {
1666 1667
    //qDebug("QInfo:0x%"PRIx64" data block discard, brange:%" PRId64 "-%" PRId64 ", rows:%d", pQInfo->qId, pBlockInfo->window.skey,
//           pBlockInfo->window.ekey, pBlockInfo->rows);
1668
    pCost->skipBlocks += 1;
1669
  } else if ((*status) == BLK_DATA_SMA_LOAD) {
1670 1671
    // this function never returns error?
    pCost->loadBlockStatis += 1;
1672
//    tsdbRetrieveDataBlockStatisInfo(pTableScanInfo->pTsdbReadHandle, &pBlock->pBlockAgg);
1673 1674

    if (pBlock->pBlockAgg == NULL) {  // data block statistics does not exist, load data block
1675
//      pBlock->pDataBlock = tsdbRetrieveDataBlock(pTableScanInfo->pTsdbReadHandle, NULL);
1676 1677 1678
      pCost->totalCheckedRows += pBlock->info.rows;
    }
  } else {
1679
    assert((*status) == BLK_DATA_DATA_LOAD);
1680 1681 1682

    // load the data block statistics to perform further filter
    pCost->loadBlockStatis += 1;
1683
//    tsdbRetrieveDataBlockStatisInfo(pTableScanInfo->pTsdbReadHandle, &pBlock->pBlockAgg);
1684 1685 1686 1687 1688 1689

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

H
Haojun Liao 已提交
1690
          bool  masterScan = IS_MAIN_SCAN(pRuntimeEnv);
1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707
          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
1708
            pCost->skipBlocks += 1;
1709 1710
            //qDebug("QInfo:0x%"PRIx64" data block discard, brange:%" PRId64 "-%" PRId64 ", rows:%d", pQInfo->qId,
//                   pBlockInfo->window.skey, pBlockInfo->window.ekey, pBlockInfo->rows);
1711
            (*status) = BLK_DATA_FILTEROUT;
1712 1713 1714 1715 1716 1717 1718 1719
            return TSDB_CODE_SUCCESS;
          }
        }
      }
    }

    // current block has been discard due to filter applied
//    if (!doFilterByBlockStatistics(pRuntimeEnv, pBlock->pBlockAgg, pTableScanInfo->pCtx, pBlockInfo->rows)) {
1720
//      pCost->skipBlocks += 1;
1721 1722
//      qDebug("QInfo:0x%"PRIx64" data block discard, brange:%" PRId64 "-%" PRId64 ", rows:%d", pQInfo->qId, pBlockInfo->window.skey,
//             pBlockInfo->window.ekey, pBlockInfo->rows);
1723
//      (*status) = BLK_DATA_FILTEROUT;
1724 1725 1726 1727 1728
//      return TSDB_CODE_SUCCESS;
//    }

    pCost->totalCheckedRows += pBlockInfo->rows;
    pCost->loadBlocks += 1;
1729
//    pBlock->pDataBlock = tsdbRetrieveDataBlock(pTableScanInfo->pTsdbReadHandle, NULL);
1730 1731 1732 1733 1734 1735 1736
//    if (pBlock->pDataBlock == NULL) {
//      return terrno;
//    }

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

1738 1739 1740 1741
//    if (pQueryAttr->pFilters != NULL || pRuntimeEnv->pTsBuf != NULL) {
//      filterColRowsInDataBlock(pRuntimeEnv, pBlock, ascQuery);
//    }
  }
H
Haojun Liao 已提交
1742
#endif
1743 1744 1745
  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
1746
void copyToSDataBlock(SSDataBlock* pBlock, int32_t* offset, SGroupResInfo* pGroupResInfo, SDiskbasedBuf* pResBuf) {
1747 1748 1749 1750 1751 1752 1753
  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 已提交
1754 1755 1756
      //      if ((code = mergeIntoGroupResult(&pGroupResInfo, pRuntimeEnv, offset)) != TSDB_CODE_SUCCESS) {
      return;
      //      }
1757 1758
    }

L
Liu Jicong 已提交
1759
    //    doCopyToSDataBlock(pResBuf, pGroupResInfo, TSDB_ORDER_ASC, pBlock, );
1760 1761 1762 1763 1764 1765 1766 1767 1768 1769

    // 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 已提交
1770 1771 1772
    //    if (pBlock->info.rows >= threshold) {
    //      break;
    //    }
1773 1774 1775
  }
}

L
Liu Jicong 已提交
1776
static void updateTableQueryInfoForReverseScan(STableQueryInfo* pTableQueryInfo) {
1777 1778 1779 1780
  if (pTableQueryInfo == NULL) {
    return;
  }

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

L
Liu Jicong 已提交
1784 1785
  //  SWITCH_ORDER(pTableQueryInfo->cur.order);
  //  pTableQueryInfo->cur.vgroupIndex = -1;
1786 1787

  // set the index to be the end slot of result rows array
dengyihao's avatar
dengyihao 已提交
1788 1789 1790 1791 1792 1793
  //  SResultRowInfo* pResultRowInfo = &pTableQueryInfo->resInfo;
  //  if (pResultRowInfo->size > 0) {
  //    pResultRowInfo->curPos = pResultRowInfo->size - 1;
  //  } else {
  //    pResultRowInfo->curPos = -1;
  //  }
1794 1795
}

H
Haojun Liao 已提交
1796
void initResultRow(SResultRow* pResultRow) {
X
Xiaoyu Wang 已提交
1797
  //  pResultRow->pEntryInfo = (struct SResultRowEntryInfo*)((char*)pResultRow + sizeof(SResultRow));
1798 1799 1800 1801 1802
}

/*
 * 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 已提交
1803 1804 1805
 * +------------+-----------------result column 1------------+------------------result column 2-----------+
 * | SResultRow | SResultRowEntryInfo | intermediate buffer1 | SResultRowEntryInfo | intermediate buffer 2|
 * +------------+--------------------------------------------+--------------------------------------------+
1806 1807
 *           offset[0]                                  offset[1]                                   offset[2]
 */
1808
// TODO refactor: some function move away
X
Xiaoyu Wang 已提交
1809 1810
void setFunctionResultOutput(SOptrBasicInfo* pInfo, SAggSupporter* pSup, int32_t stage, int32_t numOfExprs,
                             SExecTaskInfo* pTaskInfo) {
L
Liu Jicong 已提交
1811 1812 1813
  SqlFunctionCtx* pCtx = pInfo->pCtx;
  SSDataBlock*    pDataBlock = pInfo->pRes;
  int32_t*        rowCellInfoOffset = pInfo->rowCellInfoOffset;
H
Haojun Liao 已提交
1814

H
Haojun Liao 已提交
1815
  SResultRowInfo* pResultRowInfo = &pInfo->resultRowInfo;
H
Haojun Liao 已提交
1816
  initResultRowInfo(pResultRowInfo, 16);
H
Haojun Liao 已提交
1817

L
Liu Jicong 已提交
1818 1819
  int64_t     tid = 0;
  int64_t     groupId = 0;
1820 1821
  SResultRow* pRow = doSetResultOutBufByKey(pSup->pResultBuf, pResultRowInfo, (char*)&tid, sizeof(tid), true, groupId,
                                            pTaskInfo, false, pSup);
H
Haojun Liao 已提交
1822

H
Haojun Liao 已提交
1823
  ASSERT(pDataBlock->info.numOfCols == numOfExprs);
H
Haojun Liao 已提交
1824 1825 1826 1827
  for (int32_t i = 0; i < pDataBlock->info.numOfCols; ++i) {
    struct SResultRowEntryInfo* pEntry = getResultCell(pRow, i, rowCellInfoOffset);
    cleanupResultRowEntry(pEntry);

L
Liu Jicong 已提交
1828
    pCtx[i].resultInfo = pEntry;
1829
    pCtx[i].scanFlag = stage;
H
Haojun Liao 已提交
1830 1831

    // set the timestamp output buffer for top/bottom/diff query
L
Liu Jicong 已提交
1832 1833
    //    int32_t fid = pCtx[i].functionId;
    //    if (fid == FUNCTION_TOP || fid == FUNCTION_BOTTOM || fid == FUNCTION_DIFF || fid == FUNCTION_DERIVATIVE) {
H
Haojun Liao 已提交
1834
    //      if (i > 0) pCtx[i].pTsOutput = pCtx[i-1].pOutput;
L
Liu Jicong 已提交
1835
    //    }
H
Haojun Liao 已提交
1836 1837 1838 1839 1840
  }

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

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

L
Liu Jicong 已提交
1844
  int32_t newSize = pDataBlock->info.rows + numOfInputRows + 5;  // extra output buffer
1845
  if ((*bufCapacity) < newSize) {
L
Liu Jicong 已提交
1846 1847
    for (int32_t i = 0; i < pDataBlock->info.numOfCols; ++i) {
      SColumnInfoData* pColInfo = taosArrayGet(pDataBlock->pDataBlock, i);
1848

wafwerar's avatar
wafwerar 已提交
1849
      char* p = taosMemoryRealloc(pColInfo->pData, newSize * pColInfo->info.bytes);
1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862
      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 已提交
1863
    SColumnInfoData* pColInfo = taosArrayGet(pDataBlock->pDataBlock, i);
1864 1865 1866 1867 1868
    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 已提交
1869 1870
    if (functionId == FUNCTION_TOP || functionId == FUNCTION_BOTTOM || functionId == FUNCTION_DIFF ||
        functionId == FUNCTION_DERIVATIVE) {
dengyihao's avatar
dengyihao 已提交
1871
      //      if (i > 0) pBInfo->pCtx[i].pTsOutput = pBInfo->pCtx[i - 1].pOutput;
1872 1873 1874 1875
    }
  }
}

H
Haojun Liao 已提交
1876
void copyTsColoum(SSDataBlock* pRes, SqlFunctionCtx* pCtx, int32_t numOfOutput) {
1877 1878
  bool    needCopyTs = false;
  int32_t tsNum = 0;
L
Liu Jicong 已提交
1879
  char*   src = NULL;
1880 1881 1882 1883
  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 已提交
1884 1885
      if (i > 0 && pCtx[i - 1].functionId == FUNCTION_TS_DUMMY) {
        SColumnInfoData* pColRes = taosArrayGet(pRes->pDataBlock, i - 1);  // find ts data
1886 1887
        src = pColRes->pData;
      }
L
Liu Jicong 已提交
1888
    } else if (functionId == FUNCTION_TS_DUMMY) {
1889 1890 1891 1892 1893 1894 1895 1896 1897 1898
      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 已提交
1899
    if (functionId == FUNCTION_TS_DUMMY) {
1900 1901 1902 1903 1904 1905
      SColumnInfoData* pColRes = taosArrayGet(pRes->pDataBlock, i);
      memcpy(pColRes->pData, src, pColRes->info.bytes * pRes->info.rows);
    }
  }
}

H
Haojun Liao 已提交
1906
void initCtxOutputBuffer(SqlFunctionCtx* pCtx, int32_t size) {
1907 1908
  for (int32_t j = 0; j < size; ++j) {
    struct SResultRowEntryInfo* pResInfo = GET_RES_INFO(&pCtx[j]);
dengyihao's avatar
dengyihao 已提交
1909 1910
    if (isRowEntryInitialized(pResInfo) || fmIsPseudoColumnFunc(pCtx[j].functionId) || pCtx[j].functionId == -1 ||
        fmIsScalarFunc(pCtx[j].functionId)) {
1911 1912 1913
      continue;
    }

H
Haojun Liao 已提交
1914
    pCtx[j].fpSet.init(&pCtx[j], pCtx[j].resultInfo);
1915 1916 1917
  }
}

L
Liu Jicong 已提交
1918
void setTaskStatus(SExecTaskInfo* pTaskInfo, int8_t status) {
1919
  if (status == TASK_NOT_COMPLETED) {
H
Haojun Liao 已提交
1920
    pTaskInfo->status = status;
1921 1922
  } else {
    // QUERY_NOT_COMPLETED is not compatible with any other status, so clear its position first
1923
    CLEAR_QUERY_STATUS(pTaskInfo, TASK_NOT_COMPLETED);
H
Haojun Liao 已提交
1924
    pTaskInfo->status |= status;
1925 1926 1927
  }
}

1928
// todo merged with the build group result.
1929 1930
void finalizeMultiTupleQueryResult(int32_t numOfOutput, SDiskbasedBuf* pBuf, SResultRowInfo* pResultRowInfo,
                                   int32_t* rowCellInfoOffset) {
1931 1932 1933
  for (int32_t i = 0; i < pResultRowInfo->size; ++i) {
    SResultRowPosition* pPos = &pResultRowInfo->pPosition[i];

L
Liu Jicong 已提交
1934
    SFilePage*  bufPage = getBufPage(pBuf, pPos->pageId);
1935
    SResultRow* pRow = (SResultRow*)((char*)bufPage + pPos->offset);
H
Haojun Liao 已提交
1936 1937

    // TODO ignore the close status anyway.
dengyihao's avatar
dengyihao 已提交
1938 1939 1940
    //    if (!isResultRowClosed(pRow)) {
    //      continue;
    //    }
1941

1942
    for (int32_t j = 0; j < numOfOutput; ++j) {
1943
      struct SResultRowEntryInfo* pResInfo = getResultCell(pRow, j, rowCellInfoOffset);
H
Haojun Liao 已提交
1944
      if (!isRowEntryInitialized(pResInfo)) {
1945 1946 1947 1948 1949 1950
        continue;
      }

      if (pRow->numOfRows < pResInfo->numOfRes) {
        pRow->numOfRows = pResInfo->numOfRes;
      }
1951
    }
1952 1953 1954

    releaseBufPage(pBuf, bufPage);
  }
1955 1956
}

1957
STableQueryInfo* createTableQueryInfo(void* buf, STimeWindow win) {
L
Liu Jicong 已提交
1958
  STableQueryInfo* pTableQueryInfo = buf;
1959 1960 1961 1962
  pTableQueryInfo->lastKey = win.skey;
  return pTableQueryInfo;
}

L
Liu Jicong 已提交
1963
void destroyTableQueryInfoImpl(STableQueryInfo* pTableQueryInfo) {
1964 1965 1966 1967
  if (pTableQueryInfo == NULL) {
    return;
  }

L
Liu Jicong 已提交
1968
  //  taosVariantDestroy(&pTableQueryInfo->tag);
dengyihao's avatar
dengyihao 已提交
1969
  //  cleanupResultRowInfo(&pTableQueryInfo->resInfo);
1970 1971
}

1972
void setResultRowInitCtx(SResultRow* pResult, SqlFunctionCtx* pCtx, int32_t numOfOutput, int32_t* rowCellInfoOffset) {
1973 1974 1975 1976 1977 1978 1979
  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;
    }
1980 1981 1982 1983 1984

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

1985 1986 1987 1988 1989 1990
    if (!pResInfo->initialized) {
      if (pCtx[i].functionId != -1) {
        pCtx[i].fpSet.init(&pCtx[i], pResInfo);
      } else {
        pResInfo->initialized = true;
      }
1991 1992 1993 1994
    }
  }
}

1995
static void extractQualifiedTupleByFilterResult(SSDataBlock* pBlock, const int8_t* rowRes, bool keep);
1996
void doFilter(const SNode* pFilterNode, SSDataBlock* pBlock, SArray* pColMatchInfo) {
1997 1998 1999 2000 2001
  if (pFilterNode == NULL) {
    return;
  }

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

H
Haojun Liao 已提交
2003
  // todo move to the initialization function
H
Haojun Liao 已提交
2004
  int32_t code = filterInitFromNode((SNode*)pFilterNode, &filter, 0);
2005 2006 2007 2008 2009

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

  int8_t* rowRes = NULL;
2010

2011
  // todo the keep seems never to be True??
2012
  bool keep = filterExecute(filter, pBlock, &rowRes, NULL, param1.numOfCols);
D
dapan1121 已提交
2013
  filterFreeInfo(filter);
2014

2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027
  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);

2028 2029
    int32_t totalRows = pBlock->info.rows;

2030 2031 2032 2033
    for (int32_t i = 0; i < pBlock->info.numOfCols; ++i) {
      SColumnInfoData* pDst = taosArrayGet(px->pDataBlock, i);
      SColumnInfoData* pSrc = taosArrayGet(pBlock->pDataBlock, i);

2034 2035 2036 2037 2038
      // it is a reserved column for scalar function, and no data in this column yet.
      if (pSrc->pData == NULL) {
        continue;
      }

2039
      int32_t numOfRows = 0;
2040
      for (int32_t j = 0; j < totalRows; ++j) {
D
dapan1121 已提交
2041 2042 2043
        if (rowRes[j] == 0) {
          continue;
        }
2044

D
dapan1121 已提交
2045
        if (colDataIsNull_s(pSrc, j)) {
2046
          colDataAppendNULL(pDst, numOfRows);
D
dapan1121 已提交
2047
        } else {
2048
          colDataAppend(pDst, numOfRows, colDataGetData(pSrc, j), false);
D
dapan1121 已提交
2049
        }
2050
        numOfRows += 1;
H
Haojun Liao 已提交
2051
      }
2052

2053 2054 2055 2056 2057 2058
      if (pBlock->info.rows == totalRows) {
        pBlock->info.rows = numOfRows;
      } else {
        ASSERT(pBlock->info.rows == numOfRows);
      }

2059 2060 2061 2062 2063
      *pSrc = *pDst;
    }
  } else {
    // do nothing
    pBlock->info.rows = 0;
2064 2065 2066
  }
}

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

2072 2073
  SResultRowInfo* pResultRowInfo = &pAggInfo->binfo.resultRowInfo;
  SqlFunctionCtx* pCtx = pAggInfo->binfo.pCtx;
L
Liu Jicong 已提交
2074
  int32_t*        rowCellInfoOffset = pAggInfo->binfo.rowCellInfoOffset;
2075

2076
  SResultRow* pResultRow = doSetResultOutBufByKey(pAggInfo->aggSup.pResultBuf, pResultRowInfo, (char*)&groupId,
L
Liu Jicong 已提交
2077
                                                  sizeof(groupId), true, groupId, pTaskInfo, false, &pAggInfo->aggSup);
L
Liu Jicong 已提交
2078
  assert(pResultRow != NULL);
2079 2080 2081 2082 2083 2084

  /*
   * 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 已提交
2085 2086
    int32_t ret =
        addNewWindowResultBuf(pResultRow, pAggInfo->aggSup.pResultBuf, groupId, pAggInfo->binfo.pRes->info.rowSize);
2087 2088 2089 2090 2091
    if (ret != TSDB_CODE_SUCCESS) {
      return;
    }
  }

2092
  setResultRowInitCtx(pResultRow, pCtx, numOfOutput, rowCellInfoOffset);
2093 2094
}

H
Haojun Liao 已提交
2095 2096
void setExecutionContext(int32_t numOfOutput, uint64_t groupId, SExecTaskInfo* pTaskInfo, SAggOperatorInfo* pAggInfo) {
  if (pAggInfo->groupId != INT32_MIN && pAggInfo->groupId == groupId) {
2097 2098 2099
    return;
  }

H
Haojun Liao 已提交
2100
  doSetTableGroupOutputBuf(pAggInfo, numOfOutput, groupId, pTaskInfo);
2101 2102

  // record the current active group id
H
Haojun Liao 已提交
2103
  pAggInfo->groupId = groupId;
2104 2105 2106 2107 2108 2109 2110 2111 2112 2113
}

/**
 * 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
 */
2114
int32_t doCopyToSDataBlock(SExecTaskInfo* taskInfo, SSDataBlock* pBlock, SExprInfo* pExprInfo, SDiskbasedBuf* pBuf, SGroupResInfo* pGroupResInfo,
2115
                           int32_t* rowCellOffset, SqlFunctionCtx* pCtx, int32_t numOfExprs) {
2116
  int32_t numOfRows = getNumOfTotalRes(pGroupResInfo);
2117
  int32_t start = pGroupResInfo->index;
2118

L
Liu Jicong 已提交
2119
  // qDebug("QInfo:0x%"PRIx64" start to copy data from windowResInfo to output buf", GET_TASKID(pRuntimeEnv));
2120

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

2125
    SResultRow* pRow = (SResultRow*)((char*)page + pPos->pos.offset);
2126 2127 2128 2129 2130
    if (pRow->numOfRows == 0) {
      pGroupResInfo->index += 1;
      continue;
    }

2131
    if (pBlock->info.rows + pRow->numOfRows > pBlock->info.capacity) {
2132 2133 2134 2135 2136
      break;
    }

    pGroupResInfo->index += 1;

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

2140
      pCtx[j].resultInfo = getResultCell(pRow, j, rowCellOffset);
2141
      if (pCtx[j].fpSet.finalize) {
2142
        int32_t code = pCtx[j].fpSet.finalize(&pCtx[j], pBlock);
2143
        if (TAOS_FAILED(code)) {
2144 2145 2146 2147
          qError("%s build result data block error, code %s", GET_TASKID(taskInfo), tstrerror(code));
          taskInfo->code = code;
          longjmp(taskInfo->env, code);
        }
2148 2149
      } else if (strcmp(pCtx[j].pExpr->pExpr->_function.functionName, "_select_value") == 0) {
        // do nothing, todo refactor
2150
      } else {
2151 2152 2153 2154 2155 2156 2157
        // 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);
          }
2158
      }
2159 2160
    }

2161
    releaseBufPage(pBuf, page);
2162 2163
    pBlock->info.rows += pRow->numOfRows;
    if (pBlock->info.rows >= pBlock->info.capacity) {  // output buffer is full
2164 2165 2166 2167
      break;
    }
  }

L
Liu Jicong 已提交
2168
  // qDebug("QInfo:0x%"PRIx64" copy data to query buf completed", GET_TASKID(pRuntimeEnv));
2169
  blockDataUpdateTsWindow(pBlock);
2170 2171 2172
  return 0;
}

2173
void doBuildResultDatablock(SOperatorInfo* pOperator, SOptrBasicInfo* pbInfo, SGroupResInfo* pGroupResInfo, SDiskbasedBuf* pBuf) {
2174 2175
  assert(pGroupResInfo->currentGroup <= pGroupResInfo->totalGroup);

2176 2177 2178 2179
  SExprInfo* pExprInfo = pOperator->pExpr;
  int32_t numOfExprs = pOperator->numOfExprs;
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;

X
Xiaoyu Wang 已提交
2180 2181 2182
  int32_t*        rowCellOffset = pbInfo->rowCellInfoOffset;
  SSDataBlock*    pBlock = pbInfo->pRes;
  SqlFunctionCtx* pCtx = pbInfo->pCtx;
2183

2184
  blockDataCleanup(pBlock);
2185 2186 2187 2188
  if (!hasRemainDataInCurrentGroup(pGroupResInfo)) {
    return;
  }

2189
  doCopyToSDataBlock(pTaskInfo, pBlock, pExprInfo, pBuf, pGroupResInfo, rowCellOffset, pCtx, numOfExprs);
2190

H
Haojun Liao 已提交
2191 2192
  // add condition (pBlock->info.rows >= 1) just to runtime happy
  blockDataUpdateTsWindow(pBlock);
2193 2194
}

L
Liu Jicong 已提交
2195 2196
static void updateNumOfRowsInResultRows(SqlFunctionCtx* pCtx, int32_t numOfOutput, SResultRowInfo* pResultRowInfo,
                                        int32_t* rowCellInfoOffset) {
2197
  // update the number of result for each, only update the number of rows for the corresponding window result.
L
Liu Jicong 已提交
2198 2199 2200
  //  if (QUERY_IS_INTERVAL_QUERY(pQueryAttr)) {
  //    return;
  //  }
H
Haojun Liao 已提交
2201
#if 0
2202
  for (int32_t i = 0; i < pResultRowInfo->size; ++i) {
L
Liu Jicong 已提交
2203
    SResultRow* pResult = pResultRowInfo->pResult[i];
2204 2205 2206 2207 2208 2209 2210

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

2211 2212
      SResultRowEntryInfo* pCell = getResultCell(pResult, j, rowCellInfoOffset);
      pResult->numOfRows = (uint16_t)(TMAX(pResult->numOfRows, pCell->numOfRes));
2213 2214
    }
  }
H
Haojun Liao 已提交
2215
#endif
2216 2217
}

L
Liu Jicong 已提交
2218
static int32_t compressQueryColData(SColumnInfoData* pColRes, int32_t numOfRows, char* data, int8_t compressed) {
2219 2220
  int32_t colSize = pColRes->info.bytes * numOfRows;
  return (*(tDataTypes[pColRes->info.type].compFunc))(pColRes->pData, colSize, numOfRows, data,
L
Liu Jicong 已提交
2221
                                                      colSize + COMP_OVERFLOW_BYTES, compressed, NULL, 0);
2222 2223
}

2224
int32_t doFillTimeIntervalGapsInResults(struct SFillInfo* pFillInfo, SSDataBlock* pBlock, int32_t capacity) {
L
Liu Jicong 已提交
2225 2226 2227 2228
  //  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);
  //  }
2229

2230 2231
  int32_t numOfRows = (int32_t)taosFillResultDataBlock(pFillInfo, pBlock, capacity - pBlock->info.rows);
  pBlock->info.rows += numOfRows;
2232

2233
  return pBlock->info.rows;
2234 2235
}

2236
void publishOperatorProfEvent(SOperatorInfo* pOperator, EQueryProfEventType eventType) {
2237 2238
  SQueryProfEvent event = {0};

L
Liu Jicong 已提交
2239 2240
  event.eventType = eventType;
  event.eventTime = taosGetTimestampUs();
2241
  event.operatorType = pOperator->operatorType;
dengyihao's avatar
dengyihao 已提交
2242 2243 2244
  //    if (pQInfo->summary.queryProfEvents) {
  //      taosArrayPush(pQInfo->summary.queryProfEvents, &event);
  //    }
2245 2246
}

L
Liu Jicong 已提交
2247
void publishQueryAbortEvent(SExecTaskInfo* pTaskInfo, int32_t code) {
2248 2249 2250 2251 2252
  SQueryProfEvent event;
  event.eventType = QUERY_PROF_QUERY_ABORT;
  event.eventTime = taosGetTimestampUs();
  event.abortCode = code;

2253 2254
  if (pTaskInfo->cost.queryProfEvents) {
    taosArrayPush(pTaskInfo->cost.queryProfEvents, &event);
2255 2256 2257
  }
}

L
Liu Jicong 已提交
2258
typedef struct {
2259 2260 2261 2262 2263 2264 2265
  uint8_t operatorType;
  int64_t beginTime;
  int64_t endTime;
  int64_t selfTime;
  int64_t descendantsTime;
} SOperatorStackItem;

L
Liu Jicong 已提交
2266 2267
static void doOperatorExecProfOnce(SOperatorStackItem* item, SQueryProfEvent* event, SArray* opStack,
                                   SHashObj* profResults) {
2268 2269 2270 2271 2272 2273 2274 2275
  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 已提交
2276
  uint8_t              operatorType = item->operatorType;
2277 2278 2279 2280 2281 2282 2283 2284 2285
  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 已提交
2286
    taosHashPut(profResults, &(operatorType), sizeof(operatorType), &opResult, sizeof(opResult));
2287 2288 2289
  }
}

2290
void calculateOperatorProfResults(void) {
dengyihao's avatar
dengyihao 已提交
2291 2292 2293 2294 2295 2296 2297 2298 2299
  //  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;
  //  }
2300 2301 2302 2303 2304

  SArray* opStack = taosArrayInit(32, sizeof(SOperatorStackItem));
  if (opStack == NULL) {
    return;
  }
2305
#if 0
L
Liu Jicong 已提交
2306
  size_t    size = taosArrayGetSize(pQInfo->summary.queryProfEvents);
2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327
  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);
      }
    }
  }
2328
#endif
2329 2330 2331
  taosArrayDestroy(opStack);
}

L
Liu Jicong 已提交
2332 2333
void queryCostStatis(SExecTaskInfo* pTaskInfo) {
  STaskCostInfo* pSummary = &pTaskInfo->cost;
2334

L
Liu Jicong 已提交
2335 2336 2337
  //  uint64_t hashSize = taosHashGetMemSize(pQInfo->runtimeEnv.pResultRowHashTable);
  //  hashSize += taosHashGetMemSize(pRuntimeEnv->tableqinfoGroupInfo.map);
  //  pSummary->hashSize = hashSize;
2338 2339 2340 2341

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

L
Liu Jicong 已提交
2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352
  //  SResultRowPool* p = pTaskInfo->pool;
  //  if (p != NULL) {
  //    pSummary->winInfoSize = getResultRowPoolMemSize(p);
  //    pSummary->numOfTimeWindows = getNumOfAllocatedResultRows(p);
  //  } else {
  //    pSummary->winInfoSize = 0;
  //    pSummary->numOfTimeWindows = 0;
  //  }
  //
  //  calculateOperatorProfResults(pQInfo);

2353 2354
  SFileBlockLoadRecorder* pRecorder = pSummary->pRecoder;
  if (pSummary->pRecoder != NULL) {
X
Xiaoyu Wang 已提交
2355 2356
    qDebug("%s :cost summary: elapsed time:%" PRId64 " us, first merge:%" PRId64
           " us, total blocks:%d, "
2357 2358 2359 2360
           "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 已提交
2361 2362 2363
  // 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);
2364 2365 2366 2367

  if (pSummary->operatorProfResults) {
    SOperatorProfResult* opRes = taosHashIterate(pSummary->operatorProfResults, NULL);
    while (opRes != NULL) {
L
Liu Jicong 已提交
2368 2369
      // qDebug("QInfo:0x%" PRIx64 " :cost summary: operator : %d, exec times: %" PRId64 ", self time: %" PRId64,
      //             pQInfo->qId, opRes->operatorType, opRes->sumRunTimes, opRes->sumSelfTime);
2370 2371 2372 2373 2374
      opRes = taosHashIterate(pSummary->operatorProfResults, opRes);
    }
  }
}

L
Liu Jicong 已提交
2375 2376 2377
// static void updateOffsetVal(STaskRuntimeEnv *pRuntimeEnv, SDataBlockInfo *pBlockInfo) {
//   STaskAttr *pQueryAttr = pRuntimeEnv->pQueryAttr;
//   STableQueryInfo* pTableQueryInfo = pRuntimeEnv->current;
2378
//
L
Liu Jicong 已提交
2379
//   int32_t step = GET_FORWARD_DIRECTION_FACTOR(pQueryAttr->order.order);
2380
//
L
Liu Jicong 已提交
2381 2382 2383 2384
//   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;
//   }
2385
//
L
Liu Jicong 已提交
2386 2387 2388 2389 2390
//   if (QUERY_IS_ASC_QUERY(pQueryAttr)) {
//     pQueryAttr->pos = (int32_t)pQueryAttr->limit.offset;
//   } else {
//     pQueryAttr->pos = pBlockInfo->rows - (int32_t)pQueryAttr->limit.offset - 1;
//   }
2391
//
L
Liu Jicong 已提交
2392
//   assert(pQueryAttr->pos >= 0 && pQueryAttr->pos <= pBlockInfo->rows - 1);
2393
//
L
Liu Jicong 已提交
2394 2395
//   SArray *         pDataBlock = tsdbRetrieveDataBlock(pRuntimeEnv->pTsdbReadHandle, NULL);
//   SColumnInfoData *pColInfoData = taosArrayGet(pDataBlock, 0);
2396
//
L
Liu Jicong 已提交
2397 2398
//   // update the pQueryAttr->limit.offset value, and pQueryAttr->pos value
//   TSKEY *keys = (TSKEY *) pColInfoData->pData;
2399
//
L
Liu Jicong 已提交
2400 2401 2402
//   // update the offset value
//   pTableQueryInfo->lastKey = keys[pQueryAttr->pos];
//   pQueryAttr->limit.offset = 0;
2403
//
L
Liu Jicong 已提交
2404
//   int32_t numOfRes = tableApplyFunctionsOnBlock(pRuntimeEnv, pBlockInfo, NULL, binarySearchForKey, pDataBlock);
2405
//
L
Liu Jicong 已提交
2406 2407 2408 2409
//   //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);
// }
2410

L
Liu Jicong 已提交
2411 2412
// void skipBlocks(STaskRuntimeEnv *pRuntimeEnv) {
//   STaskAttr *pQueryAttr = pRuntimeEnv->pQueryAttr;
2413
//
L
Liu Jicong 已提交
2414 2415 2416
//   if (pQueryAttr->limit.offset <= 0 || pQueryAttr->numOfFilterCols > 0) {
//     return;
//   }
2417
//
L
Liu Jicong 已提交
2418 2419
//   pQueryAttr->pos = 0;
//   int32_t step = GET_FORWARD_DIRECTION_FACTOR(pQueryAttr->order.order);
2420
//
L
Liu Jicong 已提交
2421 2422
//   STableQueryInfo* pTableQueryInfo = pRuntimeEnv->current;
//   TsdbQueryHandleT pTsdbReadHandle = pRuntimeEnv->pTsdbReadHandle;
2423
//
L
Liu Jicong 已提交
2424 2425 2426 2427 2428
//   SDataBlockInfo blockInfo = SDATA_BLOCK_INITIALIZER;
//   while (tsdbNextDataBlock(pTsdbReadHandle)) {
//     if (isTaskKilled(pRuntimeEnv->qinfo)) {
//       longjmp(pRuntimeEnv->env, TSDB_CODE_TSC_QUERY_CANCELLED);
//     }
2429
//
L
Liu Jicong 已提交
2430
//     tsdbRetrieveDataBlockInfo(pTsdbReadHandle, &blockInfo);
2431
//
L
Liu Jicong 已提交
2432 2433 2434 2435
//     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;
2436
//
L
Liu Jicong 已提交
2437 2438 2439 2440 2441 2442 2443
//       //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;
//     }
//   }
2444
//
L
Liu Jicong 已提交
2445 2446 2447 2448 2449 2450 2451 2452 2453
//   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;
2454
//
L
Liu Jicong 已提交
2455 2456 2457
//   assert(pQueryAttr->limit.offset == 0);
//   STimeWindow tw = *win;
//   getNextTimeWindow(pQueryAttr, &tw);
2458
//
L
Liu Jicong 已提交
2459 2460
//   if ((tw.skey <= pBlockInfo->window.ekey && QUERY_IS_ASC_QUERY(pQueryAttr)) ||
//       (tw.ekey >= pBlockInfo->window.skey && !QUERY_IS_ASC_QUERY(pQueryAttr))) {
2461
//
L
Liu Jicong 已提交
2462 2463 2464 2465
//     // 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);
2466
//
L
Liu Jicong 已提交
2467 2468 2469 2470
//     tw = *win;
//     int32_t startPos =
//         getNextQualifiedWindow(pQueryAttr, &tw, pBlockInfo, pColInfoData->pData, binarySearchForKey, -1);
//     assert(startPos >= 0);
2471
//
L
Liu Jicong 已提交
2472 2473
//     // set the abort info
//     pQueryAttr->pos = startPos;
2474
//
L
Liu Jicong 已提交
2475 2476 2477 2478
//     // reset the query start timestamp
//     pTableQueryInfo->win.skey = ((TSKEY *)pColInfoData->pData)[startPos];
//     pQueryAttr->window.skey = pTableQueryInfo->win.skey;
//     TSKEY key = pTableQueryInfo->win.skey;
2479
//
L
Liu Jicong 已提交
2480 2481
//     pWindowResInfo->prevSKey = tw.skey;
//     int32_t index = pRuntimeEnv->resultRowInfo.curIndex;
2482
//
L
Liu Jicong 已提交
2483 2484
//     int32_t numOfRes = tableApplyFunctionsOnBlock(pRuntimeEnv, pBlockInfo, NULL, binarySearchForKey, pDataBlock);
//     pRuntimeEnv->resultRowInfo.curIndex = index;  // restore the window index
2485
//
L
Liu Jicong 已提交
2486 2487 2488 2489
//     //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);
2490
//
L
Liu Jicong 已提交
2491 2492 2493 2494 2495
//     return key;
//   } else {  // do nothing
//     pQueryAttr->window.skey      = tw.skey;
//     pWindowResInfo->prevSKey = tw.skey;
//     pTableQueryInfo->lastKey = tw.skey;
2496
//
L
Liu Jicong 已提交
2497 2498
//     return tw.skey;
//   }
2499
//
L
Liu Jicong 已提交
2500 2501 2502 2503 2504 2505 2506 2507 2508 2509
//   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);
//   }
2510
//
L
Liu Jicong 已提交
2511 2512 2513 2514 2515
//   // 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;
//   }
2516
//
L
Liu Jicong 已提交
2517 2518 2519 2520 2521 2522 2523
//   /*
//    * 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);
2524
//
L
Liu Jicong 已提交
2525 2526
//   STimeWindow w = TSWINDOW_INITIALIZER;
//   bool ascQuery = QUERY_IS_ASC_QUERY(pQueryAttr);
2527
//
L
Liu Jicong 已提交
2528 2529
//   SResultRowInfo *pWindowResInfo = &pRuntimeEnv->resultRowInfo;
//   STableQueryInfo *pTableQueryInfo = pRuntimeEnv->current;
2530
//
L
Liu Jicong 已提交
2531 2532 2533
//   SDataBlockInfo blockInfo = SDATA_BLOCK_INITIALIZER;
//   while (tsdbNextDataBlock(pRuntimeEnv->pTsdbReadHandle)) {
//     tsdbRetrieveDataBlockInfo(pRuntimeEnv->pTsdbReadHandle, &blockInfo);
2534
//
L
Liu Jicong 已提交
2535 2536 2537 2538 2539 2540 2541 2542 2543
//     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;
//     }
2544
//
L
Liu Jicong 已提交
2545 2546
//     // the first time window
//     STimeWindow win = getActiveTimeWindow(pWindowResInfo, pWindowResInfo->prevSKey, pQueryAttr);
2547
//
L
Liu Jicong 已提交
2548 2549
//     while (pQueryAttr->limit.offset > 0) {
//       STimeWindow tw = win;
2550
//
L
Liu Jicong 已提交
2551 2552 2553
//       if ((win.ekey <= blockInfo.window.ekey && ascQuery) || (win.ekey >= blockInfo.window.skey && !ascQuery)) {
//         pQueryAttr->limit.offset -= 1;
//         pWindowResInfo->prevSKey = win.skey;
2554
//
L
Liu Jicong 已提交
2555 2556 2557 2558 2559 2560
//         // 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;
//         }
//       }
2561
//
L
Liu Jicong 已提交
2562 2563 2564 2565
//       if (pQueryAttr->limit.offset == 0) {
//         *start = doSkipIntervalProcess(pRuntimeEnv, &win, &blockInfo, pTableQueryInfo);
//         return true;
//       }
2566
//
L
Liu Jicong 已提交
2567 2568
//       // current window does not ended in current data block, try next data block
//       getNextTimeWindow(pQueryAttr, &tw);
2569
//
L
Liu Jicong 已提交
2570 2571 2572 2573 2574 2575 2576 2577 2578
//       /*
//        * 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)) {
2579
//
L
Liu Jicong 已提交
2580 2581
//         SArray *pDataBlock = tsdbRetrieveDataBlock(pRuntimeEnv->pTsdbReadHandle, NULL);
//         SColumnInfoData *pColInfoData = taosArrayGet(pDataBlock, 0);
2582
//
L
Liu Jicong 已提交
2583 2584 2585
//         if ((win.ekey > blockInfo.window.ekey && ascQuery) || (win.ekey < blockInfo.window.skey && !ascQuery)) {
//           pQueryAttr->limit.offset -= 1;
//         }
2586
//
L
Liu Jicong 已提交
2587 2588 2589 2590 2591 2592 2593 2594
//         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);
2595
//
L
Liu Jicong 已提交
2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606
//           // 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.
//       }
//     }
//   }
2607
//
L
Liu Jicong 已提交
2608 2609 2610 2611
//   // check for error
//   if (terrno != TSDB_CODE_SUCCESS) {
//     longjmp(pRuntimeEnv->env, terrno);
//   }
2612
//
L
Liu Jicong 已提交
2613 2614
//   return true;
// }
2615

2616
int32_t appendDownstream(SOperatorInfo* p, SOperatorInfo** pDownstream, int32_t num) {
H
Haojun Liao 已提交
2617
  if (p->pDownstream == NULL) {
H
Haojun Liao 已提交
2618
    assert(p->numOfDownstream == 0);
2619 2620
  }

wafwerar's avatar
wafwerar 已提交
2621
  p->pDownstream = taosMemoryCalloc(1, num * POINTER_BYTES);
2622 2623 2624 2625 2626 2627 2628
  if (p->pDownstream == NULL) {
    return TSDB_CODE_OUT_OF_MEMORY;
  }

  memcpy(p->pDownstream, pDownstream, num * POINTER_BYTES);
  p->numOfDownstream = num;
  return TSDB_CODE_SUCCESS;
2629 2630 2631 2632
}

static void doDestroyTableQueryInfo(STableGroupInfo* pTableqinfoGroupInfo);

2633
static void doTableQueryInfoTimeWindowCheck(SExecTaskInfo* pTaskInfo, STableQueryInfo* pTableQueryInfo, int32_t order) {
H
Haojun Liao 已提交
2634 2635
#if 0
    if (order == TSDB_ORDER_ASC) {
2636 2637
    assert(
        (pTableQueryInfo->win.skey <= pTableQueryInfo->win.ekey) &&
H
Haojun Liao 已提交
2638 2639
        (pTableQueryInfo->lastKey >= pTaskInfo->window.skey) &&
        (pTableQueryInfo->win.skey >= pTaskInfo->window.skey && pTableQueryInfo->win.ekey <= pTaskInfo->window.ekey));
2640 2641 2642
  } else {
    assert(
        (pTableQueryInfo->win.skey >= pTableQueryInfo->win.ekey) &&
H
Haojun Liao 已提交
2643 2644
        (pTableQueryInfo->lastKey <= pTaskInfo->window.skey) &&
        (pTableQueryInfo->win.skey <= pTaskInfo->window.skey && pTableQueryInfo->win.ekey >= pTaskInfo->window.ekey));
2645
  }
H
Haojun Liao 已提交
2646
#endif
2647 2648
}

L
Liu Jicong 已提交
2649 2650 2651 2652
// 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;
2653
//
L
Liu Jicong 已提交
2654 2655 2656
//   if (pTableQueryInfo->pTable == NULL) {
//     return;
//   }
2657
//
L
Liu Jicong 已提交
2658 2659 2660 2661 2662 2663 2664 2665 2666
//   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));
//   }
// }
2667

2668
int32_t loadRemoteDataCallback(void* param, const SDataBuf* pMsg, int32_t code) {
L
Liu Jicong 已提交
2669
  SSourceDataInfo* pSourceDataInfo = (SSourceDataInfo*)param;
H
Haojun Liao 已提交
2670 2671
  if (code == TSDB_CODE_SUCCESS) {
    pSourceDataInfo->pRsp = pMsg->pData;
2672

H
Haojun Liao 已提交
2673 2674
    SRetrieveTableRsp* pRsp = pSourceDataInfo->pRsp;
    pRsp->numOfRows = htonl(pRsp->numOfRows);
dengyihao's avatar
dengyihao 已提交
2675
    pRsp->compLen = htonl(pRsp->compLen);
2676
    pRsp->numOfCols = htonl(pRsp->numOfCols);
dengyihao's avatar
dengyihao 已提交
2677
    pRsp->useconds = htobe64(pRsp->useconds);
H
Haojun Liao 已提交
2678 2679 2680
  } else {
    pSourceDataInfo->code = code;
  }
H
Haojun Liao 已提交
2681

H
Haojun Liao 已提交
2682
  pSourceDataInfo->status = EX_SOURCE_DATA_READY;
2683
  tsem_post(&pSourceDataInfo->pEx->ready);
wmmhello's avatar
wmmhello 已提交
2684
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
2685 2686 2687 2688
}

static void destroySendMsgInfo(SMsgSendInfo* pMsgBody) {
  assert(pMsgBody != NULL);
wafwerar's avatar
wafwerar 已提交
2689 2690
  taosMemoryFreeClear(pMsgBody->msgInfo.pData);
  taosMemoryFreeClear(pMsgBody);
H
Haojun Liao 已提交
2691 2692
}

S
Shengliang Guan 已提交
2693
void qProcessFetchRsp(void* parent, SRpcMsg* pMsg, SEpSet* pEpSet) {
S
Shengliang Guan 已提交
2694 2695
  SMsgSendInfo* pSendInfo = (SMsgSendInfo*)pMsg->info.ahandle;
  assert(pMsg->info.ahandle != NULL);
H
Haojun Liao 已提交
2696 2697 2698 2699

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

  if (pMsg->contLen > 0) {
wafwerar's avatar
wafwerar 已提交
2700
    buf.pData = taosMemoryCalloc(1, pMsg->contLen);
H
Haojun Liao 已提交
2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711
    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);
2712 2713
}

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

wafwerar's avatar
wafwerar 已提交
2717
  SResFetchReq* pMsg = taosMemoryCalloc(1, sizeof(SResFetchReq));
2718 2719 2720 2721
  if (NULL == pMsg) {
    pTaskInfo->code = TSDB_CODE_QRY_OUT_OF_MEMORY;
    return pTaskInfo->code;
  }
2722

L
Liu Jicong 已提交
2723 2724
  SDownstreamSourceNode* pSource = taosArrayGet(pExchangeInfo->pSources, sourceIndex);
  SSourceDataInfo*       pDataInfo = taosArrayGet(pExchangeInfo->pSourceDataInfo, sourceIndex);
2725

L
Liu Jicong 已提交
2726 2727
  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);
2728 2729 2730 2731 2732 2733 2734

  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 已提交
2735
  SMsgSendInfo* pMsgSendInfo = taosMemoryCalloc(1, sizeof(SMsgSendInfo));
2736
  if (NULL == pMsgSendInfo) {
wafwerar's avatar
wafwerar 已提交
2737
    taosMemoryFreeClear(pMsg);
2738 2739 2740
    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 已提交
2741 2742
  }

2743 2744 2745 2746 2747
  pMsgSendInfo->param = pDataInfo;
  pMsgSendInfo->msgInfo.pData = pMsg;
  pMsgSendInfo->msgInfo.len = sizeof(SResFetchReq);
  pMsgSendInfo->msgType = TDMT_VND_FETCH;
  pMsgSendInfo->fp = loadRemoteDataCallback;
2748

2749
  int64_t transporterId = 0;
L
Liu Jicong 已提交
2750
  int32_t code = asyncSendMsgToServer(pExchangeInfo->pTransporter, &pSource->addr.epSet, &transporterId, pMsgSendInfo);
2751 2752 2753
  return TSDB_CODE_SUCCESS;
}

2754
// NOTE: sources columns are more than the destination SSDatablock columns.
2755
void relocateColumnData(SSDataBlock* pBlock, const SArray* pColMatchInfo, SArray* pCols) {
2756 2757 2758
  size_t numOfSrcCols = taosArrayGetSize(pCols);

  int32_t i = 0, j = 0;
L
Liu Jicong 已提交
2759
  while (i < numOfSrcCols && j < taosArrayGetSize(pColMatchInfo)) {
2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778
    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);
    }
  }
}

2779
int32_t setSDataBlockFromFetchRsp(SSDataBlock* pRes, SLoadRemoteDataInfo* pLoadInfo, int32_t numOfRows, char* pData,
dengyihao's avatar
dengyihao 已提交
2780 2781
                                  int32_t compLen, int32_t numOfOutput, int64_t startTs, uint64_t* total,
                                  SArray* pColList) {
H
Haojun Liao 已提交
2782
  if (pColList == NULL) {  // data from other sources
H
Haojun Liao 已提交
2783 2784
    blockDataEnsureCapacity(pRes, numOfRows);

L
Liu Jicong 已提交
2785
    int32_t dataLen = *(int32_t*)pData;
2786 2787
    pData += sizeof(int32_t);

L
Liu Jicong 已提交
2788
    pRes->info.groupId = *(uint64_t*)pData;
2789 2790
    pData += sizeof(uint64_t);

H
Haojun Liao 已提交
2791 2792
    int32_t* colLen = (int32_t*)pData;

2793
    char* pStart = pData + sizeof(int32_t) * numOfOutput;
2794
    for (int32_t i = 0; i < numOfOutput; ++i) {
H
Haojun Liao 已提交
2795
      colLen[i] = htonl(colLen[i]);
2796
      ASSERT(colLen[i] >= 0);
H
Haojun Liao 已提交
2797

2798
      SColumnInfoData* pColInfoData = taosArrayGet(pRes->pDataBlock, i);
H
Haojun Liao 已提交
2799 2800 2801
      if (IS_VAR_DATA_TYPE(pColInfoData->info.type)) {
        pColInfoData->varmeta.length = colLen[i];
        pColInfoData->varmeta.allocLen = colLen[i];
2802

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

2806 2807 2808
        if (colLen[i] > 0) {
          pColInfoData->pData = taosMemoryMalloc(colLen[i]);
        }
H
Haojun Liao 已提交
2809 2810 2811
      } else {
        memcpy(pColInfoData->nullbitmap, pStart, BitmapLen(numOfRows));
        pStart += BitmapLen(numOfRows);
2812
      }
H
Haojun Liao 已提交
2813

2814 2815 2816 2817
      if (colLen[i] > 0) {
        memcpy(pColInfoData->pData, pStart, colLen[i]);
      }

L
Liu Jicong 已提交
2818 2819
      // TODO setting this flag to true temporarily so aggregate function on stable will
      // examine NULL value for non-primary key column
2820
      pColInfoData->hasNull = true;
H
Haojun Liao 已提交
2821
      pStart += colLen[i];
2822
    }
H
Haojun Liao 已提交
2823
  } else {  // extract data according to pColList
2824
    ASSERT(numOfOutput == taosArrayGetSize(pColList));
2825 2826 2827 2828 2829
    char* pStart = pData;

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

2830
    // todo refactor:extract method
2831
    SSysTableSchema* pSchema = (SSysTableSchema*)pStart;
dengyihao's avatar
dengyihao 已提交
2832
    for (int32_t i = 0; i < numOfCols; ++i) {
2833 2834 2835 2836 2837 2838 2839
      SSysTableSchema* p = (SSysTableSchema*)pStart;

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

H
Haojun Liao 已提交
2840 2841 2842 2843
    SSDataBlock* pBlock = taosMemoryCalloc(1, sizeof(SSDataBlock));
    pBlock->pDataBlock = taosArrayInit(numOfCols, sizeof(SColumnInfoData));
    pBlock->info.numOfCols = numOfCols;

dengyihao's avatar
dengyihao 已提交
2844
    for (int32_t i = 0; i < numOfCols; ++i) {
2845 2846 2847 2848 2849
      SColumnInfoData idata = {0};
      idata.info.type = pSchema[i].type;
      idata.info.bytes = pSchema[i].bytes;
      idata.info.colId = pSchema[i].colId;

H
Haojun Liao 已提交
2850
      taosArrayPush(pBlock->pDataBlock, &idata);
2851
      if (IS_VAR_DATA_TYPE(idata.info.type)) {
H
Haojun Liao 已提交
2852
        pBlock->info.hasVarCol = true;
2853 2854 2855
      }
    }

H
Haojun Liao 已提交
2856
    blockDataEnsureCapacity(pBlock, numOfRows);
2857

L
Liu Jicong 已提交
2858 2859
    int32_t  dataLen = *(int32_t*)pStart;
    uint64_t groupId = *(uint64_t*)(pStart + sizeof(int32_t));
2860 2861
    pStart += sizeof(int32_t) + sizeof(uint64_t);

L
Liu Jicong 已提交
2862
    int32_t* colLen = (int32_t*)(pStart);
2863 2864 2865 2866
    pStart += sizeof(int32_t) * numOfCols;

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

H
Haojun Liao 已提交
2869
      SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, i);
2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885
      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 已提交
2886 2887

    // data from mnode
H
Haojun Liao 已提交
2888 2889 2890
    relocateColumnData(pRes, pColList, pBlock->pDataBlock);
    taosArrayDestroy(pBlock->pDataBlock);
    taosMemoryFree(pBlock);
X
Xiaoyu Wang 已提交
2891
    //    blockDataDestroy(pBlock);
2892
  }
2893

H
Haojun Liao 已提交
2894
  pRes->info.rows = numOfRows;
2895
  blockDataUpdateTsWindow(pRes);
2896

2897
  int64_t el = taosGetTimestampUs() - startTs;
2898

H
Haojun Liao 已提交
2899 2900
  pLoadInfo->totalRows += numOfRows;
  pLoadInfo->totalSize += compLen;
2901

H
Haojun Liao 已提交
2902 2903 2904
  if (total != NULL) {
    *total += numOfRows;
  }
2905

H
Haojun Liao 已提交
2906
  pLoadInfo->totalElapsed += el;
2907 2908
  return TSDB_CODE_SUCCESS;
}
2909

L
Liu Jicong 已提交
2910 2911
static void* setAllSourcesCompleted(SOperatorInfo* pOperator, int64_t startTs) {
  SExchangeInfo* pExchangeInfo = pOperator->info;
2912
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
H
Haojun Liao 已提交
2913

L
Liu Jicong 已提交
2914
  int64_t              el = taosGetTimestampUs() - startTs;
H
Haojun Liao 已提交
2915 2916
  SLoadRemoteDataInfo* pLoadInfo = &pExchangeInfo->loadInfo;
  pLoadInfo->totalElapsed += el;
H
Haojun Liao 已提交
2917

2918
  size_t totalSources = taosArrayGetSize(pExchangeInfo->pSources);
L
Liu Jicong 已提交
2919 2920 2921
  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);
2922 2923 2924 2925 2926

  doSetOperatorCompleted(pOperator);
  return NULL;
}

L
Liu Jicong 已提交
2927 2928
static SSDataBlock* concurrentlyLoadRemoteDataImpl(SOperatorInfo* pOperator, SExchangeInfo* pExchangeInfo,
                                                   SExecTaskInfo* pTaskInfo) {
2929 2930 2931 2932 2933 2934 2935 2936 2937
  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);

2938
      if (pDataInfo->status == EX_SOURCE_DATA_EXHAUSTED) {
2939
        completed += 1;
H
Haojun Liao 已提交
2940 2941
        continue;
      }
2942

2943
      if (pDataInfo->status != EX_SOURCE_DATA_READY) {
2944 2945 2946
        continue;
      }

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

L
Liu Jicong 已提交
2950
      SSDataBlock*         pRes = pExchangeInfo->pResult;
H
Haojun Liao 已提交
2951
      SLoadRemoteDataInfo* pLoadInfo = &pExchangeInfo->loadInfo;
2952
      if (pRsp->numOfRows == 0) {
L
Liu Jicong 已提交
2953 2954
        qDebug("%s vgId:%d, taskID:0x%" PRIx64 " index:%d completed, rowsOfSource:%" PRIu64 ", totalRows:%" PRIu64
               " try next",
2955
               GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->taskId, i + 1, pDataInfo->totalRows,
H
Haojun Liao 已提交
2956
               pExchangeInfo->loadInfo.totalRows);
2957
        pDataInfo->status = EX_SOURCE_DATA_EXHAUSTED;
2958 2959 2960
        completed += 1;
        continue;
      }
H
Haojun Liao 已提交
2961

H
Haojun Liao 已提交
2962
      SRetrieveTableRsp* pTableRsp = pDataInfo->pRsp;
X
Xiaoyu Wang 已提交
2963 2964
      code = setSDataBlockFromFetchRsp(pExchangeInfo->pResult, pLoadInfo, pTableRsp->numOfRows, pTableRsp->data,
                                       pTableRsp->compLen, pTableRsp->numOfCols, startTs, &pDataInfo->totalRows, NULL);
2965
      if (code != 0) {
2966 2967 2968
        goto _error;
      }

2969 2970 2971
      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 已提交
2972 2973
               GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->taskId, pRes->info.rows, pDataInfo->totalRows,
               pLoadInfo->totalRows, pLoadInfo->totalSize, i + 1, totalSources);
2974
        pDataInfo->status = EX_SOURCE_DATA_EXHAUSTED;
2975
      } else {
dengyihao's avatar
dengyihao 已提交
2976 2977
        qDebug("%s fetch msg rsp from vgId:%d, taskId:0x%" PRIx64 " numOfRows:%d, totalRows:%" PRIu64
               ", totalBytes:%" PRIu64,
H
Haojun Liao 已提交
2978 2979
               GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->taskId, pRes->info.rows, pLoadInfo->totalRows,
               pLoadInfo->totalSize);
2980 2981
      }

2982 2983
      if (pDataInfo->status != EX_SOURCE_DATA_EXHAUSTED) {
        pDataInfo->status = EX_SOURCE_DATA_NOT_READY;
2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002
        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 已提交
3003 3004 3005
static SSDataBlock* concurrentlyLoadRemoteData(SOperatorInfo* pOperator) {
  SExchangeInfo* pExchangeInfo = pOperator->info;
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
H
Haojun Liao 已提交
3006

H
Haojun Liao 已提交
3007 3008 3009
  if (pOperator->status == OP_RES_TO_RETURN) {
    return concurrentlyLoadRemoteDataImpl(pOperator, pExchangeInfo, pTaskInfo);
  }
3010

L
Liu Jicong 已提交
3011
  size_t  totalSources = taosArrayGetSize(pExchangeInfo->pSources);
3012 3013 3014
  int64_t startTs = taosGetTimestampUs();

  // Asynchronously send all fetch requests to all sources.
L
Liu Jicong 已提交
3015
  for (int32_t i = 0; i < totalSources; ++i) {
3016 3017
    int32_t code = doSendFetchDataRequest(pExchangeInfo, pTaskInfo, i);
    if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
3018
      return NULL;
3019 3020 3021 3022
    }
  }

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

  tsem_wait(&pExchangeInfo->ready);
H
Haojun Liao 已提交
3027 3028
  pOperator->status = OP_RES_TO_RETURN;
  return concurrentlyLoadRemoteDataImpl(pOperator, pExchangeInfo, pTaskInfo);
3029 3030
}

L
Liu Jicong 已提交
3031 3032 3033
static int32_t prepareConcurrentlyLoad(SOperatorInfo* pOperator) {
  SExchangeInfo* pExchangeInfo = pOperator->info;
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
3034

L
Liu Jicong 已提交
3035
  size_t  totalSources = taosArrayGetSize(pExchangeInfo->pSources);
3036 3037 3038
  int64_t startTs = taosGetTimestampUs();

  // Asynchronously send all fetch requests to all sources.
L
Liu Jicong 已提交
3039
  for (int32_t i = 0; i < totalSources; ++i) {
3040 3041
    int32_t code = doSendFetchDataRequest(pExchangeInfo, pTaskInfo, i);
    if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
3042 3043
      pTaskInfo->code = code;
      return code;
3044 3045 3046 3047
    }
  }

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

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

H
Haojun Liao 已提交
3054
  return TSDB_CODE_SUCCESS;
3055 3056
}

L
Liu Jicong 已提交
3057 3058 3059
static SSDataBlock* seqLoadRemoteData(SOperatorInfo* pOperator) {
  SExchangeInfo* pExchangeInfo = pOperator->info;
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
3060

L
Liu Jicong 已提交
3061
  size_t  totalSources = taosArrayGetSize(pExchangeInfo->pSources);
3062
  int64_t startTs = taosGetTimestampUs();
3063

L
Liu Jicong 已提交
3064
  while (1) {
3065 3066
    if (pExchangeInfo->current >= totalSources) {
      return setAllSourcesCompleted(pOperator, startTs);
3067
    }
3068

3069 3070 3071
    doSendFetchDataRequest(pExchangeInfo, pTaskInfo, pExchangeInfo->current);
    tsem_wait(&pExchangeInfo->ready);

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

H
Haojun Liao 已提交
3075
    if (pDataInfo->code != TSDB_CODE_SUCCESS) {
dengyihao's avatar
dengyihao 已提交
3076 3077
      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 已提交
3078 3079 3080 3081
      pOperator->pTaskInfo->code = pDataInfo->code;
      return NULL;
    }

L
Liu Jicong 已提交
3082
    SRetrieveTableRsp*   pRsp = pDataInfo->pRsp;
H
Haojun Liao 已提交
3083
    SLoadRemoteDataInfo* pLoadInfo = &pExchangeInfo->loadInfo;
3084
    if (pRsp->numOfRows == 0) {
dengyihao's avatar
dengyihao 已提交
3085 3086
      qDebug("%s vgId:%d, taskID:0x%" PRIx64 " %d of total completed, rowsOfSource:%" PRIu64 ", totalRows:%" PRIu64
             " try next",
3087
             GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->taskId, pExchangeInfo->current + 1,
H
Haojun Liao 已提交
3088
             pDataInfo->totalRows, pLoadInfo->totalRows);
H
Haojun Liao 已提交
3089

3090
      pDataInfo->status = EX_SOURCE_DATA_EXHAUSTED;
3091 3092 3093
      pExchangeInfo->current += 1;
      continue;
    }
H
Haojun Liao 已提交
3094

L
Liu Jicong 已提交
3095
    SSDataBlock*       pRes = pExchangeInfo->pResult;
H
Haojun Liao 已提交
3096
    SRetrieveTableRsp* pTableRsp = pDataInfo->pRsp;
L
Liu Jicong 已提交
3097 3098
    int32_t            code =
        setSDataBlockFromFetchRsp(pExchangeInfo->pResult, pLoadInfo, pTableRsp->numOfRows, pTableRsp->data,
3099
                                  pTableRsp->compLen, pTableRsp->numOfCols, startTs, &pDataInfo->totalRows, NULL);
3100 3101

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

3107
      pDataInfo->status = EX_SOURCE_DATA_EXHAUSTED;
3108 3109
      pExchangeInfo->current += 1;
    } else {
L
Liu Jicong 已提交
3110 3111 3112 3113
      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);
3114 3115 3116 3117
    }

    return pExchangeInfo->pResult;
  }
3118 3119
}

L
Liu Jicong 已提交
3120
static int32_t prepareLoadRemoteData(SOperatorInfo* pOperator) {
3121
  if (OPTR_IS_OPENED(pOperator)) {
H
Haojun Liao 已提交
3122 3123 3124
    return TSDB_CODE_SUCCESS;
  }

L
Liu Jicong 已提交
3125
  SExchangeInfo* pExchangeInfo = pOperator->info;
H
Haojun Liao 已提交
3126 3127 3128 3129 3130 3131 3132 3133 3134
  if (pExchangeInfo->seqLoadData) {
    // do nothing for sequentially load data
  } else {
    int32_t code = prepareConcurrentlyLoad(pOperator);
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }
  }

3135
  OPTR_SET_OPENED(pOperator);
H
Haojun Liao 已提交
3136 3137 3138
  return TSDB_CODE_SUCCESS;
}

3139
static SSDataBlock* doLoadRemoteData(SOperatorInfo* pOperator) {
L
Liu Jicong 已提交
3140 3141
  SExchangeInfo* pExchangeInfo = pOperator->info;
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
3142

3143
  pTaskInfo->code = pOperator->fpSet._openFn(pOperator);
3144
  if (pTaskInfo->code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
3145 3146
    return NULL;
  }
3147

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

3151
  if (pOperator->status == OP_EXEC_DONE) {
L
Liu Jicong 已提交
3152 3153 3154
    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);
3155 3156 3157 3158 3159 3160
    return NULL;
  }

  if (pExchangeInfo->seqLoadData) {
    return seqLoadRemoteData(pOperator);
  } else {
H
Haojun Liao 已提交
3161
    return concurrentlyLoadRemoteData(pOperator);
3162
  }
H
Haojun Liao 已提交
3163

3164
#if 0
H
Haojun Liao 已提交
3165
  _error:
wafwerar's avatar
wafwerar 已提交
3166 3167
  taosMemoryFreeClear(pMsg);
  taosMemoryFreeClear(pMsgSendInfo);
H
Haojun Liao 已提交
3168 3169 3170

  terrno = pTaskInfo->code;
  return NULL;
3171
#endif
H
Haojun Liao 已提交
3172
}
3173

H
Haojun Liao 已提交
3174
static int32_t initDataSource(int32_t numOfSources, SExchangeInfo* pInfo) {
3175
  pInfo->pSourceDataInfo = taosArrayInit(numOfSources, sizeof(SSourceDataInfo));
H
Haojun Liao 已提交
3176 3177
  if (pInfo->pSourceDataInfo == NULL) {
    return TSDB_CODE_OUT_OF_MEMORY;
3178 3179
  }

L
Liu Jicong 已提交
3180
  for (int32_t i = 0; i < numOfSources; ++i) {
3181
    SSourceDataInfo dataInfo = {0};
H
Haojun Liao 已提交
3182
    dataInfo.status = EX_SOURCE_DATA_NOT_READY;
L
Liu Jicong 已提交
3183 3184
    dataInfo.pEx = pInfo;
    dataInfo.index = i;
3185

H
Haojun Liao 已提交
3186 3187 3188 3189 3190 3191 3192 3193 3194 3195
    void* ret = taosArrayPush(pInfo->pSourceDataInfo, &dataInfo);
    if (ret == NULL) {
      taosArrayDestroy(pInfo->pSourceDataInfo);
      return TSDB_CODE_OUT_OF_MEMORY;
    }
  }

  return TSDB_CODE_SUCCESS;
}

3196
SOperatorInfo* createExchangeOperatorInfo(void *pTransporter, const SNodeList* pSources, SSDataBlock* pBlock,
3197
                                          SExecTaskInfo* pTaskInfo) {
L
Liu Jicong 已提交
3198
  SExchangeInfo* pInfo = taosMemoryCalloc(1, sizeof(SExchangeInfo));
wafwerar's avatar
wafwerar 已提交
3199
  SOperatorInfo* pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
3200 3201

  if (pInfo == NULL || pOperator == NULL) {
wafwerar's avatar
wafwerar 已提交
3202 3203
    taosMemoryFreeClear(pInfo);
    taosMemoryFreeClear(pOperator);
H
Haojun Liao 已提交
3204 3205
    terrno = TSDB_CODE_QRY_OUT_OF_MEMORY;
    return NULL;
H
Haojun Liao 已提交
3206 3207
  }

H
Haojun Liao 已提交
3208
  size_t numOfSources = LIST_LENGTH(pSources);
H
Haojun Liao 已提交
3209
  pInfo->pSources = taosArrayInit(numOfSources, sizeof(SDownstreamSourceNode));
H
Haojun Liao 已提交
3210 3211 3212
  pInfo->pSourceDataInfo = taosArrayInit(numOfSources, sizeof(SSourceDataInfo));
  if (pInfo->pSourceDataInfo == NULL || pInfo->pSources == NULL) {
    goto _error;
H
Haojun Liao 已提交
3213 3214
  }

L
Liu Jicong 已提交
3215 3216
  for (int32_t i = 0; i < numOfSources; ++i) {
    SNodeListNode* pNode = nodesListGetNode((SNodeList*)pSources, i);
H
Haojun Liao 已提交
3217 3218
    taosArrayPush(pInfo->pSources, pNode);
  }
3219

H
Haojun Liao 已提交
3220 3221 3222
  int32_t code = initDataSource(numOfSources, pInfo);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
3223
  }
H
Haojun Liao 已提交
3224

dengyihao's avatar
dengyihao 已提交
3225
  pInfo->pResult = pBlock;
3226 3227 3228
  pInfo->seqLoadData = true;

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

dengyihao's avatar
dengyihao 已提交
3230
  pOperator->name = "ExchangeOperator";
X
Xiaoyu Wang 已提交
3231
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_EXCHANGE;
3232
  pOperator->blocking = false;
dengyihao's avatar
dengyihao 已提交
3233 3234
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
3235
  pOperator->numOfExprs = pBlock->info.numOfCols;
dengyihao's avatar
dengyihao 已提交
3236
  pOperator->pTaskInfo = pTaskInfo;
3237

L
Liu Jicong 已提交
3238 3239
  pOperator->fpSet = createOperatorFpSet(prepareLoadRemoteData, doLoadRemoteData, NULL, NULL,
                                         destroyExchangeOperatorInfo, NULL, NULL, NULL);
3240
  pInfo->pTransporter = pTransporter;
3241

3242
  return pOperator;
H
Haojun Liao 已提交
3243

L
Liu Jicong 已提交
3244
_error:
H
Haojun Liao 已提交
3245
  if (pInfo != NULL) {
H
Haojun Liao 已提交
3246
    destroyExchangeOperatorInfo(pInfo, numOfSources);
H
Haojun Liao 已提交
3247 3248
  }

wafwerar's avatar
wafwerar 已提交
3249 3250
  taosMemoryFreeClear(pInfo);
  taosMemoryFreeClear(pOperator);
H
Haojun Liao 已提交
3251
  pTaskInfo->code = TSDB_CODE_OUT_OF_MEMORY;
H
Haojun Liao 已提交
3252
  return NULL;
3253 3254
}

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

3258
static void destroySortedMergeOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
3259
  SSortedMergeOperatorInfo* pInfo = (SSortedMergeOperatorInfo*)param;
H
Haojun Liao 已提交
3260
  taosArrayDestroy(pInfo->pSortInfo);
3261 3262 3263
  taosArrayDestroy(pInfo->groupInfo);

  if (pInfo->pSortHandle != NULL) {
H
Haojun Liao 已提交
3264
    tsortDestroySortHandle(pInfo->pSortHandle);
3265 3266
  }

H
Haojun Liao 已提交
3267
  blockDataDestroy(pInfo->binfo.pRes);
H
Haojun Liao 已提交
3268
  cleanupAggSup(&pInfo->aggSup);
3269
}
H
Haojun Liao 已提交
3270

L
Liu Jicong 已提交
3271
static bool needToMerge(SSDataBlock* pBlock, SArray* groupInfo, char** buf, int32_t rowIndex) {
3272 3273 3274 3275
  size_t size = taosArrayGetSize(groupInfo);
  if (size == 0) {
    return true;
  }
3276

3277 3278
  for (int32_t i = 0; i < size; ++i) {
    int32_t* index = taosArrayGet(groupInfo, i);
3279

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

3283 3284 3285
    if ((isNull && buf[i] != NULL) || (!isNull && buf[i] == NULL)) {
      return false;
    }
3286

3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299
    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;
      }
3300 3301 3302
    }
  }

3303
  return 0;
3304 3305
}

L
Liu Jicong 已提交
3306 3307 3308
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
3309
//    pCtx[j].startRow = rowIndex;
3310 3311
  }

3312 3313
  for (int32_t j = 0; j < numOfExpr; ++j) {
    int32_t functionId = pCtx[j].functionId;
L
Liu Jicong 已提交
3314 3315 3316 3317 3318 3319 3320 3321 3322
    //    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]);
    //    }
3323
  }
3324
}
3325

L
Liu Jicong 已提交
3326 3327
static void doFinalizeResultImpl(SqlFunctionCtx* pCtx, int32_t numOfExpr) {
  for (int32_t j = 0; j < numOfExpr; ++j) {
3328 3329 3330 3331
    int32_t functionId = pCtx[j].functionId;
    //    if (functionId == FUNC_TAG_DUMMY || functionId == FUNC_TS_DUMMY) {
    //      continue;
    //    }
3332

3333 3334 3335 3336
    //    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 已提交
3337
    //    pCtx[j].fpSet.finalize(&pCtx[j]);
3338 3339
  }
}
3340

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

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

3348 3349 3350
    char* data = colDataGetData(pColInfo, rowIndex);
    memcpy(rowColData[i], data, colDataGetLength(pColInfo, rowIndex));
  }
3351

3352 3353
  return true;
}
3354

3355 3356
static void doMergeImpl(SOperatorInfo* pOperator, int32_t numOfExpr, SSDataBlock* pBlock) {
  SSortedMergeOperatorInfo* pInfo = pOperator->info;
3357

3358
  SqlFunctionCtx* pCtx = pInfo->binfo.pCtx;
L
Liu Jicong 已提交
3359
  for (int32_t i = 0; i < pBlock->info.numOfCols; ++i) {
3360
//    pCtx[i].size = 1;
3361
  }
3362

L
Liu Jicong 已提交
3363
  for (int32_t i = 0; i < pBlock->info.rows; ++i) {
3364 3365 3366 3367 3368 3369 3370 3371 3372
    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);
3373 3374
        int32_t numOfRows = getNumOfResult(pInfo->binfo.pCtx, pOperator->numOfExprs, NULL);
        //        setTagValueForMultipleRows(pCtx, pOperator->numOfExprs, numOfRows);
3375

3376
        // TODO check for available buffer;
H
Haojun Liao 已提交
3377

3378 3379 3380 3381 3382
        // next group info data
        pInfo->binfo.pRes->info.rows += numOfRows;
        for (int32_t j = 0; j < numOfExpr; ++j) {
          if (pCtx[j].functionId < 0) {
            continue;
3383
          }
3384

H
Haojun Liao 已提交
3385
          pCtx[j].fpSet.process(&pCtx[j]);
3386
        }
3387 3388 3389

        doMergeResultImpl(pInfo, pCtx, numOfExpr, i);
        pInfo->hasGroupVal = saveCurrentTuple(pInfo->groupVal, pInfo->groupInfo, pBlock, i);
H
Haojun Liao 已提交
3390
      }
3391 3392 3393 3394
    }
  }
}

3395 3396
static SSDataBlock* doMerge(SOperatorInfo* pOperator) {
  SSortedMergeOperatorInfo* pInfo = pOperator->info;
L
Liu Jicong 已提交
3397
  SSortHandle*              pHandle = pInfo->pSortHandle;
3398

3399
  SSDataBlock* pDataBlock = createOneDataBlock(pInfo->binfo.pRes, false);
3400
  blockDataEnsureCapacity(pDataBlock, pOperator->resultInfo.capacity);
3401

L
Liu Jicong 已提交
3402
  while (1) {
3403
    blockDataCleanup(pDataBlock);
3404
    while (1) {
H
Haojun Liao 已提交
3405
      STupleHandle* pTupleHandle = tsortNextTuple(pHandle);
3406 3407
      if (pTupleHandle == NULL) {
        break;
3408
      }
3409

3410 3411
      // build datablock for merge for one group
      appendOneRowToDataBlock(pDataBlock, pTupleHandle);
3412
      if (pDataBlock->info.rows >= pOperator->resultInfo.capacity) {
3413 3414
        break;
      }
3415
    }
3416

3417 3418 3419
    if (pDataBlock->info.rows == 0) {
      break;
    }
3420

3421
    setInputDataBlock(pOperator, pInfo->binfo.pCtx, pDataBlock, TSDB_ORDER_ASC, MAIN_SCAN, true);
L
Liu Jicong 已提交
3422 3423
    //  updateOutputBuf(&pInfo->binfo, &pAggInfo->bufCapacity, pBlock->info.rows * pAggInfo->resultRowFactor,
    //  pOperator->pRuntimeEnv, true);
3424
    doMergeImpl(pOperator, pOperator->numOfExprs, pDataBlock);
3425 3426
    // flush to tuple store, and after all data have been handled, return to upstream node or sink node
  }
3427

3428 3429 3430
  doFinalizeResultImpl(pInfo->binfo.pCtx, pOperator->numOfExprs);
  int32_t numOfRows = getNumOfResult(pInfo->binfo.pCtx, pOperator->numOfExprs, NULL);
  //        setTagValueForMultipleRows(pCtx, pOperator->numOfExprs, numOfRows);
3431

3432
  // TODO check for available buffer;
3433

3434 3435
  // next group info data
  pInfo->binfo.pRes->info.rows += numOfRows;
L
Liu Jicong 已提交
3436
  return (pInfo->binfo.pRes->info.rows > 0) ? pInfo->binfo.pRes : NULL;
3437
}
3438

3439
static SSDataBlock* doSortedMerge(SOperatorInfo* pOperator) {
3440 3441
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
3442 3443
  }

L
Liu Jicong 已提交
3444
  SExecTaskInfo*            pTaskInfo = pOperator->pTaskInfo;
3445
  SSortedMergeOperatorInfo* pInfo = pOperator->info;
H
Haojun Liao 已提交
3446
  if (pOperator->status == OP_RES_TO_RETURN) {
3447
    return getSortedBlockData(pInfo->pSortHandle, pInfo->binfo.pRes, pOperator->resultInfo.capacity, NULL);
3448 3449
  }

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

3454
  tsortSetFetchRawDataFp(pInfo->pSortHandle, loadNextDataBlock, NULL, NULL);
3455

L
Liu Jicong 已提交
3456
  for (int32_t i = 0; i < pOperator->numOfDownstream; ++i) {
wmmhello's avatar
wmmhello 已提交
3457
    SSortSource* ps = taosMemoryCalloc(1, sizeof(SSortSource));
H
Haojun Liao 已提交
3458
    ps->param = pOperator->pDownstream[i];
H
Haojun Liao 已提交
3459
    tsortAddSource(pInfo->pSortHandle, ps);
3460 3461
  }

H
Haojun Liao 已提交
3462
  int32_t code = tsortOpen(pInfo->pSortHandle);
3463
  if (code != TSDB_CODE_SUCCESS) {
3464
    longjmp(pTaskInfo->env, terrno);
3465 3466
  }

H
Haojun Liao 已提交
3467
  pOperator->status = OP_RES_TO_RETURN;
3468
  return doMerge(pOperator);
3469
}
3470

L
Liu Jicong 已提交
3471 3472
static int32_t initGroupCol(SExprInfo* pExprInfo, int32_t numOfCols, SArray* pGroupInfo,
                            SSortedMergeOperatorInfo* pInfo) {
3473 3474
  if (pGroupInfo == NULL || taosArrayGetSize(pGroupInfo) == 0) {
    return 0;
H
Haojun Liao 已提交
3475 3476
  }

3477 3478 3479 3480 3481 3482 3483 3484
  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 已提交
3485 3486
  size_t numOfGroupCol = taosArrayGetSize(pInfo->groupInfo);
  for (int32_t i = 0; i < numOfGroupCol; ++i) {
3487
    SColumn* pCol = taosArrayGet(pGroupInfo, i);
L
Liu Jicong 已提交
3488
    for (int32_t j = 0; j < numOfCols; ++j) {
H
Haojun Liao 已提交
3489
      SExprInfo* pe = &pExprInfo[j];
3490
      if (pe->base.resSchema.slotId == pCol->colId) {
3491 3492
        taosArrayPush(plist, pCol);
        taosArrayPush(pInfo->groupInfo, &j);
H
Haojun Liao 已提交
3493
        len += pCol->bytes;
3494 3495
        break;
      }
H
Haojun Liao 已提交
3496 3497 3498
    }
  }

3499
  ASSERT(taosArrayGetSize(pGroupInfo) == taosArrayGetSize(plist));
H
Haojun Liao 已提交
3500

wafwerar's avatar
wafwerar 已提交
3501
  pInfo->groupVal = taosMemoryCalloc(1, (POINTER_BYTES * numOfGroupCol + len));
3502 3503 3504 3505
  if (pInfo->groupVal == NULL) {
    taosArrayDestroy(plist);
    return TSDB_CODE_OUT_OF_MEMORY;
  }
H
Haojun Liao 已提交
3506

3507
  int32_t offset = 0;
L
Liu Jicong 已提交
3508 3509
  char*   start = (char*)(pInfo->groupVal + (POINTER_BYTES * numOfGroupCol));
  for (int32_t i = 0; i < numOfGroupCol; ++i) {
3510 3511
    pInfo->groupVal[i] = start + offset;
    SColumn* pCol = taosArrayGet(plist, i);
H
Haojun Liao 已提交
3512
    offset += pCol->bytes;
3513
  }
H
Haojun Liao 已提交
3514

3515
  taosArrayDestroy(plist);
H
Haojun Liao 已提交
3516

3517 3518
  return TSDB_CODE_SUCCESS;
}
H
Haojun Liao 已提交
3519

L
Liu Jicong 已提交
3520 3521 3522
SOperatorInfo* createSortedMergeOperatorInfo(SOperatorInfo** downstream, int32_t numOfDownstream, SExprInfo* pExprInfo,
                                             int32_t num, SArray* pSortInfo, SArray* pGroupInfo,
                                             SExecTaskInfo* pTaskInfo) {
wafwerar's avatar
wafwerar 已提交
3523
  SSortedMergeOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SSortedMergeOperatorInfo));
L
Liu Jicong 已提交
3524
  SOperatorInfo*            pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
3525
  if (pInfo == NULL || pOperator == NULL) {
3526
    goto _error;
3527
  }
H
Haojun Liao 已提交
3528

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

3532 3533 3534
  if (pInfo->binfo.pCtx == NULL || pInfo->binfo.pRes == NULL) {
    goto _error;
  }
H
Haojun Liao 已提交
3535

dengyihao's avatar
dengyihao 已提交
3536
  size_t  keyBufSize = sizeof(int64_t) + sizeof(int64_t) + POINTER_BYTES;
3537
  int32_t code = doInitAggInfoSup(&pInfo->aggSup, pInfo->binfo.pCtx, num, keyBufSize, pTaskInfo->id.str);
3538 3539 3540
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
H
Haojun Liao 已提交
3541

H
Haojun Liao 已提交
3542
  setFunctionResultOutput(&pInfo->binfo, &pInfo->aggSup, MAIN_SCAN, num, pTaskInfo);
H
Haojun Liao 已提交
3543
  code = initGroupCol(pExprInfo, num, pGroupInfo, pInfo);
3544 3545 3546
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
H
Haojun Liao 已提交
3547

L
Liu Jicong 已提交
3548 3549 3550 3551 3552
  //  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 已提交
3553

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

L
Liu Jicong 已提交
3556
  pOperator->name = "SortedMerge";
X
Xiaoyu Wang 已提交
3557
  // pOperator->operatorType = OP_SortedMerge;
3558
  pOperator->blocking = true;
L
Liu Jicong 已提交
3559 3560
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
3561
  pOperator->numOfExprs = num;
L
Liu Jicong 已提交
3562
  pOperator->pExpr = pExprInfo;
H
Haojun Liao 已提交
3563

L
Liu Jicong 已提交
3564
  pOperator->pTaskInfo = pTaskInfo;
H
Haojun Liao 已提交
3565

3566 3567
  pOperator->fpSet = createOperatorFpSet(operatorDummyOpenFn, doSortedMerge, NULL, NULL, destroySortedMergeOperatorInfo,
                                         NULL, NULL, NULL);
3568 3569 3570
  code = appendDownstream(pOperator, downstream, numOfDownstream);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
3571
  }
H
Haojun Liao 已提交
3572

3573
  return pOperator;
H
Haojun Liao 已提交
3574

L
Liu Jicong 已提交
3575
_error:
3576
  if (pInfo != NULL) {
H
Haojun Liao 已提交
3577
    destroySortedMergeOperatorInfo(pInfo, num);
H
Haojun Liao 已提交
3578 3579
  }

wafwerar's avatar
wafwerar 已提交
3580 3581
  taosMemoryFreeClear(pInfo);
  taosMemoryFreeClear(pOperator);
3582 3583
  terrno = TSDB_CODE_QRY_OUT_OF_MEMORY;
  return NULL;
H
Haojun Liao 已提交
3584 3585
}

3586
int32_t getTableScanInfo(SOperatorInfo* pOperator, int32_t *order, int32_t* scanFlag) {
3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597
  // 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 已提交
3598
    if (pOperator->pDownstream == NULL || pOperator->pDownstream[0] == NULL) {
3599
      return TSDB_CODE_INVALID_PARA;
H
Haojun Liao 已提交
3600
    } else {
3601
      return getTableScanInfo(pOperator->pDownstream[0], order, scanFlag);
3602 3603 3604
    }
  }
}
3605 3606

// this is a blocking operator
L
Liu Jicong 已提交
3607
static int32_t doOpenAggregateOptr(SOperatorInfo* pOperator) {
H
Haojun Liao 已提交
3608 3609
  if (OPTR_IS_OPENED(pOperator)) {
    return TSDB_CODE_SUCCESS;
3610 3611
  }

H
Haojun Liao 已提交
3612
  SExecTaskInfo*    pTaskInfo = pOperator->pTaskInfo;
3613
  SAggOperatorInfo* pAggInfo = pOperator->info;
H
Haojun Liao 已提交
3614

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

3618 3619 3620
  int32_t order = TSDB_ORDER_ASC;
  int32_t scanFlag = MAIN_SCAN;

H
Haojun Liao 已提交
3621
  while (1) {
H
Haojun Liao 已提交
3622
    publishOperatorProfEvent(downstream, QUERY_PROF_BEFORE_OPERATOR_EXEC);
3623
    SSDataBlock* pBlock = downstream->fpSet.getNextFn(downstream);
H
Haojun Liao 已提交
3624
    publishOperatorProfEvent(downstream, QUERY_PROF_AFTER_OPERATOR_EXEC);
3625 3626 3627 3628 3629

    if (pBlock == NULL) {
      break;
    }

3630 3631 3632 3633
    int32_t code = getTableScanInfo(pOperator, &order, &scanFlag);
    if (code != TSDB_CODE_SUCCESS) {
      longjmp(pTaskInfo->env, code);
    }
3634

3635 3636
    // there is an scalar expression that needs to be calculated before apply the group aggregation.
    if (pAggInfo->pScalarExprInfo != NULL) {
3637
      code = projectApplyFunctions(pAggInfo->pScalarExprInfo, pBlock, pBlock, pAggInfo->pScalarCtx,
3638
                                   pAggInfo->numOfScalarExpr, NULL);
3639
      if (code != TSDB_CODE_SUCCESS) {
3640
        longjmp(pTaskInfo->env, code);
3641
      }
3642 3643
    }

3644
    // the pDataBlock are always the same one, no need to call this again
3645
    setExecutionContext(pOperator->numOfExprs, pBlock->info.groupId, pTaskInfo, pAggInfo);
3646
    setInputDataBlock(pOperator, pInfo->pCtx, pBlock, order, scanFlag, true);
3647 3648 3649 3650
    code = doAggregateImpl(pOperator, 0, pInfo->pCtx);
    if (code != 0) {
      longjmp(pTaskInfo->env, code);
    }
3651

dengyihao's avatar
dengyihao 已提交
3652
#if 0  // test for encode/decode result info
3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663
    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);
      }
3664
    }
3665
#endif
3666 3667
  }

H
Haojun Liao 已提交
3668
  closeAllResultRows(&pAggInfo->binfo.resultRowInfo);
3669 3670
  finalizeMultiTupleQueryResult(pOperator->numOfExprs, pAggInfo->aggSup.pResultBuf, &pAggInfo->binfo.resultRowInfo,
                                pAggInfo->binfo.rowCellInfoOffset);
H
Haojun Liao 已提交
3671

3672
  initGroupedResultInfo(&pAggInfo->groupResInfo, pAggInfo->aggSup.pResultRowHashTable, 0);
H
Haojun Liao 已提交
3673 3674 3675 3676
  OPTR_SET_OPENED(pOperator);
  return TSDB_CODE_SUCCESS;
}

3677
static SSDataBlock* getAggregateResult(SOperatorInfo* pOperator) {
L
Liu Jicong 已提交
3678
  SAggOperatorInfo* pAggInfo = pOperator->info;
H
Haojun Liao 已提交
3679 3680 3681 3682 3683 3684
  SOptrBasicInfo*   pInfo = &pAggInfo->binfo;

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

L
Liu Jicong 已提交
3685
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
3686
  pTaskInfo->code = pOperator->fpSet._openFn(pOperator);
H
Haojun Liao 已提交
3687 3688 3689 3690
  if (pTaskInfo->code != TSDB_CODE_SUCCESS) {
    return NULL;
  }

H
Haojun Liao 已提交
3691
  blockDataEnsureCapacity(pInfo->pRes, pOperator->resultInfo.capacity);
3692
  doBuildResultDatablock(pOperator, pInfo, &pAggInfo->groupResInfo, pAggInfo->aggSup.pResultBuf);
H
Haojun Liao 已提交
3693 3694 3695
  if (pInfo->pRes->info.rows == 0 || !hasRemainDataInCurrentGroup(&pAggInfo->groupResInfo)) {
    doSetOperatorCompleted(pOperator);
  }
3696

H
Haojun Liao 已提交
3697
  doSetOperatorCompleted(pOperator);
L
Liu Jicong 已提交
3698
  return (blockDataGetNumOfRows(pInfo->pRes) != 0) ? pInfo->pRes : NULL;
3699 3700
}

dengyihao's avatar
dengyihao 已提交
3701 3702
void aggEncodeResultRow(SOperatorInfo* pOperator, SAggSupporter* pSup, SOptrBasicInfo* pInfo, char** result,
                        int32_t* length) {
wmmhello's avatar
wmmhello 已提交
3703
  int32_t size = taosHashGetSize(pSup->pResultRowHashTable);
3704
  size_t  keyLen = sizeof(uint64_t) * 2;  // estimate the key length
wmmhello's avatar
wmmhello 已提交
3705
  int32_t totalSize = sizeof(int32_t) + size * (sizeof(int32_t) + keyLen + sizeof(int32_t) + pSup->resultRowSize);
wafwerar's avatar
wafwerar 已提交
3706
  *result = taosMemoryCalloc(1, totalSize);
L
Liu Jicong 已提交
3707
  if (*result == NULL) {
3708
    longjmp(pOperator->pTaskInfo->env, TSDB_CODE_OUT_OF_MEMORY);
wmmhello's avatar
wmmhello 已提交
3709 3710 3711
  }
  *(int32_t*)(*result) = size;
  int32_t offset = sizeof(int32_t);
3712 3713

  // prepare memory
3714
  SResultRowPosition* pos = &pInfo->resultRowInfo.cur;
dengyihao's avatar
dengyihao 已提交
3715 3716
  void*               pPage = getBufPage(pSup->pResultBuf, pos->pageId);
  SResultRow*         pRow = (SResultRow*)((char*)pPage + pos->offset);
3717 3718 3719
  setBufPageDirty(pPage, true);
  releaseBufPage(pSup->pResultBuf, pPage);

dengyihao's avatar
dengyihao 已提交
3720
  void* pIter = taosHashIterate(pSup->pResultRowHashTable, NULL);
wmmhello's avatar
wmmhello 已提交
3721
  while (pIter) {
dengyihao's avatar
dengyihao 已提交
3722
    void*               key = taosHashGetKey(pIter, &keyLen);
3723
    SResultRowPosition* p1 = (SResultRowPosition*)pIter;
3724

dengyihao's avatar
dengyihao 已提交
3725
    pPage = (SFilePage*)getBufPage(pSup->pResultBuf, p1->pageId);
3726
    pRow = (SResultRow*)((char*)pPage + p1->offset);
3727 3728
    setBufPageDirty(pPage, true);
    releaseBufPage(pSup->pResultBuf, pPage);
wmmhello's avatar
wmmhello 已提交
3729 3730 3731

    // recalculate the result size
    int32_t realTotalSize = offset + sizeof(int32_t) + keyLen + sizeof(int32_t) + pSup->resultRowSize;
L
Liu Jicong 已提交
3732 3733 3734
    if (realTotalSize > totalSize) {
      char* tmp = taosMemoryRealloc(*result, realTotalSize);
      if (tmp == NULL) {
wmmhello's avatar
wmmhello 已提交
3735
        terrno = TSDB_CODE_OUT_OF_MEMORY;
wafwerar's avatar
wafwerar 已提交
3736
        taosMemoryFree(*result);
wmmhello's avatar
wmmhello 已提交
3737
        *result = NULL;
3738
        longjmp(pOperator->pTaskInfo->env, TSDB_CODE_OUT_OF_MEMORY);
L
Liu Jicong 已提交
3739
      } else {
wmmhello's avatar
wmmhello 已提交
3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751
        *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);
3752
    memcpy(*result + offset, pRow, pSup->resultRowSize);
wmmhello's avatar
wmmhello 已提交
3753 3754 3755 3756 3757
    offset += pSup->resultRowSize;

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

L
Liu Jicong 已提交
3758
  if (length) {
wmmhello's avatar
wmmhello 已提交
3759 3760 3761 3762 3763
    *length = offset;
  }
  return;
}

dengyihao's avatar
dengyihao 已提交
3764 3765
bool aggDecodeResultRow(SOperatorInfo* pOperator, SAggSupporter* pSup, SOptrBasicInfo* pInfo, char* result,
                        int32_t length) {
L
Liu Jicong 已提交
3766
  if (!result || length <= 0) {
wmmhello's avatar
wmmhello 已提交
3767 3768 3769 3770 3771 3772 3773
    return false;
  }

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

  int32_t offset = sizeof(int32_t);
L
Liu Jicong 已提交
3774
  while (count-- > 0 && length > offset) {
wmmhello's avatar
wmmhello 已提交
3775 3776 3777
    int32_t keyLen = *(int32_t*)(result + offset);
    offset += sizeof(int32_t);

L
Liu Jicong 已提交
3778 3779 3780
    uint64_t    tableGroupId = *(uint64_t*)(result + offset);
    SResultRow* resultRow = getNewResultRow_rv(pSup->pResultBuf, tableGroupId, pSup->resultRowSize);
    if (!resultRow) {
3781
      longjmp(pOperator->pTaskInfo->env, TSDB_CODE_TSC_INVALID_INPUT);
wmmhello's avatar
wmmhello 已提交
3782
    }
3783

wmmhello's avatar
wmmhello 已提交
3784
    // add a new result set for a new group
3785 3786
    SResultRowPosition pos = {.pageId = resultRow->pageId, .offset = resultRow->offset};
    taosHashPut(pSup->pResultRowHashTable, result + offset, keyLen, &pos, sizeof(SResultRowPosition));
wmmhello's avatar
wmmhello 已提交
3787 3788 3789

    offset += keyLen;
    int32_t valueLen = *(int32_t*)(result + offset);
L
Liu Jicong 已提交
3790
    if (valueLen != pSup->resultRowSize) {
3791
      longjmp(pOperator->pTaskInfo->env, TSDB_CODE_TSC_INVALID_INPUT);
wmmhello's avatar
wmmhello 已提交
3792 3793 3794 3795 3796 3797 3798 3799 3800 3801
    }
    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);
3802
    prepareResultListBuffer(&pInfo->resultRowInfo, pOperator->pTaskInfo->env);
dengyihao's avatar
dengyihao 已提交
3803
    //    pInfo->resultRowInfo.cur = pInfo->resultRowInfo.size;
L
Liu Jicong 已提交
3804 3805
    //    pInfo->resultRowInfo.pPosition[pInfo->resultRowInfo.size++] =
    //        (SResultRowPosition){.pageId = resultRow->pageId, .offset = resultRow->offset};
dengyihao's avatar
dengyihao 已提交
3806
    pInfo->resultRowInfo.cur = (SResultRowPosition){.pageId = resultRow->pageId, .offset = resultRow->offset};
wmmhello's avatar
wmmhello 已提交
3807 3808
  }

L
Liu Jicong 已提交
3809
  if (offset != length) {
3810
    longjmp(pOperator->pTaskInfo->env, TSDB_CODE_TSC_INVALID_INPUT);
wmmhello's avatar
wmmhello 已提交
3811 3812 3813 3814
  }
  return true;
}

3815 3816
enum {
  PROJECT_RETRIEVE_CONTINUE = 0x1,
L
Liu Jicong 已提交
3817
  PROJECT_RETRIEVE_DONE = 0x2,
3818 3819 3820 3821 3822
};

static int32_t handleLimitOffset(SOperatorInfo* pOperator, SSDataBlock* pBlock) {
  SProjectOperatorInfo* pProjectInfo = pOperator->info;
  SOptrBasicInfo*       pInfo = &pProjectInfo->binfo;
L
Liu Jicong 已提交
3823
  SSDataBlock*          pRes = pInfo->pRes;
3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871

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

3872 3873 3874
  // 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);
3875 3876 3877 3878 3879

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

3880
    return PROJECT_RETRIEVE_DONE;
3881
  }
3882

3883
  // todo optimize performance
3884 3885
  // 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 已提交
3886 3887
  if (pRes->info.rows >= pOperator->resultInfo.threshold || pProjectInfo->slimit.offset != -1 ||
      pProjectInfo->slimit.limit != -1) {
3888
    return PROJECT_RETRIEVE_DONE;
L
Liu Jicong 已提交
3889
  } else {  // not full enough, continue to accumulate the output data in the buffer.
3890 3891 3892 3893
    return PROJECT_RETRIEVE_CONTINUE;
  }
}

3894
static SSDataBlock* doProjectOperation(SOperatorInfo* pOperator) {
3895
  SProjectOperatorInfo* pProjectInfo = pOperator->info;
L
Liu Jicong 已提交
3896
  SOptrBasicInfo*       pInfo = &pProjectInfo->binfo;
3897 3898

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

3901
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
3902 3903 3904
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }
dengyihao's avatar
dengyihao 已提交
3905

H
Haojun Liao 已提交
3906
#if 0
3907 3908 3909 3910 3911
  if (pProjectInfo->existDataBlock) {  // TODO refactor
    SSDataBlock* pBlock = pProjectInfo->existDataBlock;
    pProjectInfo->existDataBlock = NULL;

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

H
Haojun Liao 已提交
3914
    blockDataEnsureCapacity(pInfo->pRes, pBlock->info.rows);
3915
    projectApplyFunctions(pOperator->pExpr, pInfo->pRes, pBlock, pInfo->pCtx, pOperator->numOfExprs);
L
Liu Jicong 已提交
3916
    if (pRes->info.rows >= pProjectInfo->binfo.capacity * 0.8) {
3917 3918
      copyTsColoum(pRes, pInfo->pCtx, pOperator->numOfExprs);
      resetResultRowEntryResult(pInfo->pCtx, pOperator->numOfExprs);
3919 3920 3921
      return pRes;
    }
  }
H
Haojun Liao 已提交
3922
#endif
3923

3924 3925 3926
  int32_t order = 0;
  int32_t scanFlag = 0;

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

L
Liu Jicong 已提交
3929
  while (1) {
H
Haojun Liao 已提交
3930
    // The downstream exec may change the value of the newgroup, so use a local variable instead.
H
Haojun Liao 已提交
3931
    publishOperatorProfEvent(downstream, QUERY_PROF_BEFORE_OPERATOR_EXEC);
3932
    SSDataBlock* pBlock = downstream->fpSet.getNextFn(downstream);
H
Haojun Liao 已提交
3933
    publishOperatorProfEvent(downstream, QUERY_PROF_AFTER_OPERATOR_EXEC);
3934 3935

    if (pBlock == NULL) {
3936
      setTaskStatus(pOperator->pTaskInfo, TASK_COMPLETED);
3937 3938 3939 3940
      break;
    }

    // Return result of the previous group in the firstly.
3941
    if (false) {
3942 3943 3944
      if (pRes->info.rows > 0) {
        pProjectInfo->existDataBlock = pBlock;
        break;
L
Liu Jicong 已提交
3945
      } else {  // init output buffer for a new group data
3946
        initCtxOutputBuffer(pInfo->pCtx, pOperator->numOfExprs);
3947 3948 3949 3950
      }
    }

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

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

3956 3957 3958
    code = projectApplyFunctions(pOperator->pExpr, pInfo->pRes, pBlock, pInfo->pCtx, pOperator->numOfExprs, pProjectInfo->pPseudoColInfo);
    if (code != TSDB_CODE_SUCCESS) {
      longjmp(pTaskInfo->env, code);
3959 3960
    }

3961 3962
    int32_t status = handleLimitOffset(pOperator, pBlock);
    if (status == PROJECT_RETRIEVE_CONTINUE) {
H
Haojun Liao 已提交
3963
      continue;
L
Liu Jicong 已提交
3964
    } else if (status == PROJECT_RETRIEVE_DONE) {
3965 3966 3967
      break;
    }
  }
dengyihao's avatar
dengyihao 已提交
3968

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

3971
  //  copyTsColoum(pRes, pInfo->pCtx, pOperator->numOfExprs);
L
Liu Jicong 已提交
3972
  return (pInfo->pRes->info.rows > 0) ? pInfo->pRes : NULL;
3973 3974
}

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

L
Liu Jicong 已提交
3979 3980
  int64_t ekey = Q_STATUS_EQUAL(pTaskInfo->status, TASK_COMPLETED) ? pTaskInfo->window.ekey
                                                                   : pInfo->existNewGroupBlock->info.window.ekey;
3981 3982
  taosResetFillInfo(pInfo->pFillInfo, getFillInfoStart(pInfo->pFillInfo));

3983
  taosFillSetStartInfo(pInfo->pFillInfo, pInfo->existNewGroupBlock->info.rows, ekey);
3984 3985
  taosFillSetInputDataBlock(pInfo->pFillInfo, pInfo->existNewGroupBlock);

3986
  doFillTimeIntervalGapsInResults(pInfo->pFillInfo, pInfo->pRes, pResultInfo->capacity);
3987 3988 3989 3990
  pInfo->existNewGroupBlock = NULL;
  *newgroup = true;
}

L
Liu Jicong 已提交
3991 3992
static void doHandleRemainBlockFromNewGroup(SFillOperatorInfo* pInfo, SResultInfo* pResultInfo, bool* newgroup,
                                            SExecTaskInfo* pTaskInfo) {
3993 3994
  if (taosFillHasMoreResults(pInfo->pFillInfo)) {
    *newgroup = false;
3995
    doFillTimeIntervalGapsInResults(pInfo->pFillInfo, pInfo->pRes, (int32_t)pResultInfo->capacity);
H
Haojun Liao 已提交
3996
    if (pInfo->pRes->info.rows > pResultInfo->threshold || (!pInfo->multigroupResult)) {
3997 3998 3999 4000 4001 4002
      return;
    }
  }

  // handle the cached new group data block
  if (pInfo->existNewGroupBlock) {
4003
    doHandleRemainBlockForNewGroupImpl(pInfo, pResultInfo, newgroup, pTaskInfo);
4004 4005 4006
  }
}

4007
static SSDataBlock* doFill(SOperatorInfo* pOperator) {
L
Liu Jicong 已提交
4008 4009
  SFillOperatorInfo* pInfo = pOperator->info;
  SExecTaskInfo*     pTaskInfo = pOperator->pTaskInfo;
4010

H
Haojun Liao 已提交
4011
  SResultInfo* pResultInfo = &pOperator->resultInfo;
4012 4013 4014
  SSDataBlock* pResBlock = pInfo->pRes;

  blockDataCleanup(pResBlock);
4015 4016 4017 4018
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

4019
  // todo handle different group data interpolation
X
Xiaoyu Wang 已提交
4020 4021
  bool  n = false;
  bool* newgroup = &n;
4022
  doHandleRemainBlockFromNewGroup(pInfo, pResultInfo, newgroup, pTaskInfo);
4023 4024
  if (pResBlock->info.rows > pResultInfo->threshold || (!pInfo->multigroupResult && pResBlock->info.rows > 0)) {
    return pResBlock;
H
Haojun Liao 已提交
4025
  }
4026

H
Haojun Liao 已提交
4027
  SOperatorInfo* pDownstream = pOperator->pDownstream[0];
L
Liu Jicong 已提交
4028
  while (1) {
H
Haojun Liao 已提交
4029
    publishOperatorProfEvent(pDownstream, QUERY_PROF_BEFORE_OPERATOR_EXEC);
4030
    SSDataBlock* pBlock = pDownstream->fpSet.getNextFn(pDownstream);
H
Haojun Liao 已提交
4031
    publishOperatorProfEvent(pDownstream, QUERY_PROF_AFTER_OPERATOR_EXEC);
4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042

    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
4043
      taosFillSetStartInfo(pInfo->pFillInfo, 0, pTaskInfo->window.ekey);
4044 4045 4046 4047 4048 4049 4050
    } else {
      if (pBlock == NULL) {
        if (pInfo->totalInputRows == 0) {
          pOperator->status = OP_EXEC_DONE;
          return NULL;
        }

4051
        taosFillSetStartInfo(pInfo->pFillInfo, 0, pTaskInfo->window.ekey);
4052 4053 4054 4055 4056 4057 4058
      } else {
        pInfo->totalInputRows += pBlock->info.rows;
        taosFillSetStartInfo(pInfo->pFillInfo, pBlock->info.rows, pBlock->info.window.ekey);
        taosFillSetInputDataBlock(pInfo->pFillInfo, pBlock);
      }
    }

4059 4060
    blockDataEnsureCapacity(pResBlock, pOperator->resultInfo.capacity);
    doFillTimeIntervalGapsInResults(pInfo->pFillInfo, pResBlock, pOperator->resultInfo.capacity);
4061 4062

    // current group has no more result to return
4063
    if (pResBlock->info.rows > 0) {
4064 4065
      // 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
4066 4067
      if (pResBlock->info.rows > pResultInfo->threshold || pBlock == NULL || (!pInfo->multigroupResult)) {
        return pResBlock;
4068 4069
      }

4070
      doHandleRemainBlockFromNewGroup(pInfo, pResultInfo, newgroup, pTaskInfo);
4071 4072
      if (pResBlock->info.rows > pOperator->resultInfo.threshold || pBlock == NULL) {
        return pResBlock;
4073 4074 4075
      }
    } else if (pInfo->existNewGroupBlock) {  // try next group
      assert(pBlock != NULL);
4076
      doHandleRemainBlockForNewGroupImpl(pInfo, pResultInfo, newgroup, pTaskInfo);
4077 4078
      if (pResBlock->info.rows > pResultInfo->threshold) {
        return pResBlock;
4079 4080 4081 4082 4083 4084 4085 4086
      }
    } else {
      return NULL;
    }
  }
}

// todo set the attribute of query scan count
H
Haojun Liao 已提交
4087
static int32_t getNumOfScanTimes(STaskAttr* pQueryAttr) {
L
Liu Jicong 已提交
4088
  for (int32_t i = 0; i < pQueryAttr->numOfOutput; ++i) {
4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102
    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;
  }

4103
  if (pOperator->fpSet.closeFn != NULL) {
4104
    pOperator->fpSet.closeFn(pOperator->info, pOperator->numOfExprs);
4105 4106
  }

H
Haojun Liao 已提交
4107
  if (pOperator->pDownstream != NULL) {
L
Liu Jicong 已提交
4108
    for (int32_t i = 0; i < pOperator->numOfDownstream; ++i) {
H
Haojun Liao 已提交
4109
      destroyOperatorInfo(pOperator->pDownstream[i]);
4110 4111
    }

wafwerar's avatar
wafwerar 已提交
4112
    taosMemoryFreeClear(pOperator->pDownstream);
H
Haojun Liao 已提交
4113
    pOperator->numOfDownstream = 0;
4114 4115
  }

H
Haojun Liao 已提交
4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126
  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 已提交
4127
  taosMemoryFreeClear(pOperator->pExpr);
wafwerar's avatar
wafwerar 已提交
4128 4129
  taosMemoryFreeClear(pOperator->info);
  taosMemoryFreeClear(pOperator);
4130 4131
}

dengyihao's avatar
dengyihao 已提交
4132 4133
int32_t doInitAggInfoSup(SAggSupporter* pAggSup, SqlFunctionCtx* pCtx, int32_t numOfOutput, size_t keyBufSize,
                         const char* pKey) {
4134 4135
  _hash_fn_t hashFn = taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY);

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

H
Haojun Liao 已提交
4140
  if (pAggSup->keyBuf == NULL || pAggSup->pResultRowHashTable == NULL) {
4141 4142 4143
    return TSDB_CODE_OUT_OF_MEMORY;
  }

H
Haojun Liao 已提交
4144
  uint32_t defaultPgsz = 4096;
X
Xiaoyu Wang 已提交
4145
  while (defaultPgsz < pAggSup->resultRowSize * 4) {
H
Haojun Liao 已提交
4146 4147 4148 4149 4150 4151 4152 4153 4154 4155
    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 已提交
4156 4157 4158 4159
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

4160 4161 4162
  return TSDB_CODE_SUCCESS;
}

4163
void cleanupAggSup(SAggSupporter* pAggSup) {
wafwerar's avatar
wafwerar 已提交
4164
  taosMemoryFreeClear(pAggSup->keyBuf);
4165
  taosHashCleanup(pAggSup->pResultRowHashTable);
H
Haojun Liao 已提交
4166
  destroyDiskbasedBuf(pAggSup->pResultBuf);
4167 4168
}

H
Haojun Liao 已提交
4169
int32_t initAggInfo(SOptrBasicInfo* pBasicInfo, SAggSupporter* pAggSup, SExprInfo* pExprInfo, int32_t numOfCols,
4170
                    SSDataBlock* pResultBlock, size_t keyBufSize, const char* pkey) {
4171
  pBasicInfo->pCtx = createSqlFunctionCtx(pExprInfo, numOfCols, &pBasicInfo->rowCellInfoOffset);
H
Haojun Liao 已提交
4172 4173
  pBasicInfo->pRes = pResultBlock;

4174
  doInitAggInfoSup(pAggSup, pBasicInfo->pCtx, numOfCols, keyBufSize, pkey);
4175

L
Liu Jicong 已提交
4176
  for (int32_t i = 0; i < numOfCols; ++i) {
4177 4178 4179
    pBasicInfo->pCtx[i].pBuf = pAggSup->pResultBuf;
  }

4180
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
4181 4182
}

4183 4184 4185 4186 4187 4188 4189 4190 4191
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 已提交
4192
static STableQueryInfo* initTableQueryInfo(const STableGroupInfo* pTableGroupInfo) {
L
Liu Jicong 已提交
4193 4194 4195 4196
  if (pTableGroupInfo->numOfTables == 0) {
    return NULL;
  }

wafwerar's avatar
wafwerar 已提交
4197
  STableQueryInfo* pTableQueryInfo = taosMemoryCalloc(pTableGroupInfo->numOfTables, sizeof(STableQueryInfo));
H
Haojun Liao 已提交
4198 4199
  if (pTableQueryInfo == NULL) {
    return NULL;
H
Haojun Liao 已提交
4200
  }
H
Haojun Liao 已提交
4201 4202

  int32_t index = 0;
L
Liu Jicong 已提交
4203
  for (int32_t i = 0; i < taosArrayGetSize(pTableGroupInfo->pGroupList); ++i) {
H
Haojun Liao 已提交
4204
    SArray* pa = taosArrayGetP(pTableGroupInfo->pGroupList, i);
L
Liu Jicong 已提交
4205
    for (int32_t j = 0; j < taosArrayGetSize(pa); ++j) {
H
Haojun Liao 已提交
4206
      STableKeyInfo* pk = taosArrayGet(pa, j);
H
Haojun Liao 已提交
4207
      STableQueryInfo* pTQueryInfo = &pTableQueryInfo[index++];
L
Liu Jicong 已提交
4208
      pTQueryInfo->lastKey = pk->lastKey;
H
Haojun Liao 已提交
4209 4210
    }
  }
H
Haojun Liao 已提交
4211 4212

  STimeWindow win = {0, INT64_MAX};
4213
  createTableQueryInfo(pTableQueryInfo, win);
H
Haojun Liao 已提交
4214
  return pTableQueryInfo;
H
Haojun Liao 已提交
4215 4216
}

L
Liu Jicong 已提交
4217
SOperatorInfo* createAggregateOperatorInfo(SOperatorInfo* downstream, SExprInfo* pExprInfo, int32_t numOfCols,
4218
                                           SSDataBlock* pResultBlock, SExprInfo* pScalarExprInfo,
L
Liu Jicong 已提交
4219 4220
                                           int32_t numOfScalarExpr, SExecTaskInfo* pTaskInfo,
                                           const STableGroupInfo* pTableGroupInfo) {
wafwerar's avatar
wafwerar 已提交
4221
  SAggOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SAggOperatorInfo));
L
Liu Jicong 已提交
4222
  SOperatorInfo*    pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
4223 4224 4225
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }
H
Haojun Liao 已提交
4226

4227
  int32_t numOfRows = 1024;
dengyihao's avatar
dengyihao 已提交
4228
  size_t  keyBufSize = sizeof(int64_t) + sizeof(int64_t) + POINTER_BYTES;
4229 4230

  initResultSizeInfo(pOperator, numOfRows);
dengyihao's avatar
dengyihao 已提交
4231 4232
  int32_t code =
      initAggInfo(&pInfo->binfo, &pInfo->aggSup, pExprInfo, numOfCols, pResultBlock, keyBufSize, pTaskInfo->id.str);
H
Haojun Liao 已提交
4233
  pInfo->pTableQueryInfo = initTableQueryInfo(pTableGroupInfo);
L
Liu Jicong 已提交
4234
  if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
4235 4236
    goto _error;
  }
H
Haojun Liao 已提交
4237

H
Haojun Liao 已提交
4238 4239 4240 4241
  int32_t numOfGroup = 10;  // todo replaced with true value
  pInfo->groupId = INT32_MIN;
  initResultRowInfo(&pInfo->binfo.resultRowInfo, numOfGroup);

4242 4243
  pInfo->pScalarExprInfo = pScalarExprInfo;
  pInfo->numOfScalarExpr = numOfScalarExpr;
4244 4245 4246
  if (pInfo->pScalarExprInfo != NULL) {
    pInfo->pScalarCtx = createSqlFunctionCtx(pScalarExprInfo, numOfCols, &pInfo->rowCellInfoOffset);
  }
4247

dengyihao's avatar
dengyihao 已提交
4248
  pOperator->name = "TableAggregate";
X
Xiaoyu Wang 已提交
4249
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_AGG;
4250
  pOperator->blocking = true;
dengyihao's avatar
dengyihao 已提交
4251 4252 4253
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
  pOperator->pExpr = pExprInfo;
4254
  pOperator->numOfExprs = numOfCols;
dengyihao's avatar
dengyihao 已提交
4255
  pOperator->pTaskInfo = pTaskInfo;
H
Haojun Liao 已提交
4256

4257 4258
  pOperator->fpSet = createOperatorFpSet(doOpenAggregateOptr, getAggregateResult, NULL, NULL, destroyAggOperatorInfo,
                                         aggEncodeResultRow, aggDecodeResultRow, NULL);
H
Haojun Liao 已提交
4259 4260 4261 4262 4263

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

  return pOperator;
L
Liu Jicong 已提交
4266
_error:
H
Haojun Liao 已提交
4267
  destroyAggOperatorInfo(pInfo, numOfCols);
wafwerar's avatar
wafwerar 已提交
4268 4269
  taosMemoryFreeClear(pInfo);
  taosMemoryFreeClear(pOperator);
H
Haojun Liao 已提交
4270 4271
  pTaskInfo->code = TSDB_CODE_OUT_OF_MEMORY;
  return NULL;
4272 4273
}

H
Haojun Liao 已提交
4274
void doDestroyBasicInfo(SOptrBasicInfo* pInfo, int32_t numOfOutput) {
4275 4276
  assert(pInfo != NULL);

4277
  destroySqlFunctionCtx(pInfo->pCtx, numOfOutput);
wafwerar's avatar
wafwerar 已提交
4278
  taosMemoryFreeClear(pInfo->rowCellInfoOffset);
4279 4280

  cleanupResultRowInfo(&pInfo->resultRowInfo);
H
Haojun Liao 已提交
4281
  pInfo->pRes = blockDataDestroy(pInfo->pRes);
4282 4283
}

H
Haojun Liao 已提交
4284
void destroyBasicOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
4285
  SOptrBasicInfo* pInfo = (SOptrBasicInfo*)param;
4286 4287
  doDestroyBasicInfo(pInfo, numOfOutput);
}
H
Haojun Liao 已提交
4288 4289

void destroyAggOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
4290
  SAggOperatorInfo* pInfo = (SAggOperatorInfo*)param;
4291 4292
  doDestroyBasicInfo(&pInfo->binfo, numOfOutput);
}
4293

H
Haojun Liao 已提交
4294
void destroySFillOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
4295
  SFillOperatorInfo* pInfo = (SFillOperatorInfo*)param;
4296
  pInfo->pFillInfo = taosDestroyFillInfo(pInfo->pFillInfo);
H
Haojun Liao 已提交
4297
  pInfo->pRes = blockDataDestroy(pInfo->pRes);
wafwerar's avatar
wafwerar 已提交
4298
  taosMemoryFreeClear(pInfo->p);
4299 4300
}

H
Haojun Liao 已提交
4301
static void destroyProjectOperatorInfo(void* param, int32_t numOfOutput) {
D
fix bug  
dapan 已提交
4302 4303 4304
  if (NULL == param) {
    return;
  }
L
Liu Jicong 已提交
4305
  SProjectOperatorInfo* pInfo = (SProjectOperatorInfo*)param;
4306
  doDestroyBasicInfo(&pInfo->binfo, numOfOutput);
H
Haojun Liao 已提交
4307
  cleanupAggSup(&pInfo->aggSup);
H
Haojun Liao 已提交
4308
  taosArrayDestroy(pInfo->pPseudoColInfo);
4309 4310
}

H
Haojun Liao 已提交
4311
void destroyExchangeOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
4312
  SExchangeInfo* pExInfo = (SExchangeInfo*)param;
H
Haojun Liao 已提交
4313 4314 4315 4316 4317 4318 4319 4320 4321
  taosArrayDestroy(pExInfo->pSources);
  taosArrayDestroy(pExInfo->pSourceDataInfo);
  if (pExInfo->pResult != NULL) {
    blockDataDestroy(pExInfo->pResult);
  }

  tsem_destroy(&pExInfo->ready);
}

H
Haojun Liao 已提交
4322 4323
static SArray* setRowTsColumnOutputInfo(SqlFunctionCtx* pCtx, int32_t numOfCols) {
  SArray* pList = taosArrayInit(4, sizeof(int32_t));
dengyihao's avatar
dengyihao 已提交
4324
  for (int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
4325 4326 4327 4328 4329 4330 4331 4332
    if (fmIsPseudoColumnFunc(pCtx[i].functionId)) {
      taosArrayPush(pList, &i);
    }
  }

  return pList;
}

L
Liu Jicong 已提交
4333
SOperatorInfo* createProjectOperatorInfo(SOperatorInfo* downstream, SExprInfo* pExprInfo, int32_t num,
dengyihao's avatar
dengyihao 已提交
4334 4335
                                         SSDataBlock* pResBlock, SLimit* pLimit, SLimit* pSlimit,
                                         SExecTaskInfo* pTaskInfo) {
wafwerar's avatar
wafwerar 已提交
4336
  SProjectOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SProjectOperatorInfo));
L
Liu Jicong 已提交
4337
  SOperatorInfo*        pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
4338 4339 4340
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }
4341

4342 4343 4344
  pInfo->limit      = *pLimit;
  pInfo->slimit     = *pSlimit;
  pInfo->curOffset  = pLimit->offset;
H
Haojun Liao 已提交
4345 4346
  pInfo->curSOffset = pSlimit->offset;

H
Haojun Liao 已提交
4347
  pInfo->binfo.pRes = pResBlock;
H
Haojun Liao 已提交
4348 4349 4350

  int32_t numOfCols = num;
  int32_t numOfRows = 4096;
dengyihao's avatar
dengyihao 已提交
4351
  size_t  keyBufSize = sizeof(int64_t) + sizeof(int64_t) + POINTER_BYTES;
4352 4353 4354

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

dengyihao's avatar
dengyihao 已提交
4358
  pOperator->name = "ProjectOperator";
H
Haojun Liao 已提交
4359
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_PROJECT;
4360
  pOperator->blocking = false;
dengyihao's avatar
dengyihao 已提交
4361 4362 4363
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
  pOperator->pExpr = pExprInfo;
4364
  pOperator->numOfExprs = num;
4365

L
Liu Jicong 已提交
4366 4367
  pOperator->fpSet = createOperatorFpSet(operatorDummyOpenFn, doProjectOperation, NULL, NULL,
                                         destroyProjectOperatorInfo, NULL, NULL, NULL);
L
Liu Jicong 已提交
4368 4369

  pOperator->pTaskInfo = pTaskInfo;
4370
  int32_t code = appendDownstream(pOperator, &downstream, 1);
H
Haojun Liao 已提交
4371
  if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
4372 4373
    goto _error;
  }
4374 4375

  return pOperator;
H
Haojun Liao 已提交
4376

L
Liu Jicong 已提交
4377
_error:
H
Haojun Liao 已提交
4378 4379
  pTaskInfo->code = TSDB_CODE_OUT_OF_MEMORY;
  return NULL;
4380 4381
}

4382
static int32_t initFillInfo(SFillOperatorInfo* pInfo, SExprInfo* pExpr, int32_t numOfCols, SNodeListNode* pValNode,
L
Liu Jicong 已提交
4383
                            STimeWindow win, int32_t capacity, const char* id, SInterval* pInterval, int32_t fillType) {
4384
  SFillColInfo* pColInfo = createFillColInfo(pExpr, numOfCols, pValNode);
H
Haojun Liao 已提交
4385 4386

  STimeWindow w = TSWINDOW_INITIALIZER;
4387
  getAlignQueryTimeWindow(pInterval, pInterval->precision, win.skey, &w);
H
Haojun Liao 已提交
4388 4389

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

wafwerar's avatar
wafwerar 已提交
4392
  pInfo->p = taosMemoryCalloc(numOfCols, POINTER_BYTES);
H
Haojun Liao 已提交
4393 4394 4395 4396 4397 4398 4399
  if (pInfo->pFillInfo == NULL || pInfo->p == NULL) {
    return TSDB_CODE_OUT_OF_MEMORY;
  } else {
    return TSDB_CODE_SUCCESS;
  }
}

L
Liu Jicong 已提交
4400
SOperatorInfo* createFillOperatorInfo(SOperatorInfo* downstream, SExprInfo* pExpr, int32_t numOfCols,
X
Xiaoyu Wang 已提交
4401 4402 4403
                                      SInterval* pInterval, STimeWindow* pWindow, SSDataBlock* pResBlock,
                                      int32_t fillType, SNodeListNode* pValueNode, bool multigroupResult,
                                      SExecTaskInfo* pTaskInfo) {
wafwerar's avatar
wafwerar 已提交
4404
  SFillOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SFillOperatorInfo));
L
Liu Jicong 已提交
4405
  SOperatorInfo*     pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
4406

L
Liu Jicong 已提交
4407
  pInfo->pRes = pResBlock;
4408 4409
  pInfo->multigroupResult = multigroupResult;

4410 4411
  int32_t type = TSDB_FILL_NONE;
  switch (fillType) {
dengyihao's avatar
dengyihao 已提交
4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429
    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;
4430 4431 4432 4433
    default:
      type = TSDB_FILL_NONE;
  }

H
Haojun Liao 已提交
4434
  SResultInfo* pResultInfo = &pOperator->resultInfo;
4435 4436
  initResultSizeInfo(pOperator, 4096);

X
Xiaoyu Wang 已提交
4437 4438
  int32_t code = initFillInfo(pInfo, pExpr, numOfCols, pValueNode, *pWindow, pResultInfo->capacity, pTaskInfo->id.str,
                              pInterval, type);
4439 4440 4441
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
4442

dengyihao's avatar
dengyihao 已提交
4443
  pOperator->name = "FillOperator";
4444
  pOperator->blocking = false;
dengyihao's avatar
dengyihao 已提交
4445
  pOperator->status = OP_NOT_OPENED;
4446
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_FILL;
dengyihao's avatar
dengyihao 已提交
4447
  pOperator->pExpr = pExpr;
4448
  pOperator->numOfExprs = numOfCols;
dengyihao's avatar
dengyihao 已提交
4449
  pOperator->info = pInfo;
H
Haojun Liao 已提交
4450

L
Liu Jicong 已提交
4451 4452
  pOperator->fpSet =
      createOperatorFpSet(operatorDummyOpenFn, doFill, NULL, NULL, destroySFillOperatorInfo, NULL, NULL, NULL);
4453
  pOperator->pTaskInfo = pTaskInfo;
4454
  code = appendDownstream(pOperator, &downstream, 1);
4455
  return pOperator;
H
Haojun Liao 已提交
4456

L
Liu Jicong 已提交
4457
_error:
wafwerar's avatar
wafwerar 已提交
4458 4459
  taosMemoryFreeClear(pOperator);
  taosMemoryFreeClear(pInfo);
H
Haojun Liao 已提交
4460
  return NULL;
4461 4462
}

L
Liu Jicong 已提交
4463 4464
static SResSchema createResSchema(int32_t type, int32_t bytes, int32_t slotId, int32_t scale, int32_t precision,
                                  const char* name) {
H
Haojun Liao 已提交
4465
  SResSchema s = {0};
dengyihao's avatar
dengyihao 已提交
4466 4467 4468 4469
  s.scale = scale;
  s.type = type;
  s.bytes = bytes;
  s.slotId = slotId;
H
Haojun Liao 已提交
4470
  s.precision = precision;
H
Haojun Liao 已提交
4471 4472 4473 4474
  strncpy(s.name, name, tListLen(s.name));

  return s;
}
H
Haojun Liao 已提交
4475

4476
static SColumn* createColumn(int32_t blockId, int32_t slotId, int32_t colId, SDataType* pType) {
H
Haojun Liao 已提交
4477 4478 4479 4480 4481 4482
  SColumn* pCol = taosMemoryCalloc(1, sizeof(SColumn));
  if (pCol == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

dengyihao's avatar
dengyihao 已提交
4483
  pCol->slotId = slotId;
4484 4485 4486 4487
  pCol->colId  = colId;
  pCol->bytes  = pType->bytes;
  pCol->type   = pType->type;
  pCol->scale  = pType->scale;
dengyihao's avatar
dengyihao 已提交
4488
  pCol->precision = pType->precision;
H
Haojun Liao 已提交
4489 4490 4491 4492 4493
  pCol->dataBlockId = blockId;

  return pCol;
}

H
Haojun Liao 已提交
4494
SExprInfo* createExprInfo(SNodeList* pNodeList, SNodeList* pGroupKeys, int32_t* numOfExprs) {
H
Haojun Liao 已提交
4495
  int32_t numOfFuncs = LIST_LENGTH(pNodeList);
H
Haojun Liao 已提交
4496 4497 4498 4499
  int32_t numOfGroupKeys = 0;
  if (pGroupKeys != NULL) {
    numOfGroupKeys = LIST_LENGTH(pGroupKeys);
  }
H
Haojun Liao 已提交
4500

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

L
Liu Jicong 已提交
4504
  for (int32_t i = 0; i < (*numOfExprs); ++i) {
H
Haojun Liao 已提交
4505 4506 4507 4508 4509 4510
    STargetNode* pTargetNode = NULL;
    if (i < numOfFuncs) {
      pTargetNode = (STargetNode*)nodesListGetNode(pNodeList, i);
    } else {
      pTargetNode = (STargetNode*)nodesListGetNode(pGroupKeys, i - numOfFuncs);
    }
H
Haojun Liao 已提交
4511

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

wafwerar's avatar
wafwerar 已提交
4514
    pExp->pExpr = taosMemoryCalloc(1, sizeof(tExprNode));
H
Haojun Liao 已提交
4515
    pExp->pExpr->_function.num = 1;
H
Haojun Liao 已提交
4516
    pExp->pExpr->_function.functionId = -1;
H
Haojun Liao 已提交
4517

4518
    int32_t type = nodeType(pTargetNode->pExpr);
H
Haojun Liao 已提交
4519
    // it is a project query, or group by column
4520
    if (type == QUERY_NODE_COLUMN) {
H
Haojun Liao 已提交
4521
      pExp->pExpr->nodeType = QUERY_NODE_COLUMN;
L
Liu Jicong 已提交
4522
      SColumnNode* pColNode = (SColumnNode*)pTargetNode->pExpr;
H
Haojun Liao 已提交
4523

G
Ganlin Zhao 已提交
4524 4525 4526
      pExp->base.pParam = taosMemoryCalloc(1, sizeof(SFunctParam));
      pExp->base.numOfParams = 1;

H
Haojun Liao 已提交
4527
      SDataType* pType = &pColNode->node.resType;
dengyihao's avatar
dengyihao 已提交
4528 4529
      pExp->base.resSchema = createResSchema(pType->type, pType->bytes, pTargetNode->slotId, pType->scale,
                                             pType->precision, pColNode->colName);
4530
      pExp->base.pParam[0].pCol = createColumn(pColNode->dataBlockId, pColNode->slotId, pColNode->colId, pType);
H
Haojun Liao 已提交
4531
      pExp->base.pParam[0].type = FUNC_PARAM_TYPE_COLUMN;
4532
    } else if (type == QUERY_NODE_VALUE) {
4533 4534 4535 4536 4537 4538 4539
      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 已提交
4540 4541
      pExp->base.resSchema = createResSchema(pType->type, pType->bytes, pTargetNode->slotId, pType->scale,
                                             pType->precision, pValNode->node.aliasName);
4542 4543
      pExp->base.pParam[0].type = FUNC_PARAM_TYPE_VALUE;
      valueNodeToVariant(pValNode, &pExp->base.pParam[0].param);
4544
    } else if (type == QUERY_NODE_FUNCTION) {
H
Haojun Liao 已提交
4545
      pExp->pExpr->nodeType = QUERY_NODE_FUNCTION;
H
Haojun Liao 已提交
4546 4547 4548
      SFunctionNode* pFuncNode = (SFunctionNode*)pTargetNode->pExpr;

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

H
Haojun Liao 已提交
4552
      pExp->pExpr->_function.functionId = pFuncNode->funcId;
H
Haojun Liao 已提交
4553
      pExp->pExpr->_function.pFunctNode = pFuncNode;
4554

dengyihao's avatar
dengyihao 已提交
4555 4556
      strncpy(pExp->pExpr->_function.functionName, pFuncNode->functionName,
              tListLen(pExp->pExpr->_function.functionName));
4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569
#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 已提交
4570 4571

      int32_t numOfParam = LIST_LENGTH(pFuncNode->pParameterList);
G
Ganlin Zhao 已提交
4572 4573 4574 4575

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

H
Haojun Liao 已提交
4576
      for (int32_t j = 0; j < numOfParam; ++j) {
4577
        SNode* p1 = nodesListGetNode(pFuncNode->pParameterList, j);
G
Ganlin Zhao 已提交
4578
        if (p1->type == QUERY_NODE_COLUMN) {
dengyihao's avatar
dengyihao 已提交
4579
          SColumnNode* pcn = (SColumnNode*)p1;
G
Ganlin Zhao 已提交
4580 4581

          pExp->base.pParam[j].type = FUNC_PARAM_TYPE_COLUMN;
4582
          pExp->base.pParam[j].pCol = createColumn(pcn->dataBlockId, pcn->slotId, pcn->colId, &pcn->node.resType);
G
Ganlin Zhao 已提交
4583 4584 4585
        } else if (p1->type == QUERY_NODE_VALUE) {
          SValueNode* pvn = (SValueNode*)p1;
          pExp->base.pParam[j].type = FUNC_PARAM_TYPE_VALUE;
4586
          valueNodeToVariant(pvn, &pExp->base.pParam[j].param);
G
Ganlin Zhao 已提交
4587
        }
H
Haojun Liao 已提交
4588
      }
4589
    } else if (type == QUERY_NODE_OPERATOR) {
H
Haojun Liao 已提交
4590
      pExp->pExpr->nodeType = QUERY_NODE_OPERATOR;
L
Liu Jicong 已提交
4591
      SOperatorNode* pNode = (SOperatorNode*)pTargetNode->pExpr;
4592

G
Ganlin Zhao 已提交
4593 4594 4595
      pExp->base.pParam = taosMemoryCalloc(1, sizeof(SFunctParam));
      pExp->base.numOfParams = 1;

4596
      SDataType* pType = &pNode->node.resType;
dengyihao's avatar
dengyihao 已提交
4597 4598
      pExp->base.resSchema = createResSchema(pType->type, pType->bytes, pTargetNode->slotId, pType->scale,
                                             pType->precision, pNode->node.aliasName);
4599 4600 4601
      pExp->pExpr->_optrRoot.pRootNode = pTargetNode->pExpr;
    } else {
      ASSERT(0);
H
Haojun Liao 已提交
4602 4603 4604
    }
  }

H
Haojun Liao 已提交
4605
  return pExprs;
H
Haojun Liao 已提交
4606 4607
}

4608
static SExecTaskInfo* createExecTaskInfo(uint64_t queryId, uint64_t taskId, EOPTR_EXEC_MODEL model) {
wafwerar's avatar
wafwerar 已提交
4609
  SExecTaskInfo* pTaskInfo = taosMemoryCalloc(1, sizeof(SExecTaskInfo));
4610
  setTaskStatus(pTaskInfo, TASK_NOT_COMPLETED);
H
Haojun Liao 已提交
4611

4612
  pTaskInfo->cost.created = taosGetTimestampMs();
H
Haojun Liao 已提交
4613
  pTaskInfo->id.queryId = queryId;
dengyihao's avatar
dengyihao 已提交
4614
  pTaskInfo->execModel = model;
H
Haojun Liao 已提交
4615

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

4620 4621
  return pTaskInfo;
}
H
Haojun Liao 已提交
4622

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

L
Liu Jicong 已提交
4626 4627
static int32_t doCreateTableGroup(void* metaHandle, int32_t tableType, uint64_t tableUid, STableGroupInfo* pGroupInfo,
                                  uint64_t queryId, uint64_t taskId);
4628
static SArray* extractTableIdList(const STableGroupInfo* pTableGroupInfo);
H
Haojun Liao 已提交
4629
static SArray* extractColumnInfo(SNodeList* pNodeList);
4630

4631
static SArray* createSortInfo(SNodeList* pNodeList);
4632
static SArray* extractPartitionColInfo(SNodeList* pNodeList);
4633

H
Haojun Liao 已提交
4634
SOperatorInfo* createOperatorTree(SPhysiNode* pPhyNode, SExecTaskInfo* pTaskInfo, SReadHandle* pHandle,
4635
                                  uint64_t queryId, uint64_t taskId, STableGroupInfo* pTableGroupInfo) {
4636 4637
  int32_t type = nodeType(pPhyNode);

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

H
Haojun Liao 已提交
4642
      tsdbReaderT pDataReader = doCreateDataReader(pTableScanNode, pHandle, pTableGroupInfo, (uint64_t)queryId, taskId);
4643
      if (pDataReader == NULL && terrno != 0) {
4644 4645
        return NULL;
      }
4646

4647
      SOperatorInfo* pOperator = createTableScanOperatorInfo(pTableScanNode, pDataReader, pHandle, pTaskInfo);
4648

4649 4650
      STableScanInfo* pScanInfo = pOperator->info;
      pTaskInfo->cost.pRecoder = &pScanInfo->readRecorder;
4651

4652
      return pOperator;
H
Haojun Liao 已提交
4653
    } else if (QUERY_NODE_PHYSICAL_PLAN_EXCHANGE == type) {
H
Haojun Liao 已提交
4654
      SExchangePhysiNode* pExchange = (SExchangePhysiNode*)pPhyNode;
4655
      SSDataBlock*        pResBlock = createResDataBlock(pExchange->node.pOutputDataBlockDesc);
4656
      return createExchangeOperatorInfo(pHandle->pMsgCb->clientRpc, pExchange->pSrcEndPoints, pResBlock, pTaskInfo);
H
Haojun Liao 已提交
4657
    } else if (QUERY_NODE_PHYSICAL_PLAN_STREAM_SCAN == type) {
H
Haojun Liao 已提交
4658
      SScanPhysiNode* pScanPhyNode = (SScanPhysiNode*)pPhyNode;  // simple child table.
5
54liuyao 已提交
4659
      STableScanPhysiNode* pTableScanNode = (STableScanPhysiNode*)pPhyNode;
4660

4661
      int32_t numOfCols = 0;
5
54liuyao 已提交
4662 4663 4664 4665 4666 4667 4668 4669

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

5
54liuyao 已提交
4671 4672 4673 4674 4675 4676
      if (pDataReader == NULL && terrno != 0) {
        qDebug("pDataReader is     NULL");
        // return NULL;
      } else {
        qDebug("pDataReader is not NULL");
      }
H
Haojun Liao 已提交
4677

4678
      SDataBlockDescNode* pDescNode = pScanPhyNode->node.pOutputDataBlockDesc;
4679
      SOperatorInfo* pOperatorDumy = createTableScanOperatorInfo(pTableScanNode, pDataReader, pHandle, pTaskInfo);
5
54liuyao 已提交
4680 4681

      SArray* tableIdList = extractTableIdList(pTableGroupInfo);
4682

4683 4684 4685 4686
      SSDataBlock* pResBlock = createResDataBlock(pDescNode);
      SArray*      pCols = extractColMatchInfo(pScanPhyNode->pScanCols, pDescNode, &numOfCols, COL_MATCH_FROM_COL_ID);

      SOperatorInfo* pOperator = createStreamScanOperatorInfo(pHandle->reader, pDataReader, pHandle, pScanPhyNode->uid, pResBlock, pCols, tableIdList, pTaskInfo,
5
54liuyao 已提交
4687
                                                              pScanPhyNode->node.pConditions, pOperatorDumy);
4688
      taosArrayDestroy(tableIdList);
H
Haojun Liao 已提交
4689
      return pOperator;
H
Haojun Liao 已提交
4690
    } else if (QUERY_NODE_PHYSICAL_PLAN_SYSTABLE_SCAN == type) {
L
Liu Jicong 已提交
4691
      SSystemTableScanPhysiNode* pSysScanPhyNode = (SSystemTableScanPhysiNode*)pPhyNode;
L
Liu Jicong 已提交
4692
      SScanPhysiNode*            pScanNode = &pSysScanPhyNode->scan;
H
Haojun Liao 已提交
4693

4694 4695 4696
      SDataBlockDescNode* pDescNode = pScanNode->node.pOutputDataBlockDesc;

      SSDataBlock* pResBlock = createResDataBlock(pDescNode);
4697

4698
      int32_t numOfOutputCols = 0;
4699
      SArray* colList = extractColMatchInfo(pScanNode->pScanCols, pDescNode, &numOfOutputCols, COL_MATCH_FROM_COL_ID);
L
Liu Jicong 已提交
4700
      SOperatorInfo* pOperator = createSysTableScanOperatorInfo(
L
Liu Jicong 已提交
4701 4702
          pHandle, pResBlock, &pScanNode->tableName, pScanNode->node.pConditions, pSysScanPhyNode->mgmtEpSet, colList,
          pTaskInfo, pSysScanPhyNode->showRewrite, pSysScanPhyNode->accountId);
H
Haojun Liao 已提交
4703
      return pOperator;
4704
    } else if (QUERY_NODE_PHYSICAL_PLAN_TAG_SCAN == type) {
X
Xiaoyu Wang 已提交
4705
      STagScanPhysiNode* pScanPhyNode = (STagScanPhysiNode*)pPhyNode;
4706 4707 4708 4709

      SDataBlockDescNode* pDescNode = pScanPhyNode->node.pOutputDataBlockDesc;

      SSDataBlock* pResBlock = createResDataBlock(pDescNode);
4710

X
Xiaoyu Wang 已提交
4711 4712
      int32_t code = doCreateTableGroup(pHandle->meta, pScanPhyNode->tableType, pScanPhyNode->uid, pTableGroupInfo,
                                        queryId, taskId);
4713 4714 4715 4716
      if (code != TSDB_CODE_SUCCESS) {
        return NULL;
      }

X
Xiaoyu Wang 已提交
4717
      int32_t    num = 0;
4718 4719 4720
      SExprInfo* pExprInfo = createExprInfo(pScanPhyNode->pScanPseudoCols, NULL, &num);

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

X
Xiaoyu Wang 已提交
4724 4725
      SOperatorInfo* pOperator =
          createTagScanOperatorInfo(pHandle, pExprInfo, num, pResBlock, colList, pTableGroupInfo, pTaskInfo);
4726
      return pOperator;
H
Haojun Liao 已提交
4727 4728
    } else {
      ASSERT(0);
H
Haojun Liao 已提交
4729 4730 4731
    }
  }

4732 4733
  int32_t num = 0;
  size_t  size = LIST_LENGTH(pPhyNode->pChildren);
H
Haojun Liao 已提交
4734

4735
  SOperatorInfo** ops = taosMemoryCalloc(size, POINTER_BYTES);
dengyihao's avatar
dengyihao 已提交
4736
  for (int32_t i = 0; i < size; ++i) {
4737 4738
    SPhysiNode* pChildNode = (SPhysiNode*)nodesListGetNode(pPhyNode->pChildren, i);
    ops[i] = createOperatorTree(pChildNode, pTaskInfo, pHandle, queryId, taskId, pTableGroupInfo);
4739 4740 4741
    if (ops[i] == NULL) {
      return NULL;
    }
4742
  }
H
Haojun Liao 已提交
4743

4744
  SOperatorInfo* pOptr = NULL;
H
Haojun Liao 已提交
4745
  if (QUERY_NODE_PHYSICAL_PLAN_PROJECT == type) {
dengyihao's avatar
dengyihao 已提交
4746 4747
    SProjectPhysiNode* pProjPhyNode = (SProjectPhysiNode*)pPhyNode;
    SExprInfo*         pExprInfo = createExprInfo(pProjPhyNode->pProjections, NULL, &num);
H
Haojun Liao 已提交
4748

4749
    SSDataBlock* pResBlock = createResDataBlock(pPhyNode->pOutputDataBlockDesc);
dengyihao's avatar
dengyihao 已提交
4750 4751
    SLimit       limit = {.limit = pProjPhyNode->limit, .offset = pProjPhyNode->offset};
    SLimit       slimit = {.limit = pProjPhyNode->slimit, .offset = pProjPhyNode->soffset};
4752
    pOptr = createProjectOperatorInfo(ops[0], pExprInfo, num, pResBlock, &limit, &slimit, pTaskInfo);
H
Haojun Liao 已提交
4753 4754 4755
  } else if (QUERY_NODE_PHYSICAL_PLAN_AGG == type) {
    SAggPhysiNode* pAggNode = (SAggPhysiNode*)pPhyNode;
    SExprInfo*     pExprInfo = createExprInfo(pAggNode->pAggFuncs, pAggNode->pGroupKeys, &num);
4756
    SSDataBlock*   pResBlock = createResDataBlock(pPhyNode->pOutputDataBlockDesc);
H
Haojun Liao 已提交
4757

dengyihao's avatar
dengyihao 已提交
4758
    int32_t    numOfScalarExpr = 0;
4759 4760 4761 4762 4763
    SExprInfo* pScalarExprInfo = NULL;
    if (pAggNode->pExprs != NULL) {
      pScalarExprInfo = createExprInfo(pAggNode->pExprs, NULL, &numOfScalarExpr);
    }

H
Haojun Liao 已提交
4764 4765
    if (pAggNode->pGroupKeys != NULL) {
      SArray* pColList = extractColumnInfo(pAggNode->pGroupKeys);
dengyihao's avatar
dengyihao 已提交
4766 4767
      pOptr = createGroupOperatorInfo(ops[0], pExprInfo, num, pResBlock, pColList, pAggNode->node.pConditions,
                                      pScalarExprInfo, numOfScalarExpr, pTaskInfo, NULL);
H
Haojun Liao 已提交
4768
    } else {
dengyihao's avatar
dengyihao 已提交
4769 4770
      pOptr = createAggregateOperatorInfo(ops[0], pExprInfo, num, pResBlock, pScalarExprInfo, numOfScalarExpr,
                                          pTaskInfo, pTableGroupInfo);
H
Haojun Liao 已提交
4771
    }
X
Xiaoyu Wang 已提交
4772
  } else if (QUERY_NODE_PHYSICAL_PLAN_INTERVAL == type || QUERY_NODE_PHYSICAL_PLAN_STREAM_INTERVAL == type) {
H
Haojun Liao 已提交
4773
    SIntervalPhysiNode* pIntervalPhyNode = (SIntervalPhysiNode*)pPhyNode;
H
Haojun Liao 已提交
4774

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

dengyihao's avatar
dengyihao 已提交
4778 4779 4780 4781 4782 4783
    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 已提交
4784

dengyihao's avatar
dengyihao 已提交
4785 4786
    STimeWindowAggSupp as = {.waterMark = pIntervalPhyNode->window.watermark,
                             .calTrigger = pIntervalPhyNode->window.triggerType};
4787

4788 4789 4790 4791
    int32_t tsSlotId = ((SColumnNode*)pIntervalPhyNode->window.pTspk)->slotId;
    pOptr = createIntervalOperatorInfo(ops[0], pExprInfo, num, pResBlock, &interval, tsSlotId, &as, pTableGroupInfo,
                                       pTaskInfo);

H
Haojun Liao 已提交
4792
  } else if (QUERY_NODE_PHYSICAL_PLAN_SORT == type) {
H
Haojun Liao 已提交
4793
    SSortPhysiNode* pSortPhyNode = (SSortPhysiNode*)pPhyNode;
H
Haojun Liao 已提交
4794

4795 4796 4797
    SDataBlockDescNode* pDescNode = pPhyNode->pOutputDataBlockDesc;

    SSDataBlock* pResBlock = createResDataBlock(pDescNode);
4798
    SArray*      info = createSortInfo(pSortPhyNode->pSortKeys);
4799 4800

    int32_t    numOfCols = 0;
4801 4802 4803
    SExprInfo* pExprInfo = createExprInfo(pSortPhyNode->pExprs, NULL, &numOfCols);

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

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

X
Xiaoyu Wang 已提交
4810 4811
    STimeWindowAggSupp as = {.waterMark = pSessionNode->window.watermark,
                             .calTrigger = pSessionNode->window.triggerType};
4812

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

X
Xiaoyu Wang 已提交
4817 4818
    pOptr =
        createSessionAggOperatorInfo(ops[0], pExprInfo, num, pResBlock, pSessionNode->gap, tsSlotId, &as, pTaskInfo);
H
Haojun Liao 已提交
4819
  } else if (QUERY_NODE_PHYSICAL_PLAN_PARTITION == type) {
dengyihao's avatar
dengyihao 已提交
4820 4821 4822
    SPartitionPhysiNode* pPartNode = (SPartitionPhysiNode*)pPhyNode;
    SArray*              pColList = extractPartitionColInfo(pPartNode->pPartitionKeys);
    SSDataBlock*         pResBlock = createResDataBlock(pPhyNode->pOutputDataBlockDesc);
4823 4824

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

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

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

4835 4836 4837
    SColumnNode* pColNode = (SColumnNode*)((STargetNode*)pStateNode->pStateKey)->pExpr;
    SColumn col = extractColumnFromColumnNode(pColNode);
    pOptr = createStatewindowOperatorInfo(ops[0], pExprInfo, num, pResBlock, &as, tsSlotId, &col, pTaskInfo);
4838
  } else if (QUERY_NODE_PHYSICAL_PLAN_JOIN == type) {
dengyihao's avatar
dengyihao 已提交
4839 4840
    SJoinPhysiNode* pJoinNode = (SJoinPhysiNode*)pPhyNode;
    SSDataBlock*    pResBlock = createResDataBlock(pPhyNode->pOutputDataBlockDesc);
4841 4842

    SExprInfo* pExprInfo = createExprInfo(pJoinNode->pTargets, NULL, &num);
H
Haojun Liao 已提交
4843
    pOptr = createMergeJoinOperatorInfo(ops, size, pExprInfo, num, pResBlock, pJoinNode->pOnConditions, pTaskInfo);
4844 4845
  } else if (QUERY_NODE_PHYSICAL_PLAN_FILL == type) {
    SFillPhysiNode* pFillNode = (SFillPhysiNode*)pPhyNode;
X
Xiaoyu Wang 已提交
4846 4847
    SSDataBlock*    pResBlock = createResDataBlock(pPhyNode->pOutputDataBlockDesc);
    SExprInfo*      pExprInfo = createExprInfo(pFillNode->pTargets, NULL, &num);
4848

4849
    SInterval* pInterval = &((SIntervalAggOperatorInfo*)ops[0]->info)->interval;
X
Xiaoyu Wang 已提交
4850 4851
    pOptr = createFillOperatorInfo(ops[0], pExprInfo, num, pInterval, &pFillNode->timeRange, pResBlock, pFillNode->mode,
                                   (SNodeListNode*)pFillNode->pValues, false, pTaskInfo);
H
Haojun Liao 已提交
4852 4853
  } else {
    ASSERT(0);
H
Haojun Liao 已提交
4854
  }
4855 4856 4857

  taosMemoryFree(ops);
  return pOptr;
4858
}
H
Haojun Liao 已提交
4859

4860
int32_t initQueryTableDataCond(SQueryTableDataCond* pCond, const STableScanPhysiNode* pTableScanNode) {
4861 4862 4863 4864 4865 4866
  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 已提交
4867
    terrno = TSDB_CODE_QRY_OUT_OF_MEMORY;
4868 4869 4870 4871 4872 4873
    return terrno;
  }

  pCond->twindow = pTableScanNode->scanRange;

#if 1
L
Liu Jicong 已提交
4874
  // todo work around a problem, remove it later
4875 4876
  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 已提交
4877
    TSWAP(pCond->twindow.skey, pCond->twindow.ekey);
H
Haojun Liao 已提交
4878
  }
4879
#endif
H
Haojun Liao 已提交
4880

4881 4882
  pCond->type = BLOCK_LOAD_OFFSET_SEQ_ORDER;
  //  pCond->type = pTableScanNode->scanFlag;
H
Haojun Liao 已提交
4883

H
Haojun Liao 已提交
4884
  int32_t j = 0;
4885
  for (int32_t i = 0; i < pCond->numOfCols; ++i) {
H
Haojun Liao 已提交
4886 4887
    STargetNode* pNode = (STargetNode*)nodesListGetNode(pTableScanNode->scan.pScanCols, i);
    SColumnNode* pColNode = (SColumnNode*)pNode->pExpr;
H
Haojun Liao 已提交
4888 4889 4890
    if (pColNode->colType == COLUMN_TYPE_TAG) {
      continue;
    }
H
Haojun Liao 已提交
4891

4892 4893 4894
    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 已提交
4895
    j += 1;
H
Haojun Liao 已提交
4896 4897
  }

4898 4899
  pCond->numOfCols = j;
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
4900
}
H
Haojun Liao 已提交
4901

4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912
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 已提交
4913
SArray* extractColumnInfo(SNodeList* pNodeList) {
L
Liu Jicong 已提交
4914
  size_t  numOfCols = LIST_LENGTH(pNodeList);
H
Haojun Liao 已提交
4915 4916 4917 4918 4919 4920
  SArray* pList = taosArrayInit(numOfCols, sizeof(SColumn));
  if (pList == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

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

4924 4925 4926
    if (nodeType(pNode->pExpr) == QUERY_NODE_COLUMN) {
      SColumnNode* pColNode = (SColumnNode*)pNode->pExpr;

4927
      SColumn c = extractColumnFromColumnNode(pColNode);
4928 4929
      taosArrayPush(pList, &c);
    } else if (nodeType(pNode->pExpr) == QUERY_NODE_VALUE) {
L
Liu Jicong 已提交
4930 4931
      SValueNode* pValNode = (SValueNode*)pNode->pExpr;
      SColumn     c = {0};
4932
      c.slotId = pNode->slotId;
L
Liu Jicong 已提交
4933 4934 4935 4936
      c.colId = pNode->slotId;
      c.type = pValNode->node.type;
      c.bytes = pValNode->node.resType.bytes;
      c.scale = pValNode->node.resType.scale;
4937 4938 4939 4940
      c.precision = pValNode->node.resType.precision;

      taosArrayPush(pList, &c);
    }
H
Haojun Liao 已提交
4941 4942 4943 4944 4945
  }

  return pList;
}

4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959
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 已提交
4960 4961 4962
    c.colId = pColNode->colId;
    c.type = pColNode->node.resType.type;
    c.bytes = pColNode->node.resType.bytes;
4963 4964 4965 4966 4967 4968 4969 4970 4971
    c.precision = pColNode->node.resType.precision;
    c.scale = pColNode->node.resType.scale;

    taosArrayPush(pList, &c);
  }

  return pList;
}

4972
SArray* createSortInfo(SNodeList* pNodeList) {
L
Liu Jicong 已提交
4973
  size_t  numOfCols = LIST_LENGTH(pNodeList);
H
Haojun Liao 已提交
4974 4975 4976 4977 4978 4979
  SArray* pList = taosArrayInit(numOfCols, sizeof(SBlockOrderInfo));
  if (pList == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return pList;
  }

L
Liu Jicong 已提交
4980
  for (int32_t i = 0; i < numOfCols; ++i) {
4981
    SOrderByExprNode* pSortKey = (SOrderByExprNode*)nodesListGetNode(pNodeList, i);
L
Liu Jicong 已提交
4982 4983
    SBlockOrderInfo   bi = {0};
    bi.order = (pSortKey->order == ORDER_ASC) ? TSDB_ORDER_ASC : TSDB_ORDER_DESC;
H
Haojun Liao 已提交
4984 4985 4986
    bi.nullFirst = (pSortKey->nullOrder == NULL_ORDER_FIRST);

    SColumnNode* pColNode = (SColumnNode*)pSortKey->pExpr;
4987
    bi.slotId = pColNode->slotId;
H
Haojun Liao 已提交
4988 4989 4990 4991 4992 4993
    taosArrayPush(pList, &bi);
  }

  return pList;
}

X
Xiaoyu Wang 已提交
4994 4995
SArray* extractColMatchInfo(SNodeList* pNodeList, SDataBlockDescNode* pOutputNodeList, int32_t* numOfOutputCols,
                            int32_t type) {
L
Liu Jicong 已提交
4996
  size_t  numOfCols = LIST_LENGTH(pNodeList);
H
Haojun Liao 已提交
4997 4998 4999 5000 5001 5002
  SArray* pList = taosArrayInit(numOfCols, sizeof(SColMatchInfo));
  if (pList == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

L
Liu Jicong 已提交
5003 5004 5005
  for (int32_t i = 0; i < numOfCols; ++i) {
    STargetNode* pNode = (STargetNode*)nodesListGetNode(pNodeList, i);
    SColumnNode* pColNode = (SColumnNode*)pNode->pExpr;
H
Haojun Liao 已提交
5006 5007

    SColMatchInfo c = {0};
X
Xiaoyu Wang 已提交
5008 5009 5010 5011
    c.output = true;
    c.colId = pColNode->colId;
    c.srcSlotId = pColNode->slotId;
    c.matchType = type;
H
Haojun Liao 已提交
5012 5013 5014 5015
    c.targetSlotId = pNode->slotId;
    taosArrayPush(pList, &c);
  }

H
Haojun Liao 已提交
5016 5017
  *numOfOutputCols = 0;
  int32_t num = LIST_LENGTH(pOutputNodeList->pSlots);
L
Liu Jicong 已提交
5018 5019
  for (int32_t i = 0; i < num; ++i) {
    SSlotDescNode* pNode = (SSlotDescNode*)nodesListGetNode(pOutputNodeList->pSlots, i);
5020

5021
    // todo: add reserve flag check
5022 5023
    // it is a column reserved for the arithmetic expression calculation
    if (pNode->slotId >= numOfCols) {
5024 5025 5026 5027
      (*numOfOutputCols) += 1;
      continue;
    }

H
Haojun Liao 已提交
5028
    SColMatchInfo* info = taosArrayGet(pList, pNode->slotId);
H
Haojun Liao 已提交
5029 5030 5031 5032 5033
    if (pNode->output) {
      (*numOfOutputCols) += 1;
    } else {
      info->output = false;
    }
H
Haojun Liao 已提交
5034 5035
  }

H
Haojun Liao 已提交
5036 5037 5038
  return pList;
}

dengyihao's avatar
dengyihao 已提交
5039 5040
int32_t doCreateTableGroup(void* metaHandle, int32_t tableType, uint64_t tableUid, STableGroupInfo* pGroupInfo,
                           uint64_t queryId, uint64_t taskId) {
5041
  int32_t code = 0;
H
Haojun Liao 已提交
5042
  if (tableType == TSDB_SUPER_TABLE) {
H
Haojun Liao 已提交
5043
    code = tsdbQuerySTableByTagCond(metaHandle, tableUid, 0, NULL, 0, 0, NULL, pGroupInfo, NULL, 0, queryId, taskId);
H
Haojun Liao 已提交
5044
  } else {  // Create one table group.
H
Haojun Liao 已提交
5045
    code = tsdbGetOneTableGroup(metaHandle, tableUid, 0, pGroupInfo);
5046 5047 5048 5049
  }

  return code;
}
H
Haojun Liao 已提交
5050

5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068
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 已提交
5069 5070
tsdbReaderT doCreateDataReader(STableScanPhysiNode* pTableScanNode, SReadHandle* pHandle,
                               STableGroupInfo* pTableGroupInfo, uint64_t queryId, uint64_t taskId) {
5071
  uint64_t uid = pTableScanNode->scan.uid;
L
Liu Jicong 已提交
5072 5073
  int32_t  code =
      doCreateTableGroup(pHandle->meta, pTableScanNode->scan.tableType, uid, pTableGroupInfo, queryId, taskId);
5074 5075
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
H
Haojun Liao 已提交
5076
  }
H
Haojun Liao 已提交
5077

H
Haojun Liao 已提交
5078
  if (pTableGroupInfo->numOfTables == 0) {
H
Haojun Liao 已提交
5079
    code = 0;
L
Liu Jicong 已提交
5080
    qDebug("no table qualified for query, TID:0x%" PRIx64 ", QID:0x%" PRIx64, taskId, queryId);
H
Haojun Liao 已提交
5081 5082
    goto _error;
  }
H
Haojun Liao 已提交
5083

5084 5085 5086 5087
  SQueryTableDataCond cond = {0};
  code = initQueryTableDataCond(&cond, pTableScanNode);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
X
Xiaoyu Wang 已提交
5088
  }
5089

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

L
Liu Jicong 已提交
5092
_error:
H
Haojun Liao 已提交
5093 5094 5095 5096
  terrno = code;
  return NULL;
}

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

H
Haojun Liao 已提交
5101
  int32_t code = TSDB_CODE_SUCCESS;
5102
  *pTaskInfo = createExecTaskInfo(queryId, taskId, model);
H
Haojun Liao 已提交
5103 5104 5105 5106
  if (*pTaskInfo == NULL) {
    code = TSDB_CODE_QRY_OUT_OF_MEMORY;
    goto _complete;
  }
H
Haojun Liao 已提交
5107

L
Liu Jicong 已提交
5108 5109
  (*pTaskInfo)->pRoot =
      createOperatorTree(pPlan->pNode, *pTaskInfo, pHandle, queryId, taskId, &(*pTaskInfo)->tableqinfoGroupInfo);
D
dapan1121 已提交
5110
  if (NULL == (*pTaskInfo)->pRoot) {
L
Liu Jicong 已提交
5111
    code = terrno;
D
dapan1121 已提交
5112 5113
    goto _complete;
  }
H
Haojun Liao 已提交
5114

5115
  if ((*pTaskInfo)->pRoot == NULL) {
H
Haojun Liao 已提交
5116
    code = TSDB_CODE_QRY_OUT_OF_MEMORY;
H
Haojun Liao 已提交
5117
    goto _complete;
5118 5119
  }

H
Haojun Liao 已提交
5120 5121
  return code;

H
Haojun Liao 已提交
5122
_complete:
wafwerar's avatar
wafwerar 已提交
5123
  taosMemoryFreeClear(*pTaskInfo);
H
Haojun Liao 已提交
5124 5125 5126

  terrno = code;
  return code;
H
Haojun Liao 已提交
5127 5128
}

H
Haojun Liao 已提交
5129
void setResultBufSize(STaskAttr* pQueryAttr, SResultInfo* pResultInfo) {
5130 5131 5132 5133 5134 5135 5136 5137
  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 已提交
5138 5139 5140 5141 5142 5143 5144 5145 5146 5147
  //  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;
  //  }
5148 5149

  pResultInfo->threshold = (int32_t)(pResultInfo->capacity * THRESHOLD_RATIO);
H
Haojun Liao 已提交
5150
  pResultInfo->totalRows = 0;
5151 5152
}

L
Liu Jicong 已提交
5153
// TODO refactor
5154
void freeColumnFilterInfo(SColumnFilterInfo* pFilter, int32_t numOfFilters) {
L
Liu Jicong 已提交
5155 5156 5157
  if (pFilter == NULL || numOfFilters == 0) {
    return;
  }
5158

L
Liu Jicong 已提交
5159 5160 5161
  for (int32_t i = 0; i < numOfFilters; i++) {
    if (pFilter[i].filterstr && pFilter[i].pz) {
      taosMemoryFree((void*)(pFilter[i].pz));
5162
    }
L
Liu Jicong 已提交
5163
  }
5164

L
Liu Jicong 已提交
5165
  taosMemoryFree(pFilter);
5166 5167 5168 5169
}

static void doDestroyTableQueryInfo(STableGroupInfo* pTableqinfoGroupInfo) {
  if (pTableqinfoGroupInfo->pGroupList != NULL) {
L
Liu Jicong 已提交
5170
    int32_t numOfGroups = (int32_t)taosArrayGetSize(pTableqinfoGroupInfo->pGroupList);
5171
    for (int32_t i = 0; i < numOfGroups; ++i) {
L
Liu Jicong 已提交
5172
      SArray* p = taosArrayGetP(pTableqinfoGroupInfo->pGroupList, i);
5173 5174

      size_t num = taosArrayGetSize(p);
L
Liu Jicong 已提交
5175
      for (int32_t j = 0; j < num; ++j) {
5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191
        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 已提交
5192
void doDestroyTask(SExecTaskInfo* pTaskInfo) {
H
Haojun Liao 已提交
5193 5194
  qDebug("%s execTask is freed", GET_TASKID(pTaskInfo));

H
Haojun Liao 已提交
5195
  doDestroyTableQueryInfo(&pTaskInfo->tableqinfoGroupInfo);
H
Haojun Liao 已提交
5196
  destroyOperatorInfo(pTaskInfo->pRoot);
L
Liu Jicong 已提交
5197 5198
  //  taosArrayDestroy(pTaskInfo->summary.queryProfEvents);
  //  taosHashCleanup(pTaskInfo->summary.operatorProfResults);
5199

wafwerar's avatar
wafwerar 已提交
5200 5201 5202
  taosMemoryFreeClear(pTaskInfo->sql);
  taosMemoryFreeClear(pTaskInfo->id.str);
  taosMemoryFreeClear(pTaskInfo);
5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214
}

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 已提交
5215
      int32_t len = (varDataLen(val) > maxLen) ? maxLen : varDataLen(val);
5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227
      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 已提交
5228 5229
  //  size_t s3 = sizeof(STableCheckInfo);  buffer consumption in tsdb
  return (int64_t)(s1 * 1.5 * numOfTables);
5230 5231 5232 5233 5234 5235 5236
}

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 已提交
5237
    while (1) {
5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263
      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 已提交
5264

dengyihao's avatar
dengyihao 已提交
5265 5266
int32_t getOperatorExplainExecInfo(SOperatorInfo* operatorInfo, SExplainExecInfo** pRes, int32_t* capacity,
                                   int32_t* resNum) {
D
dapan1121 已提交
5267 5268
  if (*resNum >= *capacity) {
    *capacity += 10;
dengyihao's avatar
dengyihao 已提交
5269

D
dapan1121 已提交
5270 5271
    *pRes = taosMemoryRealloc(*pRes, (*capacity) * sizeof(SExplainExecInfo));
    if (NULL == *pRes) {
D
dapan1121 已提交
5272
      qError("malloc %d failed", (*capacity) * (int32_t)sizeof(SExplainExecInfo));
D
dapan1121 已提交
5273 5274 5275 5276
      return TSDB_CODE_QRY_OUT_OF_MEMORY;
    }
  }

D
dapan1121 已提交
5277 5278 5279 5280
  (*pRes)[*resNum].numOfRows = operatorInfo->resultInfo.totalRows;
  (*pRes)[*resNum].startupCost = operatorInfo->cost.openCost;
  (*pRes)[*resNum].totalCost = operatorInfo->cost.totalCost;

5281 5282
  if (operatorInfo->fpSet.getExplainFn) {
    int32_t code = (*operatorInfo->fpSet.getExplainFn)(operatorInfo, &(*pRes)->verboseInfo);
D
dapan1121 已提交
5283 5284 5285 5286 5287
    if (code) {
      qError("operator getExplainFn failed, error:%s", tstrerror(code));
      return code;
    }
  }
dengyihao's avatar
dengyihao 已提交
5288

D
dapan1121 已提交
5289
  ++(*resNum);
dengyihao's avatar
dengyihao 已提交
5290

D
dapan1121 已提交
5291
  int32_t code = 0;
D
dapan1121 已提交
5292 5293
  for (int32_t i = 0; i < operatorInfo->numOfDownstream; ++i) {
    code = getOperatorExplainExecInfo(operatorInfo->pDownstream[i], pRes, capacity, resNum);
D
dapan1121 已提交
5294 5295 5296 5297 5298 5299 5300
    if (code) {
      taosMemoryFreeClear(*pRes);
      return TSDB_CODE_QRY_OUT_OF_MEMORY;
    }
  }

  return TSDB_CODE_SUCCESS;
D
dapan1121 已提交
5301
}
5
54liuyao 已提交
5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313

int32_t initCatchSupporter(SCatchSupporter* pCatchSup, size_t rowSize, size_t keyBufSize,
                         const char* pKey, const char* pDir) {
  pCatchSup->keySize = sizeof(int64_t) + sizeof(int64_t) + sizeof(TSKEY);
  pCatchSup->pKeyBuf = taosMemoryCalloc(1, pCatchSup->keySize);
  int32_t pageSize = rowSize * 32;
  int32_t bufSize = pageSize * 4096;
  createDiskbasedBuf(&pCatchSup->pDataBuf, pageSize, bufSize, pKey, pDir);
  _hash_fn_t hashFn = taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY);
  pCatchSup->pWindowHashTable = taosHashInit(10000, hashFn, true, HASH_NO_LOCK);;
  return TSDB_CODE_SUCCESS;
}
L
Liu Jicong 已提交
5314