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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

L
Liu Jicong 已提交
93
static void destroyTableQueryInfoImpl(STableQueryInfo* pTableQueryInfo);
94

X
Xiaoyu Wang 已提交
95
static void releaseQueryBuf(size_t numOfTables);
96 97 98 99 100

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

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

105 106
static void destroyOperatorInfo(SOperatorInfo* pOperator);

107
void doSetOperatorCompleted(SOperatorInfo* pOperator) {
108
  pOperator->status = OP_EXEC_DONE;
109

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

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

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

  return fpSet;
}

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

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

145
static void initCtxOutputBuffer(SqlFunctionCtx* pCtx, int32_t size);
H
Haojun Liao 已提交
146
static void setResultBufSize(STaskAttr* pQueryAttr, SResultInfo* pResultInfo);
dengyihao's avatar
dengyihao 已提交
147 148
static void doSetTableGroupOutputBuf(SAggOperatorInfo* pAggInfo, int32_t numOfOutput, uint64_t groupId,
                                     SExecTaskInfo* pTaskInfo);
149

H
Haojun Liao 已提交
150
SArray* getOrderCheckColumns(STaskAttr* pQuery);
151 152

typedef struct SRowCompSupporter {
L
Liu Jicong 已提交
153 154 155
  STaskRuntimeEnv* pRuntimeEnv;
  int16_t          dataOffset;
  __compar_fn_t    comFunc;
156 157
} SRowCompSupporter;

L
Liu Jicong 已提交
158 159 160
static int compareRowData(const void* a, const void* b, const void* userData) {
  const SResultRow* pRow1 = (const SResultRow*)a;
  const SResultRow* pRow2 = (const SResultRow*)b;
161

L
Liu Jicong 已提交
162 163
  SRowCompSupporter* supporter = (SRowCompSupporter*)userData;
  STaskRuntimeEnv*   pRuntimeEnv = supporter->pRuntimeEnv;
164

L
Liu Jicong 已提交
165 166
  SFilePage* page1 = getBufPage(pRuntimeEnv->pResultBuf, pRow1->pageId);
  SFilePage* page2 = getBufPage(pRuntimeEnv->pResultBuf, pRow2->pageId);
167 168

  int16_t offset = supporter->dataOffset;
169
  return 0;
X
Xiaoyu Wang 已提交
170 171
  //  char*   in1 = getPosInResultPage(pRuntimeEnv->pQueryAttr, page1, pRow1->offset, offset);
  //  char*   in2 = getPosInResultPage(pRuntimeEnv->pQueryAttr, page2, pRow2->offset, offset);
172

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

L
Liu Jicong 已提交
176 177
// setup the output buffer for each operator
static bool hasNull(SColumn* pColumn, SColumnDataAgg* pStatis) {
dengyihao's avatar
dengyihao 已提交
178 179
  if (TSDB_COL_IS_TAG(pColumn->flag) || TSDB_COL_IS_UD_COL(pColumn->flag) ||
      pColumn->colId == PRIMARYKEY_TIMESTAMP_COL_ID) {
180 181 182 183 184 185 186 187 188 189
    return false;
  }

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

  return true;
}

L
Liu Jicong 已提交
190 191
static bool chkResultRowFromKey(STaskRuntimeEnv* pRuntimeEnv, SResultRowInfo* pResultRowInfo, char* pData,
                                int16_t bytes, bool masterscan, uint64_t uid) {
192 193 194
  bool existed = false;
  SET_RES_WINDOW_KEY(pRuntimeEnv->keyBuf, pData, bytes, uid);

L
Liu Jicong 已提交
195 196
  SResultRow** p1 =
      (SResultRow**)taosHashGet(pRuntimeEnv->pResultRowHashTable, pRuntimeEnv->keyBuf, GET_RES_WINDOW_KEY_LEN(bytes));
197 198 199 200 201 202 203 204 205 206 207

  // 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 已提交
208
        //        existed = (pResultRowInfo->pResult[0] == (*p1));
209 210
      } else {  // check if current pResultRowInfo contains the existed pResultRow
        SET_RES_EXT_WINDOW_KEY(pRuntimeEnv->keyBuf, pData, bytes, uid, pResultRowInfo);
L
Liu Jicong 已提交
211 212
        int64_t* index =
            taosHashGet(pRuntimeEnv->pResultRowListSet, pRuntimeEnv->keyBuf, GET_RES_EXT_WINDOW_KEY_LEN(bytes));
213 214 215 216 217 218 219 220 221 222 223 224 225 226
        if (index != NULL) {
          existed = true;
        } else {
          existed = false;
        }
      }
    }

    return existed;
  }

  return p1 != NULL;
}

227
SResultRow* getNewResultRow(SDiskbasedBuf* pResultBuf, int64_t tableGroupId, int32_t interBufSize) {
L
Liu Jicong 已提交
228
  SFilePage* pData = NULL;
229 230 231 232 233 234 235 236 237 238 239 240 241

  // 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 已提交
242
    if (pData->num + interBufSize > getBufPageSize(pResultBuf)) {
243 244 245 246 247 248 249 250 251 252 253 254 255 256
      // 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;
  }

257 258
  setBufPageDirty(pData, true);

259 260 261 262 263
  // 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 已提交
264
  pData->num += interBufSize;
265 266 267 268

  return pResultRow;
}

269 270 271 272 273 274 275
/**
 * the struct of key in hash table
 * +----------+---------------+
 * | group id |   key data    |
 * | 8 bytes  | actual length |
 * +----------+---------------+
 */
276 277 278
SResultRow* doSetResultOutBufByKey(SDiskbasedBuf* pResultBuf, SResultRowInfo* pResultRowInfo, char* pData,
                                   int16_t bytes, bool masterscan, uint64_t groupId, SExecTaskInfo* pTaskInfo,
                                   bool isIntervalQuery, SAggSupporter* pSup) {
279
  SET_RES_WINDOW_KEY(pSup->keyBuf, pData, bytes, groupId);
H
Haojun Liao 已提交
280

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

284 285
  SResultRow* pResult = NULL;

H
Haojun Liao 已提交
286 287
  // in case of repeat scan/reverse scan, no new time window added.
  if (isIntervalQuery) {
288 289
    if (masterscan && p1 != NULL) {  // the *p1 may be NULL in case of sliding+offset exists.
      pResult = getResultRowByPos(pResultBuf, p1);
290
      ASSERT(pResult->pageId == p1->pageId && pResult->offset == p1->offset);
H
Haojun Liao 已提交
291 292
    }
  } else {
dengyihao's avatar
dengyihao 已提交
293 294
    // In case of group by column query, the required SResultRow object must be existInCurrentResusltRowInfo in the
    // pResultRowInfo object.
H
Haojun Liao 已提交
295
    if (p1 != NULL) {
296
      // todo
297
      pResult = getResultRowByPos(pResultBuf, p1);
298
      ASSERT(pResult->pageId == p1->pageId && pResult->offset == p1->offset);
H
Haojun Liao 已提交
299 300 301
    }
  }

L
Liu Jicong 已提交
302
  // 1. close current opened time window
303
  if (pResultRowInfo->cur.pageId != -1 && ((pResult == NULL) || (pResult->pageId != pResultRowInfo->cur.pageId &&
L
Liu Jicong 已提交
304
                                                                 pResult->offset != pResultRowInfo->cur.offset))) {
305
    SResultRowPosition pos = pResultRowInfo->cur;
X
Xiaoyu Wang 已提交
306
    SFilePage*         pPage = getBufPage(pResultBuf, pos.pageId);
307 308 309 310 311
    releaseBufPage(pResultBuf, pPage);
  }

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

315
    initResultRow(pResult);
H
Haojun Liao 已提交
316

317 318
    // add a new result set for a new group
    SResultRowPosition pos = {.pageId = pResult->pageId, .offset = pResult->offset};
X
Xiaoyu Wang 已提交
319 320
    taosHashPut(pSup->pResultRowHashTable, pSup->keyBuf, GET_RES_WINDOW_KEY_LEN(bytes), &pos,
                sizeof(SResultRowPosition));
H
Haojun Liao 已提交
321 322
  }

323 324 325
  // 2. set the new time window to be the new active time window
  pResultRowInfo->cur = (SResultRowPosition){.pageId = pResult->pageId, .offset = pResult->offset};

H
Haojun Liao 已提交
326
  // too many time window in query
327
  if (taosHashGetSize(pSup->pResultRowHashTable) > MAX_INTERVAL_TIME_WINDOW) {
H
Haojun Liao 已提交
328 329 330
    longjmp(pTaskInfo->env, TSDB_CODE_QRY_TOO_MANY_TIMEWINDOW);
  }

H
Haojun Liao 已提交
331
  return pResult;
H
Haojun Liao 已提交
332 333
}

334
// get the correct time window according to the handled timestamp
L
Liu Jicong 已提交
335
static STimeWindow getCurrentActiveTimeWindow(SResultRowInfo* pResultRowInfo, int64_t ts, STaskAttr* pQueryAttr) {
336
  STimeWindow w = {0};
H
Haojun Liao 已提交
337
#if 0
L
Liu Jicong 已提交
338 339
  if (pResultRowInfo->curPos == -1) {  // the first window, from the previous stored value
                                       //    getInitialStartTimeWindow(pQueryAttr, ts, &w);
340 341

    if (pQueryAttr->interval.intervalUnit == 'n' || pQueryAttr->interval.intervalUnit == 'y') {
L
Liu Jicong 已提交
342 343 344
      w.ekey =
          taosTimeAdd(w.skey, pQueryAttr->interval.interval, pQueryAttr->interval.intervalUnit, pQueryAttr->precision) -
          1;
345 346 347 348
    } else {
      w.ekey = w.skey + pQueryAttr->interval.interval - 1;
    }
  } else {
H
Haojun Liao 已提交
349
    w = pRow->win;
350 351 352 353 354 355 356 357 358
  }

  /*
   * 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 已提交
359
#endif
360 361 362 363 364

  return w;
}

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

L
Liu Jicong 已提交
370
  SFilePage* pData = NULL;
371 372 373 374 375 376

  // 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 已提交
377
    pData = getNewBufPage(pResultBuf, tid, &pageId);
378
    pData->num = sizeof(SFilePage);
379 380
  } else {
    SPageInfo* pi = getLastPageInfo(list);
381
    pData = getBufPage(pResultBuf, getPageId(pi));
382
    pageId = getPageId(pi);
383

384
    if (pData->num + size > getBufPageSize(pResultBuf)) {
385
      // release current page first, and prepare the next one
386
      releaseBufPageInfo(pResultBuf, pi);
387

H
Haojun Liao 已提交
388
      pData = getNewBufPage(pResultBuf, tid, &pageId);
389
      if (pData != NULL) {
390
        pData->num = sizeof(SFilePage);
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410
      }
    }
  }

  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 已提交
411 412 413
static bool chkWindowOutputBufByKey(STaskRuntimeEnv* pRuntimeEnv, SResultRowInfo* pResultRowInfo, STimeWindow* win,
                                    bool masterscan, SResultRow** pResult, int64_t groupId, SqlFunctionCtx* pCtx,
                                    int32_t numOfOutput, int32_t* rowCellInfoOffset) {
414
  assert(win->skey <= win->ekey);
L
Liu Jicong 已提交
415
  return chkResultRowFromKey(pRuntimeEnv, pResultRowInfo, (char*)&win->skey, TSDB_KEYSIZE, masterscan, groupId);
416 417
}

418
//  query_range_start, query_range_end, window_duration, window_start, window_end
419
void initExecTimeWindowInfo(SColumnInfoData* pColData, STimeWindow* pQueryWindow) {
420 421 422
  pColData->info.type = TSDB_DATA_TYPE_TIMESTAMP;
  pColData->info.bytes = sizeof(int64_t);

423
  colInfoDataEnsureCapacity(pColData, 0, 5);
424 425 426 427 428 429 430 431 432
  colDataAppendInt64(pColData, 0, &pQueryWindow->skey);
  colDataAppendInt64(pColData, 1, &pQueryWindow->ekey);

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

X
Xiaoyu Wang 已提交
433 434 435
void doApplyFunctions(SExecTaskInfo* taskInfo, SqlFunctionCtx* pCtx, STimeWindow* pWin,
                      SColumnInfoData* pTimeWindowData, int32_t offset, int32_t forwardStep, TSKEY* tsCol,
                      int32_t numOfTotal, int32_t numOfOutput, int32_t order) {
436
  for (int32_t k = 0; k < numOfOutput; ++k) {
H
Haojun Liao 已提交
437
    // keep it temporarily
438
    // todo no need this??
dengyihao's avatar
dengyihao 已提交
439 440
    bool    hasAgg = pCtx[k].input.colDataAggIsSet;
    int32_t numOfRows = pCtx[k].input.numOfRows;
H
Haojun Liao 已提交
441
    int32_t startOffset = pCtx[k].input.startRowIndex;
442

443
    pCtx[k].input.startRowIndex = offset;
444
    pCtx[k].input.numOfRows = forwardStep;
445 446 447

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

452 453
    if (fmIsWindowPseudoColumnFunc(pCtx[k].functionId)) {
      SResultRowEntryInfo* pEntryInfo = GET_RES_INFO(&pCtx[k]);
454 455

      char* p = GET_ROWCELL_INTERBUF(pEntryInfo);
456

457
      SColumnInfoData idata = {0};
dengyihao's avatar
dengyihao 已提交
458
      idata.info.type = TSDB_DATA_TYPE_BIGINT;
459
      idata.info.bytes = tDataTypes[TSDB_DATA_TYPE_BIGINT].bytes;
dengyihao's avatar
dengyihao 已提交
460
      idata.pData = p;
461 462 463 464

      SScalarParam out = {.columnData = &idata};
      SScalarParam tw = {.numOfRows = 5, .columnData = pTimeWindowData};
      pCtx[k].sfp.process(&tw, 1, &out);
465
      pEntryInfo->numOfRes = 1;
466 467 468 469 470 471 472 473 474 475
    } else {
      int32_t code = TSDB_CODE_SUCCESS;
      if (functionNeedToExecute(&pCtx[k]) && pCtx[k].fpSet.process != NULL) {
        code = pCtx[k].fpSet.process(&pCtx[k]);

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

478 479 480 481 482
      // restore it
      pCtx[k].input.colDataAggIsSet = hasAgg;
      pCtx[k].input.startRowIndex = startOffset;
      pCtx[k].input.numOfRows = numOfRows;
    }
483 484 485
  }
}

L
Liu Jicong 已提交
486
static FORCE_INLINE TSKEY reviseWindowEkey(STaskAttr* pQueryAttr, STimeWindow* pWindow) {
dengyihao's avatar
dengyihao 已提交
487
  TSKEY   ekey = -1;
488 489
  int32_t order = TSDB_ORDER_ASC;
  if (order == TSDB_ORDER_ASC) {
490 491 492 493 494 495 496 497 498 499 500 501 502 503
    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 已提交
504
static int32_t doSetInputDataBlock(SOperatorInfo* pOperator, SqlFunctionCtx* pCtx, SSDataBlock* pBlock, int32_t order,
505
                                   int32_t scanFlag, bool createDummyCol);
506

dengyihao's avatar
dengyihao 已提交
507 508
static void doSetInputDataBlockInfo(SOperatorInfo* pOperator, SqlFunctionCtx* pCtx, SSDataBlock* pBlock,
                                    int32_t order) {
509
  for (int32_t i = 0; i < pOperator->numOfExprs; ++i) {
510
    pCtx[i].order = order;
511
    pCtx[i].input.numOfRows = pBlock->info.rows;
512
    setBlockStatisInfo(&pCtx[i], &pOperator->pExpr[i], pBlock);
513 514 515
  }
}

X
Xiaoyu Wang 已提交
516 517
void setInputDataBlock(SOperatorInfo* pOperator, SqlFunctionCtx* pCtx, SSDataBlock* pBlock, int32_t order,
                       int32_t scanFlag, bool createDummyCol) {
518
  if (pBlock->pBlockAgg != NULL) {
H
Haojun Liao 已提交
519
    doSetInputDataBlockInfo(pOperator, pCtx, pBlock, order);
520
  } else {
521
    doSetInputDataBlock(pOperator, pCtx, pBlock, order, scanFlag, createDummyCol);
H
Haojun Liao 已提交
522
  }
523 524
}

L
Liu Jicong 已提交
525 526
static int32_t doCreateConstantValColumnInfo(SInputColumnInfoData* pInput, SFunctParam* pFuncParam, int32_t paramIndex,
                                             int32_t numOfRows) {
527 528 529 530 531 532 533 534
  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)
535 536
    pColInfo->info.type = pFuncParam->param.nType;
    pColInfo->info.bytes = pFuncParam->param.nLen;
537 538

    pInput->pData[paramIndex] = pColInfo;
539 540
  } else {
    pColInfo = pInput->pData[paramIndex];
541 542
  }

543
  colInfoDataEnsureCapacity(pColInfo, 0, numOfRows);
544

545
  int8_t type = pFuncParam->param.nType;
546 547
  if (type == TSDB_DATA_TYPE_BIGINT || type == TSDB_DATA_TYPE_UBIGINT) {
    int64_t v = pFuncParam->param.i;
dengyihao's avatar
dengyihao 已提交
548
    for (int32_t i = 0; i < numOfRows; ++i) {
549 550 551 552
      colDataAppendInt64(pColInfo, i, &v);
    }
  } else if (type == TSDB_DATA_TYPE_DOUBLE) {
    double v = pFuncParam->param.d;
dengyihao's avatar
dengyihao 已提交
553
    for (int32_t i = 0; i < numOfRows; ++i) {
554 555
      colDataAppendDouble(pColInfo, i, &v);
    }
556
  } else if (type == TSDB_DATA_TYPE_VARCHAR) {
L
Liu Jicong 已提交
557
    char* tmp = taosMemoryMalloc(pFuncParam->param.nLen + VARSTR_HEADER_SIZE);
558
    STR_WITH_SIZE_TO_VARSTR(tmp, pFuncParam->param.pz, pFuncParam->param.nLen);
L
Liu Jicong 已提交
559
    for (int32_t i = 0; i < numOfRows; ++i) {
560 561
      colDataAppend(pColInfo, i, tmp, false);
    }
562 563 564 565 566
  }

  return TSDB_CODE_SUCCESS;
}

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

571
  for (int32_t i = 0; i < pOperator->numOfExprs; ++i) {
L
Liu Jicong 已提交
572
    pCtx[i].order = order;
573 574
    pCtx[i].input.numOfRows = pBlock->info.rows;

L
Liu Jicong 已提交
575
    pCtx[i].pSrcBlock = pBlock;
X
Xiaoyu Wang 已提交
576
    pCtx[i].scanFlag = scanFlag;
H
Haojun Liao 已提交
577

578
    SInputColumnInfoData* pInput = &pCtx[i].input;
579
    pInput->uid = pBlock->info.uid;
C
Cary Xu 已提交
580
    pInput->colDataAggIsSet = false;
581

582 583
    SExprInfo* pOneExpr = &pOperator->pExpr[i];
    for (int32_t j = 0; j < pOneExpr->base.numOfParams; ++j) {
dengyihao's avatar
dengyihao 已提交
584
      SFunctParam* pFuncParam = &pOneExpr->base.pParam[j];
G
Ganlin Zhao 已提交
585 586
      if (pFuncParam->type == FUNC_PARAM_TYPE_COLUMN) {
        int32_t slotId = pFuncParam->pCol->slotId;
dengyihao's avatar
dengyihao 已提交
587
        pInput->pData[j] = taosArrayGet(pBlock->pDataBlock, slotId);
588 589 590
        pInput->totalRows = pBlock->info.rows;
        pInput->numOfRows = pBlock->info.rows;
        pInput->startRowIndex = 0;
591

592
        // NOTE: the last parameter is the primary timestamp column
593 594 595
        if (fmIsTimelineFunc(pCtx[i].functionId) && (j == pOneExpr->base.numOfParams - 1)) {
          pInput->pPTS = pInput->pData[j];
        }
596 597
        ASSERT(pInput->pData[j] != NULL);
      } else if (pFuncParam->type == FUNC_PARAM_TYPE_VALUE) {
598 599 600
        // 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) {
601 602 603 604
          pInput->totalRows = pBlock->info.rows;
          pInput->numOfRows = pBlock->info.rows;
          pInput->startRowIndex = 0;

605
          code = doCreateConstantValColumnInfo(pInput, pFuncParam, j, pBlock->info.rows);
606 607 608
          if (code != TSDB_CODE_SUCCESS) {
            return code;
          }
609
        }
G
Ganlin Zhao 已提交
610 611
      }
    }
H
Haojun Liao 已提交
612
  }
613 614

  return code;
H
Haojun Liao 已提交
615 616
}

617
static int32_t doAggregateImpl(SOperatorInfo* pOperator, TSKEY startTs, SqlFunctionCtx* pCtx) {
618
  for (int32_t k = 0; k < pOperator->numOfExprs; ++k) {
H
Haojun Liao 已提交
619
    if (functionNeedToExecute(&pCtx[k])) {
620
      // todo add a dummy funtion to avoid process check
621 622 623 624 625 626 627 628
      if (pCtx[k].fpSet.process == NULL) {
        continue;
      }

      int32_t code = pCtx[k].fpSet.process(&pCtx[k]);
      if (code != TSDB_CODE_SUCCESS) {
        qError("%s aggregate function error happens, code: %s", GET_TASKID(pOperator->pTaskInfo), tstrerror(code));
        return code;
629
      }
630 631
    }
  }
632 633

  return TSDB_CODE_SUCCESS;
634 635
}

H
Haojun Liao 已提交
636
static void setPseudoOutputColInfo(SSDataBlock* pResult, SqlFunctionCtx* pCtx, SArray* pPseudoList) {
dengyihao's avatar
dengyihao 已提交
637
  size_t num = (pPseudoList != NULL) ? taosArrayGetSize(pPseudoList) : 0;
H
Haojun Liao 已提交
638 639 640 641 642
  for (int32_t i = 0; i < num; ++i) {
    pCtx[i].pOutput = taosArrayGet(pResult->pDataBlock, i);
  }
}

643
int32_t projectApplyFunctions(SExprInfo* pExpr, SSDataBlock* pResult, SSDataBlock* pSrcBlock, SqlFunctionCtx* pCtx,
X
Xiaoyu Wang 已提交
644
                              int32_t numOfOutput, SArray* pPseudoList) {
H
Haojun Liao 已提交
645
  setPseudoOutputColInfo(pResult, pCtx, pPseudoList);
H
Haojun Liao 已提交
646
  pResult->info.groupId = pSrcBlock->info.groupId;
H
Haojun Liao 已提交
647

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

652 653
  int32_t numOfRows = 0;

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

L
Liu Jicong 已提交
658
    if (pExpr[k].pExpr->nodeType == QUERY_NODE_COLUMN) {  // it is a project query
659
      SColumnInfoData* pColInfoData = taosArrayGet(pResult->pDataBlock, outputSlotId);
660
      if (pResult->info.rows > 0 && !createNewColModel) {
X
Xiaoyu Wang 已提交
661 662
        colDataMergeCol(pColInfoData, pResult->info.rows, &pResult->info.capacity, pfCtx->input.pData[0],
                        pfCtx->input.numOfRows);
663 664 665
      } else {
        colDataAssign(pColInfoData, pfCtx->input.pData[0], pfCtx->input.numOfRows);
      }
666

667
      numOfRows = pfCtx->input.numOfRows;
668
    } else if (pExpr[k].pExpr->nodeType == QUERY_NODE_VALUE) {
669
      SColumnInfoData* pColInfoData = taosArrayGet(pResult->pDataBlock, outputSlotId);
670

dengyihao's avatar
dengyihao 已提交
671
      int32_t offset = createNewColModel ? 0 : pResult->info.rows;
672
      for (int32_t i = 0; i < pSrcBlock->info.rows; ++i) {
dengyihao's avatar
dengyihao 已提交
673 674 675
        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);
676
      }
677 678

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

683
      SColumnInfoData* pResColData = taosArrayGet(pResult->pDataBlock, outputSlotId);
684
      SColumnInfoData  idata = {.info = pResColData->info, .hasNull = true};
685

686
      SScalarParam dest = {.columnData = &idata};
X
Xiaoyu Wang 已提交
687
      int32_t      code = scalarCalculate(pExpr[k].pExpr->_optrRoot.pRootNode, pBlockList, &dest);
688 689 690 691
      if (code != TSDB_CODE_SUCCESS) {
        taosArrayDestroy(pBlockList);
        return code;
      }
692

dengyihao's avatar
dengyihao 已提交
693
      int32_t startOffset = createNewColModel ? 0 : pResult->info.rows;
694
      colInfoDataEnsureCapacity(pResColData, startOffset, pResult->info.capacity);
695
      colDataMergeCol(pResColData, startOffset, &pResult->info.capacity, &idata, dest.numOfRows);
696 697

      numOfRows = dest.numOfRows;
698 699
      taosArrayDestroy(pBlockList);
    } else if (pExpr[k].pExpr->nodeType == QUERY_NODE_FUNCTION) {
700
      ASSERT(!fmIsAggFunc(pfCtx->functionId));
701

702 703
      // _rowts/_c0, not tbname column
      if (fmIsPseudoColumnFunc(pfCtx->functionId) && (!fmIsScanPseudoColumnFunc(pfCtx->functionId))) {
H
Haojun Liao 已提交
704
        // do nothing
705 706 707 708 709 710 711 712 713 714 715 716 717 718
      } else if (fmIsIndefiniteRowsFunc(pfCtx->functionId)) {
        SResultRowEntryInfo* pResInfo = GET_RES_INFO(&pCtx[k]);
        pfCtx->fpSet.init(&pCtx[k], pResInfo);

        pfCtx->pOutput = taosArrayGet(pResult->pDataBlock, outputSlotId);
        pfCtx->offset = createNewColModel ? 0 : pResult->info.rows;  // set the start offset

        // set the timestamp(_rowts) output buffer
        if (taosArrayGetSize(pPseudoList) > 0) {
          int32_t* outputColIndex = taosArrayGet(pPseudoList, 0);
          pfCtx->pTsOutput = (SColumnInfoData*)pCtx[*outputColIndex].pOutput;
        }

        numOfRows = pfCtx->fpSet.process(pfCtx);
H
Haojun Liao 已提交
719 720 721
      } else {
        SArray* pBlockList = taosArrayInit(4, POINTER_BYTES);
        taosArrayPush(pBlockList, &pSrcBlock);
G
Ganlin Zhao 已提交
722

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

726
        SScalarParam dest = {.columnData = &idata};
X
Xiaoyu Wang 已提交
727
        int32_t      code = scalarCalculate((SNode*)pExpr[k].pExpr->_function.pFunctNode, pBlockList, &dest);
728 729 730 731
        if (code != TSDB_CODE_SUCCESS) {
          taosArrayDestroy(pBlockList);
          return code;
        }
732

dengyihao's avatar
dengyihao 已提交
733
        int32_t startOffset = createNewColModel ? 0 : pResult->info.rows;
734
        colInfoDataEnsureCapacity(pResColData, startOffset, pResult->info.capacity);
735
        colDataMergeCol(pResColData, startOffset, &pResult->info.capacity, &idata, dest.numOfRows);
736 737

        numOfRows = dest.numOfRows;
H
Haojun Liao 已提交
738 739
        taosArrayDestroy(pBlockList);
      }
740
    } else {
741
      ASSERT(0);
742 743
    }
  }
744

745 746 747
  if (!createNewColModel) {
    pResult->info.rows += numOfRows;
  }
748 749

  return TSDB_CODE_SUCCESS;
750 751
}

752 753 754
static void setResultRowKey(SResultRow* pResultRow, char* pData, int16_t type) {
  if (IS_VAR_DATA_TYPE(type)) {
    // todo disable this
755

756 757 758 759 760 761 762 763 764
    //    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);
765

766 767
    pResultRow->win.skey = v;
    pResultRow->win.ekey = v;
768 769 770
  }
}

5
54liuyao 已提交
771
bool functionNeedToExecute(SqlFunctionCtx* pCtx) {
772
  struct SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
773

774 775 776 777 778
  // in case of timestamp column, always generated results.
  int32_t functionId = pCtx->functionId;
  if (functionId == -1) {
    return false;
  }
779

780 781
  if (pCtx->scanFlag == REPEAT_SCAN) {
    return fmIsRepeatScanFunc(pCtx->functionId);
782 783
  }

784 785
  if (isRowEntryCompleted(pResInfo)) {
    return false;
786 787
  }

788 789 790
  return true;
}

791 792 793 794 795 796 797
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;
    }
798

799 800 801
    // Set the correct column info (data type and bytes)
    pInput->pData[paramIndex]->info.type = type;
    pInput->pData[paramIndex]->info.bytes = tDataTypes[type].bytes;
802
  }
H
Haojun Liao 已提交
803

804 805 806 807 808 809
  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;
810 811
    }
  } else {
812
    da = pInput->pColumnDataAgg[paramIndex];
813 814
  }

815
  ASSERT(!IS_VAR_DATA_TYPE(type));
816

817 818 819 820 821 822
  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};
823

824 825 826 827 828 829 830 831 832 833 834 835
    *(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
836
  } else {
837
    ASSERT(0);
838 839
  }

840 841
  return TSDB_CODE_SUCCESS;
}
842 843 844 845 846 847 848 849 850 851 852

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;

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

856 857
      if (pFuncParam->type == FUNC_PARAM_TYPE_COLUMN) {
        int32_t slotId = pFuncParam->pCol->slotId;
858 859 860 861
        pInput->pColumnDataAgg[j] = pBlock->pBlockAgg[slotId];
        if (pInput->pColumnDataAgg[j] == NULL) {
          pInput->colDataAggIsSet = false;
        }
862 863 864 865

        // 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);
866 867
      } else if (pFuncParam->type == FUNC_PARAM_TYPE_VALUE) {
        doCreateConstantValColumnAggInfo(pInput, pFuncParam, pFuncParam->param.nType, j, pBlock->info.rows);
868 869
      }
    }
870
  } else {
871
    pInput->colDataAggIsSet = false;
872 873 874
  }

  // set the statistics data for primary time stamp column
875 876 877 878 879
  //  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;
  //  }
880 881
}

L
Liu Jicong 已提交
882
bool isTaskKilled(SExecTaskInfo* pTaskInfo) {
883 884
  // query has been executed more than tsShellActivityTimer, and the retrieve has not arrived
  // abort current query execution.
L
Liu Jicong 已提交
885 886
  if (pTaskInfo->owner != 0 &&
      ((taosGetTimestampSec() - pTaskInfo->cost.start / 1000) > 10 * getMaximumIdleDurationSec())
887 888
      /*(!needBuildResAfterQueryComplete(pTaskInfo))*/) {
    assert(pTaskInfo->cost.start != 0);
L
Liu Jicong 已提交
889 890 891
    //    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;
892 893 894 895 896
  }

  return false;
}

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

L
Liu Jicong 已提交
899
static bool isCachedLastQuery(STaskAttr* pQueryAttr) {
900 901
  for (int32_t i = 0; i < pQueryAttr->numOfOutput; ++i) {
    int32_t functionId = getExprFunctionId(&pQueryAttr->pExpr1[i]);
X
Xiaoyu Wang 已提交
902 903 904
    //    if (functionId == FUNCTION_LAST || functionId == FUNCTION_LAST_DST) {
    //      continue;
    //    }
905 906 907 908

    return false;
  }

909 910
  int32_t order = TSDB_ORDER_ASC;
  if (order != TSDB_ORDER_DESC || !TSWINDOW_IS_EQUAL(pQueryAttr->window, TSWINDOW_DESC_INITIALIZER)) {
911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929
    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 已提交
930
// todo refactor : return window
931
void getAlignQueryTimeWindow(SInterval* pInterval, int32_t precision, int64_t key, STimeWindow* win) {
H
Haojun Liao 已提交
932
  win->skey = taosTimeTruncate(key, pInterval, precision);
933 934

  /*
H
Haojun Liao 已提交
935
   * if the realSkey > INT64_MAX - pInterval->interval, the query duration between
936 937
   * realSkey and realEkey must be less than one interval.Therefore, no need to adjust the query ranges.
   */
938 939
  win->ekey = taosTimeAdd(win->skey, pInterval->interval, pInterval->intervalUnit, precision) - 1;
  if (win->ekey < win->skey) {
940 941 942 943
    win->ekey = INT64_MAX;
  }
}

L
Liu Jicong 已提交
944
static int32_t updateBlockLoadStatus(STaskAttr* pQuery, int32_t status) {
945 946 947
  bool hasFirstLastFunc = false;
  bool hasOtherFunc = false;

948
  if (status == BLK_DATA_DATA_LOAD || status == BLK_DATA_FILTEROUT) {
949 950 951 952 953
    return status;
  }

  for (int32_t i = 0; i < pQuery->numOfOutput; ++i) {
    int32_t functionId = getExprFunctionId(&pQuery->pExpr1[i]);
954
#if 0
955 956 957 958 959 960 961 962 963 964
    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;
    }
965
#endif
966 967
  }

968
  if (hasFirstLastFunc && status == BLK_DATA_NOT_LOAD) {
L
Liu Jicong 已提交
969
    if (!hasOtherFunc) {
970
      return BLK_DATA_FILTEROUT;
971
    } else {
972
      return BLK_DATA_DATA_LOAD;
973 974 975 976 977 978
    }
  }

  return status;
}

L
Liu Jicong 已提交
979 980
// static void updateDataCheckOrder(SQInfo *pQInfo, SQueryTableReq* pQueryMsg, bool stableQuery) {
//   STaskAttr* pQueryAttr = pQInfo->runtimeEnv.pQueryAttr;
H
Haojun Liao 已提交
981
//
L
Liu Jicong 已提交
982 983 984 985
//   // 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 已提交
986
//
L
Liu Jicong 已提交
987 988 989 990 991
//   // 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 已提交
992
//
L
Liu Jicong 已提交
993 994
//     pQueryAttr->order.order = TSDB_ORDER_ASC;
//     if (pQueryAttr->window.skey > pQueryAttr->window.ekey) {
wafwerar's avatar
wafwerar 已提交
995
//       TSWAP(pQueryAttr->window.skey, pQueryAttr->window.ekey);
L
Liu Jicong 已提交
996
//     }
H
Haojun Liao 已提交
997
//
L
Liu Jicong 已提交
998 999 1000
//     pQueryAttr->needReverseScan = false;
//     return;
//   }
H
Haojun Liao 已提交
1001
//
L
Liu Jicong 已提交
1002 1003 1004
//   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 已提交
1005
//       TSWAP(pQueryAttr->window.skey, pQueryAttr->window.ekey);
L
Liu Jicong 已提交
1006
//     }
H
Haojun Liao 已提交
1007
//
L
Liu Jicong 已提交
1008 1009 1010 1011
//     pQueryAttr->needReverseScan = false;
//     doUpdateLastKey(pQueryAttr);
//     return;
//   }
H
Haojun Liao 已提交
1012
//
L
Liu Jicong 已提交
1013 1014 1015 1016 1017 1018
//   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 已提交
1019
//
L
Liu Jicong 已提交
1020 1021 1022
//     pQueryAttr->order.order = TSDB_ORDER_ASC;
//     return;
//   }
H
Haojun Liao 已提交
1023
//
L
Liu Jicong 已提交
1024 1025 1026 1027
//   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 已提交
1028 1029
////               pQueryAttr->window.ekey, pQueryAttr->window.ekey, pQueryAttr->window.skey);
//
wafwerar's avatar
wafwerar 已提交
1030
//        TSWAP(pQueryAttr->window.skey, pQueryAttr->window.ekey);
H
Haojun Liao 已提交
1031 1032 1033 1034 1035 1036 1037 1038 1039 1040
//        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 已提交
1041
//        TSWAP(pQueryAttr->window.skey, pQueryAttr->window.ekey);
H
Haojun Liao 已提交
1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053
//        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 已提交
1054 1055
////                 pQueryAttr->window.skey, pQueryAttr->window.ekey, pQueryAttr->window.ekey,
/// pQueryAttr->window.skey);
H
Haojun Liao 已提交
1056
//
wafwerar's avatar
wafwerar 已提交
1057
//          TSWAP(pQueryAttr->window.skey, pQueryAttr->window.ekey);
H
Haojun Liao 已提交
1058 1059 1060 1061 1062 1063 1064 1065
//          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 已提交
1066 1067
////                 pQueryAttr->window.skey, pQueryAttr->window.ekey, pQueryAttr->window.ekey,
/// pQueryAttr->window.skey);
H
Haojun Liao 已提交
1068
//
wafwerar's avatar
wafwerar 已提交
1069
//          TSWAP(pQueryAttr->window.skey, pQueryAttr->window.ekey);
H
Haojun Liao 已提交
1070 1071 1072 1073 1074 1075 1076 1077 1078
//          doUpdateLastKey(pQueryAttr);
//        }
//
//        pQueryAttr->order.order = TSDB_ORDER_DESC;
//        pQueryAttr->needReverseScan = false;
//      }
//    }
//  }
//}
1079

L
Liu Jicong 已提交
1080 1081 1082
// static FORCE_INLINE bool doFilterByBlockStatistics(STaskRuntimeEnv* pRuntimeEnv, SDataStatis *pDataStatis,
// SqlFunctionCtx *pCtx, int32_t numOfRows) {
//   STaskAttr* pQueryAttr = pRuntimeEnv->pQueryAttr;
1083
//
L
Liu Jicong 已提交
1084 1085 1086
//   if (pDataStatis == NULL || pQueryAttr->pFilters == NULL) {
//     return true;
//   }
1087
//
L
Liu Jicong 已提交
1088 1089
//   return filterRangeExecute(pQueryAttr->pFilters, pDataStatis, pQueryAttr->numOfCols, numOfRows);
// }
1090

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

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

1097
  if (true) {
L
Liu Jicong 已提交
1098
    //    getAlignQueryTimeWindow(pQueryAttr, pBlockInfo->window.skey, sk, ek, &w);
1099 1100 1101 1102 1103 1104
    assert(w.ekey >= pBlockInfo->window.skey);

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

L
Liu Jicong 已提交
1105 1106
    while (1) {
      //      getNextTimeWindow(pQueryAttr, &w);
1107 1108 1109 1110 1111 1112 1113 1114 1115 1116
      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 已提交
1117
    //    getAlignQueryTimeWindow(pQueryAttr, pBlockInfo->window.ekey, sk, ek, &w);
1118 1119 1120 1121 1122 1123
    assert(w.skey <= pBlockInfo->window.ekey);

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

L
Liu Jicong 已提交
1124 1125
    while (1) {
      //      getNextTimeWindow(pQueryAttr, &w);
1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189
      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 已提交
1190
  SqlFunctionCtx* pCtx = pTableScanInfo->pCtx;
1191
  uint32_t        status = BLK_DATA_NOT_LOAD;
1192 1193 1194 1195

  int32_t numOfOutput = pTableScanInfo->numOfOutput;
  for (int32_t i = 0; i < numOfOutput; ++i) {
    int32_t functionId = pCtx[i].functionId;
H
Haojun Liao 已提交
1196
    int32_t colId = pTableScanInfo->pExpr[i].base.pParam[0].pCol->colId;
1197 1198 1199

    // group by + first/last should not apply the first/last block filter
    if (functionId < 0) {
1200
      status |= BLK_DATA_DATA_LOAD;
1201 1202
      return status;
    } else {
L
Liu Jicong 已提交
1203
      //      status |= aAggs[functionId].dataReqFunc(&pTableScanInfo->pCtx[i], &pBlock->info.window, colId);
1204
      //      if ((status & BLK_DATA_DATA_LOAD) == BLK_DATA_DATA_LOAD) {
L
Liu Jicong 已提交
1205 1206
      //        return status;
      //      }
1207 1208 1209 1210 1211 1212
    }
  }

  return status;
}

L
Liu Jicong 已提交
1213 1214
int32_t loadDataBlockOnDemand(SExecTaskInfo* pTaskInfo, STableScanInfo* pTableScanInfo, SSDataBlock* pBlock,
                              uint32_t* status) {
1215
  *status = BLK_DATA_NOT_LOAD;
1216

H
Haojun Liao 已提交
1217
  pBlock->pDataBlock = NULL;
L
Liu Jicong 已提交
1218
  pBlock->pBlockAgg = NULL;
H
Haojun Liao 已提交
1219

L
Liu Jicong 已提交
1220 1221
  //  int64_t groupId = pRuntimeEnv->current->groupIndex;
  //  bool    ascQuery = QUERY_IS_ASC_QUERY(pQueryAttr);
1222

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

1225 1226
//  pCost->totalBlocks += 1;
//  pCost->totalRows += pBlock->info.rows;
H
Haojun Liao 已提交
1227
#if 0
1228 1229 1230
  // 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 已提交
1231
      (QUERY_IS_INTERVAL_QUERY(pQueryAttr) && overlapWithTimeWindow(pTaskInfo, &pBlock->info))) {
1232
    (*status) = BLK_DATA_DATA_LOAD;
1233 1234 1235
  }

  // check if this data block is required to load
1236
  if ((*status) != BLK_DATA_DATA_LOAD) {
1237 1238 1239 1240 1241 1242 1243
    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 已提交
1244
      bool  masterScan = IS_MAIN_SCAN(pRuntimeEnv);
1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267
      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 {
1268
      (*status) = BLK_DATA_DATA_LOAD;
1269 1270 1271 1272
    }
  }

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

1275
  if ((*status) == BLK_DATA_NOT_LOAD || (*status) == BLK_DATA_FILTEROUT) {
1276 1277
    //qDebug("QInfo:0x%"PRIx64" data block discard, brange:%" PRId64 "-%" PRId64 ", rows:%d", pQInfo->qId, pBlockInfo->window.skey,
//           pBlockInfo->window.ekey, pBlockInfo->rows);
1278
    pCost->skipBlocks += 1;
1279
  } else if ((*status) == BLK_DATA_SMA_LOAD) {
1280 1281
    // this function never returns error?
    pCost->loadBlockStatis += 1;
1282
//    tsdbRetrieveDataBlockStatisInfo(pTableScanInfo->pTsdbReadHandle, &pBlock->pBlockAgg);
1283 1284

    if (pBlock->pBlockAgg == NULL) {  // data block statistics does not exist, load data block
1285
//      pBlock->pDataBlock = tsdbRetrieveDataBlock(pTableScanInfo->pTsdbReadHandle, NULL);
1286 1287 1288
      pCost->totalCheckedRows += pBlock->info.rows;
    }
  } else {
1289
    assert((*status) == BLK_DATA_DATA_LOAD);
1290 1291 1292

    // load the data block statistics to perform further filter
    pCost->loadBlockStatis += 1;
1293
//    tsdbRetrieveDataBlockStatisInfo(pTableScanInfo->pTsdbReadHandle, &pBlock->pBlockAgg);
1294 1295 1296 1297 1298 1299

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

H
Haojun Liao 已提交
1300
          bool  masterScan = IS_MAIN_SCAN(pRuntimeEnv);
1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317
          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
1318
            pCost->skipBlocks += 1;
1319 1320
            //qDebug("QInfo:0x%"PRIx64" data block discard, brange:%" PRId64 "-%" PRId64 ", rows:%d", pQInfo->qId,
//                   pBlockInfo->window.skey, pBlockInfo->window.ekey, pBlockInfo->rows);
1321
            (*status) = BLK_DATA_FILTEROUT;
1322 1323 1324 1325 1326 1327 1328 1329
            return TSDB_CODE_SUCCESS;
          }
        }
      }
    }

    // current block has been discard due to filter applied
//    if (!doFilterByBlockStatistics(pRuntimeEnv, pBlock->pBlockAgg, pTableScanInfo->pCtx, pBlockInfo->rows)) {
1330
//      pCost->skipBlocks += 1;
1331 1332
//      qDebug("QInfo:0x%"PRIx64" data block discard, brange:%" PRId64 "-%" PRId64 ", rows:%d", pQInfo->qId, pBlockInfo->window.skey,
//             pBlockInfo->window.ekey, pBlockInfo->rows);
1333
//      (*status) = BLK_DATA_FILTEROUT;
1334 1335 1336 1337 1338
//      return TSDB_CODE_SUCCESS;
//    }

    pCost->totalCheckedRows += pBlockInfo->rows;
    pCost->loadBlocks += 1;
1339
//    pBlock->pDataBlock = tsdbRetrieveDataBlock(pTableScanInfo->pTsdbReadHandle, NULL);
1340 1341 1342 1343 1344 1345 1346
//    if (pBlock->pDataBlock == NULL) {
//      return terrno;
//    }

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

1348 1349 1350 1351
//    if (pQueryAttr->pFilters != NULL || pRuntimeEnv->pTsBuf != NULL) {
//      filterColRowsInDataBlock(pRuntimeEnv, pBlock, ascQuery);
//    }
  }
H
Haojun Liao 已提交
1352
#endif
1353 1354 1355
  return TSDB_CODE_SUCCESS;
}

L
Liu Jicong 已提交
1356
static void updateTableQueryInfoForReverseScan(STableQueryInfo* pTableQueryInfo) {
1357 1358 1359 1360
  if (pTableQueryInfo == NULL) {
    return;
  }

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

L
Liu Jicong 已提交
1364 1365
  //  SWITCH_ORDER(pTableQueryInfo->cur.order);
  //  pTableQueryInfo->cur.vgroupIndex = -1;
1366 1367

  // set the index to be the end slot of result rows array
dengyihao's avatar
dengyihao 已提交
1368 1369 1370 1371 1372 1373
  //  SResultRowInfo* pResultRowInfo = &pTableQueryInfo->resInfo;
  //  if (pResultRowInfo->size > 0) {
  //    pResultRowInfo->curPos = pResultRowInfo->size - 1;
  //  } else {
  //    pResultRowInfo->curPos = -1;
  //  }
1374 1375
}

H
Haojun Liao 已提交
1376
void initResultRow(SResultRow* pResultRow) {
X
Xiaoyu Wang 已提交
1377
  //  pResultRow->pEntryInfo = (struct SResultRowEntryInfo*)((char*)pResultRow + sizeof(SResultRow));
1378 1379 1380 1381 1382
}

/*
 * 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 已提交
1383 1384 1385
 * +------------+-----------------result column 1------------+------------------result column 2-----------+
 * | SResultRow | SResultRowEntryInfo | intermediate buffer1 | SResultRowEntryInfo | intermediate buffer 2|
 * +------------+--------------------------------------------+--------------------------------------------+
1386 1387
 *           offset[0]                                  offset[1]                                   offset[2]
 */
1388
// TODO refactor: some function move away
X
Xiaoyu Wang 已提交
1389 1390
void setFunctionResultOutput(SOptrBasicInfo* pInfo, SAggSupporter* pSup, int32_t stage, int32_t numOfExprs,
                             SExecTaskInfo* pTaskInfo) {
L
Liu Jicong 已提交
1391 1392
  SqlFunctionCtx* pCtx = pInfo->pCtx;
  int32_t*        rowCellInfoOffset = pInfo->rowCellInfoOffset;
H
Haojun Liao 已提交
1393

H
Haojun Liao 已提交
1394
  SResultRowInfo* pResultRowInfo = &pInfo->resultRowInfo;
1395
  initResultRowInfo(pResultRowInfo);
H
Haojun Liao 已提交
1396

L
Liu Jicong 已提交
1397 1398
  int64_t     tid = 0;
  int64_t     groupId = 0;
1399 1400
  SResultRow* pRow = doSetResultOutBufByKey(pSup->pResultBuf, pResultRowInfo, (char*)&tid, sizeof(tid), true, groupId,
                                            pTaskInfo, false, pSup);
H
Haojun Liao 已提交
1401

1402
  for (int32_t i = 0; i < numOfExprs; ++i) {
1403
    struct SResultRowEntryInfo* pEntry = getResultEntryInfo(pRow, i, rowCellInfoOffset);
H
Haojun Liao 已提交
1404 1405
    cleanupResultRowEntry(pEntry);

L
Liu Jicong 已提交
1406
    pCtx[i].resultInfo = pEntry;
1407
    pCtx[i].scanFlag = stage;
H
Haojun Liao 已提交
1408 1409
  }

1410
  initCtxOutputBuffer(pCtx, numOfExprs);
H
Haojun Liao 已提交
1411 1412
}

H
Haojun Liao 已提交
1413
void initCtxOutputBuffer(SqlFunctionCtx* pCtx, int32_t size) {
1414 1415
  for (int32_t j = 0; j < size; ++j) {
    struct SResultRowEntryInfo* pResInfo = GET_RES_INFO(&pCtx[j]);
dengyihao's avatar
dengyihao 已提交
1416 1417
    if (isRowEntryInitialized(pResInfo) || fmIsPseudoColumnFunc(pCtx[j].functionId) || pCtx[j].functionId == -1 ||
        fmIsScalarFunc(pCtx[j].functionId)) {
1418 1419 1420
      continue;
    }

H
Haojun Liao 已提交
1421
    pCtx[j].fpSet.init(&pCtx[j], pCtx[j].resultInfo);
1422 1423 1424
  }
}

L
Liu Jicong 已提交
1425
void setTaskStatus(SExecTaskInfo* pTaskInfo, int8_t status) {
1426
  if (status == TASK_NOT_COMPLETED) {
H
Haojun Liao 已提交
1427
    pTaskInfo->status = status;
1428 1429
  } else {
    // QUERY_NOT_COMPLETED is not compatible with any other status, so clear its position first
1430
    CLEAR_QUERY_STATUS(pTaskInfo, TASK_NOT_COMPLETED);
H
Haojun Liao 已提交
1431
    pTaskInfo->status |= status;
1432 1433 1434
  }
}

L
Liu Jicong 已提交
1435
void destroyTableQueryInfoImpl(STableQueryInfo* pTableQueryInfo) {
1436 1437 1438 1439
  if (pTableQueryInfo == NULL) {
    return;
  }

L
Liu Jicong 已提交
1440
  //  taosVariantDestroy(&pTableQueryInfo->tag);
dengyihao's avatar
dengyihao 已提交
1441
  //  cleanupResultRowInfo(&pTableQueryInfo->resInfo);
1442 1443
}

1444
void setResultRowInitCtx(SResultRow* pResult, SqlFunctionCtx* pCtx, int32_t numOfOutput, int32_t* rowCellInfoOffset) {
1445
  for (int32_t i = 0; i < numOfOutput; ++i) {
1446
    pCtx[i].resultInfo = getResultEntryInfo(pResult, i, rowCellInfoOffset);
1447 1448 1449 1450 1451

    struct SResultRowEntryInfo* pResInfo = pCtx[i].resultInfo;
    if (isRowEntryCompleted(pResInfo) && isRowEntryInitialized(pResInfo)) {
      continue;
    }
1452 1453 1454 1455 1456

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

1457 1458 1459 1460 1461 1462
    if (!pResInfo->initialized) {
      if (pCtx[i].functionId != -1) {
        pCtx[i].fpSet.init(&pCtx[i], pResInfo);
      } else {
        pResInfo->initialized = true;
      }
1463 1464 1465 1466
    }
  }
}

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

1469
void doFilter(const SNode* pFilterNode, SSDataBlock* pBlock) {
1470 1471 1472 1473 1474
  if (pFilterNode == NULL) {
    return;
  }

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

H
Haojun Liao 已提交
1476
  // todo move to the initialization function
H
Haojun Liao 已提交
1477
  int32_t code = filterInitFromNode((SNode*)pFilterNode, &filter, 0);
1478 1479 1480 1481 1482

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

  int8_t* rowRes = NULL;
1483

1484
  // todo the keep seems never to be True??
1485
  bool keep = filterExecute(filter, pBlock, &rowRes, NULL, param1.numOfCols);
D
dapan1121 已提交
1486
  filterFreeInfo(filter);
1487

H
Haojun Liao 已提交
1488
  extractQualifiedTupleByFilterResult(pBlock, rowRes, keep);
1489
  blockDataUpdateTsWindow(pBlock, 0);
1490 1491
}

H
Haojun Liao 已提交
1492
void extractQualifiedTupleByFilterResult(SSDataBlock* pBlock, const int8_t* rowRes, bool keep) {
1493 1494 1495 1496 1497
  if (keep) {
    return;
  }

  if (rowRes != NULL) {
1498
    SSDataBlock* px = createOneDataBlock(pBlock, true);
1499

1500
    int32_t totalRows = pBlock->info.rows;
1501
    for (int32_t i = 0; i < pBlock->info.numOfCols; ++i) {
1502 1503
      SColumnInfoData* pSrc = taosArrayGet(px->pDataBlock, i);
      SColumnInfoData* pDst = taosArrayGet(pBlock->pDataBlock, i);
1504
      // it is a reserved column for scalar function, and no data in this column yet.
1505
      if (pDst->pData == NULL) {
1506 1507 1508
        continue;
      }

1509 1510
      colInfoDataCleanup(pDst, pBlock->info.rows);

1511
      int32_t numOfRows = 0;
1512
      for (int32_t j = 0; j < totalRows; ++j) {
D
dapan1121 已提交
1513 1514 1515
        if (rowRes[j] == 0) {
          continue;
        }
1516

D
dapan1121 已提交
1517
        if (colDataIsNull_s(pSrc, j)) {
1518
          colDataAppendNULL(pDst, numOfRows);
D
dapan1121 已提交
1519
        } else {
1520
          colDataAppend(pDst, numOfRows, colDataGetData(pSrc, j), false);
D
dapan1121 已提交
1521
        }
1522
        numOfRows += 1;
H
Haojun Liao 已提交
1523
      }
1524

1525 1526 1527 1528 1529
      if (pBlock->info.rows == totalRows) {
        pBlock->info.rows = numOfRows;
      } else {
        ASSERT(pBlock->info.rows == numOfRows);
      }
1530
    }
1531

dengyihao's avatar
dengyihao 已提交
1532
    blockDataDestroy(px);  // fix memory leak
1533 1534 1535
  } else {
    // do nothing
    pBlock->info.rows = 0;
1536 1537 1538
  }
}

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

1544 1545
  SResultRowInfo* pResultRowInfo = &pAggInfo->binfo.resultRowInfo;
  SqlFunctionCtx* pCtx = pAggInfo->binfo.pCtx;
L
Liu Jicong 已提交
1546
  int32_t*        rowCellInfoOffset = pAggInfo->binfo.rowCellInfoOffset;
1547

1548
  SResultRow* pResultRow = doSetResultOutBufByKey(pAggInfo->aggSup.pResultBuf, pResultRowInfo, (char*)&groupId,
L
Liu Jicong 已提交
1549
                                                  sizeof(groupId), true, groupId, pTaskInfo, false, &pAggInfo->aggSup);
L
Liu Jicong 已提交
1550
  assert(pResultRow != NULL);
1551 1552 1553 1554 1555 1556

  /*
   * 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 已提交
1557 1558
    int32_t ret =
        addNewWindowResultBuf(pResultRow, pAggInfo->aggSup.pResultBuf, groupId, pAggInfo->binfo.pRes->info.rowSize);
1559 1560 1561 1562 1563
    if (ret != TSDB_CODE_SUCCESS) {
      return;
    }
  }

1564
  setResultRowInitCtx(pResultRow, pCtx, numOfOutput, rowCellInfoOffset);
1565 1566
}

H
Haojun Liao 已提交
1567 1568
void setExecutionContext(int32_t numOfOutput, uint64_t groupId, SExecTaskInfo* pTaskInfo, SAggOperatorInfo* pAggInfo) {
  if (pAggInfo->groupId != INT32_MIN && pAggInfo->groupId == groupId) {
1569 1570 1571
    return;
  }

H
Haojun Liao 已提交
1572
  doSetTableGroupOutputBuf(pAggInfo, numOfOutput, groupId, pTaskInfo);
1573 1574

  // record the current active group id
H
Haojun Liao 已提交
1575
  pAggInfo->groupId = groupId;
1576 1577
}

1578 1579
static void doUpdateNumOfRows(SResultRow* pRow, int32_t numOfExprs, const int32_t* rowCellOffset) {
  for (int32_t j = 0; j < numOfExprs; ++j) {
1580
    struct SResultRowEntryInfo* pResInfo = getResultEntryInfo(pRow, j, rowCellOffset);
1581 1582 1583 1584 1585 1586 1587 1588 1589 1590
    if (!isRowEntryInitialized(pResInfo)) {
      continue;
    }

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

1591
int32_t finalizeResultRowIntoResultDataBlock(SDiskbasedBuf* pBuf, SResultRowPosition* resultRowPosition,
S
shenglian zhou 已提交
1592 1593 1594
                                             SqlFunctionCtx* pCtx, SExprInfo* pExprInfo, int32_t numOfExprs,
                                             const int32_t* rowCellOffset, SSDataBlock* pBlock,
                                             SExecTaskInfo* pTaskInfo) {
1595 1596 1597 1598 1599 1600 1601 1602 1603
  SFilePage*  page = getBufPage(pBuf, resultRowPosition->pageId);
  SResultRow* pRow = (SResultRow*)((char*)page + resultRowPosition->offset);

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

1604 1605 1606 1607 1608 1609 1610
  while (pBlock->info.rows + pRow->numOfRows > pBlock->info.capacity) {
    int32_t code = blockDataEnsureCapacity(pBlock, pBlock->info.capacity * 1.25);
    if (TAOS_FAILED(code)) {
      releaseBufPage(pBuf, page);
      qError("%s ensure result data capacity failed, code %s", GET_TASKID(pTaskInfo), tstrerror(code));
      longjmp(pTaskInfo->env, code);
    }
1611 1612 1613 1614 1615
  }

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

1616
    pCtx[j].resultInfo = getResultEntryInfo(pRow, j, rowCellOffset);
1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636
    if (pCtx[j].fpSet.finalize) {
      int32_t code = pCtx[j].fpSet.finalize(&pCtx[j], pBlock);
      if (TAOS_FAILED(code)) {
        qError("%s build result data block error, code %s", GET_TASKID(pTaskInfo), tstrerror(code));
        longjmp(pTaskInfo->env, code);
      }
    } else if (strcmp(pCtx[j].pExpr->pExpr->_function.functionName, "_select_value") == 0) {
      // do nothing, todo refactor
    } else {
      // 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);
      }
    }
  }

  releaseBufPage(pBuf, page);
1637
  pBlock->info.rows += pRow->numOfRows;
1638 1639 1640 1641

  return 0;
}

X
Xiaoyu Wang 已提交
1642 1643 1644
int32_t doCopyToSDataBlock(SExecTaskInfo* pTaskInfo, SSDataBlock* pBlock, SExprInfo* pExprInfo, SDiskbasedBuf* pBuf,
                           SGroupResInfo* pGroupResInfo, const int32_t* rowCellOffset, SqlFunctionCtx* pCtx,
                           int32_t numOfExprs) {
1645
  int32_t numOfRows = getNumOfTotalRes(pGroupResInfo);
1646
  int32_t start = pGroupResInfo->index;
1647

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

1652
    SResultRow* pRow = (SResultRow*)((char*)page + pPos->pos.offset);
1653 1654

    doUpdateNumOfRows(pRow, numOfExprs, rowCellOffset);
1655 1656
    if (pRow->numOfRows == 0) {
      pGroupResInfo->index += 1;
1657
      releaseBufPage(pBuf, page);
1658 1659 1660
      continue;
    }

1661 1662 1663 1664 1665
    if (pBlock->info.groupId == 0) {
      pBlock->info.groupId = pPos->groupId;
    } else {
      // current value belongs to different group, it can't be packed into one datablock
      if (pBlock->info.groupId != pPos->groupId) {
1666
        releaseBufPage(pBuf, page);
1667 1668 1669 1670
        break;
      }
    }

1671
    if (pBlock->info.rows + pRow->numOfRows > pBlock->info.capacity) {
1672
      releaseBufPage(pBuf, page);
1673 1674 1675 1676 1677
      break;
    }

    pGroupResInfo->index += 1;

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

1681
      pCtx[j].resultInfo = getResultEntryInfo(pRow, j, rowCellOffset);
1682
      if (pCtx[j].fpSet.finalize) {
1683
        int32_t code = pCtx[j].fpSet.finalize(&pCtx[j], pBlock);
1684
        if (TAOS_FAILED(code)) {
1685 1686
          qError("%s build result data block error, code %s", GET_TASKID(pTaskInfo), tstrerror(code));
          longjmp(pTaskInfo->env, code);
1687
        }
1688 1689
      } else if (strcmp(pCtx[j].pExpr->pExpr->_function.functionName, "_select_value") == 0) {
        // do nothing, todo refactor
1690
      } else {
1691 1692
        // expand the result into multiple rows. E.g., _wstartts, top(k, 20)
        // the _wstartts needs to copy to 20 following rows, since the results of top-k expands to 20 different rows.
X
Xiaoyu Wang 已提交
1693 1694
        SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, slotId);
        char*            in = GET_ROWCELL_INTERBUF(pCtx[j].resultInfo);
1695
        if (pCtx[j].increase) {
L
Liu Jicong 已提交
1696
          int64_t ts = *(int64_t*)in;
1697
          for (int32_t k = 0; k < pRow->numOfRows; ++k) {
L
Liu Jicong 已提交
1698
            colDataAppend(pColInfoData, pBlock->info.rows + k, (const char*)&ts, pCtx[j].resultInfo->isNullRes);
1699 1700 1701 1702 1703 1704
            ts++;
          }
        } else {
          for (int32_t k = 0; k < pRow->numOfRows; ++k) {
            colDataAppend(pColInfoData, pBlock->info.rows + k, in, pCtx[j].resultInfo->isNullRes);
          }
X
Xiaoyu Wang 已提交
1705
        }
1706
      }
1707 1708
    }

1709
    releaseBufPage(pBuf, page);
1710 1711
    pBlock->info.rows += pRow->numOfRows;
    if (pBlock->info.rows >= pBlock->info.capacity) {  // output buffer is full
1712 1713 1714 1715
      break;
    }
  }

X
Xiaoyu Wang 已提交
1716 1717
  qDebug("%s result generated, rows:%d, groupId:%" PRIu64, GET_TASKID(pTaskInfo), pBlock->info.rows,
         pBlock->info.groupId);
1718
  blockDataUpdateTsWindow(pBlock, 0);
1719 1720 1721
  return 0;
}

X
Xiaoyu Wang 已提交
1722 1723 1724 1725
void doBuildResultDatablock(SOperatorInfo* pOperator, SOptrBasicInfo* pbInfo, SGroupResInfo* pGroupResInfo,
                            SDiskbasedBuf* pBuf) {
  SExprInfo*     pExprInfo = pOperator->pExpr;
  int32_t        numOfExprs = pOperator->numOfExprs;
1726 1727
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;

X
Xiaoyu Wang 已提交
1728 1729 1730
  int32_t*        rowCellOffset = pbInfo->rowCellInfoOffset;
  SSDataBlock*    pBlock = pbInfo->pRes;
  SqlFunctionCtx* pCtx = pbInfo->pCtx;
1731

1732
  blockDataCleanup(pBlock);
1733
  if (!hasDataInGroupInfo(pGroupResInfo)) {
1734 1735 1736
    return;
  }

1737 1738
  // clear the existed group id
  pBlock->info.groupId = 0;
1739
  doCopyToSDataBlock(pTaskInfo, pBlock, pExprInfo, pBuf, pGroupResInfo, rowCellOffset, pCtx, numOfExprs);
1740 1741
}

L
Liu Jicong 已提交
1742 1743
static void updateNumOfRowsInResultRows(SqlFunctionCtx* pCtx, int32_t numOfOutput, SResultRowInfo* pResultRowInfo,
                                        int32_t* rowCellInfoOffset) {
1744
  // update the number of result for each, only update the number of rows for the corresponding window result.
L
Liu Jicong 已提交
1745 1746 1747
  //  if (QUERY_IS_INTERVAL_QUERY(pQueryAttr)) {
  //    return;
  //  }
H
Haojun Liao 已提交
1748
#if 0
1749
  for (int32_t i = 0; i < pResultRowInfo->size; ++i) {
L
Liu Jicong 已提交
1750
    SResultRow* pResult = pResultRowInfo->pResult[i];
1751 1752 1753 1754 1755 1756 1757

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

1758
      SResultRowEntryInfo* pCell = getResultEntryInfo(pResult, j, rowCellInfoOffset);
1759
      pResult->numOfRows = (uint16_t)(TMAX(pResult->numOfRows, pCell->numOfRes));
1760 1761
    }
  }
H
Haojun Liao 已提交
1762
#endif
1763 1764
}

L
Liu Jicong 已提交
1765
static int32_t compressQueryColData(SColumnInfoData* pColRes, int32_t numOfRows, char* data, int8_t compressed) {
1766 1767
  int32_t colSize = pColRes->info.bytes * numOfRows;
  return (*(tDataTypes[pColRes->info.type].compFunc))(pColRes->pData, colSize, numOfRows, data,
L
Liu Jicong 已提交
1768
                                                      colSize + COMP_OVERFLOW_BYTES, compressed, NULL, 0);
1769 1770
}

1771 1772 1773
int32_t doFillTimeIntervalGapsInResults(struct SFillInfo* pFillInfo, SSDataBlock* pBlock, int32_t capacity) {
  int32_t numOfRows = (int32_t)taosFillResultDataBlock(pFillInfo, pBlock, capacity - pBlock->info.rows);
  pBlock->info.rows += numOfRows;
1774

1775
  return pBlock->info.rows;
1776 1777
}

L
Liu Jicong 已提交
1778 1779
void queryCostStatis(SExecTaskInfo* pTaskInfo) {
  STaskCostInfo* pSummary = &pTaskInfo->cost;
1780

L
Liu Jicong 已提交
1781 1782 1783
  //  uint64_t hashSize = taosHashGetMemSize(pQInfo->runtimeEnv.pResultRowHashTable);
  //  hashSize += taosHashGetMemSize(pRuntimeEnv->tableqinfoGroupInfo.map);
  //  pSummary->hashSize = hashSize;
1784 1785 1786 1787

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

L
Liu Jicong 已提交
1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798
  //  SResultRowPool* p = pTaskInfo->pool;
  //  if (p != NULL) {
  //    pSummary->winInfoSize = getResultRowPoolMemSize(p);
  //    pSummary->numOfTimeWindows = getNumOfAllocatedResultRows(p);
  //  } else {
  //    pSummary->winInfoSize = 0;
  //    pSummary->numOfTimeWindows = 0;
  //  }
  //
  //  calculateOperatorProfResults(pQInfo);

1799 1800
  SFileBlockLoadRecorder* pRecorder = pSummary->pRecoder;
  if (pSummary->pRecoder != NULL) {
X
Xiaoyu Wang 已提交
1801 1802
    qDebug("%s :cost summary: elapsed time:%" PRId64 " us, first merge:%" PRId64
           " us, total blocks:%d, "
1803 1804 1805 1806
           "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 已提交
1807 1808 1809
  // 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);
1810 1811
}

L
Liu Jicong 已提交
1812 1813 1814
// static void updateOffsetVal(STaskRuntimeEnv *pRuntimeEnv, SDataBlockInfo *pBlockInfo) {
//   STaskAttr *pQueryAttr = pRuntimeEnv->pQueryAttr;
//   STableQueryInfo* pTableQueryInfo = pRuntimeEnv->current;
1815
//
L
Liu Jicong 已提交
1816
//   int32_t step = GET_FORWARD_DIRECTION_FACTOR(pQueryAttr->order.order);
1817
//
L
Liu Jicong 已提交
1818 1819 1820 1821
//   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;
//   }
1822
//
L
Liu Jicong 已提交
1823 1824 1825 1826 1827
//   if (QUERY_IS_ASC_QUERY(pQueryAttr)) {
//     pQueryAttr->pos = (int32_t)pQueryAttr->limit.offset;
//   } else {
//     pQueryAttr->pos = pBlockInfo->rows - (int32_t)pQueryAttr->limit.offset - 1;
//   }
1828
//
L
Liu Jicong 已提交
1829
//   assert(pQueryAttr->pos >= 0 && pQueryAttr->pos <= pBlockInfo->rows - 1);
1830
//
L
Liu Jicong 已提交
1831 1832
//   SArray *         pDataBlock = tsdbRetrieveDataBlock(pRuntimeEnv->pTsdbReadHandle, NULL);
//   SColumnInfoData *pColInfoData = taosArrayGet(pDataBlock, 0);
1833
//
L
Liu Jicong 已提交
1834 1835
//   // update the pQueryAttr->limit.offset value, and pQueryAttr->pos value
//   TSKEY *keys = (TSKEY *) pColInfoData->pData;
1836
//
L
Liu Jicong 已提交
1837 1838 1839
//   // update the offset value
//   pTableQueryInfo->lastKey = keys[pQueryAttr->pos];
//   pQueryAttr->limit.offset = 0;
1840
//
L
Liu Jicong 已提交
1841
//   int32_t numOfRes = tableApplyFunctionsOnBlock(pRuntimeEnv, pBlockInfo, NULL, binarySearchForKey, pDataBlock);
1842
//
L
Liu Jicong 已提交
1843 1844 1845 1846
//   //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);
// }
1847

L
Liu Jicong 已提交
1848 1849
// void skipBlocks(STaskRuntimeEnv *pRuntimeEnv) {
//   STaskAttr *pQueryAttr = pRuntimeEnv->pQueryAttr;
1850
//
L
Liu Jicong 已提交
1851 1852 1853
//   if (pQueryAttr->limit.offset <= 0 || pQueryAttr->numOfFilterCols > 0) {
//     return;
//   }
1854
//
L
Liu Jicong 已提交
1855 1856
//   pQueryAttr->pos = 0;
//   int32_t step = GET_FORWARD_DIRECTION_FACTOR(pQueryAttr->order.order);
1857
//
L
Liu Jicong 已提交
1858 1859
//   STableQueryInfo* pTableQueryInfo = pRuntimeEnv->current;
//   TsdbQueryHandleT pTsdbReadHandle = pRuntimeEnv->pTsdbReadHandle;
1860
//
L
Liu Jicong 已提交
1861 1862 1863 1864 1865
//   SDataBlockInfo blockInfo = SDATA_BLOCK_INITIALIZER;
//   while (tsdbNextDataBlock(pTsdbReadHandle)) {
//     if (isTaskKilled(pRuntimeEnv->qinfo)) {
//       longjmp(pRuntimeEnv->env, TSDB_CODE_TSC_QUERY_CANCELLED);
//     }
1866
//
L
Liu Jicong 已提交
1867
//     tsdbRetrieveDataBlockInfo(pTsdbReadHandle, &blockInfo);
1868
//
L
Liu Jicong 已提交
1869 1870 1871 1872
//     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;
1873
//
L
Liu Jicong 已提交
1874 1875 1876 1877 1878 1879 1880
//       //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;
//     }
//   }
1881
//
L
Liu Jicong 已提交
1882 1883 1884 1885 1886 1887 1888 1889 1890
//   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;
1891
//
L
Liu Jicong 已提交
1892 1893 1894
//   assert(pQueryAttr->limit.offset == 0);
//   STimeWindow tw = *win;
//   getNextTimeWindow(pQueryAttr, &tw);
1895
//
L
Liu Jicong 已提交
1896 1897
//   if ((tw.skey <= pBlockInfo->window.ekey && QUERY_IS_ASC_QUERY(pQueryAttr)) ||
//       (tw.ekey >= pBlockInfo->window.skey && !QUERY_IS_ASC_QUERY(pQueryAttr))) {
1898
//
L
Liu Jicong 已提交
1899 1900 1901 1902
//     // 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);
1903
//
L
Liu Jicong 已提交
1904 1905 1906 1907
//     tw = *win;
//     int32_t startPos =
//         getNextQualifiedWindow(pQueryAttr, &tw, pBlockInfo, pColInfoData->pData, binarySearchForKey, -1);
//     assert(startPos >= 0);
1908
//
L
Liu Jicong 已提交
1909 1910
//     // set the abort info
//     pQueryAttr->pos = startPos;
1911
//
L
Liu Jicong 已提交
1912 1913 1914 1915
//     // reset the query start timestamp
//     pTableQueryInfo->win.skey = ((TSKEY *)pColInfoData->pData)[startPos];
//     pQueryAttr->window.skey = pTableQueryInfo->win.skey;
//     TSKEY key = pTableQueryInfo->win.skey;
1916
//
L
Liu Jicong 已提交
1917 1918
//     pWindowResInfo->prevSKey = tw.skey;
//     int32_t index = pRuntimeEnv->resultRowInfo.curIndex;
1919
//
L
Liu Jicong 已提交
1920 1921
//     int32_t numOfRes = tableApplyFunctionsOnBlock(pRuntimeEnv, pBlockInfo, NULL, binarySearchForKey, pDataBlock);
//     pRuntimeEnv->resultRowInfo.curIndex = index;  // restore the window index
1922
//
L
Liu Jicong 已提交
1923 1924 1925 1926
//     //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);
1927
//
L
Liu Jicong 已提交
1928 1929 1930 1931 1932
//     return key;
//   } else {  // do nothing
//     pQueryAttr->window.skey      = tw.skey;
//     pWindowResInfo->prevSKey = tw.skey;
//     pTableQueryInfo->lastKey = tw.skey;
1933
//
L
Liu Jicong 已提交
1934 1935
//     return tw.skey;
//   }
1936
//
L
Liu Jicong 已提交
1937 1938 1939 1940 1941 1942 1943 1944 1945 1946
//   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);
//   }
1947
//
L
Liu Jicong 已提交
1948 1949 1950 1951 1952
//   // 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;
//   }
1953
//
L
Liu Jicong 已提交
1954 1955 1956 1957 1958 1959 1960
//   /*
//    * 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);
1961
//
L
Liu Jicong 已提交
1962 1963
//   STimeWindow w = TSWINDOW_INITIALIZER;
//   bool ascQuery = QUERY_IS_ASC_QUERY(pQueryAttr);
1964
//
L
Liu Jicong 已提交
1965 1966
//   SResultRowInfo *pWindowResInfo = &pRuntimeEnv->resultRowInfo;
//   STableQueryInfo *pTableQueryInfo = pRuntimeEnv->current;
1967
//
L
Liu Jicong 已提交
1968 1969 1970
//   SDataBlockInfo blockInfo = SDATA_BLOCK_INITIALIZER;
//   while (tsdbNextDataBlock(pRuntimeEnv->pTsdbReadHandle)) {
//     tsdbRetrieveDataBlockInfo(pRuntimeEnv->pTsdbReadHandle, &blockInfo);
1971
//
L
Liu Jicong 已提交
1972 1973 1974 1975 1976 1977 1978 1979 1980
//     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;
//     }
1981
//
L
Liu Jicong 已提交
1982 1983
//     // the first time window
//     STimeWindow win = getActiveTimeWindow(pWindowResInfo, pWindowResInfo->prevSKey, pQueryAttr);
1984
//
L
Liu Jicong 已提交
1985 1986
//     while (pQueryAttr->limit.offset > 0) {
//       STimeWindow tw = win;
1987
//
L
Liu Jicong 已提交
1988 1989 1990
//       if ((win.ekey <= blockInfo.window.ekey && ascQuery) || (win.ekey >= blockInfo.window.skey && !ascQuery)) {
//         pQueryAttr->limit.offset -= 1;
//         pWindowResInfo->prevSKey = win.skey;
1991
//
L
Liu Jicong 已提交
1992 1993 1994 1995 1996 1997
//         // 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;
//         }
//       }
1998
//
L
Liu Jicong 已提交
1999 2000 2001 2002
//       if (pQueryAttr->limit.offset == 0) {
//         *start = doSkipIntervalProcess(pRuntimeEnv, &win, &blockInfo, pTableQueryInfo);
//         return true;
//       }
2003
//
L
Liu Jicong 已提交
2004 2005
//       // current window does not ended in current data block, try next data block
//       getNextTimeWindow(pQueryAttr, &tw);
2006
//
L
Liu Jicong 已提交
2007 2008 2009 2010 2011 2012 2013 2014 2015
//       /*
//        * 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)) {
2016
//
L
Liu Jicong 已提交
2017 2018
//         SArray *pDataBlock = tsdbRetrieveDataBlock(pRuntimeEnv->pTsdbReadHandle, NULL);
//         SColumnInfoData *pColInfoData = taosArrayGet(pDataBlock, 0);
2019
//
L
Liu Jicong 已提交
2020 2021 2022
//         if ((win.ekey > blockInfo.window.ekey && ascQuery) || (win.ekey < blockInfo.window.skey && !ascQuery)) {
//           pQueryAttr->limit.offset -= 1;
//         }
2023
//
L
Liu Jicong 已提交
2024 2025 2026 2027 2028 2029 2030 2031
//         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);
2032
//
L
Liu Jicong 已提交
2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043
//           // 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.
//       }
//     }
//   }
2044
//
L
Liu Jicong 已提交
2045 2046 2047 2048
//   // check for error
//   if (terrno != TSDB_CODE_SUCCESS) {
//     longjmp(pRuntimeEnv->env, terrno);
//   }
2049
//
L
Liu Jicong 已提交
2050 2051
//   return true;
// }
2052

2053
int32_t appendDownstream(SOperatorInfo* p, SOperatorInfo** pDownstream, int32_t num) {
H
Haojun Liao 已提交
2054
  if (p->pDownstream == NULL) {
H
Haojun Liao 已提交
2055
    assert(p->numOfDownstream == 0);
2056 2057
  }

wafwerar's avatar
wafwerar 已提交
2058
  p->pDownstream = taosMemoryCalloc(1, num * POINTER_BYTES);
2059 2060 2061 2062 2063 2064 2065
  if (p->pDownstream == NULL) {
    return TSDB_CODE_OUT_OF_MEMORY;
  }

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

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

2070
static void doTableQueryInfoTimeWindowCheck(SExecTaskInfo* pTaskInfo, STableQueryInfo* pTableQueryInfo, int32_t order) {
H
Haojun Liao 已提交
2071 2072
#if 0
    if (order == TSDB_ORDER_ASC) {
2073 2074
    assert(
        (pTableQueryInfo->win.skey <= pTableQueryInfo->win.ekey) &&
H
Haojun Liao 已提交
2075 2076
        (pTableQueryInfo->lastKey >= pTaskInfo->window.skey) &&
        (pTableQueryInfo->win.skey >= pTaskInfo->window.skey && pTableQueryInfo->win.ekey <= pTaskInfo->window.ekey));
2077 2078 2079
  } else {
    assert(
        (pTableQueryInfo->win.skey >= pTableQueryInfo->win.ekey) &&
H
Haojun Liao 已提交
2080 2081
        (pTableQueryInfo->lastKey <= pTaskInfo->window.skey) &&
        (pTableQueryInfo->win.skey <= pTaskInfo->window.skey && pTableQueryInfo->win.ekey >= pTaskInfo->window.ekey));
2082
  }
H
Haojun Liao 已提交
2083
#endif
2084 2085
}

2086 2087 2088 2089
typedef struct SFetchRspHandleWrapper {
  uint32_t exchangeId;
  int32_t  sourceIndex;
} SFetchRspHandleWrapper;
2090

2091
int32_t loadRemoteDataCallback(void* param, const SDataBuf* pMsg, int32_t code) {
X
Xiaoyu Wang 已提交
2092
  SFetchRspHandleWrapper* pWrapper = (SFetchRspHandleWrapper*)param;
2093 2094 2095 2096 2097 2098 2099

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

X
Xiaoyu Wang 已提交
2100
  int32_t          index = pWrapper->sourceIndex;
2101
  SSourceDataInfo* pSourceDataInfo = taosArrayGet(pExchangeInfo->pSourceDataInfo, index);
2102

H
Haojun Liao 已提交
2103 2104
  if (code == TSDB_CODE_SUCCESS) {
    pSourceDataInfo->pRsp = pMsg->pData;
2105

H
Haojun Liao 已提交
2106 2107
    SRetrieveTableRsp* pRsp = pSourceDataInfo->pRsp;
    pRsp->numOfRows = htonl(pRsp->numOfRows);
dengyihao's avatar
dengyihao 已提交
2108
    pRsp->compLen = htonl(pRsp->compLen);
2109
    pRsp->numOfCols = htonl(pRsp->numOfCols);
dengyihao's avatar
dengyihao 已提交
2110
    pRsp->useconds = htobe64(pRsp->useconds);
2111

2112
    ASSERT(pRsp != NULL);
2113
    qDebug("%s fetch rsp received, index:%d, rows:%d", pSourceDataInfo->taskId, index, pRsp->numOfRows);
H
Haojun Liao 已提交
2114 2115 2116
  } else {
    pSourceDataInfo->code = code;
  }
H
Haojun Liao 已提交
2117

H
Haojun Liao 已提交
2118
  pSourceDataInfo->status = EX_SOURCE_DATA_READY;
2119 2120 2121 2122 2123

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

  taosMemoryFree(pWrapper);
wmmhello's avatar
wmmhello 已提交
2124
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
2125 2126 2127 2128
}

static void destroySendMsgInfo(SMsgSendInfo* pMsgBody) {
  assert(pMsgBody != NULL);
wafwerar's avatar
wafwerar 已提交
2129 2130
  taosMemoryFreeClear(pMsgBody->msgInfo.pData);
  taosMemoryFreeClear(pMsgBody);
H
Haojun Liao 已提交
2131 2132
}

S
Shengliang Guan 已提交
2133
void qProcessFetchRsp(void* parent, SRpcMsg* pMsg, SEpSet* pEpSet) {
S
Shengliang Guan 已提交
2134 2135
  SMsgSendInfo* pSendInfo = (SMsgSendInfo*)pMsg->info.ahandle;
  assert(pMsg->info.ahandle != NULL);
H
Haojun Liao 已提交
2136 2137 2138 2139

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

  if (pMsg->contLen > 0) {
wafwerar's avatar
wafwerar 已提交
2140
    buf.pData = taosMemoryCalloc(1, pMsg->contLen);
H
Haojun Liao 已提交
2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151
    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);
2152 2153
}

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

wafwerar's avatar
wafwerar 已提交
2157
  SResFetchReq* pMsg = taosMemoryCalloc(1, sizeof(SResFetchReq));
2158 2159 2160 2161
  if (NULL == pMsg) {
    pTaskInfo->code = TSDB_CODE_QRY_OUT_OF_MEMORY;
    return pTaskInfo->code;
  }
2162

L
Liu Jicong 已提交
2163 2164
  SDownstreamSourceNode* pSource = taosArrayGet(pExchangeInfo->pSources, sourceIndex);
  SSourceDataInfo*       pDataInfo = taosArrayGet(pExchangeInfo->pSourceDataInfo, sourceIndex);
2165

2166 2167
  ASSERT(pDataInfo->status == EX_SOURCE_DATA_NOT_READY);

L
Liu Jicong 已提交
2168 2169
  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);
2170 2171 2172 2173 2174 2175 2176

  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 已提交
2177
  SMsgSendInfo* pMsgSendInfo = taosMemoryCalloc(1, sizeof(SMsgSendInfo));
2178
  if (NULL == pMsgSendInfo) {
wafwerar's avatar
wafwerar 已提交
2179
    taosMemoryFreeClear(pMsg);
2180 2181 2182
    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 已提交
2183 2184
  }

2185
  SFetchRspHandleWrapper* pWrapper = taosMemoryCalloc(1, sizeof(SFetchRspHandleWrapper));
X
Xiaoyu Wang 已提交
2186
  pWrapper->exchangeId = pExchangeInfo->self;
2187 2188 2189
  pWrapper->sourceIndex = sourceIndex;

  pMsgSendInfo->param = pWrapper;
2190 2191 2192 2193
  pMsgSendInfo->msgInfo.pData = pMsg;
  pMsgSendInfo->msgInfo.len = sizeof(SResFetchReq);
  pMsgSendInfo->msgType = TDMT_VND_FETCH;
  pMsgSendInfo->fp = loadRemoteDataCallback;
2194

2195
  int64_t transporterId = 0;
L
Liu Jicong 已提交
2196
  int32_t code = asyncSendMsgToServer(pExchangeInfo->pTransporter, &pSource->addr.epSet, &transporterId, pMsgSendInfo);
2197 2198 2199
  return TSDB_CODE_SUCCESS;
}

2200
int32_t extractDataBlockFromFetchRsp(SSDataBlock* pRes, SLoadRemoteDataInfo* pLoadInfo, int32_t numOfRows, char* pData,
X
Xiaoyu Wang 已提交
2201 2202
                                 int32_t compLen, int32_t numOfOutput, int64_t startTs, uint64_t* total,
                                 SArray* pColList) {
H
Haojun Liao 已提交
2203
  if (pColList == NULL) {  // data from other sources
2204
    blockCompressDecode(pRes, numOfOutput, numOfRows, pData);
2205
    pRes->info.rows = numOfRows;
H
Haojun Liao 已提交
2206
  } else {  // extract data according to pColList
2207
    ASSERT(numOfOutput == taosArrayGetSize(pColList));
2208 2209 2210 2211 2212
    char* pStart = pData;

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

2213
    // todo refactor:extract method
2214
    SSysTableSchema* pSchema = (SSysTableSchema*)pStart;
dengyihao's avatar
dengyihao 已提交
2215
    for (int32_t i = 0; i < numOfCols; ++i) {
2216 2217 2218 2219 2220 2221 2222
      SSysTableSchema* p = (SSysTableSchema*)pStart;

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

H
Haojun Liao 已提交
2223 2224 2225 2226
    SSDataBlock* pBlock = taosMemoryCalloc(1, sizeof(SSDataBlock));
    pBlock->pDataBlock = taosArrayInit(numOfCols, sizeof(SColumnInfoData));
    pBlock->info.numOfCols = numOfCols;

dengyihao's avatar
dengyihao 已提交
2227
    for (int32_t i = 0; i < numOfCols; ++i) {
2228
      SColumnInfoData idata = {0};
2229

X
Xiaoyu Wang 已提交
2230
      idata.info.type = pSchema[i].type;
2231 2232
      idata.info.bytes = pSchema[i].bytes;
      idata.info.colId = pSchema[i].colId;
X
Xiaoyu Wang 已提交
2233
      idata.hasNull = true;
2234

H
Haojun Liao 已提交
2235
      taosArrayPush(pBlock->pDataBlock, &idata);
2236
      if (IS_VAR_DATA_TYPE(idata.info.type)) {
H
Haojun Liao 已提交
2237
        pBlock->info.hasVarCol = true;
2238 2239 2240
      }
    }

2241
    blockCompressDecode(pBlock, numOfCols, numOfRows, pStart);
2242

H
Haojun Liao 已提交
2243
    // data from mnode
2244
    pRes->info.rows = numOfRows;
H
Haojun Liao 已提交
2245 2246 2247
    relocateColumnData(pRes, pColList, pBlock->pDataBlock);
    taosArrayDestroy(pBlock->pDataBlock);
    taosMemoryFree(pBlock);
X
Xiaoyu Wang 已提交
2248
    //    blockDataDestroy(pBlock);
2249
  }
2250

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

2254
  int64_t el = taosGetTimestampUs() - startTs;
2255

H
Haojun Liao 已提交
2256 2257
  pLoadInfo->totalRows += numOfRows;
  pLoadInfo->totalSize += compLen;
2258

H
Haojun Liao 已提交
2259 2260 2261
  if (total != NULL) {
    *total += numOfRows;
  }
2262

H
Haojun Liao 已提交
2263
  pLoadInfo->totalElapsed += el;
2264 2265
  return TSDB_CODE_SUCCESS;
}
2266

L
Liu Jicong 已提交
2267 2268
static void* setAllSourcesCompleted(SOperatorInfo* pOperator, int64_t startTs) {
  SExchangeInfo* pExchangeInfo = pOperator->info;
2269
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
H
Haojun Liao 已提交
2270

2271
  int64_t              el = taosGetTimestampUs() - startTs;
H
Haojun Liao 已提交
2272
  SLoadRemoteDataInfo* pLoadInfo = &pExchangeInfo->loadInfo;
2273

H
Haojun Liao 已提交
2274
  pLoadInfo->totalElapsed += el;
H
Haojun Liao 已提交
2275

2276
  size_t totalSources = taosArrayGetSize(pExchangeInfo->pSources);
L
Liu Jicong 已提交
2277 2278 2279
  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);
2280 2281 2282 2283 2284

  doSetOperatorCompleted(pOperator);
  return NULL;
}

L
Liu Jicong 已提交
2285 2286
static SSDataBlock* concurrentlyLoadRemoteDataImpl(SOperatorInfo* pOperator, SExchangeInfo* pExchangeInfo,
                                                   SExecTaskInfo* pTaskInfo) {
2287 2288 2289 2290 2291 2292 2293 2294
  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);
2295
      if (pDataInfo->status == EX_SOURCE_DATA_EXHAUSTED) {
2296
        completed += 1;
H
Haojun Liao 已提交
2297 2298
        continue;
      }
2299

2300
      if (pDataInfo->status != EX_SOURCE_DATA_READY) {
2301 2302 2303
        continue;
      }

2304 2305 2306 2307 2308
      if (pDataInfo->code != TSDB_CODE_SUCCESS) {
        code = pDataInfo->code;
        goto _error;
      }

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

L
Liu Jicong 已提交
2312
      SSDataBlock*         pRes = pExchangeInfo->pResult;
H
Haojun Liao 已提交
2313
      SLoadRemoteDataInfo* pLoadInfo = &pExchangeInfo->loadInfo;
2314
      if (pRsp->numOfRows == 0) {
2315
        qDebug("%s vgId:%d, taskId:0x%" PRIx64 " index:%d completed, rowsOfSource:%" PRIu64 ", totalRows:%" PRIu64
X
Xiaoyu Wang 已提交
2316
               ", completed:%d try next %d/%" PRIzu,
2317 2318
               GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->taskId, i, pDataInfo->totalRows,
               pExchangeInfo->loadInfo.totalRows, completed + 1, i + 1, totalSources);
2319
        pDataInfo->status = EX_SOURCE_DATA_EXHAUSTED;
2320
        completed += 1;
D
dapan1121 已提交
2321
        taosMemoryFreeClear(pDataInfo->pRsp);
2322 2323
        continue;
      }
H
Haojun Liao 已提交
2324

H
Haojun Liao 已提交
2325
      SRetrieveTableRsp* pTableRsp = pDataInfo->pRsp;
2326
      code = extractDataBlockFromFetchRsp(pExchangeInfo->pResult, pLoadInfo, pTableRsp->numOfRows, pTableRsp->data,
X
Xiaoyu Wang 已提交
2327
                                      pTableRsp->compLen, pTableRsp->numOfCols, startTs, &pDataInfo->totalRows, NULL);
2328
      if (code != 0) {
2329
        taosMemoryFreeClear(pDataInfo->pRsp);
2330 2331 2332
        goto _error;
      }

2333
      if (pRsp->completed == 1) {
X
Xiaoyu Wang 已提交
2334 2335 2336
        qDebug("%s fetch msg rsp from vgId:%d, taskId:0x%" PRIx64
               " index:%d completed, numOfRows:%d, rowsOfSource:%" PRIu64 ", totalRows:%" PRIu64 ", totalBytes:%" PRIu64
               ", completed:%d try next %d/%" PRIzu,
2337 2338 2339
               GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->taskId, i, pRes->info.rows, pDataInfo->totalRows,
               pLoadInfo->totalRows, pLoadInfo->totalSize, completed + 1, i + 1, totalSources);
        completed += 1;
2340
        pDataInfo->status = EX_SOURCE_DATA_EXHAUSTED;
2341
      } else {
dengyihao's avatar
dengyihao 已提交
2342 2343
        qDebug("%s fetch msg rsp from vgId:%d, taskId:0x%" PRIx64 " numOfRows:%d, totalRows:%" PRIu64
               ", totalBytes:%" PRIu64,
H
Haojun Liao 已提交
2344 2345
               GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->taskId, pRes->info.rows, pLoadInfo->totalRows,
               pLoadInfo->totalSize);
2346 2347
      }

2348 2349
      taosMemoryFreeClear(pDataInfo->pRsp);

2350 2351
      if (pDataInfo->status != EX_SOURCE_DATA_EXHAUSTED) {
        pDataInfo->status = EX_SOURCE_DATA_NOT_READY;
2352 2353
        code = doSendFetchDataRequest(pExchangeInfo, pTaskInfo, i);
        if (code != TSDB_CODE_SUCCESS) {
2354
          taosMemoryFreeClear(pDataInfo->pRsp);
2355 2356 2357 2358 2359 2360 2361
          goto _error;
        }
      }

      return pExchangeInfo->pResult;
    }

2362
    if (completed == totalSources) {
2363 2364 2365 2366 2367 2368 2369 2370 2371
      return setAllSourcesCompleted(pOperator, startTs);
    }
  }

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

L
Liu Jicong 已提交
2372 2373 2374
static int32_t prepareConcurrentlyLoad(SOperatorInfo* pOperator) {
  SExchangeInfo* pExchangeInfo = pOperator->info;
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
2375

L
Liu Jicong 已提交
2376
  size_t  totalSources = taosArrayGetSize(pExchangeInfo->pSources);
2377 2378 2379
  int64_t startTs = taosGetTimestampUs();

  // Asynchronously send all fetch requests to all sources.
L
Liu Jicong 已提交
2380
  for (int32_t i = 0; i < totalSources; ++i) {
2381 2382
    int32_t code = doSendFetchDataRequest(pExchangeInfo, pTaskInfo, i);
    if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
2383 2384
      pTaskInfo->code = code;
      return code;
2385 2386 2387 2388
    }
  }

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

2392
  pOperator->status = OP_RES_TO_RETURN;
H
Haojun Liao 已提交
2393
  pOperator->cost.openCost = taosGetTimestampUs() - startTs;
2394

2395
  tsem_wait(&pExchangeInfo->ready);
H
Haojun Liao 已提交
2396
  return TSDB_CODE_SUCCESS;
2397 2398
}

L
Liu Jicong 已提交
2399 2400 2401
static SSDataBlock* seqLoadRemoteData(SOperatorInfo* pOperator) {
  SExchangeInfo* pExchangeInfo = pOperator->info;
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
2402

L
Liu Jicong 已提交
2403
  size_t  totalSources = taosArrayGetSize(pExchangeInfo->pSources);
2404
  int64_t startTs = taosGetTimestampUs();
2405

L
Liu Jicong 已提交
2406
  while (1) {
2407 2408
    if (pExchangeInfo->current >= totalSources) {
      return setAllSourcesCompleted(pOperator, startTs);
2409
    }
2410

2411 2412 2413
    doSendFetchDataRequest(pExchangeInfo, pTaskInfo, pExchangeInfo->current);
    tsem_wait(&pExchangeInfo->ready);

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

H
Haojun Liao 已提交
2417
    if (pDataInfo->code != TSDB_CODE_SUCCESS) {
dengyihao's avatar
dengyihao 已提交
2418 2419
      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 已提交
2420 2421 2422 2423
      pOperator->pTaskInfo->code = pDataInfo->code;
      return NULL;
    }

L
Liu Jicong 已提交
2424
    SRetrieveTableRsp*   pRsp = pDataInfo->pRsp;
H
Haojun Liao 已提交
2425
    SLoadRemoteDataInfo* pLoadInfo = &pExchangeInfo->loadInfo;
2426
    if (pRsp->numOfRows == 0) {
dengyihao's avatar
dengyihao 已提交
2427 2428
      qDebug("%s vgId:%d, taskID:0x%" PRIx64 " %d of total completed, rowsOfSource:%" PRIu64 ", totalRows:%" PRIu64
             " try next",
2429
             GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->taskId, pExchangeInfo->current + 1,
H
Haojun Liao 已提交
2430
             pDataInfo->totalRows, pLoadInfo->totalRows);
H
Haojun Liao 已提交
2431

2432
      pDataInfo->status = EX_SOURCE_DATA_EXHAUSTED;
2433
      pExchangeInfo->current += 1;
D
dapan1121 已提交
2434
      taosMemoryFreeClear(pDataInfo->pRsp);
2435 2436
      continue;
    }
H
Haojun Liao 已提交
2437

L
Liu Jicong 已提交
2438
    SSDataBlock*       pRes = pExchangeInfo->pResult;
H
Haojun Liao 已提交
2439
    SRetrieveTableRsp* pTableRsp = pDataInfo->pRsp;
L
Liu Jicong 已提交
2440
    int32_t            code =
2441
        extractDataBlockFromFetchRsp(pExchangeInfo->pResult, pLoadInfo, pTableRsp->numOfRows, pTableRsp->data,
X
Xiaoyu Wang 已提交
2442
                                 pTableRsp->compLen, pTableRsp->numOfCols, startTs, &pDataInfo->totalRows, NULL);
2443 2444

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

2450
      pDataInfo->status = EX_SOURCE_DATA_EXHAUSTED;
2451 2452
      pExchangeInfo->current += 1;
    } else {
L
Liu Jicong 已提交
2453 2454 2455 2456
      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);
2457 2458
    }

2459
    pOperator->resultInfo.totalRows += pRes->info.rows;
2460
    taosMemoryFreeClear(pDataInfo->pRsp);
2461 2462
    return pExchangeInfo->pResult;
  }
2463 2464
}

L
Liu Jicong 已提交
2465
static int32_t prepareLoadRemoteData(SOperatorInfo* pOperator) {
2466
  if (OPTR_IS_OPENED(pOperator)) {
H
Haojun Liao 已提交
2467 2468 2469
    return TSDB_CODE_SUCCESS;
  }

2470 2471
  int64_t st = taosGetTimestampUs();

L
Liu Jicong 已提交
2472
  SExchangeInfo* pExchangeInfo = pOperator->info;
2473
  if (!pExchangeInfo->seqLoadData) {
H
Haojun Liao 已提交
2474 2475 2476 2477 2478 2479
    int32_t code = prepareConcurrentlyLoad(pOperator);
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }
  }

2480
  OPTR_SET_OPENED(pOperator);
2481
  pOperator->cost.openCost = (taosGetTimestampUs() - st) / 1000.0;
H
Haojun Liao 已提交
2482 2483 2484
  return TSDB_CODE_SUCCESS;
}

2485
static SSDataBlock* doLoadRemoteData(SOperatorInfo* pOperator) {
L
Liu Jicong 已提交
2486 2487
  SExchangeInfo* pExchangeInfo = pOperator->info;
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
2488

2489
  pTaskInfo->code = pOperator->fpSet._openFn(pOperator);
2490
  if (pTaskInfo->code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
2491 2492
    return NULL;
  }
2493

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

2497
  if (pOperator->status == OP_EXEC_DONE) {
L
Liu Jicong 已提交
2498 2499 2500
    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);
2501 2502 2503 2504 2505 2506
    return NULL;
  }

  if (pExchangeInfo->seqLoadData) {
    return seqLoadRemoteData(pOperator);
  } else {
2507
    return concurrentlyLoadRemoteDataImpl(pOperator, pExchangeInfo, pTaskInfo);
2508
  }
H
Haojun Liao 已提交
2509
}
2510

2511
static int32_t initDataSource(int32_t numOfSources, SExchangeInfo* pInfo, const char* id) {
2512
  pInfo->pSourceDataInfo = taosArrayInit(numOfSources, sizeof(SSourceDataInfo));
H
Haojun Liao 已提交
2513 2514
  if (pInfo->pSourceDataInfo == NULL) {
    return TSDB_CODE_OUT_OF_MEMORY;
2515 2516
  }

L
Liu Jicong 已提交
2517
  for (int32_t i = 0; i < numOfSources; ++i) {
2518
    SSourceDataInfo dataInfo = {0};
H
Haojun Liao 已提交
2519
    dataInfo.status = EX_SOURCE_DATA_NOT_READY;
2520
    dataInfo.taskId = id;
L
Liu Jicong 已提交
2521
    dataInfo.index = i;
X
Xiaoyu Wang 已提交
2522
    SSourceDataInfo* pDs = taosArrayPush(pInfo->pSourceDataInfo, &dataInfo);
2523
    if (pDs == NULL) {
H
Haojun Liao 已提交
2524 2525 2526 2527 2528 2529 2530 2531
      taosArrayDestroy(pInfo->pSourceDataInfo);
      return TSDB_CODE_OUT_OF_MEMORY;
    }
  }

  return TSDB_CODE_SUCCESS;
}

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

2535
  if (numOfSources == 0) {
X
Xiaoyu Wang 已提交
2536
    qError("%s invalid number: %d of sources in exchange operator", id, (int32_t)numOfSources);
2537 2538 2539
    return TSDB_CODE_INVALID_PARA;
  }

H
Haojun Liao 已提交
2540
  pInfo->pSources = taosArrayInit(numOfSources, sizeof(SDownstreamSourceNode));
H
Haojun Liao 已提交
2541 2542
  pInfo->pSourceDataInfo = taosArrayInit(numOfSources, sizeof(SSourceDataInfo));
  if (pInfo->pSourceDataInfo == NULL || pInfo->pSources == NULL) {
2543
    return TSDB_CODE_OUT_OF_MEMORY;
H
Haojun Liao 已提交
2544 2545
  }

L
Liu Jicong 已提交
2546
  for (int32_t i = 0; i < numOfSources; ++i) {
2547
    SNodeListNode* pNode = (SNodeListNode*)nodesListGetNode((SNodeList*)pExNode->pSrcEndPoints, i);
H
Haojun Liao 已提交
2548 2549
    taosArrayPush(pInfo->pSources, pNode);
  }
2550

2551 2552
  pInfo->self = taosAddRef(exchangeObjRefPool, pInfo);

2553
  return initDataSource(numOfSources, pInfo, id);
2554 2555 2556 2557 2558 2559
}

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

2563
  int32_t code = initExchangeOperator(pExNode, pInfo, GET_TASKID(pTaskInfo));
2564 2565 2566
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
2567 2568

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

X
Xiaoyu Wang 已提交
2570
  pInfo->seqLoadData = false;
2571
  pInfo->pTransporter = pTransporter;
X
Xiaoyu Wang 已提交
2572 2573
  pInfo->pResult = createResDataBlock(pExNode->node.pOutputDataBlockDesc);
  pOperator->name = "ExchangeOperator";
X
Xiaoyu Wang 已提交
2574
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_EXCHANGE;
X
Xiaoyu Wang 已提交
2575 2576 2577 2578 2579
  pOperator->blocking = false;
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
  pOperator->numOfExprs = pInfo->pResult->info.numOfCols;
  pOperator->pTaskInfo = pTaskInfo;
2580

L
Liu Jicong 已提交
2581 2582
  pOperator->fpSet = createOperatorFpSet(prepareLoadRemoteData, doLoadRemoteData, NULL, NULL,
                                         destroyExchangeOperatorInfo, NULL, NULL, NULL);
2583
  return pOperator;
H
Haojun Liao 已提交
2584

L
Liu Jicong 已提交
2585
_error:
H
Haojun Liao 已提交
2586
  if (pInfo != NULL) {
2587
    doDestroyExchangeOperatorInfo(pInfo);
H
Haojun Liao 已提交
2588 2589
  }

wafwerar's avatar
wafwerar 已提交
2590 2591
  taosMemoryFreeClear(pInfo);
  taosMemoryFreeClear(pOperator);
2592
  pTaskInfo->code = code;
H
Haojun Liao 已提交
2593
  return NULL;
2594 2595
}

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

2599
static void destroySortedMergeOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
2600
  SSortedMergeOperatorInfo* pInfo = (SSortedMergeOperatorInfo*)param;
H
Haojun Liao 已提交
2601
  taosArrayDestroy(pInfo->pSortInfo);
2602 2603 2604
  taosArrayDestroy(pInfo->groupInfo);

  if (pInfo->pSortHandle != NULL) {
H
Haojun Liao 已提交
2605
    tsortDestroySortHandle(pInfo->pSortHandle);
2606 2607
  }

H
Haojun Liao 已提交
2608
  blockDataDestroy(pInfo->binfo.pRes);
H
Haojun Liao 已提交
2609
  cleanupAggSup(&pInfo->aggSup);
2610
}
H
Haojun Liao 已提交
2611

L
Liu Jicong 已提交
2612
static bool needToMerge(SSDataBlock* pBlock, SArray* groupInfo, char** buf, int32_t rowIndex) {
2613 2614 2615 2616
  size_t size = taosArrayGetSize(groupInfo);
  if (size == 0) {
    return true;
  }
2617

2618 2619
  for (int32_t i = 0; i < size; ++i) {
    int32_t* index = taosArrayGet(groupInfo, i);
2620

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

2624 2625 2626
    if ((isNull && buf[i] != NULL) || (!isNull && buf[i] == NULL)) {
      return false;
    }
2627

2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640
    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;
      }
2641 2642 2643
    }
  }

2644
  return 0;
2645 2646
}

L
Liu Jicong 已提交
2647 2648 2649
static void doMergeResultImpl(SSortedMergeOperatorInfo* pInfo, SqlFunctionCtx* pCtx, int32_t numOfExpr,
                              int32_t rowIndex) {
  for (int32_t j = 0; j < numOfExpr; ++j) {  // TODO set row index
X
Xiaoyu Wang 已提交
2650
                                             //    pCtx[j].startRow = rowIndex;
2651 2652
  }

2653 2654
  for (int32_t j = 0; j < numOfExpr; ++j) {
    int32_t functionId = pCtx[j].functionId;
L
Liu Jicong 已提交
2655 2656 2657 2658 2659 2660 2661 2662 2663
    //    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]);
    //    }
2664
  }
2665
}
2666

L
Liu Jicong 已提交
2667 2668
static void doFinalizeResultImpl(SqlFunctionCtx* pCtx, int32_t numOfExpr) {
  for (int32_t j = 0; j < numOfExpr; ++j) {
2669 2670 2671 2672
    int32_t functionId = pCtx[j].functionId;
    //    if (functionId == FUNC_TAG_DUMMY || functionId == FUNC_TS_DUMMY) {
    //      continue;
    //    }
2673

2674 2675 2676 2677
    //    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 已提交
2678
    //    pCtx[j].fpSet.finalize(&pCtx[j]);
2679 2680
  }
}
2681

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

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

2689 2690 2691
    char* data = colDataGetData(pColInfo, rowIndex);
    memcpy(rowColData[i], data, colDataGetLength(pColInfo, rowIndex));
  }
2692

2693 2694
  return true;
}
2695

2696 2697
static void doMergeImpl(SOperatorInfo* pOperator, int32_t numOfExpr, SSDataBlock* pBlock) {
  SSortedMergeOperatorInfo* pInfo = pOperator->info;
2698

2699
  SqlFunctionCtx* pCtx = pInfo->binfo.pCtx;
L
Liu Jicong 已提交
2700
  for (int32_t i = 0; i < pBlock->info.numOfCols; ++i) {
X
Xiaoyu Wang 已提交
2701
    //    pCtx[i].size = 1;
2702
  }
2703

L
Liu Jicong 已提交
2704
  for (int32_t i = 0; i < pBlock->info.rows; ++i) {
2705 2706 2707 2708 2709 2710 2711 2712 2713
    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);
2714 2715
        int32_t numOfRows = getNumOfResult(pInfo->binfo.pCtx, pOperator->numOfExprs, NULL);
        //        setTagValueForMultipleRows(pCtx, pOperator->numOfExprs, numOfRows);
2716

2717
        // TODO check for available buffer;
H
Haojun Liao 已提交
2718

2719 2720 2721 2722 2723
        // next group info data
        pInfo->binfo.pRes->info.rows += numOfRows;
        for (int32_t j = 0; j < numOfExpr; ++j) {
          if (pCtx[j].functionId < 0) {
            continue;
2724
          }
2725

H
Haojun Liao 已提交
2726
          pCtx[j].fpSet.process(&pCtx[j]);
2727
        }
2728 2729 2730

        doMergeResultImpl(pInfo, pCtx, numOfExpr, i);
        pInfo->hasGroupVal = saveCurrentTuple(pInfo->groupVal, pInfo->groupInfo, pBlock, i);
H
Haojun Liao 已提交
2731
      }
2732 2733 2734 2735
    }
  }
}

2736 2737
static SSDataBlock* doMerge(SOperatorInfo* pOperator) {
  SSortedMergeOperatorInfo* pInfo = pOperator->info;
L
Liu Jicong 已提交
2738
  SSortHandle*              pHandle = pInfo->pSortHandle;
2739

2740
  SSDataBlock* pDataBlock = createOneDataBlock(pInfo->binfo.pRes, false);
2741
  blockDataEnsureCapacity(pDataBlock, pOperator->resultInfo.capacity);
2742

L
Liu Jicong 已提交
2743
  while (1) {
2744
    blockDataCleanup(pDataBlock);
2745
    while (1) {
H
Haojun Liao 已提交
2746
      STupleHandle* pTupleHandle = tsortNextTuple(pHandle);
2747 2748
      if (pTupleHandle == NULL) {
        break;
2749
      }
2750

2751 2752
      // build datablock for merge for one group
      appendOneRowToDataBlock(pDataBlock, pTupleHandle);
2753
      if (pDataBlock->info.rows >= pOperator->resultInfo.capacity) {
2754 2755
        break;
      }
2756
    }
2757

2758 2759 2760
    if (pDataBlock->info.rows == 0) {
      break;
    }
2761

2762
    setInputDataBlock(pOperator, pInfo->binfo.pCtx, pDataBlock, TSDB_ORDER_ASC, MAIN_SCAN, true);
L
Liu Jicong 已提交
2763 2764
    //  updateOutputBuf(&pInfo->binfo, &pAggInfo->bufCapacity, pBlock->info.rows * pAggInfo->resultRowFactor,
    //  pOperator->pRuntimeEnv, true);
2765
    doMergeImpl(pOperator, pOperator->numOfExprs, pDataBlock);
2766 2767
    // flush to tuple store, and after all data have been handled, return to upstream node or sink node
  }
2768

2769 2770 2771
  doFinalizeResultImpl(pInfo->binfo.pCtx, pOperator->numOfExprs);
  int32_t numOfRows = getNumOfResult(pInfo->binfo.pCtx, pOperator->numOfExprs, NULL);
  //        setTagValueForMultipleRows(pCtx, pOperator->numOfExprs, numOfRows);
2772

2773
  // TODO check for available buffer;
2774

2775 2776
  // next group info data
  pInfo->binfo.pRes->info.rows += numOfRows;
L
Liu Jicong 已提交
2777
  return (pInfo->binfo.pRes->info.rows > 0) ? pInfo->binfo.pRes : NULL;
2778
}
2779

L
Liu Jicong 已提交
2780 2781
SSDataBlock* getSortedMergeBlockData(SSortHandle* pHandle, SSDataBlock* pDataBlock, int32_t capacity,
                                     SArray* pColMatchInfo, SSortedMergeOperatorInfo* pInfo) {
2782 2783 2784 2785 2786 2787 2788 2789 2790 2791
  blockDataCleanup(pDataBlock);

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

  blockDataEnsureCapacity(p, capacity);

  while (1) {
2792
    STupleHandle* pTupleHandle = tsortNextTuple(pHandle);
2793 2794 2795 2796
    if (pTupleHandle == NULL) {
      break;
    }

2797
    appendOneRowToDataBlock(p, pTupleHandle);
2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821
    if (p->info.rows >= capacity) {
      break;
    }
  }

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

      SColumnInfoData* pSrc = taosArrayGet(p->pDataBlock, pmInfo->srcSlotId);
      SColumnInfoData* pDst = taosArrayGet(pDataBlock->pDataBlock, pmInfo->targetSlotId);
      colDataAssign(pDst, pSrc, p->info.rows);
    }

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

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

2822
static SSDataBlock* doSortedMerge(SOperatorInfo* pOperator) {
2823 2824
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
2825 2826
  }

L
Liu Jicong 已提交
2827
  SExecTaskInfo*            pTaskInfo = pOperator->pTaskInfo;
2828
  SSortedMergeOperatorInfo* pInfo = pOperator->info;
H
Haojun Liao 已提交
2829
  if (pOperator->status == OP_RES_TO_RETURN) {
2830
    return getSortedMergeBlockData(pInfo->pSortHandle, pInfo->binfo.pRes, pOperator->resultInfo.capacity, NULL, pInfo);
2831 2832
  }

2833
  int32_t numOfBufPage = pInfo->sortBufSize / pInfo->bufPageSize;
2834
  pInfo->pSortHandle = tsortCreateSortHandle(pInfo->pSortInfo, SORT_MULTISOURCE_MERGE, pInfo->bufPageSize,
dengyihao's avatar
dengyihao 已提交
2835
                                             numOfBufPage, pInfo->binfo.pRes, "GET_TASKID(pTaskInfo)");
H
Haojun Liao 已提交
2836

2837
  tsortSetFetchRawDataFp(pInfo->pSortHandle, loadNextDataBlock, NULL, NULL);
2838

L
Liu Jicong 已提交
2839
  for (int32_t i = 0; i < pOperator->numOfDownstream; ++i) {
wmmhello's avatar
wmmhello 已提交
2840
    SSortSource* ps = taosMemoryCalloc(1, sizeof(SSortSource));
H
Haojun Liao 已提交
2841
    ps->param = pOperator->pDownstream[i];
H
Haojun Liao 已提交
2842
    tsortAddSource(pInfo->pSortHandle, ps);
2843 2844
  }

H
Haojun Liao 已提交
2845
  int32_t code = tsortOpen(pInfo->pSortHandle);
2846
  if (code != TSDB_CODE_SUCCESS) {
2847
    longjmp(pTaskInfo->env, terrno);
2848 2849
  }

H
Haojun Liao 已提交
2850
  pOperator->status = OP_RES_TO_RETURN;
2851
  return doMerge(pOperator);
2852
}
2853

L
Liu Jicong 已提交
2854 2855
static int32_t initGroupCol(SExprInfo* pExprInfo, int32_t numOfCols, SArray* pGroupInfo,
                            SSortedMergeOperatorInfo* pInfo) {
2856 2857
  if (pGroupInfo == NULL || taosArrayGetSize(pGroupInfo) == 0) {
    return 0;
H
Haojun Liao 已提交
2858 2859
  }

2860 2861 2862 2863 2864 2865 2866 2867
  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 已提交
2868 2869
  size_t numOfGroupCol = taosArrayGetSize(pInfo->groupInfo);
  for (int32_t i = 0; i < numOfGroupCol; ++i) {
2870
    SColumn* pCol = taosArrayGet(pGroupInfo, i);
L
Liu Jicong 已提交
2871
    for (int32_t j = 0; j < numOfCols; ++j) {
H
Haojun Liao 已提交
2872
      SExprInfo* pe = &pExprInfo[j];
2873
      if (pe->base.resSchema.slotId == pCol->colId) {
2874 2875
        taosArrayPush(plist, pCol);
        taosArrayPush(pInfo->groupInfo, &j);
H
Haojun Liao 已提交
2876
        len += pCol->bytes;
2877 2878
        break;
      }
H
Haojun Liao 已提交
2879 2880 2881
    }
  }

2882
  ASSERT(taosArrayGetSize(pGroupInfo) == taosArrayGetSize(plist));
H
Haojun Liao 已提交
2883

wafwerar's avatar
wafwerar 已提交
2884
  pInfo->groupVal = taosMemoryCalloc(1, (POINTER_BYTES * numOfGroupCol + len));
2885 2886 2887 2888
  if (pInfo->groupVal == NULL) {
    taosArrayDestroy(plist);
    return TSDB_CODE_OUT_OF_MEMORY;
  }
H
Haojun Liao 已提交
2889

2890
  int32_t offset = 0;
L
Liu Jicong 已提交
2891 2892
  char*   start = (char*)(pInfo->groupVal + (POINTER_BYTES * numOfGroupCol));
  for (int32_t i = 0; i < numOfGroupCol; ++i) {
2893 2894
    pInfo->groupVal[i] = start + offset;
    SColumn* pCol = taosArrayGet(plist, i);
H
Haojun Liao 已提交
2895
    offset += pCol->bytes;
2896
  }
H
Haojun Liao 已提交
2897

2898
  taosArrayDestroy(plist);
H
Haojun Liao 已提交
2899

2900 2901
  return TSDB_CODE_SUCCESS;
}
H
Haojun Liao 已提交
2902

L
Liu Jicong 已提交
2903 2904 2905
SOperatorInfo* createSortedMergeOperatorInfo(SOperatorInfo** downstream, int32_t numOfDownstream, SExprInfo* pExprInfo,
                                             int32_t num, SArray* pSortInfo, SArray* pGroupInfo,
                                             SExecTaskInfo* pTaskInfo) {
wafwerar's avatar
wafwerar 已提交
2906
  SSortedMergeOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SSortedMergeOperatorInfo));
L
Liu Jicong 已提交
2907
  SOperatorInfo*            pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
2908
  if (pInfo == NULL || pOperator == NULL) {
2909
    goto _error;
2910
  }
H
Haojun Liao 已提交
2911

2912
  pInfo->binfo.pCtx = createSqlFunctionCtx(pExprInfo, num, &pInfo->binfo.rowCellInfoOffset);
2913
  initResultRowInfo(&pInfo->binfo.resultRowInfo);
H
Haojun Liao 已提交
2914

2915 2916 2917
  if (pInfo->binfo.pCtx == NULL || pInfo->binfo.pRes == NULL) {
    goto _error;
  }
H
Haojun Liao 已提交
2918

dengyihao's avatar
dengyihao 已提交
2919
  size_t  keyBufSize = sizeof(int64_t) + sizeof(int64_t) + POINTER_BYTES;
2920
  int32_t code = doInitAggInfoSup(&pInfo->aggSup, pInfo->binfo.pCtx, num, keyBufSize, pTaskInfo->id.str);
2921 2922 2923
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
H
Haojun Liao 已提交
2924

H
Haojun Liao 已提交
2925
  setFunctionResultOutput(&pInfo->binfo, &pInfo->aggSup, MAIN_SCAN, num, pTaskInfo);
H
Haojun Liao 已提交
2926
  code = initGroupCol(pExprInfo, num, pGroupInfo, pInfo);
2927 2928 2929
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
H
Haojun Liao 已提交
2930

L
Liu Jicong 已提交
2931 2932 2933 2934 2935
  //  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 已提交
2936

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

L
Liu Jicong 已提交
2939
  pOperator->name = "SortedMerge";
X
Xiaoyu Wang 已提交
2940
  // pOperator->operatorType = OP_SortedMerge;
2941
  pOperator->blocking = true;
L
Liu Jicong 已提交
2942 2943
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
2944
  pOperator->numOfExprs = num;
L
Liu Jicong 已提交
2945
  pOperator->pExpr = pExprInfo;
H
Haojun Liao 已提交
2946

L
Liu Jicong 已提交
2947
  pOperator->pTaskInfo = pTaskInfo;
H
Haojun Liao 已提交
2948

2949 2950
  pOperator->fpSet = createOperatorFpSet(operatorDummyOpenFn, doSortedMerge, NULL, NULL, destroySortedMergeOperatorInfo,
                                         NULL, NULL, NULL);
2951 2952 2953
  code = appendDownstream(pOperator, downstream, numOfDownstream);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
2954
  }
H
Haojun Liao 已提交
2955

2956
  return pOperator;
H
Haojun Liao 已提交
2957

L
Liu Jicong 已提交
2958
_error:
2959
  if (pInfo != NULL) {
H
Haojun Liao 已提交
2960
    destroySortedMergeOperatorInfo(pInfo, num);
H
Haojun Liao 已提交
2961 2962
  }

wafwerar's avatar
wafwerar 已提交
2963 2964
  taosMemoryFreeClear(pInfo);
  taosMemoryFreeClear(pOperator);
2965 2966
  terrno = TSDB_CODE_QRY_OUT_OF_MEMORY;
  return NULL;
H
Haojun Liao 已提交
2967 2968
}

X
Xiaoyu Wang 已提交
2969
int32_t getTableScanInfo(SOperatorInfo* pOperator, int32_t* order, int32_t* scanFlag) {
2970
  // todo add more information about exchange operation
2971
  int32_t type = pOperator->operatorType;
X
Xiaoyu Wang 已提交
2972
  if (type == QUERY_NODE_PHYSICAL_PLAN_EXCHANGE || type == QUERY_NODE_PHYSICAL_PLAN_SYSTABLE_SCAN ||
2973
      type == QUERY_NODE_PHYSICAL_PLAN_STREAM_SCAN || type == QUERY_NODE_PHYSICAL_PLAN_TAG_SCAN) {
2974 2975 2976
    *order = TSDB_ORDER_ASC;
    *scanFlag = MAIN_SCAN;
    return TSDB_CODE_SUCCESS;
2977
  } else if (type == QUERY_NODE_PHYSICAL_PLAN_TABLE_SCAN) {
2978 2979 2980 2981 2982
    STableScanInfo* pTableScanInfo = pOperator->info;
    *order = pTableScanInfo->cond.order;
    *scanFlag = pTableScanInfo->scanFlag;
    return TSDB_CODE_SUCCESS;
  } else {
H
Haojun Liao 已提交
2983
    if (pOperator->pDownstream == NULL || pOperator->pDownstream[0] == NULL) {
2984
      return TSDB_CODE_INVALID_PARA;
H
Haojun Liao 已提交
2985
    } else {
2986
      return getTableScanInfo(pOperator->pDownstream[0], order, scanFlag);
2987 2988 2989
    }
  }
}
2990 2991

// this is a blocking operator
L
Liu Jicong 已提交
2992
static int32_t doOpenAggregateOptr(SOperatorInfo* pOperator) {
H
Haojun Liao 已提交
2993 2994
  if (OPTR_IS_OPENED(pOperator)) {
    return TSDB_CODE_SUCCESS;
2995 2996
  }

H
Haojun Liao 已提交
2997
  SExecTaskInfo*    pTaskInfo = pOperator->pTaskInfo;
2998
  SAggOperatorInfo* pAggInfo = pOperator->info;
H
Haojun Liao 已提交
2999

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

3003 3004
  int64_t st = taosGetTimestampUs();

3005 3006 3007
  int32_t order = TSDB_ORDER_ASC;
  int32_t scanFlag = MAIN_SCAN;

H
Haojun Liao 已提交
3008
  while (1) {
3009
    SSDataBlock* pBlock = downstream->fpSet.getNextFn(downstream);
3010 3011 3012 3013
    if (pBlock == NULL) {
      break;
    }

3014 3015 3016 3017
    int32_t code = getTableScanInfo(pOperator, &order, &scanFlag);
    if (code != TSDB_CODE_SUCCESS) {
      longjmp(pTaskInfo->env, code);
    }
3018

3019 3020
    // there is an scalar expression that needs to be calculated before apply the group aggregation.
    if (pAggInfo->pScalarExprInfo != NULL) {
3021
      code = projectApplyFunctions(pAggInfo->pScalarExprInfo, pBlock, pBlock, pAggInfo->pScalarCtx,
3022
                                   pAggInfo->numOfScalarExpr, NULL);
3023
      if (code != TSDB_CODE_SUCCESS) {
3024
        longjmp(pTaskInfo->env, code);
3025
      }
3026 3027
    }

3028
    // the pDataBlock are always the same one, no need to call this again
3029
    setExecutionContext(pOperator->numOfExprs, pBlock->info.groupId, pTaskInfo, pAggInfo);
3030
    setInputDataBlock(pOperator, pInfo->pCtx, pBlock, order, scanFlag, true);
3031 3032 3033 3034
    code = doAggregateImpl(pOperator, 0, pInfo->pCtx);
    if (code != 0) {
      longjmp(pTaskInfo->env, code);
    }
3035

dengyihao's avatar
dengyihao 已提交
3036
#if 0  // test for encode/decode result info
3037
    if(pOperator->fpSet.encodeResultRow){
3038 3039
      char *result = NULL;
      int32_t length = 0;
3040 3041
      pOperator->fpSet.encodeResultRow(pOperator, &result, &length);
      SAggSupporter* pSup = &pAggInfo->aggSup;
3042 3043
      taosHashClear(pSup->pResultRowHashTable);
      pInfo->resultRowInfo.size = 0;
3044
      pOperator->fpSet.decodeResultRow(pOperator, result);
3045 3046 3047
      if(result){
        taosMemoryFree(result);
      }
3048
    }
3049
#endif
3050 3051
  }

H
Haojun Liao 已提交
3052
  closeAllResultRows(&pAggInfo->binfo.resultRowInfo);
3053
  initGroupedResultInfo(&pAggInfo->groupResInfo, pAggInfo->aggSup.pResultRowHashTable, 0);
H
Haojun Liao 已提交
3054
  OPTR_SET_OPENED(pOperator);
3055

3056
  pOperator->cost.openCost = (taosGetTimestampUs() - st) / 1000.0;
H
Haojun Liao 已提交
3057 3058 3059
  return TSDB_CODE_SUCCESS;
}

3060
static SSDataBlock* getAggregateResult(SOperatorInfo* pOperator) {
L
Liu Jicong 已提交
3061
  SAggOperatorInfo* pAggInfo = pOperator->info;
H
Haojun Liao 已提交
3062 3063 3064 3065 3066 3067
  SOptrBasicInfo*   pInfo = &pAggInfo->binfo;

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

L
Liu Jicong 已提交
3068
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
3069
  pTaskInfo->code = pOperator->fpSet._openFn(pOperator);
H
Haojun Liao 已提交
3070
  if (pTaskInfo->code != TSDB_CODE_SUCCESS) {
3071
    doSetOperatorCompleted(pOperator);
H
Haojun Liao 已提交
3072 3073 3074
    return NULL;
  }

H
Haojun Liao 已提交
3075
  blockDataEnsureCapacity(pInfo->pRes, pOperator->resultInfo.capacity);
3076
  doBuildResultDatablock(pOperator, pInfo, &pAggInfo->groupResInfo, pAggInfo->aggSup.pResultBuf);
3077
  if (pInfo->pRes->info.rows == 0 || !hasDataInGroupInfo(&pAggInfo->groupResInfo)) {
H
Haojun Liao 已提交
3078 3079
    doSetOperatorCompleted(pOperator);
  }
3080

3081
  size_t rows = blockDataGetNumOfRows(pInfo->pRes);
3082 3083
  pOperator->resultInfo.totalRows += rows;

3084
  return (rows == 0) ? NULL : pInfo->pRes;
3085 3086
}

wmmhello's avatar
wmmhello 已提交
3087
int32_t aggEncodeResultRow(SOperatorInfo* pOperator, char** result, int32_t* length) {
3088
  if (result == NULL || length == NULL) {
wmmhello's avatar
wmmhello 已提交
3089 3090 3091
    return TSDB_CODE_TSC_INVALID_INPUT;
  }
  SOptrBasicInfo* pInfo = (SOptrBasicInfo*)(pOperator->info);
3092 3093 3094 3095 3096
  SAggSupporter*  pSup = (SAggSupporter*)POINTER_SHIFT(pOperator->info, sizeof(SOptrBasicInfo));
  int32_t         size = taosHashGetSize(pSup->pResultRowHashTable);
  size_t          keyLen = sizeof(uint64_t) * 2;  // estimate the key length
  int32_t         totalSize =
      sizeof(int32_t) + sizeof(int32_t) + size * (sizeof(int32_t) + keyLen + sizeof(int32_t) + pSup->resultRowSize);
wmmhello's avatar
wmmhello 已提交
3097

wmmhello's avatar
wmmhello 已提交
3098
  *result = (char*)taosMemoryCalloc(1, totalSize);
L
Liu Jicong 已提交
3099
  if (*result == NULL) {
wmmhello's avatar
wmmhello 已提交
3100
    return TSDB_CODE_OUT_OF_MEMORY;
wmmhello's avatar
wmmhello 已提交
3101
  }
wmmhello's avatar
wmmhello 已提交
3102

wmmhello's avatar
wmmhello 已提交
3103
  int32_t offset = sizeof(int32_t);
wmmhello's avatar
wmmhello 已提交
3104 3105
  *(int32_t*)(*result + offset) = size;
  offset += sizeof(int32_t);
3106 3107

  // prepare memory
3108
  SResultRowPosition* pos = &pInfo->resultRowInfo.cur;
dengyihao's avatar
dengyihao 已提交
3109 3110
  void*               pPage = getBufPage(pSup->pResultBuf, pos->pageId);
  SResultRow*         pRow = (SResultRow*)((char*)pPage + pos->offset);
3111 3112 3113
  setBufPageDirty(pPage, true);
  releaseBufPage(pSup->pResultBuf, pPage);

dengyihao's avatar
dengyihao 已提交
3114
  void* pIter = taosHashIterate(pSup->pResultRowHashTable, NULL);
wmmhello's avatar
wmmhello 已提交
3115
  while (pIter) {
dengyihao's avatar
dengyihao 已提交
3116
    void*               key = taosHashGetKey(pIter, &keyLen);
3117
    SResultRowPosition* p1 = (SResultRowPosition*)pIter;
3118

dengyihao's avatar
dengyihao 已提交
3119
    pPage = (SFilePage*)getBufPage(pSup->pResultBuf, p1->pageId);
3120
    pRow = (SResultRow*)((char*)pPage + p1->offset);
3121 3122
    setBufPageDirty(pPage, true);
    releaseBufPage(pSup->pResultBuf, pPage);
wmmhello's avatar
wmmhello 已提交
3123 3124 3125

    // recalculate the result size
    int32_t realTotalSize = offset + sizeof(int32_t) + keyLen + sizeof(int32_t) + pSup->resultRowSize;
L
Liu Jicong 已提交
3126
    if (realTotalSize > totalSize) {
wmmhello's avatar
wmmhello 已提交
3127
      char* tmp = (char*)taosMemoryRealloc(*result, realTotalSize);
L
Liu Jicong 已提交
3128
      if (tmp == NULL) {
wafwerar's avatar
wafwerar 已提交
3129
        taosMemoryFree(*result);
wmmhello's avatar
wmmhello 已提交
3130
        *result = NULL;
wmmhello's avatar
wmmhello 已提交
3131
        return TSDB_CODE_OUT_OF_MEMORY;
L
Liu Jicong 已提交
3132
      } else {
wmmhello's avatar
wmmhello 已提交
3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144
        *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);
3145
    memcpy(*result + offset, pRow, pSup->resultRowSize);
wmmhello's avatar
wmmhello 已提交
3146 3147 3148 3149 3150
    offset += pSup->resultRowSize;

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

wmmhello's avatar
wmmhello 已提交
3151 3152 3153 3154
  *(int32_t*)(*result) = offset;
  *length = offset;

  return TDB_CODE_SUCCESS;
wmmhello's avatar
wmmhello 已提交
3155 3156
}

3157
int32_t aggDecodeResultRow(SOperatorInfo* pOperator, char* result) {
3158
  if (result == NULL) {
wmmhello's avatar
wmmhello 已提交
3159
    return TSDB_CODE_TSC_INVALID_INPUT;
wmmhello's avatar
wmmhello 已提交
3160
  }
wmmhello's avatar
wmmhello 已提交
3161
  SOptrBasicInfo* pInfo = (SOptrBasicInfo*)(pOperator->info);
3162
  SAggSupporter*  pSup = (SAggSupporter*)POINTER_SHIFT(pOperator->info, sizeof(SOptrBasicInfo));
wmmhello's avatar
wmmhello 已提交
3163 3164

  //  int32_t size = taosHashGetSize(pSup->pResultRowHashTable);
3165
  int32_t length = *(int32_t*)(result);
wmmhello's avatar
wmmhello 已提交
3166
  int32_t offset = sizeof(int32_t);
3167 3168 3169 3170

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

L
Liu Jicong 已提交
3171
  while (count-- > 0 && length > offset) {
wmmhello's avatar
wmmhello 已提交
3172 3173 3174
    int32_t keyLen = *(int32_t*)(result + offset);
    offset += sizeof(int32_t);

L
Liu Jicong 已提交
3175
    uint64_t    tableGroupId = *(uint64_t*)(result + offset);
3176
    SResultRow* resultRow = getNewResultRow(pSup->pResultBuf, tableGroupId, pSup->resultRowSize);
L
Liu Jicong 已提交
3177
    if (!resultRow) {
wmmhello's avatar
wmmhello 已提交
3178
      return TSDB_CODE_TSC_INVALID_INPUT;
wmmhello's avatar
wmmhello 已提交
3179
    }
3180

wmmhello's avatar
wmmhello 已提交
3181
    // add a new result set for a new group
3182 3183
    SResultRowPosition pos = {.pageId = resultRow->pageId, .offset = resultRow->offset};
    taosHashPut(pSup->pResultRowHashTable, result + offset, keyLen, &pos, sizeof(SResultRowPosition));
wmmhello's avatar
wmmhello 已提交
3184 3185 3186

    offset += keyLen;
    int32_t valueLen = *(int32_t*)(result + offset);
L
Liu Jicong 已提交
3187
    if (valueLen != pSup->resultRowSize) {
wmmhello's avatar
wmmhello 已提交
3188
      return TSDB_CODE_TSC_INVALID_INPUT;
wmmhello's avatar
wmmhello 已提交
3189 3190 3191 3192 3193 3194 3195 3196 3197 3198
    }
    offset += sizeof(int32_t);
    int32_t pageId = resultRow->pageId;
    int32_t pOffset = resultRow->offset;
    memcpy(resultRow, result + offset, valueLen);
    resultRow->pageId = pageId;
    resultRow->offset = pOffset;
    offset += valueLen;

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

L
Liu Jicong 已提交
3202
  if (offset != length) {
wmmhello's avatar
wmmhello 已提交
3203
    return TSDB_CODE_TSC_INVALID_INPUT;
wmmhello's avatar
wmmhello 已提交
3204
  }
wmmhello's avatar
wmmhello 已提交
3205
  return TDB_CODE_SUCCESS;
wmmhello's avatar
wmmhello 已提交
3206 3207
}

3208 3209
enum {
  PROJECT_RETRIEVE_CONTINUE = 0x1,
L
Liu Jicong 已提交
3210
  PROJECT_RETRIEVE_DONE = 0x2,
3211 3212 3213 3214 3215
};

static int32_t handleLimitOffset(SOperatorInfo* pOperator, SSDataBlock* pBlock) {
  SProjectOperatorInfo* pProjectInfo = pOperator->info;
  SOptrBasicInfo*       pInfo = &pProjectInfo->binfo;
L
Liu Jicong 已提交
3216
  SSDataBlock*          pRes = pInfo->pRes;
3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264

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

3265 3266 3267
  // 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);
3268
    if (pProjectInfo->slimit.limit > 0 && pProjectInfo->slimit.limit <= pProjectInfo->curGroupOutput) {
3269 3270 3271
      pOperator->status = OP_EXEC_DONE;
    }

3272
    return PROJECT_RETRIEVE_DONE;
3273
  }
3274

3275
  // todo optimize performance
3276 3277
  // 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 已提交
3278 3279
  if (pRes->info.rows >= pOperator->resultInfo.threshold || pProjectInfo->slimit.offset != -1 ||
      pProjectInfo->slimit.limit != -1) {
3280
    return PROJECT_RETRIEVE_DONE;
L
Liu Jicong 已提交
3281
  } else {  // not full enough, continue to accumulate the output data in the buffer.
3282 3283 3284 3285
    return PROJECT_RETRIEVE_CONTINUE;
  }
}

3286
static SSDataBlock* doProjectOperation(SOperatorInfo* pOperator) {
3287
  SProjectOperatorInfo* pProjectInfo = pOperator->info;
L
Liu Jicong 已提交
3288
  SOptrBasicInfo*       pInfo = &pProjectInfo->binfo;
3289 3290

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

3293
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
3294 3295 3296
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }
dengyihao's avatar
dengyihao 已提交
3297

H
Haojun Liao 已提交
3298
#if 0
3299 3300 3301 3302 3303
  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 已提交
3304
    setInputDataBlock(pOperator, pInfo->pCtx, pBlock, TSDB_ORDER_ASC);
3305

H
Haojun Liao 已提交
3306
    blockDataEnsureCapacity(pInfo->pRes, pBlock->info.rows);
3307
    projectApplyFunctions(pOperator->pExpr, pInfo->pRes, pBlock, pInfo->pCtx, pOperator->numOfExprs);
L
Liu Jicong 已提交
3308
    if (pRes->info.rows >= pProjectInfo->binfo.capacity * 0.8) {
3309 3310
      copyTsColoum(pRes, pInfo->pCtx, pOperator->numOfExprs);
      resetResultRowEntryResult(pInfo->pCtx, pOperator->numOfExprs);
3311 3312 3313
      return pRes;
    }
  }
H
Haojun Liao 已提交
3314
#endif
3315

3316
  int64_t st = 0;
3317 3318 3319
  int32_t order = 0;
  int32_t scanFlag = 0;

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

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

L
Liu Jicong 已提交
3326
  while (1) {
H
Haojun Liao 已提交
3327
    // The downstream exec may change the value of the newgroup, so use a local variable instead.
3328
    SSDataBlock* pBlock = downstream->fpSet.getNextFn(downstream);
3329
    if (pBlock == NULL) {
3330
      doSetOperatorCompleted(pOperator);
3331 3332 3333 3334
      break;
    }

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

3340
    doFilter(pProjectInfo->pFilterNode, pBlock);
3341

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

X
Xiaoyu Wang 已提交
3345 3346
    code = projectApplyFunctions(pOperator->pExpr, pInfo->pRes, pBlock, pInfo->pCtx, pOperator->numOfExprs,
                                 pProjectInfo->pPseudoColInfo);
3347 3348
    if (code != TSDB_CODE_SUCCESS) {
      longjmp(pTaskInfo->env, code);
3349 3350
    }

3351 3352
    int32_t status = handleLimitOffset(pOperator, pBlock);
    if (status == PROJECT_RETRIEVE_CONTINUE) {
H
Haojun Liao 已提交
3353
      continue;
L
Liu Jicong 已提交
3354
    } else if (status == PROJECT_RETRIEVE_DONE) {
3355 3356 3357
      break;
    }
  }
dengyihao's avatar
dengyihao 已提交
3358

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

3361 3362 3363 3364
  size_t rows = pInfo->pRes->info.rows;
  pOperator->resultInfo.totalRows += rows;

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

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

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

L
Liu Jicong 已提交
3375 3376
  int64_t ekey = Q_STATUS_EQUAL(pTaskInfo->status, TASK_COMPLETED) ? pTaskInfo->window.ekey
                                                                   : pInfo->existNewGroupBlock->info.window.ekey;
3377 3378
  taosResetFillInfo(pInfo->pFillInfo, getFillInfoStart(pInfo->pFillInfo));

3379
  taosFillSetStartInfo(pInfo->pFillInfo, pInfo->existNewGroupBlock->info.rows, ekey);
3380 3381
  taosFillSetInputDataBlock(pInfo->pFillInfo, pInfo->existNewGroupBlock);

3382
  doFillTimeIntervalGapsInResults(pInfo->pFillInfo, pInfo->pRes, pResultInfo->capacity);
3383 3384 3385 3386
  pInfo->existNewGroupBlock = NULL;
  *newgroup = true;
}

L
Liu Jicong 已提交
3387 3388
static void doHandleRemainBlockFromNewGroup(SFillOperatorInfo* pInfo, SResultInfo* pResultInfo, bool* newgroup,
                                            SExecTaskInfo* pTaskInfo) {
3389 3390
  if (taosFillHasMoreResults(pInfo->pFillInfo)) {
    *newgroup = false;
3391
    doFillTimeIntervalGapsInResults(pInfo->pFillInfo, pInfo->pRes, (int32_t)pResultInfo->capacity);
H
Haojun Liao 已提交
3392
    if (pInfo->pRes->info.rows > pResultInfo->threshold || (!pInfo->multigroupResult)) {
3393 3394 3395 3396 3397 3398
      return;
    }
  }

  // handle the cached new group data block
  if (pInfo->existNewGroupBlock) {
3399
    doHandleRemainBlockForNewGroupImpl(pInfo, pResultInfo, newgroup, pTaskInfo);
3400 3401 3402
  }
}

3403
static SSDataBlock* doFill(SOperatorInfo* pOperator) {
L
Liu Jicong 已提交
3404 3405
  SFillOperatorInfo* pInfo = pOperator->info;
  SExecTaskInfo*     pTaskInfo = pOperator->pTaskInfo;
3406

H
Haojun Liao 已提交
3407
  SResultInfo* pResultInfo = &pOperator->resultInfo;
3408 3409 3410
  SSDataBlock* pResBlock = pInfo->pRes;

  blockDataCleanup(pResBlock);
3411 3412 3413 3414
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

3415
  // todo handle different group data interpolation
X
Xiaoyu Wang 已提交
3416 3417
  bool  n = false;
  bool* newgroup = &n;
3418
  doHandleRemainBlockFromNewGroup(pInfo, pResultInfo, newgroup, pTaskInfo);
3419 3420
  if (pResBlock->info.rows > pResultInfo->threshold || (!pInfo->multigroupResult && pResBlock->info.rows > 0)) {
    return pResBlock;
H
Haojun Liao 已提交
3421
  }
3422

H
Haojun Liao 已提交
3423
  SOperatorInfo* pDownstream = pOperator->pDownstream[0];
L
Liu Jicong 已提交
3424
  while (1) {
3425
    SSDataBlock* pBlock = pDownstream->fpSet.getNextFn(pDownstream);
3426 3427 3428 3429 3430 3431 3432 3433 3434 3435
    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
3436
      taosFillSetStartInfo(pInfo->pFillInfo, 0, pTaskInfo->window.ekey);
3437 3438 3439 3440 3441 3442 3443
    } else {
      if (pBlock == NULL) {
        if (pInfo->totalInputRows == 0) {
          pOperator->status = OP_EXEC_DONE;
          return NULL;
        }

3444
        taosFillSetStartInfo(pInfo->pFillInfo, 0, pTaskInfo->window.ekey);
3445 3446 3447 3448 3449 3450 3451
      } else {
        pInfo->totalInputRows += pBlock->info.rows;
        taosFillSetStartInfo(pInfo->pFillInfo, pBlock->info.rows, pBlock->info.window.ekey);
        taosFillSetInputDataBlock(pInfo->pFillInfo, pBlock);
      }
    }

3452 3453
    blockDataEnsureCapacity(pResBlock, pOperator->resultInfo.capacity);
    doFillTimeIntervalGapsInResults(pInfo->pFillInfo, pResBlock, pOperator->resultInfo.capacity);
3454 3455

    // current group has no more result to return
3456
    if (pResBlock->info.rows > 0) {
3457 3458
      // 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
3459 3460
      if (pResBlock->info.rows > pResultInfo->threshold || pBlock == NULL || (!pInfo->multigroupResult)) {
        return pResBlock;
3461 3462
      }

3463
      doHandleRemainBlockFromNewGroup(pInfo, pResultInfo, newgroup, pTaskInfo);
3464 3465
      if (pResBlock->info.rows > pOperator->resultInfo.threshold || pBlock == NULL) {
        return pResBlock;
3466 3467 3468
      }
    } else if (pInfo->existNewGroupBlock) {  // try next group
      assert(pBlock != NULL);
3469
      doHandleRemainBlockForNewGroupImpl(pInfo, pResultInfo, newgroup, pTaskInfo);
3470 3471
      if (pResBlock->info.rows > pResultInfo->threshold) {
        return pResBlock;
3472 3473 3474 3475 3476 3477 3478
      }
    } else {
      return NULL;
    }
  }
}

H
Haojun Liao 已提交
3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489
static void destroyExprInfo(SExprInfo* pExpr, int32_t numOfExprs) {
  for (int32_t i = 0; i < numOfExprs; ++i) {
    SExprInfo* pExprInfo = &pExpr[i];
    if (pExprInfo->pExpr->nodeType == QUERY_NODE_COLUMN) {
      taosMemoryFree(pExprInfo->base.pParam[0].pCol);
    }
    taosMemoryFree(pExprInfo->base.pParam);
    taosMemoryFree(pExprInfo->pExpr);
  }
}

3490 3491 3492 3493 3494
static void destroyOperatorInfo(SOperatorInfo* pOperator) {
  if (pOperator == NULL) {
    return;
  }

3495
  if (pOperator->fpSet.closeFn != NULL) {
3496
    pOperator->fpSet.closeFn(pOperator->info, pOperator->numOfExprs);
3497 3498
  }

H
Haojun Liao 已提交
3499
  if (pOperator->pDownstream != NULL) {
L
Liu Jicong 已提交
3500
    for (int32_t i = 0; i < pOperator->numOfDownstream; ++i) {
H
Haojun Liao 已提交
3501
      destroyOperatorInfo(pOperator->pDownstream[i]);
3502 3503
    }

wafwerar's avatar
wafwerar 已提交
3504
    taosMemoryFreeClear(pOperator->pDownstream);
H
Haojun Liao 已提交
3505
    pOperator->numOfDownstream = 0;
3506 3507
  }

H
Haojun Liao 已提交
3508
  if (pOperator->pExpr != NULL) {
H
Haojun Liao 已提交
3509
    destroyExprInfo(pOperator->pExpr, pOperator->numOfExprs);
H
Haojun Liao 已提交
3510 3511
  }

D
fix bug  
dapan 已提交
3512
  taosMemoryFreeClear(pOperator->pExpr);
wafwerar's avatar
wafwerar 已提交
3513 3514
  taosMemoryFreeClear(pOperator->info);
  taosMemoryFreeClear(pOperator);
3515 3516
}

3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531
int32_t getBufferPgSize(int32_t rowSize, uint32_t* defaultPgsz, uint32_t* defaultBufsz) {
  *defaultPgsz = 4096;
  while (*defaultPgsz < rowSize * 4) {
    *defaultPgsz <<= 1u;
  }

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

  return 0;
}

dengyihao's avatar
dengyihao 已提交
3532 3533
int32_t doInitAggInfoSup(SAggSupporter* pAggSup, SqlFunctionCtx* pCtx, int32_t numOfOutput, size_t keyBufSize,
                         const char* pKey) {
3534 3535
  _hash_fn_t hashFn = taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY);

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

H
Haojun Liao 已提交
3540
  if (pAggSup->keyBuf == NULL || pAggSup->pResultRowHashTable == NULL) {
3541 3542 3543
    return TSDB_CODE_OUT_OF_MEMORY;
  }

dengyihao's avatar
dengyihao 已提交
3544
  uint32_t defaultPgsz = 0;
3545 3546
  uint32_t defaultBufsz = 0;
  getBufferPgSize(pAggSup->resultRowSize, &defaultPgsz, &defaultBufsz);
H
Haojun Liao 已提交
3547

3548
  int32_t code = createDiskbasedBuf(&pAggSup->pResultBuf, defaultPgsz, defaultBufsz, pKey, TD_TMP_DIR_PATH);
H
Haojun Liao 已提交
3549 3550 3551 3552
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

3553 3554 3555
  return TSDB_CODE_SUCCESS;
}

3556
void cleanupAggSup(SAggSupporter* pAggSup) {
wafwerar's avatar
wafwerar 已提交
3557
  taosMemoryFreeClear(pAggSup->keyBuf);
3558
  taosHashCleanup(pAggSup->pResultRowHashTable);
H
Haojun Liao 已提交
3559
  destroyDiskbasedBuf(pAggSup->pResultBuf);
3560 3561
}

H
Haojun Liao 已提交
3562
int32_t initAggInfo(SOptrBasicInfo* pBasicInfo, SAggSupporter* pAggSup, SExprInfo* pExprInfo, int32_t numOfCols,
3563
                    SSDataBlock* pResultBlock, size_t keyBufSize, const char* pkey) {
3564
  pBasicInfo->pCtx = createSqlFunctionCtx(pExprInfo, numOfCols, &pBasicInfo->rowCellInfoOffset);
H
Haojun Liao 已提交
3565 3566
  pBasicInfo->pRes = pResultBlock;

3567
  doInitAggInfoSup(pAggSup, pBasicInfo->pCtx, numOfCols, keyBufSize, pkey);
3568

L
Liu Jicong 已提交
3569
  for (int32_t i = 0; i < numOfCols; ++i) {
3570 3571 3572
    pBasicInfo->pCtx[i].pBuf = pAggSup->pResultBuf;
  }

3573
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
3574 3575
}

3576 3577 3578 3579 3580 3581 3582 3583 3584
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;
  }
}

L
Liu Jicong 已提交
3585
SOperatorInfo* createAggregateOperatorInfo(SOperatorInfo* downstream, SExprInfo* pExprInfo, int32_t numOfCols,
3586
                                           SSDataBlock* pResultBlock, SExprInfo* pScalarExprInfo,
wmmhello's avatar
wmmhello 已提交
3587
                                           int32_t numOfScalarExpr, SExecTaskInfo* pTaskInfo) {
wafwerar's avatar
wafwerar 已提交
3588
  SAggOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SAggOperatorInfo));
L
Liu Jicong 已提交
3589
  SOperatorInfo*    pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
3590 3591 3592
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }
H
Haojun Liao 已提交
3593

3594
  int32_t numOfRows = 1024;
dengyihao's avatar
dengyihao 已提交
3595
  size_t  keyBufSize = sizeof(int64_t) + sizeof(int64_t) + POINTER_BYTES;
3596 3597

  initResultSizeInfo(pOperator, numOfRows);
dengyihao's avatar
dengyihao 已提交
3598 3599
  int32_t code =
      initAggInfo(&pInfo->binfo, &pInfo->aggSup, pExprInfo, numOfCols, pResultBlock, keyBufSize, pTaskInfo->id.str);
L
Liu Jicong 已提交
3600
  if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
3601 3602
    goto _error;
  }
H
Haojun Liao 已提交
3603

H
Haojun Liao 已提交
3604
  pInfo->groupId = INT32_MIN;
3605
  initResultRowInfo(&pInfo->binfo.resultRowInfo);
H
Haojun Liao 已提交
3606

3607 3608
  pInfo->pScalarExprInfo = pScalarExprInfo;
  pInfo->numOfScalarExpr = numOfScalarExpr;
3609
  if (pInfo->pScalarExprInfo != NULL) {
3610
    pInfo->pScalarCtx = createSqlFunctionCtx(pScalarExprInfo, numOfScalarExpr, &pInfo->rowCellInfoOffset);
3611
  }
3612

dengyihao's avatar
dengyihao 已提交
3613
  pOperator->name = "TableAggregate";
3614
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_HASH_AGG;
3615
  pOperator->blocking = true;
dengyihao's avatar
dengyihao 已提交
3616 3617 3618
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
  pOperator->pExpr = pExprInfo;
3619
  pOperator->numOfExprs = numOfCols;
dengyihao's avatar
dengyihao 已提交
3620
  pOperator->pTaskInfo = pTaskInfo;
H
Haojun Liao 已提交
3621

3622 3623
  pOperator->fpSet = createOperatorFpSet(doOpenAggregateOptr, getAggregateResult, NULL, NULL, destroyAggOperatorInfo,
                                         aggEncodeResultRow, aggDecodeResultRow, NULL);
H
Haojun Liao 已提交
3624 3625 3626 3627 3628

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

  return pOperator;
L
Liu Jicong 已提交
3631
_error:
H
Haojun Liao 已提交
3632
  destroyAggOperatorInfo(pInfo, numOfCols);
wafwerar's avatar
wafwerar 已提交
3633 3634
  taosMemoryFreeClear(pInfo);
  taosMemoryFreeClear(pOperator);
H
Haojun Liao 已提交
3635 3636
  pTaskInfo->code = TSDB_CODE_OUT_OF_MEMORY;
  return NULL;
3637 3638
}

3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657
static void* destroySqlFunctionCtx(SqlFunctionCtx* pCtx, int32_t numOfOutput) {
  if (pCtx == NULL) {
    return NULL;
  }

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

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

  taosMemoryFreeClear(pCtx);
  return NULL;
}

H
Haojun Liao 已提交
3658
void doDestroyBasicInfo(SOptrBasicInfo* pInfo, int32_t numOfOutput) {
3659 3660
  assert(pInfo != NULL);

3661
  destroySqlFunctionCtx(pInfo->pCtx, numOfOutput);
wafwerar's avatar
wafwerar 已提交
3662
  taosMemoryFreeClear(pInfo->rowCellInfoOffset);
3663 3664

  cleanupResultRowInfo(&pInfo->resultRowInfo);
H
Haojun Liao 已提交
3665
  pInfo->pRes = blockDataDestroy(pInfo->pRes);
3666 3667
}

H
Haojun Liao 已提交
3668
void destroyBasicOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
3669
  SOptrBasicInfo* pInfo = (SOptrBasicInfo*)param;
3670 3671
  doDestroyBasicInfo(pInfo, numOfOutput);
}
H
Haojun Liao 已提交
3672 3673

void destroyAggOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
3674
  SAggOperatorInfo* pInfo = (SAggOperatorInfo*)param;
3675 3676
  doDestroyBasicInfo(&pInfo->binfo, numOfOutput);
}
3677

H
Haojun Liao 已提交
3678
void destroySFillOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
3679
  SFillOperatorInfo* pInfo = (SFillOperatorInfo*)param;
3680
  pInfo->pFillInfo = taosDestroyFillInfo(pInfo->pFillInfo);
H
Haojun Liao 已提交
3681
  pInfo->pRes = blockDataDestroy(pInfo->pRes);
wafwerar's avatar
wafwerar 已提交
3682
  taosMemoryFreeClear(pInfo->p);
3683 3684
}

H
Haojun Liao 已提交
3685
static void destroyProjectOperatorInfo(void* param, int32_t numOfOutput) {
D
fix bug  
dapan 已提交
3686 3687 3688
  if (NULL == param) {
    return;
  }
L
Liu Jicong 已提交
3689
  SProjectOperatorInfo* pInfo = (SProjectOperatorInfo*)param;
3690
  doDestroyBasicInfo(&pInfo->binfo, numOfOutput);
H
Haojun Liao 已提交
3691
  cleanupAggSup(&pInfo->aggSup);
H
Haojun Liao 已提交
3692
  taosArrayDestroy(pInfo->pPseudoColInfo);
3693 3694
}

H
Haojun Liao 已提交
3695
static void destroyIndefinitOperatorInfo(void* param, int32_t numOfOutput) {
3696
  SIndefOperatorInfo* pInfo = (SIndefOperatorInfo*)param;
H
Haojun Liao 已提交
3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707
  doDestroyBasicInfo(&pInfo->binfo, numOfOutput);

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

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

  taosMemoryFree(pInfo->rowCellInfoOffset);
}

H
Haojun Liao 已提交
3708
void destroyExchangeOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
3709
  SExchangeInfo* pExInfo = (SExchangeInfo*)param;
3710 3711 3712 3713
  taosRemoveRef(exchangeObjRefPool, pExInfo->self);
}

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

H
Haojun Liao 已提交
3716 3717 3718 3719 3720 3721 3722 3723 3724
  taosArrayDestroy(pExInfo->pSources);
  taosArrayDestroy(pExInfo->pSourceDataInfo);
  if (pExInfo->pResult != NULL) {
    blockDataDestroy(pExInfo->pResult);
  }

  tsem_destroy(&pExInfo->ready);
}

H
Haojun Liao 已提交
3725 3726
static SArray* setRowTsColumnOutputInfo(SqlFunctionCtx* pCtx, int32_t numOfCols) {
  SArray* pList = taosArrayInit(4, sizeof(int32_t));
dengyihao's avatar
dengyihao 已提交
3727
  for (int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
3728 3729 3730 3731 3732 3733 3734 3735
    if (fmIsPseudoColumnFunc(pCtx[i].functionId)) {
      taosArrayPush(pList, &i);
    }
  }

  return pList;
}

3736
SOperatorInfo* createProjectOperatorInfo(SOperatorInfo* downstream, SProjectPhysiNode* pProjPhyNode, SExecTaskInfo* pTaskInfo) {
wafwerar's avatar
wafwerar 已提交
3737
  SProjectOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SProjectOperatorInfo));
L
Liu Jicong 已提交
3738
  SOperatorInfo*        pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
3739 3740 3741
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }
3742

3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755
  int32_t numOfCols = 0;
  SExprInfo* pExprInfo = createExprInfo(pProjPhyNode->pProjections, NULL, &numOfCols);

  SSDataBlock* pResBlock = createResDataBlock(pProjPhyNode->node.pOutputDataBlockDesc);
  SLimit       limit = {.limit = pProjPhyNode->limit, .offset = pProjPhyNode->offset};
  SLimit       slimit = {.limit = pProjPhyNode->slimit, .offset = pProjPhyNode->soffset};

  pInfo->limit       = limit;
  pInfo->slimit      = slimit;
  pInfo->curOffset   = limit.offset;
  pInfo->curSOffset  = slimit.offset;
  pInfo->binfo.pRes  = pResBlock;
  pInfo->pFilterNode = pProjPhyNode->node.pConditions;
H
Haojun Liao 已提交
3756 3757

  int32_t numOfRows = 4096;
dengyihao's avatar
dengyihao 已提交
3758
  size_t  keyBufSize = sizeof(int64_t) + sizeof(int64_t) + POINTER_BYTES;
3759

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

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

X
Xiaoyu Wang 已提交
3770
  pInfo->pPseudoColInfo = setRowTsColumnOutputInfo(pInfo->binfo.pCtx, numOfCols);
3771
  pOperator->name       = "ProjectOperator";
H
Haojun Liao 已提交
3772
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_PROJECT;
3773 3774 3775 3776 3777 3778
  pOperator->blocking   = false;
  pOperator->status     = OP_NOT_OPENED;
  pOperator->info       = pInfo;
  pOperator->pExpr      = pExprInfo;
  pOperator->numOfExprs = numOfCols;
  pOperator->pTaskInfo  = pTaskInfo;
3779

L
Liu Jicong 已提交
3780 3781
  pOperator->fpSet = createOperatorFpSet(operatorDummyOpenFn, doProjectOperation, NULL, NULL,
                                         destroyProjectOperatorInfo, NULL, NULL, NULL);
L
Liu Jicong 已提交
3782

3783
  int32_t code = appendDownstream(pOperator, &downstream, 1);
H
Haojun Liao 已提交
3784
  if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
3785 3786
    goto _error;
  }
3787 3788

  return pOperator;
H
Haojun Liao 已提交
3789

L
Liu Jicong 已提交
3790
_error:
H
Haojun Liao 已提交
3791 3792
  pTaskInfo->code = TSDB_CODE_OUT_OF_MEMORY;
  return NULL;
3793 3794
}

H
Haojun Liao 已提交
3795 3796
static SSDataBlock* doApplyIndefinitFunction(SOperatorInfo* pOperator) {
  SIndefOperatorInfo* pIndefInfo = pOperator->info;
3797
  SOptrBasicInfo*     pInfo = &pIndefInfo->binfo;
H
Haojun Liao 已提交
3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842

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

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

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

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

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

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

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

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

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

3843 3844
    code = projectApplyFunctions(pOperator->pExpr, pInfo->pRes, pBlock, pInfo->pCtx, pOperator->numOfExprs,
                                 pIndefInfo->pPseudoColInfo);
H
Haojun Liao 已提交
3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859
    if (code != TSDB_CODE_SUCCESS) {
      longjmp(pTaskInfo->env, code);
    }
  }

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

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

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

3860 3861
SOperatorInfo* createIndefinitOutputOperatorInfo(SOperatorInfo* downstream, SPhysiNode* pNode,
                                                 SExecTaskInfo* pTaskInfo) {
H
Haojun Liao 已提交
3862
  SIndefOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SIndefOperatorInfo));
3863
  SOperatorInfo*      pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }

  SIndefRowsFuncPhysiNode* pPhyNode = (SIndefRowsFuncPhysiNode*)pNode;

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

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

3879 3880
  SSDataBlock* pResBlock = createResDataBlock(pPhyNode->node.pOutputDataBlockDesc);
  ;
H
Haojun Liao 已提交
3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894

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

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

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

3895 3896 3897
  pInfo->binfo.pRes = pResBlock;
  pInfo->numOfScalarExpr = numOfScalarExpr;
  pInfo->pPseudoColInfo = setRowTsColumnOutputInfo(pInfo->binfo.pCtx, numOfExpr);
H
Haojun Liao 已提交
3898

3899
  pOperator->name = "IndefinitOperator";
H
Haojun Liao 已提交
3900
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_PROJECT;
3901 3902 3903 3904 3905 3906
  pOperator->blocking = false;
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
  pOperator->pExpr = pExprInfo;
  pOperator->numOfExprs = numOfExpr;
  pOperator->pTaskInfo = pTaskInfo;
H
Haojun Liao 已提交
3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917

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

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

  return pOperator;

3918
_error:
H
Haojun Liao 已提交
3919 3920 3921 3922 3923 3924
  taosMemoryFree(pInfo);
  taosMemoryFree(pOperator);
  pTaskInfo->code = TSDB_CODE_OUT_OF_MEMORY;
  return NULL;
}

3925
static int32_t initFillInfo(SFillOperatorInfo* pInfo, SExprInfo* pExpr, int32_t numOfCols, SNodeListNode* pValNode,
L
Liu Jicong 已提交
3926
                            STimeWindow win, int32_t capacity, const char* id, SInterval* pInterval, int32_t fillType) {
3927
  SFillColInfo* pColInfo = createFillColInfo(pExpr, numOfCols, pValNode);
H
Haojun Liao 已提交
3928 3929

  STimeWindow w = TSWINDOW_INITIALIZER;
3930
  getAlignQueryTimeWindow(pInterval, pInterval->precision, win.skey, &w);
H
Haojun Liao 已提交
3931 3932

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

wafwerar's avatar
wafwerar 已提交
3935
  pInfo->p = taosMemoryCalloc(numOfCols, POINTER_BYTES);
H
Haojun Liao 已提交
3936
  if (pInfo->pFillInfo == NULL || pInfo->p == NULL) {
H
Haojun Liao 已提交
3937 3938
    taosMemoryFree(pInfo->pFillInfo);
    taosMemoryFree(pInfo->p);
H
Haojun Liao 已提交
3939 3940 3941 3942 3943 3944
    return TSDB_CODE_OUT_OF_MEMORY;
  } else {
    return TSDB_CODE_SUCCESS;
  }
}

3945
static int32_t convertFillType(int32_t mode) {
3946
  int32_t type = TSDB_FILL_NONE;
3947
  switch (mode) {
dengyihao's avatar
dengyihao 已提交
3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965
    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;
3966 3967 3968 3969
    default:
      type = TSDB_FILL_NONE;
  }

3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986
  return type;
}

SOperatorInfo* createFillOperatorInfo(SOperatorInfo* downstream, SFillPhysiNode* pPhyFillNode, bool multigroupResult,
                                      SExecTaskInfo* pTaskInfo) {
  SFillOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SFillOperatorInfo));
  SOperatorInfo*     pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }

  int32_t num = 0;
  SSDataBlock*    pResBlock = createResDataBlock(pPhyFillNode->node.pOutputDataBlockDesc);
  SExprInfo* pExprInfo = createExprInfo(pPhyFillNode->pTargets, NULL, &num);
  SInterval* pInterval = &((SIntervalAggOperatorInfo*)downstream->info)->interval;
  int32_t    type = convertFillType(pPhyFillNode->mode);

H
Haojun Liao 已提交
3987
  SResultInfo* pResultInfo = &pOperator->resultInfo;
3988 3989
  initResultSizeInfo(pOperator, 4096);

3990 3991
  int32_t code = initFillInfo(pInfo, pExprInfo, num, (SNodeListNode*)pPhyFillNode->pValues, pPhyFillNode->timeRange,
                              pResultInfo->capacity, pTaskInfo->id.str, pInterval, type);
3992 3993 3994
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
3995

3996 3997 3998 3999 4000
  pInfo->pRes             = pResBlock;
  pInfo->multigroupResult = multigroupResult;
  pOperator->name         = "FillOperator";
  pOperator->blocking     = false;
  pOperator->status       = OP_NOT_OPENED;
4001
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_FILL;
4002 4003 4004 4005
  pOperator->pExpr        = pExprInfo;
  pOperator->numOfExprs   = num;
  pOperator->info         = pInfo;
  pOperator->pTaskInfo    = pTaskInfo;
H
Haojun Liao 已提交
4006

L
Liu Jicong 已提交
4007 4008
  pOperator->fpSet =
      createOperatorFpSet(operatorDummyOpenFn, doFill, NULL, NULL, destroySFillOperatorInfo, NULL, NULL, NULL);
4009

4010
  code = appendDownstream(pOperator, &downstream, 1);
4011
  return pOperator;
H
Haojun Liao 已提交
4012

L
Liu Jicong 已提交
4013
_error:
wafwerar's avatar
wafwerar 已提交
4014 4015
  taosMemoryFreeClear(pOperator);
  taosMemoryFreeClear(pInfo);
H
Haojun Liao 已提交
4016
  return NULL;
4017 4018
}

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

D
dapan1121 已提交
4023
  pTaskInfo->schemaVer.dbname = strdup(dbFName);
4024
  pTaskInfo->cost.created = taosGetTimestampMs();
H
Haojun Liao 已提交
4025
  pTaskInfo->id.queryId = queryId;
dengyihao's avatar
dengyihao 已提交
4026
  pTaskInfo->execModel = model;
H
Haojun Liao 已提交
4027

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

4032 4033
  return pTaskInfo;
}
H
Haojun Liao 已提交
4034

L
Liu Jicong 已提交
4035
static tsdbReaderT doCreateDataReader(STableScanPhysiNode* pTableScanNode, SReadHandle* pHandle,
4036
                                      STableListInfo* pTableListInfo, uint64_t queryId, uint64_t taskId,
dengyihao's avatar
dengyihao 已提交
4037
                                      SNode* pTagCond);
H
Haojun Liao 已提交
4038

H
Haojun Liao 已提交
4039
static SArray* extractColumnInfo(SNodeList* pNodeList);
4040

D
dapan1121 已提交
4041
int32_t extractTableSchemaVersion(SReadHandle* pHandle, uint64_t uid, SExecTaskInfo* pTaskInfo) {
4042 4043
  SMetaReader mr = {0};
  metaReaderInit(&mr, pHandle->meta, 0);
D
dapan1121 已提交
4044 4045 4046 4047 4048
  int32_t code = metaGetTableEntryByUid(&mr, uid);
  if (code) {
    metaReaderClear(&mr);
    return code;
  }
4049 4050 4051 4052

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

  if (mr.me.type == TSDB_SUPER_TABLE) {
4053 4054
    pTaskInfo->schemaVer.sversion = mr.me.stbEntry.schemaRow.version;
    pTaskInfo->schemaVer.tversion = mr.me.stbEntry.schemaTag.version;
4055 4056 4057
  } else if (mr.me.type == TSDB_CHILD_TABLE) {
    tb_uid_t suid = mr.me.ctbEntry.suid;
    metaGetTableEntryByUid(&mr, suid);
4058 4059
    pTaskInfo->schemaVer.sversion = mr.me.stbEntry.schemaRow.version;
    pTaskInfo->schemaVer.tversion = mr.me.stbEntry.schemaTag.version;
4060
  } else {
4061
    pTaskInfo->schemaVer.sversion = mr.me.ntbEntry.schemaRow.version;
4062
  }
4063 4064

  metaReaderClear(&mr);
D
dapan1121 已提交
4065 4066

  return TSDB_CODE_SUCCESS;
4067 4068
}

X
Xiaoyu Wang 已提交
4069 4070
int32_t generateGroupIdMap(STableListInfo* pTableListInfo, SReadHandle* pHandle, SArray* groupKey) {
  if (groupKey == NULL) {
wmmhello's avatar
wmmhello 已提交
4071 4072 4073 4074 4075 4076 4077 4078
    return TDB_CODE_SUCCESS;
  }

  pTableListInfo->map = taosHashInit(32, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), false, HASH_NO_LOCK);
  if (pTableListInfo->map == NULL) {
    return TSDB_CODE_OUT_OF_MEMORY;
  }
  int32_t keyLen = 0;
X
Xiaoyu Wang 已提交
4079
  void*   keyBuf = NULL;
wmmhello's avatar
wmmhello 已提交
4080 4081 4082
  int32_t numOfGroupCols = taosArrayGetSize(groupKey);
  for (int32_t j = 0; j < numOfGroupCols; ++j) {
    SColumn* pCol = taosArrayGet(groupKey, j);
X
Xiaoyu Wang 已提交
4083
    keyLen += pCol->bytes;  // actual data + null_flag
wmmhello's avatar
wmmhello 已提交
4084 4085 4086 4087 4088 4089 4090 4091 4092 4093
  }

  int32_t nullFlagSize = sizeof(int8_t) * numOfGroupCols;
  keyLen += nullFlagSize;

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

X
Xiaoyu Wang 已提交
4094 4095 4096
  for (int32_t i = 0; i < taosArrayGetSize(pTableListInfo->pTableList); i++) {
    STableKeyInfo* info = taosArrayGet(pTableListInfo->pTableList, i);
    SMetaReader    mr = {0};
wmmhello's avatar
wmmhello 已提交
4097 4098 4099 4100 4101 4102 4103 4104
    metaReaderInit(&mr, pHandle->meta, 0);
    metaGetTableEntryByUid(&mr, info->uid);

    char* isNull = (char*)keyBuf;
    char* pStart = (char*)keyBuf + sizeof(int8_t) * numOfGroupCols;
    for (int32_t j = 0; j < numOfGroupCols; ++j) {
      SColumn* pCol = taosArrayGet(groupKey, j);

X
Xiaoyu Wang 已提交
4105
      if (strcmp(pCol->name, "tbname") == 0) {
wmmhello's avatar
wmmhello 已提交
4106 4107 4108
        isNull[i] = 0;
        memcpy(pStart, mr.me.name, strlen(mr.me.name));
        pStart += strlen(mr.me.name);
X
Xiaoyu Wang 已提交
4109
      } else {
wmmhello's avatar
wmmhello 已提交
4110 4111 4112
        STagVal tagVal = {0};
        tagVal.cid = pCol->colId;
        const char* p = metaGetTableTagVal(&mr.me, pCol->type, &tagVal);
X
Xiaoyu Wang 已提交
4113
        if (p == NULL) {
wmmhello's avatar
wmmhello 已提交
4114 4115 4116 4117 4118
          isNull[j] = 1;
          continue;
        }
        isNull[i] = 0;
        if (pCol->type == TSDB_DATA_TYPE_JSON) {
X
Xiaoyu Wang 已提交
4119 4120 4121
          //          int32_t dataLen = getJsonValueLen(pkey->pData);
          //          memcpy(pStart, (pkey->pData), dataLen);
          //          pStart += dataLen;
wmmhello's avatar
wmmhello 已提交
4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132
        } else if (IS_VAR_DATA_TYPE(pCol->type)) {
          memcpy(pStart, tagVal.pData, tagVal.nData);
          pStart += tagVal.nData;
          ASSERT(tagVal.nData <= pCol->bytes);
        } else {
          memcpy(pStart, &(tagVal.i64), pCol->bytes);
          pStart += pCol->bytes;
        }
      }
    }

X
Xiaoyu Wang 已提交
4133
    int32_t   len = (int32_t)(pStart - (char*)keyBuf);
wmmhello's avatar
wmmhello 已提交
4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147
    uint64_t* groupId = taosHashGet(pTableListInfo->map, keyBuf, len);
    if (groupId) {
      taosHashPut(pTableListInfo->map, &(info->uid), sizeof(uint64_t), groupId, sizeof(uint64_t));
    } else {
      uint64_t tmpId = calcGroupId(keyBuf, len);
      taosHashPut(pTableListInfo->map, &(info->uid), sizeof(uint64_t), &tmpId, sizeof(uint64_t));
    }

    metaReaderClear(&mr);
  }
  taosMemoryFree(keyBuf);
  return TDB_CODE_SUCCESS;
}

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

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

dengyihao's avatar
dengyihao 已提交
4156
      tsdbReaderT pDataReader =
dengyihao's avatar
dengyihao 已提交
4157
          doCreateDataReader(pTableScanNode, pHandle, pTableListInfo, (uint64_t)queryId, taskId, pTagCond);
4158
      if (pDataReader == NULL && terrno != 0) {
4159
        pTaskInfo->code = terrno;
4160 4161
        return NULL;
      }
wmmhello's avatar
wmmhello 已提交
4162

D
dapan1121 已提交
4163 4164 4165
      int32_t code = extractTableSchemaVersion(pHandle, pTableScanNode->scan.uid, pTaskInfo);
      if (code) {
        tsdbCleanupReadHandle(pDataReader);
4166
        pTaskInfo->code = terrno;
D
dapan1121 已提交
4167 4168
        return NULL;
      }
wmmhello's avatar
wmmhello 已提交
4169

X
Xiaoyu Wang 已提交
4170
      SArray* groupKeys = extractPartitionColInfo(pTableScanNode->pPartitionTags);
S
slzhou 已提交
4171
      code = generateGroupIdMap(pTableListInfo, pHandle, groupKeys);  // todo for json
4172
      taosArrayDestroy(groupKeys);
S
slzhou 已提交
4173
      if (code) {
wmmhello's avatar
wmmhello 已提交
4174
        tsdbCleanupReadHandle(pDataReader);
4175
        pTaskInfo->code = terrno;
wmmhello's avatar
wmmhello 已提交
4176 4177 4178
        return NULL;
      }

X
Xiaoyu Wang 已提交
4179
      SOperatorInfo*  pOperator = createTableScanOperatorInfo(pTableScanNode, pDataReader, pHandle, pTaskInfo);
4180 4181
      STableScanInfo* pScanInfo = pOperator->info;
      pTaskInfo->cost.pRecoder = &pScanInfo->readRecorder;
S
slzhou 已提交
4182 4183 4184
      return pOperator;
    } else if (QUERY_NODE_PHYSICAL_PLAN_TABLE_MERGE_SCAN == type) {
      STableMergeScanPhysiNode* pTableScanNode = (STableMergeScanPhysiNode*)pPhyNode;
4185

S
shenglian zhou 已提交
4186 4187 4188
      SArray* dataReaders = taosArrayInit(8, POINTER_BYTES);
      createMultipleDataReaders(pTableScanNode, pHandle, pTableListInfo, dataReaders, queryId, taskId, pTagCond);
      extractTableSchemaVersion(pHandle, pTableScanNode->scan.uid, pTaskInfo);
X
Xiaoyu Wang 已提交
4189
      SArray* groupKeys = extractPartitionColInfo(pTableScanNode->pPartitionTags);
X
Xiaoyu Wang 已提交
4190
      generateGroupIdMap(pTableListInfo, pHandle, groupKeys);  // todo for json
4191
      taosArrayDestroy(groupKeys);
X
Xiaoyu Wang 已提交
4192
      SOperatorInfo*  pOperator = createTableMergeScanOperatorInfo(pTableScanNode, dataReaders, pHandle, pTaskInfo);
4193 4194 4195
      STableScanInfo* pScanInfo = pOperator->info;
      pTaskInfo->cost.pRecoder = &pScanInfo->readRecorder;
      return pOperator;
H
Haojun Liao 已提交
4196
    } else if (QUERY_NODE_PHYSICAL_PLAN_EXCHANGE == type) {
4197
      return createExchangeOperatorInfo(pHandle->pMsgCb->clientRpc, (SExchangePhysiNode*)pPhyNode, pTaskInfo);
H
Haojun Liao 已提交
4198
    } else if (QUERY_NODE_PHYSICAL_PLAN_STREAM_SCAN == type) {
X
Xiaoyu Wang 已提交
4199
      SScanPhysiNode*      pScanPhyNode = (SScanPhysiNode*)pPhyNode;  // simple child table.
5
54liuyao 已提交
4200
      STableScanPhysiNode* pTableScanNode = (STableScanPhysiNode*)pPhyNode;
4201
      STimeWindowAggSupp   twSup = {
S
shenglian zhou 已提交
4202
            .waterMark = pTableScanNode->watermark, .calTrigger = pTableScanNode->triggerType, .maxTs = INT64_MIN};
5
54liuyao 已提交
4203 4204
      tsdbReaderT pDataReader = NULL;
      if (pHandle->vnode) {
wmmhello's avatar
wmmhello 已提交
4205
        pDataReader = doCreateDataReader(pTableScanNode, pHandle, pTableListInfo, (uint64_t)queryId, taskId, pTagCond);
wmmhello's avatar
wmmhello 已提交
4206
      } else {
4207
        getTableList(pHandle->meta, pScanPhyNode, pTableListInfo, pTagCond);
5
54liuyao 已提交
4208
      }
4209

5
54liuyao 已提交
4210
      if (pDataReader == NULL && terrno != 0) {
4211
        qDebug("%s pDataReader is NULL", GET_TASKID(pTaskInfo));
5
54liuyao 已提交
4212 4213
        // return NULL;
      } else {
4214
        qDebug("%s pDataReader is not NULL", GET_TASKID(pTaskInfo));
5
54liuyao 已提交
4215
      }
4216

X
Xiaoyu Wang 已提交
4217 4218
      SArray* groupKeys = extractPartitionColInfo(pTableScanNode->pPartitionTags);
      int32_t code = generateGroupIdMap(pTableListInfo, pHandle, groupKeys);  // todo for json
4219
      taosArrayDestroy(groupKeys);
X
Xiaoyu Wang 已提交
4220
      if (code) {
4221 4222 4223
        tsdbCleanupReadHandle(pDataReader);
        return NULL;
      }
4224

X
Xiaoyu Wang 已提交
4225
      SOperatorInfo* pOperator = createStreamScanOperatorInfo(pDataReader, pHandle, pTableScanNode, pTaskInfo, &twSup);
4226

H
Haojun Liao 已提交
4227
      return pOperator;
H
Haojun Liao 已提交
4228
    } else if (QUERY_NODE_PHYSICAL_PLAN_SYSTABLE_SCAN == type) {
L
Liu Jicong 已提交
4229
      SSystemTableScanPhysiNode* pSysScanPhyNode = (SSystemTableScanPhysiNode*)pPhyNode;
4230
      return createSysTableScanOperatorInfo(pHandle, pSysScanPhyNode, pTaskInfo);
4231
    } else if (QUERY_NODE_PHYSICAL_PLAN_TAG_SCAN == type) {
X
Xiaoyu Wang 已提交
4232
      STagScanPhysiNode* pScanPhyNode = (STagScanPhysiNode*)pPhyNode;
4233

4234
      int32_t code = getTableList(pHandle->meta, pScanPhyNode, pTableListInfo, pScanPhyNode->node.pConditions);
4235
      if (code != TSDB_CODE_SUCCESS) {
4236
        pTaskInfo->code = terrno;
4237 4238 4239
        return NULL;
      }

4240
      return createTagScanOperatorInfo(pHandle, pScanPhyNode, pTableListInfo, pTaskInfo);
H
Haojun Liao 已提交
4241 4242
    } else {
      ASSERT(0);
H
Haojun Liao 已提交
4243 4244 4245
    }
  }

4246 4247
  int32_t num = 0;
  size_t  size = LIST_LENGTH(pPhyNode->pChildren);
H
Haojun Liao 已提交
4248

4249
  SOperatorInfo** ops = taosMemoryCalloc(size, POINTER_BYTES);
dengyihao's avatar
dengyihao 已提交
4250
  for (int32_t i = 0; i < size; ++i) {
4251
    SPhysiNode* pChildNode = (SPhysiNode*)nodesListGetNode(pPhyNode->pChildren, i);
wmmhello's avatar
wmmhello 已提交
4252
    ops[i] = createOperatorTree(pChildNode, pTaskInfo, pHandle, queryId, taskId, pTableListInfo, pTagCond);
4253 4254 4255
    if (ops[i] == NULL) {
      return NULL;
    }
4256
  }
H
Haojun Liao 已提交
4257

4258
  SOperatorInfo* pOptr = NULL;
H
Haojun Liao 已提交
4259
  if (QUERY_NODE_PHYSICAL_PLAN_PROJECT == type) {
4260
    pOptr = createProjectOperatorInfo(ops[0], (SProjectPhysiNode*)pPhyNode, pTaskInfo);
4261
  } else if (QUERY_NODE_PHYSICAL_PLAN_HASH_AGG == type) {
H
Haojun Liao 已提交
4262 4263
    SAggPhysiNode* pAggNode = (SAggPhysiNode*)pPhyNode;
    SExprInfo*     pExprInfo = createExprInfo(pAggNode->pAggFuncs, pAggNode->pGroupKeys, &num);
4264
    SSDataBlock*   pResBlock = createResDataBlock(pPhyNode->pOutputDataBlockDesc);
H
Haojun Liao 已提交
4265

dengyihao's avatar
dengyihao 已提交
4266
    int32_t    numOfScalarExpr = 0;
4267 4268 4269 4270 4271
    SExprInfo* pScalarExprInfo = NULL;
    if (pAggNode->pExprs != NULL) {
      pScalarExprInfo = createExprInfo(pAggNode->pExprs, NULL, &numOfScalarExpr);
    }

H
Haojun Liao 已提交
4272 4273
    if (pAggNode->pGroupKeys != NULL) {
      SArray* pColList = extractColumnInfo(pAggNode->pGroupKeys);
dengyihao's avatar
dengyihao 已提交
4274
      pOptr = createGroupOperatorInfo(ops[0], pExprInfo, num, pResBlock, pColList, pAggNode->node.pConditions,
wmmhello's avatar
wmmhello 已提交
4275
                                      pScalarExprInfo, numOfScalarExpr, pTaskInfo);
H
Haojun Liao 已提交
4276
    } else {
dengyihao's avatar
dengyihao 已提交
4277 4278
      pOptr =
          createAggregateOperatorInfo(ops[0], pExprInfo, num, pResBlock, pScalarExprInfo, numOfScalarExpr, pTaskInfo);
H
Haojun Liao 已提交
4279
    }
X
Xiaoyu Wang 已提交
4280
  } else if (QUERY_NODE_PHYSICAL_PLAN_HASH_INTERVAL == type || QUERY_NODE_PHYSICAL_PLAN_STREAM_INTERVAL == type) {
H
Haojun Liao 已提交
4281
    SIntervalPhysiNode* pIntervalPhyNode = (SIntervalPhysiNode*)pPhyNode;
H
Haojun Liao 已提交
4282

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

dengyihao's avatar
dengyihao 已提交
4286 4287 4288 4289 4290 4291
    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 已提交
4292

X
Xiaoyu Wang 已提交
4293 4294 4295 4296 4297
    STimeWindowAggSupp as = {
        .waterMark = pIntervalPhyNode->window.watermark,
        .calTrigger = pIntervalPhyNode->window.triggerType,
        .maxTs = INT64_MIN,
    };
4298
    ASSERT(as.calTrigger != STREAM_TRIGGER_MAX_DELAY);
4299

4300
    int32_t tsSlotId = ((SColumnNode*)pIntervalPhyNode->window.pTspk)->slotId;
L
Liu Jicong 已提交
4301 4302 4303
    bool    isStream = (QUERY_NODE_PHYSICAL_PLAN_STREAM_INTERVAL == type);
    pOptr =
        createIntervalOperatorInfo(ops[0], pExprInfo, num, pResBlock, &interval, tsSlotId, &as, pTaskInfo, isStream);
4304

S
shenglian zhou 已提交
4305
  } else if (QUERY_NODE_PHYSICAL_PLAN_MERGE_INTERVAL == type) {
X
Xiaoyu Wang 已提交
4306
    SMergeIntervalPhysiNode* pIntervalPhyNode = (SMergeIntervalPhysiNode*)pPhyNode;
S
shenglian zhou 已提交
4307 4308 4309 4310 4311 4312 4313 4314 4315 4316

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

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

S
shenglian zhou 已提交
4318 4319
    int32_t tsSlotId = ((SColumnNode*)pIntervalPhyNode->window.pTspk)->slotId;
    pOptr = createMergeIntervalOperatorInfo(ops[0], pExprInfo, num, pResBlock, &interval, tsSlotId, pTaskInfo);
5
54liuyao 已提交
4320
  } else if (QUERY_NODE_PHYSICAL_PLAN_STREAM_SEMI_INTERVAL == type) {
4321
    int32_t children = 0;
5
54liuyao 已提交
4322 4323
    pOptr = createStreamFinalIntervalOperatorInfo(ops[0], pPhyNode, pTaskInfo, children);
  } else if (QUERY_NODE_PHYSICAL_PLAN_STREAM_FINAL_INTERVAL == type) {
4324
    int32_t children = 1;
5
54liuyao 已提交
4325
    pOptr = createStreamFinalIntervalOperatorInfo(ops[0], pPhyNode, pTaskInfo, children);
H
Haojun Liao 已提交
4326
  } else if (QUERY_NODE_PHYSICAL_PLAN_SORT == type) {
4327
    pOptr = createSortOperatorInfo(ops[0], (SSortPhysiNode*)pPhyNode, pTaskInfo);
X
Xiaoyu Wang 已提交
4328
  } else if (QUERY_NODE_PHYSICAL_PLAN_MERGE == type) {
4329 4330 4331
    SMergePhysiNode* pMergePhyNode = (SMergePhysiNode*)pPhyNode;

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

X
Xiaoyu Wang 已提交
4334
    SArray* sortInfo = createSortInfo(pMergePhyNode->pMergeKeys);
4335
    int32_t numOfOutputCols = 0;
X
Xiaoyu Wang 已提交
4336
    SArray* pColList =
4337
        extractColMatchInfo(pMergePhyNode->pTargets, pDescNode, &numOfOutputCols, COL_MATCH_FROM_SLOT_ID);
S
shenglian zhou 已提交
4338
    SPhysiNode*  pChildNode = (SPhysiNode*)nodesListGetNode(pPhyNode->pChildren, 0);
4339 4340
    SSDataBlock* pInputDataBlock = createResDataBlock(pChildNode->pOutputDataBlockDesc);
    pOptr = createMultiwaySortMergeOperatorInfo(ops, size, pInputDataBlock, pResBlock, sortInfo, pColList, pTaskInfo);
4341
  } else if (QUERY_NODE_PHYSICAL_PLAN_MERGE_SESSION == type) {
H
Haojun Liao 已提交
4342 4343
    SSessionWinodwPhysiNode* pSessionNode = (SSessionWinodwPhysiNode*)pPhyNode;

X
Xiaoyu Wang 已提交
4344 4345
    STimeWindowAggSupp as = {.waterMark = pSessionNode->window.watermark,
                             .calTrigger = pSessionNode->window.triggerType};
4346

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

X
Xiaoyu Wang 已提交
4351 4352
    pOptr =
        createSessionAggOperatorInfo(ops[0], pExprInfo, num, pResBlock, pSessionNode->gap, tsSlotId, &as, pTaskInfo);
4353
  } else if (QUERY_NODE_PHYSICAL_PLAN_STREAM_SESSION == type) {
4354 4355 4356 4357 4358 4359 4360
    pOptr = createStreamSessionAggOperatorInfo(ops[0], pPhyNode, pTaskInfo);
  } else if (QUERY_NODE_PHYSICAL_PLAN_STREAM_SEMI_SESSION == type) {
    int32_t children = 0;
    pOptr = createStreamFinalSessionAggOperatorInfo(ops[0], pPhyNode, pTaskInfo, children);
  } else if (QUERY_NODE_PHYSICAL_PLAN_STREAM_FINAL_SESSION == type) {
    int32_t children = 1;
    pOptr = createStreamFinalSessionAggOperatorInfo(ops[0], pPhyNode, pTaskInfo, children);
H
Haojun Liao 已提交
4361
  } else if (QUERY_NODE_PHYSICAL_PLAN_PARTITION == type) {
4362
    pOptr = createPartitionOperatorInfo(ops[0], (SPartitionPhysiNode*)pPhyNode, pTaskInfo);
4363
  } else if (QUERY_NODE_PHYSICAL_PLAN_MERGE_STATE == type) {
dengyihao's avatar
dengyihao 已提交
4364
    SStateWinodwPhysiNode* pStateNode = (SStateWinodwPhysiNode*)pPhyNode;
4365

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

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

4372
    SColumnNode* pColNode = (SColumnNode*)((STargetNode*)pStateNode->pStateKey)->pExpr;
X
Xiaoyu Wang 已提交
4373
    SColumn      col = extractColumnFromColumnNode(pColNode);
4374
    pOptr = createStatewindowOperatorInfo(ops[0], pExprInfo, num, pResBlock, &as, tsSlotId, &col, pTaskInfo);
4375
  } else if (QUERY_NODE_PHYSICAL_PLAN_STREAM_STATE == type) {
5
54liuyao 已提交
4376
    pOptr = createStreamStateAggOperatorInfo(ops[0], pPhyNode, pTaskInfo);
4377
  } else if (QUERY_NODE_PHYSICAL_PLAN_MERGE_JOIN == type) {
4378
    pOptr = createMergeJoinOperatorInfo(ops, size, (SJoinPhysiNode*)pPhyNode, pTaskInfo);
4379
  } else if (QUERY_NODE_PHYSICAL_PLAN_FILL == type) {
4380
    pOptr = createFillOperatorInfo(ops[0], (SFillPhysiNode*)pPhyNode, false, pTaskInfo);
H
Haojun Liao 已提交
4381 4382
  } else if (QUERY_NODE_PHYSICAL_PLAN_INDEF_ROWS_FUNC == type) {
    pOptr = createIndefinitOutputOperatorInfo(ops[0], pPhyNode, pTaskInfo);
H
Haojun Liao 已提交
4383 4384
  } else {
    ASSERT(0);
H
Haojun Liao 已提交
4385
  }
4386 4387 4388

  taosMemoryFree(ops);
  return pOptr;
4389
}
H
Haojun Liao 已提交
4390

4391
int32_t compareTimeWindow(const void* p1, const void* p2, const void* param) {
dengyihao's avatar
dengyihao 已提交
4392 4393 4394
  const SQueryTableDataCond* pCond = param;
  const STimeWindow*         pWin1 = p1;
  const STimeWindow*         pWin2 = p2;
4395 4396 4397 4398 4399 4400 4401 4402
  if (pCond->order == TSDB_ORDER_ASC) {
    return pWin1->skey - pWin2->skey;
  } else if (pCond->order == TSDB_ORDER_DESC) {
    return pWin2->skey - pWin1->skey;
  }
  return 0;
}

H
Haojun Liao 已提交
4403
SArray* extractColumnInfo(SNodeList* pNodeList) {
L
Liu Jicong 已提交
4404
  size_t  numOfCols = LIST_LENGTH(pNodeList);
H
Haojun Liao 已提交
4405 4406 4407 4408 4409 4410
  SArray* pList = taosArrayInit(numOfCols, sizeof(SColumn));
  if (pList == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

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

4414 4415 4416
    if (nodeType(pNode->pExpr) == QUERY_NODE_COLUMN) {
      SColumnNode* pColNode = (SColumnNode*)pNode->pExpr;

4417
      SColumn c = extractColumnFromColumnNode(pColNode);
4418 4419
      taosArrayPush(pList, &c);
    } else if (nodeType(pNode->pExpr) == QUERY_NODE_VALUE) {
L
Liu Jicong 已提交
4420 4421
      SValueNode* pValNode = (SValueNode*)pNode->pExpr;
      SColumn     c = {0};
4422
      c.slotId = pNode->slotId;
L
Liu Jicong 已提交
4423
      c.colId = pNode->slotId;
4424
      c.type  = pValNode->node.type;
L
Liu Jicong 已提交
4425 4426
      c.bytes = pValNode->node.resType.bytes;
      c.scale = pValNode->node.resType.scale;
4427 4428 4429 4430
      c.precision = pValNode->node.resType.precision;

      taosArrayPush(pList, &c);
    }
H
Haojun Liao 已提交
4431 4432 4433 4434 4435
  }

  return pList;
}

L
Liu Jicong 已提交
4436
tsdbReaderT doCreateDataReader(STableScanPhysiNode* pTableScanNode, SReadHandle* pHandle,
wmmhello's avatar
wmmhello 已提交
4437
                               STableListInfo* pTableListInfo, uint64_t queryId, uint64_t taskId, SNode* pTagCond) {
dengyihao's avatar
dengyihao 已提交
4438
  int32_t code =
4439
      getTableList(pHandle->meta, &pTableScanNode->scan, pTableListInfo, pTagCond);
wmmhello's avatar
wmmhello 已提交
4440 4441 4442 4443 4444 4445 4446 4447 4448 4449
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }

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

4450
  SQueryTableDataCond cond = {0};
wmmhello's avatar
wmmhello 已提交
4451
  code = initQueryTableDataCond(&cond, pTableScanNode);
4452
  if (code != TSDB_CODE_SUCCESS) {
wmmhello's avatar
wmmhello 已提交
4453
    goto _error;
X
Xiaoyu Wang 已提交
4454
  }
4455

H
Haojun Liao 已提交
4456
  tsdbReaderT* pReader = tsdbReaderOpen(pHandle->vnode, &cond, pTableListInfo, queryId, taskId);
4457
  cleanupQueryTableDataCond(&cond);
H
Haojun Liao 已提交
4458 4459

  return pReader;
wmmhello's avatar
wmmhello 已提交
4460 4461 4462 4463

_error:
  terrno = code;
  return NULL;
H
Haojun Liao 已提交
4464 4465
}

4466
int32_t encodeOperator(SOperatorInfo* ops, char** result, int32_t* length) {
wmmhello's avatar
wmmhello 已提交
4467
  int32_t code = TDB_CODE_SUCCESS;
4468
  char*   pCurrent = NULL;
wmmhello's avatar
wmmhello 已提交
4469
  int32_t currLength = 0;
4470 4471
  if (ops->fpSet.encodeResultRow) {
    if (result == NULL || length == NULL) {
wmmhello's avatar
wmmhello 已提交
4472 4473 4474
      return TSDB_CODE_TSC_INVALID_INPUT;
    }
    code = ops->fpSet.encodeResultRow(ops, &pCurrent, &currLength);
wmmhello's avatar
wmmhello 已提交
4475

4476 4477
    if (code != TDB_CODE_SUCCESS) {
      if (*result != NULL) {
wmmhello's avatar
wmmhello 已提交
4478 4479 4480 4481 4482
        taosMemoryFree(*result);
        *result = NULL;
      }
      return code;
    }
wmmhello's avatar
wmmhello 已提交
4483

4484
    if (*result == NULL) {
wmmhello's avatar
wmmhello 已提交
4485
      *result = (char*)taosMemoryCalloc(1, currLength + sizeof(int32_t));
wmmhello's avatar
wmmhello 已提交
4486 4487 4488 4489 4490 4491
      if (*result == NULL) {
        taosMemoryFree(pCurrent);
        return TSDB_CODE_OUT_OF_MEMORY;
      }
      memcpy(*result + sizeof(int32_t), pCurrent, currLength);
      *(int32_t*)(*result) = currLength + sizeof(int32_t);
4492
    } else {
wmmhello's avatar
wmmhello 已提交
4493
      int32_t sizePre = *(int32_t*)(*result);
4494
      char*   tmp = (char*)taosMemoryRealloc(*result, sizePre + currLength);
wmmhello's avatar
wmmhello 已提交
4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506
      if (tmp == NULL) {
        taosMemoryFree(pCurrent);
        taosMemoryFree(*result);
        *result = NULL;
        return TSDB_CODE_OUT_OF_MEMORY;
      }
      *result = tmp;
      memcpy(*result + sizePre, pCurrent, currLength);
      *(int32_t*)(*result) += currLength;
    }
    taosMemoryFree(pCurrent);
    *length = *(int32_t*)(*result);
wmmhello's avatar
wmmhello 已提交
4507 4508
  }

wmmhello's avatar
wmmhello 已提交
4509 4510
  for (int32_t i = 0; i < ops->numOfDownstream; ++i) {
    code = encodeOperator(ops->pDownstream[i], result, length);
4511
    if (code != TDB_CODE_SUCCESS) {
wmmhello's avatar
wmmhello 已提交
4512
      return code;
wmmhello's avatar
wmmhello 已提交
4513 4514
    }
  }
wmmhello's avatar
wmmhello 已提交
4515
  return TDB_CODE_SUCCESS;
wmmhello's avatar
wmmhello 已提交
4516 4517
}

H
Haojun Liao 已提交
4518
int32_t decodeOperator(SOperatorInfo* ops, const char* result, int32_t length) {
wmmhello's avatar
wmmhello 已提交
4519
  int32_t code = TDB_CODE_SUCCESS;
4520 4521
  if (ops->fpSet.decodeResultRow) {
    if (result == NULL) {
wmmhello's avatar
wmmhello 已提交
4522 4523
      return TSDB_CODE_TSC_INVALID_INPUT;
    }
H
Haojun Liao 已提交
4524

4525
    ASSERT(length == *(int32_t*)result);
H
Haojun Liao 已提交
4526 4527 4528

    const char* data = result + sizeof(int32_t);
    code = ops->fpSet.decodeResultRow(ops, (char*) data);
4529
    if (code != TDB_CODE_SUCCESS) {
wmmhello's avatar
wmmhello 已提交
4530 4531
      return code;
    }
wmmhello's avatar
wmmhello 已提交
4532

wmmhello's avatar
wmmhello 已提交
4533
    int32_t totalLength = *(int32_t*)result;
4534 4535
    int32_t dataLength = *(int32_t*)data;

4536
    if (totalLength == dataLength + sizeof(int32_t)) {  // the last data
wmmhello's avatar
wmmhello 已提交
4537 4538
      result = NULL;
      length = 0;
4539
    } else {
wmmhello's avatar
wmmhello 已提交
4540 4541 4542 4543
      result += dataLength;
      *(int32_t*)(result) = totalLength - dataLength;
      length = totalLength - dataLength;
    }
wmmhello's avatar
wmmhello 已提交
4544 4545
  }

wmmhello's avatar
wmmhello 已提交
4546 4547
  for (int32_t i = 0; i < ops->numOfDownstream; ++i) {
    code = decodeOperator(ops->pDownstream[i], result, length);
4548
    if (code != TDB_CODE_SUCCESS) {
wmmhello's avatar
wmmhello 已提交
4549
      return code;
wmmhello's avatar
wmmhello 已提交
4550 4551
    }
  }
wmmhello's avatar
wmmhello 已提交
4552
  return TDB_CODE_SUCCESS;
wmmhello's avatar
wmmhello 已提交
4553 4554
}

4555
int32_t createDataSinkParam(SDataSinkNode* pNode, void** pParam, qTaskInfo_t* pTaskInfo) {
D
dapan1121 已提交
4556
  SExecTaskInfo* pTask = *(SExecTaskInfo**)pTaskInfo;
4557

D
dapan1121 已提交
4558 4559
  switch (pNode->type) {
    case QUERY_NODE_PHYSICAL_PLAN_DELETE: {
4560
      SDeleterParam* pDeleterParam = taosMemoryCalloc(1, sizeof(SDeleterParam));
D
dapan1121 已提交
4561 4562 4563 4564 4565 4566 4567 4568 4569 4570
      if (NULL == pDeleterParam) {
        return TSDB_CODE_OUT_OF_MEMORY;
      }
      int32_t tbNum = taosArrayGetSize(pTask->tableqinfoList.pTableList);
      pDeleterParam->pUidList = taosArrayInit(tbNum, sizeof(uint64_t));
      if (NULL == pDeleterParam->pUidList) {
        taosMemoryFree(pDeleterParam);
        return TSDB_CODE_OUT_OF_MEMORY;
      }
      for (int32_t i = 0; i < tbNum; ++i) {
4571
        STableKeyInfo* pTable = taosArrayGet(pTask->tableqinfoList.pTableList, i);
D
dapan1121 已提交
4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584
        taosArrayPush(pDeleterParam->pUidList, &pTable->uid);
      }

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

  return TSDB_CODE_SUCCESS;
}

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

H
Haojun Liao 已提交
4589
  int32_t code = TSDB_CODE_SUCCESS;
D
dapan1121 已提交
4590
  *pTaskInfo = createExecTaskInfo(queryId, taskId, model, pPlan->dbFName);
H
Haojun Liao 已提交
4591 4592 4593 4594
  if (*pTaskInfo == NULL) {
    code = TSDB_CODE_QRY_OUT_OF_MEMORY;
    goto _complete;
  }
H
Haojun Liao 已提交
4595

4596
  (*pTaskInfo)->sql = sql;
dengyihao's avatar
dengyihao 已提交
4597
  (*pTaskInfo)->pRoot = createOperatorTree(pPlan->pNode, *pTaskInfo, pHandle, queryId, taskId,
dengyihao's avatar
dengyihao 已提交
4598
                                           &(*pTaskInfo)->tableqinfoList, pPlan->pTagCond);
D
dapan1121 已提交
4599
  if (NULL == (*pTaskInfo)->pRoot) {
4600
    code = (*pTaskInfo)->code;
D
dapan1121 已提交
4601 4602
    goto _complete;
  }
H
Haojun Liao 已提交
4603

4604
  if ((*pTaskInfo)->pRoot == NULL) {
H
Haojun Liao 已提交
4605
    code = TSDB_CODE_QRY_OUT_OF_MEMORY;
H
Haojun Liao 已提交
4606
    goto _complete;
4607 4608
  }

H
Haojun Liao 已提交
4609 4610
  return code;

H
Haojun Liao 已提交
4611
_complete:
wafwerar's avatar
wafwerar 已提交
4612
  taosMemoryFreeClear(*pTaskInfo);
H
Haojun Liao 已提交
4613 4614
  terrno = code;
  return code;
H
Haojun Liao 已提交
4615 4616
}

wmmhello's avatar
wmmhello 已提交
4617 4618 4619
static void doDestroyTableList(STableListInfo* pTableqinfoList) {
  taosArrayDestroy(pTableqinfoList->pTableList);
  taosHashCleanup(pTableqinfoList->map);
4620

wmmhello's avatar
wmmhello 已提交
4621 4622
  pTableqinfoList->pTableList = NULL;
  pTableqinfoList->map = NULL;
4623 4624
}

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

wmmhello's avatar
wmmhello 已提交
4628
  doDestroyTableList(&pTaskInfo->tableqinfoList);
H
Haojun Liao 已提交
4629
  destroyOperatorInfo(pTaskInfo->pRoot);
L
Liu Jicong 已提交
4630 4631
  //  taosArrayDestroy(pTaskInfo->summary.queryProfEvents);
  //  taosHashCleanup(pTaskInfo->summary.operatorProfResults);
4632

4633 4634
  taosMemoryFree(pTaskInfo->schemaVer.dbname);
  taosMemoryFree(pTaskInfo->schemaVer.tablename);
wafwerar's avatar
wafwerar 已提交
4635 4636 4637
  taosMemoryFreeClear(pTaskInfo->sql);
  taosMemoryFreeClear(pTaskInfo->id.str);
  taosMemoryFreeClear(pTaskInfo);
4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649
}

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 已提交
4650
      int32_t len = (varDataLen(val) > maxLen) ? maxLen : varDataLen(val);
4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662
      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 已提交
4663 4664
  //  size_t s3 = sizeof(STableCheckInfo);  buffer consumption in tsdb
  return (int64_t)(s1 * 1.5 * numOfTables);
4665 4666 4667 4668 4669 4670 4671
}

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 已提交
4672
    while (1) {
4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698
      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 已提交
4699

dengyihao's avatar
dengyihao 已提交
4700 4701
int32_t getOperatorExplainExecInfo(SOperatorInfo* operatorInfo, SExplainExecInfo** pRes, int32_t* capacity,
                                   int32_t* resNum) {
D
dapan1121 已提交
4702 4703
  if (*resNum >= *capacity) {
    *capacity += 10;
dengyihao's avatar
dengyihao 已提交
4704

D
dapan1121 已提交
4705 4706
    *pRes = taosMemoryRealloc(*pRes, (*capacity) * sizeof(SExplainExecInfo));
    if (NULL == *pRes) {
D
dapan1121 已提交
4707
      qError("malloc %d failed", (*capacity) * (int32_t)sizeof(SExplainExecInfo));
D
dapan1121 已提交
4708 4709 4710 4711
      return TSDB_CODE_QRY_OUT_OF_MEMORY;
    }
  }

4712 4713 4714 4715 4716
  SExplainExecInfo* pInfo = &(*pRes)[*resNum];

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

4718
  if (operatorInfo->fpSet.getExplainFn) {
4719
    int32_t code = operatorInfo->fpSet.getExplainFn(operatorInfo, &pInfo->verboseInfo, &pInfo->verboseLen);
D
dapan1121 已提交
4720
    if (code) {
4721
      qError("%s operator getExplainFn failed, code:%s", GET_TASKID(operatorInfo->pTaskInfo), tstrerror(code));
D
dapan1121 已提交
4722 4723
      return code;
    }
4724 4725 4726
  } else {
    pInfo->verboseLen = 0;
    pInfo->verboseInfo = NULL;
D
dapan1121 已提交
4727
  }
dengyihao's avatar
dengyihao 已提交
4728

D
dapan1121 已提交
4729
  ++(*resNum);
dengyihao's avatar
dengyihao 已提交
4730

D
dapan1121 已提交
4731
  int32_t code = 0;
D
dapan1121 已提交
4732 4733
  for (int32_t i = 0; i < operatorInfo->numOfDownstream; ++i) {
    code = getOperatorExplainExecInfo(operatorInfo->pDownstream[i], pRes, capacity, resNum);
D
dapan1121 已提交
4734 4735 4736 4737 4738 4739 4740
    if (code) {
      taosMemoryFreeClear(*pRes);
      return TSDB_CODE_QRY_OUT_OF_MEMORY;
    }
  }

  return TSDB_CODE_SUCCESS;
D
dapan1121 已提交
4741
}
5
54liuyao 已提交
4742

L
Liu Jicong 已提交
4743
int32_t initStreamAggSupporter(SStreamAggSupporter* pSup, const char* pKey, SqlFunctionCtx* pCtx, int32_t numOfOutput,
4744
                               int32_t size) {
4745
  pSup->resultRowSize = getResultRowSize(pCtx, numOfOutput);
5
54liuyao 已提交
4746 4747
  pSup->keySize = sizeof(int64_t) + sizeof(TSKEY);
  pSup->pKeyBuf = taosMemoryCalloc(1, pSup->keySize);
4748 4749
  _hash_fn_t hashFn = taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY);
  pSup->pResultRows = taosHashInit(1024, hashFn, false, HASH_NO_LOCK);
5
54liuyao 已提交
4750 4751 4752
  if (pSup->pKeyBuf == NULL || pSup->pResultRows == NULL) {
    return TSDB_CODE_OUT_OF_MEMORY;
  }
4753
  pSup->valueSize = size;
5
54liuyao 已提交
4754

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

5
54liuyao 已提交
4757 4758 4759 4760 4761 4762 4763 4764 4765
  int32_t pageSize = 4096;
  while (pageSize < pSup->resultRowSize * 4) {
    pageSize <<= 1u;
  }
  // at least four pages need to be in buffer
  int32_t bufSize = 4096 * 256;
  if (bufSize <= pageSize) {
    bufSize = pageSize * 4;
  }
4766
  int32_t code = createDiskbasedBuf(&pSup->pResultBuf, pageSize, bufSize, pKey, TD_TMP_DIR_PATH);
L
Liu Jicong 已提交
4767
  for (int32_t i = 0; i < numOfOutput; ++i) {
4768 4769 4770
    pCtx[i].pBuf = pSup->pResultBuf;
  }
  return code;
5
54liuyao 已提交
4771
}