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

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

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

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

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

#define TSWINDOW_IS_EQUAL(t1, t2) (((t1).skey == (t2).skey) && ((t1).ekey == (t2).ekey))

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

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

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

typedef enum SResultTsInterpType {
  RESULT_ROW_START_INTERP = 1,
L
Liu Jicong 已提交
59
  RESULT_ROW_END_INTERP = 2,
60 61 62 63
} SResultTsInterpType;

#if 0
static UNUSED_FUNC void *u_malloc (size_t __size) {
wafwerar's avatar
wafwerar 已提交
64
  uint32_t v = taosRand();
65 66 67 68

  if (v % 1000 <= 0) {
    return NULL;
  } else {
wafwerar's avatar
wafwerar 已提交
69
    return taosMemoryMalloc(__size);
70 71 72 73
  }
}

static UNUSED_FUNC void* u_calloc(size_t num, size_t __size) {
wafwerar's avatar
wafwerar 已提交
74
  uint32_t v = taosRand();
75 76 77
  if (v % 1000 <= 0) {
    return NULL;
  } else {
wafwerar's avatar
wafwerar 已提交
78
    return taosMemoryCalloc(num, __size);
79 80 81 82
  }
}

static UNUSED_FUNC void* u_realloc(void* p, size_t __size) {
wafwerar's avatar
wafwerar 已提交
83
  uint32_t v = taosRand();
84 85 86
  if (v % 5 <= 1) {
    return NULL;
  } else {
wafwerar's avatar
wafwerar 已提交
87
    return taosMemoryRealloc(p, __size);
88 89 90 91 92 93 94 95 96 97 98 99
  }
}

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

#define CLEAR_QUERY_STATUS(q, st)   ((q)->status &= (~(st)))
#define GET_NUM_OF_TABLEGROUP(q)    taosArrayGetSize((q)->tableqinfoGroupInfo.pGroupList)
#define QUERY_IS_INTERVAL_QUERY(_q) ((_q)->interval.interval > 0)

L
Liu Jicong 已提交
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
#define TSKEY_MAX_ADD(a, b)                      \
  do {                                           \
    if (a < 0) {                                 \
      a = a + b;                                 \
      break;                                     \
    }                                            \
    if (sizeof(a) == sizeof(int32_t)) {          \
      if ((b) > 0 && ((b) >= INT32_MAX - (a))) { \
        a = INT32_MAX;                           \
      } else {                                   \
        a = a + b;                               \
      }                                          \
    } else {                                     \
      if ((b) > 0 && ((b) >= INT64_MAX - (a))) { \
        a = INT64_MAX;                           \
      } else {                                   \
        a = a + b;                               \
      }                                          \
    }                                            \
  } while (0)

#define TSKEY_MIN_SUB(a, b)                      \
  do {                                           \
    if (a >= 0) {                                \
      a = a + b;                                 \
      break;                                     \
    }                                            \
    if (sizeof(a) == sizeof(int32_t)) {          \
      if ((b) < 0 && ((b) <= INT32_MIN - (a))) { \
        a = INT32_MIN;                           \
      } else {                                   \
        a = a + b;                               \
      }                                          \
    } else {                                     \
      if ((b) < 0 && ((b) <= INT64_MIN - (a))) { \
        a = INT64_MIN;                           \
      } else {                                   \
        a = a + b;                               \
      }                                          \
    }                                            \
  } while (0)

int32_t getMaximumIdleDurationSec() { return tsShellActivityTimer * 2; }

static int32_t getExprFunctionId(SExprInfo* pExprInfo) {
145
  assert(pExprInfo != NULL && pExprInfo->pExpr != NULL && pExprInfo->pExpr->nodeType == TEXPR_UNARYEXPR_NODE);
146
  return 0;
147 148
}

H
Haojun Liao 已提交
149 150 151 152 153
static void getNextTimeWindow(SInterval* pInterval, int32_t precision, int32_t order, STimeWindow* tw) {
  int32_t factor = GET_FORWARD_DIRECTION_FACTOR(order);
  if (pInterval->intervalUnit != 'n' && pInterval->intervalUnit != 'y') {
    tw->skey += pInterval->sliding * factor;
    tw->ekey = tw->skey + pInterval->interval - 1;
154 155 156
    return;
  }

H
Haojun Liao 已提交
157
  int64_t key = tw->skey, interval = pInterval->interval;
L
Liu Jicong 已提交
158
  // convert key to second
H
Haojun Liao 已提交
159
  key = convertTimePrecision(key, precision, TSDB_TIME_PRECISION_MILLI) / 1000;
160

H
Haojun Liao 已提交
161
  if (pInterval->intervalUnit == 'y') {
162 163 164 165
    interval *= 12;
  }

  struct tm tm;
L
Liu Jicong 已提交
166
  time_t    t = (time_t)key;
wafwerar's avatar
wafwerar 已提交
167
  taosLocalTime(&t, &tm);
168 169 170 171

  int mon = (int)(tm.tm_year * 12 + tm.tm_mon + interval * factor);
  tm.tm_year = mon / 12;
  tm.tm_mon = mon % 12;
172
  tw->skey = convertTimePrecision((int64_t)taosMktime(&tm) * 1000L, TSDB_TIME_PRECISION_MILLI, precision);
173 174 175 176

  mon = (int)(mon + interval);
  tm.tm_year = mon / 12;
  tm.tm_mon = mon % 12;
177
  tw->ekey = convertTimePrecision((int64_t)taosMktime(&tm) * 1000L, TSDB_TIME_PRECISION_MILLI, precision);
178 179 180 181 182

  tw->ekey -= 1;
}

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

185
static void setBlockStatisInfo(SqlFunctionCtx* pCtx, SExprInfo* pExpr, SSDataBlock* pSDataBlock);
186

L
Liu Jicong 已提交
187
static void destroyTableQueryInfoImpl(STableQueryInfo* pTableQueryInfo);
188 189 190

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

L
Liu Jicong 已提交
191 192 193
static int32_t setTimestampListJoinInfo(STaskRuntimeEnv* pRuntimeEnv, SVariant* pTag, STableQueryInfo* pTableQueryInfo);
static void    releaseQueryBuf(size_t numOfTables);
static int32_t binarySearchForKey(char* pValue, int num, TSKEY key, int order);
194
// static SQueryTableDataCond createTsdbQueryCond(STaskAttr* pQueryAttr, STimeWindow* win);
195 196
static STableIdInfo createTableIdInfo(STableQueryInfo* pTableQueryInfo);

H
Haojun Liao 已提交
197
static int32_t getNumOfScanTimes(STaskAttr* pQueryAttr);
198 199 200 201 202 203 204 205 206

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

H
Haojun Liao 已提交
208
static void destroyIntervalOperatorInfo(void* param, int32_t numOfOutput);
H
Haojun Liao 已提交
209 210
static void destroyExchangeOperatorInfo(void* param, int32_t numOfOutput);

211
static void destroyOperatorInfo(SOperatorInfo* pOperator);
212
static void destroySysTableScannerOperatorInfo(void* param, int32_t numOfOutput);
213

214
void doSetOperatorCompleted(SOperatorInfo* pOperator) {
215
  pOperator->status = OP_EXEC_DONE;
H
Haojun Liao 已提交
216
  if (pOperator->pTaskInfo != NULL) {
217
    setTaskStatus(pOperator->pTaskInfo, TASK_COMPLETED);
218 219
  }
}
220

221 222 223
#define OPTR_IS_OPENED(_optr)  (((_optr)->status & OP_OPENED) == OP_OPENED)
#define OPTR_SET_OPENED(_optr) ((_optr)->status |= OP_OPENED)

H
Haojun Liao 已提交
224
int32_t operatorDummyOpenFn(SOperatorInfo* pOperator) {
225
  OPTR_SET_OPENED(pOperator);
H
Haojun Liao 已提交
226
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
227 228
}

229
SOperatorFpSet createOperatorFpSet(__optr_open_fn_t openFn, __optr_fn_t nextFn, __optr_fn_t streamFn,
L
Liu Jicong 已提交
230 231
                                   __optr_fn_t cleanup, __optr_close_fn_t closeFn, __optr_encode_fn_t encode,
                                   __optr_decode_fn_t decode, __optr_get_explain_fn_t explain) {
232 233 234 235 236 237 238 239 240 241 242 243 244 245
  SOperatorFpSet fpSet = {
      ._openFn = openFn,
      .getNextFn = nextFn,
      .getStreamResFn = streamFn,
      .cleanupFn = cleanup,
      .closeFn = closeFn,
      .encodeResultRow = encode,
      .decodeResultRow = decode,
      .getExplainFn = explain,
  };

  return fpSet;
}

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

dengyihao's avatar
dengyihao 已提交
248 249 250
static int32_t doCopyToSDataBlock(SSDataBlock* pBlock, SExprInfo* pExprInfo, SDiskbasedBuf* pBuf,
                                  SGroupResInfo* pGroupResInfo, int32_t orderType, int32_t* rowCellOffset,
                                  SqlFunctionCtx* pCtx);
H
Haojun Liao 已提交
251

252
static void initCtxOutputBuffer(SqlFunctionCtx* pCtx, int32_t size);
H
Haojun Liao 已提交
253
static void setResultBufSize(STaskAttr* pQueryAttr, SResultInfo* pResultInfo);
dengyihao's avatar
dengyihao 已提交
254 255
static void doSetTableGroupOutputBuf(SAggOperatorInfo* pAggInfo, int32_t numOfOutput, uint64_t groupId,
                                     SExecTaskInfo* pTaskInfo);
256

H
Haojun Liao 已提交
257
SArray* getOrderCheckColumns(STaskAttr* pQuery);
258 259

typedef struct SRowCompSupporter {
L
Liu Jicong 已提交
260 261 262
  STaskRuntimeEnv* pRuntimeEnv;
  int16_t          dataOffset;
  __compar_fn_t    comFunc;
263 264
} SRowCompSupporter;

L
Liu Jicong 已提交
265 266 267
static int compareRowData(const void* a, const void* b, const void* userData) {
  const SResultRow* pRow1 = (const SResultRow*)a;
  const SResultRow* pRow2 = (const SResultRow*)b;
268

L
Liu Jicong 已提交
269 270
  SRowCompSupporter* supporter = (SRowCompSupporter*)userData;
  STaskRuntimeEnv*   pRuntimeEnv = supporter->pRuntimeEnv;
271

L
Liu Jicong 已提交
272 273
  SFilePage* page1 = getBufPage(pRuntimeEnv->pResultBuf, pRow1->pageId);
  SFilePage* page2 = getBufPage(pRuntimeEnv->pResultBuf, pRow2->pageId);
274 275

  int16_t offset = supporter->dataOffset;
L
Liu Jicong 已提交
276 277
  char*   in1 = getPosInResultPage(pRuntimeEnv->pQueryAttr, page1, pRow1->offset, offset);
  char*   in2 = getPosInResultPage(pRuntimeEnv->pQueryAttr, page2, pRow2->offset, offset);
278 279 280 281

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

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

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

H
Haojun Liao 已提交
289
  pBlock->info.blockId = pNode->dataBlockId;
dengyihao's avatar
dengyihao 已提交
290
  pBlock->info.rowSize = pNode->totalRowSize;  // todo ??
H
Haojun Liao 已提交
291

L
Liu Jicong 已提交
292
  for (int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
293
    SColumnInfoData idata = {{0}};
L
Liu Jicong 已提交
294
    SSlotDescNode*  pDescNode = nodesListGetNode(pNode->pSlots, i);
H
Haojun Liao 已提交
295 296
    if (!pDescNode->output) {
      continue;
H
Haojun Liao 已提交
297
    }
H
Haojun Liao 已提交
298

dengyihao's avatar
dengyihao 已提交
299
    idata.info.type = pDescNode->dataType.type;
L
Liu Jicong 已提交
300 301
    idata.info.bytes = pDescNode->dataType.bytes;
    idata.info.scale = pDescNode->dataType.scale;
H
Haojun Liao 已提交
302
    idata.info.slotId = pDescNode->slotId;
H
Haojun Liao 已提交
303 304
    idata.info.precision = pDescNode->dataType.precision;

H
Hongze Cheng 已提交
305 306 307 308
    if (IS_VAR_DATA_TYPE(idata.info.type)) {
      pBlock->info.hasVarCol = true;
    }

H
Haojun Liao 已提交
309
    taosArrayPush(pBlock->pDataBlock, &idata);
H
Haojun Liao 已提交
310
  }
H
Haojun Liao 已提交
311

312
  pBlock->info.numOfCols = taosArrayGetSize(pBlock->pDataBlock);
H
Haojun Liao 已提交
313
  return pBlock;
H
Haojun Liao 已提交
314 315
}

L
Liu Jicong 已提交
316
static bool hasNull(SColumn* pColumn, SColumnDataAgg* pStatis) {
dengyihao's avatar
dengyihao 已提交
317 318
  if (TSDB_COL_IS_TAG(pColumn->flag) || TSDB_COL_IS_UD_COL(pColumn->flag) ||
      pColumn->colId == PRIMARYKEY_TIMESTAMP_COL_ID) {
319 320 321 322 323 324 325 326 327 328
    return false;
  }

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

  return true;
}

H
Haojun Liao 已提交
329
static void prepareResultListBuffer(SResultRowInfo* pResultRowInfo, jmp_buf env) {
330 331
  int64_t newCapacity = 0;

332 333 334 335 336 337 338 339 340 341 342
  // more than the capacity, reallocate the resources
  if (pResultRowInfo->size < pResultRowInfo->capacity) {
    return;
  }

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

343
  if (newCapacity <= pResultRowInfo->capacity) {
H
Haojun Liao 已提交
344 345 346
    newCapacity += 4;
  }

347 348 349 350 351 352
  char* p = taosMemoryRealloc(pResultRowInfo->pPosition, newCapacity * sizeof(SResultRowPosition));
  if (p == NULL) {
    longjmp(env, TSDB_CODE_OUT_OF_MEMORY);
  }

  pResultRowInfo->pPosition = (SResultRowPosition*)p;
353 354

  int32_t inc = (int32_t)newCapacity - pResultRowInfo->capacity;
wmmhello's avatar
wmmhello 已提交
355
  memset(&pResultRowInfo->pPosition[pResultRowInfo->capacity], 0, sizeof(SResultRowPosition) * inc);
356 357 358
  pResultRowInfo->capacity = (int32_t)newCapacity;
}

L
Liu Jicong 已提交
359 360
static bool chkResultRowFromKey(STaskRuntimeEnv* pRuntimeEnv, SResultRowInfo* pResultRowInfo, char* pData,
                                int16_t bytes, bool masterscan, uint64_t uid) {
361 362 363
  bool existed = false;
  SET_RES_WINDOW_KEY(pRuntimeEnv->keyBuf, pData, bytes, uid);

L
Liu Jicong 已提交
364 365
  SResultRow** p1 =
      (SResultRow**)taosHashGet(pRuntimeEnv->pResultRowHashTable, pRuntimeEnv->keyBuf, GET_RES_WINDOW_KEY_LEN(bytes));
366 367 368 369 370 371 372 373 374 375 376

  // 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 已提交
377
        //        existed = (pResultRowInfo->pResult[0] == (*p1));
378 379
      } else {  // check if current pResultRowInfo contains the existed pResultRow
        SET_RES_EXT_WINDOW_KEY(pRuntimeEnv->keyBuf, pData, bytes, uid, pResultRowInfo);
L
Liu Jicong 已提交
380 381
        int64_t* index =
            taosHashGet(pRuntimeEnv->pResultRowListSet, pRuntimeEnv->keyBuf, GET_RES_EXT_WINDOW_KEY_LEN(bytes));
382 383 384 385 386 387 388 389 390 391 392 393 394 395
        if (index != NULL) {
          existed = true;
        } else {
          existed = false;
        }
      }
    }

    return existed;
  }

  return p1 != NULL;
}

396
SResultRow* getNewResultRow_rv(SDiskbasedBuf* pResultBuf, int64_t tableGroupId, int32_t interBufSize) {
L
Liu Jicong 已提交
397
  SFilePage* pData = NULL;
398 399 400 401 402 403 404 405 406 407 408 409 410

  // 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 已提交
411
    if (pData->num + interBufSize > getBufPageSize(pResultBuf)) {
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
      // release current page first, and prepare the next one
      releaseBufPageInfo(pResultBuf, pi);

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

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

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

wmmhello's avatar
wmmhello 已提交
431
  pData->num += interBufSize;
432 433 434 435

  return pResultRow;
}

436 437 438 439 440 441 442
/**
 * the struct of key in hash table
 * +----------+---------------+
 * | group id |   key data    |
 * | 8 bytes  | actual length |
 * +----------+---------------+
 */
443
static SResultRow* doSetResultOutBufByKey(SDiskbasedBuf* pResultBuf, SResultRowInfo* pResultRowInfo, int64_t uid,
L
Liu Jicong 已提交
444 445
                                          char* pData, int16_t bytes, bool masterscan, uint64_t groupId,
                                          SExecTaskInfo* pTaskInfo, bool isIntervalQuery, SAggSupporter* pSup) {
446
  SET_RES_WINDOW_KEY(pSup->keyBuf, pData, bytes, groupId);
H
Haojun Liao 已提交
447

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

451 452
  SResultRow* pResult = NULL;

H
Haojun Liao 已提交
453 454
  // in case of repeat scan/reverse scan, no new time window added.
  if (isIntervalQuery) {
455 456
    if (masterscan && p1 != NULL) {  // the *p1 may be NULL in case of sliding+offset exists.
      pResult = getResultRowByPos(pResultBuf, p1);
H
Haojun Liao 已提交
457 458
    }
  } else {
dengyihao's avatar
dengyihao 已提交
459 460
    // In case of group by column query, the required SResultRow object must be existInCurrentResusltRowInfo in the
    // pResultRowInfo object.
H
Haojun Liao 已提交
461
    if (p1 != NULL) {
462
      pResult = getResultRowByPos(pResultBuf, p1);
H
Haojun Liao 已提交
463 464 465
    }
  }

L
Liu Jicong 已提交
466
  // 1. close current opened time window
467
  if (pResultRowInfo->cur.pageId != -1 && ((pResult == NULL) || (pResult->pageId != pResultRowInfo->cur.pageId &&
L
Liu Jicong 已提交
468
                                                                 pResult->offset != pResultRowInfo->cur.offset))) {
469 470 471 472 473 474 475 476 477 478 479 480 481
    // todo extract function
    SResultRowPosition pos = pResultRowInfo->cur;
    SFilePage*         pPage = getBufPage(pResultBuf, pos.pageId);
    SResultRow*        pRow = (SResultRow*)((char*)pPage + pos.offset);
    closeResultRow(pRow);
    releaseBufPage(pResultBuf, pPage);
  }

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

483 484
    // add a new result set for a new group
    SResultRowPosition pos = {.pageId = pResult->pageId, .offset = pResult->offset};
L
Liu Jicong 已提交
485 486
    taosHashPut(pSup->pResultRowHashTable, pSup->keyBuf, GET_RES_WINDOW_KEY_LEN(bytes), &pos,
                sizeof(SResultRowPosition));
H
Haojun Liao 已提交
487 488
  }

489 490 491 492 493
  // 2. set the new time window to be the new active time window
  pResultRowInfo->pPosition[pResultRowInfo->size++] =
      (SResultRowPosition){.pageId = pResult->pageId, .offset = pResult->offset};
  pResultRowInfo->cur = (SResultRowPosition){.pageId = pResult->pageId, .offset = pResult->offset};

H
Haojun Liao 已提交
494 495 496 497 498
  // too many time window in query
  if (pResultRowInfo->size > MAX_INTERVAL_TIME_WINDOW) {
    longjmp(pTaskInfo->env, TSDB_CODE_QRY_TOO_MANY_TIMEWINDOW);
  }

H
Haojun Liao 已提交
499
  return pResult;
H
Haojun Liao 已提交
500 501
}

dengyihao's avatar
dengyihao 已提交
502 503
static void getInitialStartTimeWindow(SInterval* pInterval, int32_t precision, TSKEY ts, STimeWindow* w,
                                      bool ascQuery) {
H
Haojun Liao 已提交
504
  if (ascQuery) {
505
    getAlignQueryTimeWindow(pInterval, precision, ts, w);
506 507
  } else {
    // the start position of the first time window in the endpoint that spreads beyond the queried last timestamp
508
    getAlignQueryTimeWindow(pInterval, precision, ts, w);
509 510

    int64_t key = w->skey;
L
Liu Jicong 已提交
511
    while (key < ts) {  // moving towards end
512
      key = taosTimeAdd(key, pInterval->sliding, pInterval->slidingUnit, precision);
513 514 515 516 517 518 519 520 521 522
      if (key >= ts) {
        break;
      }

      w->skey = key;
    }
  }
}

// get the correct time window according to the handled timestamp
dengyihao's avatar
dengyihao 已提交
523 524
static STimeWindow getActiveTimeWindow(SDiskbasedBuf* pBuf, SResultRowInfo* pResultRowInfo, int64_t ts,
                                       SInterval* pInterval, int32_t precision, STimeWindow* win) {
525 526
  STimeWindow w = {0};

527
  if (pResultRowInfo->cur.pageId == -1) {  // the first window, from the previous stored value
528
    getInitialStartTimeWindow(pInterval, precision, ts, &w, true);
529
    w.ekey = taosTimeAdd(w.skey, pInterval->interval, pInterval->intervalUnit, precision) - 1;
530
  } else {
531
    w = getResultRowByPos(pBuf, &pResultRowInfo->cur)->win;
532 533 534
  }

  if (w.skey > ts || w.ekey < ts) {
H
Haojun Liao 已提交
535 536 537
    if (pInterval->intervalUnit == 'n' || pInterval->intervalUnit == 'y') {
      w.skey = taosTimeTruncate(ts, pInterval, precision);
      w.ekey = taosTimeAdd(w.skey, pInterval->interval, pInterval->intervalUnit, precision) - 1;
538 539 540 541
    } else {
      int64_t st = w.skey;

      if (st > ts) {
H
Haojun Liao 已提交
542
        st -= ((st - ts + pInterval->sliding - 1) / pInterval->sliding) * pInterval->sliding;
543 544
      }

H
Haojun Liao 已提交
545
      int64_t et = st + pInterval->interval - 1;
546
      if (et < ts) {
H
Haojun Liao 已提交
547
        st += ((ts - et + pInterval->sliding - 1) / pInterval->sliding) * pInterval->sliding;
548 549 550
      }

      w.skey = st;
551
      w.ekey = taosTimeAdd(w.skey, pInterval->interval, pInterval->intervalUnit, precision) - 1;
552 553 554 555 556 557
    }
  }
  return w;
}

// get the correct time window according to the handled timestamp
L
Liu Jicong 已提交
558
static STimeWindow getCurrentActiveTimeWindow(SResultRowInfo* pResultRowInfo, int64_t ts, STaskAttr* pQueryAttr) {
559
  STimeWindow w = {0};
H
Haojun Liao 已提交
560
#if 0
L
Liu Jicong 已提交
561 562
  if (pResultRowInfo->curPos == -1) {  // the first window, from the previous stored value
                                       //    getInitialStartTimeWindow(pQueryAttr, ts, &w);
563 564

    if (pQueryAttr->interval.intervalUnit == 'n' || pQueryAttr->interval.intervalUnit == 'y') {
L
Liu Jicong 已提交
565 566 567
      w.ekey =
          taosTimeAdd(w.skey, pQueryAttr->interval.interval, pQueryAttr->interval.intervalUnit, pQueryAttr->precision) -
          1;
568 569 570 571
    } else {
      w.ekey = w.skey + pQueryAttr->interval.interval - 1;
    }
  } else {
H
Haojun Liao 已提交
572
    w = pRow->win;
573 574 575 576 577 578 579 580 581
  }

  /*
   * 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 已提交
582
#endif
583 584 585 586 587

  return w;
}

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

L
Liu Jicong 已提交
593
  SFilePage* pData = NULL;
594 595 596 597 598 599

  // 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 已提交
600
    pData = getNewBufPage(pResultBuf, tid, &pageId);
601
    pData->num = sizeof(SFilePage);
602 603
  } else {
    SPageInfo* pi = getLastPageInfo(list);
604
    pData = getBufPage(pResultBuf, getPageId(pi));
605
    pageId = getPageId(pi);
606

607
    if (pData->num + size > getBufPageSize(pResultBuf)) {
608
      // release current page first, and prepare the next one
609
      releaseBufPageInfo(pResultBuf, pi);
610

H
Haojun Liao 已提交
611
      pData = getNewBufPage(pResultBuf, tid, &pageId);
612
      if (pData != NULL) {
613
        pData->num = sizeof(SFilePage);
614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633
      }
    }
  }

  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 已提交
634 635 636
static bool chkWindowOutputBufByKey(STaskRuntimeEnv* pRuntimeEnv, SResultRowInfo* pResultRowInfo, STimeWindow* win,
                                    bool masterscan, SResultRow** pResult, int64_t groupId, SqlFunctionCtx* pCtx,
                                    int32_t numOfOutput, int32_t* rowCellInfoOffset) {
637
  assert(win->skey <= win->ekey);
L
Liu Jicong 已提交
638
  return chkResultRowFromKey(pRuntimeEnv, pResultRowInfo, (char*)&win->skey, TSDB_KEYSIZE, masterscan, groupId);
639 640
}

dengyihao's avatar
dengyihao 已提交
641 642
static void setResultRowOutputBufInitCtx_rv(SResultRow* pResult, SqlFunctionCtx* pCtx, int32_t numOfOutput,
                                            int32_t* rowCellInfoOffset);
H
Haojun Liao 已提交
643

L
Liu Jicong 已提交
644 645 646 647
static int32_t setResultOutputBufByKey_rv(SResultRowInfo* pResultRowInfo, int64_t id, STimeWindow* win, bool masterscan,
                                          SResultRow** pResult, int64_t tableGroupId, SqlFunctionCtx* pCtx,
                                          int32_t numOfOutput, int32_t* rowCellInfoOffset, SAggSupporter* pAggSup,
                                          SExecTaskInfo* pTaskInfo) {
H
Haojun Liao 已提交
648
  assert(win->skey <= win->ekey);
649
  SResultRow* pResultRow = doSetResultOutBufByKey(pAggSup->pResultBuf, pResultRowInfo, id, (char*)&win->skey,
L
Liu Jicong 已提交
650
                                                  TSDB_KEYSIZE, masterscan, tableGroupId, pTaskInfo, true, pAggSup);
H
Haojun Liao 已提交
651 652 653 654 655 656 657 658 659

  if (pResultRow == NULL) {
    *pResult = NULL;
    return TSDB_CODE_SUCCESS;
  }

  // set time window for current result
  pResultRow->win = (*win);
  *pResult = pResultRow;
H
Haojun Liao 已提交
660
  setResultRowOutputBufInitCtx_rv(pResultRow, pCtx, numOfOutput, rowCellInfoOffset);
H
Haojun Liao 已提交
661 662 663
  return TSDB_CODE_SUCCESS;
}

664 665 666 667 668
static void setResultRowInterpo(SResultRow* pResult, SResultTsInterpType type) {
  assert(pResult != NULL && (type == RESULT_ROW_START_INTERP || type == RESULT_ROW_END_INTERP));
  if (type == RESULT_ROW_START_INTERP) {
    pResult->startInterp = true;
  } else {
L
Liu Jicong 已提交
669
    pResult->endInterp = true;
670 671 672 673 674 675 676 677
  }
}

static bool resultRowInterpolated(SResultRow* pResult, SResultTsInterpType type) {
  assert(pResult != NULL && (type == RESULT_ROW_START_INTERP || type == RESULT_ROW_END_INTERP));
  if (type == RESULT_ROW_START_INTERP) {
    return pResult->startInterp == true;
  } else {
L
Liu Jicong 已提交
678
    return pResult->endInterp == true;
679 680 681
  }
}

L
Liu Jicong 已提交
682 683
static FORCE_INLINE int32_t getForwardStepsInBlock(int32_t numOfRows, __block_search_fn_t searchFn, TSKEY ekey,
                                                   int16_t pos, int16_t order, int64_t* pData) {
684 685 686
  int32_t forwardStep = 0;

  if (order == TSDB_ORDER_ASC) {
L
Liu Jicong 已提交
687
    int32_t end = searchFn((char*)&pData[pos], numOfRows - pos, ekey, order);
688 689 690 691 692 693 694 695
    if (end >= 0) {
      forwardStep = end;

      if (pData[end + pos] == ekey) {
        forwardStep += 1;
      }
    }
  } else {
L
Liu Jicong 已提交
696
    int32_t end = searchFn((char*)pData, pos + 1, ekey, order);
697 698 699 700 701 702 703 704 705 706 707 708 709
    if (end >= 0) {
      forwardStep = pos - end;

      if (pData[end] == ekey) {
        forwardStep += 1;
      }
    }
  }

  assert(forwardStep >= 0);
  return forwardStep;
}

dengyihao's avatar
dengyihao 已提交
710 711
static void doUpdateResultRowIndex(SResultRowInfo* pResultRowInfo, TSKEY lastKey, bool ascQuery,
                                   bool timeWindowInterpo) {
712
  int64_t skey = TSKEY_INITIAL_VAL;
H
Haojun Liao 已提交
713
#if 0
714 715
  int32_t i = 0;
  for (i = pResultRowInfo->size - 1; i >= 0; --i) {
L
Liu Jicong 已提交
716
    SResultRow* pResult = pResultRowInfo->pResult[i];
717 718 719 720 721 722
    if (pResult->closed) {
      break;
    }

    // new closed result rows
    if (timeWindowInterpo) {
L
Liu Jicong 已提交
723 724 725
      if (pResult->endInterp &&
          ((pResult->win.skey <= lastKey && ascQuery) || (pResult->win.skey >= lastKey && !ascQuery))) {
        if (i > 0) {  // the first time window, the startInterp is false.
726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744
          assert(pResult->startInterp);
        }

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

  // all result rows are closed, set the last one to be the skey
  if (skey == TSKEY_INITIAL_VAL) {
    if (pResultRowInfo->size == 0) {
L
Liu Jicong 已提交
745
      //      assert(pResultRowInfo->current == NULL);
746 747 748 749 750 751 752
      assert(pResultRowInfo->curPos == -1);
      pResultRowInfo->curPos = -1;
    } else {
      pResultRowInfo->curPos = pResultRowInfo->size - 1;
    }
  } else {
    for (i = pResultRowInfo->size - 1; i >= 0; --i) {
L
Liu Jicong 已提交
753
      SResultRow* pResult = pResultRowInfo->pResult[i];
754 755 756 757 758 759 760 761 762 763 764
      if (pResult->closed) {
        break;
      }
    }

    if (i == pResultRowInfo->size - 1) {
      pResultRowInfo->curPos = i;
    } else {
      pResultRowInfo->curPos = i + 1;  // current not closed result object
    }
  }
H
Haojun Liao 已提交
765
#endif
766
}
767
//
dengyihao's avatar
dengyihao 已提交
768
// static void updateResultRowInfoActiveIndex(SResultRowInfo* pResultRowInfo, const STimeWindow* pWin, TSKEY lastKey,
769 770 771 772 773 774 775 776 777
//                                           bool ascQuery, bool interp) {
//  if ((lastKey > pWin->ekey && ascQuery) || (lastKey < pWin->ekey && (!ascQuery))) {
//    closeAllResultRows(pResultRowInfo);
//    pResultRowInfo->curPos = pResultRowInfo->size - 1;
//  } else {
//    int32_t step = ascQuery ? 1 : -1;
//    doUpdateResultRowIndex(pResultRowInfo, lastKey - step, ascQuery, interp);
//  }
//}
778

L
Liu Jicong 已提交
779 780 781
static int32_t getNumOfRowsInTimeWindow(SDataBlockInfo* pDataBlockInfo, TSKEY* pPrimaryColumn, int32_t startPos,
                                        TSKEY ekey, __block_search_fn_t searchFn, STableQueryInfo* item,
                                        int32_t order) {
782 783
  assert(startPos >= 0 && startPos < pDataBlockInfo->rows);

L
Liu Jicong 已提交
784 785
  int32_t num = -1;
  int32_t step = GET_FORWARD_DIRECTION_FACTOR(order);
786

H
Haojun Liao 已提交
787
  if (order == TSDB_ORDER_ASC) {
788 789
    if (ekey < pDataBlockInfo->window.ekey && pPrimaryColumn) {
      num = getForwardStepsInBlock(pDataBlockInfo->rows, searchFn, ekey, startPos, order, pPrimaryColumn);
H
Haojun Liao 已提交
790
      if (item != NULL) {
791 792 793 794
        item->lastKey = pPrimaryColumn[startPos + (num - 1)] + step;
      }
    } else {
      num = pDataBlockInfo->rows - startPos;
H
Haojun Liao 已提交
795
      if (item != NULL) {
796 797 798 799 800 801
        item->lastKey = pDataBlockInfo->window.ekey + step;
      }
    }
  } else {  // desc
    if (ekey > pDataBlockInfo->window.skey && pPrimaryColumn) {
      num = getForwardStepsInBlock(pDataBlockInfo->rows, searchFn, ekey, startPos, order, pPrimaryColumn);
H
Haojun Liao 已提交
802
      if (item != NULL) {
803 804 805 806
        item->lastKey = pPrimaryColumn[startPos - (num - 1)] + step;
      }
    } else {
      num = startPos + 1;
H
Haojun Liao 已提交
807
      if (item != NULL) {
808 809 810 811 812 813 814 815 816
        item->lastKey = pDataBlockInfo->window.skey + step;
      }
    }
  }

  assert(num >= 0);
  return num;
}

817 818 819 820 821
//  query_range_start, query_range_end, window_duration, window_start, window_end
static void initExecTimeWindowInfo(SColumnInfoData* pColData, STimeWindow* pQueryWindow) {
  pColData->info.type = TSDB_DATA_TYPE_TIMESTAMP;
  pColData->info.bytes = sizeof(int64_t);

822
  colInfoDataEnsureCapacity(pColData, 0, 5);
823 824 825 826 827 828 829 830 831
  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);
}

832
static void updateTimeWindowInfo(SColumnInfoData* pColData, STimeWindow* pWin, bool includeEndpoint) {
833
  int64_t* ts = (int64_t*)pColData->pData;
dengyihao's avatar
dengyihao 已提交
834
  int32_t  delta = includeEndpoint ? 1 : 0;
835

836
  int64_t duration = pWin->ekey - pWin->skey + delta;
dengyihao's avatar
dengyihao 已提交
837 838 839
  ts[2] = duration;            // set the duration
  ts[3] = pWin->skey;          // window start key
  ts[4] = pWin->ekey + delta;  // window end key
840 841
}

dengyihao's avatar
dengyihao 已提交
842 843
void doApplyFunctions(SqlFunctionCtx* pCtx, STimeWindow* pWin, SColumnInfoData* pTimeWindowData, int32_t offset,
                      int32_t forwardStep, TSKEY* tsCol, int32_t numOfTotal, int32_t numOfOutput, int32_t order) {
844 845 846
  for (int32_t k = 0; k < numOfOutput; ++k) {
    pCtx[k].startTs = pWin->skey;

H
Haojun Liao 已提交
847
    // keep it temporarily
dengyihao's avatar
dengyihao 已提交
848 849
    bool    hasAgg = pCtx[k].input.colDataAggIsSet;
    int32_t numOfRows = pCtx[k].input.numOfRows;
H
Haojun Liao 已提交
850
    int32_t startOffset = pCtx[k].input.startRowIndex;
851

H
Haojun Liao 已提交
852
    int32_t pos = (order == TSDB_ORDER_ASC) ? offset : offset - (forwardStep - 1);
853 854
    pCtx[k].input.startRowIndex = pos;
    pCtx[k].input.numOfRows = forwardStep;
855 856

    if (tsCol != NULL) {
H
Haojun Liao 已提交
857
      pCtx[k].ptsList = tsCol;
858 859 860 861 862 863 864 865
    }

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

866 867
    if (fmIsWindowPseudoColumnFunc(pCtx[k].functionId)) {
      SResultRowEntryInfo* pEntryInfo = GET_RES_INFO(&pCtx[k]);
dengyihao's avatar
dengyihao 已提交
868
      char*                p = GET_ROWCELL_INTERBUF(pEntryInfo);
869

870
      SColumnInfoData idata = {0};
dengyihao's avatar
dengyihao 已提交
871
      idata.info.type = TSDB_DATA_TYPE_BIGINT;
872
      idata.info.bytes = tDataTypes[TSDB_DATA_TYPE_BIGINT].bytes;
dengyihao's avatar
dengyihao 已提交
873
      idata.pData = p;
874 875 876 877

      SScalarParam out = {.columnData = &idata};
      SScalarParam tw = {.numOfRows = 5, .columnData = pTimeWindowData};
      pCtx[k].sfp.process(&tw, 1, &out);
878 879 880 881
      pEntryInfo->numOfRes = 1;
      continue;
    }

H
Haojun Liao 已提交
882
    if (functionNeedToExecute(&pCtx[k])) {
883
      pCtx[k].fpSet.process(&pCtx[k]);
884 885 886
    }

    // restore it
887 888 889
    pCtx[k].input.colDataAggIsSet = hasAgg;
    pCtx[k].input.startRowIndex = startOffset;
    pCtx[k].input.numOfRows = numOfRows;
890 891 892
  }
}

H
Haojun Liao 已提交
893 894 895
static int32_t getNextQualifiedWindow(SInterval* pInterval, STimeWindow* pNext, SDataBlockInfo* pDataBlockInfo,
                                      TSKEY* primaryKeys, int32_t prevPosition, STableIntervalOperatorInfo* pInfo) {
  int32_t order = pInfo->order;
L
Liu Jicong 已提交
896
  bool    ascQuery = (order == TSDB_ORDER_ASC);
H
Haojun Liao 已提交
897

898
  int32_t precision = pInterval->precision;
H
Haojun Liao 已提交
899
  getNextTimeWindow(pInterval, precision, order, pNext);
900 901

  // next time window is not in current block
H
Haojun Liao 已提交
902 903
  if ((pNext->skey > pDataBlockInfo->window.ekey && order == TSDB_ORDER_ASC) ||
      (pNext->ekey < pDataBlockInfo->window.skey && order == TSDB_ORDER_DESC)) {
904 905 906
    return -1;
  }

L
Liu Jicong 已提交
907
  TSKEY   startKey = ascQuery ? pNext->skey : pNext->ekey;
908 909 910
  int32_t startPos = 0;

  // tumbling time window query, a special case of sliding time window query
H
Haojun Liao 已提交
911 912
  if (pInterval->sliding == pInterval->interval && prevPosition != -1) {
    int32_t factor = GET_FORWARD_DIRECTION_FACTOR(order);
913 914
    startPos = prevPosition + factor;
  } else {
H
Haojun Liao 已提交
915
    if (startKey <= pDataBlockInfo->window.skey && ascQuery) {
916
      startPos = 0;
H
Haojun Liao 已提交
917
    } else if (startKey >= pDataBlockInfo->window.ekey && !ascQuery) {
918 919
      startPos = pDataBlockInfo->rows - 1;
    } else {
L
Liu Jicong 已提交
920
      startPos = binarySearchForKey((char*)primaryKeys, pDataBlockInfo->rows, startKey, order);
921 922 923 924
    }
  }

  /* interp query with fill should not skip time window */
L
Liu Jicong 已提交
925 926 927
  //  if (pQueryAttr->pointInterpQuery && pQueryAttr->fillType != TSDB_FILL_NONE) {
  //    return startPos;
  //  }
928 929 930 931 932 933

  /*
   * This time window does not cover any data, try next time window,
   * this case may happen when the time window is too small
   */
  if (primaryKeys == NULL) {
H
Haojun Liao 已提交
934
    if (ascQuery) {
935 936 937 938 939
      assert(pDataBlockInfo->window.skey <= pNext->ekey);
    } else {
      assert(pDataBlockInfo->window.ekey >= pNext->skey);
    }
  } else {
H
Haojun Liao 已提交
940
    if (ascQuery && primaryKeys[startPos] > pNext->ekey) {
941
      TSKEY next = primaryKeys[startPos];
H
Haojun Liao 已提交
942 943 944
      if (pInterval->intervalUnit == 'n' || pInterval->intervalUnit == 'y') {
        pNext->skey = taosTimeTruncate(next, pInterval, precision);
        pNext->ekey = taosTimeAdd(pNext->skey, pInterval->interval, pInterval->intervalUnit, precision) - 1;
945
      } else {
L
Liu Jicong 已提交
946
        pNext->ekey += ((next - pNext->ekey + pInterval->sliding - 1) / pInterval->sliding) * pInterval->sliding;
H
Haojun Liao 已提交
947
        pNext->skey = pNext->ekey - pInterval->interval + 1;
948
      }
H
Haojun Liao 已提交
949
    } else if ((!ascQuery) && primaryKeys[startPos] < pNext->skey) {
950
      TSKEY next = primaryKeys[startPos];
H
Haojun Liao 已提交
951 952 953
      if (pInterval->intervalUnit == 'n' || pInterval->intervalUnit == 'y') {
        pNext->skey = taosTimeTruncate(next, pInterval, precision);
        pNext->ekey = taosTimeAdd(pNext->skey, pInterval->interval, pInterval->intervalUnit, precision) - 1;
954
      } else {
H
Haojun Liao 已提交
955 956
        pNext->skey -= ((pNext->skey - next + pInterval->sliding - 1) / pInterval->sliding) * pInterval->sliding;
        pNext->ekey = pNext->skey + pInterval->interval - 1;
957 958 959 960 961 962 963
      }
    }
  }

  return startPos;
}

L
Liu Jicong 已提交
964
static FORCE_INLINE TSKEY reviseWindowEkey(STaskAttr* pQueryAttr, STimeWindow* pWindow) {
dengyihao's avatar
dengyihao 已提交
965
  TSKEY   ekey = -1;
966 967
  int32_t order = TSDB_ORDER_ASC;
  if (order == TSDB_ORDER_ASC) {
968 969 970 971 972 973 974 975 976 977 978 979 980 981
    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;
}

H
Haojun Liao 已提交
982
static void setNotInterpoWindowKey(SqlFunctionCtx* pCtx, int32_t numOfOutput, int32_t type) {
983 984 985 986 987 988 989 990 991 992 993
  if (type == RESULT_ROW_START_INTERP) {
    for (int32_t k = 0; k < numOfOutput; ++k) {
      pCtx[k].start.key = INT64_MIN;
    }
  } else {
    for (int32_t k = 0; k < numOfOutput; ++k) {
      pCtx[k].end.key = INT64_MIN;
    }
  }
}

H
Haojun Liao 已提交
994
static void saveDataBlockLastRow(char** pRow, SArray* pDataBlock, int32_t rowIndex, int32_t numOfCols) {
995 996 997 998
  if (pDataBlock == NULL) {
    return;
  }

H
Haojun Liao 已提交
999
  for (int32_t k = 0; k < numOfCols; ++k) {
L
Liu Jicong 已提交
1000
    SColumnInfoData* pColInfo = taosArrayGet(pDataBlock, k);
H
Haojun Liao 已提交
1001
    memcpy(pRow[k], ((char*)pColInfo->pData) + (pColInfo->info.bytes * rowIndex), pColInfo->info.bytes);
1002 1003 1004
  }
}

H
Haojun Liao 已提交
1005
static TSKEY getStartTsKey(STimeWindow* win, const TSKEY* tsCols, int32_t rows, bool ascQuery) {
1006 1007
  TSKEY ts = TSKEY_INITIAL_VAL;
  if (tsCols == NULL) {
L
Liu Jicong 已提交
1008
    ts = ascQuery ? win->skey : win->ekey;
1009
  } else {
L
Liu Jicong 已提交
1010
    int32_t offset = ascQuery ? 0 : rows - 1;
1011 1012 1013 1014 1015 1016
    ts = tsCols[offset];
  }

  return ts;
}

dengyihao's avatar
dengyihao 已提交
1017 1018
static int32_t doSetInputDataBlock(SOperatorInfo* pOperator, SqlFunctionCtx* pCtx, SSDataBlock* pBlock, int32_t order,
                                   bool createDummyCol);
1019

dengyihao's avatar
dengyihao 已提交
1020 1021
static void doSetInputDataBlockInfo(SOperatorInfo* pOperator, SqlFunctionCtx* pCtx, SSDataBlock* pBlock,
                                    int32_t order) {
1022 1023
  for (int32_t i = 0; i < pOperator->numOfOutput; ++i) {
    pCtx[i].order = order;
L
Liu Jicong 已提交
1024
    pCtx[i].size = pBlock->info.rows;
1025
    setBlockStatisInfo(&pCtx[i], &pOperator->pExpr[i], pBlock);
1026 1027 1028
  }
}

dengyihao's avatar
dengyihao 已提交
1029 1030
void setInputDataBlock(SOperatorInfo* pOperator, SqlFunctionCtx* pCtx, SSDataBlock* pBlock, int32_t order,
                       bool createDummyCol) {
1031
  if (pBlock->pBlockAgg != NULL) {
H
Haojun Liao 已提交
1032
    doSetInputDataBlockInfo(pOperator, pCtx, pBlock, order);
1033
  } else {
1034
    doSetInputDataBlock(pOperator, pCtx, pBlock, order, createDummyCol);
H
Haojun Liao 已提交
1035
  }
1036 1037
}

L
Liu Jicong 已提交
1038 1039
static int32_t doCreateConstantValColumnInfo(SInputColumnInfoData* pInput, SFunctParam* pFuncParam, int32_t paramIndex,
                                             int32_t numOfRows) {
1040 1041 1042 1043 1044 1045 1046 1047
  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)
1048 1049
    pColInfo->info.type = pFuncParam->param.nType;
    pColInfo->info.bytes = pFuncParam->param.nLen;
1050 1051

    pInput->pData[paramIndex] = pColInfo;
1052 1053
  } else {
    pColInfo = pInput->pData[paramIndex];
1054 1055
  }

1056
  colInfoDataEnsureCapacity(pColInfo, 0, numOfRows);
1057

1058
  int8_t type = pFuncParam->param.nType;
1059 1060
  if (type == TSDB_DATA_TYPE_BIGINT || type == TSDB_DATA_TYPE_UBIGINT) {
    int64_t v = pFuncParam->param.i;
dengyihao's avatar
dengyihao 已提交
1061
    for (int32_t i = 0; i < numOfRows; ++i) {
1062 1063 1064 1065
      colDataAppendInt64(pColInfo, i, &v);
    }
  } else if (type == TSDB_DATA_TYPE_DOUBLE) {
    double v = pFuncParam->param.d;
dengyihao's avatar
dengyihao 已提交
1066
    for (int32_t i = 0; i < numOfRows; ++i) {
1067 1068
      colDataAppendDouble(pColInfo, i, &v);
    }
1069
  } else if (type == TSDB_DATA_TYPE_VARCHAR) {
L
Liu Jicong 已提交
1070
    char* tmp = taosMemoryMalloc(pFuncParam->param.nLen + VARSTR_HEADER_SIZE);
1071
    STR_WITH_SIZE_TO_VARSTR(tmp, pFuncParam->param.pz, pFuncParam->param.nLen);
L
Liu Jicong 已提交
1072
    for (int32_t i = 0; i < numOfRows; ++i) {
1073 1074
      colDataAppend(pColInfo, i, tmp, false);
    }
1075 1076 1077 1078 1079
  }

  return TSDB_CODE_SUCCESS;
}

dengyihao's avatar
dengyihao 已提交
1080 1081
static int32_t doSetInputDataBlock(SOperatorInfo* pOperator, SqlFunctionCtx* pCtx, SSDataBlock* pBlock, int32_t order,
                                   bool createDummyCol) {
1082 1083
  int32_t code = TSDB_CODE_SUCCESS;

1084
  for (int32_t i = 0; i < pOperator->numOfOutput; ++i) {
L
Liu Jicong 已提交
1085 1086 1087
    pCtx[i].order = order;
    pCtx[i].size = pBlock->info.rows;
    pCtx[i].pSrcBlock = pBlock;
H
Haojun Liao 已提交
1088 1089
    pCtx[i].currentStage = MAIN_SCAN;

1090
    SInputColumnInfoData* pInput = &pCtx[i].input;
1091
    pInput->uid = pBlock->info.uid;
C
Cary Xu 已提交
1092
    pInput->colDataAggIsSet = false;
1093

1094 1095
    SExprInfo* pOneExpr = &pOperator->pExpr[i];
    for (int32_t j = 0; j < pOneExpr->base.numOfParams; ++j) {
dengyihao's avatar
dengyihao 已提交
1096
      SFunctParam* pFuncParam = &pOneExpr->base.pParam[j];
G
Ganlin Zhao 已提交
1097 1098
      if (pFuncParam->type == FUNC_PARAM_TYPE_COLUMN) {
        int32_t slotId = pFuncParam->pCol->slotId;
dengyihao's avatar
dengyihao 已提交
1099
        pInput->pData[j] = taosArrayGet(pBlock->pDataBlock, slotId);
1100 1101 1102
        pInput->totalRows = pBlock->info.rows;
        pInput->numOfRows = pBlock->info.rows;
        pInput->startRowIndex = 0;
1103

dengyihao's avatar
dengyihao 已提交
1104
        pInput->pPTS = taosArrayGet(pBlock->pDataBlock, 0);  // todo set the correct timestamp column
1105 1106
        ASSERT(pInput->pData[j] != NULL);
      } else if (pFuncParam->type == FUNC_PARAM_TYPE_VALUE) {
1107 1108 1109
        // 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) {
1110 1111 1112 1113
          pInput->totalRows = pBlock->info.rows;
          pInput->numOfRows = pBlock->info.rows;
          pInput->startRowIndex = 0;

1114
          code = doCreateConstantValColumnInfo(pInput, pFuncParam, j, pBlock->info.rows);
1115 1116 1117
          if (code != TSDB_CODE_SUCCESS) {
            return code;
          }
1118
        }
G
Ganlin Zhao 已提交
1119 1120
      }
    }
H
Haojun Liao 已提交
1121

H
Haojun Liao 已提交
1122
    //    setBlockStatisInfo(&pCtx[i], pBlock, pOperator->pExpr[i].base.pColumns);
H
Haojun Liao 已提交
1123 1124 1125 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
    //      uint32_t flag = pOperator->pExpr[i].base.pParam[0].pCol->flag;
    //      if (TSDB_COL_IS_NORMAL_COL(flag) /*|| (pCtx[i].functionId == FUNCTION_BLKINFO) ||
    //          (TSDB_COL_IS_TAG(flag) && pOperator->pRuntimeEnv->scanFlag == MERGE_STAGE)*/) {

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

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

  return code;
H
Haojun Liao 已提交
1163 1164 1165
}

static void doAggregateImpl(SOperatorInfo* pOperator, TSKEY startTs, SqlFunctionCtx* pCtx) {
1166
  for (int32_t k = 0; k < pOperator->numOfOutput; ++k) {
H
Haojun Liao 已提交
1167
    if (functionNeedToExecute(&pCtx[k])) {
L
Liu Jicong 已提交
1168
      pCtx[k].startTs = startTs;  // this can be set during create the struct
H
Haojun Liao 已提交
1169
      pCtx[k].fpSet.process(&pCtx[k]);
1170 1171 1172 1173
    }
  }
}

H
Haojun Liao 已提交
1174
static void setPseudoOutputColInfo(SSDataBlock* pResult, SqlFunctionCtx* pCtx, SArray* pPseudoList) {
dengyihao's avatar
dengyihao 已提交
1175
  size_t num = (pPseudoList != NULL) ? taosArrayGetSize(pPseudoList) : 0;
H
Haojun Liao 已提交
1176 1177 1178 1179 1180
  for (int32_t i = 0; i < num; ++i) {
    pCtx[i].pOutput = taosArrayGet(pResult->pDataBlock, i);
  }
}

dengyihao's avatar
dengyihao 已提交
1181 1182
void projectApplyFunctions(SExprInfo* pExpr, SSDataBlock* pResult, SSDataBlock* pSrcBlock, SqlFunctionCtx* pCtx,
                           int32_t numOfOutput, SArray* pPseudoList) {
H
Haojun Liao 已提交
1183
  setPseudoOutputColInfo(pResult, pCtx, pPseudoList);
H
Haojun Liao 已提交
1184
  pResult->info.groupId = pSrcBlock->info.groupId;
H
Haojun Liao 已提交
1185

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

1190 1191
  int32_t numOfRows = 0;

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

L
Liu Jicong 已提交
1196
    if (pExpr[k].pExpr->nodeType == QUERY_NODE_COLUMN) {  // it is a project query
1197
      SColumnInfoData* pColInfoData = taosArrayGet(pResult->pDataBlock, outputSlotId);
1198
      if (pResult->info.rows > 0 && !createNewColModel) {
1199 1200 1201 1202
        colDataMergeCol(pColInfoData, pResult->info.rows, pfCtx->input.pData[0], pfCtx->input.numOfRows);
      } else {
        colDataAssign(pColInfoData, pfCtx->input.pData[0], pfCtx->input.numOfRows);
      }
1203

1204
      numOfRows = pfCtx->input.numOfRows;
1205
    } else if (pExpr[k].pExpr->nodeType == QUERY_NODE_VALUE) {
1206
      SColumnInfoData* pColInfoData = taosArrayGet(pResult->pDataBlock, outputSlotId);
1207

dengyihao's avatar
dengyihao 已提交
1208
      int32_t offset = createNewColModel ? 0 : pResult->info.rows;
1209
      for (int32_t i = 0; i < pSrcBlock->info.rows; ++i) {
dengyihao's avatar
dengyihao 已提交
1210 1211 1212
        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);
1213
      }
1214 1215

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

1220
      SColumnInfoData* pResColData = taosArrayGet(pResult->pDataBlock, outputSlotId);
dengyihao's avatar
dengyihao 已提交
1221
      SColumnInfoData  idata = {.info = pResColData->info};
1222

1223
      SScalarParam dest = {.columnData = &idata};
1224 1225
      scalarCalculate(pExpr[k].pExpr->_optrRoot.pRootNode, pBlockList, &dest);

dengyihao's avatar
dengyihao 已提交
1226
      int32_t startOffset = createNewColModel ? 0 : pResult->info.rows;
1227
      colDataMergeCol(pResColData, startOffset, &idata, dest.numOfRows);
1228 1229

      numOfRows = dest.numOfRows;
1230 1231
      taosArrayDestroy(pBlockList);
    } else if (pExpr[k].pExpr->nodeType == QUERY_NODE_FUNCTION) {
1232
      ASSERT(!fmIsAggFunc(pfCtx->functionId));
1233

1234
      if (fmIsPseudoColumnFunc(pfCtx->functionId)) {
H
Haojun Liao 已提交
1235
        // do nothing
1236
      } else if (fmIsNonstandardSQLFunc(pfCtx->functionId)) {
H
Haojun Liao 已提交
1237
        // todo set the correct timestamp column
1238
        pfCtx->input.pPTS = taosArrayGet(pSrcBlock->pDataBlock, 1);
1239

dengyihao's avatar
dengyihao 已提交
1240
        SResultRowEntryInfo* pResInfo = GET_RES_INFO(&pCtx[k]);
1241
        pfCtx->fpSet.init(&pCtx[k], pResInfo);
1242

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

1246
        // set the timestamp(_rowts) output buffer
1247 1248
        if (taosArrayGetSize(pPseudoList) > 0) {
          int32_t* outputColIndex = taosArrayGet(pPseudoList, 0);
1249
          pfCtx->pTsOutput = (SColumnInfoData*)pCtx[*outputColIndex].pOutput;
1250
        }
H
Haojun Liao 已提交
1251

1252
        numOfRows = pfCtx->fpSet.process(pfCtx);
H
Haojun Liao 已提交
1253 1254 1255
      } else {
        SArray* pBlockList = taosArrayInit(4, POINTER_BYTES);
        taosArrayPush(pBlockList, &pSrcBlock);
G
Ganlin Zhao 已提交
1256

1257
        SColumnInfoData* pResColData = taosArrayGet(pResult->pDataBlock, outputSlotId);
dengyihao's avatar
dengyihao 已提交
1258
        SColumnInfoData  idata = {.info = pResColData->info};
H
Haojun Liao 已提交
1259

1260
        SScalarParam dest = {.columnData = &idata};
H
Haojun Liao 已提交
1261
        scalarCalculate((SNode*)pExpr[k].pExpr->_function.pFunctNode, pBlockList, &dest);
1262

dengyihao's avatar
dengyihao 已提交
1263
        int32_t startOffset = createNewColModel ? 0 : pResult->info.rows;
1264
        colDataMergeCol(pResColData, startOffset, &idata, dest.numOfRows);
1265 1266

        numOfRows = dest.numOfRows;
H
Haojun Liao 已提交
1267 1268
        taosArrayDestroy(pBlockList);
      }
1269
    } else {
1270
      ASSERT(0);
1271 1272
    }
  }
1273

1274 1275 1276
  if (!createNewColModel) {
    pResult->info.rows += numOfRows;
  }
1277 1278 1279 1280
}

void doTimeWindowInterpolation(SOperatorInfo* pOperator, SOptrBasicInfo* pInfo, SArray* pDataBlock, TSKEY prevTs,
                               int32_t prevRowIndex, TSKEY curTs, int32_t curRowIndex, TSKEY windowKey, int32_t type) {
dengyihao's avatar
dengyihao 已提交
1281
  SExprInfo* pExpr = pOperator->pExpr;
1282

H
Haojun Liao 已提交
1283
  SqlFunctionCtx* pCtx = pInfo->pCtx;
1284 1285 1286 1287 1288 1289 1290 1291

  for (int32_t k = 0; k < pOperator->numOfOutput; ++k) {
    int32_t functionId = pCtx[k].functionId;
    if (functionId != FUNCTION_TWA && functionId != FUNCTION_INTERP) {
      pCtx[k].start.key = INT64_MIN;
      continue;
    }

L
Liu Jicong 已提交
1292
    SColIndex*       pColIndex = NULL /*&pExpr[k].base.colInfo*/;
1293
    int16_t          index = pColIndex->colIndex;
L
Liu Jicong 已提交
1294
    SColumnInfoData* pColInfo = taosArrayGet(pDataBlock, index);
1295

L
Liu Jicong 已提交
1296
    //    assert(pColInfo->info.colId == pColIndex->info.colId && curTs != windowKey);
1297 1298 1299
    double v1 = 0, v2 = 0, v = 0;

    if (prevRowIndex == -1) {
dengyihao's avatar
dengyihao 已提交
1300
      //      GET_TYPED_DATA(v1, double, pColInfo->info.type, (char*)pRuntimeEnv->prevRow[index]);
1301
    } else {
L
Liu Jicong 已提交
1302
      GET_TYPED_DATA(v1, double, pColInfo->info.type, (char*)pColInfo->pData + prevRowIndex * pColInfo->info.bytes);
1303 1304
    }

L
Liu Jicong 已提交
1305
    GET_TYPED_DATA(v2, double, pColInfo->info.type, (char*)pColInfo->pData + curRowIndex * pColInfo->info.bytes);
1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316

    if (functionId == FUNCTION_INTERP) {
      if (type == RESULT_ROW_START_INTERP) {
        pCtx[k].start.key = prevTs;
        pCtx[k].start.val = v1;

        pCtx[k].end.key = curTs;
        pCtx[k].end.val = v2;

        if (pColInfo->info.type == TSDB_DATA_TYPE_BINARY || pColInfo->info.type == TSDB_DATA_TYPE_NCHAR) {
          if (prevRowIndex == -1) {
dengyihao's avatar
dengyihao 已提交
1317
            //            pCtx[k].start.ptr = (char*)pRuntimeEnv->prevRow[index];
1318
          } else {
L
Liu Jicong 已提交
1319
            pCtx[k].start.ptr = (char*)pColInfo->pData + prevRowIndex * pColInfo->info.bytes;
1320 1321
          }

L
Liu Jicong 已提交
1322
          pCtx[k].end.ptr = (char*)pColInfo->pData + curRowIndex * pColInfo->info.bytes;
1323 1324 1325
        }
      }
    } else if (functionId == FUNCTION_TWA) {
L
Liu Jicong 已提交
1326 1327 1328
      SPoint point1 = (SPoint){.key = prevTs, .val = &v1};
      SPoint point2 = (SPoint){.key = curTs, .val = &v2};
      SPoint point = (SPoint){.key = windowKey, .val = &v};
1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342

      taosGetLinearInterpolationVal(&point, TSDB_DATA_TYPE_DOUBLE, &point1, &point2, TSDB_DATA_TYPE_DOUBLE);

      if (type == RESULT_ROW_START_INTERP) {
        pCtx[k].start.key = point.key;
        pCtx[k].start.val = v;
      } else {
        pCtx[k].end.key = point.key;
        pCtx[k].end.val = v;
      }
    }
  }
}

H
Haojun Liao 已提交
1343
static bool setTimeWindowInterpolationStartTs(SOperatorInfo* pOperatorInfo, SqlFunctionCtx* pCtx, int32_t pos,
dengyihao's avatar
dengyihao 已提交
1344 1345
                                              int32_t numOfRows, SArray* pDataBlock, const TSKEY* tsCols,
                                              STimeWindow* win) {
H
Haojun Liao 已提交
1346
  bool  ascQuery = true;
L
Liu Jicong 已提交
1347
  TSKEY curTs = tsCols[pos];
dengyihao's avatar
dengyihao 已提交
1348
  TSKEY lastTs = 0;  //*(TSKEY*)pRuntimeEnv->prevRow[0];
1349 1350 1351

  // lastTs == INT64_MIN and pos == 0 means this is the first time window, interpolation is not needed.
  // start exactly from this point, no need to do interpolation
L
Liu Jicong 已提交
1352
  TSKEY key = ascQuery ? win->skey : win->ekey;
1353 1354 1355 1356 1357 1358 1359 1360 1361 1362
  if (key == curTs) {
    setNotInterpoWindowKey(pCtx, pOperatorInfo->numOfOutput, RESULT_ROW_START_INTERP);
    return true;
  }

  if (lastTs == INT64_MIN && ((pos == 0 && ascQuery) || (pos == (numOfRows - 1) && !ascQuery))) {
    setNotInterpoWindowKey(pCtx, pOperatorInfo->numOfOutput, RESULT_ROW_START_INTERP);
    return true;
  }

dengyihao's avatar
dengyihao 已提交
1363
  int32_t step = 1;  // GET_FORWARD_DIRECTION_FACTOR(pQueryAttr->order.order);
L
Liu Jicong 已提交
1364
  TSKEY   prevTs = ((pos == 0 && ascQuery) || (pos == (numOfRows - 1) && !ascQuery)) ? lastTs : tsCols[pos - step];
1365

dengyihao's avatar
dengyihao 已提交
1366 1367
  doTimeWindowInterpolation(pOperatorInfo, pOperatorInfo->info, pDataBlock, prevTs, pos - step, curTs, pos, key,
                            RESULT_ROW_START_INTERP);
1368 1369 1370
  return true;
}

L
Liu Jicong 已提交
1371 1372 1373
static bool setTimeWindowInterpolationEndTs(SOperatorInfo* pOperatorInfo, SqlFunctionCtx* pCtx, int32_t endRowIndex,
                                            SArray* pDataBlock, const TSKEY* tsCols, TSKEY blockEkey,
                                            STimeWindow* win) {
H
Haojun Liao 已提交
1374 1375
  int32_t order = TSDB_ORDER_ASC;
  int32_t numOfOutput = pOperatorInfo->numOfOutput;
1376

L
Liu Jicong 已提交
1377
  TSKEY actualEndKey = tsCols[endRowIndex];
H
Haojun Liao 已提交
1378
  TSKEY key = order ? win->ekey : win->skey;
1379 1380

  // not ended in current data block, do not invoke interpolation
dengyihao's avatar
dengyihao 已提交
1381 1382
  if ((key > blockEkey /*&& QUERY_IS_ASC_QUERY(pQueryAttr)*/) ||
      (key < blockEkey /*&& !QUERY_IS_ASC_QUERY(pQueryAttr)*/)) {
1383 1384 1385 1386 1387 1388 1389 1390 1391 1392
    setNotInterpoWindowKey(pCtx, numOfOutput, RESULT_ROW_END_INTERP);
    return false;
  }

  // there is actual end point of current time window, no interpolation need
  if (key == actualEndKey) {
    setNotInterpoWindowKey(pCtx, numOfOutput, RESULT_ROW_END_INTERP);
    return true;
  }

H
Haojun Liao 已提交
1393
  int32_t step = GET_FORWARD_DIRECTION_FACTOR(order);
1394 1395 1396 1397 1398
  int32_t nextRowIndex = endRowIndex + step;
  assert(nextRowIndex >= 0);

  TSKEY nextKey = tsCols[nextRowIndex];
  doTimeWindowInterpolation(pOperatorInfo, pOperatorInfo->info, pDataBlock, actualEndKey, endRowIndex, nextKey,
L
Liu Jicong 已提交
1399
                            nextRowIndex, key, RESULT_ROW_END_INTERP);
1400 1401 1402
  return true;
}

H
Haojun Liao 已提交
1403
static void doWindowBorderInterpolation(SOperatorInfo* pOperatorInfo, SSDataBlock* pBlock, SqlFunctionCtx* pCtx,
L
Liu Jicong 已提交
1404 1405
                                        SResultRow* pResult, STimeWindow* win, int32_t startPos, int32_t forwardStep,
                                        int32_t order, bool timeWindowInterpo) {
H
Haojun Liao 已提交
1406
  if (!timeWindowInterpo) {
1407 1408 1409 1410
    return;
  }

  assert(pBlock != NULL);
H
Haojun Liao 已提交
1411
  int32_t step = GET_FORWARD_DIRECTION_FACTOR(order);
1412

L
Liu Jicong 已提交
1413 1414
  if (pBlock->pDataBlock == NULL) {
    //    tscError("pBlock->pDataBlock == NULL");
1415 1416
    return;
  }
H
Haojun Liao 已提交
1417

L
Liu Jicong 已提交
1418
  SColumnInfoData* pColInfo = taosArrayGet(pBlock->pDataBlock, 0);
1419

L
Liu Jicong 已提交
1420 1421 1422
  TSKEY* tsCols = (TSKEY*)(pColInfo->pData);
  bool   done = resultRowInterpolated(pResult, RESULT_ROW_START_INTERP);
  if (!done) {  // it is not interpolated, now start to generated the interpolated value
1423
    int32_t startRowIndex = startPos;
L
Liu Jicong 已提交
1424
    bool    interp = setTimeWindowInterpolationStartTs(pOperatorInfo, pCtx, startRowIndex, pBlock->info.rows,
L
Liu Jicong 已提交
1425
                                                       pBlock->pDataBlock, tsCols, win);
1426 1427 1428 1429
    if (interp) {
      setResultRowInterpo(pResult, RESULT_ROW_START_INTERP);
    }
  } else {
H
Haojun Liao 已提交
1430
    setNotInterpoWindowKey(pCtx, pOperatorInfo->numOfOutput, RESULT_ROW_START_INTERP);
1431 1432 1433
  }

  // point interpolation does not require the end key time window interpolation.
L
Liu Jicong 已提交
1434 1435 1436
  //  if (pointInterpQuery) {
  //    return;
  //  }
1437 1438 1439 1440 1441 1442

  // interpolation query does not generate the time window end interpolation
  done = resultRowInterpolated(pResult, RESULT_ROW_END_INTERP);
  if (!done) {
    int32_t endRowIndex = startPos + (forwardStep - 1) * step;

L
Liu Jicong 已提交
1443 1444 1445
    TSKEY endKey = (order == TSDB_ORDER_ASC) ? pBlock->info.window.ekey : pBlock->info.window.skey;
    bool  interp =
        setTimeWindowInterpolationEndTs(pOperatorInfo, pCtx, endRowIndex, pBlock->pDataBlock, tsCols, endKey, win);
1446 1447 1448 1449
    if (interp) {
      setResultRowInterpo(pResult, RESULT_ROW_END_INTERP);
    }
  } else {
H
Haojun Liao 已提交
1450
    setNotInterpoWindowKey(pCtx, pOperatorInfo->numOfOutput, RESULT_ROW_END_INTERP);
1451 1452 1453
  }
}

dengyihao's avatar
dengyihao 已提交
1454 1455
static SArray* hashIntervalAgg(SOperatorInfo* pOperatorInfo, SResultRowInfo* pResultRowInfo, SSDataBlock* pSDataBlock,
                               int32_t tableGroupId) {
L
Liu Jicong 已提交
1456
  STableIntervalOperatorInfo* pInfo = (STableIntervalOperatorInfo*)pOperatorInfo->info;
1457

H
Haojun Liao 已提交
1458
  SExecTaskInfo* pTaskInfo = pOperatorInfo->pTaskInfo;
L
Liu Jicong 已提交
1459
  int32_t        numOfOutput = pOperatorInfo->numOfOutput;
1460

1461 1462
  SArray* pUpdated = NULL;
  if (pInfo->execModel == OPTR_EXEC_MODEL_STREAM) {
1463
    pUpdated = taosArrayInit(4, POINTER_BYTES);
1464 1465
  }

H
Haojun Liao 已提交
1466
  int32_t step = 1;
1467
  bool    ascScan = true;
1468

dengyihao's avatar
dengyihao 已提交
1469
  //  int32_t prevIndex = pResultRowInfo->curPos;
1470 1471 1472

  TSKEY* tsCols = NULL;
  if (pSDataBlock->pDataBlock != NULL) {
1473
    SColumnInfoData* pColDataInfo = taosArrayGet(pSDataBlock->pDataBlock, pInfo->primaryTsIndex);
L
Liu Jicong 已提交
1474
    tsCols = (int64_t*)pColDataInfo->pData;
1475 1476
  }

dengyihao's avatar
dengyihao 已提交
1477
  int32_t startPos = ascScan ? 0 : (pSDataBlock->info.rows - 1);
1478
  TSKEY   ts = getStartTsKey(&pSDataBlock->info.window, tsCols, pSDataBlock->info.rows, ascScan);
1479

dengyihao's avatar
dengyihao 已提交
1480 1481
  STimeWindow win = getActiveTimeWindow(pInfo->aggSup.pResultBuf, pResultRowInfo, ts, &pInfo->interval,
                                        pInfo->interval.precision, &pInfo->win);
L
Liu Jicong 已提交
1482
  bool        masterScan = true;
1483 1484

  SResultRow* pResult = NULL;
L
Liu Jicong 已提交
1485
  int32_t     ret = setResultOutputBufByKey_rv(pResultRowInfo, pSDataBlock->info.uid, &win, masterScan, &pResult,
L
Liu Jicong 已提交
1486 1487
                                               tableGroupId, pInfo->binfo.pCtx, numOfOutput, pInfo->binfo.rowCellInfoOffset,
                                               &pInfo->aggSup, pTaskInfo);
1488
  if (ret != TSDB_CODE_SUCCESS || pResult == NULL) {
H
Haojun Liao 已提交
1489
    longjmp(pTaskInfo->env, TSDB_CODE_QRY_OUT_OF_MEMORY);
1490 1491
  }

1492
  if (pInfo->execModel == OPTR_EXEC_MODEL_STREAM) {
1493 1494
    SResKeyPos* pos = taosMemoryMalloc(sizeof(SResKeyPos) + sizeof(uint64_t));
    pos->groupId = tableGroupId;
L
Liu Jicong 已提交
1495 1496
    pos->pos = (SResultRowPosition){.pageId = pResult->pageId, .offset = pResult->offset};
    *(int64_t*)pos->key = pResult->win.skey;
1497

1498 1499 1500
    taosArrayPush(pUpdated, &pos);
  }

1501
  int32_t forwardStep = 0;
H
Haojun Liao 已提交
1502
  TSKEY   ekey = win.ekey;
1503
  forwardStep =
H
Haojun Liao 已提交
1504
      getNumOfRowsInTimeWindow(&pSDataBlock->info, tsCols, startPos, ekey, binarySearchForKey, NULL, TSDB_ORDER_ASC);
1505 1506

  // prev time window not interpolation yet.
dengyihao's avatar
dengyihao 已提交
1507
  //  int32_t curIndex = pResultRowInfo->curPos;
H
Haojun Liao 已提交
1508 1509

#if 0
H
Haojun Liao 已提交
1510
  if (prevIndex != -1 && prevIndex < curIndex && pInfo->timeWindowInterpo) {
1511 1512 1513
    for (int32_t j = prevIndex; j < curIndex; ++j) {  // previous time window may be all closed already.
      SResultRow* pRes = getResultRow(pResultRowInfo, j);
      if (pRes->closed) {
1514
        assert(resultRowInterpolated(pRes, RESULT_ROW_START_INTERP) && resultRowInterpolated(pRes, RESULT_ROW_END_INTERP));
1515 1516 1517
        continue;
      }

L
Liu Jicong 已提交
1518 1519 1520 1521 1522 1523 1524
      STimeWindow w = pRes->win;
      ret = setResultOutputBufByKey_rv(pResultRowInfo, pSDataBlock->info.uid, &w, masterScan, &pResult, tableGroupId,
                                       pInfo->binfo.pCtx, numOfOutput, pInfo->binfo.rowCellInfoOffset, &pInfo->aggSup,
                                       pTaskInfo);
      if (ret != TSDB_CODE_SUCCESS) {
        longjmp(pTaskInfo->env, TSDB_CODE_QRY_OUT_OF_MEMORY);
      }
1525

L
Liu Jicong 已提交
1526 1527 1528
      assert(!resultRowInterpolated(pResult, RESULT_ROW_END_INTERP));
      doTimeWindowInterpolation(pOperatorInfo, &pInfo->binfo, pSDataBlock->pDataBlock, *(TSKEY*)pInfo->pRow[0], -1,
                                tsCols[startPos], startPos, w.ekey, RESULT_ROW_END_INTERP);
1529

L
Liu Jicong 已提交
1530 1531
      setResultRowInterpo(pResult, RESULT_ROW_END_INTERP);
      setNotInterpoWindowKey(pInfo->binfo.pCtx, pOperatorInfo->numOfOutput, RESULT_ROW_START_INTERP);
1532

1533
      doApplyFunctions(pInfo->binfo.pCtx, &w, &pInfo->timeWindowData, startPos, 0, tsCols, pSDataBlock->info.rows, numOfOutput, TSDB_ORDER_ASC);
L
Liu Jicong 已提交
1534
    }
1535 1536

    // restore current time window
L
Liu Jicong 已提交
1537 1538 1539
    ret = setResultOutputBufByKey_rv(pResultRowInfo, pSDataBlock->info.uid, &win, masterScan, &pResult, tableGroupId,
                                     pInfo->binfo.pCtx, numOfOutput, pInfo->binfo.rowCellInfoOffset, &pInfo->aggSup,
                                     pTaskInfo);
1540
    if (ret != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
1541
      longjmp(pTaskInfo->env, TSDB_CODE_QRY_OUT_OF_MEMORY);
1542 1543
    }
  }
H
Haojun Liao 已提交
1544
#endif
1545 1546

  // window start key interpolation
dengyihao's avatar
dengyihao 已提交
1547 1548
  doWindowBorderInterpolation(pOperatorInfo, pSDataBlock, pInfo->binfo.pCtx, pResult, &win, startPos, forwardStep,
                              pInfo->order, false);
1549

1550
  updateTimeWindowInfo(&pInfo->twAggSup.timeWindowData, &win, true);
dengyihao's avatar
dengyihao 已提交
1551 1552
  doApplyFunctions(pInfo->binfo.pCtx, &win, &pInfo->twAggSup.timeWindowData, startPos, forwardStep, tsCols,
                   pSDataBlock->info.rows, numOfOutput, TSDB_ORDER_ASC);
1553 1554 1555 1556

  STimeWindow nextWin = win;
  while (1) {
    int32_t prevEndPos = (forwardStep - 1) * step + startPos;
H
Haojun Liao 已提交
1557
    startPos = getNextQualifiedWindow(&pInfo->interval, &nextWin, &pSDataBlock->info, tsCols, prevEndPos, pInfo);
1558 1559 1560 1561 1562
    if (startPos < 0) {
      break;
    }

    // null data, failed to allocate more memory buffer
L
Liu Jicong 已提交
1563 1564 1565
    int32_t code = setResultOutputBufByKey_rv(pResultRowInfo, pSDataBlock->info.uid, &nextWin, masterScan, &pResult,
                                              tableGroupId, pInfo->binfo.pCtx, numOfOutput,
                                              pInfo->binfo.rowCellInfoOffset, &pInfo->aggSup, pTaskInfo);
1566
    if (code != TSDB_CODE_SUCCESS || pResult == NULL) {
H
Haojun Liao 已提交
1567
      longjmp(pTaskInfo->env, TSDB_CODE_QRY_OUT_OF_MEMORY);
1568 1569
    }

1570
    if (pInfo->execModel == OPTR_EXEC_MODEL_STREAM) {
1571 1572
      SResKeyPos* pos = taosMemoryMalloc(sizeof(SResKeyPos) + sizeof(uint64_t));
      pos->groupId = tableGroupId;
L
Liu Jicong 已提交
1573 1574
      pos->pos = (SResultRowPosition){.pageId = pResult->pageId, .offset = pResult->offset};
      *(int64_t*)pos->key = pResult->win.skey;
1575

1576 1577 1578
      taosArrayPush(pUpdated, &pos);
    }

L
Liu Jicong 已提交
1579 1580 1581
    ekey = nextWin.ekey;  // reviseWindowEkey(pQueryAttr, &nextWin);
    forwardStep =
        getNumOfRowsInTimeWindow(&pSDataBlock->info, tsCols, startPos, ekey, binarySearchForKey, NULL, TSDB_ORDER_ASC);
1582 1583

    // window start(end) key interpolation
C
Cary Xu 已提交
1584 1585
    doWindowBorderInterpolation(pOperatorInfo, pSDataBlock, pInfo->binfo.pCtx, pResult, &nextWin, startPos, forwardStep,
                                pInfo->order, false);
1586

1587
    updateTimeWindowInfo(&pInfo->twAggSup.timeWindowData, &nextWin, true);
dengyihao's avatar
dengyihao 已提交
1588 1589
    doApplyFunctions(pInfo->binfo.pCtx, &nextWin, &pInfo->twAggSup.timeWindowData, startPos, forwardStep, tsCols,
                     pSDataBlock->info.rows, numOfOutput, TSDB_ORDER_ASC);
1590 1591
  }

H
Haojun Liao 已提交
1592
  if (pInfo->timeWindowInterpo) {
1593
    int32_t rowIndex = ascScan ? (pSDataBlock->info.rows - 1) : 0;
H
Haojun Liao 已提交
1594
    saveDataBlockLastRow(pInfo->pRow, pSDataBlock->pDataBlock, rowIndex, pSDataBlock->info.numOfCols);
1595 1596
  }

1597
  return pUpdated;
L
Liu Jicong 已提交
1598
  //  updateResultRowInfoActiveIndex(pResultRowInfo, &pInfo->win, pRuntimeEnv->current->lastKey, true, false);
1599 1600
}

1601
static void doKeepTuple(SWindowRowsSup* pRowSup, int64_t ts) {
dengyihao's avatar
dengyihao 已提交
1602 1603
  pRowSup->win.ekey = ts;
  pRowSup->prevTs = ts;
1604
  pRowSup->numOfRows += 1;
1605 1606
}

1607 1608
static void doKeepNewWindowStartInfo(SWindowRowsSup* pRowSup, const int64_t* tsList, int32_t rowIndex) {
  pRowSup->startRowIndex = rowIndex;
dengyihao's avatar
dengyihao 已提交
1609 1610
  pRowSup->numOfRows = 0;
  pRowSup->win.skey = tsList[rowIndex];
1611 1612
}

1613
// todo handle multiple tables cases.
L
Liu Jicong 已提交
1614
static void doSessionWindowAggImpl(SOperatorInfo* pOperator, SSessionAggOperatorInfo* pInfo, SSDataBlock* pBlock) {
H
Haojun Liao 已提交
1615
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
1616

1617
  // todo find the correct time stamp column slot
1618
  SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, 0);
1619

1620 1621 1622
  bool    masterScan = true;
  int32_t numOfOutput = pOperator->numOfOutput;
  int64_t gid = pBlock->info.groupId;
1623

H
Haojun Liao 已提交
1624
  int64_t gap = pInfo->gap;
1625

1626
  if (!pInfo->reptScan) {
1627
    pInfo->reptScan = true;
1628
    pInfo->winSup.prevTs = INT64_MIN;
1629 1630
  }

1631 1632 1633
  SWindowRowsSup* pRowSup = &pInfo->winSup;
  pRowSup->numOfRows = 0;

1634
  // In case of ascending or descending order scan data, only one time window needs to be kepted for each table.
1635
  TSKEY* tsList = (TSKEY*)pColInfoData->pData;
1636
  for (int32_t j = 0; j < pBlock->info.rows; ++j) {
1637 1638 1639 1640
    if (pInfo->winSup.prevTs == INT64_MIN) {
      doKeepNewWindowStartInfo(pRowSup, tsList, j);
      doKeepTuple(pRowSup, tsList[j]);
    } else if (tsList[j] - pRowSup->prevTs <= gap && (tsList[j] - pRowSup->prevTs) >= 0) {
1641
      // The gap is less than the threshold, so it belongs to current session window that has been opened already.
1642 1643 1644
      doKeepTuple(pRowSup, tsList[j]);
      if (j == 0 && pRowSup->startRowIndex != 0) {
        pRowSup->startRowIndex = 0;
1645 1646 1647
      }
    } else {  // start a new session window
      SResultRow* pResult = NULL;
1648 1649

      // keep the time window for the closed time window.
1650
      STimeWindow window = pRowSup->win;
1651

1652
      pRowSup->win.ekey = pRowSup->win.skey;
L
Liu Jicong 已提交
1653
      int32_t ret = setResultOutputBufByKey_rv(&pInfo->binfo.resultRowInfo, pBlock->info.uid, &window, masterScan,
dengyihao's avatar
dengyihao 已提交
1654 1655
                                               &pResult, gid, pInfo->binfo.pCtx, numOfOutput,
                                               pInfo->binfo.rowCellInfoOffset, &pInfo->aggSup, pTaskInfo);
1656
      if (ret != TSDB_CODE_SUCCESS) {  // null data, too many state code
1657
        longjmp(pTaskInfo->env, TSDB_CODE_QRY_APP_ERROR);
1658 1659
      }

1660
      // pInfo->numOfRows data belong to the current session window
1661
      updateTimeWindowInfo(&pInfo->twAggSup.timeWindowData, &window, false);
dengyihao's avatar
dengyihao 已提交
1662 1663
      doApplyFunctions(pInfo->binfo.pCtx, &window, &pInfo->twAggSup.timeWindowData, pRowSup->startRowIndex,
                       pRowSup->numOfRows, NULL, pBlock->info.rows, numOfOutput, TSDB_ORDER_ASC);
1664

1665
      // here we start a new session window
1666 1667
      doKeepNewWindowStartInfo(pRowSup, tsList, j);
      doKeepTuple(pRowSup, tsList[j]);
1668 1669 1670 1671
    }
  }

  SResultRow* pResult = NULL;
1672
  pRowSup->win.ekey = tsList[pBlock->info.rows - 1];
dengyihao's avatar
dengyihao 已提交
1673 1674 1675
  int32_t ret = setResultOutputBufByKey_rv(&pInfo->binfo.resultRowInfo, pBlock->info.uid, &pRowSup->win, masterScan,
                                           &pResult, gid, pInfo->binfo.pCtx, numOfOutput,
                                           pInfo->binfo.rowCellInfoOffset, &pInfo->aggSup, pTaskInfo);
1676
  if (ret != TSDB_CODE_SUCCESS) {  // null data, too many state code
1677
    longjmp(pTaskInfo->env, TSDB_CODE_QRY_APP_ERROR);
1678 1679
  }

1680
  updateTimeWindowInfo(&pInfo->twAggSup.timeWindowData, &pRowSup->win, false);
dengyihao's avatar
dengyihao 已提交
1681 1682
  doApplyFunctions(pInfo->binfo.pCtx, &pRowSup->win, &pInfo->twAggSup.timeWindowData, pRowSup->startRowIndex,
                   pRowSup->numOfRows, NULL, pBlock->info.rows, numOfOutput, TSDB_ORDER_ASC);
1683 1684 1685 1686
}

static void setResultRowKey(SResultRow* pResultRow, char* pData, int16_t type) {
  if (IS_VAR_DATA_TYPE(type)) {
1687
    // todo disable this
dengyihao's avatar
dengyihao 已提交
1688 1689 1690 1691 1692 1693
    //    if (pResultRow->key == NULL) {
    //      pResultRow->key = taosMemoryMalloc(varDataTLen(pData));
    //      varDataCopy(pResultRow->key, pData);
    //    } else {
    //      ASSERT(memcmp(pResultRow->key, pData, varDataTLen(pData)) == 0);
    //    }
1694 1695 1696 1697 1698 1699 1700 1701 1702
  } else {
    int64_t v = -1;
    GET_TYPED_DATA(v, int64_t, type, pData);

    pResultRow->win.skey = v;
    pResultRow->win.ekey = v;
  }
}

1703
int32_t setGroupResultOutputBuf(SOptrBasicInfo* binfo, int32_t numOfCols, char* pData, int16_t type, int16_t bytes,
dengyihao's avatar
dengyihao 已提交
1704 1705
                                int32_t groupId, SDiskbasedBuf* pBuf, SExecTaskInfo* pTaskInfo,
                                SAggSupporter* pAggSup) {
L
Liu Jicong 已提交
1706 1707
  SResultRowInfo* pResultRowInfo = &binfo->resultRowInfo;
  SqlFunctionCtx* pCtx = binfo->pCtx;
1708

1709
  SResultRow* pResultRow = doSetResultOutBufByKey(pBuf, pResultRowInfo, groupId, (char*)pData, bytes, true, groupId,
L
Liu Jicong 已提交
1710
                                                  pTaskInfo, false, pAggSup);
L
Liu Jicong 已提交
1711
  assert(pResultRow != NULL);
1712 1713

  setResultRowKey(pResultRow, pData, type);
H
Haojun Liao 已提交
1714
  setResultRowOutputBufInitCtx_rv(pResultRow, pCtx, numOfCols, binfo->rowCellInfoOffset);
1715 1716 1717
  return TSDB_CODE_SUCCESS;
}

L
Liu Jicong 已提交
1718 1719
static bool functionNeedToExecute(SqlFunctionCtx* pCtx) {
  struct SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
1720 1721 1722

  // in case of timestamp column, always generated results.
  int32_t functionId = pCtx->functionId;
H
Haojun Liao 已提交
1723 1724 1725 1726
  if (functionId == -1) {
    return false;
  }

1727
  if (isRowEntryCompleted(pResInfo)) {
1728 1729 1730 1731
    return false;
  }

  if (functionId == FUNCTION_FIRST_DST || functionId == FUNCTION_FIRST) {
L
Liu Jicong 已提交
1732
    //    return QUERY_IS_ASC_QUERY(pQueryAttr);
1733 1734 1735 1736
  }

  // denote the order type
  if ((functionId == FUNCTION_LAST_DST || functionId == FUNCTION_LAST)) {
L
Liu Jicong 已提交
1737
    //    return pCtx->param[0].i == pQueryAttr->order.order;
1738 1739 1740
  }

  // in the reverse table scan, only the following functions need to be executed
L
Liu Jicong 已提交
1741 1742 1743 1744
  //  if (IS_REVERSE_SCAN(pRuntimeEnv) ||
  //      (pRuntimeEnv->scanFlag == REPEAT_SCAN && functionId != FUNCTION_STDDEV && functionId != FUNCTION_PERCT)) {
  //    return false;
  //  }
1745 1746 1747 1748

  return true;
}

dengyihao's avatar
dengyihao 已提交
1749 1750
static int32_t doCreateConstantValColumnAggInfo(SInputColumnInfoData* pInput, SFunctParam* pFuncParam, int32_t type,
                                                int32_t paramIndex, int32_t numOfRows) {
1751 1752 1753 1754 1755 1756 1757
  if (pInput->pData[paramIndex] == NULL) {
    pInput->pData[paramIndex] = taosMemoryCalloc(1, sizeof(SColumnInfoData));
    if (pInput->pData[paramIndex] == NULL) {
      return TSDB_CODE_OUT_OF_MEMORY;
    }

    // Set the correct column info (data type and bytes)
dengyihao's avatar
dengyihao 已提交
1758 1759
    pInput->pData[paramIndex]->info.type = type;
    pInput->pData[paramIndex]->info.bytes = tDataTypes[type].bytes;
1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776
  }

  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;
    }
  } else {
    da = pInput->pColumnDataAgg[paramIndex];
  }

  ASSERT(!IS_VAR_DATA_TYPE(type));

  if (type == TSDB_DATA_TYPE_BIGINT) {
    int64_t v = pFuncParam->param.i;
dengyihao's avatar
dengyihao 已提交
1777
    *da = (SColumnDataAgg){.numOfNull = 0, .min = v, .max = v, .maxIndex = 0, .minIndex = 0, .sum = v * numOfRows};
1778 1779
  } else if (type == TSDB_DATA_TYPE_DOUBLE) {
    double v = pFuncParam->param.d;
dengyihao's avatar
dengyihao 已提交
1780
    *da = (SColumnDataAgg){.numOfNull = 0, .maxIndex = 0, .minIndex = 0};
1781

dengyihao's avatar
dengyihao 已提交
1782 1783 1784
    *(double*)&da->min = v;
    *(double*)&da->max = v;
    *(double*)&da->sum = v * numOfRows;
1785 1786 1787
  } else if (type == TSDB_DATA_TYPE_BOOL) {  // todo validate this data type
    bool v = pFuncParam->param.i;

dengyihao's avatar
dengyihao 已提交
1788 1789 1790 1791
    *da = (SColumnDataAgg){.numOfNull = 0, .maxIndex = 0, .minIndex = 0};
    *(bool*)&da->min = 0;
    *(bool*)&da->max = v;
    *(bool*)&da->sum = v * numOfRows;
1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810
  } else if (type == TSDB_DATA_TYPE_TIMESTAMP) {
    // do nothing
  } else {
    ASSERT(0);
  }

  return TSDB_CODE_SUCCESS;
}

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;

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

1814 1815 1816
      if (pFuncParam->type == FUNC_PARAM_TYPE_COLUMN) {
        int32_t slotId = pFuncParam->pCol->slotId;
        pInput->pColumnDataAgg[j] = &pBlock->pBlockAgg[slotId];
1817 1818 1819 1820

        // 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);
1821 1822
      } else if (pFuncParam->type == FUNC_PARAM_TYPE_VALUE) {
        doCreateConstantValColumnAggInfo(pInput, pFuncParam, pFuncParam->param.nType, j, pBlock->info.rows);
1823 1824
      }
    }
1825
  } else {
1826
    pInput->colDataAggIsSet = false;
1827 1828 1829
  }

  // set the statistics data for primary time stamp column
1830 1831 1832 1833 1834
  //  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;
  //  }
1835 1836 1837
}

// set the output buffer for the selectivity + tag query
L
Liu Jicong 已提交
1838
static int32_t setCtxTagColumnInfo(SqlFunctionCtx* pCtx, int32_t numOfOutput) {
1839 1840 1841
  int32_t num = 0;
  int16_t tagLen = 0;

H
Haojun Liao 已提交
1842
  SqlFunctionCtx*  p = NULL;
wafwerar's avatar
wafwerar 已提交
1843
  SqlFunctionCtx** pTagCtx = taosMemoryCalloc(numOfOutput, POINTER_BYTES);
1844 1845 1846 1847 1848 1849 1850 1851
  if (pTagCtx == NULL) {
    return TSDB_CODE_QRY_OUT_OF_MEMORY;
  }

  for (int32_t i = 0; i < numOfOutput; ++i) {
    int32_t functionId = pCtx[i].functionId;

    if (functionId == FUNCTION_TAG_DUMMY || functionId == FUNCTION_TS_DUMMY) {
H
Haojun Liao 已提交
1852
      tagLen += pCtx[i].resDataInfo.bytes;
1853
      pTagCtx[num++] = &pCtx[i];
L
Liu Jicong 已提交
1854
    } else if (1 /*(aAggs[functionId].status & FUNCSTATE_SELECTIVITY) != 0*/) {
1855 1856 1857 1858 1859 1860 1861 1862 1863 1864
      p = &pCtx[i];
    } else if (functionId == FUNCTION_TS || functionId == FUNCTION_TAG) {
      // tag function may be the group by tag column
      // ts may be the required primary timestamp column
      continue;
    } else {
      // the column may be the normal column, group by normal_column, the functionId is FUNCTION_PRJ
    }
  }
  if (p != NULL) {
1865 1866
    p->subsidiaries.pCtx = pTagCtx;
    p->subsidiaries.num = num;
1867
  } else {
wafwerar's avatar
wafwerar 已提交
1868
    taosMemoryFreeClear(pTagCtx);
1869 1870 1871 1872 1873
  }

  return TSDB_CODE_SUCCESS;
}

1874
SqlFunctionCtx* createSqlFunctionCtx(SExprInfo* pExprInfo, int32_t numOfOutput, int32_t** rowCellInfoOffset) {
L
Liu Jicong 已提交
1875
  SqlFunctionCtx* pFuncCtx = (SqlFunctionCtx*)taosMemoryCalloc(numOfOutput, sizeof(SqlFunctionCtx));
H
Haojun Liao 已提交
1876 1877 1878 1879
  if (pFuncCtx == NULL) {
    return NULL;
  }

wafwerar's avatar
wafwerar 已提交
1880
  *rowCellInfoOffset = taosMemoryCalloc(numOfOutput, sizeof(int32_t));
H
Haojun Liao 已提交
1881
  if (*rowCellInfoOffset == 0) {
wafwerar's avatar
wafwerar 已提交
1882
    taosMemoryFreeClear(pFuncCtx);
H
Haojun Liao 已提交
1883 1884 1885 1886
    return NULL;
  }

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

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

1892
    pCtx->functionId = -1;
1893
    pCtx->curBufPage = -1;
L
Liu Jicong 已提交
1894
    pCtx->pExpr = pExpr;
1895

H
Haojun Liao 已提交
1896
    if (pExpr->pExpr->nodeType == QUERY_NODE_FUNCTION) {
H
Haojun Liao 已提交
1897
      SFuncExecEnv env = {0};
H
Haojun Liao 已提交
1898 1899
      pCtx->functionId = pExpr->pExpr->_function.pFunctNode->funcId;

H
Haojun Liao 已提交
1900
      if (fmIsAggFunc(pCtx->functionId) || fmIsNonstandardSQLFunc(pCtx->functionId)) {
1901 1902 1903 1904 1905 1906 1907 1908
        bool isUdaf = fmIsUserDefinedFunc(pCtx->functionId);
        if (!isUdaf) {
          fmGetFuncExecFuncs(pCtx->functionId, &pCtx->fpSet);
        } else {
          char *udfName = pExpr->pExpr->_function.pFunctNode->functionName;
          strncpy(pCtx->udfName, udfName, strlen(udfName));
          fmGetUdafExecFuncs(pCtx->functionId, &pCtx->fpSet);
        }
1909 1910 1911
        pCtx->fpSet.getEnv(pExpr->pExpr->_function.pFunctNode, &env);
      } else {
        fmGetScalarFuncExecFuncs(pCtx->functionId, &pCtx->sfp);
1912 1913 1914
        if (pCtx->sfp.getEnv != NULL) {
          pCtx->sfp.getEnv(pExpr->pExpr->_function.pFunctNode, &env);
        }
1915
      }
H
Haojun Liao 已提交
1916
      pCtx->resDataInfo.interBufSize = env.calcMemSize;
1917 1918 1919 1920
    } else if (pExpr->pExpr->nodeType == QUERY_NODE_COLUMN || pExpr->pExpr->nodeType == QUERY_NODE_OPERATOR ||
               pExpr->pExpr->nodeType == QUERY_NODE_VALUE) {
      // for simple column, the intermediate buffer needs to hold one element.
      pCtx->resDataInfo.interBufSize = pFunct->resSchema.bytes;
H
Haojun Liao 已提交
1921
    }
H
Haojun Liao 已提交
1922

H
Haojun Liao 已提交
1923
    pCtx->input.numOfInputCols = pFunct->numOfParams;
wafwerar's avatar
wafwerar 已提交
1924 1925
    pCtx->input.pData = taosMemoryCalloc(pFunct->numOfParams, POINTER_BYTES);
    pCtx->input.pColumnDataAgg = taosMemoryCalloc(pFunct->numOfParams, POINTER_BYTES);
H
Haojun Liao 已提交
1926

1927
    pCtx->pTsOutput = NULL;
L
Liu Jicong 已提交
1928
    pCtx->resDataInfo.bytes = pFunct->resSchema.bytes;
1929
    pCtx->resDataInfo.type = pFunct->resSchema.type;
L
Liu Jicong 已提交
1930
    pCtx->order = TSDB_ORDER_ASC;
1931
    pCtx->start.key = INT64_MIN;
L
Liu Jicong 已提交
1932
    pCtx->end.key = INT64_MIN;
1933
    pCtx->numOfParams = pExpr->base.numOfParams;
H
Haojun Liao 已提交
1934

1935
    pCtx->param = pFunct->pParam;
dengyihao's avatar
dengyihao 已提交
1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969
    //    for (int32_t j = 0; j < pCtx->numOfParams; ++j) {
    //      // set the order information for top/bottom query
    //      int32_t functionId = pCtx->functionId;
    //      if (functionId == FUNCTION_TOP || functionId == FUNCTION_BOTTOM || functionId == FUNCTION_DIFF) {
    //        int32_t f = getExprFunctionId(&pExpr[0]);
    //        assert(f == FUNCTION_TS || f == FUNCTION_TS_DUMMY);
    //
    //        //      pCtx->param[2].i = pQueryAttr->order.order;
    //        //      pCtx->param[2].nType = TSDB_DATA_TYPE_BIGINT;
    //        //      pCtx->param[3].i = functionId;
    //        //      pCtx->param[3].nType = TSDB_DATA_TYPE_BIGINT;
    //
    //        //      pCtx->param[1].i = pQueryAttr->order.col.info.colId;
    //      } else if (functionId == FUNCTION_INTERP) {
    //        //      pCtx->param[2].i = (int8_t)pQueryAttr->fillType;
    //        //      if (pQueryAttr->fillVal != NULL) {
    //        //        if (isNull((const char *)&pQueryAttr->fillVal[i], pCtx->inputType)) {
    //        //          pCtx->param[1].nType = TSDB_DATA_TYPE_NULL;
    //        //        } else {  // todo refactor, taosVariantCreateFromBinary should handle the NULL value
    //        //          if (pCtx->inputType != TSDB_DATA_TYPE_BINARY && pCtx->inputType != TSDB_DATA_TYPE_NCHAR) {
    //        //            taosVariantCreateFromBinary(&pCtx->param[1], (char *)&pQueryAttr->fillVal[i],
    //        pCtx->inputBytes, pCtx->inputType);
    //        //          }
    //        //        }
    //        //      }
    //      } else if (functionId == FUNCTION_TWA) {
    //        //      pCtx->param[1].i = pQueryAttr->window.skey;
    //        //      pCtx->param[1].nType = TSDB_DATA_TYPE_BIGINT;
    //        //      pCtx->param[2].i = pQueryAttr->window.ekey;
    //        //      pCtx->param[2].nType = TSDB_DATA_TYPE_BIGINT;
    //      } else if (functionId == FUNCTION_ARITHM) {
    //        //      pCtx->param[1].pz = (char*) getScalarFuncSupport(pRuntimeEnv->scalarSup, i);
    //      }
    //    }
H
Haojun Liao 已提交
1970 1971
  }

L
Liu Jicong 已提交
1972 1973 1974
  for (int32_t i = 1; i < numOfOutput; ++i) {
    (*rowCellInfoOffset)[i] =
        (int32_t)((*rowCellInfoOffset)[i - 1] + sizeof(SResultRowEntryInfo) + pFuncCtx[i - 1].resDataInfo.interBufSize);
H
Haojun Liao 已提交
1975
  }
H
Haojun Liao 已提交
1976 1977 1978 1979 1980

  setCtxTagColumnInfo(pFuncCtx, numOfOutput);
  return pFuncCtx;
}

1981
static void* destroySqlFunctionCtx(SqlFunctionCtx* pCtx, int32_t numOfOutput) {
1982 1983 1984 1985 1986 1987
  if (pCtx == NULL) {
    return NULL;
  }

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

    taosVariantDestroy(&pCtx[i].tag);
1992
    taosMemoryFreeClear(pCtx[i].subsidiaries.pCtx);
1993 1994
  }

wafwerar's avatar
wafwerar 已提交
1995
  taosMemoryFreeClear(pCtx);
1996 1997 1998
  return NULL;
}

L
Liu Jicong 已提交
1999
bool isTaskKilled(SExecTaskInfo* pTaskInfo) {
2000 2001
  // query has been executed more than tsShellActivityTimer, and the retrieve has not arrived
  // abort current query execution.
L
Liu Jicong 已提交
2002 2003
  if (pTaskInfo->owner != 0 &&
      ((taosGetTimestampSec() - pTaskInfo->cost.start / 1000) > 10 * getMaximumIdleDurationSec())
2004 2005
      /*(!needBuildResAfterQueryComplete(pTaskInfo))*/) {
    assert(pTaskInfo->cost.start != 0);
L
Liu Jicong 已提交
2006 2007 2008
    //    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;
2009 2010 2011 2012 2013
  }

  return false;
}

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

L
Liu Jicong 已提交
2016
static bool isCachedLastQuery(STaskAttr* pQueryAttr) {
2017 2018 2019 2020 2021 2022 2023 2024 2025
  for (int32_t i = 0; i < pQueryAttr->numOfOutput; ++i) {
    int32_t functionId = getExprFunctionId(&pQueryAttr->pExpr1[i]);
    if (functionId == FUNCTION_LAST || functionId == FUNCTION_LAST_DST) {
      continue;
    }

    return false;
  }

2026 2027
  int32_t order = TSDB_ORDER_ASC;
  if (order != TSDB_ORDER_DESC || !TSWINDOW_IS_EQUAL(pQueryAttr->window, TSWINDOW_DESC_INITIALIZER)) {
2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046
    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 已提交
2047
// todo refactor : return window
2048
void getAlignQueryTimeWindow(SInterval* pInterval, int32_t precision, int64_t key, STimeWindow* win) {
H
Haojun Liao 已提交
2049
  win->skey = taosTimeTruncate(key, pInterval, precision);
2050 2051

  /*
H
Haojun Liao 已提交
2052
   * if the realSkey > INT64_MAX - pInterval->interval, the query duration between
2053 2054
   * realSkey and realEkey must be less than one interval.Therefore, no need to adjust the query ranges.
   */
2055 2056
  win->ekey = taosTimeAdd(win->skey, pInterval->interval, pInterval->intervalUnit, precision) - 1;
  if (win->ekey < win->skey) {
2057 2058 2059 2060
    win->ekey = INT64_MAX;
  }
}

L
Liu Jicong 已提交
2061
static int32_t updateBlockLoadStatus(STaskAttr* pQuery, int32_t status) {
2062 2063 2064
  bool hasFirstLastFunc = false;
  bool hasOtherFunc = false;

2065
  if (status == BLK_DATA_DATA_LOAD || status == BLK_DATA_FILTEROUT) {
2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083
    return status;
  }

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

    if (functionId == FUNCTION_TS || functionId == FUNCTION_TS_DUMMY || functionId == FUNCTION_TAG ||
        functionId == FUNCTION_TAG_DUMMY) {
      continue;
    }

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

2084
  if (hasFirstLastFunc && status == BLK_DATA_NOT_LOAD) {
L
Liu Jicong 已提交
2085
    if (!hasOtherFunc) {
2086
      return BLK_DATA_FILTEROUT;
2087
    } else {
2088
      return BLK_DATA_DATA_LOAD;
2089 2090 2091 2092 2093 2094
    }
  }

  return status;
}

L
Liu Jicong 已提交
2095 2096
// static void updateDataCheckOrder(SQInfo *pQInfo, SQueryTableReq* pQueryMsg, bool stableQuery) {
//   STaskAttr* pQueryAttr = pQInfo->runtimeEnv.pQueryAttr;
H
Haojun Liao 已提交
2097
//
L
Liu Jicong 已提交
2098 2099 2100 2101
//   // 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 已提交
2102
//
L
Liu Jicong 已提交
2103 2104 2105 2106 2107
//   // 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 已提交
2108
//
L
Liu Jicong 已提交
2109 2110
//     pQueryAttr->order.order = TSDB_ORDER_ASC;
//     if (pQueryAttr->window.skey > pQueryAttr->window.ekey) {
wafwerar's avatar
wafwerar 已提交
2111
//       TSWAP(pQueryAttr->window.skey, pQueryAttr->window.ekey);
L
Liu Jicong 已提交
2112
//     }
H
Haojun Liao 已提交
2113
//
L
Liu Jicong 已提交
2114 2115 2116
//     pQueryAttr->needReverseScan = false;
//     return;
//   }
H
Haojun Liao 已提交
2117
//
L
Liu Jicong 已提交
2118 2119 2120
//   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 已提交
2121
//       TSWAP(pQueryAttr->window.skey, pQueryAttr->window.ekey);
L
Liu Jicong 已提交
2122
//     }
H
Haojun Liao 已提交
2123
//
L
Liu Jicong 已提交
2124 2125 2126 2127
//     pQueryAttr->needReverseScan = false;
//     doUpdateLastKey(pQueryAttr);
//     return;
//   }
H
Haojun Liao 已提交
2128
//
L
Liu Jicong 已提交
2129 2130 2131 2132 2133 2134
//   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 已提交
2135
//
L
Liu Jicong 已提交
2136 2137 2138
//     pQueryAttr->order.order = TSDB_ORDER_ASC;
//     return;
//   }
H
Haojun Liao 已提交
2139
//
L
Liu Jicong 已提交
2140 2141 2142 2143
//   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 已提交
2144 2145
////               pQueryAttr->window.ekey, pQueryAttr->window.ekey, pQueryAttr->window.skey);
//
wafwerar's avatar
wafwerar 已提交
2146
//        TSWAP(pQueryAttr->window.skey, pQueryAttr->window.ekey);
H
Haojun Liao 已提交
2147 2148 2149 2150 2151 2152 2153 2154 2155 2156
//        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 已提交
2157
//        TSWAP(pQueryAttr->window.skey, pQueryAttr->window.ekey);
H
Haojun Liao 已提交
2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169
//        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 已提交
2170 2171
////                 pQueryAttr->window.skey, pQueryAttr->window.ekey, pQueryAttr->window.ekey,
/// pQueryAttr->window.skey);
H
Haojun Liao 已提交
2172
//
wafwerar's avatar
wafwerar 已提交
2173
//          TSWAP(pQueryAttr->window.skey, pQueryAttr->window.ekey);
H
Haojun Liao 已提交
2174 2175 2176 2177 2178 2179 2180 2181
//          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 已提交
2182 2183
////                 pQueryAttr->window.skey, pQueryAttr->window.ekey, pQueryAttr->window.ekey,
/// pQueryAttr->window.skey);
H
Haojun Liao 已提交
2184
//
wafwerar's avatar
wafwerar 已提交
2185
//          TSWAP(pQueryAttr->window.skey, pQueryAttr->window.ekey);
H
Haojun Liao 已提交
2186 2187 2188 2189 2190 2191 2192 2193 2194
//          doUpdateLastKey(pQueryAttr);
//        }
//
//        pQueryAttr->order.order = TSDB_ORDER_DESC;
//        pQueryAttr->needReverseScan = false;
//      }
//    }
//  }
//}
2195

H
Haojun Liao 已提交
2196 2197
static void getIntermediateBufInfo(STaskRuntimeEnv* pRuntimeEnv, int32_t* ps, int32_t* rowsize) {
  STaskAttr* pQueryAttr = pRuntimeEnv->pQueryAttr;
L
Liu Jicong 已提交
2198
  int32_t    MIN_ROWS_PER_PAGE = 4;
2199

L
Liu Jicong 已提交
2200 2201
  *rowsize = (int32_t)(pQueryAttr->resultRowSize *
                       getRowNumForMultioutput(pQueryAttr, pQueryAttr->topBotQuery, pQueryAttr->stableQuery));
2202 2203 2204 2205
  int32_t overhead = sizeof(SFilePage);

  // one page contains at least two rows
  *ps = DEFAULT_INTERN_BUF_PAGE_SIZE;
L
Liu Jicong 已提交
2206
  while (((*rowsize) * MIN_ROWS_PER_PAGE) > (*ps) - overhead) {
2207 2208 2209 2210 2211 2212
    *ps = ((*ps) << 1u);
  }
}

#define IS_PREFILTER_TYPE(_t) ((_t) != TSDB_DATA_TYPE_BINARY && (_t) != TSDB_DATA_TYPE_NCHAR)

L
Liu Jicong 已提交
2213 2214 2215
// static FORCE_INLINE bool doFilterByBlockStatistics(STaskRuntimeEnv* pRuntimeEnv, SDataStatis *pDataStatis,
// SqlFunctionCtx *pCtx, int32_t numOfRows) {
//   STaskAttr* pQueryAttr = pRuntimeEnv->pQueryAttr;
2216
//
L
Liu Jicong 已提交
2217 2218 2219
//   if (pDataStatis == NULL || pQueryAttr->pFilters == NULL) {
//     return true;
//   }
2220
//
L
Liu Jicong 已提交
2221 2222
//   return filterRangeExecute(pQueryAttr->pFilters, pDataStatis, pQueryAttr->numOfCols, numOfRows);
// }
2223

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

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

2230
  if (true) {
L
Liu Jicong 已提交
2231
    //    getAlignQueryTimeWindow(pQueryAttr, pBlockInfo->window.skey, sk, ek, &w);
2232 2233 2234 2235 2236 2237
    assert(w.ekey >= pBlockInfo->window.skey);

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

L
Liu Jicong 已提交
2238 2239
    while (1) {
      //      getNextTimeWindow(pQueryAttr, &w);
2240 2241 2242 2243 2244 2245 2246 2247 2248 2249
      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 已提交
2250
    //    getAlignQueryTimeWindow(pQueryAttr, pBlockInfo->window.ekey, sk, ek, &w);
2251 2252 2253 2254 2255 2256
    assert(w.skey <= pBlockInfo->window.ekey);

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

L
Liu Jicong 已提交
2257 2258
    while (1) {
      //      getNextTimeWindow(pQueryAttr, &w);
2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322
      if (w.ekey < pBlockInfo->window.skey) {
        break;
      }

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

  return false;
}

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

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

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

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

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

    start += len;
    len = 0;
  }

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

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

static SColumnInfo* doGetTagColumnInfoById(SColumnInfo* pTagColList, int32_t numOfTags, int16_t colId);
L
Liu Jicong 已提交
2323
static void         doSetTagValueInParam(void* pTable, int32_t tagColId, SVariant* tag, int16_t type, int16_t bytes);
2324 2325

static uint32_t doFilterByBlockTimeWindow(STableScanInfo* pTableScanInfo, SSDataBlock* pBlock) {
H
Haojun Liao 已提交
2326
  SqlFunctionCtx* pCtx = pTableScanInfo->pCtx;
2327
  uint32_t        status = BLK_DATA_NOT_LOAD;
2328 2329 2330 2331

  int32_t numOfOutput = pTableScanInfo->numOfOutput;
  for (int32_t i = 0; i < numOfOutput; ++i) {
    int32_t functionId = pCtx[i].functionId;
H
Haojun Liao 已提交
2332
    int32_t colId = pTableScanInfo->pExpr[i].base.pParam[0].pCol->colId;
2333 2334 2335

    // group by + first/last should not apply the first/last block filter
    if (functionId < 0) {
2336
      status |= BLK_DATA_DATA_LOAD;
2337 2338
      return status;
    } else {
L
Liu Jicong 已提交
2339
      //      status |= aAggs[functionId].dataReqFunc(&pTableScanInfo->pCtx[i], &pBlock->info.window, colId);
2340
      //      if ((status & BLK_DATA_DATA_LOAD) == BLK_DATA_DATA_LOAD) {
L
Liu Jicong 已提交
2341 2342
      //        return status;
      //      }
2343 2344 2345 2346 2347 2348
    }
  }

  return status;
}

L
Liu Jicong 已提交
2349 2350
int32_t loadDataBlockOnDemand(SExecTaskInfo* pTaskInfo, STableScanInfo* pTableScanInfo, SSDataBlock* pBlock,
                              uint32_t* status) {
2351
  *status = BLK_DATA_NOT_LOAD;
2352

H
Haojun Liao 已提交
2353
  pBlock->pDataBlock = NULL;
L
Liu Jicong 已提交
2354
  pBlock->pBlockAgg = NULL;
H
Haojun Liao 已提交
2355

L
Liu Jicong 已提交
2356 2357
  //  int64_t groupId = pRuntimeEnv->current->groupIndex;
  //  bool    ascQuery = QUERY_IS_ASC_QUERY(pQueryAttr);
2358

H
Haojun Liao 已提交
2359
  STaskCostInfo* pCost = &pTaskInfo->cost;
2360 2361 2362

  pCost->totalBlocks += 1;
  pCost->totalRows += pBlock->info.rows;
H
Haojun Liao 已提交
2363
#if 0
2364 2365 2366
  // 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 已提交
2367
      (QUERY_IS_INTERVAL_QUERY(pQueryAttr) && overlapWithTimeWindow(pTaskInfo, &pBlock->info))) {
2368
    (*status) = BLK_DATA_DATA_LOAD;
2369 2370 2371
  }

  // check if this data block is required to load
2372
  if ((*status) != BLK_DATA_DATA_LOAD) {
2373 2374 2375 2376 2377 2378 2379
    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 已提交
2380
      bool  masterScan = IS_MAIN_SCAN(pRuntimeEnv);
2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403
      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 {
2404
      (*status) = BLK_DATA_DATA_LOAD;
2405 2406 2407 2408
    }
  }

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

2411
  if ((*status) == BLK_DATA_NOT_LOAD || (*status) == BLK_DATA_FILTEROUT) {
2412 2413
    //qDebug("QInfo:0x%"PRIx64" data block discard, brange:%" PRId64 "-%" PRId64 ", rows:%d", pQInfo->qId, pBlockInfo->window.skey,
//           pBlockInfo->window.ekey, pBlockInfo->rows);
2414
    pCost->skipBlocks += 1;
2415
  } else if ((*status) == BLK_DATA_SMA_LOAD) {
2416 2417
    // this function never returns error?
    pCost->loadBlockStatis += 1;
2418
//    tsdbRetrieveDataBlockStatisInfo(pTableScanInfo->pTsdbReadHandle, &pBlock->pBlockAgg);
2419 2420

    if (pBlock->pBlockAgg == NULL) {  // data block statistics does not exist, load data block
2421
//      pBlock->pDataBlock = tsdbRetrieveDataBlock(pTableScanInfo->pTsdbReadHandle, NULL);
2422 2423 2424
      pCost->totalCheckedRows += pBlock->info.rows;
    }
  } else {
2425
    assert((*status) == BLK_DATA_DATA_LOAD);
2426 2427 2428

    // load the data block statistics to perform further filter
    pCost->loadBlockStatis += 1;
2429
//    tsdbRetrieveDataBlockStatisInfo(pTableScanInfo->pTsdbReadHandle, &pBlock->pBlockAgg);
2430 2431 2432 2433 2434 2435

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

H
Haojun Liao 已提交
2436
          bool  masterScan = IS_MAIN_SCAN(pRuntimeEnv);
2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453
          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
2454
            pCost->skipBlocks += 1;
2455 2456
            //qDebug("QInfo:0x%"PRIx64" data block discard, brange:%" PRId64 "-%" PRId64 ", rows:%d", pQInfo->qId,
//                   pBlockInfo->window.skey, pBlockInfo->window.ekey, pBlockInfo->rows);
2457
            (*status) = BLK_DATA_FILTEROUT;
2458 2459 2460 2461 2462 2463 2464 2465
            return TSDB_CODE_SUCCESS;
          }
        }
      }
    }

    // current block has been discard due to filter applied
//    if (!doFilterByBlockStatistics(pRuntimeEnv, pBlock->pBlockAgg, pTableScanInfo->pCtx, pBlockInfo->rows)) {
2466
//      pCost->skipBlocks += 1;
2467 2468
//      qDebug("QInfo:0x%"PRIx64" data block discard, brange:%" PRId64 "-%" PRId64 ", rows:%d", pQInfo->qId, pBlockInfo->window.skey,
//             pBlockInfo->window.ekey, pBlockInfo->rows);
2469
//      (*status) = BLK_DATA_FILTEROUT;
2470 2471 2472 2473 2474
//      return TSDB_CODE_SUCCESS;
//    }

    pCost->totalCheckedRows += pBlockInfo->rows;
    pCost->loadBlocks += 1;
2475
//    pBlock->pDataBlock = tsdbRetrieveDataBlock(pTableScanInfo->pTsdbReadHandle, NULL);
2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487
//    if (pBlock->pDataBlock == NULL) {
//      return terrno;
//    }

//    if (pQueryAttr->pFilters != NULL) {
//      filterSetColFieldData(pQueryAttr->pFilters, pBlock->info.numOfCols, pBlock->pDataBlock);
//    }
    
//    if (pQueryAttr->pFilters != NULL || pRuntimeEnv->pTsBuf != NULL) {
//      filterColRowsInDataBlock(pRuntimeEnv, pBlock, ascQuery);
//    }
  }
H
Haojun Liao 已提交
2488
#endif
2489 2490 2491
  return TSDB_CODE_SUCCESS;
}

L
Liu Jicong 已提交
2492
int32_t binarySearchForKey(char* pValue, int num, TSKEY key, int order) {
2493 2494 2495 2496 2497 2498 2499 2500 2501
  int32_t midPos = -1;
  int32_t numOfRows;

  if (num <= 0) {
    return -1;
  }

  assert(order == TSDB_ORDER_ASC || order == TSDB_ORDER_DESC);

L
Liu Jicong 已提交
2502
  TSKEY*  keyList = (TSKEY*)pValue;
2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555
  int32_t firstPos = 0;
  int32_t lastPos = num - 1;

  if (order == TSDB_ORDER_DESC) {
    // find the first position which is smaller than the key
    while (1) {
      if (key >= keyList[lastPos]) return lastPos;
      if (key == keyList[firstPos]) return firstPos;
      if (key < keyList[firstPos]) return firstPos - 1;

      numOfRows = lastPos - firstPos + 1;
      midPos = (numOfRows >> 1) + firstPos;

      if (key < keyList[midPos]) {
        lastPos = midPos - 1;
      } else if (key > keyList[midPos]) {
        firstPos = midPos + 1;
      } else {
        break;
      }
    }

  } else {
    // find the first position which is bigger than the key
    while (1) {
      if (key <= keyList[firstPos]) return firstPos;
      if (key == keyList[lastPos]) return lastPos;

      if (key > keyList[lastPos]) {
        lastPos = lastPos + 1;
        if (lastPos >= num)
          return -1;
        else
          return lastPos;
      }

      numOfRows = lastPos - firstPos + 1;
      midPos = (numOfRows >> 1u) + firstPos;

      if (key < keyList[midPos]) {
        lastPos = midPos - 1;
      } else if (key > keyList[midPos]) {
        firstPos = midPos + 1;
      } else {
        break;
      }
    }
  }

  return midPos;
}

/*
H
Haojun Liao 已提交
2556
 * set tag value in SqlFunctionCtx
2557 2558
 * e.g.,tag information into input buffer
 */
L
Liu Jicong 已提交
2559
static void doSetTagValueInParam(void* pTable, int32_t tagColId, SVariant* tag, int16_t type, int16_t bytes) {
2560 2561 2562
  taosVariantDestroy(tag);

  char* val = NULL;
L
Liu Jicong 已提交
2563 2564 2565 2566 2567 2568
  //  if (tagColId == TSDB_TBNAME_COLUMN_INDEX) {
  //    val = tsdbGetTableName(pTable);
  //    assert(val != NULL);
  //  } else {
  //    val = tsdbGetTableTagVal(pTable, tagColId, type, bytes);
  //  }
2569 2570 2571 2572 2573 2574 2575 2576

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

  if (type == TSDB_DATA_TYPE_BINARY || type == TSDB_DATA_TYPE_NCHAR) {
    int32_t maxLen = bytes - VARSTR_HEADER_SIZE;
L
Liu Jicong 已提交
2577
    int32_t len = (varDataLen(val) > maxLen) ? maxLen : varDataLen(val);
2578
    taosVariantCreateFromBinary(tag, varDataVal(val), len, type);
L
Liu Jicong 已提交
2579
    // taosVariantCreateFromBinary(tag, varDataVal(val), varDataLen(val), type);
2580 2581 2582 2583 2584 2585 2586 2587
  } else {
    taosVariantCreateFromBinary(tag, val, bytes, type);
  }
}

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

L
Liu Jicong 已提交
2588
  for (int32_t i = 0; i < numOfTags; ++i) {
2589 2590 2591 2592 2593 2594 2595 2596
    if (pTagColList[i].colId == colId) {
      return &pTagColList[i];
    }
  }

  return NULL;
}

L
Liu Jicong 已提交
2597 2598
void setTagValue(SOperatorInfo* pOperatorInfo, void* pTable, SqlFunctionCtx* pCtx, int32_t numOfOutput) {
  SExprInfo* pExpr = pOperatorInfo->pExpr;
2599
  SExprInfo* pExprInfo = &pExpr[0];
L
Liu Jicong 已提交
2600
  int32_t    functionId = getExprFunctionId(pExprInfo);
2601
#if 0
2602 2603 2604
  if (pQueryAttr->numOfOutput == 1 && functionId == FUNCTION_TS_COMP && pQueryAttr->stableQuery) {
    assert(pExprInfo->base.numOfParams == 1);

L
Liu Jicong 已提交
2605
    //    int16_t      tagColId = (int16_t)pExprInfo->base.param[0].i;
H
Haojun Liao 已提交
2606
    int16_t      tagColId = -1;
2607 2608 2609
    SColumnInfo* pColInfo = doGetTagColumnInfoById(pQueryAttr->tagColList, pQueryAttr->numOfTags, tagColId);

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

2611 2612 2613 2614 2615 2616 2617 2618 2619
  } else {
    // set tag value, by which the results are aggregated.
    int32_t offset = 0;
    memset(pRuntimeEnv->tagVal, 0, pQueryAttr->tagLen);

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

      // ts_comp column required the tag value for join filter
H
Haojun Liao 已提交
2620
      if (!TSDB_COL_IS_TAG(pLocalExprInfo->base.pParam[0].pCol->flag)) {
2621 2622 2623 2624
        continue;
      }

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

L
Liu Jicong 已提交
2628 2629 2630
      if (IS_NUMERIC_TYPE(pLocalExprInfo->base.resSchema.type) ||
          pLocalExprInfo->base.resSchema.type == TSDB_DATA_TYPE_BOOL ||
          pLocalExprInfo->base.resSchema.type == TSDB_DATA_TYPE_TIMESTAMP) {
2631 2632 2633 2634
        memcpy(pRuntimeEnv->tagVal + offset, &pCtx[idx].tag.i, pLocalExprInfo->base.resSchema.bytes);
      } else {
        if (pCtx[idx].tag.pz != NULL) {
          memcpy(pRuntimeEnv->tagVal + offset, pCtx[idx].tag.pz, pCtx[idx].tag.nLen);
L
Liu Jicong 已提交
2635
        }
2636 2637 2638 2639 2640 2641 2642 2643 2644 2645
      }

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

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

H
Haojun Liao 已提交
2649
void copyToSDataBlock(SSDataBlock* pBlock, int32_t* offset, SGroupResInfo* pGroupResInfo, SDiskbasedBuf* pResBuf) {
2650 2651 2652 2653 2654 2655 2656
  pBlock->info.rows = 0;

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

L
Liu Jicong 已提交
2662
    //    doCopyToSDataBlock(pResBuf, pGroupResInfo, TSDB_ORDER_ASC, pBlock, );
2663 2664 2665 2666 2667 2668 2669 2670 2671 2672

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

    // enough results in data buffer, return
L
Liu Jicong 已提交
2673 2674 2675
    //    if (pBlock->info.rows >= threshold) {
    //      break;
    //    }
2676 2677 2678
  }
}

L
Liu Jicong 已提交
2679
static void updateTableQueryInfoForReverseScan(STableQueryInfo* pTableQueryInfo) {
2680 2681 2682 2683
  if (pTableQueryInfo == NULL) {
    return;
  }

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

L
Liu Jicong 已提交
2687 2688
  //  SWITCH_ORDER(pTableQueryInfo->cur.order);
  //  pTableQueryInfo->cur.vgroupIndex = -1;
2689 2690

  // set the index to be the end slot of result rows array
dengyihao's avatar
dengyihao 已提交
2691 2692 2693 2694 2695 2696
  //  SResultRowInfo* pResultRowInfo = &pTableQueryInfo->resInfo;
  //  if (pResultRowInfo->size > 0) {
  //    pResultRowInfo->curPos = pResultRowInfo->size - 1;
  //  } else {
  //    pResultRowInfo->curPos = -1;
  //  }
2697 2698
}

H
Haojun Liao 已提交
2699
void initResultRow(SResultRow* pResultRow) {
2700 2701 2702 2703 2704 2705
  pResultRow->pEntryInfo = (struct SResultRowEntryInfo*)((char*)pResultRow + sizeof(SResultRow));
}

/*
 * 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 已提交
2706 2707 2708
 * +------------+-----------------result column 1------------+------------------result column 2-----------+
 * | SResultRow | SResultRowEntryInfo | intermediate buffer1 | SResultRowEntryInfo | intermediate buffer 2|
 * +------------+--------------------------------------------+--------------------------------------------+
2709 2710
 *           offset[0]                                  offset[1]                                   offset[2]
 */
2711
// TODO refactor: some function move away
H
Haojun Liao 已提交
2712
void setFunctionResultOutput(SOptrBasicInfo* pInfo, SAggSupporter* pSup, int32_t stage, SExecTaskInfo* pTaskInfo) {
L
Liu Jicong 已提交
2713 2714 2715
  SqlFunctionCtx* pCtx = pInfo->pCtx;
  SSDataBlock*    pDataBlock = pInfo->pRes;
  int32_t*        rowCellInfoOffset = pInfo->rowCellInfoOffset;
H
Haojun Liao 已提交
2716

H
Haojun Liao 已提交
2717
  SResultRowInfo* pResultRowInfo = &pInfo->resultRowInfo;
H
Haojun Liao 已提交
2718
  initResultRowInfo(pResultRowInfo, 16);
H
Haojun Liao 已提交
2719

L
Liu Jicong 已提交
2720 2721
  int64_t     tid = 0;
  int64_t     groupId = 0;
2722
  SResultRow* pRow = doSetResultOutBufByKey(pSup->pResultBuf, pResultRowInfo, tid, (char*)&tid, sizeof(tid), true,
L
Liu Jicong 已提交
2723
                                            groupId, pTaskInfo, false, pSup);
H
Haojun Liao 已提交
2724 2725 2726 2727 2728

  for (int32_t i = 0; i < pDataBlock->info.numOfCols; ++i) {
    struct SResultRowEntryInfo* pEntry = getResultCell(pRow, i, rowCellInfoOffset);
    cleanupResultRowEntry(pEntry);

L
Liu Jicong 已提交
2729
    pCtx[i].resultInfo = pEntry;
H
Haojun Liao 已提交
2730 2731 2732
    pCtx[i].currentStage = stage;

    // set the timestamp output buffer for top/bottom/diff query
L
Liu Jicong 已提交
2733 2734
    //    int32_t fid = pCtx[i].functionId;
    //    if (fid == FUNCTION_TOP || fid == FUNCTION_BOTTOM || fid == FUNCTION_DIFF || fid == FUNCTION_DERIVATIVE) {
H
Haojun Liao 已提交
2735
    //      if (i > 0) pCtx[i].pTsOutput = pCtx[i-1].pOutput;
L
Liu Jicong 已提交
2736
    //    }
H
Haojun Liao 已提交
2737 2738 2739 2740 2741
  }

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

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

L
Liu Jicong 已提交
2745
  int32_t newSize = pDataBlock->info.rows + numOfInputRows + 5;  // extra output buffer
2746
  if ((*bufCapacity) < newSize) {
L
Liu Jicong 已提交
2747 2748
    for (int32_t i = 0; i < pDataBlock->info.numOfCols; ++i) {
      SColumnInfoData* pColInfo = taosArrayGet(pDataBlock->pDataBlock, i);
2749

wafwerar's avatar
wafwerar 已提交
2750
      char* p = taosMemoryRealloc(pColInfo->pData, newSize * pColInfo->info.bytes);
2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763
      if (p != NULL) {
        pColInfo->pData = p;

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

  for (int32_t i = 0; i < pDataBlock->info.numOfCols; ++i) {
L
Liu Jicong 已提交
2764
    SColumnInfoData* pColInfo = taosArrayGet(pDataBlock->pDataBlock, i);
2765 2766 2767 2768 2769
    pBInfo->pCtx[i].pOutput = pColInfo->pData + pColInfo->info.bytes * pDataBlock->info.rows;

    // set the correct pointer after the memory buffer reallocated.
    int32_t functionId = pBInfo->pCtx[i].functionId;

L
Liu Jicong 已提交
2770 2771
    if (functionId == FUNCTION_TOP || functionId == FUNCTION_BOTTOM || functionId == FUNCTION_DIFF ||
        functionId == FUNCTION_DERIVATIVE) {
dengyihao's avatar
dengyihao 已提交
2772
      //      if (i > 0) pBInfo->pCtx[i].pTsOutput = pBInfo->pCtx[i - 1].pOutput;
2773 2774 2775 2776
    }
  }
}

H
Haojun Liao 已提交
2777
void copyTsColoum(SSDataBlock* pRes, SqlFunctionCtx* pCtx, int32_t numOfOutput) {
2778 2779
  bool    needCopyTs = false;
  int32_t tsNum = 0;
L
Liu Jicong 已提交
2780
  char*   src = NULL;
2781 2782 2783 2784
  for (int32_t i = 0; i < numOfOutput; i++) {
    int32_t functionId = pCtx[i].functionId;
    if (functionId == FUNCTION_DIFF || functionId == FUNCTION_DERIVATIVE) {
      needCopyTs = true;
L
Liu Jicong 已提交
2785 2786
      if (i > 0 && pCtx[i - 1].functionId == FUNCTION_TS_DUMMY) {
        SColumnInfoData* pColRes = taosArrayGet(pRes->pDataBlock, i - 1);  // find ts data
2787 2788
        src = pColRes->pData;
      }
L
Liu Jicong 已提交
2789
    } else if (functionId == FUNCTION_TS_DUMMY) {
2790 2791 2792 2793 2794 2795 2796 2797 2798 2799
      tsNum++;
    }
  }

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

  for (int32_t i = 0; i < numOfOutput; i++) {
    int32_t functionId = pCtx[i].functionId;
L
Liu Jicong 已提交
2800
    if (functionId == FUNCTION_TS_DUMMY) {
2801 2802 2803 2804 2805 2806
      SColumnInfoData* pColRes = taosArrayGet(pRes->pDataBlock, i);
      memcpy(pColRes->pData, src, pColRes->info.bytes * pRes->info.rows);
    }
  }
}

H
Haojun Liao 已提交
2807
void initCtxOutputBuffer(SqlFunctionCtx* pCtx, int32_t size) {
2808 2809
  for (int32_t j = 0; j < size; ++j) {
    struct SResultRowEntryInfo* pResInfo = GET_RES_INFO(&pCtx[j]);
dengyihao's avatar
dengyihao 已提交
2810 2811
    if (isRowEntryInitialized(pResInfo) || fmIsPseudoColumnFunc(pCtx[j].functionId) || pCtx[j].functionId == -1 ||
        fmIsScalarFunc(pCtx[j].functionId)) {
2812 2813 2814
      continue;
    }

H
Haojun Liao 已提交
2815
    pCtx[j].fpSet.init(&pCtx[j], pCtx[j].resultInfo);
2816 2817 2818
  }
}

L
Liu Jicong 已提交
2819
void setTaskStatus(SExecTaskInfo* pTaskInfo, int8_t status) {
2820
  if (status == TASK_NOT_COMPLETED) {
H
Haojun Liao 已提交
2821
    pTaskInfo->status = status;
2822 2823
  } else {
    // QUERY_NOT_COMPLETED is not compatible with any other status, so clear its position first
2824
    CLEAR_QUERY_STATUS(pTaskInfo, TASK_NOT_COMPLETED);
H
Haojun Liao 已提交
2825
    pTaskInfo->status |= status;
2826 2827 2828
  }
}

2829
// todo merged with the build group result.
L
Liu Jicong 已提交
2830 2831
void finalizeMultiTupleQueryResult(SqlFunctionCtx* pCtx, int32_t numOfOutput, SDiskbasedBuf* pBuf,
                                   SResultRowInfo* pResultRowInfo, int32_t* rowCellInfoOffset) {
2832 2833 2834
  for (int32_t i = 0; i < pResultRowInfo->size; ++i) {
    SResultRowPosition* pPos = &pResultRowInfo->pPosition[i];

L
Liu Jicong 已提交
2835
    SFilePage*  bufPage = getBufPage(pBuf, pPos->pageId);
2836
    SResultRow* pRow = (SResultRow*)((char*)bufPage + pPos->offset);
H
Haojun Liao 已提交
2837 2838

    // TODO ignore the close status anyway.
dengyihao's avatar
dengyihao 已提交
2839 2840 2841
    //    if (!isResultRowClosed(pRow)) {
    //      continue;
    //    }
2842

2843
    for (int32_t j = 0; j < numOfOutput; ++j) {
2844 2845
      pCtx[j].resultInfo = getResultCell(pRow, j, rowCellInfoOffset);

H
Haojun Liao 已提交
2846
      struct SResultRowEntryInfo* pResInfo = pCtx[j].resultInfo;
H
Haojun Liao 已提交
2847
      if (!isRowEntryInitialized(pResInfo)) {
2848 2849 2850
        continue;
      }

H
Haojun Liao 已提交
2851
      if (pCtx[j].fpSet.process) {  // TODO set the dummy function, to avoid the check for null ptr.
dengyihao's avatar
dengyihao 已提交
2852
                                    //        pCtx[j].fpSet.finalize(&pCtx[j]);
H
Haojun Liao 已提交
2853
      }
2854 2855 2856 2857

      if (pRow->numOfRows < pResInfo->numOfRes) {
        pRow->numOfRows = pResInfo->numOfRes;
      }
2858
    }
2859 2860 2861

    releaseBufPage(pBuf, bufPage);
  }
2862 2863
}

2864
// todo merged with the build group result.
2865 2866 2867 2868 2869
void finalizeUpdatedResult(SqlFunctionCtx* pCtx, int32_t numOfOutput, SDiskbasedBuf* pBuf, SArray* pUpdateList,
                           int32_t* rowCellInfoOffset) {
  size_t num = taosArrayGetSize(pUpdateList);

  for (int32_t i = 0; i < num; ++i) {
L
Liu Jicong 已提交
2870
    SResKeyPos* pPos = taosArrayGetP(pUpdateList, i);
2871

2872 2873
    SFilePage*  bufPage = getBufPage(pBuf, pPos->pos.pageId);
    SResultRow* pRow = (SResultRow*)((char*)bufPage + pPos->pos.offset);
L
Liu Jicong 已提交
2874
    //
2875 2876
    for (int32_t j = 0; j < numOfOutput; ++j) {
      pCtx[j].resultInfo = getResultCell(pRow, j, rowCellInfoOffset);
L
Liu Jicong 已提交
2877
      //
2878
      struct SResultRowEntryInfo* pResInfo = pCtx[j].resultInfo;
L
Liu Jicong 已提交
2879 2880 2881 2882 2883 2884 2885 2886 2887
      //      if (isRowEntryCompleted(pResInfo) && isRowEntryInitialized(pResInfo)) {
      //        continue;
      //      }
      //
      //      if (pCtx[j].fpSet.process) {  // TODO set the dummy function.
      ////        pCtx[j].fpSet.finalize(&pCtx[j]);
      //        pResInfo->initialized = true;
      //      }
      //
2888 2889 2890 2891 2892 2893 2894 2895 2896
      if (pRow->numOfRows < pResInfo->numOfRes) {
        pRow->numOfRows = pResInfo->numOfRes;
      }
    }

    releaseBufPage(pBuf, bufPage);
  }
}

L
Liu Jicong 已提交
2897 2898
STableQueryInfo* createTableQueryInfo(void* buf, bool groupbyColumn, STimeWindow win) {
  STableQueryInfo* pTableQueryInfo = buf;
2899 2900 2901
  pTableQueryInfo->lastKey = win.skey;

  // set more initial size of interval/groupby query
L
Liu Jicong 已提交
2902 2903
  //  if (/*QUERY_IS_INTERVAL_QUERY(pQueryAttr) || */groupbyColumn) {
  int32_t initialSize = 128;
dengyihao's avatar
dengyihao 已提交
2904 2905 2906 2907
  //  int32_t code = initResultRowInfo(&pTableQueryInfo->resInfo, initialSize);
  //  if (code != TSDB_CODE_SUCCESS) {
  //    return NULL;
  //  }
L
Liu Jicong 已提交
2908 2909
  //  } else { // in other aggregate query, do not initialize the windowResInfo
  //  }
2910 2911 2912 2913

  return pTableQueryInfo;
}

L
Liu Jicong 已提交
2914
void destroyTableQueryInfoImpl(STableQueryInfo* pTableQueryInfo) {
2915 2916 2917 2918
  if (pTableQueryInfo == NULL) {
    return;
  }

L
Liu Jicong 已提交
2919
  //  taosVariantDestroy(&pTableQueryInfo->tag);
dengyihao's avatar
dengyihao 已提交
2920
  //  cleanupResultRowInfo(&pTableQueryInfo->resInfo);
2921 2922
}

dengyihao's avatar
dengyihao 已提交
2923 2924
void setResultRowOutputBufInitCtx_rv(SResultRow* pResult, SqlFunctionCtx* pCtx, int32_t numOfOutput,
                                     int32_t* rowCellInfoOffset) {
2925 2926 2927 2928 2929 2930 2931
  for (int32_t i = 0; i < numOfOutput; ++i) {
    pCtx[i].resultInfo = getResultCell(pResult, i, rowCellInfoOffset);

    struct SResultRowEntryInfo* pResInfo = pCtx[i].resultInfo;
    if (isRowEntryCompleted(pResInfo) && isRowEntryInitialized(pResInfo)) {
      continue;
    }
2932 2933 2934 2935 2936

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

2937 2938 2939 2940 2941 2942
    if (!pResInfo->initialized) {
      if (pCtx[i].functionId != -1) {
        pCtx[i].fpSet.init(&pCtx[i], pResInfo);
      } else {
        pResInfo->initialized = true;
      }
2943 2944 2945 2946
    }
  }
}

2947 2948 2949 2950 2951 2952
void doFilter(const SNode* pFilterNode, SSDataBlock* pBlock) {
  if (pFilterNode == NULL) {
    return;
  }

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

H
Haojun Liao 已提交
2954
  // todo move to the initialization function
H
Haojun Liao 已提交
2955
  int32_t code = filterInitFromNode((SNode*)pFilterNode, &filter, 0);
2956 2957 2958 2959 2960 2961

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

  int8_t* rowRes = NULL;
  bool    keep = filterExecute(filter, pBlock, &rowRes, NULL, param1.numOfCols);
D
dapan1121 已提交
2962
  filterFreeInfo(filter);
2963

2964
  SSDataBlock* px = createOneDataBlock(pBlock, false);
2965 2966
  blockDataEnsureCapacity(px, pBlock->info.rows);

H
Haojun Liao 已提交
2967
  // todo extract method
2968 2969 2970 2971
  int32_t numOfRow = 0;
  for (int32_t i = 0; i < pBlock->info.numOfCols; ++i) {
    SColumnInfoData* pDst = taosArrayGet(px->pDataBlock, i);
    SColumnInfoData* pSrc = taosArrayGet(pBlock->pDataBlock, i);
D
dapan1121 已提交
2972 2973 2974 2975 2976 2977 2978 2979 2980
    if (keep) {
      colDataAssign(pDst, pSrc, pBlock->info.rows);
      numOfRow = pBlock->info.rows;
    } else if (NULL != rowRes) {
      numOfRow = 0;
      for (int32_t j = 0; j < pBlock->info.rows; ++j) {
        if (rowRes[j] == 0) {
          continue;
        }
2981

D
dapan1121 已提交
2982 2983 2984 2985 2986 2987
        if (colDataIsNull_s(pSrc, j)) {
          colDataAppendNULL(pDst, numOfRow);
        } else {
          colDataAppend(pDst, numOfRow, colDataGetData(pSrc, j), false);
        }
        numOfRow += 1;
H
Haojun Liao 已提交
2988
      }
D
dapan1121 已提交
2989 2990
    } else {
      numOfRow = 0;
2991 2992 2993 2994 2995 2996
    }

    *pSrc = *pDst;
  }

  pBlock->info.rows = numOfRow;
2997
  blockDataUpdateTsWindow(pBlock);
2998 2999
}

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

3005 3006
  SResultRowInfo* pResultRowInfo = &pAggInfo->binfo.resultRowInfo;
  SqlFunctionCtx* pCtx = pAggInfo->binfo.pCtx;
L
Liu Jicong 已提交
3007
  int32_t*        rowCellInfoOffset = pAggInfo->binfo.rowCellInfoOffset;
3008

L
Liu Jicong 已提交
3009 3010
  SResultRow* pResultRow = doSetResultOutBufByKey(pAggInfo->aggSup.pResultBuf, pResultRowInfo, uid, (char*)&groupId,
                                                  sizeof(groupId), true, groupId, pTaskInfo, false, &pAggInfo->aggSup);
L
Liu Jicong 已提交
3011
  assert(pResultRow != NULL);
3012 3013 3014 3015 3016 3017

  /*
   * 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 已提交
3018 3019
    int32_t ret =
        addNewWindowResultBuf(pResultRow, pAggInfo->aggSup.pResultBuf, groupId, pAggInfo->binfo.pRes->info.rowSize);
3020 3021 3022 3023 3024
    if (ret != TSDB_CODE_SUCCESS) {
      return;
    }
  }

H
Haojun Liao 已提交
3025
  setResultRowOutputBufInitCtx_rv(pResultRow, pCtx, numOfOutput, rowCellInfoOffset);
3026 3027
}

H
Haojun Liao 已提交
3028 3029
void setExecutionContext(int32_t numOfOutput, uint64_t groupId, SExecTaskInfo* pTaskInfo, SAggOperatorInfo* pAggInfo) {
  if (pAggInfo->groupId != INT32_MIN && pAggInfo->groupId == groupId) {
3030 3031 3032
    return;
  }

H
Haojun Liao 已提交
3033
  doSetTableGroupOutputBuf(pAggInfo, numOfOutput, groupId, pTaskInfo);
3034 3035

  // record the current active group id
H
Haojun Liao 已提交
3036
  pAggInfo->groupId = groupId;
3037 3038 3039 3040 3041
}

/*
 * There are two cases to handle:
 *
L
Liu Jicong 已提交
3042 3043
 * 1. Query range is not set yet (queryRangeSet = 0). we need to set the query range info, including
 * pQueryAttr->lastKey, pQueryAttr->window.skey, and pQueryAttr->eKey.
3044 3045 3046 3047
 * 2. Query range is set and query is in progress. There may be another result with the same query ranges to be
 *    merged during merge stage. In this case, we need the pTableQueryInfo->lastResRows to decide if there
 *    is a previous result generated or not.
 */
3048
void setIntervalQueryRange(STableQueryInfo* pTableQueryInfo, TSKEY key, STimeWindow* pQRange) {
dengyihao's avatar
dengyihao 已提交
3049 3050 3051 3052
  //  SResultRowInfo*  pResultRowInfo = &pTableQueryInfo->resInfo;
  //  if (pResultRowInfo->curPos != -1) {
  //    return;
  //  }
3053

dengyihao's avatar
dengyihao 已提交
3054 3055
  //  pTableQueryInfo->win.skey = key;
  //  STimeWindow win = {.skey = key, .ekey = pQRange->ekey};
3056 3057 3058 3059 3060 3061 3062

  /**
   * In handling the both ascending and descending order super table query, we need to find the first qualified
   * timestamp of this table, and then set the first qualified start timestamp.
   * In ascending query, the key is the first qualified timestamp. However, in the descending order query, additional
   * operations involve.
   */
dengyihao's avatar
dengyihao 已提交
3063 3064 3065 3066
  //  STimeWindow w = TSWINDOW_INITIALIZER;
  //
  //  TSKEY sk = TMIN(win.skey, win.ekey);
  //  TSKEY ek = TMAX(win.skey, win.ekey);
L
Liu Jicong 已提交
3067
  //  getAlignQueryTimeWindow(pQueryAttr, win.skey, sk, ek, &w);
3068

L
Liu Jicong 已提交
3069 3070 3071 3072 3073 3074 3075
  //  if (pResultRowInfo->prevSKey == TSKEY_INITIAL_VAL) {
  //    if (!QUERY_IS_ASC_QUERY(pQueryAttr)) {
  //      assert(win.ekey == pQueryAttr->window.ekey);
  //    }
  //
  //    pResultRowInfo->prevSKey = w.skey;
  //  }
3076

L
Liu Jicong 已提交
3077
  //  pTableQueryInfo->lastKey = pTableQueryInfo->win.skey;
3078 3079 3080 3081 3082 3083 3084 3085 3086 3087
}

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

  int32_t start = 0;
  int32_t step = -1;

L
Liu Jicong 已提交
3096
  // qDebug("QInfo:0x%"PRIx64" start to copy data from windowResInfo to output buf", GET_TASKID(pRuntimeEnv));
3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107
  assert(orderType == TSDB_ORDER_ASC || orderType == TSDB_ORDER_DESC);

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

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

3111
    SResultRow* pRow = (SResultRow*)((char*)page + pPos->pos.offset);
3112 3113 3114 3115 3116
    if (pRow->numOfRows == 0) {
      pGroupResInfo->index += 1;
      continue;
    }

3117
    // TODO copy multiple rows?
3118
    int32_t numOfRowsToCopy = pRow->numOfRows;
3119
    if (numOfResult + numOfRowsToCopy >= pBlock->info.capacity) {
3120 3121 3122 3123 3124 3125
      break;
    }

    pGroupResInfo->index += 1;

    for (int32_t j = 0; j < pBlock->info.numOfCols; ++j) {
3126 3127
      int32_t slotId = pExprInfo[j].base.resSchema.slotId;

3128 3129
      pCtx[j].resultInfo = getResultCell(pRow, j, rowCellOffset);
      if (pCtx[j].fpSet.process) {
3130
        pCtx[j].fpSet.finalize(&pCtx[j], pBlock);
3131 3132
      } else {
        SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, slotId);
3133

3134 3135 3136
        char* in = GET_ROWCELL_INTERBUF(pCtx[j].resultInfo);
        colDataAppend(pColInfoData, pBlock->info.rows, in, pCtx[j].resultInfo->isNullRes);
      }
3137 3138
    }

3139 3140
    releaseBufPage(pBuf, page);

3141 3142
    pBlock->info.rows += pRow->numOfRows;
    if (pBlock->info.rows >= pBlock->info.capacity) {  // output buffer is full
3143 3144 3145 3146
      break;
    }
  }

L
Liu Jicong 已提交
3147
  // qDebug("QInfo:0x%"PRIx64" copy data to query buf completed", GET_TASKID(pRuntimeEnv));
3148
  blockDataUpdateTsWindow(pBlock);
3149 3150 3151
  return 0;
}

dengyihao's avatar
dengyihao 已提交
3152 3153
void doBuildResultDatablock(SSDataBlock* pBlock, SGroupResInfo* pGroupResInfo, SExprInfo* pExprInfo,
                            SDiskbasedBuf* pBuf, int32_t* rowCellOffset, SqlFunctionCtx* pCtx) {
3154 3155
  assert(pGroupResInfo->currentGroup <= pGroupResInfo->totalGroup);

3156
  blockDataCleanup(pBlock);
3157 3158 3159 3160
  if (!hasRemainDataInCurrentGroup(pGroupResInfo)) {
    return;
  }

3161
  int32_t orderType = TSDB_ORDER_ASC;
3162
  doCopyToSDataBlock(pBlock, pExprInfo, pBuf, pGroupResInfo, orderType, rowCellOffset, pCtx);
3163

H
Haojun Liao 已提交
3164 3165
  // add condition (pBlock->info.rows >= 1) just to runtime happy
  blockDataUpdateTsWindow(pBlock);
3166 3167
}

L
Liu Jicong 已提交
3168 3169
static void updateNumOfRowsInResultRows(SqlFunctionCtx* pCtx, int32_t numOfOutput, SResultRowInfo* pResultRowInfo,
                                        int32_t* rowCellInfoOffset) {
3170
  // update the number of result for each, only update the number of rows for the corresponding window result.
L
Liu Jicong 已提交
3171 3172 3173
  //  if (QUERY_IS_INTERVAL_QUERY(pQueryAttr)) {
  //    return;
  //  }
H
Haojun Liao 已提交
3174
#if 0
3175
  for (int32_t i = 0; i < pResultRowInfo->size; ++i) {
L
Liu Jicong 已提交
3176
    SResultRow* pResult = pResultRowInfo->pResult[i];
3177 3178 3179 3180 3181 3182 3183

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

3184 3185
      SResultRowEntryInfo* pCell = getResultCell(pResult, j, rowCellInfoOffset);
      pResult->numOfRows = (uint16_t)(TMAX(pResult->numOfRows, pCell->numOfRes));
3186 3187
    }
  }
H
Haojun Liao 已提交
3188
#endif
3189 3190
}

L
Liu Jicong 已提交
3191
static int32_t compressQueryColData(SColumnInfoData* pColRes, int32_t numOfRows, char* data, int8_t compressed) {
3192 3193
  int32_t colSize = pColRes->info.bytes * numOfRows;
  return (*(tDataTypes[pColRes->info.type].compFunc))(pColRes->pData, colSize, numOfRows, data,
L
Liu Jicong 已提交
3194
                                                      colSize + COMP_OVERFLOW_BYTES, compressed, NULL, 0);
3195 3196
}

L
Liu Jicong 已提交
3197 3198 3199 3200 3201
int32_t doFillTimeIntervalGapsInResults(struct SFillInfo* pFillInfo, SSDataBlock* pOutput, int32_t capacity, void** p) {
  //  for(int32_t i = 0; i < pFillInfo->numOfCols; ++i) {
  //    SColumnInfoData* pColInfoData = taosArrayGet(pOutput->pDataBlock, i);
  //    p[i] = pColInfoData->pData + (pColInfoData->info.bytes * pOutput->info.rows);
  //  }
3202 3203 3204 3205 3206 3207 3208

  int32_t numOfRows = (int32_t)taosFillResultDataBlock(pFillInfo, p, capacity - pOutput->info.rows);
  pOutput->info.rows += numOfRows;

  return pOutput->info.rows;
}

3209
void publishOperatorProfEvent(SOperatorInfo* pOperator, EQueryProfEventType eventType) {
3210 3211
  SQueryProfEvent event = {0};

L
Liu Jicong 已提交
3212 3213
  event.eventType = eventType;
  event.eventTime = taosGetTimestampUs();
3214
  event.operatorType = pOperator->operatorType;
dengyihao's avatar
dengyihao 已提交
3215 3216 3217
  //    if (pQInfo->summary.queryProfEvents) {
  //      taosArrayPush(pQInfo->summary.queryProfEvents, &event);
  //    }
3218 3219
}

L
Liu Jicong 已提交
3220
void publishQueryAbortEvent(SExecTaskInfo* pTaskInfo, int32_t code) {
3221 3222 3223 3224 3225
  SQueryProfEvent event;
  event.eventType = QUERY_PROF_QUERY_ABORT;
  event.eventTime = taosGetTimestampUs();
  event.abortCode = code;

3226 3227
  if (pTaskInfo->cost.queryProfEvents) {
    taosArrayPush(pTaskInfo->cost.queryProfEvents, &event);
3228 3229 3230
  }
}

L
Liu Jicong 已提交
3231
typedef struct {
3232 3233 3234 3235 3236 3237 3238
  uint8_t operatorType;
  int64_t beginTime;
  int64_t endTime;
  int64_t selfTime;
  int64_t descendantsTime;
} SOperatorStackItem;

L
Liu Jicong 已提交
3239 3240
static void doOperatorExecProfOnce(SOperatorStackItem* item, SQueryProfEvent* event, SArray* opStack,
                                   SHashObj* profResults) {
3241 3242 3243 3244 3245 3246 3247 3248
  item->endTime = event->eventTime;
  item->selfTime = (item->endTime - item->beginTime) - (item->descendantsTime);

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

L
Liu Jicong 已提交
3249
  uint8_t              operatorType = item->operatorType;
3250 3251 3252 3253 3254 3255 3256 3257 3258
  SOperatorProfResult* result = taosHashGet(profResults, &operatorType, sizeof(operatorType));
  if (result != NULL) {
    result->sumRunTimes++;
    result->sumSelfTime += item->selfTime;
  } else {
    SOperatorProfResult opResult;
    opResult.operatorType = operatorType;
    opResult.sumSelfTime = item->selfTime;
    opResult.sumRunTimes = 1;
L
Liu Jicong 已提交
3259
    taosHashPut(profResults, &(operatorType), sizeof(operatorType), &opResult, sizeof(opResult));
3260 3261 3262
  }
}

3263
void calculateOperatorProfResults(void) {
dengyihao's avatar
dengyihao 已提交
3264 3265 3266 3267 3268 3269 3270 3271 3272
  //  if (pQInfo->summary.queryProfEvents == NULL) {
  //    // qDebug("QInfo:0x%"PRIx64" query prof events array is null", pQInfo->qId);
  //    return;
  //  }
  //
  //  if (pQInfo->summary.operatorProfResults == NULL) {
  //    // qDebug("QInfo:0x%"PRIx64" operator prof results hash is null", pQInfo->qId);
  //    return;
  //  }
3273 3274 3275 3276 3277

  SArray* opStack = taosArrayInit(32, sizeof(SOperatorStackItem));
  if (opStack == NULL) {
    return;
  }
3278
#if 0
L
Liu Jicong 已提交
3279
  size_t    size = taosArrayGetSize(pQInfo->summary.queryProfEvents);
3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300
  SHashObj* profResults = pQInfo->summary.operatorProfResults;

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

L
Liu Jicong 已提交
3305 3306
void queryCostStatis(SExecTaskInfo* pTaskInfo) {
  STaskCostInfo* pSummary = &pTaskInfo->cost;
3307

L
Liu Jicong 已提交
3308 3309 3310
  //  uint64_t hashSize = taosHashGetMemSize(pQInfo->runtimeEnv.pResultRowHashTable);
  //  hashSize += taosHashGetMemSize(pRuntimeEnv->tableqinfoGroupInfo.map);
  //  pSummary->hashSize = hashSize;
3311 3312 3313 3314

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

L
Liu Jicong 已提交
3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334
  //  SResultRowPool* p = pTaskInfo->pool;
  //  if (p != NULL) {
  //    pSummary->winInfoSize = getResultRowPoolMemSize(p);
  //    pSummary->numOfTimeWindows = getNumOfAllocatedResultRows(p);
  //  } else {
  //    pSummary->winInfoSize = 0;
  //    pSummary->numOfTimeWindows = 0;
  //  }
  //
  //  calculateOperatorProfResults(pQInfo);

  qDebug("%s :cost summary: elapsed time:%" PRId64 " us, first merge:%" PRId64
         " us, total blocks:%d, "
         "load block statis:%d, load data block:%d, total rows:%" PRId64 ", check rows:%" PRId64,
         GET_TASKID(pTaskInfo), pSummary->elapsedTime, pSummary->firstStageMergeTime, pSummary->totalBlocks,
         pSummary->loadBlockStatis, pSummary->loadBlocks, pSummary->totalRows, pSummary->totalCheckedRows);
  //
  // 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);
3335 3336 3337 3338

  if (pSummary->operatorProfResults) {
    SOperatorProfResult* opRes = taosHashIterate(pSummary->operatorProfResults, NULL);
    while (opRes != NULL) {
L
Liu Jicong 已提交
3339 3340
      // qDebug("QInfo:0x%" PRIx64 " :cost summary: operator : %d, exec times: %" PRId64 ", self time: %" PRId64,
      //             pQInfo->qId, opRes->operatorType, opRes->sumRunTimes, opRes->sumSelfTime);
3341 3342 3343 3344 3345
      opRes = taosHashIterate(pSummary->operatorProfResults, opRes);
    }
  }
}

L
Liu Jicong 已提交
3346 3347 3348
// static void updateOffsetVal(STaskRuntimeEnv *pRuntimeEnv, SDataBlockInfo *pBlockInfo) {
//   STaskAttr *pQueryAttr = pRuntimeEnv->pQueryAttr;
//   STableQueryInfo* pTableQueryInfo = pRuntimeEnv->current;
3349
//
L
Liu Jicong 已提交
3350
//   int32_t step = GET_FORWARD_DIRECTION_FACTOR(pQueryAttr->order.order);
3351
//
L
Liu Jicong 已提交
3352 3353 3354 3355
//   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;
//   }
3356
//
L
Liu Jicong 已提交
3357 3358 3359 3360 3361
//   if (QUERY_IS_ASC_QUERY(pQueryAttr)) {
//     pQueryAttr->pos = (int32_t)pQueryAttr->limit.offset;
//   } else {
//     pQueryAttr->pos = pBlockInfo->rows - (int32_t)pQueryAttr->limit.offset - 1;
//   }
3362
//
L
Liu Jicong 已提交
3363
//   assert(pQueryAttr->pos >= 0 && pQueryAttr->pos <= pBlockInfo->rows - 1);
3364
//
L
Liu Jicong 已提交
3365 3366
//   SArray *         pDataBlock = tsdbRetrieveDataBlock(pRuntimeEnv->pTsdbReadHandle, NULL);
//   SColumnInfoData *pColInfoData = taosArrayGet(pDataBlock, 0);
3367
//
L
Liu Jicong 已提交
3368 3369
//   // update the pQueryAttr->limit.offset value, and pQueryAttr->pos value
//   TSKEY *keys = (TSKEY *) pColInfoData->pData;
3370
//
L
Liu Jicong 已提交
3371 3372 3373
//   // update the offset value
//   pTableQueryInfo->lastKey = keys[pQueryAttr->pos];
//   pQueryAttr->limit.offset = 0;
3374
//
L
Liu Jicong 已提交
3375
//   int32_t numOfRes = tableApplyFunctionsOnBlock(pRuntimeEnv, pBlockInfo, NULL, binarySearchForKey, pDataBlock);
3376
//
L
Liu Jicong 已提交
3377 3378 3379 3380
//   //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);
// }
3381

L
Liu Jicong 已提交
3382 3383
// void skipBlocks(STaskRuntimeEnv *pRuntimeEnv) {
//   STaskAttr *pQueryAttr = pRuntimeEnv->pQueryAttr;
3384
//
L
Liu Jicong 已提交
3385 3386 3387
//   if (pQueryAttr->limit.offset <= 0 || pQueryAttr->numOfFilterCols > 0) {
//     return;
//   }
3388
//
L
Liu Jicong 已提交
3389 3390
//   pQueryAttr->pos = 0;
//   int32_t step = GET_FORWARD_DIRECTION_FACTOR(pQueryAttr->order.order);
3391
//
L
Liu Jicong 已提交
3392 3393
//   STableQueryInfo* pTableQueryInfo = pRuntimeEnv->current;
//   TsdbQueryHandleT pTsdbReadHandle = pRuntimeEnv->pTsdbReadHandle;
3394
//
L
Liu Jicong 已提交
3395 3396 3397 3398 3399
//   SDataBlockInfo blockInfo = SDATA_BLOCK_INITIALIZER;
//   while (tsdbNextDataBlock(pTsdbReadHandle)) {
//     if (isTaskKilled(pRuntimeEnv->qinfo)) {
//       longjmp(pRuntimeEnv->env, TSDB_CODE_TSC_QUERY_CANCELLED);
//     }
3400
//
L
Liu Jicong 已提交
3401
//     tsdbRetrieveDataBlockInfo(pTsdbReadHandle, &blockInfo);
3402
//
L
Liu Jicong 已提交
3403 3404 3405 3406
//     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;
3407
//
L
Liu Jicong 已提交
3408 3409 3410 3411 3412 3413 3414
//       //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;
//     }
//   }
3415
//
L
Liu Jicong 已提交
3416 3417 3418 3419 3420 3421 3422 3423 3424
//   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;
3425
//
L
Liu Jicong 已提交
3426 3427 3428
//   assert(pQueryAttr->limit.offset == 0);
//   STimeWindow tw = *win;
//   getNextTimeWindow(pQueryAttr, &tw);
3429
//
L
Liu Jicong 已提交
3430 3431
//   if ((tw.skey <= pBlockInfo->window.ekey && QUERY_IS_ASC_QUERY(pQueryAttr)) ||
//       (tw.ekey >= pBlockInfo->window.skey && !QUERY_IS_ASC_QUERY(pQueryAttr))) {
3432
//
L
Liu Jicong 已提交
3433 3434 3435 3436
//     // 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);
3437
//
L
Liu Jicong 已提交
3438 3439 3440 3441
//     tw = *win;
//     int32_t startPos =
//         getNextQualifiedWindow(pQueryAttr, &tw, pBlockInfo, pColInfoData->pData, binarySearchForKey, -1);
//     assert(startPos >= 0);
3442
//
L
Liu Jicong 已提交
3443 3444
//     // set the abort info
//     pQueryAttr->pos = startPos;
3445
//
L
Liu Jicong 已提交
3446 3447 3448 3449
//     // reset the query start timestamp
//     pTableQueryInfo->win.skey = ((TSKEY *)pColInfoData->pData)[startPos];
//     pQueryAttr->window.skey = pTableQueryInfo->win.skey;
//     TSKEY key = pTableQueryInfo->win.skey;
3450
//
L
Liu Jicong 已提交
3451 3452
//     pWindowResInfo->prevSKey = tw.skey;
//     int32_t index = pRuntimeEnv->resultRowInfo.curIndex;
3453
//
L
Liu Jicong 已提交
3454 3455
//     int32_t numOfRes = tableApplyFunctionsOnBlock(pRuntimeEnv, pBlockInfo, NULL, binarySearchForKey, pDataBlock);
//     pRuntimeEnv->resultRowInfo.curIndex = index;  // restore the window index
3456
//
L
Liu Jicong 已提交
3457 3458 3459 3460
//     //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);
3461
//
L
Liu Jicong 已提交
3462 3463 3464 3465 3466
//     return key;
//   } else {  // do nothing
//     pQueryAttr->window.skey      = tw.skey;
//     pWindowResInfo->prevSKey = tw.skey;
//     pTableQueryInfo->lastKey = tw.skey;
3467
//
L
Liu Jicong 已提交
3468 3469
//     return tw.skey;
//   }
3470
//
L
Liu Jicong 已提交
3471 3472 3473 3474 3475 3476 3477 3478 3479 3480
//   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);
//   }
3481
//
L
Liu Jicong 已提交
3482 3483 3484 3485 3486
//   // 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;
//   }
3487
//
L
Liu Jicong 已提交
3488 3489 3490 3491 3492 3493 3494
//   /*
//    * 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);
3495
//
L
Liu Jicong 已提交
3496 3497
//   STimeWindow w = TSWINDOW_INITIALIZER;
//   bool ascQuery = QUERY_IS_ASC_QUERY(pQueryAttr);
3498
//
L
Liu Jicong 已提交
3499 3500
//   SResultRowInfo *pWindowResInfo = &pRuntimeEnv->resultRowInfo;
//   STableQueryInfo *pTableQueryInfo = pRuntimeEnv->current;
3501
//
L
Liu Jicong 已提交
3502 3503 3504
//   SDataBlockInfo blockInfo = SDATA_BLOCK_INITIALIZER;
//   while (tsdbNextDataBlock(pRuntimeEnv->pTsdbReadHandle)) {
//     tsdbRetrieveDataBlockInfo(pRuntimeEnv->pTsdbReadHandle, &blockInfo);
3505
//
L
Liu Jicong 已提交
3506 3507 3508 3509 3510 3511 3512 3513 3514
//     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;
//     }
3515
//
L
Liu Jicong 已提交
3516 3517
//     // the first time window
//     STimeWindow win = getActiveTimeWindow(pWindowResInfo, pWindowResInfo->prevSKey, pQueryAttr);
3518
//
L
Liu Jicong 已提交
3519 3520
//     while (pQueryAttr->limit.offset > 0) {
//       STimeWindow tw = win;
3521
//
L
Liu Jicong 已提交
3522 3523 3524
//       if ((win.ekey <= blockInfo.window.ekey && ascQuery) || (win.ekey >= blockInfo.window.skey && !ascQuery)) {
//         pQueryAttr->limit.offset -= 1;
//         pWindowResInfo->prevSKey = win.skey;
3525
//
L
Liu Jicong 已提交
3526 3527 3528 3529 3530 3531
//         // 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;
//         }
//       }
3532
//
L
Liu Jicong 已提交
3533 3534 3535 3536
//       if (pQueryAttr->limit.offset == 0) {
//         *start = doSkipIntervalProcess(pRuntimeEnv, &win, &blockInfo, pTableQueryInfo);
//         return true;
//       }
3537
//
L
Liu Jicong 已提交
3538 3539
//       // current window does not ended in current data block, try next data block
//       getNextTimeWindow(pQueryAttr, &tw);
3540
//
L
Liu Jicong 已提交
3541 3542 3543 3544 3545 3546 3547 3548 3549
//       /*
//        * 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)) {
3550
//
L
Liu Jicong 已提交
3551 3552
//         SArray *pDataBlock = tsdbRetrieveDataBlock(pRuntimeEnv->pTsdbReadHandle, NULL);
//         SColumnInfoData *pColInfoData = taosArrayGet(pDataBlock, 0);
3553
//
L
Liu Jicong 已提交
3554 3555 3556
//         if ((win.ekey > blockInfo.window.ekey && ascQuery) || (win.ekey < blockInfo.window.skey && !ascQuery)) {
//           pQueryAttr->limit.offset -= 1;
//         }
3557
//
L
Liu Jicong 已提交
3558 3559 3560 3561 3562 3563 3564 3565
//         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);
3566
//
L
Liu Jicong 已提交
3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577
//           // 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.
//       }
//     }
//   }
3578
//
L
Liu Jicong 已提交
3579 3580 3581 3582
//   // check for error
//   if (terrno != TSDB_CODE_SUCCESS) {
//     longjmp(pRuntimeEnv->env, terrno);
//   }
3583
//
L
Liu Jicong 已提交
3584 3585
//   return true;
// }
3586

3587
int32_t appendDownstream(SOperatorInfo* p, SOperatorInfo** pDownstream, int32_t num) {
H
Haojun Liao 已提交
3588
  if (p->pDownstream == NULL) {
H
Haojun Liao 已提交
3589
    assert(p->numOfDownstream == 0);
3590 3591
  }

wafwerar's avatar
wafwerar 已提交
3592
  p->pDownstream = taosMemoryCalloc(1, num * POINTER_BYTES);
3593 3594 3595 3596 3597 3598 3599
  if (p->pDownstream == NULL) {
    return TSDB_CODE_OUT_OF_MEMORY;
  }

  memcpy(p->pDownstream, pDownstream, num * POINTER_BYTES);
  p->numOfDownstream = num;
  return TSDB_CODE_SUCCESS;
3600 3601 3602 3603
}

static void doDestroyTableQueryInfo(STableGroupInfo* pTableqinfoGroupInfo);

3604
static void doTableQueryInfoTimeWindowCheck(SExecTaskInfo* pTaskInfo, STableQueryInfo* pTableQueryInfo, int32_t order) {
H
Haojun Liao 已提交
3605 3606
#if 0
    if (order == TSDB_ORDER_ASC) {
3607 3608
    assert(
        (pTableQueryInfo->win.skey <= pTableQueryInfo->win.ekey) &&
H
Haojun Liao 已提交
3609 3610
        (pTableQueryInfo->lastKey >= pTaskInfo->window.skey) &&
        (pTableQueryInfo->win.skey >= pTaskInfo->window.skey && pTableQueryInfo->win.ekey <= pTaskInfo->window.ekey));
3611 3612 3613
  } else {
    assert(
        (pTableQueryInfo->win.skey >= pTableQueryInfo->win.ekey) &&
H
Haojun Liao 已提交
3614 3615
        (pTableQueryInfo->lastKey <= pTaskInfo->window.skey) &&
        (pTableQueryInfo->win.skey <= pTaskInfo->window.skey && pTableQueryInfo->win.ekey >= pTaskInfo->window.ekey));
3616
  }
H
Haojun Liao 已提交
3617
#endif
3618 3619
}

3620 3621
// SQueryTableDataCond createTsdbQueryCond(STaskAttr* pQueryAttr, STimeWindow* win) {
//   SQueryTableDataCond cond = {
L
Liu Jicong 已提交
3622 3623 3624 3625 3626 3627
//       .colList   = pQueryAttr->tableCols,
//       .order     = pQueryAttr->order.order,
//       .numOfCols = pQueryAttr->numOfCols,
//       .type      = BLOCK_LOAD_OFFSET_SEQ_ORDER,
//       .loadExternalRows = false,
//   };
3628
//
L
Liu Jicong 已提交
3629 3630 3631
//   TIME_WINDOW_COPY(cond.twindow, *win);
//   return cond;
// }
3632 3633 3634

static STableIdInfo createTableIdInfo(STableQueryInfo* pTableQueryInfo) {
  STableIdInfo tidInfo;
L
Liu Jicong 已提交
3635 3636 3637 3638 3639
  //  STableId* id = TSDB_TABLEID(pTableQueryInfo->pTable);
  //
  //  tidInfo.uid = id->uid;
  //  tidInfo.tid = id->tid;
  //  tidInfo.key = pTableQueryInfo->lastKey;
3640 3641 3642 3643

  return tidInfo;
}

L
Liu Jicong 已提交
3644 3645 3646 3647
// static void updateTableIdInfo(STableQueryInfo* pTableQueryInfo, SSDataBlock* pBlock, SHashObj* pTableIdInfo, int32_t
// order) {
//   int32_t step = GET_FORWARD_DIRECTION_FACTOR(order);
//   pTableQueryInfo->lastKey = ((order == TSDB_ORDER_ASC)? pBlock->info.window.ekey:pBlock->info.window.skey) + step;
3648
//
L
Liu Jicong 已提交
3649 3650 3651
//   if (pTableQueryInfo->pTable == NULL) {
//     return;
//   }
3652
//
L
Liu Jicong 已提交
3653 3654 3655 3656 3657 3658 3659 3660 3661
//   STableIdInfo tidInfo = createTableIdInfo(pTableQueryInfo);
//   STableIdInfo *idinfo = taosHashGet(pTableIdInfo, &tidInfo.tid, sizeof(tidInfo.tid));
//   if (idinfo != NULL) {
//     assert(idinfo->tid == tidInfo.tid && idinfo->uid == tidInfo.uid);
//     idinfo->key = tidInfo.key;
//   } else {
//     taosHashPut(pTableIdInfo, &tidInfo.tid, sizeof(tidInfo.tid), &tidInfo, sizeof(STableIdInfo));
//   }
// }
3662

3663
int32_t loadRemoteDataCallback(void* param, const SDataBuf* pMsg, int32_t code) {
L
Liu Jicong 已提交
3664
  SSourceDataInfo* pSourceDataInfo = (SSourceDataInfo*)param;
H
Haojun Liao 已提交
3665 3666
  if (code == TSDB_CODE_SUCCESS) {
    pSourceDataInfo->pRsp = pMsg->pData;
3667

H
Haojun Liao 已提交
3668 3669
    SRetrieveTableRsp* pRsp = pSourceDataInfo->pRsp;
    pRsp->numOfRows = htonl(pRsp->numOfRows);
dengyihao's avatar
dengyihao 已提交
3670 3671
    pRsp->compLen = htonl(pRsp->compLen);
    pRsp->useconds = htobe64(pRsp->useconds);
H
Haojun Liao 已提交
3672 3673 3674
  } else {
    pSourceDataInfo->code = code;
  }
H
Haojun Liao 已提交
3675

H
Haojun Liao 已提交
3676
  pSourceDataInfo->status = EX_SOURCE_DATA_READY;
3677
  tsem_post(&pSourceDataInfo->pEx->ready);
wmmhello's avatar
wmmhello 已提交
3678
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
3679 3680 3681 3682
}

static void destroySendMsgInfo(SMsgSendInfo* pMsgBody) {
  assert(pMsgBody != NULL);
wafwerar's avatar
wafwerar 已提交
3683 3684
  taosMemoryFreeClear(pMsgBody->msgInfo.pData);
  taosMemoryFreeClear(pMsgBody);
H
Haojun Liao 已提交
3685 3686
}

S
Shengliang Guan 已提交
3687
void qProcessFetchRsp(void* parent, SRpcMsg* pMsg, SEpSet* pEpSet) {
L
Liu Jicong 已提交
3688
  SMsgSendInfo* pSendInfo = (SMsgSendInfo*)pMsg->ahandle;
H
Haojun Liao 已提交
3689 3690 3691 3692 3693
  assert(pMsg->ahandle != NULL);

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

  if (pMsg->contLen > 0) {
wafwerar's avatar
wafwerar 已提交
3694
    buf.pData = taosMemoryCalloc(1, pMsg->contLen);
H
Haojun Liao 已提交
3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705
    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);
3706 3707
}

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

wafwerar's avatar
wafwerar 已提交
3711
  SResFetchReq* pMsg = taosMemoryCalloc(1, sizeof(SResFetchReq));
3712 3713 3714 3715
  if (NULL == pMsg) {
    pTaskInfo->code = TSDB_CODE_QRY_OUT_OF_MEMORY;
    return pTaskInfo->code;
  }
3716

L
Liu Jicong 已提交
3717 3718
  SDownstreamSourceNode* pSource = taosArrayGet(pExchangeInfo->pSources, sourceIndex);
  SSourceDataInfo*       pDataInfo = taosArrayGet(pExchangeInfo->pSourceDataInfo, sourceIndex);
3719

L
Liu Jicong 已提交
3720 3721
  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);
3722 3723 3724 3725 3726 3727 3728

  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 已提交
3729
  SMsgSendInfo* pMsgSendInfo = taosMemoryCalloc(1, sizeof(SMsgSendInfo));
3730
  if (NULL == pMsgSendInfo) {
wafwerar's avatar
wafwerar 已提交
3731
    taosMemoryFreeClear(pMsg);
3732 3733 3734
    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 已提交
3735 3736
  }

3737 3738 3739 3740 3741
  pMsgSendInfo->param = pDataInfo;
  pMsgSendInfo->msgInfo.pData = pMsg;
  pMsgSendInfo->msgInfo.len = sizeof(SResFetchReq);
  pMsgSendInfo->msgType = TDMT_VND_FETCH;
  pMsgSendInfo->fp = loadRemoteDataCallback;
3742

3743
  int64_t transporterId = 0;
L
Liu Jicong 已提交
3744
  int32_t code = asyncSendMsgToServer(pExchangeInfo->pTransporter, &pSource->addr.epSet, &transporterId, pMsgSendInfo);
3745 3746 3747
  return TSDB_CODE_SUCCESS;
}

3748 3749 3750 3751 3752 3753
// NOTE: sources columns are more than the destination SSDatablock columns.
static void relocateColumnData(SSDataBlock* pBlock, const SArray* pColMatchInfo, SArray* pCols) {
  size_t numOfSrcCols = taosArrayGetSize(pCols);
  ASSERT(numOfSrcCols >= pBlock->info.numOfCols);

  int32_t i = 0, j = 0;
L
Liu Jicong 已提交
3754
  while (i < numOfSrcCols && j < taosArrayGetSize(pColMatchInfo)) {
3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773
    SColumnInfoData* p = taosArrayGet(pCols, i);
    SColMatchInfo*   pmInfo = taosArrayGet(pColMatchInfo, j);
    if (!pmInfo->output) {
      j++;
      continue;
    }

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

3774
int32_t setSDataBlockFromFetchRsp(SSDataBlock* pRes, SLoadRemoteDataInfo* pLoadInfo, int32_t numOfRows, char* pData,
dengyihao's avatar
dengyihao 已提交
3775 3776
                                  int32_t compLen, int32_t numOfOutput, int64_t startTs, uint64_t* total,
                                  SArray* pColList) {
H
Haojun Liao 已提交
3777
  blockDataEnsureCapacity(pRes, numOfRows);
3778

H
Haojun Liao 已提交
3779
  if (pColList == NULL) {  // data from other sources
L
Liu Jicong 已提交
3780
    int32_t dataLen = *(int32_t*)pData;
3781 3782
    pData += sizeof(int32_t);

L
Liu Jicong 已提交
3783
    pRes->info.groupId = *(uint64_t*)pData;
3784 3785
    pData += sizeof(uint64_t);

H
Haojun Liao 已提交
3786 3787
    int32_t* colLen = (int32_t*)pData;

3788
    char* pStart = pData + sizeof(int32_t) * numOfOutput;
3789
    for (int32_t i = 0; i < numOfOutput; ++i) {
H
Haojun Liao 已提交
3790
      colLen[i] = htonl(colLen[i]);
3791
      ASSERT(colLen[i] >= 0);
H
Haojun Liao 已提交
3792

3793
      SColumnInfoData* pColInfoData = taosArrayGet(pRes->pDataBlock, i);
H
Haojun Liao 已提交
3794 3795 3796
      if (IS_VAR_DATA_TYPE(pColInfoData->info.type)) {
        pColInfoData->varmeta.length = colLen[i];
        pColInfoData->varmeta.allocLen = colLen[i];
3797

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

3801 3802 3803
        if (colLen[i] > 0) {
          pColInfoData->pData = taosMemoryMalloc(colLen[i]);
        }
H
Haojun Liao 已提交
3804 3805 3806
      } else {
        memcpy(pColInfoData->nullbitmap, pStart, BitmapLen(numOfRows));
        pStart += BitmapLen(numOfRows);
3807
      }
H
Haojun Liao 已提交
3808

3809 3810 3811 3812
      if (colLen[i] > 0) {
        memcpy(pColInfoData->pData, pStart, colLen[i]);
      }

L
Liu Jicong 已提交
3813 3814
      // TODO setting this flag to true temporarily so aggregate function on stable will
      // examine NULL value for non-primary key column
3815
      pColInfoData->hasNull = true;
H
Haojun Liao 已提交
3816
      pStart += colLen[i];
3817
    }
H
Haojun Liao 已提交
3818
  } else {  // extract data according to pColList
3819
    ASSERT(numOfOutput == taosArrayGetSize(pColList));
3820 3821 3822 3823 3824
    char* pStart = pData;

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

3825
    // todo refactor:extract method
3826
    SSysTableSchema* pSchema = (SSysTableSchema*)pStart;
dengyihao's avatar
dengyihao 已提交
3827
    for (int32_t i = 0; i < numOfCols; ++i) {
3828 3829 3830 3831 3832 3833 3834 3835
      SSysTableSchema* p = (SSysTableSchema*)pStart;

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

    SSDataBlock block = {.pDataBlock = taosArrayInit(numOfCols, sizeof(SColumnInfoData)), .info.numOfCols = numOfCols};
dengyihao's avatar
dengyihao 已提交
3836
    for (int32_t i = 0; i < numOfCols; ++i) {
3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849
      SColumnInfoData idata = {0};
      idata.info.type = pSchema[i].type;
      idata.info.bytes = pSchema[i].bytes;
      idata.info.colId = pSchema[i].colId;

      taosArrayPush(block.pDataBlock, &idata);
      if (IS_VAR_DATA_TYPE(idata.info.type)) {
        block.info.hasVarCol = true;
      }
    }

    blockDataEnsureCapacity(&block, numOfRows);

L
Liu Jicong 已提交
3850 3851
    int32_t  dataLen = *(int32_t*)pStart;
    uint64_t groupId = *(uint64_t*)(pStart + sizeof(int32_t));
3852 3853
    pStart += sizeof(int32_t) + sizeof(uint64_t);

L
Liu Jicong 已提交
3854
    int32_t* colLen = (int32_t*)(pStart);
3855 3856 3857 3858
    pStart += sizeof(int32_t) * numOfCols;

    for (int32_t i = 0; i < numOfCols; ++i) {
      colLen[i] = htonl(colLen[i]);
3859
      ASSERT(colLen[i] >= 0);
3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877

      SColumnInfoData* pColInfoData = taosArrayGet(block.pDataBlock, i);
      if (IS_VAR_DATA_TYPE(pColInfoData->info.type)) {
        pColInfoData->varmeta.length = colLen[i];
        pColInfoData->varmeta.allocLen = colLen[i];

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

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

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

    // data from mnode
L
Liu Jicong 已提交
3880
    relocateColumnData(pRes, pColList, block.pDataBlock);
3881
  }
3882

H
Haojun Liao 已提交
3883
  pRes->info.rows = numOfRows;
3884
  blockDataUpdateTsWindow(pRes);
3885

3886
  int64_t el = taosGetTimestampUs() - startTs;
3887

H
Haojun Liao 已提交
3888 3889
  pLoadInfo->totalRows += numOfRows;
  pLoadInfo->totalSize += compLen;
3890

H
Haojun Liao 已提交
3891 3892 3893
  if (total != NULL) {
    *total += numOfRows;
  }
3894

H
Haojun Liao 已提交
3895
  pLoadInfo->totalElapsed += el;
3896 3897
  return TSDB_CODE_SUCCESS;
}
3898

L
Liu Jicong 已提交
3899 3900
static void* setAllSourcesCompleted(SOperatorInfo* pOperator, int64_t startTs) {
  SExchangeInfo* pExchangeInfo = pOperator->info;
3901
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
H
Haojun Liao 已提交
3902

L
Liu Jicong 已提交
3903
  int64_t              el = taosGetTimestampUs() - startTs;
H
Haojun Liao 已提交
3904 3905
  SLoadRemoteDataInfo* pLoadInfo = &pExchangeInfo->loadInfo;
  pLoadInfo->totalElapsed += el;
H
Haojun Liao 已提交
3906

3907
  size_t totalSources = taosArrayGetSize(pExchangeInfo->pSources);
L
Liu Jicong 已提交
3908 3909 3910
  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);
3911 3912 3913 3914 3915

  doSetOperatorCompleted(pOperator);
  return NULL;
}

L
Liu Jicong 已提交
3916 3917
static SSDataBlock* concurrentlyLoadRemoteDataImpl(SOperatorInfo* pOperator, SExchangeInfo* pExchangeInfo,
                                                   SExecTaskInfo* pTaskInfo) {
3918 3919 3920 3921 3922 3923 3924 3925 3926
  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);

3927
      if (pDataInfo->status == EX_SOURCE_DATA_EXHAUSTED) {
3928
        completed += 1;
H
Haojun Liao 已提交
3929 3930
        continue;
      }
3931

3932
      if (pDataInfo->status != EX_SOURCE_DATA_READY) {
3933 3934 3935
        continue;
      }

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

L
Liu Jicong 已提交
3939
      SSDataBlock*         pRes = pExchangeInfo->pResult;
H
Haojun Liao 已提交
3940
      SLoadRemoteDataInfo* pLoadInfo = &pExchangeInfo->loadInfo;
3941
      if (pRsp->numOfRows == 0) {
L
Liu Jicong 已提交
3942 3943
        qDebug("%s vgId:%d, taskID:0x%" PRIx64 " index:%d completed, rowsOfSource:%" PRIu64 ", totalRows:%" PRIu64
               " try next",
3944
               GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->taskId, i + 1, pDataInfo->totalRows,
H
Haojun Liao 已提交
3945
               pExchangeInfo->loadInfo.totalRows);
3946
        pDataInfo->status = EX_SOURCE_DATA_EXHAUSTED;
3947 3948 3949
        completed += 1;
        continue;
      }
H
Haojun Liao 已提交
3950

H
Haojun Liao 已提交
3951
      SRetrieveTableRsp* pTableRsp = pDataInfo->pRsp;
L
Liu Jicong 已提交
3952 3953 3954
      code =
          setSDataBlockFromFetchRsp(pExchangeInfo->pResult, pLoadInfo, pTableRsp->numOfRows, pTableRsp->data,
                                    pTableRsp->compLen, pOperator->numOfOutput, startTs, &pDataInfo->totalRows, NULL);
3955
      if (code != 0) {
3956 3957 3958
        goto _error;
      }

3959 3960 3961
      if (pRsp->completed == 1) {
        qDebug("%s fetch msg rsp from vgId:%d, taskId:0x%" PRIx64 " numOfRows:%d, rowsOfSource:%" PRIu64
               ", totalRows:%" PRIu64 ", totalBytes:%" PRIu64 " try next %d/%" PRIzu,
L
Liu Jicong 已提交
3962 3963
               GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->taskId, pRes->info.rows, pDataInfo->totalRows,
               pLoadInfo->totalRows, pLoadInfo->totalSize, i + 1, totalSources);
3964
        pDataInfo->status = EX_SOURCE_DATA_EXHAUSTED;
3965
      } else {
dengyihao's avatar
dengyihao 已提交
3966 3967
        qDebug("%s fetch msg rsp from vgId:%d, taskId:0x%" PRIx64 " numOfRows:%d, totalRows:%" PRIu64
               ", totalBytes:%" PRIu64,
H
Haojun Liao 已提交
3968 3969
               GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->taskId, pRes->info.rows, pLoadInfo->totalRows,
               pLoadInfo->totalSize);
3970 3971
      }

3972 3973
      if (pDataInfo->status != EX_SOURCE_DATA_EXHAUSTED) {
        pDataInfo->status = EX_SOURCE_DATA_NOT_READY;
3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992
        code = doSendFetchDataRequest(pExchangeInfo, pTaskInfo, i);
        if (code != TSDB_CODE_SUCCESS) {
          goto _error;
        }
      }

      return pExchangeInfo->pResult;
    }

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

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

L
Liu Jicong 已提交
3993 3994 3995
static SSDataBlock* concurrentlyLoadRemoteData(SOperatorInfo* pOperator) {
  SExchangeInfo* pExchangeInfo = pOperator->info;
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
H
Haojun Liao 已提交
3996

H
Haojun Liao 已提交
3997 3998 3999
  if (pOperator->status == OP_RES_TO_RETURN) {
    return concurrentlyLoadRemoteDataImpl(pOperator, pExchangeInfo, pTaskInfo);
  }
4000

L
Liu Jicong 已提交
4001
  size_t  totalSources = taosArrayGetSize(pExchangeInfo->pSources);
4002 4003 4004
  int64_t startTs = taosGetTimestampUs();

  // Asynchronously send all fetch requests to all sources.
L
Liu Jicong 已提交
4005
  for (int32_t i = 0; i < totalSources; ++i) {
4006 4007
    int32_t code = doSendFetchDataRequest(pExchangeInfo, pTaskInfo, i);
    if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
4008
      return NULL;
4009 4010 4011 4012
    }
  }

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

  tsem_wait(&pExchangeInfo->ready);
H
Haojun Liao 已提交
4017 4018
  pOperator->status = OP_RES_TO_RETURN;
  return concurrentlyLoadRemoteDataImpl(pOperator, pExchangeInfo, pTaskInfo);
4019 4020
}

L
Liu Jicong 已提交
4021 4022 4023
static int32_t prepareConcurrentlyLoad(SOperatorInfo* pOperator) {
  SExchangeInfo* pExchangeInfo = pOperator->info;
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
4024

L
Liu Jicong 已提交
4025
  size_t  totalSources = taosArrayGetSize(pExchangeInfo->pSources);
4026 4027 4028
  int64_t startTs = taosGetTimestampUs();

  // Asynchronously send all fetch requests to all sources.
L
Liu Jicong 已提交
4029
  for (int32_t i = 0; i < totalSources; ++i) {
4030 4031
    int32_t code = doSendFetchDataRequest(pExchangeInfo, pTaskInfo, i);
    if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
4032 4033
      pTaskInfo->code = code;
      return code;
4034 4035 4036 4037
    }
  }

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

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

H
Haojun Liao 已提交
4044
  return TSDB_CODE_SUCCESS;
4045 4046
}

L
Liu Jicong 已提交
4047 4048 4049
static SSDataBlock* seqLoadRemoteData(SOperatorInfo* pOperator) {
  SExchangeInfo* pExchangeInfo = pOperator->info;
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
4050

L
Liu Jicong 已提交
4051
  size_t  totalSources = taosArrayGetSize(pExchangeInfo->pSources);
4052
  int64_t startTs = taosGetTimestampUs();
4053

L
Liu Jicong 已提交
4054
  while (1) {
4055 4056
    if (pExchangeInfo->current >= totalSources) {
      return setAllSourcesCompleted(pOperator, startTs);
4057
    }
4058

4059 4060 4061
    doSendFetchDataRequest(pExchangeInfo, pTaskInfo, pExchangeInfo->current);
    tsem_wait(&pExchangeInfo->ready);

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

H
Haojun Liao 已提交
4065
    if (pDataInfo->code != TSDB_CODE_SUCCESS) {
dengyihao's avatar
dengyihao 已提交
4066 4067
      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 已提交
4068 4069 4070 4071
      pOperator->pTaskInfo->code = pDataInfo->code;
      return NULL;
    }

L
Liu Jicong 已提交
4072
    SRetrieveTableRsp*   pRsp = pDataInfo->pRsp;
H
Haojun Liao 已提交
4073
    SLoadRemoteDataInfo* pLoadInfo = &pExchangeInfo->loadInfo;
4074
    if (pRsp->numOfRows == 0) {
dengyihao's avatar
dengyihao 已提交
4075 4076
      qDebug("%s vgId:%d, taskID:0x%" PRIx64 " %d of total completed, rowsOfSource:%" PRIu64 ", totalRows:%" PRIu64
             " try next",
4077
             GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->taskId, pExchangeInfo->current + 1,
H
Haojun Liao 已提交
4078
             pDataInfo->totalRows, pLoadInfo->totalRows);
H
Haojun Liao 已提交
4079

4080
      pDataInfo->status = EX_SOURCE_DATA_EXHAUSTED;
4081 4082 4083
      pExchangeInfo->current += 1;
      continue;
    }
H
Haojun Liao 已提交
4084

L
Liu Jicong 已提交
4085
    SSDataBlock*       pRes = pExchangeInfo->pResult;
H
Haojun Liao 已提交
4086
    SRetrieveTableRsp* pTableRsp = pDataInfo->pRsp;
L
Liu Jicong 已提交
4087 4088 4089
    int32_t            code =
        setSDataBlockFromFetchRsp(pExchangeInfo->pResult, pLoadInfo, pTableRsp->numOfRows, pTableRsp->data,
                                  pTableRsp->compLen, pOperator->numOfOutput, startTs, &pDataInfo->totalRows, NULL);
4090 4091

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

4097
      pDataInfo->status = EX_SOURCE_DATA_EXHAUSTED;
4098 4099
      pExchangeInfo->current += 1;
    } else {
L
Liu Jicong 已提交
4100 4101 4102 4103
      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);
4104 4105 4106 4107
    }

    return pExchangeInfo->pResult;
  }
4108 4109
}

L
Liu Jicong 已提交
4110
static int32_t prepareLoadRemoteData(SOperatorInfo* pOperator) {
4111
  if (OPTR_IS_OPENED(pOperator)) {
H
Haojun Liao 已提交
4112 4113 4114
    return TSDB_CODE_SUCCESS;
  }

L
Liu Jicong 已提交
4115
  SExchangeInfo* pExchangeInfo = pOperator->info;
H
Haojun Liao 已提交
4116 4117 4118 4119 4120 4121 4122 4123 4124
  if (pExchangeInfo->seqLoadData) {
    // do nothing for sequentially load data
  } else {
    int32_t code = prepareConcurrentlyLoad(pOperator);
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }
  }

4125
  OPTR_SET_OPENED(pOperator);
H
Haojun Liao 已提交
4126 4127 4128
  return TSDB_CODE_SUCCESS;
}

L
Liu Jicong 已提交
4129 4130 4131
static SSDataBlock* doLoadRemoteData(SOperatorInfo* pOperator, bool* newgroup) {
  SExchangeInfo* pExchangeInfo = pOperator->info;
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
4132

4133
  pTaskInfo->code = pOperator->fpSet._openFn(pOperator);
4134
  if (pTaskInfo->code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
4135 4136
    return NULL;
  }
4137

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

4141
  if (pOperator->status == OP_EXEC_DONE) {
L
Liu Jicong 已提交
4142 4143 4144
    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);
4145 4146 4147 4148
    return NULL;
  }

  *newgroup = false;
H
Haojun Liao 已提交
4149

4150 4151 4152
  if (pExchangeInfo->seqLoadData) {
    return seqLoadRemoteData(pOperator);
  } else {
H
Haojun Liao 已提交
4153
    return concurrentlyLoadRemoteData(pOperator);
4154
  }
H
Haojun Liao 已提交
4155

4156
#if 0
H
Haojun Liao 已提交
4157
  _error:
wafwerar's avatar
wafwerar 已提交
4158 4159
  taosMemoryFreeClear(pMsg);
  taosMemoryFreeClear(pMsgSendInfo);
H
Haojun Liao 已提交
4160 4161 4162

  terrno = pTaskInfo->code;
  return NULL;
4163
#endif
H
Haojun Liao 已提交
4164
}
4165

H
Haojun Liao 已提交
4166
static int32_t initDataSource(int32_t numOfSources, SExchangeInfo* pInfo) {
4167
  pInfo->pSourceDataInfo = taosArrayInit(numOfSources, sizeof(SSourceDataInfo));
H
Haojun Liao 已提交
4168 4169
  if (pInfo->pSourceDataInfo == NULL) {
    return TSDB_CODE_OUT_OF_MEMORY;
4170 4171
  }

L
Liu Jicong 已提交
4172
  for (int32_t i = 0; i < numOfSources; ++i) {
4173
    SSourceDataInfo dataInfo = {0};
H
Haojun Liao 已提交
4174
    dataInfo.status = EX_SOURCE_DATA_NOT_READY;
L
Liu Jicong 已提交
4175 4176
    dataInfo.pEx = pInfo;
    dataInfo.index = i;
4177

H
Haojun Liao 已提交
4178 4179 4180 4181 4182 4183 4184 4185 4186 4187
    void* ret = taosArrayPush(pInfo->pSourceDataInfo, &dataInfo);
    if (ret == NULL) {
      taosArrayDestroy(pInfo->pSourceDataInfo);
      return TSDB_CODE_OUT_OF_MEMORY;
    }
  }

  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
4188
SOperatorInfo* createExchangeOperatorInfo(const SNodeList* pSources, SSDataBlock* pBlock, SExecTaskInfo* pTaskInfo) {
L
Liu Jicong 已提交
4189
  SExchangeInfo* pInfo = taosMemoryCalloc(1, sizeof(SExchangeInfo));
wafwerar's avatar
wafwerar 已提交
4190
  SOperatorInfo* pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
4191 4192

  if (pInfo == NULL || pOperator == NULL) {
wafwerar's avatar
wafwerar 已提交
4193 4194
    taosMemoryFreeClear(pInfo);
    taosMemoryFreeClear(pOperator);
H
Haojun Liao 已提交
4195 4196
    terrno = TSDB_CODE_QRY_OUT_OF_MEMORY;
    return NULL;
H
Haojun Liao 已提交
4197 4198
  }

H
Haojun Liao 已提交
4199
  size_t numOfSources = LIST_LENGTH(pSources);
H
Haojun Liao 已提交
4200
  pInfo->pSources = taosArrayInit(numOfSources, sizeof(SDownstreamSourceNode));
H
Haojun Liao 已提交
4201 4202 4203
  pInfo->pSourceDataInfo = taosArrayInit(numOfSources, sizeof(SSourceDataInfo));
  if (pInfo->pSourceDataInfo == NULL || pInfo->pSources == NULL) {
    goto _error;
H
Haojun Liao 已提交
4204 4205
  }

L
Liu Jicong 已提交
4206 4207
  for (int32_t i = 0; i < numOfSources; ++i) {
    SNodeListNode* pNode = nodesListGetNode((SNodeList*)pSources, i);
H
Haojun Liao 已提交
4208 4209
    taosArrayPush(pInfo->pSources, pNode);
  }
4210

H
Haojun Liao 已提交
4211 4212 4213
  int32_t code = initDataSource(numOfSources, pInfo);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
4214
  }
H
Haojun Liao 已提交
4215

dengyihao's avatar
dengyihao 已提交
4216
  pInfo->pResult = pBlock;
4217 4218 4219
  pInfo->seqLoadData = true;

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

dengyihao's avatar
dengyihao 已提交
4221
  pOperator->name = "ExchangeOperator";
X
Xiaoyu Wang 已提交
4222
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_EXCHANGE;
4223
  pOperator->blockingOptr = false;
dengyihao's avatar
dengyihao 已提交
4224 4225 4226 4227
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
  pOperator->numOfOutput = pBlock->info.numOfCols;
  pOperator->pTaskInfo = pTaskInfo;
4228

L
Liu Jicong 已提交
4229 4230
  pOperator->fpSet = createOperatorFpSet(prepareLoadRemoteData, doLoadRemoteData, NULL, NULL,
                                         destroyExchangeOperatorInfo, NULL, NULL, NULL);
4231

S
Shengliang Guan 已提交
4232
#if 1
L
Liu Jicong 已提交
4233
  {  // todo refactor
H
Haojun Liao 已提交
4234 4235 4236
    SRpcInit rpcInit;
    memset(&rpcInit, 0, sizeof(rpcInit));
    rpcInit.localPort = 0;
H
Haojun Liao 已提交
4237
    rpcInit.label = "EX";
H
Haojun Liao 已提交
4238
    rpcInit.numOfThreads = 1;
S
Shengliang Guan 已提交
4239
    rpcInit.cfp = qProcessFetchRsp;
S
Shengliang Guan 已提交
4240
    rpcInit.sessions = tsMaxConnections;
H
Haojun Liao 已提交
4241
    rpcInit.connType = TAOS_CONN_CLIENT;
L
Liu Jicong 已提交
4242
    rpcInit.user = (char*)"root";
S
Shengliang Guan 已提交
4243
    rpcInit.idleTime = tsShellActivityTimer * 1000;
H
Haojun Liao 已提交
4244
    rpcInit.ckey = "key";
S
Shengliang Guan 已提交
4245
    rpcInit.spi = 1;
L
Liu Jicong 已提交
4246
    rpcInit.secret = (char*)"dcc5bed04851fec854c035b2e40263b6";
H
Haojun Liao 已提交
4247 4248 4249

    pInfo->pTransporter = rpcOpen(&rpcInit);
    if (pInfo->pTransporter == NULL) {
L
Liu Jicong 已提交
4250
      return NULL;  // todo
H
Haojun Liao 已提交
4251 4252
    }
  }
S
Shengliang 已提交
4253
#endif
4254

4255
  return pOperator;
H
Haojun Liao 已提交
4256

L
Liu Jicong 已提交
4257
_error:
H
Haojun Liao 已提交
4258
  if (pInfo != NULL) {
H
Haojun Liao 已提交
4259
    destroyExchangeOperatorInfo(pInfo, numOfSources);
H
Haojun Liao 已提交
4260 4261
  }

wafwerar's avatar
wafwerar 已提交
4262 4263
  taosMemoryFreeClear(pInfo);
  taosMemoryFreeClear(pOperator);
H
Haojun Liao 已提交
4264
  pTaskInfo->code = TSDB_CODE_OUT_OF_MEMORY;
H
Haojun Liao 已提交
4265
  return NULL;
4266 4267
}

dengyihao's avatar
dengyihao 已提交
4268 4269
static int32_t doInitAggInfoSup(SAggSupporter* pAggSup, SqlFunctionCtx* pCtx, int32_t numOfOutput, size_t keyBufSize,
                                const char* pKey);
H
Haojun Liao 已提交
4270
static void    cleanupAggSup(SAggSupporter* pAggSup);
4271

4272
static void destroySortedMergeOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
4273
  SSortedMergeOperatorInfo* pInfo = (SSortedMergeOperatorInfo*)param;
H
Haojun Liao 已提交
4274
  taosArrayDestroy(pInfo->pSortInfo);
4275 4276 4277
  taosArrayDestroy(pInfo->groupInfo);

  if (pInfo->pSortHandle != NULL) {
H
Haojun Liao 已提交
4278
    tsortDestroySortHandle(pInfo->pSortHandle);
4279 4280
  }

H
Haojun Liao 已提交
4281
  blockDataDestroy(pInfo->binfo.pRes);
H
Haojun Liao 已提交
4282
  cleanupAggSup(&pInfo->aggSup);
4283
}
H
Haojun Liao 已提交
4284

X
Xiaoyu Wang 已提交
4285 4286
static void assignExprInfo(SExprInfo* dst, const SExprInfo* src) {
  assert(dst != NULL && src != NULL);
4287

X
Xiaoyu Wang 已提交
4288
  *dst = *src;
4289

X
Xiaoyu Wang 已提交
4290
  dst->pExpr = exprdup(src->pExpr);
wafwerar's avatar
wafwerar 已提交
4291
  dst->base.pParam = taosMemoryCalloc(src->base.numOfParams, sizeof(SColumn));
H
Haojun Liao 已提交
4292
  memcpy(dst->base.pParam, src->base.pParam, sizeof(SColumn) * src->base.numOfParams);
4293

L
Liu Jicong 已提交
4294 4295 4296 4297
  //  memset(dst->base.param, 0, sizeof(SVariant) * tListLen(dst->base.param));
  //  for (int32_t j = 0; j < src->base.numOfParams; ++j) {
  //    taosVariantAssign(&dst->base.param[j], &src->base.param[j]);
  //  }
X
Xiaoyu Wang 已提交
4298
}
4299

H
Haojun Liao 已提交
4300
// TODO merge aggregate super table
L
Liu Jicong 已提交
4301
static void appendOneRowToDataBlock(SSDataBlock* pBlock, STupleHandle* pTupleHandle) {
4302 4303
  for (int32_t i = 0; i < pBlock->info.numOfCols; ++i) {
    SColumnInfoData* pColInfo = taosArrayGet(pBlock->pDataBlock, i);
4304

H
Haojun Liao 已提交
4305
    bool isNull = tsortIsNullVal(pTupleHandle, i);
H
Haojun Liao 已提交
4306 4307 4308
    if (isNull) {
      colDataAppend(pColInfo, pBlock->info.rows, NULL, true);
    } else {
H
Haojun Liao 已提交
4309
      char* pData = tsortGetValue(pTupleHandle, i);
H
Haojun Liao 已提交
4310 4311
      colDataAppend(pColInfo, pBlock->info.rows, pData, false);
    }
4312 4313
  }

4314 4315
  pBlock->info.rows += 1;
}
4316

H
Haojun Liao 已提交
4317
SSDataBlock* getSortedBlockData(SSortHandle* pHandle, SSDataBlock* pDataBlock, int32_t capacity) {
4318
  blockDataCleanup(pDataBlock);
D
dapan1121 已提交
4319
  blockDataEnsureCapacity(pDataBlock, capacity);
4320

wmmhello's avatar
wmmhello 已提交
4321 4322
  blockDataEnsureCapacity(pDataBlock, capacity);

L
Liu Jicong 已提交
4323
  while (1) {
H
Haojun Liao 已提交
4324
    STupleHandle* pTupleHandle = tsortNextTuple(pHandle);
4325 4326 4327
    if (pTupleHandle == NULL) {
      break;
    }
4328

4329 4330 4331
    appendOneRowToDataBlock(pDataBlock, pTupleHandle);
    if (pDataBlock->info.rows >= capacity) {
      return pDataBlock;
H
Haojun Liao 已提交
4332 4333
    }
  }
4334

L
Liu Jicong 已提交
4335
  return (pDataBlock->info.rows > 0) ? pDataBlock : NULL;
4336
}
4337

4338
SSDataBlock* loadNextDataBlock(void* param) {
L
Liu Jicong 已提交
4339 4340
  SOperatorInfo* pOperator = (SOperatorInfo*)param;
  bool           newgroup = false;
4341
  return pOperator->fpSet.getNextFn(pOperator, &newgroup);
4342 4343
}

L
Liu Jicong 已提交
4344
static bool needToMerge(SSDataBlock* pBlock, SArray* groupInfo, char** buf, int32_t rowIndex) {
4345 4346 4347 4348
  size_t size = taosArrayGetSize(groupInfo);
  if (size == 0) {
    return true;
  }
4349

4350 4351
  for (int32_t i = 0; i < size; ++i) {
    int32_t* index = taosArrayGet(groupInfo, i);
4352

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

4356 4357 4358
    if ((isNull && buf[i] != NULL) || (!isNull && buf[i] == NULL)) {
      return false;
    }
4359

4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372
    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;
      }
4373 4374 4375
    }
  }

4376
  return 0;
4377 4378
}

L
Liu Jicong 已提交
4379 4380 4381
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
4382
    pCtx[j].startRow = rowIndex;
4383 4384
  }

4385 4386
  for (int32_t j = 0; j < numOfExpr; ++j) {
    int32_t functionId = pCtx[j].functionId;
L
Liu Jicong 已提交
4387 4388 4389 4390 4391 4392 4393 4394 4395
    //    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]);
    //    }
4396
  }
4397
}
4398

L
Liu Jicong 已提交
4399 4400
static void doFinalizeResultImpl(SqlFunctionCtx* pCtx, int32_t numOfExpr) {
  for (int32_t j = 0; j < numOfExpr; ++j) {
4401 4402 4403 4404
    int32_t functionId = pCtx[j].functionId;
    //    if (functionId == FUNC_TAG_DUMMY || functionId == FUNC_TS_DUMMY) {
    //      continue;
    //    }
4405

4406 4407 4408 4409
    //    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 已提交
4410
    //    pCtx[j].fpSet.finalize(&pCtx[j]);
4411 4412
  }
}
4413

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

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

4421 4422 4423
    char* data = colDataGetData(pColInfo, rowIndex);
    memcpy(rowColData[i], data, colDataGetLength(pColInfo, rowIndex));
  }
4424

4425 4426
  return true;
}
4427

4428 4429
static void doMergeImpl(SOperatorInfo* pOperator, int32_t numOfExpr, SSDataBlock* pBlock) {
  SSortedMergeOperatorInfo* pInfo = pOperator->info;
4430

4431
  SqlFunctionCtx* pCtx = pInfo->binfo.pCtx;
L
Liu Jicong 已提交
4432
  for (int32_t i = 0; i < pBlock->info.numOfCols; ++i) {
4433 4434
    pCtx[i].size = 1;
  }
4435

L
Liu Jicong 已提交
4436
  for (int32_t i = 0; i < pBlock->info.rows; ++i) {
4437 4438 4439 4440 4441 4442 4443 4444 4445
    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);
H
Haojun Liao 已提交
4446
        int32_t numOfRows = getNumOfResult(pInfo->binfo.pCtx, pOperator->numOfOutput, NULL);
4447
        //        setTagValueForMultipleRows(pCtx, pOperator->numOfOutput, numOfRows);
4448

4449
        // TODO check for available buffer;
H
Haojun Liao 已提交
4450

4451 4452 4453 4454 4455
        // next group info data
        pInfo->binfo.pRes->info.rows += numOfRows;
        for (int32_t j = 0; j < numOfExpr; ++j) {
          if (pCtx[j].functionId < 0) {
            continue;
4456
          }
4457

H
Haojun Liao 已提交
4458
          pCtx[j].fpSet.process(&pCtx[j]);
4459
        }
4460 4461 4462

        doMergeResultImpl(pInfo, pCtx, numOfExpr, i);
        pInfo->hasGroupVal = saveCurrentTuple(pInfo->groupVal, pInfo->groupInfo, pBlock, i);
H
Haojun Liao 已提交
4463
      }
4464 4465 4466 4467
    }
  }
}

4468 4469
static SSDataBlock* doMerge(SOperatorInfo* pOperator) {
  SSortedMergeOperatorInfo* pInfo = pOperator->info;
L
Liu Jicong 已提交
4470
  SSortHandle*              pHandle = pInfo->pSortHandle;
4471

4472
  SSDataBlock* pDataBlock = createOneDataBlock(pInfo->binfo.pRes, false);
4473
  blockDataEnsureCapacity(pDataBlock, pOperator->resultInfo.capacity);
4474

L
Liu Jicong 已提交
4475
  while (1) {
4476
    blockDataCleanup(pDataBlock);
4477
    while (1) {
H
Haojun Liao 已提交
4478
      STupleHandle* pTupleHandle = tsortNextTuple(pHandle);
4479 4480
      if (pTupleHandle == NULL) {
        break;
4481
      }
4482

4483 4484
      // build datablock for merge for one group
      appendOneRowToDataBlock(pDataBlock, pTupleHandle);
4485
      if (pDataBlock->info.rows >= pOperator->resultInfo.capacity) {
4486 4487
        break;
      }
4488
    }
4489

4490 4491 4492
    if (pDataBlock->info.rows == 0) {
      break;
    }
4493

4494
    setInputDataBlock(pOperator, pInfo->binfo.pCtx, pDataBlock, TSDB_ORDER_ASC, true);
L
Liu Jicong 已提交
4495 4496
    //  updateOutputBuf(&pInfo->binfo, &pAggInfo->bufCapacity, pBlock->info.rows * pAggInfo->resultRowFactor,
    //  pOperator->pRuntimeEnv, true);
4497 4498 4499
    doMergeImpl(pOperator, pOperator->numOfOutput, pDataBlock);
    // flush to tuple store, and after all data have been handled, return to upstream node or sink node
  }
4500

4501
  doFinalizeResultImpl(pInfo->binfo.pCtx, pOperator->numOfOutput);
H
Haojun Liao 已提交
4502
  int32_t numOfRows = getNumOfResult(pInfo->binfo.pCtx, pOperator->numOfOutput, NULL);
4503
  //        setTagValueForMultipleRows(pCtx, pOperator->numOfOutput, numOfRows);
4504

4505
  // TODO check for available buffer;
4506

4507 4508
  // next group info data
  pInfo->binfo.pRes->info.rows += numOfRows;
L
Liu Jicong 已提交
4509
  return (pInfo->binfo.pRes->info.rows > 0) ? pInfo->binfo.pRes : NULL;
4510
}
4511

L
Liu Jicong 已提交
4512
static SSDataBlock* doSortedMerge(SOperatorInfo* pOperator, bool* newgroup) {
4513 4514
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
4515 4516
  }

L
Liu Jicong 已提交
4517
  SExecTaskInfo*            pTaskInfo = pOperator->pTaskInfo;
4518
  SSortedMergeOperatorInfo* pInfo = pOperator->info;
H
Haojun Liao 已提交
4519
  if (pOperator->status == OP_RES_TO_RETURN) {
4520
    return getSortedBlockData(pInfo->pSortHandle, pInfo->binfo.pRes, pOperator->resultInfo.capacity);
4521 4522
  }

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

H
Haojun Liao 已提交
4527
  tsortSetFetchRawDataFp(pInfo->pSortHandle, loadNextDataBlock);
4528

L
Liu Jicong 已提交
4529
  for (int32_t i = 0; i < pOperator->numOfDownstream; ++i) {
wmmhello's avatar
wmmhello 已提交
4530
    SSortSource* ps = taosMemoryCalloc(1, sizeof(SSortSource));
H
Haojun Liao 已提交
4531
    ps->param = pOperator->pDownstream[i];
H
Haojun Liao 已提交
4532
    tsortAddSource(pInfo->pSortHandle, ps);
4533 4534
  }

H
Haojun Liao 已提交
4535
  int32_t code = tsortOpen(pInfo->pSortHandle);
4536
  if (code != TSDB_CODE_SUCCESS) {
4537
    longjmp(pTaskInfo->env, terrno);
4538 4539
  }

H
Haojun Liao 已提交
4540
  pOperator->status = OP_RES_TO_RETURN;
4541
  return doMerge(pOperator);
4542
}
4543

L
Liu Jicong 已提交
4544 4545
static int32_t initGroupCol(SExprInfo* pExprInfo, int32_t numOfCols, SArray* pGroupInfo,
                            SSortedMergeOperatorInfo* pInfo) {
4546 4547
  if (pGroupInfo == NULL || taosArrayGetSize(pGroupInfo) == 0) {
    return 0;
H
Haojun Liao 已提交
4548 4549
  }

4550 4551 4552 4553 4554 4555 4556 4557
  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 已提交
4558 4559
  size_t numOfGroupCol = taosArrayGetSize(pInfo->groupInfo);
  for (int32_t i = 0; i < numOfGroupCol; ++i) {
4560
    SColumn* pCol = taosArrayGet(pGroupInfo, i);
L
Liu Jicong 已提交
4561
    for (int32_t j = 0; j < numOfCols; ++j) {
H
Haojun Liao 已提交
4562
      SExprInfo* pe = &pExprInfo[j];
4563
      if (pe->base.resSchema.slotId == pCol->colId) {
4564 4565
        taosArrayPush(plist, pCol);
        taosArrayPush(pInfo->groupInfo, &j);
H
Haojun Liao 已提交
4566
        len += pCol->bytes;
4567 4568
        break;
      }
H
Haojun Liao 已提交
4569 4570 4571
    }
  }

4572
  ASSERT(taosArrayGetSize(pGroupInfo) == taosArrayGetSize(plist));
H
Haojun Liao 已提交
4573

wafwerar's avatar
wafwerar 已提交
4574
  pInfo->groupVal = taosMemoryCalloc(1, (POINTER_BYTES * numOfGroupCol + len));
4575 4576 4577 4578
  if (pInfo->groupVal == NULL) {
    taosArrayDestroy(plist);
    return TSDB_CODE_OUT_OF_MEMORY;
  }
H
Haojun Liao 已提交
4579

4580
  int32_t offset = 0;
L
Liu Jicong 已提交
4581 4582
  char*   start = (char*)(pInfo->groupVal + (POINTER_BYTES * numOfGroupCol));
  for (int32_t i = 0; i < numOfGroupCol; ++i) {
4583 4584
    pInfo->groupVal[i] = start + offset;
    SColumn* pCol = taosArrayGet(plist, i);
H
Haojun Liao 已提交
4585
    offset += pCol->bytes;
4586
  }
H
Haojun Liao 已提交
4587

4588
  taosArrayDestroy(plist);
H
Haojun Liao 已提交
4589

4590 4591
  return TSDB_CODE_SUCCESS;
}
H
Haojun Liao 已提交
4592

L
Liu Jicong 已提交
4593 4594 4595
SOperatorInfo* createSortedMergeOperatorInfo(SOperatorInfo** downstream, int32_t numOfDownstream, SExprInfo* pExprInfo,
                                             int32_t num, SArray* pSortInfo, SArray* pGroupInfo,
                                             SExecTaskInfo* pTaskInfo) {
wafwerar's avatar
wafwerar 已提交
4596
  SSortedMergeOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SSortedMergeOperatorInfo));
L
Liu Jicong 已提交
4597
  SOperatorInfo*            pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
4598
  if (pInfo == NULL || pOperator == NULL) {
4599
    goto _error;
4600
  }
H
Haojun Liao 已提交
4601

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

4605 4606 4607
  if (pInfo->binfo.pCtx == NULL || pInfo->binfo.pRes == NULL) {
    goto _error;
  }
H
Haojun Liao 已提交
4608

dengyihao's avatar
dengyihao 已提交
4609
  size_t  keyBufSize = sizeof(int64_t) + sizeof(int64_t) + POINTER_BYTES;
4610
  int32_t code = doInitAggInfoSup(&pInfo->aggSup, pInfo->binfo.pCtx, num, keyBufSize, pTaskInfo->id.str);
4611 4612 4613
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
H
Haojun Liao 已提交
4614

H
Haojun Liao 已提交
4615
  setFunctionResultOutput(&pInfo->binfo, &pInfo->aggSup, MAIN_SCAN, pTaskInfo);
H
Haojun Liao 已提交
4616
  code = initGroupCol(pExprInfo, num, pGroupInfo, pInfo);
4617 4618 4619
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
H
Haojun Liao 已提交
4620

L
Liu Jicong 已提交
4621 4622 4623 4624 4625
  //  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 已提交
4626

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

L
Liu Jicong 已提交
4629
  pOperator->name = "SortedMerge";
X
Xiaoyu Wang 已提交
4630
  // pOperator->operatorType = OP_SortedMerge;
4631
  pOperator->blockingOptr = true;
L
Liu Jicong 已提交
4632 4633 4634 4635
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
  pOperator->numOfOutput = num;
  pOperator->pExpr = pExprInfo;
H
Haojun Liao 已提交
4636

L
Liu Jicong 已提交
4637
  pOperator->pTaskInfo = pTaskInfo;
H
Haojun Liao 已提交
4638

4639 4640
  pOperator->fpSet = createOperatorFpSet(operatorDummyOpenFn, doSortedMerge, NULL, NULL, destroySortedMergeOperatorInfo,
                                         NULL, NULL, NULL);
4641 4642 4643
  code = appendDownstream(pOperator, downstream, numOfDownstream);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
4644
  }
H
Haojun Liao 已提交
4645

4646
  return pOperator;
H
Haojun Liao 已提交
4647

L
Liu Jicong 已提交
4648
_error:
4649
  if (pInfo != NULL) {
H
Haojun Liao 已提交
4650
    destroySortedMergeOperatorInfo(pInfo, num);
H
Haojun Liao 已提交
4651 4652
  }

wafwerar's avatar
wafwerar 已提交
4653 4654
  taosMemoryFreeClear(pInfo);
  taosMemoryFreeClear(pOperator);
4655 4656
  terrno = TSDB_CODE_QRY_OUT_OF_MEMORY;
  return NULL;
H
Haojun Liao 已提交
4657 4658
}

L
Liu Jicong 已提交
4659
static SSDataBlock* doSort(SOperatorInfo* pOperator, bool* newgroup) {
4660 4661 4662 4663
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

L
Liu Jicong 已提交
4664
  SExecTaskInfo*     pTaskInfo = pOperator->pTaskInfo;
H
Haojun Liao 已提交
4665 4666
  SSortOperatorInfo* pInfo = pOperator->info;

H
Haojun Liao 已提交
4667
  if (pOperator->status == OP_RES_TO_RETURN) {
H
Haojun Liao 已提交
4668
    return getSortedBlockData(pInfo->pSortHandle, pInfo->pDataBlock, pInfo->numOfRowsInRes);
H
Haojun Liao 已提交
4669 4670
  }

4671
  int32_t numOfBufPage = pInfo->sortBufSize / pInfo->bufPageSize;
dengyihao's avatar
dengyihao 已提交
4672 4673
  pInfo->pSortHandle = tsortCreateSortHandle(pInfo->pSortInfo, pInfo->inputSlotMap, SORT_SINGLESOURCE_SORT,
                                             pInfo->bufPageSize, numOfBufPage, pInfo->pDataBlock, pTaskInfo->id.str);
4674

H
Haojun Liao 已提交
4675
  tsortSetFetchRawDataFp(pInfo->pSortHandle, loadNextDataBlock);
H
Haojun Liao 已提交
4676

wmmhello's avatar
wmmhello 已提交
4677
  SSortSource* ps = taosMemoryCalloc(1, sizeof(SSortSource));
H
Haojun Liao 已提交
4678
  ps->param = pOperator->pDownstream[0];
H
Haojun Liao 已提交
4679
  tsortAddSource(pInfo->pSortHandle, ps);
4680

H
Haojun Liao 已提交
4681
  int32_t code = tsortOpen(pInfo->pSortHandle);
4682
  taosMemoryFreeClear(ps);
4683
  if (code != TSDB_CODE_SUCCESS) {
4684
    longjmp(pTaskInfo->env, terrno);
4685
  }
4686

H
Haojun Liao 已提交
4687
  pOperator->status = OP_RES_TO_RETURN;
H
Haojun Liao 已提交
4688
  return getSortedBlockData(pInfo->pSortHandle, pInfo->pDataBlock, pInfo->numOfRowsInRes);
4689 4690
}

dengyihao's avatar
dengyihao 已提交
4691 4692
SOperatorInfo* createSortOperatorInfo(SOperatorInfo* downstream, SSDataBlock* pResBlock, SArray* pSortInfo,
                                      SArray* pIndexMap, SExecTaskInfo* pTaskInfo) {
H
Haojun Liao 已提交
4693
  SSortOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SSortOperatorInfo));
L
Liu Jicong 已提交
4694
  SOperatorInfo*     pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
dengyihao's avatar
dengyihao 已提交
4695
  int32_t            rowSize = pResBlock->info.rowSize;
4696 4697

  if (pInfo == NULL || pOperator == NULL || rowSize > 100 * 1024 * 1024) {
wafwerar's avatar
wafwerar 已提交
4698 4699
    taosMemoryFreeClear(pInfo);
    taosMemoryFreeClear(pOperator);
H
Haojun Liao 已提交
4700 4701 4702
    terrno = TSDB_CODE_QRY_OUT_OF_MEMORY;
    return NULL;
  }
4703

dengyihao's avatar
dengyihao 已提交
4704
  pInfo->bufPageSize = rowSize < 1024 ? 1024 * 2 : rowSize * 2;  // there are headers, so pageSize = rowSize + header
4705

wmmhello's avatar
wmmhello 已提交
4706
  pInfo->sortBufSize = pInfo->bufPageSize * 16;  // TODO dynamic set the available sort buffer
L
Liu Jicong 已提交
4707 4708 4709
  pInfo->numOfRowsInRes = 1024;
  pInfo->pDataBlock = pResBlock;
  pInfo->pSortInfo = pSortInfo;
4710
  pInfo->inputSlotMap = pIndexMap;
H
Haojun Liao 已提交
4711

dengyihao's avatar
dengyihao 已提交
4712
  pOperator->name = "SortOperator";
L
Liu Jicong 已提交
4713 4714
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_SORT;
  pOperator->blockingOptr = true;
dengyihao's avatar
dengyihao 已提交
4715 4716
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
4717

dengyihao's avatar
dengyihao 已提交
4718
  pOperator->pTaskInfo = pTaskInfo;
L
Liu Jicong 已提交
4719 4720
  pOperator->fpSet =
      createOperatorFpSet(operatorDummyOpenFn, doSort, NULL, NULL, destroyOrderOperatorInfo, NULL, NULL, NULL);
4721

4722
  int32_t code = appendDownstream(pOperator, &downstream, 1);
4723
  return pOperator;
H
Haojun Liao 已提交
4724

dengyihao's avatar
dengyihao 已提交
4725
_error:
H
Haojun Liao 已提交
4726 4727 4728 4729
  pTaskInfo->code = TSDB_CODE_OUT_OF_MEMORY;
  taosMemoryFree(pInfo);
  taosMemoryFree(pOperator);
  return NULL;
4730 4731
}

4732 4733
int32_t getTableScanOrder(SOperatorInfo* pOperator) {
  if (pOperator->operatorType != QUERY_NODE_PHYSICAL_PLAN_TABLE_SCAN) {
H
Haojun Liao 已提交
4734
    if (pOperator->pDownstream == NULL || pOperator->pDownstream[0] == NULL) {
4735
      return TSDB_ORDER_ASC;
H
Haojun Liao 已提交
4736 4737
    } else {
      return getTableScanOrder(pOperator->pDownstream[0]);
4738 4739 4740 4741 4742 4743
    }
  }

  STableScanInfo* pTableScanInfo = pOperator->info;
  return pTableScanInfo->cond.order;
}
4744 4745

// this is a blocking operator
L
Liu Jicong 已提交
4746
static int32_t doOpenAggregateOptr(SOperatorInfo* pOperator) {
H
Haojun Liao 已提交
4747 4748
  if (OPTR_IS_OPENED(pOperator)) {
    return TSDB_CODE_SUCCESS;
4749 4750
  }

H
Haojun Liao 已提交
4751
  SExecTaskInfo*    pTaskInfo = pOperator->pTaskInfo;
4752
  SAggOperatorInfo* pAggInfo = pOperator->info;
H
Haojun Liao 已提交
4753

dengyihao's avatar
dengyihao 已提交
4754
  SOptrBasicInfo* pInfo = &pAggInfo->binfo;
4755

H
Haojun Liao 已提交
4756
  int32_t        order = TSDB_ORDER_ASC;
H
Haojun Liao 已提交
4757
  SOperatorInfo* downstream = pOperator->pDownstream[0];
4758

H
Haojun Liao 已提交
4759 4760
  bool newgroup = true;
  while (1) {
H
Haojun Liao 已提交
4761
    publishOperatorProfEvent(downstream, QUERY_PROF_BEFORE_OPERATOR_EXEC);
4762
    SSDataBlock* pBlock = downstream->fpSet.getNextFn(downstream, &newgroup);
H
Haojun Liao 已提交
4763
    publishOperatorProfEvent(downstream, QUERY_PROF_AFTER_OPERATOR_EXEC);
4764 4765 4766 4767

    if (pBlock == NULL) {
      break;
    }
H
Haojun Liao 已提交
4768 4769 4770
    //    if (pAggInfo->current != NULL) {
    //      setTagValue(pOperator, pAggInfo->current->pTable, pInfo->pCtx, pOperator->numOfOutput);
    //    }
4771

4772 4773
    // there is an scalar expression that needs to be calculated before apply the group aggregation.
    if (pAggInfo->pScalarExprInfo != NULL) {
dengyihao's avatar
dengyihao 已提交
4774 4775
      projectApplyFunctions(pAggInfo->pScalarExprInfo, pBlock, pBlock, pAggInfo->pScalarCtx, pAggInfo->numOfScalarExpr,
                            NULL);
4776 4777
    }

4778
    // the pDataBlock are always the same one, no need to call this again
H
Haojun Liao 已提交
4779
    setExecutionContext(pOperator->numOfOutput, pBlock->info.groupId, pTaskInfo, pAggInfo);
4780
    setInputDataBlock(pOperator, pInfo->pCtx, pBlock, order, true);
H
Haojun Liao 已提交
4781
    doAggregateImpl(pOperator, 0, pInfo->pCtx);
4782

dengyihao's avatar
dengyihao 已提交
4783
#if 0  // test for encode/decode result info
4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794
    if(pOperator->encodeResultRow){
      char *result = NULL;
      int32_t length = 0;
      SAggSupporter   *pSup = &pAggInfo->aggSup;
      pOperator->encodeResultRow(pOperator, pSup, pInfo, &result, &length);
      taosHashClear(pSup->pResultRowHashTable);
      pInfo->resultRowInfo.size = 0;
      pOperator->decodeResultRow(pOperator, pSup, pInfo, result, length);
      if(result){
        taosMemoryFree(result);
      }
4795
    }
4796
#endif
4797 4798
  }

H
Haojun Liao 已提交
4799 4800 4801
  closeAllResultRows(&pAggInfo->binfo.resultRowInfo);
  finalizeMultiTupleQueryResult(pAggInfo->binfo.pCtx, pOperator->numOfOutput, pAggInfo->aggSup.pResultBuf,
                                &pAggInfo->binfo.resultRowInfo, pAggInfo->binfo.rowCellInfoOffset);
H
Haojun Liao 已提交
4802

4803
  initGroupedResultInfo(&pAggInfo->groupResInfo, pAggInfo->aggSup.pResultRowHashTable, false);
H
Haojun Liao 已提交
4804 4805 4806 4807
  OPTR_SET_OPENED(pOperator);
  return TSDB_CODE_SUCCESS;
}

L
Liu Jicong 已提交
4808 4809
static SSDataBlock* getAggregateResult(SOperatorInfo* pOperator, bool* newgroup) {
  SAggOperatorInfo* pAggInfo = pOperator->info;
H
Haojun Liao 已提交
4810 4811 4812 4813 4814 4815
  SOptrBasicInfo*   pInfo = &pAggInfo->binfo;

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

L
Liu Jicong 已提交
4816
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
4817
  pTaskInfo->code = pOperator->fpSet._openFn(pOperator);
H
Haojun Liao 已提交
4818 4819 4820 4821
  if (pTaskInfo->code != TSDB_CODE_SUCCESS) {
    return NULL;
  }

H
Haojun Liao 已提交
4822
  blockDataEnsureCapacity(pInfo->pRes, pOperator->resultInfo.capacity);
dengyihao's avatar
dengyihao 已提交
4823 4824
  doBuildResultDatablock(pInfo->pRes, &pAggInfo->groupResInfo, pOperator->pExpr, pAggInfo->aggSup.pResultBuf,
                         pInfo->rowCellInfoOffset, pInfo->pCtx);
H
Haojun Liao 已提交
4825 4826 4827
  if (pInfo->pRes->info.rows == 0 || !hasRemainDataInCurrentGroup(&pAggInfo->groupResInfo)) {
    doSetOperatorCompleted(pOperator);
  }
4828

H
Haojun Liao 已提交
4829
  doSetOperatorCompleted(pOperator);
L
Liu Jicong 已提交
4830
  return (blockDataGetNumOfRows(pInfo->pRes) != 0) ? pInfo->pRes : NULL;
4831 4832
}

dengyihao's avatar
dengyihao 已提交
4833 4834
void aggEncodeResultRow(SOperatorInfo* pOperator, SAggSupporter* pSup, SOptrBasicInfo* pInfo, char** result,
                        int32_t* length) {
wmmhello's avatar
wmmhello 已提交
4835
  int32_t size = taosHashGetSize(pSup->pResultRowHashTable);
4836
  size_t  keyLen = sizeof(uint64_t) * 2;  // estimate the key length
wmmhello's avatar
wmmhello 已提交
4837
  int32_t totalSize = sizeof(int32_t) + size * (sizeof(int32_t) + keyLen + sizeof(int32_t) + pSup->resultRowSize);
wafwerar's avatar
wafwerar 已提交
4838
  *result = taosMemoryCalloc(1, totalSize);
L
Liu Jicong 已提交
4839
  if (*result == NULL) {
4840
    longjmp(pOperator->pTaskInfo->env, TSDB_CODE_OUT_OF_MEMORY);
wmmhello's avatar
wmmhello 已提交
4841 4842 4843
  }
  *(int32_t*)(*result) = size;
  int32_t offset = sizeof(int32_t);
4844 4845

  // prepare memory
4846
  SResultRowPosition* pos = &pInfo->resultRowInfo.cur;
dengyihao's avatar
dengyihao 已提交
4847 4848
  void*               pPage = getBufPage(pSup->pResultBuf, pos->pageId);
  SResultRow*         pRow = (SResultRow*)((char*)pPage + pos->offset);
4849 4850 4851
  setBufPageDirty(pPage, true);
  releaseBufPage(pSup->pResultBuf, pPage);

dengyihao's avatar
dengyihao 已提交
4852
  void* pIter = taosHashIterate(pSup->pResultRowHashTable, NULL);
wmmhello's avatar
wmmhello 已提交
4853
  while (pIter) {
dengyihao's avatar
dengyihao 已提交
4854
    void*               key = taosHashGetKey(pIter, &keyLen);
4855
    SResultRowPosition* p1 = (SResultRowPosition*)pIter;
4856

dengyihao's avatar
dengyihao 已提交
4857
    pPage = (SFilePage*)getBufPage(pSup->pResultBuf, p1->pageId);
4858
    pRow = (SResultRow*)((char*)pPage + p1->offset);
4859 4860
    setBufPageDirty(pPage, true);
    releaseBufPage(pSup->pResultBuf, pPage);
wmmhello's avatar
wmmhello 已提交
4861 4862 4863

    // recalculate the result size
    int32_t realTotalSize = offset + sizeof(int32_t) + keyLen + sizeof(int32_t) + pSup->resultRowSize;
L
Liu Jicong 已提交
4864 4865 4866
    if (realTotalSize > totalSize) {
      char* tmp = taosMemoryRealloc(*result, realTotalSize);
      if (tmp == NULL) {
wmmhello's avatar
wmmhello 已提交
4867
        terrno = TSDB_CODE_OUT_OF_MEMORY;
wafwerar's avatar
wafwerar 已提交
4868
        taosMemoryFree(*result);
wmmhello's avatar
wmmhello 已提交
4869
        *result = NULL;
4870
        longjmp(pOperator->pTaskInfo->env, TSDB_CODE_OUT_OF_MEMORY);
L
Liu Jicong 已提交
4871
      } else {
wmmhello's avatar
wmmhello 已提交
4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883
        *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);
4884
    memcpy(*result + offset, pRow, pSup->resultRowSize);
wmmhello's avatar
wmmhello 已提交
4885 4886 4887 4888 4889
    offset += pSup->resultRowSize;

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

L
Liu Jicong 已提交
4890
  if (length) {
wmmhello's avatar
wmmhello 已提交
4891 4892 4893 4894 4895
    *length = offset;
  }
  return;
}

dengyihao's avatar
dengyihao 已提交
4896 4897
bool aggDecodeResultRow(SOperatorInfo* pOperator, SAggSupporter* pSup, SOptrBasicInfo* pInfo, char* result,
                        int32_t length) {
L
Liu Jicong 已提交
4898
  if (!result || length <= 0) {
wmmhello's avatar
wmmhello 已提交
4899 4900 4901 4902 4903 4904 4905
    return false;
  }

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

  int32_t offset = sizeof(int32_t);
L
Liu Jicong 已提交
4906
  while (count-- > 0 && length > offset) {
wmmhello's avatar
wmmhello 已提交
4907 4908 4909
    int32_t keyLen = *(int32_t*)(result + offset);
    offset += sizeof(int32_t);

L
Liu Jicong 已提交
4910 4911 4912
    uint64_t    tableGroupId = *(uint64_t*)(result + offset);
    SResultRow* resultRow = getNewResultRow_rv(pSup->pResultBuf, tableGroupId, pSup->resultRowSize);
    if (!resultRow) {
4913
      longjmp(pOperator->pTaskInfo->env, TSDB_CODE_TSC_INVALID_INPUT);
wmmhello's avatar
wmmhello 已提交
4914
    }
4915

wmmhello's avatar
wmmhello 已提交
4916
    // add a new result set for a new group
4917 4918
    SResultRowPosition pos = {.pageId = resultRow->pageId, .offset = resultRow->offset};
    taosHashPut(pSup->pResultRowHashTable, result + offset, keyLen, &pos, sizeof(SResultRowPosition));
wmmhello's avatar
wmmhello 已提交
4919 4920 4921

    offset += keyLen;
    int32_t valueLen = *(int32_t*)(result + offset);
L
Liu Jicong 已提交
4922
    if (valueLen != pSup->resultRowSize) {
4923
      longjmp(pOperator->pTaskInfo->env, TSDB_CODE_TSC_INVALID_INPUT);
wmmhello's avatar
wmmhello 已提交
4924 4925 4926 4927 4928 4929 4930 4931 4932 4933
    }
    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);
4934
    prepareResultListBuffer(&pInfo->resultRowInfo, pOperator->pTaskInfo->env);
dengyihao's avatar
dengyihao 已提交
4935
    //    pInfo->resultRowInfo.cur = pInfo->resultRowInfo.size;
L
Liu Jicong 已提交
4936 4937
    //    pInfo->resultRowInfo.pPosition[pInfo->resultRowInfo.size++] =
    //        (SResultRowPosition){.pageId = resultRow->pageId, .offset = resultRow->offset};
dengyihao's avatar
dengyihao 已提交
4938
    pInfo->resultRowInfo.cur = (SResultRowPosition){.pageId = resultRow->pageId, .offset = resultRow->offset};
wmmhello's avatar
wmmhello 已提交
4939 4940
  }

L
Liu Jicong 已提交
4941
  if (offset != length) {
4942
    longjmp(pOperator->pTaskInfo->env, TSDB_CODE_TSC_INVALID_INPUT);
wmmhello's avatar
wmmhello 已提交
4943 4944 4945 4946
  }
  return true;
}

4947 4948
enum {
  PROJECT_RETRIEVE_CONTINUE = 0x1,
L
Liu Jicong 已提交
4949
  PROJECT_RETRIEVE_DONE = 0x2,
4950 4951 4952 4953 4954
};

static int32_t handleLimitOffset(SOperatorInfo* pOperator, SSDataBlock* pBlock) {
  SProjectOperatorInfo* pProjectInfo = pOperator->info;
  SOptrBasicInfo*       pInfo = &pProjectInfo->binfo;
L
Liu Jicong 已提交
4955
  SSDataBlock*          pRes = pInfo->pRes;
4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003

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

5004 5005 5006
  // 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);
5007

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

5012
    return PROJECT_RETRIEVE_DONE;
5013
  }
5014

5015
  // todo optimize performance
5016 5017
  // 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 已提交
5018 5019
  if (pRes->info.rows >= pOperator->resultInfo.threshold || pProjectInfo->slimit.offset != -1 ||
      pProjectInfo->slimit.limit != -1) {
5020
    return PROJECT_RETRIEVE_DONE;
L
Liu Jicong 已提交
5021
  } else {  // not full enough, continue to accumulate the output data in the buffer.
5022 5023 5024 5025
    return PROJECT_RETRIEVE_CONTINUE;
  }
}

L
Liu Jicong 已提交
5026
static SSDataBlock* doProjectOperation(SOperatorInfo* pOperator, bool* newgroup) {
5027
  SProjectOperatorInfo* pProjectInfo = pOperator->info;
L
Liu Jicong 已提交
5028
  SOptrBasicInfo*       pInfo = &pProjectInfo->binfo;
5029 5030

  SSDataBlock* pRes = pInfo->pRes;
5031
  blockDataCleanup(pRes);
5032 5033 5034 5035

  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }
dengyihao's avatar
dengyihao 已提交
5036

H
Haojun Liao 已提交
5037
#if 0
5038 5039 5040 5041 5042 5043
  if (pProjectInfo->existDataBlock) {  // TODO refactor
    SSDataBlock* pBlock = pProjectInfo->existDataBlock;
    pProjectInfo->existDataBlock = NULL;
    *newgroup = true;

    // todo dynamic set tags
L
Liu Jicong 已提交
5044 5045 5046
    //    if (pTableQueryInfo != NULL) {
    //      setTagValue(pOperator, pTableQueryInfo->pTable, pInfo->pCtx, pOperator->numOfOutput);
    //    }
5047 5048

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

H
Haojun Liao 已提交
5051
    blockDataEnsureCapacity(pInfo->pRes, pBlock->info.rows);
5052
    projectApplyFunctions(pOperator->pExpr, pInfo->pRes, pBlock, pInfo->pCtx, pOperator->numOfOutput);
L
Liu Jicong 已提交
5053
    if (pRes->info.rows >= pProjectInfo->binfo.capacity * 0.8) {
5054 5055 5056 5057 5058
      copyTsColoum(pRes, pInfo->pCtx, pOperator->numOfOutput);
      resetResultRowEntryResult(pInfo->pCtx, pOperator->numOfOutput);
      return pRes;
    }
  }
H
Haojun Liao 已提交
5059
#endif
5060

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

L
Liu Jicong 已提交
5063
  while (1) {
5064 5065
    bool prevVal = *newgroup;

H
Haojun Liao 已提交
5066
    // The downstream exec may change the value of the newgroup, so use a local variable instead.
H
Haojun Liao 已提交
5067
    publishOperatorProfEvent(downstream, QUERY_PROF_BEFORE_OPERATOR_EXEC);
5068
    SSDataBlock* pBlock = downstream->fpSet.getNextFn(downstream, newgroup);
H
Haojun Liao 已提交
5069
    publishOperatorProfEvent(downstream, QUERY_PROF_AFTER_OPERATOR_EXEC);
5070 5071 5072

    if (pBlock == NULL) {
      *newgroup = prevVal;
5073
      setTaskStatus(pOperator->pTaskInfo, TASK_COMPLETED);
5074 5075 5076 5077 5078 5079 5080 5081
      break;
    }

    // Return result of the previous group in the firstly.
    if (*newgroup) {
      if (pRes->info.rows > 0) {
        pProjectInfo->existDataBlock = pBlock;
        break;
L
Liu Jicong 已提交
5082
      } else {  // init output buffer for a new group data
5083 5084 5085 5086 5087
        initCtxOutputBuffer(pInfo->pCtx, pOperator->numOfOutput);
      }
    }

    // todo dynamic set tags
H
Haojun Liao 已提交
5088 5089 5090 5091
    //    STableQueryInfo* pTableQueryInfo = pRuntimeEnv->current;
    //    if (pTableQueryInfo != NULL) {
    //      setTagValue(pOperator, pTableQueryInfo->pTable, pInfo->pCtx, pOperator->numOfOutput);
    //    }
5092 5093

    // the pDataBlock are always the same one, no need to call this again
5094 5095 5096
    int32_t order = getTableScanOrder(pOperator->pDownstream[0]);

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

dengyihao's avatar
dengyihao 已提交
5099 5100
    projectApplyFunctions(pOperator->pExpr, pInfo->pRes, pBlock, pInfo->pCtx, pOperator->numOfOutput,
                          pProjectInfo->pPseudoColInfo);
H
Haojun Liao 已提交
5101

5102 5103
    int32_t status = handleLimitOffset(pOperator, pBlock);
    if (status == PROJECT_RETRIEVE_CONTINUE) {
H
Haojun Liao 已提交
5104
      continue;
L
Liu Jicong 已提交
5105
    } else if (status == PROJECT_RETRIEVE_DONE) {
5106 5107 5108
      break;
    }
  }
dengyihao's avatar
dengyihao 已提交
5109

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

L
Liu Jicong 已提交
5112 5113
  //  copyTsColoum(pRes, pInfo->pCtx, pOperator->numOfOutput);
  return (pInfo->pRes->info.rows > 0) ? pInfo->pRes : NULL;
5114 5115
}

L
Liu Jicong 已提交
5116
static int32_t doOpenIntervalAgg(SOperatorInfo* pOperator) {
5117 5118
  if (OPTR_IS_OPENED(pOperator)) {
    return TSDB_CODE_SUCCESS;
5119 5120
  }

dengyihao's avatar
dengyihao 已提交
5121
  SExecTaskInfo*              pTaskInfo = pOperator->pTaskInfo;
H
Haojun Liao 已提交
5122
  STableIntervalOperatorInfo* pInfo = pOperator->info;
5123

5124
  int32_t order = TSDB_ORDER_ASC;
5125
  //  STimeWindow win = {0};
dengyihao's avatar
dengyihao 已提交
5126
  bool           newgroup = false;
H
Haojun Liao 已提交
5127
  SOperatorInfo* downstream = pOperator->pDownstream[0];
5128

5129
  while (1) {
H
Haojun Liao 已提交
5130
    publishOperatorProfEvent(downstream, QUERY_PROF_BEFORE_OPERATOR_EXEC);
5131
    SSDataBlock* pBlock = downstream->fpSet.getNextFn(downstream, &newgroup);
H
Haojun Liao 已提交
5132
    publishOperatorProfEvent(downstream, QUERY_PROF_AFTER_OPERATOR_EXEC);
5133 5134 5135 5136 5137

    if (pBlock == NULL) {
      break;
    }

5138
    //    setTagValue(pOperator, pRuntimeEnv->current->pTable, pInfo->pCtx, pOperator->numOfOutput);
5139
    // the pDataBlock are always the same one, no need to call this again
5140
    setInputDataBlock(pOperator, pInfo->binfo.pCtx, pBlock, order, true);
5141 5142 5143
    STableQueryInfo* pTableQueryInfo = pInfo->pCurrent;

    setIntervalQueryRange(pTableQueryInfo, pBlock->info.window.skey, &pTaskInfo->window);
5144
    hashIntervalAgg(pOperator, &pInfo->binfo.resultRowInfo, pBlock, pBlock->info.groupId);
5145

dengyihao's avatar
dengyihao 已提交
5146
#if 0  // test for encode/decode result info
5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157
    if(pOperator->encodeResultRow){
      char *result = NULL;
      int32_t length = 0;
      SAggSupporter   *pSup = &pInfo->aggSup;
      pOperator->encodeResultRow(pOperator, pSup, &pInfo->binfo, &result, &length);
      taosHashClear(pSup->pResultRowHashTable);
      pInfo->binfo.resultRowInfo.size = 0;
      pOperator->decodeResultRow(pOperator, pSup, &pInfo->binfo, result, length);
      if(result){
        taosMemoryFree(result);
      }
5158
    }
5159
#endif
5160 5161
  }

H
Haojun Liao 已提交
5162
  closeAllResultRows(&pInfo->binfo.resultRowInfo);
L
Liu Jicong 已提交
5163 5164
  finalizeMultiTupleQueryResult(pInfo->binfo.pCtx, pOperator->numOfOutput, pInfo->aggSup.pResultBuf,
                                &pInfo->binfo.resultRowInfo, pInfo->binfo.rowCellInfoOffset);
5165

5166
  initGroupedResultInfo(&pInfo->groupResInfo, pInfo->aggSup.pResultRowHashTable, true);
5167 5168 5169 5170
  OPTR_SET_OPENED(pOperator);
  return TSDB_CODE_SUCCESS;
}

L
Liu Jicong 已提交
5171
static SSDataBlock* doBuildIntervalResult(SOperatorInfo* pOperator, bool* newgroup) {
5172
  STableIntervalOperatorInfo* pInfo = pOperator->info;
L
Liu Jicong 已提交
5173
  SExecTaskInfo*              pTaskInfo = pOperator->pTaskInfo;
5174 5175 5176 5177 5178

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

5179 5180
  SSDataBlock* pBlock = pInfo->binfo.pRes;

5181
  if (pInfo->execModel == OPTR_EXEC_MODEL_STREAM) {
5182
    return pOperator->fpSet.getStreamResFn(pOperator, newgroup);
5183
  } else {
5184
    pTaskInfo->code = pOperator->fpSet._openFn(pOperator);
5185 5186 5187
    if (pTaskInfo->code != TSDB_CODE_SUCCESS) {
      return NULL;
    }
5188

5189
    blockDataEnsureCapacity(pBlock, pOperator->resultInfo.capacity);
dengyihao's avatar
dengyihao 已提交
5190 5191
    doBuildResultDatablock(pBlock, &pInfo->groupResInfo, pOperator->pExpr, pInfo->aggSup.pResultBuf,
                           pInfo->binfo.rowCellInfoOffset, pInfo->binfo.pCtx);
5192

5193
    if (pBlock->info.rows == 0 || !hasRemainDataInCurrentGroup(&pInfo->groupResInfo)) {
5194 5195
      doSetOperatorCompleted(pOperator);
    }
5196

5197
    return pBlock->info.rows == 0 ? NULL : pBlock;
5198 5199 5200
  }
}

dengyihao's avatar
dengyihao 已提交
5201
static SSDataBlock* doStreamIntervalAgg(SOperatorInfo* pOperator, bool* newgroup) {
5202
  STableIntervalOperatorInfo* pInfo = pOperator->info;
dengyihao's avatar
dengyihao 已提交
5203
  int32_t                     order = TSDB_ORDER_ASC;
5204 5205 5206 5207 5208 5209

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

  if (pOperator->status == OP_RES_TO_RETURN) {
dengyihao's avatar
dengyihao 已提交
5210 5211
    doBuildResultDatablock(pInfo->binfo.pRes, &pInfo->groupResInfo, pOperator->pExpr, pInfo->aggSup.pResultBuf,
                           pInfo->binfo.rowCellInfoOffset, pInfo->binfo.pCtx);
5212 5213 5214
    if (pInfo->binfo.pRes->info.rows == 0 || !hasRemainDataInCurrentGroup(&pInfo->groupResInfo)) {
      pOperator->status = OP_EXEC_DONE;
    }
5215
    return pInfo->binfo.pRes->info.rows == 0 ? NULL : pInfo->binfo.pRes;
5216 5217 5218
  }

  //  STimeWindow win = {0};
5219
  *newgroup = false;
5220 5221 5222 5223 5224 5225
  SOperatorInfo* downstream = pOperator->pDownstream[0];

  SArray* pUpdated = NULL;

  while (1) {
    publishOperatorProfEvent(downstream, QUERY_PROF_BEFORE_OPERATOR_EXEC);
5226
    SSDataBlock* pBlock = downstream->fpSet.getNextFn(downstream, newgroup);
5227 5228 5229 5230 5231 5232
    publishOperatorProfEvent(downstream, QUERY_PROF_AFTER_OPERATOR_EXEC);

    if (pBlock == NULL) {
      break;
    }

dengyihao's avatar
dengyihao 已提交
5233 5234
    // The timewindows that overlaps the timestamps of the input pBlock need to be recalculated and return to the
    // caller. Note that all the time window are not close till now.
5235 5236 5237

    //    setTagValue(pOperator, pRuntimeEnv->current->pTable, pInfo->pCtx, pOperator->numOfOutput);
    // the pDataBlock are always the same one, no need to call this again
5238
    setInputDataBlock(pOperator, pInfo->binfo.pCtx, pBlock, order, true);
5239 5240 5241
    pUpdated = hashIntervalAgg(pOperator, &pInfo->binfo.resultRowInfo, pBlock, 0);
  }

dengyihao's avatar
dengyihao 已提交
5242 5243
  finalizeUpdatedResult(pInfo->binfo.pCtx, pOperator->numOfOutput, pInfo->aggSup.pResultBuf, pUpdated,
                        pInfo->binfo.rowCellInfoOffset);
5244

H
Haojun Liao 已提交
5245
  initMultiResInfoFromArrayList(&pInfo->groupResInfo, pUpdated);
5246
  blockDataEnsureCapacity(pInfo->binfo.pRes, pOperator->resultInfo.capacity);
dengyihao's avatar
dengyihao 已提交
5247 5248
  doBuildResultDatablock(pInfo->binfo.pRes, &pInfo->groupResInfo, pOperator->pExpr, pInfo->aggSup.pResultBuf,
                         pInfo->binfo.rowCellInfoOffset, pInfo->binfo.pCtx);
5249 5250 5251 5252 5253 5254 5255

  ASSERT(pInfo->binfo.pRes->info.rows > 0);
  pOperator->status = OP_RES_TO_RETURN;

  return pInfo->binfo.pRes->info.rows == 0 ? NULL : pInfo->binfo.pRes;
}

dengyihao's avatar
dengyihao 已提交
5256
static SSDataBlock* doAllIntervalAgg(SOperatorInfo* pOperator, bool* newgroup) {
5257 5258 5259 5260
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

5261
  STimeSliceOperatorInfo* pSliceInfo = pOperator->info;
5262
  if (pOperator->status == OP_RES_TO_RETURN) {
5263
    //    doBuildResultDatablock(&pRuntimeEnv->groupResInfo, pRuntimeEnv, pIntervalInfo->pRes);
5264
    if (pSliceInfo->binfo.pRes->info.rows == 0 || !hasRemainDataInCurrentGroup(&pSliceInfo->groupResInfo)) {
5265 5266 5267
      doSetOperatorCompleted(pOperator);
    }

5268
    return pSliceInfo->binfo.pRes;
5269 5270
  }

dengyihao's avatar
dengyihao 已提交
5271 5272
  int32_t order = TSDB_ORDER_ASC;
  //  STimeWindow win = pQueryAttr->window;
H
Haojun Liao 已提交
5273
  SOperatorInfo* downstream = pOperator->pDownstream[0];
5274

L
Liu Jicong 已提交
5275
  while (1) {
H
Haojun Liao 已提交
5276
    publishOperatorProfEvent(downstream, QUERY_PROF_BEFORE_OPERATOR_EXEC);
5277
    SSDataBlock* pBlock = downstream->fpSet.getNextFn(downstream, newgroup);
H
Haojun Liao 已提交
5278
    publishOperatorProfEvent(downstream, QUERY_PROF_AFTER_OPERATOR_EXEC);
5279 5280 5281 5282
    if (pBlock == NULL) {
      break;
    }

L
Liu Jicong 已提交
5283
    //    setTagValue(pOperator, pRuntimeEnv->current->pTable, pIntervalInfo->pCtx, pOperator->numOfOutput);
5284
    // the pDataBlock are always the same one, no need to call this again
5285
    setInputDataBlock(pOperator, pSliceInfo->binfo.pCtx, pBlock, order, true);
dengyihao's avatar
dengyihao 已提交
5286
    //    hashAllIntervalAgg(pOperator, &pSliceInfo->binfo.resultRowInfo, pBlock, 0);
5287 5288 5289 5290
  }

  // restore the value
  pOperator->status = OP_RES_TO_RETURN;
5291
  closeAllResultRows(&pSliceInfo->binfo.resultRowInfo);
5292
  setTaskStatus(pOperator->pTaskInfo, TASK_COMPLETED);
dengyihao's avatar
dengyihao 已提交
5293
  //  finalizeQueryResult(pSliceInfo->binfo.pCtx, pOperator->numOfOutput);
5294

L
Liu Jicong 已提交
5295
  //  initGroupedResultInfo(&pSliceInfo->groupResInfo, &pSliceInfo->binfo.resultRowInfo);
5296
  //  doBuildResultDatablock(&pRuntimeEnv->groupResInfo, pRuntimeEnv, pSliceInfo->pRes);
5297

5298
  if (pSliceInfo->binfo.pRes->info.rows == 0 || !hasRemainDataInCurrentGroup(&pSliceInfo->groupResInfo)) {
5299 5300 5301
    pOperator->status = OP_EXEC_DONE;
  }

5302
  return pSliceInfo->binfo.pRes->info.rows == 0 ? NULL : pSliceInfo->binfo.pRes;
5303 5304
}

L
Liu Jicong 已提交
5305
static SSDataBlock* doSTableIntervalAgg(SOperatorInfo* pOperator, bool* newgroup) {
5306 5307 5308 5309
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

5310
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
5311

5312
  STableIntervalOperatorInfo* pInfo = pOperator->info;
5313 5314
  if (pOperator->status == OP_RES_TO_RETURN) {
    int64_t st = taosGetTimestampUs();
5315
    if (pInfo->binfo.pRes->info.rows == 0 || !hasRemainDataInCurrentGroup(&pInfo->groupResInfo)) {
5316 5317
      doSetOperatorCompleted(pOperator);
    }
5318 5319

    return pInfo->binfo.pRes->info.rows == 0 ? NULL : pInfo->binfo.pRes;
5320 5321
  }

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

L
Liu Jicong 已提交
5324
  while (1) {
H
Haojun Liao 已提交
5325
    publishOperatorProfEvent(downstream, QUERY_PROF_BEFORE_OPERATOR_EXEC);
5326
    SSDataBlock* pBlock = downstream->fpSet.getNextFn(downstream, newgroup);
H
Haojun Liao 已提交
5327
    publishOperatorProfEvent(downstream, QUERY_PROF_AFTER_OPERATOR_EXEC);
5328 5329 5330 5331 5332 5333

    if (pBlock == NULL) {
      break;
    }

    // the pDataBlock are always the same one, no need to call this again
L
Liu Jicong 已提交
5334
    //    setTagValue(pOperator, pTableQueryInfo->pTable, pIntervalInfo->pCtx, pOperator->numOfOutput);
5335
    setInputDataBlock(pOperator, pInfo->binfo.pCtx, pBlock, TSDB_ORDER_ASC, true);
5336
    STableQueryInfo* pTableQueryInfo = pInfo->pCurrent;
5337

5338
    setIntervalQueryRange(pTableQueryInfo, pBlock->info.window.skey, &pTaskInfo->window);
dengyihao's avatar
dengyihao 已提交
5339
    //    hashIntervalAgg(pOperator, &pTableQueryInfo->resInfo, pBlock, pBlock->info.groupId);
5340 5341
  }

5342 5343 5344
  closeAllResultRows(&pInfo->binfo.resultRowInfo);
  finalizeMultiTupleQueryResult(pInfo->binfo.pCtx, pOperator->numOfOutput, pInfo->aggSup.pResultBuf,
                                &pInfo->binfo.resultRowInfo, pInfo->binfo.rowCellInfoOffset);
5345

L
Liu Jicong 已提交
5346
  //  initGroupedResultInfo(&pInfo->groupResInfo, &pInfo->binfo.resultRowInfo);
5347 5348
  OPTR_SET_OPENED(pOperator);

5349
  blockDataEnsureCapacity(pInfo->binfo.pRes, pOperator->resultInfo.capacity);
dengyihao's avatar
dengyihao 已提交
5350 5351
  doBuildResultDatablock(pInfo->binfo.pRes, &pInfo->groupResInfo, pOperator->pExpr, pInfo->aggSup.pResultBuf,
                         pInfo->binfo.rowCellInfoOffset, pInfo->binfo.pCtx);
5352 5353 5354

  if (pInfo->binfo.pRes->info.rows == 0 || !hasRemainDataInCurrentGroup(&pInfo->groupResInfo)) {
    doSetOperatorCompleted(pOperator);
5355 5356
  }

5357
  return pInfo->binfo.pRes->info.rows == 0 ? NULL : pInfo->binfo.pRes;
5358 5359
}

5360
static void doStateWindowAggImpl(SOperatorInfo* pOperator, SStateWindowOperatorInfo* pInfo, SSDataBlock* pBlock) {
dengyihao's avatar
dengyihao 已提交
5361
  SExecTaskInfo*  pTaskInfo = pOperator->pTaskInfo;
5362 5363
  SOptrBasicInfo* pBInfo = &pInfo->binfo;

5364
  SColumnInfoData* pStateColInfoData = taosArrayGet(pBlock->pDataBlock, pInfo->colIndex);
dengyihao's avatar
dengyihao 已提交
5365
  int64_t          gid = pBlock->info.groupId;
5366

5367 5368 5369 5370 5371 5372 5373 5374
  bool    masterScan = true;
  int32_t numOfOutput = pOperator->numOfOutput;

  int16_t bytes = pStateColInfoData->info.bytes;
  int16_t type = pStateColInfoData->info.type;

  SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, 0);
  TSKEY*           tsList = (TSKEY*)pColInfoData->pData;
5375

5376 5377
  SWindowRowsSup* pRowSup = &pInfo->winSup;
  pRowSup->numOfRows = 0;
dengyihao's avatar
dengyihao 已提交
5378

5379 5380
  for (int32_t j = 0; j < pBlock->info.rows; ++j) {
    if (colDataIsNull(pStateColInfoData, pBlock->info.rows, j, pBlock->pBlockAgg)) {
5381 5382
      continue;
    }
5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395

    char* val = colDataGetData(pStateColInfoData, j);

    if (!pInfo->hasKey) {
      memcpy(pInfo->stateKey.pData, val, bytes);
      pInfo->hasKey = true;

      doKeepNewWindowStartInfo(pRowSup, tsList, j);
      doKeepTuple(pRowSup, tsList[j]);
    } else if (memcmp(pInfo->stateKey.pData, val, bytes) == 0) {
      doKeepTuple(pRowSup, tsList[j]);
      if (j == 0 && pRowSup->startRowIndex != 0) {
        pRowSup->startRowIndex = 0;
5396
      }
5397
    } else {  // a new state window started
5398
      SResultRow* pResult = NULL;
5399 5400 5401 5402 5403 5404

      // keep the time window for the closed time window.
      STimeWindow window = pRowSup->win;

      pRowSup->win.ekey = pRowSup->win.skey;
      int32_t ret = setResultOutputBufByKey_rv(&pInfo->binfo.resultRowInfo, pBlock->info.uid, &window, masterScan,
dengyihao's avatar
dengyihao 已提交
5405 5406
                                               &pResult, gid, pInfo->binfo.pCtx, numOfOutput,
                                               pInfo->binfo.rowCellInfoOffset, &pInfo->aggSup, pTaskInfo);
5407
      if (ret != TSDB_CODE_SUCCESS) {  // null data, too many state code
5408
        longjmp(pTaskInfo->env, TSDB_CODE_QRY_APP_ERROR);
5409 5410
      }

5411
      updateTimeWindowInfo(&pInfo->twAggSup.timeWindowData, &window, false);
dengyihao's avatar
dengyihao 已提交
5412 5413
      doApplyFunctions(pInfo->binfo.pCtx, &window, &pInfo->twAggSup.timeWindowData, pRowSup->startRowIndex,
                       pRowSup->numOfRows, NULL, pBlock->info.rows, numOfOutput, TSDB_ORDER_ASC);
5414 5415 5416 5417

      // here we start a new session window
      doKeepNewWindowStartInfo(pRowSup, tsList, j);
      doKeepTuple(pRowSup, tsList[j]);
5418 5419 5420 5421
    }
  }

  SResultRow* pResult = NULL;
5422
  pRowSup->win.ekey = tsList[pBlock->info.rows - 1];
dengyihao's avatar
dengyihao 已提交
5423 5424 5425
  int32_t ret = setResultOutputBufByKey_rv(&pInfo->binfo.resultRowInfo, pBlock->info.uid, &pRowSup->win, masterScan,
                                           &pResult, gid, pInfo->binfo.pCtx, numOfOutput,
                                           pInfo->binfo.rowCellInfoOffset, &pInfo->aggSup, pTaskInfo);
5426
  if (ret != TSDB_CODE_SUCCESS) {  // null data, too many state code
5427
    longjmp(pTaskInfo->env, TSDB_CODE_QRY_APP_ERROR);
5428 5429
  }

5430
  updateTimeWindowInfo(&pInfo->twAggSup.timeWindowData, &pRowSup->win, false);
dengyihao's avatar
dengyihao 已提交
5431 5432
  doApplyFunctions(pInfo->binfo.pCtx, &pRowSup->win, &pInfo->twAggSup.timeWindowData, pRowSup->startRowIndex,
                   pRowSup->numOfRows, NULL, pBlock->info.rows, numOfOutput, TSDB_ORDER_ASC);
5433 5434
}

L
Liu Jicong 已提交
5435
static SSDataBlock* doStateWindowAgg(SOperatorInfo* pOperator, bool* newgroup) {
5436 5437 5438 5439
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

5440
  SStateWindowOperatorInfo* pInfo = pOperator->info;
dengyihao's avatar
dengyihao 已提交
5441 5442
  SExecTaskInfo*            pTaskInfo = pOperator->pTaskInfo;
  SOptrBasicInfo*           pBInfo = &pInfo->binfo;
5443 5444

  if (pOperator->status == OP_RES_TO_RETURN) {
dengyihao's avatar
dengyihao 已提交
5445 5446
    doBuildResultDatablock(pBInfo->pRes, &pInfo->groupResInfo, pOperator->pExpr, pInfo->aggSup.pResultBuf,
                           pBInfo->rowCellInfoOffset, pInfo->binfo.pCtx);
5447 5448 5449 5450
    if (pBInfo->pRes->info.rows == 0 || !hasRemainDataInCurrentGroup(&pInfo->groupResInfo)) {
      doSetOperatorCompleted(pOperator);
      return NULL;
    }
5451 5452 5453 5454

    return pBInfo->pRes;
  }

dengyihao's avatar
dengyihao 已提交
5455 5456
  int32_t     order = TSDB_ORDER_ASC;
  STimeWindow win = pTaskInfo->window;
H
Haojun Liao 已提交
5457

H
Haojun Liao 已提交
5458
  SOperatorInfo* downstream = pOperator->pDownstream[0];
5459
  while (1) {
H
Haojun Liao 已提交
5460
    publishOperatorProfEvent(downstream, QUERY_PROF_BEFORE_OPERATOR_EXEC);
5461
    SSDataBlock* pBlock = downstream->fpSet.getNextFn(downstream, newgroup);
H
Haojun Liao 已提交
5462
    publishOperatorProfEvent(downstream, QUERY_PROF_AFTER_OPERATOR_EXEC);
5463 5464 5465 5466

    if (pBlock == NULL) {
      break;
    }
H
Haojun Liao 已提交
5467

5468
    setInputDataBlock(pOperator, pBInfo->pCtx, pBlock, order, true);
5469
    doStateWindowAggImpl(pOperator, pInfo, pBlock);
5470 5471 5472 5473
  }

  pOperator->status = OP_RES_TO_RETURN;
  closeAllResultRows(&pBInfo->resultRowInfo);
dengyihao's avatar
dengyihao 已提交
5474 5475
  finalizeMultiTupleQueryResult(pBInfo->pCtx, pOperator->numOfOutput, pInfo->aggSup.pResultBuf, &pBInfo->resultRowInfo,
                                pBInfo->rowCellInfoOffset);
5476

5477
  initGroupedResultInfo(&pInfo->groupResInfo, pInfo->aggSup.pResultRowHashTable, true);
5478
  blockDataEnsureCapacity(pBInfo->pRes, pOperator->resultInfo.capacity);
dengyihao's avatar
dengyihao 已提交
5479 5480
  doBuildResultDatablock(pBInfo->pRes, &pInfo->groupResInfo, pOperator->pExpr, pInfo->aggSup.pResultBuf,
                         pBInfo->rowCellInfoOffset, pInfo->binfo.pCtx);
5481 5482 5483
  if (pBInfo->pRes->info.rows == 0 || !hasRemainDataInCurrentGroup(&pInfo->groupResInfo)) {
    doSetOperatorCompleted(pOperator);
  }
5484

L
Liu Jicong 已提交
5485
  return pBInfo->pRes->info.rows == 0 ? NULL : pBInfo->pRes;
5486 5487
}

L
Liu Jicong 已提交
5488
static SSDataBlock* doSessionWindowAgg(SOperatorInfo* pOperator, bool* newgroup) {
5489 5490 5491 5492
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

5493
  SSessionAggOperatorInfo* pInfo = pOperator->info;
L
Liu Jicong 已提交
5494
  SOptrBasicInfo*          pBInfo = &pInfo->binfo;
5495 5496

  if (pOperator->status == OP_RES_TO_RETURN) {
dengyihao's avatar
dengyihao 已提交
5497 5498
    doBuildResultDatablock(pBInfo->pRes, &pInfo->groupResInfo, pOperator->pExpr, pInfo->aggSup.pResultBuf,
                           pBInfo->rowCellInfoOffset, pInfo->binfo.pCtx);
5499 5500 5501
    if (pBInfo->pRes->info.rows == 0 || !hasRemainDataInCurrentGroup(&pInfo->groupResInfo)) {
      doSetOperatorCompleted(pOperator);
      return NULL;
5502 5503 5504 5505 5506
    }

    return pBInfo->pRes;
  }

L
Liu Jicong 已提交
5507
  int32_t        order = TSDB_ORDER_ASC;
H
Haojun Liao 已提交
5508
  SOperatorInfo* downstream = pOperator->pDownstream[0];
5509

L
Liu Jicong 已提交
5510
  while (1) {
H
Haojun Liao 已提交
5511
    publishOperatorProfEvent(downstream, QUERY_PROF_BEFORE_OPERATOR_EXEC);
5512
    SSDataBlock* pBlock = downstream->fpSet.getNextFn(downstream, newgroup);
H
Haojun Liao 已提交
5513
    publishOperatorProfEvent(downstream, QUERY_PROF_AFTER_OPERATOR_EXEC);
5514 5515 5516 5517 5518
    if (pBlock == NULL) {
      break;
    }

    // the pDataBlock are always the same one, no need to call this again
5519
    setInputDataBlock(pOperator, pBInfo->pCtx, pBlock, order, true);
5520
    doSessionWindowAggImpl(pOperator, pInfo, pBlock);
5521 5522 5523 5524 5525
  }

  // restore the value
  pOperator->status = OP_RES_TO_RETURN;
  closeAllResultRows(&pBInfo->resultRowInfo);
dengyihao's avatar
dengyihao 已提交
5526 5527
  finalizeMultiTupleQueryResult(pBInfo->pCtx, pOperator->numOfOutput, pInfo->aggSup.pResultBuf, &pBInfo->resultRowInfo,
                                pBInfo->rowCellInfoOffset);
5528

5529
  initGroupedResultInfo(&pInfo->groupResInfo, pInfo->aggSup.pResultRowHashTable, true);
5530
  blockDataEnsureCapacity(pBInfo->pRes, pOperator->resultInfo.capacity);
dengyihao's avatar
dengyihao 已提交
5531 5532
  doBuildResultDatablock(pBInfo->pRes, &pInfo->groupResInfo, pOperator->pExpr, pInfo->aggSup.pResultBuf,
                         pBInfo->rowCellInfoOffset, pInfo->binfo.pCtx);
5533 5534
  if (pBInfo->pRes->info.rows == 0 || !hasRemainDataInCurrentGroup(&pInfo->groupResInfo)) {
    doSetOperatorCompleted(pOperator);
5535 5536
  }

L
Liu Jicong 已提交
5537
  return pBInfo->pRes->info.rows == 0 ? NULL : pBInfo->pRes;
5538 5539
}

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

L
Liu Jicong 已提交
5544 5545
  int64_t ekey = Q_STATUS_EQUAL(pTaskInfo->status, TASK_COMPLETED) ? pTaskInfo->window.ekey
                                                                   : pInfo->existNewGroupBlock->info.window.ekey;
5546 5547
  taosResetFillInfo(pInfo->pFillInfo, getFillInfoStart(pInfo->pFillInfo));

5548
  taosFillSetStartInfo(pInfo->pFillInfo, pInfo->existNewGroupBlock->info.rows, ekey);
5549 5550
  taosFillSetInputDataBlock(pInfo->pFillInfo, pInfo->existNewGroupBlock);

H
Haojun Liao 已提交
5551
  doFillTimeIntervalGapsInResults(pInfo->pFillInfo, pInfo->pRes, pResultInfo->capacity, pInfo->p);
5552 5553 5554 5555
  pInfo->existNewGroupBlock = NULL;
  *newgroup = true;
}

L
Liu Jicong 已提交
5556 5557
static void doHandleRemainBlockFromNewGroup(SFillOperatorInfo* pInfo, SResultInfo* pResultInfo, bool* newgroup,
                                            SExecTaskInfo* pTaskInfo) {
5558 5559
  if (taosFillHasMoreResults(pInfo->pFillInfo)) {
    *newgroup = false;
H
Haojun Liao 已提交
5560 5561
    doFillTimeIntervalGapsInResults(pInfo->pFillInfo, pInfo->pRes, (int32_t)pResultInfo->capacity, pInfo->p);
    if (pInfo->pRes->info.rows > pResultInfo->threshold || (!pInfo->multigroupResult)) {
5562 5563 5564 5565 5566 5567
      return;
    }
  }

  // handle the cached new group data block
  if (pInfo->existNewGroupBlock) {
5568
    doHandleRemainBlockForNewGroupImpl(pInfo, pResultInfo, newgroup, pTaskInfo);
5569 5570 5571
  }
}

L
Liu Jicong 已提交
5572 5573 5574
static SSDataBlock* doFill(SOperatorInfo* pOperator, bool* newgroup) {
  SFillOperatorInfo* pInfo = pOperator->info;
  SExecTaskInfo*     pTaskInfo = pOperator->pTaskInfo;
5575

H
Haojun Liao 已提交
5576
  SResultInfo* pResultInfo = &pOperator->resultInfo;
5577 5578 5579
  SSDataBlock* pResBlock = pInfo->pRes;

  blockDataCleanup(pResBlock);
5580 5581 5582 5583
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

5584
  doHandleRemainBlockFromNewGroup(pInfo, pResultInfo, newgroup, pTaskInfo);
5585 5586
  if (pResBlock->info.rows > pResultInfo->threshold || (!pInfo->multigroupResult && pResBlock->info.rows > 0)) {
    return pResBlock;
H
Haojun Liao 已提交
5587
  }
5588

H
Haojun Liao 已提交
5589
  SOperatorInfo* pDownstream = pOperator->pDownstream[0];
L
Liu Jicong 已提交
5590
  while (1) {
H
Haojun Liao 已提交
5591
    publishOperatorProfEvent(pDownstream, QUERY_PROF_BEFORE_OPERATOR_EXEC);
5592
    SSDataBlock* pBlock = pDownstream->fpSet.getNextFn(pDownstream, newgroup);
H
Haojun Liao 已提交
5593
    publishOperatorProfEvent(pDownstream, QUERY_PROF_AFTER_OPERATOR_EXEC);
5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604

    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
5605
      taosFillSetStartInfo(pInfo->pFillInfo, 0, pTaskInfo->window.ekey);
5606 5607 5608 5609 5610 5611 5612
    } else {
      if (pBlock == NULL) {
        if (pInfo->totalInputRows == 0) {
          pOperator->status = OP_EXEC_DONE;
          return NULL;
        }

5613
        taosFillSetStartInfo(pInfo->pFillInfo, 0, pTaskInfo->window.ekey);
5614 5615 5616 5617 5618 5619 5620
      } else {
        pInfo->totalInputRows += pBlock->info.rows;
        taosFillSetStartInfo(pInfo->pFillInfo, pBlock->info.rows, pBlock->info.window.ekey);
        taosFillSetInputDataBlock(pInfo->pFillInfo, pBlock);
      }
    }

5621
    doFillTimeIntervalGapsInResults(pInfo->pFillInfo, pResBlock, pOperator->resultInfo.capacity, pInfo->p);
5622 5623

    // current group has no more result to return
5624
    if (pResBlock->info.rows > 0) {
5625 5626
      // 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
5627 5628
      if (pResBlock->info.rows > pResultInfo->threshold || pBlock == NULL || (!pInfo->multigroupResult)) {
        return pResBlock;
5629 5630
      }

5631
      doHandleRemainBlockFromNewGroup(pInfo, pResultInfo, newgroup, pTaskInfo);
5632 5633
      if (pResBlock->info.rows > pOperator->resultInfo.threshold || pBlock == NULL) {
        return pResBlock;
5634 5635 5636
      }
    } else if (pInfo->existNewGroupBlock) {  // try next group
      assert(pBlock != NULL);
5637
      doHandleRemainBlockForNewGroupImpl(pInfo, pResultInfo, newgroup, pTaskInfo);
5638 5639
      if (pResBlock->info.rows > pResultInfo->threshold) {
        return pResBlock;
5640 5641 5642 5643 5644 5645 5646 5647
      }
    } else {
      return NULL;
    }
  }
}

// todo set the attribute of query scan count
H
Haojun Liao 已提交
5648
static int32_t getNumOfScanTimes(STaskAttr* pQueryAttr) {
L
Liu Jicong 已提交
5649
  for (int32_t i = 0; i < pQueryAttr->numOfOutput; ++i) {
5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663
    int32_t functionId = getExprFunctionId(&pQueryAttr->pExpr1[i]);
    if (functionId == FUNCTION_STDDEV || functionId == FUNCTION_PERCT) {
      return 2;
    }
  }

  return 1;
}

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

5664 5665
  if (pOperator->fpSet.closeFn != NULL) {
    pOperator->fpSet.closeFn(pOperator->info, pOperator->numOfOutput);
5666 5667
  }

H
Haojun Liao 已提交
5668
  if (pOperator->pDownstream != NULL) {
L
Liu Jicong 已提交
5669
    for (int32_t i = 0; i < pOperator->numOfDownstream; ++i) {
H
Haojun Liao 已提交
5670
      destroyOperatorInfo(pOperator->pDownstream[i]);
5671 5672
    }

wafwerar's avatar
wafwerar 已提交
5673
    taosMemoryFreeClear(pOperator->pDownstream);
H
Haojun Liao 已提交
5674
    pOperator->numOfDownstream = 0;
5675 5676
  }

wafwerar's avatar
wafwerar 已提交
5677 5678
  taosMemoryFreeClear(pOperator->info);
  taosMemoryFreeClear(pOperator);
5679 5680
}

dengyihao's avatar
dengyihao 已提交
5681 5682
int32_t doInitAggInfoSup(SAggSupporter* pAggSup, SqlFunctionCtx* pCtx, int32_t numOfOutput, size_t keyBufSize,
                         const char* pKey) {
5683 5684
  _hash_fn_t hashFn = taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY);

dengyihao's avatar
dengyihao 已提交
5685 5686
  pAggSup->resultRowSize = getResultRowSize(pCtx, numOfOutput);
  pAggSup->keyBuf = taosMemoryCalloc(1, keyBufSize + POINTER_BYTES + sizeof(int64_t));
5687
  pAggSup->pResultRowHashTable = taosHashInit(10, hashFn, true, HASH_NO_LOCK);
L
Liu Jicong 已提交
5688 5689
  //  pAggSup->pResultRowListSet = taosHashInit(100, hashFn, false, HASH_NO_LOCK);
  //  pAggSup->pResultRowArrayList = taosArrayInit(10, sizeof(SResultRowCell));
5690

5691
  if (pAggSup->keyBuf == NULL /*|| pAggSup->pResultRowArrayList == NULL || pAggSup->pResultRowListSet == NULL*/ ||
5692
      pAggSup->pResultRowHashTable == NULL) {
5693 5694 5695
    return TSDB_CODE_OUT_OF_MEMORY;
  }

H
Haojun Liao 已提交
5696 5697 5698 5699 5700
  int32_t code = createDiskbasedBuf(&pAggSup->pResultBuf, 4096, 4096 * 256, pKey, "/tmp/");
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

5701 5702 5703
  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
5704
static void cleanupAggSup(SAggSupporter* pAggSup) {
wafwerar's avatar
wafwerar 已提交
5705
  taosMemoryFreeClear(pAggSup->keyBuf);
5706
  taosHashCleanup(pAggSup->pResultRowHashTable);
L
Liu Jicong 已提交
5707 5708
  //  taosHashCleanup(pAggSup->pResultRowListSet);
  //  taosArrayDestroy(pAggSup->pResultRowArrayList);
H
Haojun Liao 已提交
5709
  destroyDiskbasedBuf(pAggSup->pResultBuf);
5710 5711
}

H
Haojun Liao 已提交
5712
int32_t initAggInfo(SOptrBasicInfo* pBasicInfo, SAggSupporter* pAggSup, SExprInfo* pExprInfo, int32_t numOfCols,
5713
                    SSDataBlock* pResultBlock, size_t keyBufSize, const char* pkey) {
5714
  pBasicInfo->pCtx = createSqlFunctionCtx(pExprInfo, numOfCols, &pBasicInfo->rowCellInfoOffset);
H
Haojun Liao 已提交
5715 5716
  pBasicInfo->pRes = pResultBlock;

5717
  doInitAggInfoSup(pAggSup, pBasicInfo->pCtx, numOfCols, keyBufSize, pkey);
5718

L
Liu Jicong 已提交
5719
  for (int32_t i = 0; i < numOfCols; ++i) {
5720 5721 5722
    pBasicInfo->pCtx[i].pBuf = pAggSup->pResultBuf;
  }

5723
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
5724 5725
}

5726 5727 5728 5729 5730 5731 5732 5733 5734
void initResultSizeInfo(SOperatorInfo* pOperator, int32_t numOfRows) {
  pOperator->resultInfo.capacity = numOfRows;
  pOperator->resultInfo.threshold = numOfRows * 0.75;

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

H
Haojun Liao 已提交
5735
static STableQueryInfo* initTableQueryInfo(const STableGroupInfo* pTableGroupInfo) {
L
Liu Jicong 已提交
5736 5737 5738 5739
  if (pTableGroupInfo->numOfTables == 0) {
    return NULL;
  }

wafwerar's avatar
wafwerar 已提交
5740
  STableQueryInfo* pTableQueryInfo = taosMemoryCalloc(pTableGroupInfo->numOfTables, sizeof(STableQueryInfo));
H
Haojun Liao 已提交
5741 5742
  if (pTableQueryInfo == NULL) {
    return NULL;
H
Haojun Liao 已提交
5743
  }
H
Haojun Liao 已提交
5744 5745

  int32_t index = 0;
L
Liu Jicong 已提交
5746
  for (int32_t i = 0; i < taosArrayGetSize(pTableGroupInfo->pGroupList); ++i) {
H
Haojun Liao 已提交
5747
    SArray* pa = taosArrayGetP(pTableGroupInfo->pGroupList, i);
L
Liu Jicong 已提交
5748
    for (int32_t j = 0; j < taosArrayGetSize(pa); ++j) {
H
Haojun Liao 已提交
5749 5750
      STableKeyInfo* pk = taosArrayGet(pa, j);

H
Haojun Liao 已提交
5751
      STableQueryInfo* pTQueryInfo = &pTableQueryInfo[index++];
dengyihao's avatar
dengyihao 已提交
5752
      //      pTQueryInfo->uid = pk->uid;
L
Liu Jicong 已提交
5753
      pTQueryInfo->lastKey = pk->lastKey;
dengyihao's avatar
dengyihao 已提交
5754
      //      pTQueryInfo->groupIndex = i;
H
Haojun Liao 已提交
5755 5756
    }
  }
H
Haojun Liao 已提交
5757 5758

  STimeWindow win = {0, INT64_MAX};
H
Haojun Liao 已提交
5759 5760
  createTableQueryInfo(pTableQueryInfo, false, win);
  return pTableQueryInfo;
H
Haojun Liao 已提交
5761 5762
}

L
Liu Jicong 已提交
5763
SOperatorInfo* createAggregateOperatorInfo(SOperatorInfo* downstream, SExprInfo* pExprInfo, int32_t numOfCols,
5764
                                           SSDataBlock* pResultBlock, SExprInfo* pScalarExprInfo,
L
Liu Jicong 已提交
5765 5766
                                           int32_t numOfScalarExpr, SExecTaskInfo* pTaskInfo,
                                           const STableGroupInfo* pTableGroupInfo) {
wafwerar's avatar
wafwerar 已提交
5767
  SAggOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SAggOperatorInfo));
L
Liu Jicong 已提交
5768
  SOperatorInfo*    pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
5769 5770 5771
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }
H
Haojun Liao 已提交
5772

H
Haojun Liao 已提交
5773
  int32_t numOfRows = 1;
dengyihao's avatar
dengyihao 已提交
5774
  size_t  keyBufSize = sizeof(int64_t) + sizeof(int64_t) + POINTER_BYTES;
5775 5776

  initResultSizeInfo(pOperator, numOfRows);
dengyihao's avatar
dengyihao 已提交
5777 5778
  int32_t code =
      initAggInfo(&pInfo->binfo, &pInfo->aggSup, pExprInfo, numOfCols, pResultBlock, keyBufSize, pTaskInfo->id.str);
H
Haojun Liao 已提交
5779
  pInfo->pTableQueryInfo = initTableQueryInfo(pTableGroupInfo);
L
Liu Jicong 已提交
5780
  if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
5781 5782
    goto _error;
  }
H
Haojun Liao 已提交
5783

H
Haojun Liao 已提交
5784 5785 5786 5787 5788 5789 5790
  pOperator->resultInfo.capacity = 4096;
  pOperator->resultInfo.threshold = 4096 * 0.75;

  int32_t numOfGroup = 10;  // todo replaced with true value
  pInfo->groupId = INT32_MIN;
  initResultRowInfo(&pInfo->binfo.resultRowInfo, numOfGroup);

5791 5792
  pInfo->pScalarExprInfo = pScalarExprInfo;
  pInfo->numOfScalarExpr = numOfScalarExpr;
5793 5794 5795
  if (pInfo->pScalarExprInfo != NULL) {
    pInfo->pScalarCtx = createSqlFunctionCtx(pScalarExprInfo, numOfCols, &pInfo->rowCellInfoOffset);
  }
5796

dengyihao's avatar
dengyihao 已提交
5797
  pOperator->name = "TableAggregate";
X
Xiaoyu Wang 已提交
5798
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_AGG;
5799
  pOperator->blockingOptr = true;
dengyihao's avatar
dengyihao 已提交
5800 5801 5802 5803 5804
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
  pOperator->pExpr = pExprInfo;
  pOperator->numOfOutput = numOfCols;
  pOperator->pTaskInfo = pTaskInfo;
H
Haojun Liao 已提交
5805

5806 5807
  pOperator->fpSet = createOperatorFpSet(doOpenAggregateOptr, getAggregateResult, NULL, NULL, destroyAggOperatorInfo,
                                         aggEncodeResultRow, aggDecodeResultRow, NULL);
H
Haojun Liao 已提交
5808 5809 5810 5811 5812

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

  return pOperator;
L
Liu Jicong 已提交
5815
_error:
H
Haojun Liao 已提交
5816
  destroyAggOperatorInfo(pInfo, numOfCols);
wafwerar's avatar
wafwerar 已提交
5817 5818
  taosMemoryFreeClear(pInfo);
  taosMemoryFreeClear(pOperator);
H
Haojun Liao 已提交
5819 5820
  pTaskInfo->code = TSDB_CODE_OUT_OF_MEMORY;
  return NULL;
5821 5822
}

H
Haojun Liao 已提交
5823
void doDestroyBasicInfo(SOptrBasicInfo* pInfo, int32_t numOfOutput) {
5824 5825
  assert(pInfo != NULL);

5826
  destroySqlFunctionCtx(pInfo->pCtx, numOfOutput);
wafwerar's avatar
wafwerar 已提交
5827
  taosMemoryFreeClear(pInfo->rowCellInfoOffset);
5828 5829

  cleanupResultRowInfo(&pInfo->resultRowInfo);
H
Haojun Liao 已提交
5830
  pInfo->pRes = blockDataDestroy(pInfo->pRes);
5831 5832
}

H
Haojun Liao 已提交
5833
void destroyBasicOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
5834
  SOptrBasicInfo* pInfo = (SOptrBasicInfo*)param;
5835 5836
  doDestroyBasicInfo(pInfo, numOfOutput);
}
H
Haojun Liao 已提交
5837 5838

void destroyStateWindowOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
5839
  SStateWindowOperatorInfo* pInfo = (SStateWindowOperatorInfo*)param;
5840
  doDestroyBasicInfo(&pInfo->binfo, numOfOutput);
5841
  taosMemoryFreeClear(pInfo->stateKey.pData);
5842
}
H
Haojun Liao 已提交
5843 5844

void destroyAggOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
5845
  SAggOperatorInfo* pInfo = (SAggOperatorInfo*)param;
5846 5847
  doDestroyBasicInfo(&pInfo->binfo, numOfOutput);
}
5848

H
Haojun Liao 已提交
5849
void destroyIntervalOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
5850
  STableIntervalOperatorInfo* pInfo = (STableIntervalOperatorInfo*)param;
H
Haojun Liao 已提交
5851 5852 5853 5854 5855
  doDestroyBasicInfo(&pInfo->binfo, numOfOutput);
  cleanupAggSup(&pInfo->aggSup);
}

void destroySWindowOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
5856
  SSessionAggOperatorInfo* pInfo = (SSessionAggOperatorInfo*)param;
5857 5858 5859
  doDestroyBasicInfo(&pInfo->binfo, numOfOutput);
}

H
Haojun Liao 已提交
5860
void destroySFillOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
5861
  SFillOperatorInfo* pInfo = (SFillOperatorInfo*)param;
5862
  pInfo->pFillInfo = taosDestroyFillInfo(pInfo->pFillInfo);
H
Haojun Liao 已提交
5863
  pInfo->pRes = blockDataDestroy(pInfo->pRes);
wafwerar's avatar
wafwerar 已提交
5864
  taosMemoryFreeClear(pInfo->p);
5865 5866
}

H
Haojun Liao 已提交
5867
static void destroyProjectOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
5868
  SProjectOperatorInfo* pInfo = (SProjectOperatorInfo*)param;
5869 5870 5871
  doDestroyBasicInfo(&pInfo->binfo, numOfOutput);
}

H
Haojun Liao 已提交
5872
static void destroyOrderOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
5873
  SSortOperatorInfo* pInfo = (SSortOperatorInfo*)param;
H
Haojun Liao 已提交
5874 5875
  pInfo->pDataBlock = blockDataDestroy(pInfo->pDataBlock);

H
Haojun Liao 已提交
5876
  taosArrayDestroy(pInfo->pSortInfo);
5877
  taosArrayDestroy(pInfo->inputSlotMap);
5878 5879
}

H
Haojun Liao 已提交
5880
void destroyExchangeOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
5881
  SExchangeInfo* pExInfo = (SExchangeInfo*)param;
H
Haojun Liao 已提交
5882 5883 5884 5885 5886 5887 5888 5889 5890
  taosArrayDestroy(pExInfo->pSources);
  taosArrayDestroy(pExInfo->pSourceDataInfo);
  if (pExInfo->pResult != NULL) {
    blockDataDestroy(pExInfo->pResult);
  }

  tsem_destroy(&pExInfo->ready);
}

H
Haojun Liao 已提交
5891 5892
static SArray* setRowTsColumnOutputInfo(SqlFunctionCtx* pCtx, int32_t numOfCols) {
  SArray* pList = taosArrayInit(4, sizeof(int32_t));
dengyihao's avatar
dengyihao 已提交
5893
  for (int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
5894 5895 5896 5897 5898 5899 5900 5901
    if (fmIsPseudoColumnFunc(pCtx[i].functionId)) {
      taosArrayPush(pList, &i);
    }
  }

  return pList;
}

L
Liu Jicong 已提交
5902
SOperatorInfo* createProjectOperatorInfo(SOperatorInfo* downstream, SExprInfo* pExprInfo, int32_t num,
dengyihao's avatar
dengyihao 已提交
5903 5904
                                         SSDataBlock* pResBlock, SLimit* pLimit, SLimit* pSlimit,
                                         SExecTaskInfo* pTaskInfo) {
wafwerar's avatar
wafwerar 已提交
5905
  SProjectOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SProjectOperatorInfo));
L
Liu Jicong 已提交
5906
  SOperatorInfo*        pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
5907 5908 5909
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }
5910

dengyihao's avatar
dengyihao 已提交
5911 5912 5913
  pInfo->limit = *pLimit;
  pInfo->slimit = *pSlimit;
  pInfo->curOffset = pLimit->offset;
H
Haojun Liao 已提交
5914 5915
  pInfo->curSOffset = pSlimit->offset;

H
Haojun Liao 已提交
5916
  pInfo->binfo.pRes = pResBlock;
H
Haojun Liao 已提交
5917 5918 5919

  int32_t numOfCols = num;
  int32_t numOfRows = 4096;
dengyihao's avatar
dengyihao 已提交
5920
  size_t  keyBufSize = sizeof(int64_t) + sizeof(int64_t) + POINTER_BYTES;
5921 5922 5923

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

dengyihao's avatar
dengyihao 已提交
5927
  pOperator->name = "ProjectOperator";
H
Haojun Liao 已提交
5928
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_PROJECT;
5929
  pOperator->blockingOptr = false;
dengyihao's avatar
dengyihao 已提交
5930 5931 5932 5933
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
  pOperator->pExpr = pExprInfo;
  pOperator->numOfOutput = num;
5934

L
Liu Jicong 已提交
5935 5936
  pOperator->fpSet = createOperatorFpSet(operatorDummyOpenFn, doProjectOperation, NULL, NULL,
                                         destroyProjectOperatorInfo, NULL, NULL, NULL);
L
Liu Jicong 已提交
5937 5938

  pOperator->pTaskInfo = pTaskInfo;
5939
  int32_t code = appendDownstream(pOperator, &downstream, 1);
H
Haojun Liao 已提交
5940
  if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
5941 5942
    goto _error;
  }
5943 5944

  return pOperator;
H
Haojun Liao 已提交
5945

L
Liu Jicong 已提交
5946
_error:
H
Haojun Liao 已提交
5947 5948
  pTaskInfo->code = TSDB_CODE_OUT_OF_MEMORY;
  return NULL;
5949 5950
}

L
Liu Jicong 已提交
5951
SOperatorInfo* createIntervalOperatorInfo(SOperatorInfo* downstream, SExprInfo* pExprInfo, int32_t numOfCols,
5952
                                          SSDataBlock* pResBlock, SInterval* pInterval, int32_t primaryTsSlotId,
dengyihao's avatar
dengyihao 已提交
5953 5954
                                          STimeWindowAggSupp* pTwAggSupp, const STableGroupInfo* pTableGroupInfo,
                                          SExecTaskInfo* pTaskInfo) {
wafwerar's avatar
wafwerar 已提交
5955
  STableIntervalOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(STableIntervalOperatorInfo));
L
Liu Jicong 已提交
5956
  SOperatorInfo*              pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
5957 5958 5959
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }
H
Haojun Liao 已提交
5960

L
Liu Jicong 已提交
5961 5962 5963 5964 5965 5966
  pInfo->order = TSDB_ORDER_ASC;
  pInfo->interval = *pInterval;
  //  pInfo->execModel      = OPTR_EXEC_MODEL_STREAM;
  pInfo->execModel = pTaskInfo->execModel;
  pInfo->win = pTaskInfo->window;
  pInfo->twAggSup = *pTwAggSupp;
5967
  pInfo->primaryTsIndex = primaryTsSlotId;
5968

5969
  int32_t numOfRows = 4096;
dengyihao's avatar
dengyihao 已提交
5970
  size_t  keyBufSize = sizeof(int64_t) + sizeof(int64_t) + POINTER_BYTES;
5971 5972

  initResultSizeInfo(pOperator, numOfRows);
dengyihao's avatar
dengyihao 已提交
5973 5974
  int32_t code =
      initAggInfo(&pInfo->binfo, &pInfo->aggSup, pExprInfo, numOfCols, pResBlock, keyBufSize, pTaskInfo->id.str);
5975
  initExecTimeWindowInfo(&pInfo->twAggSup.timeWindowData, &pInfo->win);
5976

L
Liu Jicong 已提交
5977 5978
  //  pInfo->pTableQueryInfo = initTableQueryInfo(pTableGroupInfo);
  if (code != TSDB_CODE_SUCCESS /* || pInfo->pTableQueryInfo == NULL*/) {
H
Haojun Liao 已提交
5979 5980
    goto _error;
  }
H
Haojun Liao 已提交
5981 5982

  initResultRowInfo(&pInfo->binfo.resultRowInfo, (int32_t)1);
5983

dengyihao's avatar
dengyihao 已提交
5984
  pOperator->name = "TimeIntervalAggOperator";
H
Haojun Liao 已提交
5985
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_INTERVAL;
5986
  pOperator->blockingOptr = true;
dengyihao's avatar
dengyihao 已提交
5987 5988 5989 5990 5991
  pOperator->status = OP_NOT_OPENED;
  pOperator->pExpr = pExprInfo;
  pOperator->pTaskInfo = pTaskInfo;
  pOperator->numOfOutput = numOfCols;
  pOperator->info = pInfo;
5992

L
Liu Jicong 已提交
5993 5994
  pOperator->fpSet = createOperatorFpSet(doOpenIntervalAgg, doBuildIntervalResult, doStreamIntervalAgg, NULL,
                                         destroyIntervalOperatorInfo, aggEncodeResultRow, aggDecodeResultRow, NULL);
5995

H
Haojun Liao 已提交
5996
  code = appendDownstream(pOperator, &downstream, 1);
H
Haojun Liao 已提交
5997 5998 5999 6000
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }

6001
  return pOperator;
H
Haojun Liao 已提交
6002

L
Liu Jicong 已提交
6003
_error:
H
Haojun Liao 已提交
6004
  destroyIntervalOperatorInfo(pInfo, numOfCols);
wafwerar's avatar
wafwerar 已提交
6005 6006
  taosMemoryFreeClear(pInfo);
  taosMemoryFreeClear(pOperator);
H
Haojun Liao 已提交
6007 6008
  pTaskInfo->code = code;
  return NULL;
6009 6010
}

6011 6012
SOperatorInfo* createStreamIntervalOperatorInfo(SOperatorInfo* downstream, SExprInfo* pExprInfo, int32_t numOfCols,
                                                SSDataBlock* pResBlock, SInterval* pInterval, int32_t primaryTsSlotId,
L
Liu Jicong 已提交
6013 6014
                                                STimeWindowAggSupp* pTwAggSupp, const STableGroupInfo* pTableGroupInfo,
                                                SExecTaskInfo* pTaskInfo) {
6015 6016 6017 6018 6019 6020
  STableIntervalOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(STableIntervalOperatorInfo));
  SOperatorInfo*              pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }

L
Liu Jicong 已提交
6021 6022 6023 6024 6025
  pInfo->order = TSDB_ORDER_ASC;
  pInfo->interval = *pInterval;
  pInfo->execModel = OPTR_EXEC_MODEL_STREAM;
  pInfo->win = pTaskInfo->window;
  pInfo->twAggSup = *pTwAggSupp;
6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051
  pInfo->primaryTsIndex = primaryTsSlotId;

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

  initResultSizeInfo(pOperator, numOfRows);
  int32_t code =
      initAggInfo(&pInfo->binfo, &pInfo->aggSup, pExprInfo, numOfCols, pResBlock, keyBufSize, pTaskInfo->id.str);
  initExecTimeWindowInfo(&pInfo->twAggSup.timeWindowData, &pInfo->win);

  //  pInfo->pTableQueryInfo = initTableQueryInfo(pTableGroupInfo);
  if (code != TSDB_CODE_SUCCESS /* || pInfo->pTableQueryInfo == NULL*/) {
    goto _error;
  }

  initResultRowInfo(&pInfo->binfo.resultRowInfo, (int32_t)1);

  pOperator->name = "StreamTimeIntervalAggOperator";
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_INTERVAL;
  pOperator->blockingOptr = true;
  pOperator->status = OP_NOT_OPENED;
  pOperator->pExpr = pExprInfo;
  pOperator->pTaskInfo = pTaskInfo;
  pOperator->numOfOutput = numOfCols;
  pOperator->info = pInfo;

L
Liu Jicong 已提交
6052 6053
  pOperator->fpSet = createOperatorFpSet(doOpenIntervalAgg, doStreamIntervalAgg, doStreamIntervalAgg, NULL,
                                         destroyIntervalOperatorInfo, aggEncodeResultRow, aggDecodeResultRow, NULL);
6054 6055 6056 6057 6058 6059 6060 6061

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

  return pOperator;

L
Liu Jicong 已提交
6062
_error:
6063 6064 6065 6066 6067 6068 6069
  destroyIntervalOperatorInfo(pInfo, numOfCols);
  taosMemoryFreeClear(pInfo);
  taosMemoryFreeClear(pOperator);
  pTaskInfo->code = code;
  return NULL;
}

dengyihao's avatar
dengyihao 已提交
6070 6071
SOperatorInfo* createTimeSliceOperatorInfo(SOperatorInfo* downstream, SExprInfo* pExprInfo, int32_t numOfCols,
                                           SSDataBlock* pResultBlock, SExecTaskInfo* pTaskInfo) {
6072
  STimeSliceOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(STimeSliceOperatorInfo));
dengyihao's avatar
dengyihao 已提交
6073
  SOperatorInfo*          pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
6074 6075 6076
  if (pOperator == NULL || pInfo == NULL) {
    goto _error;
  }
6077

H
Haojun Liao 已提交
6078
  initResultRowInfo(&pInfo->binfo.resultRowInfo, 8);
6079

dengyihao's avatar
dengyihao 已提交
6080
  pOperator->name = "TimeSliceOperator";
L
Liu Jicong 已提交
6081
  //  pOperator->operatorType = OP_AllTimeWindow;
6082
  pOperator->blockingOptr = true;
dengyihao's avatar
dengyihao 已提交
6083 6084 6085 6086 6087
  pOperator->status = OP_NOT_OPENED;
  pOperator->pExpr = pExprInfo;
  pOperator->numOfOutput = numOfCols;
  pOperator->info = pInfo;
  pOperator->pTaskInfo = pTaskInfo;
6088 6089 6090

  pOperator->fpSet = createOperatorFpSet(operatorDummyOpenFn, doAllIntervalAgg, NULL, NULL, destroyBasicOperatorInfo,
                                         NULL, NULL, NULL);
6091

L
Liu Jicong 已提交
6092
  int32_t code = appendDownstream(pOperator, &downstream, 1);
6093
  return pOperator;
6094

dengyihao's avatar
dengyihao 已提交
6095
_error:
6096 6097 6098 6099
  taosMemoryFree(pInfo);
  taosMemoryFree(pOperator);
  pTaskInfo->code = TSDB_CODE_OUT_OF_MEMORY;
  return NULL;
6100 6101
}

dengyihao's avatar
dengyihao 已提交
6102 6103 6104
SOperatorInfo* createStatewindowOperatorInfo(SOperatorInfo* downstream, SExprInfo* pExpr, int32_t numOfCols,
                                             SSDataBlock* pResBlock, STimeWindowAggSupp* pTwAggSup,
                                             SExecTaskInfo* pTaskInfo) {
wafwerar's avatar
wafwerar 已提交
6105
  SStateWindowOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SStateWindowOperatorInfo));
dengyihao's avatar
dengyihao 已提交
6106
  SOperatorInfo*            pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
6107 6108 6109
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }
H
Haojun Liao 已提交
6110

L
Liu Jicong 已提交
6111
  pInfo->colIndex = -1;
6112
  size_t keyBufSize = sizeof(int64_t) + sizeof(int64_t) + POINTER_BYTES;
6113 6114 6115

  initResultSizeInfo(pOperator, 4096);
  initAggInfo(&pInfo->binfo, &pInfo->aggSup, pExpr, numOfCols, pResBlock, keyBufSize, pTaskInfo->id.str);
6116
  initResultRowInfo(&pInfo->binfo.resultRowInfo, 8);
6117

6118 6119 6120
  pInfo->twAggSup = *pTwAggSup;
  initExecTimeWindowInfo(&pInfo->twAggSup.timeWindowData, &pTaskInfo->window);

dengyihao's avatar
dengyihao 已提交
6121
  pOperator->name = "StateWindowOperator";
6122
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_STATE_WINDOW;
6123
  pOperator->blockingOptr = true;
dengyihao's avatar
dengyihao 已提交
6124 6125 6126 6127 6128 6129
  pOperator->status = OP_NOT_OPENED;
  pOperator->pExpr = pExpr;
  pOperator->numOfOutput = numOfCols;

  pOperator->pTaskInfo = pTaskInfo;
  pOperator->info = pInfo;
6130

L
Liu Jicong 已提交
6131 6132
  pOperator->fpSet = createOperatorFpSet(operatorDummyOpenFn, doStateWindowAgg, NULL, NULL,
                                         destroyStateWindowOperatorInfo, aggEncodeResultRow, aggDecodeResultRow, NULL);
6133

H
Haojun Liao 已提交
6134
  int32_t code = appendDownstream(pOperator, &downstream, 1);
6135
  return pOperator;
6136

dengyihao's avatar
dengyihao 已提交
6137
_error:
6138 6139
  pTaskInfo->code = TSDB_CODE_SUCCESS;
  return NULL;
6140 6141
}

L
Liu Jicong 已提交
6142
SOperatorInfo* createSessionAggOperatorInfo(SOperatorInfo* downstream, SExprInfo* pExprInfo, int32_t numOfCols,
dengyihao's avatar
dengyihao 已提交
6143 6144
                                            SSDataBlock* pResBlock, int64_t gap, STimeWindowAggSupp* pTwAggSupp,
                                            SExecTaskInfo* pTaskInfo) {
wafwerar's avatar
wafwerar 已提交
6145
  SSessionAggOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SSessionAggOperatorInfo));
L
Liu Jicong 已提交
6146
  SOperatorInfo*           pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
6147 6148 6149
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }
H
Haojun Liao 已提交
6150

H
Haojun Liao 已提交
6151
  int32_t numOfRows = 4096;
dengyihao's avatar
dengyihao 已提交
6152
  size_t  keyBufSize = sizeof(int64_t) + sizeof(int64_t) + POINTER_BYTES;
6153 6154

  initResultSizeInfo(pOperator, numOfRows);
dengyihao's avatar
dengyihao 已提交
6155 6156
  int32_t code =
      initAggInfo(&pInfo->binfo, &pInfo->aggSup, pExprInfo, numOfCols, pResBlock, keyBufSize, pTaskInfo->id.str);
H
Haojun Liao 已提交
6157 6158 6159
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
6160

6161
  pInfo->twAggSup = *pTwAggSupp;
H
Haojun Liao 已提交
6162
  initResultRowInfo(&pInfo->binfo.resultRowInfo, 8);
6163
  initExecTimeWindowInfo(&pInfo->twAggSup.timeWindowData, &pTaskInfo->window);
6164

dengyihao's avatar
dengyihao 已提交
6165 6166 6167 6168 6169
  pInfo->gap = gap;
  pInfo->binfo.pRes = pResBlock;
  pInfo->winSup.prevTs = INT64_MIN;
  pInfo->reptScan = false;
  pOperator->name = "SessionWindowAggOperator";
H
Haojun Liao 已提交
6170
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_SESSION_WINDOW;
6171
  pOperator->blockingOptr = true;
dengyihao's avatar
dengyihao 已提交
6172 6173 6174 6175
  pOperator->status = OP_NOT_OPENED;
  pOperator->pExpr = pExprInfo;
  pOperator->numOfOutput = numOfCols;
  pOperator->info = pInfo;
6176

L
Liu Jicong 已提交
6177 6178
  pOperator->fpSet = createOperatorFpSet(operatorDummyOpenFn, doSessionWindowAgg, NULL, NULL,
                                         destroySWindowOperatorInfo, aggEncodeResultRow, aggDecodeResultRow, NULL);
dengyihao's avatar
dengyihao 已提交
6179
  pOperator->pTaskInfo = pTaskInfo;
6180

H
Haojun Liao 已提交
6181
  code = appendDownstream(pOperator, &downstream, 1);
6182
  return pOperator;
H
Haojun Liao 已提交
6183

L
Liu Jicong 已提交
6184
_error:
H
Haojun Liao 已提交
6185 6186 6187 6188
  if (pInfo != NULL) {
    destroySWindowOperatorInfo(pInfo, numOfCols);
  }

wafwerar's avatar
wafwerar 已提交
6189 6190
  taosMemoryFreeClear(pInfo);
  taosMemoryFreeClear(pOperator);
H
Haojun Liao 已提交
6191 6192
  pTaskInfo->code = code;
  return NULL;
6193 6194
}

H
Haojun Liao 已提交
6195
static int32_t initFillInfo(SFillOperatorInfo* pInfo, SExprInfo* pExpr, int32_t numOfCols, int64_t* fillVal,
L
Liu Jicong 已提交
6196
                            STimeWindow win, int32_t capacity, const char* id, SInterval* pInterval, int32_t fillType) {
6197
  SFillColInfo* pColInfo = createFillColInfo(pExpr, numOfCols, NULL);
H
Haojun Liao 已提交
6198 6199 6200

  // TODO set correct time precision
  STimeWindow w = TSWINDOW_INITIALIZER;
6201
  getAlignQueryTimeWindow(pInterval, TSDB_TIME_PRECISION_MILLI, win.skey, &w);
H
Haojun Liao 已提交
6202 6203

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

wafwerar's avatar
wafwerar 已提交
6206
  pInfo->p = taosMemoryCalloc(numOfCols, POINTER_BYTES);
H
Haojun Liao 已提交
6207 6208 6209 6210 6211 6212 6213 6214

  if (pInfo->pFillInfo == NULL || pInfo->p == NULL) {
    return TSDB_CODE_OUT_OF_MEMORY;
  } else {
    return TSDB_CODE_SUCCESS;
  }
}

L
Liu Jicong 已提交
6215 6216 6217
SOperatorInfo* createFillOperatorInfo(SOperatorInfo* downstream, SExprInfo* pExpr, int32_t numOfCols,
                                      SInterval* pInterval, SSDataBlock* pResBlock, int32_t fillType, char* fillVal,
                                      bool multigroupResult, SExecTaskInfo* pTaskInfo) {
wafwerar's avatar
wafwerar 已提交
6218
  SFillOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SFillOperatorInfo));
L
Liu Jicong 已提交
6219
  SOperatorInfo*     pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
6220

L
Liu Jicong 已提交
6221
  pInfo->pRes = pResBlock;
6222
  pInfo->multigroupResult = multigroupResult;
L
Liu Jicong 已提交
6223
  pInfo->intervalInfo = *pInterval;
6224

6225 6226
  int32_t type = TSDB_FILL_NONE;
  switch (fillType) {
dengyihao's avatar
dengyihao 已提交
6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244
    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;
6245 6246 6247 6248
    default:
      type = TSDB_FILL_NONE;
  }

H
Haojun Liao 已提交
6249
  SResultInfo* pResultInfo = &pOperator->resultInfo;
6250 6251 6252 6253
  initResultSizeInfo(pOperator, 4096);

  int32_t code = initFillInfo(pInfo, pExpr, numOfCols, (int64_t*)fillVal, pTaskInfo->window, pResultInfo->capacity,
                              pTaskInfo->id.str, pInterval, type);
6254 6255 6256
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
6257

dengyihao's avatar
dengyihao 已提交
6258
  pOperator->name = "FillOperator";
6259
  pOperator->blockingOptr = false;
dengyihao's avatar
dengyihao 已提交
6260
  pOperator->status = OP_NOT_OPENED;
L
Liu Jicong 已提交
6261
  //  pOperator->operatorType = OP_Fill;
dengyihao's avatar
dengyihao 已提交
6262 6263 6264
  pOperator->pExpr = pExpr;
  pOperator->numOfOutput = numOfCols;
  pOperator->info = pInfo;
H
Haojun Liao 已提交
6265

L
Liu Jicong 已提交
6266 6267
  pOperator->fpSet =
      createOperatorFpSet(operatorDummyOpenFn, doFill, NULL, NULL, destroySFillOperatorInfo, NULL, NULL, NULL);
6268
  pOperator->pTaskInfo = pTaskInfo;
6269
  code = appendDownstream(pOperator, &downstream, 1);
6270
  return pOperator;
H
Haojun Liao 已提交
6271

L
Liu Jicong 已提交
6272
_error:
wafwerar's avatar
wafwerar 已提交
6273 6274
  taosMemoryFreeClear(pOperator);
  taosMemoryFreeClear(pInfo);
H
Haojun Liao 已提交
6275
  return NULL;
6276 6277
}

L
Liu Jicong 已提交
6278
static int32_t getColumnIndexInSource(SQueriedTableInfo* pTableInfo, SExprBasicInfo* pExpr, SColumnInfo* pTagCols) {
6279 6280
  int32_t j = 0;

H
Haojun Liao 已提交
6281 6282
  if (TSDB_COL_IS_TAG(pExpr->pParam[0].pCol->type)) {
    if (pExpr->pParam[0].pCol->colId == TSDB_TBNAME_COLUMN_INDEX) {
6283 6284 6285
      return TSDB_TBNAME_COLUMN_INDEX;
    }

L
Liu Jicong 已提交
6286
    while (j < pTableInfo->numOfTags) {
H
Haojun Liao 已提交
6287
      if (pExpr->pParam[0].pCol->colId == pTagCols[j].colId) {
6288 6289 6290 6291 6292 6293
        return j;
      }

      j += 1;
    }

6294
  } /*else if (TSDB_COL_IS_UD_COL(pExpr->colInfo.flag)) {  // user specified column data
6295 6296 6297 6298 6299 6300 6301 6302 6303
    return TSDB_UD_COLUMN_INDEX;
  } else {
    while (j < pTableInfo->numOfCols) {
      if (pExpr->colInfo.colId == pTableInfo->colList[j].colId) {
        return j;
      }

      j += 1;
    }
6304
  }*/
6305 6306 6307 6308

  return INT32_MIN;  // return a less than TSDB_TBNAME_COLUMN_INDEX value
}

L
Liu Jicong 已提交
6309
bool validateExprColumnInfo(SQueriedTableInfo* pTableInfo, SExprBasicInfo* pExpr, SColumnInfo* pTagCols) {
6310 6311 6312 6313
  int32_t j = getColumnIndexInSource(pTableInfo, pExpr, pTagCols);
  return j != INT32_MIN;
}

L
Liu Jicong 已提交
6314 6315
static SResSchema createResSchema(int32_t type, int32_t bytes, int32_t slotId, int32_t scale, int32_t precision,
                                  const char* name) {
H
Haojun Liao 已提交
6316
  SResSchema s = {0};
dengyihao's avatar
dengyihao 已提交
6317 6318 6319 6320
  s.scale = scale;
  s.type = type;
  s.bytes = bytes;
  s.slotId = slotId;
H
Haojun Liao 已提交
6321
  s.precision = precision;
H
Haojun Liao 已提交
6322 6323 6324 6325
  strncpy(s.name, name, tListLen(s.name));

  return s;
}
H
Haojun Liao 已提交
6326

H
Haojun Liao 已提交
6327 6328 6329 6330 6331 6332 6333
static SColumn* createColumn(int32_t blockId, int32_t slotId, SDataType* pType) {
  SColumn* pCol = taosMemoryCalloc(1, sizeof(SColumn));
  if (pCol == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

dengyihao's avatar
dengyihao 已提交
6334 6335 6336 6337 6338
  pCol->slotId = slotId;
  pCol->bytes = pType->bytes;
  pCol->type = pType->type;
  pCol->scale = pType->scale;
  pCol->precision = pType->precision;
H
Haojun Liao 已提交
6339 6340 6341 6342 6343
  pCol->dataBlockId = blockId;

  return pCol;
}

H
Haojun Liao 已提交
6344
SExprInfo* createExprInfo(SNodeList* pNodeList, SNodeList* pGroupKeys, int32_t* numOfExprs) {
H
Haojun Liao 已提交
6345
  int32_t numOfFuncs = LIST_LENGTH(pNodeList);
H
Haojun Liao 已提交
6346 6347 6348 6349
  int32_t numOfGroupKeys = 0;
  if (pGroupKeys != NULL) {
    numOfGroupKeys = LIST_LENGTH(pGroupKeys);
  }
H
Haojun Liao 已提交
6350

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

L
Liu Jicong 已提交
6354
  for (int32_t i = 0; i < (*numOfExprs); ++i) {
H
Haojun Liao 已提交
6355 6356 6357 6358 6359 6360
    STargetNode* pTargetNode = NULL;
    if (i < numOfFuncs) {
      pTargetNode = (STargetNode*)nodesListGetNode(pNodeList, i);
    } else {
      pTargetNode = (STargetNode*)nodesListGetNode(pGroupKeys, i - numOfFuncs);
    }
H
Haojun Liao 已提交
6361

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

wafwerar's avatar
wafwerar 已提交
6364
    pExp->pExpr = taosMemoryCalloc(1, sizeof(tExprNode));
H
Haojun Liao 已提交
6365
    pExp->pExpr->_function.num = 1;
H
Haojun Liao 已提交
6366
    pExp->pExpr->_function.functionId = -1;
H
Haojun Liao 已提交
6367

6368
    int32_t type = nodeType(pTargetNode->pExpr);
H
Haojun Liao 已提交
6369
    // it is a project query, or group by column
6370
    if (type == QUERY_NODE_COLUMN) {
H
Haojun Liao 已提交
6371
      pExp->pExpr->nodeType = QUERY_NODE_COLUMN;
L
Liu Jicong 已提交
6372
      SColumnNode* pColNode = (SColumnNode*)pTargetNode->pExpr;
H
Haojun Liao 已提交
6373

G
Ganlin Zhao 已提交
6374 6375 6376
      pExp->base.pParam = taosMemoryCalloc(1, sizeof(SFunctParam));
      pExp->base.numOfParams = 1;

H
Haojun Liao 已提交
6377
      SDataType* pType = &pColNode->node.resType;
dengyihao's avatar
dengyihao 已提交
6378 6379
      pExp->base.resSchema = createResSchema(pType->type, pType->bytes, pTargetNode->slotId, pType->scale,
                                             pType->precision, pColNode->colName);
H
Haojun Liao 已提交
6380 6381
      pExp->base.pParam[0].pCol = createColumn(pColNode->dataBlockId, pColNode->slotId, pType);
      pExp->base.pParam[0].type = FUNC_PARAM_TYPE_COLUMN;
6382
    } else if (type == QUERY_NODE_VALUE) {
6383 6384 6385 6386 6387 6388 6389
      pExp->pExpr->nodeType = QUERY_NODE_VALUE;
      SValueNode* pValNode = (SValueNode*)pTargetNode->pExpr;

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

      SDataType* pType = &pValNode->node.resType;
dengyihao's avatar
dengyihao 已提交
6390 6391
      pExp->base.resSchema = createResSchema(pType->type, pType->bytes, pTargetNode->slotId, pType->scale,
                                             pType->precision, pValNode->node.aliasName);
6392 6393
      pExp->base.pParam[0].type = FUNC_PARAM_TYPE_VALUE;
      valueNodeToVariant(pValNode, &pExp->base.pParam[0].param);
6394
    } else if (type == QUERY_NODE_FUNCTION) {
H
Haojun Liao 已提交
6395
      pExp->pExpr->nodeType = QUERY_NODE_FUNCTION;
H
Haojun Liao 已提交
6396 6397 6398
      SFunctionNode* pFuncNode = (SFunctionNode*)pTargetNode->pExpr;

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

H
Haojun Liao 已提交
6402
      pExp->pExpr->_function.functionId = pFuncNode->funcId;
H
Haojun Liao 已提交
6403
      pExp->pExpr->_function.pFunctNode = pFuncNode;
dengyihao's avatar
dengyihao 已提交
6404 6405
      strncpy(pExp->pExpr->_function.functionName, pFuncNode->functionName,
              tListLen(pExp->pExpr->_function.functionName));
H
Haojun Liao 已提交
6406 6407

      int32_t numOfParam = LIST_LENGTH(pFuncNode->pParameterList);
G
Ganlin Zhao 已提交
6408 6409 6410 6411

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

H
Haojun Liao 已提交
6412
      for (int32_t j = 0; j < numOfParam; ++j) {
6413
        SNode* p1 = nodesListGetNode(pFuncNode->pParameterList, j);
G
Ganlin Zhao 已提交
6414
        if (p1->type == QUERY_NODE_COLUMN) {
dengyihao's avatar
dengyihao 已提交
6415
          SColumnNode* pcn = (SColumnNode*)p1;
G
Ganlin Zhao 已提交
6416 6417

          pExp->base.pParam[j].type = FUNC_PARAM_TYPE_COLUMN;
H
Haojun Liao 已提交
6418
          pExp->base.pParam[j].pCol = createColumn(pcn->dataBlockId, pcn->slotId, &pcn->node.resType);
G
Ganlin Zhao 已提交
6419 6420 6421
        } else if (p1->type == QUERY_NODE_VALUE) {
          SValueNode* pvn = (SValueNode*)p1;
          pExp->base.pParam[j].type = FUNC_PARAM_TYPE_VALUE;
6422
          valueNodeToVariant(pvn, &pExp->base.pParam[j].param);
G
Ganlin Zhao 已提交
6423
        }
H
Haojun Liao 已提交
6424
      }
6425
    } else if (type == QUERY_NODE_OPERATOR) {
H
Haojun Liao 已提交
6426
      pExp->pExpr->nodeType = QUERY_NODE_OPERATOR;
L
Liu Jicong 已提交
6427
      SOperatorNode* pNode = (SOperatorNode*)pTargetNode->pExpr;
6428

G
Ganlin Zhao 已提交
6429 6430 6431
      pExp->base.pParam = taosMemoryCalloc(1, sizeof(SFunctParam));
      pExp->base.numOfParams = 1;

6432
      SDataType* pType = &pNode->node.resType;
dengyihao's avatar
dengyihao 已提交
6433 6434
      pExp->base.resSchema = createResSchema(pType->type, pType->bytes, pTargetNode->slotId, pType->scale,
                                             pType->precision, pNode->node.aliasName);
6435 6436 6437
      pExp->pExpr->_optrRoot.pRootNode = pTargetNode->pExpr;
    } else {
      ASSERT(0);
H
Haojun Liao 已提交
6438 6439 6440
    }
  }

H
Haojun Liao 已提交
6441
  return pExprs;
H
Haojun Liao 已提交
6442 6443
}

6444
static SExecTaskInfo* createExecTaskInfo(uint64_t queryId, uint64_t taskId, EOPTR_EXEC_MODEL model) {
wafwerar's avatar
wafwerar 已提交
6445
  SExecTaskInfo* pTaskInfo = taosMemoryCalloc(1, sizeof(SExecTaskInfo));
6446
  setTaskStatus(pTaskInfo, TASK_NOT_COMPLETED);
H
Haojun Liao 已提交
6447

6448
  pTaskInfo->cost.created = taosGetTimestampMs();
H
Haojun Liao 已提交
6449
  pTaskInfo->id.queryId = queryId;
dengyihao's avatar
dengyihao 已提交
6450
  pTaskInfo->execModel = model;
H
Haojun Liao 已提交
6451

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

6456 6457
  return pTaskInfo;
}
H
Haojun Liao 已提交
6458

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

L
Liu Jicong 已提交
6462 6463
static int32_t doCreateTableGroup(void* metaHandle, int32_t tableType, uint64_t tableUid, STableGroupInfo* pGroupInfo,
                                  uint64_t queryId, uint64_t taskId);
6464
static SArray* extractTableIdList(const STableGroupInfo* pTableGroupInfo);
H
Haojun Liao 已提交
6465
static SArray* extractColumnInfo(SNodeList* pNodeList);
H
Haojun Liao 已提交
6466
static SArray* extractColMatchInfo(SNodeList* pNodeList, SDataBlockDescNode* pOutputNodeList, int32_t* numOfOutputCols);
6467

6468
static SArray* createSortInfo(SNodeList* pNodeList, SNodeList* pNodeListTarget);
6469
static SArray* createIndexMap(SNodeList* pNodeList);
6470
static SArray* extractPartitionColInfo(SNodeList* pNodeList);
6471 6472 6473 6474
static int32_t initQueryTableDataCond(SQueryTableDataCond* pCond, const STableScanPhysiNode* pTableScanNode);

static SInterval extractIntervalInfo(const STableScanPhysiNode* pTableScanNode) {
  SInterval interval = {
L
Liu Jicong 已提交
6475 6476
      .interval = pTableScanNode->interval,
      .sliding = pTableScanNode->sliding,
6477
      .intervalUnit = pTableScanNode->intervalUnit,
L
Liu Jicong 已提交
6478 6479
      .slidingUnit = pTableScanNode->slidingUnit,
      .offset = pTableScanNode->offset,
6480 6481 6482 6483
  };

  return interval;
}
H
Haojun Liao 已提交
6484

H
Haojun Liao 已提交
6485
SOperatorInfo* createOperatorTree(SPhysiNode* pPhyNode, SExecTaskInfo* pTaskInfo, SReadHandle* pHandle,
6486
                                  uint64_t queryId, uint64_t taskId, STableGroupInfo* pTableGroupInfo) {
6487 6488
  int32_t type = nodeType(pPhyNode);

X
Xiaoyu Wang 已提交
6489
  if (pPhyNode->pChildren == NULL || LIST_LENGTH(pPhyNode->pChildren) == 0) {
H
Haojun Liao 已提交
6490
    if (QUERY_NODE_PHYSICAL_PLAN_TABLE_SCAN == type) {
dengyihao's avatar
dengyihao 已提交
6491 6492
      SScanPhysiNode*      pScanPhyNode = (SScanPhysiNode*)pPhyNode;
      STableScanPhysiNode* pTableScanNode = (STableScanPhysiNode*)pPhyNode;
H
Haojun Liao 已提交
6493

L
Liu Jicong 已提交
6494
      int32_t     numOfCols = 0;
H
Haojun Liao 已提交
6495
      tsdbReaderT pDataReader = doCreateDataReader(pTableScanNode, pHandle, pTableGroupInfo, (uint64_t)queryId, taskId);
6496
      if (pDataReader == NULL && terrno != 0) {
6497 6498
        return NULL;
      }
6499

dengyihao's avatar
dengyihao 已提交
6500 6501
      SArray* pColList =
          extractColMatchInfo(pScanPhyNode->pScanCols, pScanPhyNode->node.pOutputDataBlockDesc, &numOfCols);
6502
      SSDataBlock* pResBlock = createResDataBlock(pScanPhyNode->node.pOutputDataBlockDesc);
6503

6504
      SQueryTableDataCond cond = {0};
L
Liu Jicong 已提交
6505
      int32_t             code = initQueryTableDataCond(&cond, pTableScanNode);
6506 6507 6508
      if (code != TSDB_CODE_SUCCESS) {
        return NULL;
      }
6509

6510
      SInterval interval = extractIntervalInfo(pTableScanNode);
L
Liu Jicong 已提交
6511 6512 6513
      return createTableScanOperatorInfo(pDataReader, &cond, numOfCols, pTableScanNode->dataRequired,
                                         pTableScanNode->scanSeq, pColList, pResBlock, pScanPhyNode->node.pConditions,
                                         &interval, pTableScanNode->ratio, pTaskInfo);
H
Haojun Liao 已提交
6514
    } else if (QUERY_NODE_PHYSICAL_PLAN_EXCHANGE == type) {
H
Haojun Liao 已提交
6515
      SExchangePhysiNode* pExchange = (SExchangePhysiNode*)pPhyNode;
6516
      SSDataBlock*        pResBlock = createResDataBlock(pExchange->node.pOutputDataBlockDesc);
H
Haojun Liao 已提交
6517
      return createExchangeOperatorInfo(pExchange->pSrcEndPoints, pResBlock, pTaskInfo);
H
Haojun Liao 已提交
6518
    } else if (QUERY_NODE_PHYSICAL_PLAN_STREAM_SCAN == type) {
H
Haojun Liao 已提交
6519
      SScanPhysiNode* pScanPhyNode = (SScanPhysiNode*)pPhyNode;  // simple child table.
6520

L
Liu Jicong 已提交
6521 6522
      int32_t code = doCreateTableGroup(pHandle->meta, pScanPhyNode->tableType, pScanPhyNode->uid, pTableGroupInfo,
                                        queryId, taskId);
H
Haojun Liao 已提交
6523
      SArray* tableIdList = extractTableIdList(pTableGroupInfo);
H
Haojun Liao 已提交
6524

6525
      SSDataBlock* pResBlock = createResDataBlock(pScanPhyNode->node.pOutputDataBlockDesc);
6526 6527

      int32_t numOfCols = 0;
6528
      SArray* pCols = extractColMatchInfo(pScanPhyNode->pScanCols, pScanPhyNode->node.pOutputDataBlockDesc, &numOfCols);
L
Liu Jicong 已提交
6529 6530
      SOperatorInfo* pOperator =
          createStreamScanOperatorInfo(pHandle->reader, pResBlock, pCols, tableIdList, pTaskInfo);
6531
      taosArrayDestroy(tableIdList);
H
Haojun Liao 已提交
6532
      return pOperator;
H
Haojun Liao 已提交
6533
    } else if (QUERY_NODE_PHYSICAL_PLAN_SYSTABLE_SCAN == type) {
L
Liu Jicong 已提交
6534
      SSystemTableScanPhysiNode* pSysScanPhyNode = (SSystemTableScanPhysiNode*)pPhyNode;
L
Liu Jicong 已提交
6535
      SScanPhysiNode*            pScanNode = &pSysScanPhyNode->scan;
H
Haojun Liao 已提交
6536

6537
      SSDataBlock* pResBlock = createResDataBlock(pScanNode->node.pOutputDataBlockDesc);
6538

6539
      int32_t numOfOutputCols = 0;
L
Liu Jicong 已提交
6540 6541
      SArray* colList =
          extractColMatchInfo(pScanNode->pScanCols, pScanNode->node.pOutputDataBlockDesc, &numOfOutputCols);
L
Liu Jicong 已提交
6542
      SOperatorInfo* pOperator = createSysTableScanOperatorInfo(
L
Liu Jicong 已提交
6543 6544
          pHandle, pResBlock, &pScanNode->tableName, pScanNode->node.pConditions, pSysScanPhyNode->mgmtEpSet, colList,
          pTaskInfo, pSysScanPhyNode->showRewrite, pSysScanPhyNode->accountId);
H
Haojun Liao 已提交
6545 6546 6547
      return pOperator;
    } else {
      ASSERT(0);
H
Haojun Liao 已提交
6548 6549 6550
    }
  }

6551 6552
  int32_t num = 0;
  size_t  size = LIST_LENGTH(pPhyNode->pChildren);
H
Haojun Liao 已提交
6553

6554
  SOperatorInfo** ops = taosMemoryCalloc(size, POINTER_BYTES);
dengyihao's avatar
dengyihao 已提交
6555
  for (int32_t i = 0; i < size; ++i) {
6556 6557
    SPhysiNode* pChildNode = (SPhysiNode*)nodesListGetNode(pPhyNode->pChildren, i);
    ops[i] = createOperatorTree(pChildNode, pTaskInfo, pHandle, queryId, taskId, pTableGroupInfo);
6558 6559 6560
    if (ops[i] == NULL) {
      return NULL;
    }
6561
  }
H
Haojun Liao 已提交
6562

6563
  SOperatorInfo* pOptr = NULL;
H
Haojun Liao 已提交
6564
  if (QUERY_NODE_PHYSICAL_PLAN_PROJECT == type) {
dengyihao's avatar
dengyihao 已提交
6565 6566
    SProjectPhysiNode* pProjPhyNode = (SProjectPhysiNode*)pPhyNode;
    SExprInfo*         pExprInfo = createExprInfo(pProjPhyNode->pProjections, NULL, &num);
H
Haojun Liao 已提交
6567

6568
    SSDataBlock* pResBlock = createResDataBlock(pPhyNode->pOutputDataBlockDesc);
dengyihao's avatar
dengyihao 已提交
6569 6570
    SLimit       limit = {.limit = pProjPhyNode->limit, .offset = pProjPhyNode->offset};
    SLimit       slimit = {.limit = pProjPhyNode->slimit, .offset = pProjPhyNode->soffset};
6571
    pOptr = createProjectOperatorInfo(ops[0], pExprInfo, num, pResBlock, &limit, &slimit, pTaskInfo);
H
Haojun Liao 已提交
6572 6573 6574
  } else if (QUERY_NODE_PHYSICAL_PLAN_AGG == type) {
    SAggPhysiNode* pAggNode = (SAggPhysiNode*)pPhyNode;
    SExprInfo*     pExprInfo = createExprInfo(pAggNode->pAggFuncs, pAggNode->pGroupKeys, &num);
6575
    SSDataBlock*   pResBlock = createResDataBlock(pPhyNode->pOutputDataBlockDesc);
H
Haojun Liao 已提交
6576

dengyihao's avatar
dengyihao 已提交
6577
    int32_t    numOfScalarExpr = 0;
6578 6579 6580 6581 6582
    SExprInfo* pScalarExprInfo = NULL;
    if (pAggNode->pExprs != NULL) {
      pScalarExprInfo = createExprInfo(pAggNode->pExprs, NULL, &numOfScalarExpr);
    }

H
Haojun Liao 已提交
6583 6584
    if (pAggNode->pGroupKeys != NULL) {
      SArray* pColList = extractColumnInfo(pAggNode->pGroupKeys);
dengyihao's avatar
dengyihao 已提交
6585 6586
      pOptr = createGroupOperatorInfo(ops[0], pExprInfo, num, pResBlock, pColList, pAggNode->node.pConditions,
                                      pScalarExprInfo, numOfScalarExpr, pTaskInfo, NULL);
H
Haojun Liao 已提交
6587
    } else {
dengyihao's avatar
dengyihao 已提交
6588 6589
      pOptr = createAggregateOperatorInfo(ops[0], pExprInfo, num, pResBlock, pScalarExprInfo, numOfScalarExpr,
                                          pTaskInfo, pTableGroupInfo);
H
Haojun Liao 已提交
6590
    }
H
Haojun Liao 已提交
6591 6592
  } else if (QUERY_NODE_PHYSICAL_PLAN_INTERVAL == type) {
    SIntervalPhysiNode* pIntervalPhyNode = (SIntervalPhysiNode*)pPhyNode;
H
Haojun Liao 已提交
6593

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

dengyihao's avatar
dengyihao 已提交
6597 6598 6599 6600 6601 6602
    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 已提交
6603

dengyihao's avatar
dengyihao 已提交
6604 6605
    STimeWindowAggSupp as = {.waterMark = pIntervalPhyNode->window.watermark,
                             .calTrigger = pIntervalPhyNode->window.triggerType};
6606

dengyihao's avatar
dengyihao 已提交
6607 6608 6609
    int32_t primaryTsSlotId = ((SColumnNode*)pIntervalPhyNode->window.pTspk)->slotId;
    pOptr = createIntervalOperatorInfo(ops[0], pExprInfo, num, pResBlock, &interval, primaryTsSlotId, &as,
                                       pTableGroupInfo, pTaskInfo);
6610 6611

    if (pIntervalPhyNode->pFill != NULL) {
dengyihao's avatar
dengyihao 已提交
6612 6613
      pOptr = createFillOperatorInfo(pOptr, pExprInfo, num, &interval, pResBlock, pIntervalPhyNode->pFill->mode, NULL,
                                     false, pTaskInfo);
6614 6615
    }

H
Haojun Liao 已提交
6616
  } else if (QUERY_NODE_PHYSICAL_PLAN_SORT == type) {
H
Haojun Liao 已提交
6617
    SSortPhysiNode* pSortPhyNode = (SSortPhysiNode*)pPhyNode;
H
Haojun Liao 已提交
6618

6619
    SSDataBlock* pResBlock = createResDataBlock(pPhyNode->pOutputDataBlockDesc);
6620
    SArray*      info = createSortInfo(pSortPhyNode->pSortKeys, pSortPhyNode->pTargets);
6621
    SArray*      slotMap = createIndexMap(pSortPhyNode->pTargets);
6622
    pOptr = createSortOperatorInfo(ops[0], pResBlock, info, slotMap, pTaskInfo);
H
Haojun Liao 已提交
6623
  } else if (QUERY_NODE_PHYSICAL_PLAN_SESSION_WINDOW == type) {
H
Haojun Liao 已提交
6624 6625
    SSessionWinodwPhysiNode* pSessionNode = (SSessionWinodwPhysiNode*)pPhyNode;

dengyihao's avatar
dengyihao 已提交
6626 6627
    STimeWindowAggSupp as = {.waterMark = pSessionNode->window.watermark,
                             .calTrigger = pSessionNode->window.triggerType};
6628

H
Haojun Liao 已提交
6629
    SExprInfo*   pExprInfo = createExprInfo(pSessionNode->window.pFuncs, NULL, &num);
6630
    SSDataBlock* pResBlock = createResDataBlock(pPhyNode->pOutputDataBlockDesc);
6631
    pOptr = createSessionAggOperatorInfo(ops[0], pExprInfo, num, pResBlock, pSessionNode->gap, &as, pTaskInfo);
H
Haojun Liao 已提交
6632
  } else if (QUERY_NODE_PHYSICAL_PLAN_PARTITION == type) {
dengyihao's avatar
dengyihao 已提交
6633 6634 6635
    SPartitionPhysiNode* pPartNode = (SPartitionPhysiNode*)pPhyNode;
    SArray*              pColList = extractPartitionColInfo(pPartNode->pPartitionKeys);
    SSDataBlock*         pResBlock = createResDataBlock(pPhyNode->pOutputDataBlockDesc);
6636 6637

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

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

dengyihao's avatar
dengyihao 已提交
6644
    SExprInfo*   pExprInfo = createExprInfo(pStateNode->window.pFuncs, NULL, &num);
6645
    SSDataBlock* pResBlock = createResDataBlock(pPhyNode->pOutputDataBlockDesc);
6646
    pOptr = createStatewindowOperatorInfo(ops[0], pExprInfo, num, pResBlock, &as, pTaskInfo);
6647
  } else if (QUERY_NODE_PHYSICAL_PLAN_JOIN == type) {
dengyihao's avatar
dengyihao 已提交
6648 6649
    SJoinPhysiNode* pJoinNode = (SJoinPhysiNode*)pPhyNode;
    SSDataBlock*    pResBlock = createResDataBlock(pPhyNode->pOutputDataBlockDesc);
6650 6651

    SExprInfo* pExprInfo = createExprInfo(pJoinNode->pTargets, NULL, &num);
6652
    pOptr = createJoinOperatorInfo(ops, size, pExprInfo, num, pResBlock, pJoinNode->pOnConditions, pTaskInfo);
H
Haojun Liao 已提交
6653 6654
  } else {
    ASSERT(0);
H
Haojun Liao 已提交
6655
  }
6656 6657 6658

  taosMemoryFree(ops);
  return pOptr;
6659
}
H
Haojun Liao 已提交
6660

L
Liu Jicong 已提交
6661
static int32_t initQueryTableDataCond(SQueryTableDataCond* pCond, const STableScanPhysiNode* pTableScanNode) {
6662 6663 6664 6665 6666 6667
  pCond->loadExternalRows = false;

  pCond->order = pTableScanNode->scanSeq[0] > 0 ? TSDB_ORDER_ASC : TSDB_ORDER_DESC;
  pCond->numOfCols = LIST_LENGTH(pTableScanNode->scan.pScanCols);
  pCond->colList = taosMemoryCalloc(pCond->numOfCols, sizeof(SColumnInfo));
  if (pCond->colList == NULL) {
H
Haojun Liao 已提交
6668
    terrno = TSDB_CODE_QRY_OUT_OF_MEMORY;
6669 6670 6671 6672 6673 6674
    return terrno;
  }

  pCond->twindow = pTableScanNode->scanRange;

#if 1
L
Liu Jicong 已提交
6675
  // todo work around a problem, remove it later
6676 6677
  if ((pCond->order == TSDB_ORDER_ASC && pCond->twindow.skey > pCond->twindow.ekey) ||
      (pCond->order == TSDB_ORDER_DESC && pCond->twindow.skey < pCond->twindow.ekey)) {
wafwerar's avatar
wafwerar 已提交
6678
    TSWAP(pCond->twindow.skey, pCond->twindow.ekey);
H
Haojun Liao 已提交
6679
  }
6680
#endif
H
Haojun Liao 已提交
6681

6682 6683
  pCond->type = BLOCK_LOAD_OFFSET_SEQ_ORDER;
  //  pCond->type = pTableScanNode->scanFlag;
H
Haojun Liao 已提交
6684

H
Haojun Liao 已提交
6685
  int32_t j = 0;
6686
  for (int32_t i = 0; i < pCond->numOfCols; ++i) {
H
Haojun Liao 已提交
6687 6688
    STargetNode* pNode = (STargetNode*)nodesListGetNode(pTableScanNode->scan.pScanCols, i);
    SColumnNode* pColNode = (SColumnNode*)pNode->pExpr;
H
Haojun Liao 已提交
6689 6690 6691
    if (pColNode->colType == COLUMN_TYPE_TAG) {
      continue;
    }
H
Haojun Liao 已提交
6692

6693 6694 6695
    pCond->colList[j].type = pColNode->node.resType.type;
    pCond->colList[j].bytes = pColNode->node.resType.bytes;
    pCond->colList[j].colId = pColNode->colId;
H
Haojun Liao 已提交
6696
    j += 1;
H
Haojun Liao 已提交
6697 6698
  }

6699 6700
  pCond->numOfCols = j;
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
6701
}
H
Haojun Liao 已提交
6702

H
Haojun Liao 已提交
6703
SArray* extractColumnInfo(SNodeList* pNodeList) {
L
Liu Jicong 已提交
6704
  size_t  numOfCols = LIST_LENGTH(pNodeList);
H
Haojun Liao 已提交
6705 6706 6707 6708 6709 6710
  SArray* pList = taosArrayInit(numOfCols, sizeof(SColumn));
  if (pList == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

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

6714 6715 6716 6717 6718
    if (nodeType(pNode->pExpr) == QUERY_NODE_COLUMN) {
      SColumnNode* pColNode = (SColumnNode*)pNode->pExpr;

      // todo extract method
      SColumn c = {0};
L
Liu Jicong 已提交
6719 6720 6721 6722 6723
      c.slotId = pColNode->slotId;
      c.colId = pColNode->colId;
      c.type = pColNode->node.resType.type;
      c.bytes = pColNode->node.resType.bytes;
      c.scale = pColNode->node.resType.scale;
6724 6725 6726 6727
      c.precision = pColNode->node.resType.precision;

      taosArrayPush(pList, &c);
    } else if (nodeType(pNode->pExpr) == QUERY_NODE_VALUE) {
L
Liu Jicong 已提交
6728 6729
      SValueNode* pValNode = (SValueNode*)pNode->pExpr;
      SColumn     c = {0};
6730
      c.slotId = pNode->slotId;
L
Liu Jicong 已提交
6731 6732 6733 6734
      c.colId = pNode->slotId;
      c.type = pValNode->node.type;
      c.bytes = pValNode->node.resType.bytes;
      c.scale = pValNode->node.resType.scale;
6735 6736 6737 6738
      c.precision = pValNode->node.resType.precision;

      taosArrayPush(pList, &c);
    }
H
Haojun Liao 已提交
6739 6740 6741 6742 6743
  }

  return pList;
}

6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757
SArray* extractPartitionColInfo(SNodeList* pNodeList) {
  size_t  numOfCols = LIST_LENGTH(pNodeList);
  SArray* pList = taosArrayInit(numOfCols, sizeof(SColumn));
  if (pList == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

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

    // todo extract method
    SColumn c = {0};
    c.slotId = pColNode->slotId;
dengyihao's avatar
dengyihao 已提交
6758 6759 6760
    c.colId = pColNode->colId;
    c.type = pColNode->node.resType.type;
    c.bytes = pColNode->node.resType.bytes;
6761 6762 6763 6764 6765 6766 6767 6768 6769
    c.precision = pColNode->node.resType.precision;
    c.scale = pColNode->node.resType.scale;

    taosArrayPush(pList, &c);
  }

  return pList;
}

6770
SArray* createSortInfo(SNodeList* pNodeList, SNodeList* pNodeListTarget) {
L
Liu Jicong 已提交
6771
  size_t  numOfCols = LIST_LENGTH(pNodeList);
H
Haojun Liao 已提交
6772 6773 6774 6775 6776 6777
  SArray* pList = taosArrayInit(numOfCols, sizeof(SBlockOrderInfo));
  if (pList == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return pList;
  }

L
Liu Jicong 已提交
6778
  for (int32_t i = 0; i < numOfCols; ++i) {
6779
    SOrderByExprNode* pSortKey = (SOrderByExprNode*)nodesListGetNode(pNodeList, i);
L
Liu Jicong 已提交
6780 6781
    SBlockOrderInfo   bi = {0};
    bi.order = (pSortKey->order == ORDER_ASC) ? TSDB_ORDER_ASC : TSDB_ORDER_DESC;
H
Haojun Liao 已提交
6782 6783 6784 6785
    bi.nullFirst = (pSortKey->nullOrder == NULL_ORDER_FIRST);

    SColumnNode* pColNode = (SColumnNode*)pSortKey->pExpr;

6786 6787 6788 6789 6790
    bool found = false;
    for (int32_t j = 0; j < LIST_LENGTH(pNodeListTarget); ++j) {
      STargetNode* pTarget = (STargetNode*)nodesListGetNode(pNodeListTarget, j);

      SColumnNode* pColNodeT = (SColumnNode*)pTarget->pExpr;
dengyihao's avatar
dengyihao 已提交
6791
      if (pColNode->slotId == pColNodeT->slotId) {  // to find slotId in PhysiSort OutputDataBlockDesc
6792 6793 6794 6795 6796 6797
        bi.slotId = pTarget->slotId;
        found = true;
        break;
      }
    }

dengyihao's avatar
dengyihao 已提交
6798
    if (!found) {
6799 6800
      qError("sort slot id does not found");
    }
H
Haojun Liao 已提交
6801 6802 6803 6804 6805 6806
    taosArrayPush(pList, &bi);
  }

  return pList;
}

6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824
SArray* createIndexMap(SNodeList* pNodeList) {
  size_t  numOfCols = LIST_LENGTH(pNodeList);
  SArray* pList = taosArrayInit(numOfCols, sizeof(int32_t));
  if (pList == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return pList;
  }

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

    SColumnNode* pColNode = (SColumnNode*)pTarget->pExpr;
    taosArrayPush(pList, &pColNode->slotId);
  }

  return pList;
}

H
Haojun Liao 已提交
6825
SArray* extractColMatchInfo(SNodeList* pNodeList, SDataBlockDescNode* pOutputNodeList, int32_t* numOfOutputCols) {
L
Liu Jicong 已提交
6826
  size_t  numOfCols = LIST_LENGTH(pNodeList);
H
Haojun Liao 已提交
6827 6828 6829 6830 6831 6832
  SArray* pList = taosArrayInit(numOfCols, sizeof(SColMatchInfo));
  if (pList == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

L
Liu Jicong 已提交
6833 6834 6835
  for (int32_t i = 0; i < numOfCols; ++i) {
    STargetNode* pNode = (STargetNode*)nodesListGetNode(pNodeList, i);
    SColumnNode* pColNode = (SColumnNode*)pNode->pExpr;
H
Haojun Liao 已提交
6836 6837

    SColMatchInfo c = {0};
6838
    c.output = true;
L
Liu Jicong 已提交
6839
    c.colId = pColNode->colId;
H
Haojun Liao 已提交
6840 6841 6842 6843
    c.targetSlotId = pNode->slotId;
    taosArrayPush(pList, &c);
  }

H
Haojun Liao 已提交
6844 6845
  *numOfOutputCols = 0;
  int32_t num = LIST_LENGTH(pOutputNodeList->pSlots);
L
Liu Jicong 已提交
6846 6847
  for (int32_t i = 0; i < num; ++i) {
    SSlotDescNode* pNode = (SSlotDescNode*)nodesListGetNode(pOutputNodeList->pSlots, i);
6848

6849
    // todo: add reserve flag check
6850 6851
    // it is a column reserved for the arithmetic expression calculation
    if (pNode->slotId >= numOfCols) {
6852 6853 6854 6855
      (*numOfOutputCols) += 1;
      continue;
    }

H
Haojun Liao 已提交
6856
    SColMatchInfo* info = taosArrayGet(pList, pNode->slotId);
H
Haojun Liao 已提交
6857 6858 6859 6860 6861
    if (pNode->output) {
      (*numOfOutputCols) += 1;
    } else {
      info->output = false;
    }
H
Haojun Liao 已提交
6862 6863
  }

H
Haojun Liao 已提交
6864 6865 6866
  return pList;
}

dengyihao's avatar
dengyihao 已提交
6867 6868
int32_t doCreateTableGroup(void* metaHandle, int32_t tableType, uint64_t tableUid, STableGroupInfo* pGroupInfo,
                           uint64_t queryId, uint64_t taskId) {
6869
  int32_t code = 0;
H
Haojun Liao 已提交
6870
  if (tableType == TSDB_SUPER_TABLE) {
H
Haojun Liao 已提交
6871
    code = tsdbQuerySTableByTagCond(metaHandle, tableUid, 0, NULL, 0, 0, NULL, pGroupInfo, NULL, 0, queryId, taskId);
H
Haojun Liao 已提交
6872
  } else {  // Create one table group.
H
Haojun Liao 已提交
6873
    code = tsdbGetOneTableGroup(metaHandle, tableUid, 0, pGroupInfo);
6874 6875 6876 6877
  }

  return code;
}
H
Haojun Liao 已提交
6878

6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896
SArray* extractTableIdList(const STableGroupInfo* pTableGroupInfo) {
  SArray* tableIdList = taosArrayInit(4, sizeof(uint64_t));

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

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

  return tableIdList;
}

L
Liu Jicong 已提交
6897 6898
tsdbReaderT doCreateDataReader(STableScanPhysiNode* pTableScanNode, SReadHandle* pHandle,
                               STableGroupInfo* pTableGroupInfo, uint64_t queryId, uint64_t taskId) {
6899
  uint64_t uid = pTableScanNode->scan.uid;
L
Liu Jicong 已提交
6900 6901
  int32_t  code =
      doCreateTableGroup(pHandle->meta, pTableScanNode->scan.tableType, uid, pTableGroupInfo, queryId, taskId);
6902 6903
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
H
Haojun Liao 已提交
6904
  }
H
Haojun Liao 已提交
6905

H
Haojun Liao 已提交
6906
  if (pTableGroupInfo->numOfTables == 0) {
H
Haojun Liao 已提交
6907
    code = 0;
L
Liu Jicong 已提交
6908
    qDebug("no table qualified for query, TID:0x%" PRIx64 ", QID:0x%" PRIx64, taskId, queryId);
H
Haojun Liao 已提交
6909 6910
    goto _error;
  }
H
Haojun Liao 已提交
6911

6912 6913 6914 6915 6916 6917 6918
  SQueryTableDataCond cond = {0};
  code = initQueryTableDataCond(&cond, pTableScanNode);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }

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

L
Liu Jicong 已提交
6920
_error:
H
Haojun Liao 已提交
6921 6922 6923 6924
  terrno = code;
  return NULL;
}

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

H
Haojun Liao 已提交
6929
  int32_t code = TSDB_CODE_SUCCESS;
6930
  *pTaskInfo = createExecTaskInfo(queryId, taskId, model);
H
Haojun Liao 已提交
6931 6932 6933 6934
  if (*pTaskInfo == NULL) {
    code = TSDB_CODE_QRY_OUT_OF_MEMORY;
    goto _complete;
  }
H
Haojun Liao 已提交
6935

L
Liu Jicong 已提交
6936 6937
  (*pTaskInfo)->pRoot =
      createOperatorTree(pPlan->pNode, *pTaskInfo, pHandle, queryId, taskId, &(*pTaskInfo)->tableqinfoGroupInfo);
D
dapan1121 已提交
6938
  if (NULL == (*pTaskInfo)->pRoot) {
L
Liu Jicong 已提交
6939
    code = terrno;
D
dapan1121 已提交
6940 6941
    goto _complete;
  }
H
Haojun Liao 已提交
6942

6943
  if ((*pTaskInfo)->pRoot == NULL) {
H
Haojun Liao 已提交
6944
    code = TSDB_CODE_QRY_OUT_OF_MEMORY;
H
Haojun Liao 已提交
6945
    goto _complete;
6946 6947
  }

H
Haojun Liao 已提交
6948 6949
  return code;

H
Haojun Liao 已提交
6950
_complete:
wafwerar's avatar
wafwerar 已提交
6951
  taosMemoryFreeClear(*pTaskInfo);
H
Haojun Liao 已提交
6952 6953 6954

  terrno = code;
  return code;
H
Haojun Liao 已提交
6955 6956
}

L
Liu Jicong 已提交
6957 6958
static int32_t updateOutputBufForTopBotQuery(SQueriedTableInfo* pTableInfo, SColumnInfo* pTagCols, SExprInfo* pExprs,
                                             int32_t numOfOutput, int32_t tagLen, bool superTable) {
6959 6960 6961 6962 6963 6964 6965 6966 6967
  for (int32_t i = 0; i < numOfOutput; ++i) {
    int16_t functId = getExprFunctionId(&pExprs[i]);

    if (functId == FUNCTION_TOP || functId == FUNCTION_BOTTOM) {
      int32_t j = getColumnIndexInSource(pTableInfo, &pExprs[i].base, pTagCols);
      if (j < 0 || j >= pTableInfo->numOfCols) {
        return TSDB_CODE_QRY_INVALID_MSG;
      } else {
        SColumnInfo* pCol = &pTableInfo->colList[j];
L
Liu Jicong 已提交
6968 6969 6970 6971
        //        int32_t ret = getResultDataInfo(pCol->type, pCol->bytes, functId, (int32_t)pExprs[i].base.param[0].i,
        //                                        &pExprs[i].base.resSchema.type, &pExprs[i].base.resSchema.bytes,
        //                                        &pExprs[i].base.interBytes, tagLen, superTable, NULL);
        //        assert(ret == TSDB_CODE_SUCCESS);
6972 6973 6974 6975 6976 6977 6978
      }
    }
  }

  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
6979
void setResultBufSize(STaskAttr* pQueryAttr, SResultInfo* pResultInfo) {
6980 6981 6982 6983 6984 6985 6986 6987
  const int32_t DEFAULT_RESULT_MSG_SIZE = 1024 * (1024 + 512);

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

  const float THRESHOLD_RATIO = 0.85f;

dengyihao's avatar
dengyihao 已提交
6988 6989 6990 6991 6992 6993 6994 6995 6996 6997
  //  if (isProjQuery(pQueryAttr)) {
  //    int32_t numOfRes = DEFAULT_RESULT_MSG_SIZE / pQueryAttr->resultRowSize;
  //    if (numOfRes < MIN_ROWS_FOR_PRJ_QUERY) {
  //      numOfRes = MIN_ROWS_FOR_PRJ_QUERY;
  //    }
  //
  //    pResultInfo->capacity = numOfRes;
  //  } else {  // in case of non-prj query, a smaller output buffer will be used.
  //    pResultInfo->capacity = DEFAULT_MIN_ROWS;
  //  }
6998 6999

  pResultInfo->threshold = (int32_t)(pResultInfo->capacity * THRESHOLD_RATIO);
H
Haojun Liao 已提交
7000
  pResultInfo->totalRows = 0;
7001 7002
}

L
Liu Jicong 已提交
7003
// TODO refactor
7004
void freeColumnFilterInfo(SColumnFilterInfo* pFilter, int32_t numOfFilters) {
L
Liu Jicong 已提交
7005 7006 7007
  if (pFilter == NULL || numOfFilters == 0) {
    return;
  }
7008

L
Liu Jicong 已提交
7009 7010 7011
  for (int32_t i = 0; i < numOfFilters; i++) {
    if (pFilter[i].filterstr && pFilter[i].pz) {
      taosMemoryFree((void*)(pFilter[i].pz));
7012
    }
L
Liu Jicong 已提交
7013
  }
7014

L
Liu Jicong 已提交
7015
  taosMemoryFree(pFilter);
7016 7017 7018 7019
}

static void doDestroyTableQueryInfo(STableGroupInfo* pTableqinfoGroupInfo) {
  if (pTableqinfoGroupInfo->pGroupList != NULL) {
L
Liu Jicong 已提交
7020
    int32_t numOfGroups = (int32_t)taosArrayGetSize(pTableqinfoGroupInfo->pGroupList);
7021
    for (int32_t i = 0; i < numOfGroups; ++i) {
L
Liu Jicong 已提交
7022
      SArray* p = taosArrayGetP(pTableqinfoGroupInfo->pGroupList, i);
7023 7024

      size_t num = taosArrayGetSize(p);
L
Liu Jicong 已提交
7025
      for (int32_t j = 0; j < num; ++j) {
7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041
        STableQueryInfo* item = taosArrayGetP(p, j);
        destroyTableQueryInfoImpl(item);
      }

      taosArrayDestroy(p);
    }
  }

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

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

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

H
Haojun Liao 已提交
7045
  doDestroyTableQueryInfo(&pTaskInfo->tableqinfoGroupInfo);
L
Liu Jicong 已提交
7046 7047
  //  taosArrayDestroy(pTaskInfo->summary.queryProfEvents);
  //  taosHashCleanup(pTaskInfo->summary.operatorProfResults);
7048

wafwerar's avatar
wafwerar 已提交
7049 7050 7051
  taosMemoryFreeClear(pTaskInfo->sql);
  taosMemoryFreeClear(pTaskInfo->id.str);
  taosMemoryFreeClear(pTaskInfo);
7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063
}

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 已提交
7064
      int32_t len = (varDataLen(val) > maxLen) ? maxLen : varDataLen(val);
7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076
      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 已提交
7077 7078
  //  size_t s3 = sizeof(STableCheckInfo);  buffer consumption in tsdb
  return (int64_t)(s1 * 1.5 * numOfTables);
7079 7080 7081 7082 7083 7084 7085
}

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 已提交
7086
    while (1) {
7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112
      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 已提交
7113

dengyihao's avatar
dengyihao 已提交
7114 7115
int32_t getOperatorExplainExecInfo(SOperatorInfo* operatorInfo, SExplainExecInfo** pRes, int32_t* capacity,
                                   int32_t* resNum) {
D
dapan1121 已提交
7116 7117
  if (*resNum >= *capacity) {
    *capacity += 10;
dengyihao's avatar
dengyihao 已提交
7118

D
dapan1121 已提交
7119 7120
    *pRes = taosMemoryRealloc(*pRes, (*capacity) * sizeof(SExplainExecInfo));
    if (NULL == *pRes) {
D
dapan1121 已提交
7121
      qError("malloc %d failed", (*capacity) * (int32_t)sizeof(SExplainExecInfo));
D
dapan1121 已提交
7122 7123 7124 7125
      return TSDB_CODE_QRY_OUT_OF_MEMORY;
    }
  }

D
dapan1121 已提交
7126 7127 7128 7129
  (*pRes)[*resNum].numOfRows = operatorInfo->resultInfo.totalRows;
  (*pRes)[*resNum].startupCost = operatorInfo->cost.openCost;
  (*pRes)[*resNum].totalCost = operatorInfo->cost.totalCost;

7130 7131
  if (operatorInfo->fpSet.getExplainFn) {
    int32_t code = (*operatorInfo->fpSet.getExplainFn)(operatorInfo, &(*pRes)->verboseInfo);
D
dapan1121 已提交
7132 7133 7134 7135 7136
    if (code) {
      qError("operator getExplainFn failed, error:%s", tstrerror(code));
      return code;
    }
  }
dengyihao's avatar
dengyihao 已提交
7137

D
dapan1121 已提交
7138
  ++(*resNum);
dengyihao's avatar
dengyihao 已提交
7139

D
dapan1121 已提交
7140
  int32_t code = 0;
D
dapan1121 已提交
7141 7142
  for (int32_t i = 0; i < operatorInfo->numOfDownstream; ++i) {
    code = getOperatorExplainExecInfo(operatorInfo->pDownstream[i], pRes, capacity, resNum);
D
dapan1121 已提交
7143 7144 7145 7146 7147 7148 7149
    if (code) {
      taosMemoryFreeClear(*pRes);
      return TSDB_CODE_QRY_OUT_OF_MEMORY;
    }
  }

  return TSDB_CODE_SUCCESS;
D
dapan1121 已提交
7150 7151
}

7152 7153
static SSDataBlock* doMergeJoin(struct SOperatorInfo* pOperator, bool* newgroup) {
  SJoinOperatorInfo* pJoinInfo = pOperator->info;
dengyihao's avatar
dengyihao 已提交
7154
  //  SOptrBasicInfo* pInfo = &pJoinInfo->binfo;
7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167

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

  int32_t nrows = 0;

  while (1) {
    bool prevVal = *newgroup;

    if (pJoinInfo->pLeft == NULL || pJoinInfo->leftPos >= pJoinInfo->pLeft->info.rows) {
      SOperatorInfo* ds1 = pOperator->pDownstream[0];
      publishOperatorProfEvent(ds1, QUERY_PROF_BEFORE_OPERATOR_EXEC);
7168
      pJoinInfo->pLeft = ds1->fpSet.getNextFn(ds1, newgroup);
7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180
      publishOperatorProfEvent(ds1, QUERY_PROF_AFTER_OPERATOR_EXEC);

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

    if (pJoinInfo->pRight == NULL || pJoinInfo->rightPos >= pJoinInfo->pRight->info.rows) {
      SOperatorInfo* ds2 = pOperator->pDownstream[1];
      publishOperatorProfEvent(ds2, QUERY_PROF_BEFORE_OPERATOR_EXEC);
7181
      pJoinInfo->pRight = ds2->fpSet.getNextFn(ds2, newgroup);
7182 7183 7184 7185 7186 7187 7188 7189 7190 7191
      publishOperatorProfEvent(ds2, QUERY_PROF_AFTER_OPERATOR_EXEC);

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

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

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

    // only the timestamp match support for ordinary table
dengyihao's avatar
dengyihao 已提交
7198 7199 7200 7201
    ASSERT(pLeftCol->info.type == TSDB_DATA_TYPE_TIMESTAMP);
    if (*(int64_t*)pLeftVal == *(int64_t*)pRightVal) {
      for (int32_t i = 0; i < pOperator->numOfOutput; ++i) {
        SColumnInfoData* pDst = taosArrayGet(pRes->pDataBlock, i);
7202

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

dengyihao's avatar
dengyihao 已提交
7205 7206
        int32_t blockId = pExprInfo->base.pParam[0].pCol->dataBlockId;
        int32_t slotId = pExprInfo->base.pParam[0].pCol->slotId;
7207

dengyihao's avatar
dengyihao 已提交
7208 7209 7210 7211 7212 7213
        SColumnInfoData* pSrc = NULL;
        if (pJoinInfo->pLeft->info.blockId == blockId) {
          pSrc = taosArrayGet(pJoinInfo->pLeft->pDataBlock, slotId);
        } else {
          pSrc = taosArrayGet(pJoinInfo->pRight->pDataBlock, slotId);
        }
7214

dengyihao's avatar
dengyihao 已提交
7215 7216 7217 7218 7219
        if (colDataIsNull_s(pSrc, pJoinInfo->leftPos)) {
          colDataAppendNULL(pDst, nrows);
        } else {
          char* p = colDataGetData(pSrc, pJoinInfo->leftPos);
          colDataAppend(pDst, nrows, p, false);
7220
        }
dengyihao's avatar
dengyihao 已提交
7221
      }
7222

dengyihao's avatar
dengyihao 已提交
7223 7224
      pJoinInfo->leftPos += 1;
      pJoinInfo->rightPos += 1;
7225

dengyihao's avatar
dengyihao 已提交
7226 7227 7228
      nrows += 1;
    } else if (*(int64_t*)pLeftVal < *(int64_t*)pRightVal) {
      pJoinInfo->leftPos += 1;
D
dapan1121 已提交
7229

dengyihao's avatar
dengyihao 已提交
7230 7231
      if (pJoinInfo->leftPos >= pJoinInfo->pLeft->info.rows) {
        continue;
7232
      }
dengyihao's avatar
dengyihao 已提交
7233 7234 7235 7236
    } else if (*(int64_t*)pLeftVal > *(int64_t*)pRightVal) {
      pJoinInfo->rightPos += 1;
      if (pJoinInfo->rightPos >= pJoinInfo->pRight->info.rows) {
        continue;
7237
      }
dengyihao's avatar
dengyihao 已提交
7238
    }
7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249

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

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

dengyihao's avatar
dengyihao 已提交
7250 7251 7252
SOperatorInfo* createJoinOperatorInfo(SOperatorInfo** pDownstream, int32_t numOfDownstream, SExprInfo* pExprInfo,
                                      int32_t numOfCols, SSDataBlock* pResBlock, SNode* pOnCondition,
                                      SExecTaskInfo* pTaskInfo) {
7253
  SJoinOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SJoinOperatorInfo));
dengyihao's avatar
dengyihao 已提交
7254
  SOperatorInfo*     pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
7255 7256 7257 7258 7259 7260 7261
  if (pOperator == NULL || pInfo == NULL) {
    goto _error;
  }

  pOperator->resultInfo.capacity = 4096;
  pOperator->resultInfo.threshold = 4096 * 0.75;

dengyihao's avatar
dengyihao 已提交
7262 7263 7264
  //  initResultRowInf
  //  o(&pInfo->binfo.resultRowInfo, 8);
  pInfo->pRes = pResBlock;
7265

dengyihao's avatar
dengyihao 已提交
7266
  pOperator->name = "JoinOperator";
7267
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_JOIN;
7268
  pOperator->blockingOptr = false;
dengyihao's avatar
dengyihao 已提交
7269 7270 7271 7272 7273
  pOperator->status = OP_NOT_OPENED;
  pOperator->pExpr = pExprInfo;
  pOperator->numOfOutput = numOfCols;
  pOperator->info = pInfo;
  pOperator->pTaskInfo = pTaskInfo;
7274

L
Liu Jicong 已提交
7275 7276
  pOperator->fpSet =
      createOperatorFpSet(operatorDummyOpenFn, doMergeJoin, NULL, NULL, destroyBasicOperatorInfo, NULL, NULL, NULL);
7277 7278 7279
  int32_t code = appendDownstream(pOperator, pDownstream, numOfDownstream);
  return pOperator;

dengyihao's avatar
dengyihao 已提交
7280
_error:
7281 7282 7283 7284
  taosMemoryFree(pInfo);
  taosMemoryFree(pOperator);
  pTaskInfo->code = TSDB_CODE_OUT_OF_MEMORY;
  return NULL;
dengyihao's avatar
dengyihao 已提交
7285
}