executorimpl.c 264.0 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 18 19 20
#include "filter.h"
#include "functionMgt.h"
#include "function.h"
#include "querynodes.h"
#include "tname.h"
21
#include "os.h"
22

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

29
#include "executorimpl.h"
30
#include "query.h"
31 32
#include "tcompare.h"
#include "tcompression.h"
H
Haojun Liao 已提交
33
#include "thash.h"
H
Hongze Cheng 已提交
34
#include "vnode.h"
35 36
#include "ttypes.h"

H
Haojun Liao 已提交
37
#define IS_MAIN_SCAN(runtime)          ((runtime)->scanFlag == MAIN_SCAN)
38 39
#define IS_REVERSE_SCAN(runtime)       ((runtime)->scanFlag == REVERSE_SCAN)
#define IS_REPEAT_SCAN(runtime)        ((runtime)->scanFlag == REPEAT_SCAN)
L
Liu Jicong 已提交
40
#define SET_MAIN_SCAN_FLAG(runtime)    ((runtime)->scanFlag = MAIN_SCAN)
41 42 43 44
#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 已提交
45 46
#define SDATA_BLOCK_INITIALIZER \
  (SDataBlockInfo) { {0}, 0 }
47 48 49 50

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

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

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

H
Haojun Liao 已提交
61

62 63
#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 194
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);
// static STsdbQueryCond 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 211
static void destroyExchangeOperatorInfo(void* param, int32_t numOfOutput);
static void destroyConditionOperatorInfo(void* param, int32_t numOfOutput);

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

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

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

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

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

232 233
static int32_t doCopyToSDataBlock(SSDataBlock* pBlock, int32_t rowCapacity, SExprInfo* pExprInfo, SDiskbasedBuf* pBuf, SGroupResInfo* pGroupResInfo,
                                  int32_t orderType, int32_t* rowCellOffset);
L
Liu Jicong 已提交
234
static void    initCtxOutputBuffer(SqlFunctionCtx* pCtx, int32_t size);
H
Haojun Liao 已提交
235

H
Haojun Liao 已提交
236
static void setResultBufSize(STaskAttr* pQueryAttr, SResultInfo* pResultInfo);
H
Haojun Liao 已提交
237
static void setCtxTagForJoin(STaskRuntimeEnv* pRuntimeEnv, SqlFunctionCtx* pCtx, SExprInfo* pExprInfo, void* pTable);
H
Haojun Liao 已提交
238
static void doSetTableGroupOutputBuf(SAggOperatorInfo* pAggInfo, int32_t numOfOutput, uint64_t groupId, SExecTaskInfo* pTaskInfo);
239

H
Haojun Liao 已提交
240
SArray* getOrderCheckColumns(STaskAttr* pQuery);
241 242

typedef struct SRowCompSupporter {
L
Liu Jicong 已提交
243 244 245
  STaskRuntimeEnv* pRuntimeEnv;
  int16_t          dataOffset;
  __compar_fn_t    comFunc;
246 247
} SRowCompSupporter;

L
Liu Jicong 已提交
248 249 250
static int compareRowData(const void* a, const void* b, const void* userData) {
  const SResultRow* pRow1 = (const SResultRow*)a;
  const SResultRow* pRow2 = (const SResultRow*)b;
251

L
Liu Jicong 已提交
252 253
  SRowCompSupporter* supporter = (SRowCompSupporter*)userData;
  STaskRuntimeEnv*   pRuntimeEnv = supporter->pRuntimeEnv;
254

L
Liu Jicong 已提交
255 256
  SFilePage* page1 = getBufPage(pRuntimeEnv->pResultBuf, pRow1->pageId);
  SFilePage* page2 = getBufPage(pRuntimeEnv->pResultBuf, pRow2->pageId);
257 258

  int16_t offset = supporter->dataOffset;
L
Liu Jicong 已提交
259 260
  char*   in1 = getPosInResultPage(pRuntimeEnv->pQueryAttr, page1, pRow1->offset, offset);
  char*   in2 = getPosInResultPage(pRuntimeEnv->pQueryAttr, page2, pRow2->offset, offset);
261 262 263 264

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

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

wafwerar's avatar
wafwerar 已提交
269
  SSDataBlock* pBlock = taosMemoryCalloc(1, sizeof(SSDataBlock));
H
Haojun Liao 已提交
270 271 272
  pBlock->info.numOfCols = numOfCols;
  pBlock->pDataBlock = taosArrayInit(numOfCols, sizeof(SColumnInfoData));

H
Haojun Liao 已提交
273
  pBlock->info.blockId = pNode->dataBlockId;
X
Xiaoyu Wang 已提交
274
  pBlock->info.rowSize = pNode->totalRowSize;   // todo ??
H
Haojun Liao 已提交
275

L
Liu Jicong 已提交
276
  for (int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
277
    SColumnInfoData idata = {{0}};
L
Liu Jicong 已提交
278
    SSlotDescNode*  pDescNode = nodesListGetNode(pNode->pSlots, i);
H
Haojun Liao 已提交
279 280
    if (!pDescNode->output) {
      continue;
H
Haojun Liao 已提交
281
    }
H
Haojun Liao 已提交
282

283
    idata.info.type  = pDescNode->dataType.type;
L
Liu Jicong 已提交
284 285
    idata.info.bytes = pDescNode->dataType.bytes;
    idata.info.scale = pDescNode->dataType.scale;
H
Haojun Liao 已提交
286
    idata.info.slotId = pDescNode->slotId;
H
Haojun Liao 已提交
287 288
    idata.info.precision = pDescNode->dataType.precision;

H
Hongze Cheng 已提交
289 290 291 292
    if (IS_VAR_DATA_TYPE(idata.info.type)) {
      pBlock->info.hasVarCol = true;
    }

H
Haojun Liao 已提交
293
    taosArrayPush(pBlock->pDataBlock, &idata);
H
Haojun Liao 已提交
294
  }
H
Haojun Liao 已提交
295 296

  return pBlock;
H
Haojun Liao 已提交
297 298
}

L
Liu Jicong 已提交
299
static bool isSelectivityWithTagsQuery(SqlFunctionCtx* pCtx, int32_t numOfOutput) {
300
  return true;
L
Liu Jicong 已提交
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
  //  bool    hasTags = false;
  //  int32_t numOfSelectivity = 0;
  //
  //  for (int32_t i = 0; i < numOfOutput; ++i) {
  //    int32_t functId = pCtx[i].functionId;
  //    if (functId == FUNCTION_TAG_DUMMY || functId == FUNCTION_TS_DUMMY) {
  //      hasTags = true;
  //      continue;
  //    }
  //
  //    if ((aAggs[functId].status & FUNCSTATE_SELECTIVITY) != 0) {
  //      numOfSelectivity++;
  //    }
  //  }
  //
  //  return (numOfSelectivity > 0 && hasTags);
}

static bool hasNull(SColumn* pColumn, SColumnDataAgg* pStatis) {
320
  if (TSDB_COL_IS_TAG(pColumn->flag) || TSDB_COL_IS_UD_COL(pColumn->flag) || pColumn->colId == PRIMARYKEY_TIMESTAMP_COL_ID) {
321 322 323 324 325 326 327 328 329 330
    return false;
  }

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

  return true;
}

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

334 335 336 337 338 339 340 341 342 343 344
  // 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);
  }

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

wafwerar's avatar
wafwerar 已提交
349
  pResultRowInfo->pPosition = taosMemoryRealloc(pResultRowInfo->pPosition, newCapacity * sizeof(SResultRowPosition));
350 351

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

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

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

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

    return existed;
  }

  return p1 != NULL;
}

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

  // 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 已提交
408
    if (pData->num + interBufSize > getBufPageSize(pResultBuf)) {
409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
      // 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 已提交
428
  pData->num += interBufSize;
429 430 431 432

  return pResultRow;
}

433 434
static SResultRow* doSetResultOutBufByKey_rv(SDiskbasedBuf* pResultBuf, SResultRowInfo* pResultRowInfo, int64_t uid,
                                             char* pData, int16_t bytes, bool masterscan, uint64_t groupId,
L
Liu Jicong 已提交
435
                                             SExecTaskInfo* pTaskInfo, bool isIntervalQuery, SAggSupporter* pSup) {
H
Haojun Liao 已提交
436
  bool existInCurrentResusltRowInfo = false;
437
  SET_RES_WINDOW_KEY(pSup->keyBuf, pData, bytes, groupId);
H
Haojun Liao 已提交
438

H
Haojun Liao 已提交
439
  SResultRowPosition* p1 = (SResultRowPosition*)taosHashGet(pSup->pResultRowHashTable, pSup->keyBuf, GET_RES_WINDOW_KEY_LEN(bytes));
H
Haojun Liao 已提交
440 441 442 443

  // in case of repeat scan/reverse scan, no new time window added.
  if (isIntervalQuery) {
    if (!masterscan) {  // the *p1 may be NULL in case of sliding+offset exists.
H
Haojun Liao 已提交
444 445 446 447 448
      if (p1 != NULL) {
        return getResultRowByPos(pResultBuf, p1);
      } else {
        return NULL;
      }
H
Haojun Liao 已提交
449 450 451 452
    }

    if (p1 != NULL) {
      if (pResultRowInfo->size == 0) {
H
Haojun Liao 已提交
453
        existInCurrentResusltRowInfo = false;  // this time window created by other timestamp that does not belongs to current table.
H
Haojun Liao 已提交
454
      } else if (pResultRowInfo->size == 1) {
C
Cary Xu 已提交
455 456
        SResultRowPosition* p = &pResultRowInfo->pPosition[0];
        existInCurrentResusltRowInfo = (p->pageId == p1->pageId && p->offset == p1->offset);
H
Haojun Liao 已提交
457
      } else {  // check if current pResultRowInfo contains the existInCurrentResusltRowInfo pResultRow
458
        SET_RES_EXT_WINDOW_KEY(pSup->keyBuf, pData, bytes, uid, pResultRowInfo);
459
        int64_t* index = taosHashGet(pSup->pResultRowListSet, pSup->keyBuf, GET_RES_EXT_WINDOW_KEY_LEN(bytes));
H
Haojun Liao 已提交
460
        if (index != NULL) {
H
Haojun Liao 已提交
461 462
          // TODO check the scan order for current opened time window
          existInCurrentResusltRowInfo = true;
H
Haojun Liao 已提交
463
        } else {
H
Haojun Liao 已提交
464
          existInCurrentResusltRowInfo = false;
H
Haojun Liao 已提交
465 466 467 468
        }
      }
    }
  } else {
H
Haojun Liao 已提交
469
    // In case of group by column query, the required SResultRow object must be existInCurrentResusltRowInfo in the pResultRowInfo object.
H
Haojun Liao 已提交
470
    if (p1 != NULL) {
H
Haojun Liao 已提交
471
      return getResultRowByPos(pResultBuf, p1);
H
Haojun Liao 已提交
472 473 474
    }
  }

H
Haojun Liao 已提交
475 476 477
  SResultRow* pResult = NULL;
  if (!existInCurrentResusltRowInfo) {
    // 1. close current opened time window
478 479 480 481
    if (pResultRowInfo->cur.pageId != -1) {  // todo extract function
      SResultRowPosition pos = pResultRowInfo->cur;
      SFilePage* pPage = getBufPage(pResultBuf, pos.pageId);
      SResultRow* pRow = (SResultRow*)((char*)pPage + pos.offset);
H
Haojun Liao 已提交
482 483 484
      closeResultRow(pRow);
      releaseBufPage(pResultBuf, pPage);
    }
H
Haojun Liao 已提交
485

H
Haojun Liao 已提交
486
    prepareResultListBuffer(pResultRowInfo, pTaskInfo->env);
H
Haojun Liao 已提交
487
    if (p1 == NULL) {
488
      pResult = getNewResultRow_rv(pResultBuf, groupId, pSup->resultRowSize);
H
Haojun Liao 已提交
489
      initResultRow(pResult);
H
Haojun Liao 已提交
490 491

      // add a new result set for a new group
H
Haojun Liao 已提交
492
      SResultRowPosition pos = {.pageId = pResult->pageId, .offset = pResult->offset};
wmmhello's avatar
wmmhello 已提交
493
      taosHashPut(pSup->pResultRowHashTable, pSup->keyBuf, GET_RES_WINDOW_KEY_LEN(bytes), &pos, sizeof(SResultRowPosition));
494
      SResultRowCell cell = {.groupId = groupId, .pos = pos};
495
      taosArrayPush(pSup->pResultRowArrayList, &cell);
H
Haojun Liao 已提交
496
    } else {
H
Haojun Liao 已提交
497
      pResult = getResultRowByPos(pResultBuf, p1);
H
Haojun Liao 已提交
498 499
    }

H
Haojun Liao 已提交
500 501
    // 2. set the new time window to be the new active time window
    pResultRowInfo->pPosition[pResultRowInfo->size++] = (SResultRowPosition){.pageId = pResult->pageId, .offset = pResult->offset};
502
    pResultRowInfo->cur = (SResultRowPosition){.pageId = pResult->pageId, .offset = pResult->offset};
503
    SET_RES_EXT_WINDOW_KEY(pSup->keyBuf, pData, bytes, uid, pResultRowInfo);
504
    taosHashPut(pSup->pResultRowListSet, pSup->keyBuf, GET_RES_EXT_WINDOW_KEY_LEN(bytes), &pResultRowInfo->cur, POINTER_BYTES);
C
Cary Xu 已提交
505 506
  } else {
    pResult = getResultRowByPos(pResultBuf, p1);
H
Haojun Liao 已提交
507 508 509 510 511 512 513
  }

  // 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 已提交
514
  return pResult;
H
Haojun Liao 已提交
515 516
}

L
Liu Jicong 已提交
517 518
static void getInitialStartTimeWindow(SInterval* pInterval, int32_t precision, TSKEY ts, STimeWindow* w, TSKEY ekey,
                                      bool ascQuery) {
H
Haojun Liao 已提交
519 520
  if (ascQuery) {
    getAlignQueryTimeWindow(pInterval, precision, ts, ts, ekey, w);
521 522
  } else {
    // the start position of the first time window in the endpoint that spreads beyond the queried last timestamp
H
Haojun Liao 已提交
523
    getAlignQueryTimeWindow(pInterval, precision, ts, ekey, ts, w);
524 525

    int64_t key = w->skey;
L
Liu Jicong 已提交
526
    while (key < ts) {  // moving towards end
527
      key = taosTimeAdd(key, pInterval->sliding, pInterval->slidingUnit, precision);
528 529 530 531 532 533 534 535 536 537
      if (key >= ts) {
        break;
      }

      w->skey = key;
    }
  }
}

// get the correct time window according to the handled timestamp
H
Haojun Liao 已提交
538
static STimeWindow getActiveTimeWindow(SDiskbasedBuf * pBuf, SResultRowInfo* pResultRowInfo, int64_t ts, SInterval* pInterval,
L
Liu Jicong 已提交
539
                                       int32_t precision, STimeWindow* win) {
540 541
  STimeWindow w = {0};

542
  if (pResultRowInfo->cur.pageId == -1) {  // the first window, from the previous stored value
H
Haojun Liao 已提交
543
    getInitialStartTimeWindow(pInterval, precision, ts, &w, win->ekey, true);
544
    w.ekey = taosTimeAdd(w.skey, pInterval->interval, pInterval->intervalUnit, precision) - 1;
545
  } else {
546
    w = getResultRowByPos(pBuf, &pResultRowInfo->cur)->win;
547 548 549
  }

  if (w.skey > ts || w.ekey < ts) {
H
Haojun Liao 已提交
550 551 552
    if (pInterval->intervalUnit == 'n' || pInterval->intervalUnit == 'y') {
      w.skey = taosTimeTruncate(ts, pInterval, precision);
      w.ekey = taosTimeAdd(w.skey, pInterval->interval, pInterval->intervalUnit, precision) - 1;
553 554 555 556
    } else {
      int64_t st = w.skey;

      if (st > ts) {
H
Haojun Liao 已提交
557
        st -= ((st - ts + pInterval->sliding - 1) / pInterval->sliding) * pInterval->sliding;
558 559
      }

H
Haojun Liao 已提交
560
      int64_t et = st + pInterval->interval - 1;
561
      if (et < ts) {
H
Haojun Liao 已提交
562
        st += ((ts - et + pInterval->sliding - 1) / pInterval->sliding) * pInterval->sliding;
563 564 565
      }

      w.skey = st;
566
      w.ekey = taosTimeAdd(w.skey, pInterval->interval, pInterval->intervalUnit, precision) - 1;
567 568 569 570 571 572
    }
  }
  return w;
}

// get the correct time window according to the handled timestamp
L
Liu Jicong 已提交
573
static STimeWindow getCurrentActiveTimeWindow(SResultRowInfo* pResultRowInfo, int64_t ts, STaskAttr* pQueryAttr) {
574
  STimeWindow w = {0};
H
Haojun Liao 已提交
575
#if 0
L
Liu Jicong 已提交
576 577
  if (pResultRowInfo->curPos == -1) {  // the first window, from the previous stored value
                                       //    getInitialStartTimeWindow(pQueryAttr, ts, &w);
578 579

    if (pQueryAttr->interval.intervalUnit == 'n' || pQueryAttr->interval.intervalUnit == 'y') {
L
Liu Jicong 已提交
580 581 582
      w.ekey =
          taosTimeAdd(w.skey, pQueryAttr->interval.interval, pQueryAttr->interval.intervalUnit, pQueryAttr->precision) -
          1;
583 584 585 586
    } else {
      w.ekey = w.skey + pQueryAttr->interval.interval - 1;
    }
  } else {
H
Haojun Liao 已提交
587
    w = pRow->win;
588 589 590 591 592 593 594 595 596
  }

  /*
   * 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 已提交
597
#endif
598 599 600 601 602

  return w;
}

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

L
Liu Jicong 已提交
608
  SFilePage* pData = NULL;
609 610 611 612 613 614

  // 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 已提交
615
    pData = getNewBufPage(pResultBuf, tid, &pageId);
616
    pData->num = sizeof(SFilePage);
617 618
  } else {
    SPageInfo* pi = getLastPageInfo(list);
619
    pData = getBufPage(pResultBuf, getPageId(pi));
620
    pageId = getPageId(pi);
621

622
    if (pData->num + size > getBufPageSize(pResultBuf)) {
623
      // release current page first, and prepare the next one
624
      releaseBufPageInfo(pResultBuf, pi);
625

H
Haojun Liao 已提交
626
      pData = getNewBufPage(pResultBuf, tid, &pageId);
627
      if (pData != NULL) {
628
        pData->num = sizeof(SFilePage);
629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648
      }
    }
  }

  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 已提交
649 650 651
static bool chkWindowOutputBufByKey(STaskRuntimeEnv* pRuntimeEnv, SResultRowInfo* pResultRowInfo, STimeWindow* win,
                                    bool masterscan, SResultRow** pResult, int64_t groupId, SqlFunctionCtx* pCtx,
                                    int32_t numOfOutput, int32_t* rowCellInfoOffset) {
652
  assert(win->skey <= win->ekey);
L
Liu Jicong 已提交
653
  return chkResultRowFromKey(pRuntimeEnv, pResultRowInfo, (char*)&win->skey, TSDB_KEYSIZE, masterscan, groupId);
654 655
}

H
Haojun Liao 已提交
656
static void setResultRowOutputBufInitCtx_rv(SResultRow* pResult, SqlFunctionCtx* pCtx, int32_t numOfOutput, int32_t* rowCellInfoOffset);
H
Haojun Liao 已提交
657

L
Liu Jicong 已提交
658 659 660 661
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 已提交
662
  assert(win->skey <= win->ekey);
L
Liu Jicong 已提交
663 664
  SResultRow* pResultRow = doSetResultOutBufByKey_rv(pAggSup->pResultBuf, pResultRowInfo, id, (char*)&win->skey,
                                                     TSDB_KEYSIZE, masterscan, tableGroupId, pTaskInfo, true, pAggSup);
H
Haojun Liao 已提交
665 666 667 668 669 670 671 672 673

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

  // set time window for current result
  pResultRow->win = (*win);
  *pResult = pResultRow;
H
Haojun Liao 已提交
674
  setResultRowOutputBufInitCtx_rv(pResultRow, pCtx, numOfOutput, rowCellInfoOffset);
H
Haojun Liao 已提交
675 676 677
  return TSDB_CODE_SUCCESS;
}

678 679 680 681 682
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 已提交
683
    pResult->endInterp = true;
684 685 686 687 688 689 690 691
  }
}

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 已提交
692
    return pResult->endInterp == true;
693 694 695
  }
}

L
Liu Jicong 已提交
696 697
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) {
698 699 700
  int32_t forwardStep = 0;

  if (order == TSDB_ORDER_ASC) {
L
Liu Jicong 已提交
701
    int32_t end = searchFn((char*)&pData[pos], numOfRows - pos, ekey, order);
702 703 704 705 706 707 708 709
    if (end >= 0) {
      forwardStep = end;

      if (pData[end + pos] == ekey) {
        forwardStep += 1;
      }
    }
  } else {
L
Liu Jicong 已提交
710
    int32_t end = searchFn((char*)pData, pos + 1, ekey, order);
711 712 713 714 715 716 717 718 719 720 721 722 723
    if (end >= 0) {
      forwardStep = pos - end;

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

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

H
Haojun Liao 已提交
724
static void doUpdateResultRowIndex(SResultRowInfo* pResultRowInfo, TSKEY lastKey, bool ascQuery, bool timeWindowInterpo) {
725
  int64_t skey = TSKEY_INITIAL_VAL;
H
Haojun Liao 已提交
726
#if 0
727 728
  int32_t i = 0;
  for (i = pResultRowInfo->size - 1; i >= 0; --i) {
L
Liu Jicong 已提交
729
    SResultRow* pResult = pResultRowInfo->pResult[i];
730 731 732 733 734 735
    if (pResult->closed) {
      break;
    }

    // new closed result rows
    if (timeWindowInterpo) {
L
Liu Jicong 已提交
736 737 738
      if (pResult->endInterp &&
          ((pResult->win.skey <= lastKey && ascQuery) || (pResult->win.skey >= lastKey && !ascQuery))) {
        if (i > 0) {  // the first time window, the startInterp is false.
739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757
          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 已提交
758
      //      assert(pResultRowInfo->current == NULL);
759 760 761 762 763 764 765
      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 已提交
766
      SResultRow* pResult = pResultRowInfo->pResult[i];
767 768 769 770 771 772 773 774 775 776 777
      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 已提交
778
#endif
779
}
780 781 782 783 784 785 786 787 788 789 790
//
//static void updateResultRowInfoActiveIndex(SResultRowInfo* pResultRowInfo, const STimeWindow* pWin, TSKEY lastKey,
//                                           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);
//  }
//}
791

L
Liu Jicong 已提交
792 793 794
static int32_t getNumOfRowsInTimeWindow(SDataBlockInfo* pDataBlockInfo, TSKEY* pPrimaryColumn, int32_t startPos,
                                        TSKEY ekey, __block_search_fn_t searchFn, STableQueryInfo* item,
                                        int32_t order) {
795 796
  assert(startPos >= 0 && startPos < pDataBlockInfo->rows);

L
Liu Jicong 已提交
797 798
  int32_t num = -1;
  int32_t step = GET_FORWARD_DIRECTION_FACTOR(order);
799

H
Haojun Liao 已提交
800
  if (order == TSDB_ORDER_ASC) {
801 802
    if (ekey < pDataBlockInfo->window.ekey && pPrimaryColumn) {
      num = getForwardStepsInBlock(pDataBlockInfo->rows, searchFn, ekey, startPos, order, pPrimaryColumn);
H
Haojun Liao 已提交
803
      if (item != NULL) {
804 805 806 807
        item->lastKey = pPrimaryColumn[startPos + (num - 1)] + step;
      }
    } else {
      num = pDataBlockInfo->rows - startPos;
H
Haojun Liao 已提交
808
      if (item != NULL) {
809 810 811 812 813 814
        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 已提交
815
      if (item != NULL) {
816 817 818 819
        item->lastKey = pPrimaryColumn[startPos - (num - 1)] + step;
      }
    } else {
      num = startPos + 1;
H
Haojun Liao 已提交
820
      if (item != NULL) {
821 822 823 824 825 826 827 828 829
        item->lastKey = pDataBlockInfo->window.skey + step;
      }
    }
  }

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

830 831 832 833 834
//  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);

835
  colInfoDataEnsureCapacity(pColData, 0, 5);
836 837 838 839 840 841 842 843 844
  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);
}

845
static void updateTimeWindowInfo(SColumnInfoData* pColData, STimeWindow* pWin, bool includeEndpoint) {
846
  int64_t* ts = (int64_t*)pColData->pData;
847
  int32_t delta = includeEndpoint? 1:0;
848

849
  int64_t duration = pWin->ekey - pWin->skey + delta;
850 851
  ts[2] = duration;       // set the duration
  ts[3] = pWin->skey;     // window start key
852
  ts[4] = pWin->ekey + delta; // window end key
853 854
}

H
Haojun Liao 已提交
855
void doApplyFunctions(SqlFunctionCtx* pCtx, STimeWindow* pWin, SColumnInfoData* pTimeWindowData, int32_t offset, int32_t forwardStep, TSKEY* tsCol,
856
                             int32_t numOfTotal, int32_t numOfOutput, int32_t order) {
857 858 859
  for (int32_t k = 0; k < numOfOutput; ++k) {
    pCtx[k].startTs = pWin->skey;

H
Haojun Liao 已提交
860
    // keep it temporarily
861 862
    bool    hasAgg      = pCtx[k].input.colDataAggIsSet;
    int32_t numOfRows   = pCtx[k].input.numOfRows;
H
Haojun Liao 已提交
863
    int32_t startOffset = pCtx[k].input.startRowIndex;
864

H
Haojun Liao 已提交
865
    int32_t pos = (order == TSDB_ORDER_ASC) ? offset : offset - (forwardStep - 1);
866 867
    pCtx[k].input.startRowIndex = pos;
    pCtx[k].input.numOfRows = forwardStep;
868 869

    if (tsCol != NULL) {
H
Haojun Liao 已提交
870
      pCtx[k].ptsList = tsCol;
871 872 873 874 875 876 877 878
    }

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

879 880 881 882
    if (fmIsWindowPseudoColumnFunc(pCtx[k].functionId)) {
      SResultRowEntryInfo* pEntryInfo = GET_RES_INFO(&pCtx[k]);
      char* p = GET_ROWCELL_INTERBUF(pEntryInfo);

883 884 885 886 887 888 889 890
      SColumnInfoData idata = {0};
      idata.info.type  = TSDB_DATA_TYPE_BIGINT;
      idata.info.bytes = tDataTypes[TSDB_DATA_TYPE_BIGINT].bytes;
      idata.pData      = p;

      SScalarParam out = {.columnData = &idata};
      SScalarParam tw = {.numOfRows = 5, .columnData = pTimeWindowData};
      pCtx[k].sfp.process(&tw, 1, &out);
891 892 893 894
      pEntryInfo->numOfRes = 1;
      continue;
    }

H
Haojun Liao 已提交
895
    if (functionNeedToExecute(&pCtx[k])) {
896
      pCtx[k].fpSet.process(&pCtx[k]);
897 898 899
    }

    // restore it
900 901 902
    pCtx[k].input.colDataAggIsSet = hasAgg;
    pCtx[k].input.startRowIndex = startOffset;
    pCtx[k].input.numOfRows = numOfRows;
903 904 905
  }
}

H
Haojun Liao 已提交
906 907 908
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 已提交
909
  bool    ascQuery = (order == TSDB_ORDER_ASC);
H
Haojun Liao 已提交
910

911
  int32_t precision = pInterval->precision;
H
Haojun Liao 已提交
912
  getNextTimeWindow(pInterval, precision, order, pNext);
913 914

  // next time window is not in current block
H
Haojun Liao 已提交
915 916
  if ((pNext->skey > pDataBlockInfo->window.ekey && order == TSDB_ORDER_ASC) ||
      (pNext->ekey < pDataBlockInfo->window.skey && order == TSDB_ORDER_DESC)) {
917 918 919
    return -1;
  }

L
Liu Jicong 已提交
920
  TSKEY   startKey = ascQuery ? pNext->skey : pNext->ekey;
921 922 923
  int32_t startPos = 0;

  // tumbling time window query, a special case of sliding time window query
H
Haojun Liao 已提交
924 925
  if (pInterval->sliding == pInterval->interval && prevPosition != -1) {
    int32_t factor = GET_FORWARD_DIRECTION_FACTOR(order);
926 927
    startPos = prevPosition + factor;
  } else {
H
Haojun Liao 已提交
928
    if (startKey <= pDataBlockInfo->window.skey && ascQuery) {
929
      startPos = 0;
H
Haojun Liao 已提交
930
    } else if (startKey >= pDataBlockInfo->window.ekey && !ascQuery) {
931 932
      startPos = pDataBlockInfo->rows - 1;
    } else {
L
Liu Jicong 已提交
933
      startPos = binarySearchForKey((char*)primaryKeys, pDataBlockInfo->rows, startKey, order);
934 935 936 937
    }
  }

  /* interp query with fill should not skip time window */
L
Liu Jicong 已提交
938 939 940
  //  if (pQueryAttr->pointInterpQuery && pQueryAttr->fillType != TSDB_FILL_NONE) {
  //    return startPos;
  //  }
941 942 943 944 945 946

  /*
   * 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 已提交
947
    if (ascQuery) {
948 949 950 951 952
      assert(pDataBlockInfo->window.skey <= pNext->ekey);
    } else {
      assert(pDataBlockInfo->window.ekey >= pNext->skey);
    }
  } else {
H
Haojun Liao 已提交
953
    if (ascQuery && primaryKeys[startPos] > pNext->ekey) {
954
      TSKEY next = primaryKeys[startPos];
H
Haojun Liao 已提交
955 956 957
      if (pInterval->intervalUnit == 'n' || pInterval->intervalUnit == 'y') {
        pNext->skey = taosTimeTruncate(next, pInterval, precision);
        pNext->ekey = taosTimeAdd(pNext->skey, pInterval->interval, pInterval->intervalUnit, precision) - 1;
958
      } else {
L
Liu Jicong 已提交
959
        pNext->ekey += ((next - pNext->ekey + pInterval->sliding - 1) / pInterval->sliding) * pInterval->sliding;
H
Haojun Liao 已提交
960
        pNext->skey = pNext->ekey - pInterval->interval + 1;
961
      }
H
Haojun Liao 已提交
962
    } else if ((!ascQuery) && primaryKeys[startPos] < pNext->skey) {
963
      TSKEY next = primaryKeys[startPos];
H
Haojun Liao 已提交
964 965 966
      if (pInterval->intervalUnit == 'n' || pInterval->intervalUnit == 'y') {
        pNext->skey = taosTimeTruncate(next, pInterval, precision);
        pNext->ekey = taosTimeAdd(pNext->skey, pInterval->interval, pInterval->intervalUnit, precision) - 1;
967
      } else {
H
Haojun Liao 已提交
968 969
        pNext->skey -= ((pNext->skey - next + pInterval->sliding - 1) / pInterval->sliding) * pInterval->sliding;
        pNext->ekey = pNext->skey + pInterval->interval - 1;
970 971 972 973 974 975 976
      }
    }
  }

  return startPos;
}

L
Liu Jicong 已提交
977
static FORCE_INLINE TSKEY reviseWindowEkey(STaskAttr* pQueryAttr, STimeWindow* pWindow) {
978
  TSKEY ekey = -1;
979 980
  int32_t order = TSDB_ORDER_ASC;
  if (order == TSDB_ORDER_ASC) {
981 982 983 984 985 986 987 988 989 990 991 992 993 994
    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 已提交
995
static void setNotInterpoWindowKey(SqlFunctionCtx* pCtx, int32_t numOfOutput, int32_t type) {
996 997 998 999 1000 1001 1002 1003 1004 1005 1006
  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 已提交
1007
static void saveDataBlockLastRow(char** pRow, SArray* pDataBlock, int32_t rowIndex, int32_t numOfCols) {
1008 1009 1010 1011
  if (pDataBlock == NULL) {
    return;
  }

H
Haojun Liao 已提交
1012
  for (int32_t k = 0; k < numOfCols; ++k) {
L
Liu Jicong 已提交
1013
    SColumnInfoData* pColInfo = taosArrayGet(pDataBlock, k);
H
Haojun Liao 已提交
1014
    memcpy(pRow[k], ((char*)pColInfo->pData) + (pColInfo->info.bytes * rowIndex), pColInfo->info.bytes);
1015 1016 1017
  }
}

H
Haojun Liao 已提交
1018
static TSKEY getStartTsKey(STimeWindow* win, const TSKEY* tsCols, int32_t rows, bool ascQuery) {
1019 1020
  TSKEY ts = TSKEY_INITIAL_VAL;
  if (tsCols == NULL) {
L
Liu Jicong 已提交
1021
    ts = ascQuery ? win->skey : win->ekey;
1022
  } else {
L
Liu Jicong 已提交
1023
    int32_t offset = ascQuery ? 0 : rows - 1;
1024 1025 1026 1027 1028 1029
    ts = tsCols[offset];
  }

  return ts;
}

1030
static int32_t doSetInputDataBlock(SOperatorInfo* pOperator, SqlFunctionCtx* pCtx, SSDataBlock* pBlock, int32_t order, bool createDummyCol);
1031

1032
static void doSetInputDataBlockInfo(SOperatorInfo* pOperator, SqlFunctionCtx* pCtx, SSDataBlock* pBlock, int32_t order) {
1033 1034
  for (int32_t i = 0; i < pOperator->numOfOutput; ++i) {
    pCtx[i].order = order;
L
Liu Jicong 已提交
1035
    pCtx[i].size = pBlock->info.rows;
1036
    setBlockStatisInfo(&pCtx[i], &pOperator->pExpr[i], pBlock);
1037 1038 1039
  }
}

1040
void setInputDataBlock(SOperatorInfo* pOperator, SqlFunctionCtx* pCtx, SSDataBlock* pBlock, int32_t order, bool createDummyCol) {
1041
  if (pBlock->pBlockAgg != NULL) {
H
Haojun Liao 已提交
1042
    doSetInputDataBlockInfo(pOperator, pCtx, pBlock, order);
1043
  } else {
1044
    doSetInputDataBlock(pOperator, pCtx, pBlock, order, createDummyCol);
H
Haojun Liao 已提交
1045
  }
1046 1047
}

1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063
static int32_t doCreateConstantValColumnInfo(SInputColumnInfoData* pInput, SFunctParam* pFuncParam, int32_t type, int32_t paramIndex, int32_t numOfRows) {
  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)
    pColInfo->info.type  = type;
    pColInfo->info.bytes  = tDataTypes[type].bytes;

    pInput->pData[paramIndex] = pColInfo;
  }

  ASSERT(!IS_VAR_DATA_TYPE(type));
1064
  colInfoDataEnsureCapacity(pColInfo, 0, numOfRows);
1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080

  if (type == TSDB_DATA_TYPE_BIGINT || type == TSDB_DATA_TYPE_UBIGINT) {
    int64_t v = pFuncParam->param.i;
    for(int32_t i = 0; i < numOfRows; ++i) {
      colDataAppendInt64(pColInfo, i, &v);
    }
  } else if (type == TSDB_DATA_TYPE_DOUBLE) {
    double v = pFuncParam->param.d;
    for(int32_t i = 0; i < numOfRows; ++i) {
      colDataAppendDouble(pColInfo, i, &v);
    }
  }

  return TSDB_CODE_SUCCESS;
}

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

1089 1090
    SInputColumnInfoData* pInput = &pCtx[i].input;

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

        pInput->pPTS = taosArrayGet(pBlock->pDataBlock, 0); // todo set the correct timestamp column
1102 1103
        ASSERT(pInput->pData[j] != NULL);
      } else if (pFuncParam->type == FUNC_PARAM_TYPE_VALUE) {
1104 1105 1106 1107 1108
        if (createDummyCol) {
          code = doCreateConstantValColumnInfo(pInput, pFuncParam, pFuncParam->param.nType, j, pBlock->info.rows);
          if (code != TSDB_CODE_SUCCESS) {
            return code;
          }
1109
        }
G
Ganlin Zhao 已提交
1110 1111
      }
    }
H
Haojun Liao 已提交
1112

H
Haojun Liao 已提交
1113
    //    setBlockStatisInfo(&pCtx[i], pBlock, pOperator->pExpr[i].base.pColumns);
H
Haojun Liao 已提交
1114 1115 1116 1117 1118 1119 1120 1121 1122 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
    //      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);
    //        }
    //      }
  }
1152 1153

  return code;
H
Haojun Liao 已提交
1154 1155 1156
}

static void doAggregateImpl(SOperatorInfo* pOperator, TSKEY startTs, SqlFunctionCtx* pCtx) {
1157
  for (int32_t k = 0; k < pOperator->numOfOutput; ++k) {
H
Haojun Liao 已提交
1158
    if (functionNeedToExecute(&pCtx[k])) {
L
Liu Jicong 已提交
1159
      pCtx[k].startTs = startTs;  // this can be set during create the struct
H
Haojun Liao 已提交
1160
      pCtx[k].fpSet.process(&pCtx[k]);
1161 1162 1163 1164
    }
  }
}

H
Haojun Liao 已提交
1165
static void setPseudoOutputColInfo(SSDataBlock* pResult, SqlFunctionCtx* pCtx, SArray* pPseudoList) {
1166
  size_t num = (pPseudoList != NULL)? taosArrayGetSize(pPseudoList):0;
H
Haojun Liao 已提交
1167 1168 1169 1170 1171
  for (int32_t i = 0; i < num; ++i) {
    pCtx[i].pOutput = taosArrayGet(pResult->pDataBlock, i);
  }
}

1172
void projectApplyFunctions(SExprInfo* pExpr, SSDataBlock* pResult, SSDataBlock* pSrcBlock, SqlFunctionCtx* pCtx, int32_t numOfOutput, SArray* pPseudoList) {
H
Haojun Liao 已提交
1173
  setPseudoOutputColInfo(pResult, pCtx, pPseudoList);
H
Haojun Liao 已提交
1174
  pResult->info.groupId = pSrcBlock->info.groupId;
H
Haojun Liao 已提交
1175

1176 1177 1178
  // if the source equals to the destination, it is to create a new column as the result of scalar function or some operators.
  bool createNewColModel = (pResult == pSrcBlock);

1179 1180
  int32_t numOfRows = 0;

1181
  for (int32_t k = 0; k < numOfOutput; ++k) {
1182 1183 1184
    int32_t outputSlotId = pExpr[k].base.resSchema.slotId;
    SqlFunctionCtx* pfCtx = &pCtx[k];

L
Liu Jicong 已提交
1185
    if (pExpr[k].pExpr->nodeType == QUERY_NODE_COLUMN) {  // it is a project query
1186
      SColumnInfoData* pColInfoData = taosArrayGet(pResult->pDataBlock, outputSlotId);
1187
      if (pResult->info.rows > 0 && !createNewColModel) {
1188 1189 1190 1191
        colDataMergeCol(pColInfoData, pResult->info.rows, pfCtx->input.pData[0], pfCtx->input.numOfRows);
      } else {
        colDataAssign(pColInfoData, pfCtx->input.pData[0], pfCtx->input.numOfRows);
      }
1192

1193
      numOfRows = pfCtx->input.numOfRows;
1194
    } else if (pExpr[k].pExpr->nodeType == QUERY_NODE_VALUE) {
1195
      SColumnInfoData* pColInfoData = taosArrayGet(pResult->pDataBlock, outputSlotId);
1196

1197
      int32_t offset = createNewColModel? 0: pResult->info.rows;
1198
      for (int32_t i = 0; i < pSrcBlock->info.rows; ++i) {
1199
        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);
1200
      }
1201 1202

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

1207 1208
      SColumnInfoData* pResColData = taosArrayGet(pResult->pDataBlock, outputSlotId);
      SColumnInfoData idata = {.info = pResColData->info};
1209

1210
      SScalarParam dest = {.columnData = &idata};
1211 1212
      scalarCalculate(pExpr[k].pExpr->_optrRoot.pRootNode, pBlockList, &dest);

1213 1214
      int32_t startOffset = createNewColModel? 0:pResult->info.rows;
      colDataMergeCol(pResColData, startOffset, &idata, dest.numOfRows);
1215 1216

      numOfRows = dest.numOfRows;
1217 1218
      taosArrayDestroy(pBlockList);
    } else if (pExpr[k].pExpr->nodeType == QUERY_NODE_FUNCTION) {
1219
      ASSERT(!fmIsAggFunc(pfCtx->functionId));
1220

1221
      if (fmIsPseudoColumnFunc(pfCtx->functionId)) {
H
Haojun Liao 已提交
1222
        // do nothing
1223
      } else if (fmIsNonstandardSQLFunc(pfCtx->functionId)) {
H
Haojun Liao 已提交
1224
        // todo set the correct timestamp column
1225
        pfCtx->input.pPTS = taosArrayGet(pSrcBlock->pDataBlock, 1);
1226

H
Haojun Liao 已提交
1227
        SResultRowEntryInfo *pResInfo = GET_RES_INFO(&pCtx[k]);
1228
        pfCtx->fpSet.init(&pCtx[k], pResInfo);
1229

1230
        pfCtx->pOutput = taosArrayGet(pResult->pDataBlock, outputSlotId);
1231
        pfCtx->offset  = createNewColModel? 0:pResult->info.rows; // set the start offset
H
Haojun Liao 已提交
1232

1233
        // set the timestamp(_rowts) output buffer
1234 1235
        if (taosArrayGetSize(pPseudoList) > 0) {
          int32_t* outputColIndex = taosArrayGet(pPseudoList, 0);
1236
          pfCtx->pTsOutput = (SColumnInfoData*)pCtx[*outputColIndex].pOutput;
1237
        }
H
Haojun Liao 已提交
1238

1239
        numOfRows = pfCtx->fpSet.process(pfCtx);
H
Haojun Liao 已提交
1240 1241 1242
      } else {
        SArray* pBlockList = taosArrayInit(4, POINTER_BYTES);
        taosArrayPush(pBlockList, &pSrcBlock);
G
Ganlin Zhao 已提交
1243

1244 1245
        SColumnInfoData* pResColData = taosArrayGet(pResult->pDataBlock, outputSlotId);
        SColumnInfoData idata = {.info = pResColData->info};
H
Haojun Liao 已提交
1246

1247
        SScalarParam dest = {.columnData = &idata};
H
Haojun Liao 已提交
1248
        scalarCalculate((SNode*)pExpr[k].pExpr->_function.pFunctNode, pBlockList, &dest);
1249 1250 1251

        int32_t startOffset = createNewColModel? 0:pResult->info.rows;
        colDataMergeCol(pResColData, startOffset, &idata, dest.numOfRows);
1252 1253

        numOfRows = dest.numOfRows;
H
Haojun Liao 已提交
1254 1255
        taosArrayDestroy(pBlockList);
      }
1256
    } else {
1257
      ASSERT(0);
1258 1259
    }
  }
1260

1261 1262 1263
  if (!createNewColModel) {
    pResult->info.rows += numOfRows;
  }
1264 1265 1266 1267
}

void doTimeWindowInterpolation(SOperatorInfo* pOperator, SOptrBasicInfo* pInfo, SArray* pDataBlock, TSKEY prevTs,
                               int32_t prevRowIndex, TSKEY curTs, int32_t curRowIndex, TSKEY windowKey, int32_t type) {
L
Liu Jicong 已提交
1268
  SExprInfo*       pExpr = pOperator->pExpr;
1269

H
Haojun Liao 已提交
1270
  SqlFunctionCtx* pCtx = pInfo->pCtx;
1271 1272 1273 1274 1275 1276 1277 1278

  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 已提交
1279
    SColIndex*       pColIndex = NULL /*&pExpr[k].base.colInfo*/;
1280
    int16_t          index = pColIndex->colIndex;
L
Liu Jicong 已提交
1281
    SColumnInfoData* pColInfo = taosArrayGet(pDataBlock, index);
1282

L
Liu Jicong 已提交
1283
    //    assert(pColInfo->info.colId == pColIndex->info.colId && curTs != windowKey);
1284 1285 1286
    double v1 = 0, v2 = 0, v = 0;

    if (prevRowIndex == -1) {
1287
//      GET_TYPED_DATA(v1, double, pColInfo->info.type, (char*)pRuntimeEnv->prevRow[index]);
1288
    } else {
L
Liu Jicong 已提交
1289
      GET_TYPED_DATA(v1, double, pColInfo->info.type, (char*)pColInfo->pData + prevRowIndex * pColInfo->info.bytes);
1290 1291
    }

L
Liu Jicong 已提交
1292
    GET_TYPED_DATA(v2, double, pColInfo->info.type, (char*)pColInfo->pData + curRowIndex * pColInfo->info.bytes);
1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303

    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) {
1304
//            pCtx[k].start.ptr = (char*)pRuntimeEnv->prevRow[index];
1305
          } else {
L
Liu Jicong 已提交
1306
            pCtx[k].start.ptr = (char*)pColInfo->pData + prevRowIndex * pColInfo->info.bytes;
1307 1308
          }

L
Liu Jicong 已提交
1309
          pCtx[k].end.ptr = (char*)pColInfo->pData + curRowIndex * pColInfo->info.bytes;
1310 1311 1312
        }
      }
    } else if (functionId == FUNCTION_TWA) {
L
Liu Jicong 已提交
1313 1314 1315
      SPoint point1 = (SPoint){.key = prevTs, .val = &v1};
      SPoint point2 = (SPoint){.key = curTs, .val = &v2};
      SPoint point = (SPoint){.key = windowKey, .val = &v};
1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329

      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 已提交
1330
static bool setTimeWindowInterpolationStartTs(SOperatorInfo* pOperatorInfo, SqlFunctionCtx* pCtx, int32_t pos,
H
Haojun Liao 已提交
1331 1332
                                              int32_t numOfRows, SArray* pDataBlock, const TSKEY* tsCols, STimeWindow* win) {
  bool  ascQuery = true;
L
Liu Jicong 已提交
1333
  TSKEY curTs = tsCols[pos];
H
Haojun Liao 已提交
1334
  TSKEY lastTs = 0;//*(TSKEY*)pRuntimeEnv->prevRow[0];
1335 1336 1337

  // 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 已提交
1338
  TSKEY key = ascQuery ? win->skey : win->ekey;
1339 1340 1341 1342 1343 1344 1345 1346 1347 1348
  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;
  }

H
Haojun Liao 已提交
1349
  int32_t step = 1;//GET_FORWARD_DIRECTION_FACTOR(pQueryAttr->order.order);
L
Liu Jicong 已提交
1350
  TSKEY   prevTs = ((pos == 0 && ascQuery) || (pos == (numOfRows - 1) && !ascQuery)) ? lastTs : tsCols[pos - step];
1351

H
Haojun Liao 已提交
1352
  doTimeWindowInterpolation(pOperatorInfo, pOperatorInfo->info, pDataBlock, prevTs, pos - step, curTs, pos, key, RESULT_ROW_START_INTERP);
1353 1354 1355
  return true;
}

L
Liu Jicong 已提交
1356 1357 1358
static bool setTimeWindowInterpolationEndTs(SOperatorInfo* pOperatorInfo, SqlFunctionCtx* pCtx, int32_t endRowIndex,
                                            SArray* pDataBlock, const TSKEY* tsCols, TSKEY blockEkey,
                                            STimeWindow* win) {
H
Haojun Liao 已提交
1359 1360
  int32_t order = TSDB_ORDER_ASC;
  int32_t numOfOutput = pOperatorInfo->numOfOutput;
1361

L
Liu Jicong 已提交
1362
  TSKEY actualEndKey = tsCols[endRowIndex];
H
Haojun Liao 已提交
1363
  TSKEY key = order ? win->ekey : win->skey;
1364 1365

  // not ended in current data block, do not invoke interpolation
H
Haojun Liao 已提交
1366
  if ((key > blockEkey /*&& QUERY_IS_ASC_QUERY(pQueryAttr)*/) || (key < blockEkey /*&& !QUERY_IS_ASC_QUERY(pQueryAttr)*/)) {
1367 1368 1369 1370 1371 1372 1373 1374 1375 1376
    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 已提交
1377
  int32_t step = GET_FORWARD_DIRECTION_FACTOR(order);
1378 1379 1380 1381 1382
  int32_t nextRowIndex = endRowIndex + step;
  assert(nextRowIndex >= 0);

  TSKEY nextKey = tsCols[nextRowIndex];
  doTimeWindowInterpolation(pOperatorInfo, pOperatorInfo->info, pDataBlock, actualEndKey, endRowIndex, nextKey,
L
Liu Jicong 已提交
1383
                            nextRowIndex, key, RESULT_ROW_END_INTERP);
1384 1385 1386
  return true;
}

H
Haojun Liao 已提交
1387
static void doWindowBorderInterpolation(SOperatorInfo* pOperatorInfo, SSDataBlock* pBlock, SqlFunctionCtx* pCtx,
L
Liu Jicong 已提交
1388 1389
                                        SResultRow* pResult, STimeWindow* win, int32_t startPos, int32_t forwardStep,
                                        int32_t order, bool timeWindowInterpo) {
H
Haojun Liao 已提交
1390
  if (!timeWindowInterpo) {
1391 1392 1393 1394
    return;
  }

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

L
Liu Jicong 已提交
1397 1398
  if (pBlock->pDataBlock == NULL) {
    //    tscError("pBlock->pDataBlock == NULL");
1399 1400
    return;
  }
H
Haojun Liao 已提交
1401

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

L
Liu Jicong 已提交
1404 1405 1406
  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
1407
    int32_t startRowIndex = startPos;
L
Liu Jicong 已提交
1408 1409
    bool    interp = setTimeWindowInterpolationStartTs(pOperatorInfo, pCtx, startRowIndex, pBlock->info.rows,
                                                       pBlock->pDataBlock, tsCols, win);
1410 1411 1412 1413
    if (interp) {
      setResultRowInterpo(pResult, RESULT_ROW_START_INTERP);
    }
  } else {
H
Haojun Liao 已提交
1414
    setNotInterpoWindowKey(pCtx, pOperatorInfo->numOfOutput, RESULT_ROW_START_INTERP);
1415 1416 1417
  }

  // point interpolation does not require the end key time window interpolation.
L
Liu Jicong 已提交
1418 1419 1420
  //  if (pointInterpQuery) {
  //    return;
  //  }
1421 1422 1423 1424 1425 1426

  // 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 已提交
1427 1428 1429
    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);
1430 1431 1432 1433
    if (interp) {
      setResultRowInterpo(pResult, RESULT_ROW_END_INTERP);
    }
  } else {
H
Haojun Liao 已提交
1434
    setNotInterpoWindowKey(pCtx, pOperatorInfo->numOfOutput, RESULT_ROW_END_INTERP);
1435 1436 1437
  }
}

1438
static SArray* hashIntervalAgg(SOperatorInfo* pOperatorInfo, SResultRowInfo* pResultRowInfo, SSDataBlock* pSDataBlock, int32_t tableGroupId) {
L
Liu Jicong 已提交
1439
  STableIntervalOperatorInfo* pInfo = (STableIntervalOperatorInfo*)pOperatorInfo->info;
1440

H
Haojun Liao 已提交
1441
  SExecTaskInfo* pTaskInfo = pOperatorInfo->pTaskInfo;
L
Liu Jicong 已提交
1442
  int32_t        numOfOutput = pOperatorInfo->numOfOutput;
1443

1444 1445 1446 1447 1448
  SArray* pUpdated = NULL;
  if (pInfo->execModel == OPTR_EXEC_MODEL_STREAM) {
    pUpdated = taosArrayInit(4, sizeof(SResultRowPosition));
  }

H
Haojun Liao 已提交
1449
  int32_t step = 1;
1450
  bool    ascScan = true;
1451

1452
//  int32_t prevIndex = pResultRowInfo->curPos;
1453 1454 1455

  TSKEY* tsCols = NULL;
  if (pSDataBlock->pDataBlock != NULL) {
1456
    SColumnInfoData* pColDataInfo = taosArrayGet(pSDataBlock->pDataBlock, pInfo->primaryTsIndex);
L
Liu Jicong 已提交
1457
    tsCols = (int64_t*)pColDataInfo->pData;
H
Haojun Liao 已提交
1458 1459
//    assert(tsCols[0] == pSDataBlock->info.window.skey && tsCols[pSDataBlock->info.rows - 1] ==
//           pSDataBlock->info.window.ekey);
1460 1461
  }

1462 1463
  int32_t startPos = ascScan? 0 : (pSDataBlock->info.rows - 1);
  TSKEY   ts = getStartTsKey(&pSDataBlock->info.window, tsCols, pSDataBlock->info.rows, ascScan);
1464

H
Haojun Liao 已提交
1465
  STimeWindow win = getActiveTimeWindow(pInfo->aggSup.pResultBuf, pResultRowInfo, ts, &pInfo->interval, pInfo->interval.precision, &pInfo->win);
L
Liu Jicong 已提交
1466
  bool        masterScan = true;
1467 1468

  SResultRow* pResult = NULL;
L
Liu Jicong 已提交
1469 1470 1471
  int32_t     ret = setResultOutputBufByKey_rv(pResultRowInfo, pSDataBlock->info.uid, &win, masterScan, &pResult,
                                               tableGroupId, pInfo->binfo.pCtx, numOfOutput, pInfo->binfo.rowCellInfoOffset,
                                               &pInfo->aggSup, pTaskInfo);
1472
  if (ret != TSDB_CODE_SUCCESS || pResult == NULL) {
H
Haojun Liao 已提交
1473
    longjmp(pTaskInfo->env, TSDB_CODE_QRY_OUT_OF_MEMORY);
1474 1475
  }

1476 1477 1478 1479 1480
  if (pInfo->execModel == OPTR_EXEC_MODEL_STREAM) {
    SResultRowPosition pos = {.pageId = pResult->pageId, .offset = pResult->offset};
    taosArrayPush(pUpdated, &pos);
  }

1481
  int32_t forwardStep = 0;
H
Haojun Liao 已提交
1482
  TSKEY   ekey = win.ekey;
1483
  forwardStep =
H
Haojun Liao 已提交
1484
      getNumOfRowsInTimeWindow(&pSDataBlock->info, tsCols, startPos, ekey, binarySearchForKey, NULL, TSDB_ORDER_ASC);
1485 1486

  // prev time window not interpolation yet.
1487
//  int32_t curIndex = pResultRowInfo->curPos;
H
Haojun Liao 已提交
1488 1489

#if 0
H
Haojun Liao 已提交
1490
  if (prevIndex != -1 && prevIndex < curIndex && pInfo->timeWindowInterpo) {
1491 1492 1493
    for (int32_t j = prevIndex; j < curIndex; ++j) {  // previous time window may be all closed already.
      SResultRow* pRes = getResultRow(pResultRowInfo, j);
      if (pRes->closed) {
1494
        assert(resultRowInterpolated(pRes, RESULT_ROW_START_INTERP) && resultRowInterpolated(pRes, RESULT_ROW_END_INTERP));
1495 1496 1497
        continue;
      }

L
Liu Jicong 已提交
1498 1499 1500 1501 1502 1503 1504
      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);
      }
1505

L
Liu Jicong 已提交
1506 1507 1508
      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);
1509

L
Liu Jicong 已提交
1510 1511
      setResultRowInterpo(pResult, RESULT_ROW_END_INTERP);
      setNotInterpoWindowKey(pInfo->binfo.pCtx, pOperatorInfo->numOfOutput, RESULT_ROW_START_INTERP);
1512

1513
      doApplyFunctions(pInfo->binfo.pCtx, &w, &pInfo->timeWindowData, startPos, 0, tsCols, pSDataBlock->info.rows, numOfOutput, TSDB_ORDER_ASC);
L
Liu Jicong 已提交
1514
    }
1515 1516

    // restore current time window
L
Liu Jicong 已提交
1517 1518 1519
    ret = setResultOutputBufByKey_rv(pResultRowInfo, pSDataBlock->info.uid, &win, masterScan, &pResult, tableGroupId,
                                     pInfo->binfo.pCtx, numOfOutput, pInfo->binfo.rowCellInfoOffset, &pInfo->aggSup,
                                     pTaskInfo);
1520
    if (ret != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
1521
      longjmp(pTaskInfo->env, TSDB_CODE_QRY_OUT_OF_MEMORY);
1522 1523
    }
  }
H
Haojun Liao 已提交
1524
#endif
1525 1526

  // window start key interpolation
1527 1528
  doWindowBorderInterpolation(pOperatorInfo, pSDataBlock, pInfo->binfo.pCtx, pResult, &win, startPos, forwardStep, pInfo->order, false);

1529 1530
  updateTimeWindowInfo(&pInfo->twAggSup.timeWindowData, &win, true);
  doApplyFunctions(pInfo->binfo.pCtx, &win, &pInfo->twAggSup.timeWindowData, startPos, forwardStep, tsCols, pSDataBlock->info.rows, numOfOutput, TSDB_ORDER_ASC);
1531 1532 1533 1534

  STimeWindow nextWin = win;
  while (1) {
    int32_t prevEndPos = (forwardStep - 1) * step + startPos;
H
Haojun Liao 已提交
1535
    startPos = getNextQualifiedWindow(&pInfo->interval, &nextWin, &pSDataBlock->info, tsCols, prevEndPos, pInfo);
1536 1537 1538 1539 1540
    if (startPos < 0) {
      break;
    }

    // null data, failed to allocate more memory buffer
L
Liu Jicong 已提交
1541 1542 1543
    int32_t code = setResultOutputBufByKey_rv(pResultRowInfo, pSDataBlock->info.uid, &nextWin, masterScan, &pResult,
                                              tableGroupId, pInfo->binfo.pCtx, numOfOutput,
                                              pInfo->binfo.rowCellInfoOffset, &pInfo->aggSup, pTaskInfo);
1544
    if (code != TSDB_CODE_SUCCESS || pResult == NULL) {
H
Haojun Liao 已提交
1545
      longjmp(pTaskInfo->env, TSDB_CODE_QRY_OUT_OF_MEMORY);
1546 1547
    }

1548 1549 1550 1551 1552
    if (pInfo->execModel == OPTR_EXEC_MODEL_STREAM) {
      SResultRowPosition pos = {.pageId = pResult->pageId, .offset = pResult->offset};
      taosArrayPush(pUpdated, &pos);
    }

L
Liu Jicong 已提交
1553 1554 1555
    ekey = nextWin.ekey;  // reviseWindowEkey(pQueryAttr, &nextWin);
    forwardStep =
        getNumOfRowsInTimeWindow(&pSDataBlock->info, tsCols, startPos, ekey, binarySearchForKey, NULL, TSDB_ORDER_ASC);
1556 1557

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

1561 1562
    updateTimeWindowInfo(&pInfo->twAggSup.timeWindowData, &nextWin, true);
    doApplyFunctions(pInfo->binfo.pCtx, &nextWin, &pInfo->twAggSup.timeWindowData, startPos, forwardStep, tsCols, pSDataBlock->info.rows, numOfOutput, TSDB_ORDER_ASC);
1563 1564
  }

H
Haojun Liao 已提交
1565
  if (pInfo->timeWindowInterpo) {
1566
    int32_t rowIndex = ascScan ? (pSDataBlock->info.rows - 1) : 0;
H
Haojun Liao 已提交
1567
    saveDataBlockLastRow(pInfo->pRow, pSDataBlock->pDataBlock, rowIndex, pSDataBlock->info.numOfCols);
1568 1569
  }

1570
  return pUpdated;
L
Liu Jicong 已提交
1571
  //  updateResultRowInfoActiveIndex(pResultRowInfo, &pInfo->win, pRuntimeEnv->current->lastKey, true, false);
1572 1573
}

1574 1575 1576 1577
static void doKeepTuple(SWindowRowsSup* pRowSup, int64_t ts) {
  pRowSup->win.ekey  = ts;
  pRowSup->prevTs    = ts;
  pRowSup->numOfRows += 1;
1578 1579
}

1580 1581 1582 1583
static void doKeepNewWindowStartInfo(SWindowRowsSup* pRowSup, const int64_t* tsList, int32_t rowIndex) {
  pRowSup->startRowIndex = rowIndex;
  pRowSup->numOfRows     = 0;
  pRowSup->win.skey      = tsList[rowIndex];
1584 1585
}

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

1590
  // todo find the correct time stamp column slot
1591
  SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, 0);
1592

1593 1594 1595
  bool    masterScan = true;
  int32_t numOfOutput = pOperator->numOfOutput;
  int64_t gid = pBlock->info.groupId;
1596

H
Haojun Liao 已提交
1597
  int64_t gap = pInfo->gap;
1598

1599
  if (!pInfo->reptScan) {
1600
    pInfo->reptScan = true;
1601
    pInfo->winSup.prevTs = INT64_MIN;
1602 1603
  }

1604 1605 1606
  SWindowRowsSup* pRowSup = &pInfo->winSup;
  pRowSup->numOfRows = 0;

1607
  // In case of ascending or descending order scan data, only one time window needs to be kepted for each table.
1608
  TSKEY* tsList = (TSKEY*)pColInfoData->pData;
1609
  for (int32_t j = 0; j < pBlock->info.rows; ++j) {
1610 1611 1612 1613
    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) {
1614
      // The gap is less than the threshold, so it belongs to current session window that has been opened already.
1615 1616 1617
      doKeepTuple(pRowSup, tsList[j]);
      if (j == 0 && pRowSup->startRowIndex != 0) {
        pRowSup->startRowIndex = 0;
1618 1619 1620
      }
    } else {  // start a new session window
      SResultRow* pResult = NULL;
1621 1622

      // keep the time window for the closed time window.
1623
      STimeWindow window = pRowSup->win;
1624

1625
      pRowSup->win.ekey = pRowSup->win.skey;
L
Liu Jicong 已提交
1626
      int32_t ret = setResultOutputBufByKey_rv(&pInfo->binfo.resultRowInfo, pBlock->info.uid, &window, masterScan,
1627
                                               &pResult, gid, pInfo->binfo.pCtx, numOfOutput, pInfo->binfo.rowCellInfoOffset, &pInfo->aggSup, pTaskInfo);
1628
      if (ret != TSDB_CODE_SUCCESS) {  // null data, too many state code
1629
        longjmp(pTaskInfo->env, TSDB_CODE_QRY_APP_ERROR);
1630 1631
      }

1632
      // pInfo->numOfRows data belong to the current session window
1633 1634
      updateTimeWindowInfo(&pInfo->twAggSup.timeWindowData, &window, false);
      doApplyFunctions(pInfo->binfo.pCtx, &window, &pInfo->twAggSup.timeWindowData, pRowSup->startRowIndex, pRowSup->numOfRows, NULL, pBlock->info.rows, numOfOutput, TSDB_ORDER_ASC);
1635

1636
      // here we start a new session window
1637 1638
      doKeepNewWindowStartInfo(pRowSup, tsList, j);
      doKeepTuple(pRowSup, tsList[j]);
1639 1640 1641 1642
    }
  }

  SResultRow* pResult = NULL;
1643 1644
  pRowSup->win.ekey = tsList[pBlock->info.rows - 1];
  int32_t ret = setResultOutputBufByKey_rv(&pInfo->binfo.resultRowInfo, pBlock->info.uid, &pRowSup->win, masterScan, &pResult,
1645
                                           gid, pInfo->binfo.pCtx, numOfOutput, pInfo->binfo.rowCellInfoOffset, &pInfo->aggSup, pTaskInfo);
1646
  if (ret != TSDB_CODE_SUCCESS) {  // null data, too many state code
1647
    longjmp(pTaskInfo->env, TSDB_CODE_QRY_APP_ERROR);
1648 1649
  }

1650 1651
  updateTimeWindowInfo(&pInfo->twAggSup.timeWindowData, &pRowSup->win, false);
  doApplyFunctions(pInfo->binfo.pCtx, &pRowSup->win, &pInfo->twAggSup.timeWindowData, pRowSup->startRowIndex, pRowSup->numOfRows, NULL, pBlock->info.rows, numOfOutput, TSDB_ORDER_ASC);
1652 1653 1654 1655
}

static void setResultRowKey(SResultRow* pResultRow, char* pData, int16_t type) {
  if (IS_VAR_DATA_TYPE(type)) {
1656 1657 1658 1659 1660 1661 1662
    // todo disable this
//    if (pResultRow->key == NULL) {
//      pResultRow->key = taosMemoryMalloc(varDataTLen(pData));
//      varDataCopy(pResultRow->key, pData);
//    } else {
//      ASSERT(memcmp(pResultRow->key, pData, varDataTLen(pData)) == 0);
//    }
1663 1664 1665 1666 1667 1668 1669 1670 1671
  } else {
    int64_t v = -1;
    GET_TYPED_DATA(v, int64_t, type, pData);

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

1672 1673
int32_t setGroupResultOutputBuf(SOptrBasicInfo* binfo, int32_t numOfCols, char* pData, int16_t type, int16_t bytes,
                                int32_t groupId, SDiskbasedBuf* pBuf, SExecTaskInfo* pTaskInfo, SAggSupporter* pAggSup) {
L
Liu Jicong 已提交
1674 1675
  SResultRowInfo* pResultRowInfo = &binfo->resultRowInfo;
  SqlFunctionCtx* pCtx = binfo->pCtx;
1676

L
Liu Jicong 已提交
1677
  SResultRow* pResultRow = doSetResultOutBufByKey_rv(pBuf, pResultRowInfo, groupId, (char*)pData, bytes, true, groupId,
H
Haojun Liao 已提交
1678
                                                     pTaskInfo, false, pAggSup);
L
Liu Jicong 已提交
1679
  assert(pResultRow != NULL);
1680 1681

  setResultRowKey(pResultRow, pData, type);
H
Haojun Liao 已提交
1682
  setResultRowOutputBufInitCtx_rv(pResultRow, pCtx, numOfCols, binfo->rowCellInfoOffset);
1683 1684 1685
  return TSDB_CODE_SUCCESS;
}

L
Liu Jicong 已提交
1686 1687
static bool functionNeedToExecute(SqlFunctionCtx* pCtx) {
  struct SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
1688 1689 1690

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

1695
  if (isRowEntryCompleted(pResInfo)) {
1696 1697 1698 1699
    return false;
  }

  if (functionId == FUNCTION_FIRST_DST || functionId == FUNCTION_FIRST) {
L
Liu Jicong 已提交
1700
    //    return QUERY_IS_ASC_QUERY(pQueryAttr);
1701 1702 1703 1704
  }

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

  // in the reverse table scan, only the following functions need to be executed
L
Liu Jicong 已提交
1709 1710 1711 1712
  //  if (IS_REVERSE_SCAN(pRuntimeEnv) ||
  //      (pRuntimeEnv->scanFlag == REPEAT_SCAN && functionId != FUNCTION_STDDEV && functionId != FUNCTION_PERCT)) {
  //    return false;
  //  }
1713 1714 1715 1716

  return true;
}

1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777
static int32_t doCreateConstantValColumnAggInfo(SInputColumnInfoData* pInput, SFunctParam* pFuncParam, int32_t type, int32_t paramIndex, int32_t numOfRows) {
  if (pInput->pData[paramIndex] == NULL) {
    pInput->pData[paramIndex] = taosMemoryCalloc(1, sizeof(SColumnInfoData));
    if (pInput->pData[paramIndex] == NULL) {
      return TSDB_CODE_OUT_OF_MEMORY;
    }

    // Set the correct column info (data type and bytes)
    pInput->pData[paramIndex]->info.type  = type;
    pInput->pData[paramIndex]->info.bytes  = tDataTypes[type].bytes;
  }

  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;
    *da = (SColumnDataAgg) {.numOfNull = 0, .min = v, .max = v, .maxIndex = 0, .minIndex = 0, .sum = v * numOfRows};
  } else if (type == TSDB_DATA_TYPE_DOUBLE) {
    double v = pFuncParam->param.d;
    *da = (SColumnDataAgg) {.numOfNull = 0, .maxIndex = 0, .minIndex = 0};

    *(double*) &da->min = v;
    *(double*) &da->max = v;
    *(double*) &da->sum = v * numOfRows;
  } else if (type == TSDB_DATA_TYPE_BOOL) {  // todo validate this data type
    bool v = pFuncParam->param.i;

    *da = (SColumnDataAgg) {.numOfNull = 0, .maxIndex = 0, .minIndex = 0};
    *(bool*) &da->min = 0;
    *(bool*) &da->max = v;
    *(bool*) &da->sum = v * numOfRows;
  } else if (type == TSDB_DATA_TYPE_TIMESTAMP) {
    // do nothing
  } 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;

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

1781 1782 1783
      if (pFuncParam->type == FUNC_PARAM_TYPE_COLUMN) {
        int32_t slotId = pFuncParam->pCol->slotId;
        pInput->pColumnDataAgg[j] = &pBlock->pBlockAgg[slotId];
1784 1785 1786 1787

        // 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);
1788 1789
      } else if (pFuncParam->type == FUNC_PARAM_TYPE_VALUE) {
        doCreateConstantValColumnAggInfo(pInput, pFuncParam, pFuncParam->param.nType, j, pBlock->info.rows);
1790 1791
      }
    }
1792
  } else {
1793
    pInput->colDataAggIsSet = false;
1794 1795 1796
  }

  // set the statistics data for primary time stamp column
1797 1798 1799 1800 1801
  //  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;
  //  }
1802 1803 1804
}

// set the output buffer for the selectivity + tag query
L
Liu Jicong 已提交
1805
static int32_t setCtxTagColumnInfo(SqlFunctionCtx* pCtx, int32_t numOfOutput) {
1806 1807 1808 1809 1810 1811 1812
  if (!isSelectivityWithTagsQuery(pCtx, numOfOutput)) {
    return TSDB_CODE_SUCCESS;
  }

  int32_t num = 0;
  int16_t tagLen = 0;

H
Haojun Liao 已提交
1813
  SqlFunctionCtx*  p = NULL;
wafwerar's avatar
wafwerar 已提交
1814
  SqlFunctionCtx** pTagCtx = taosMemoryCalloc(numOfOutput, POINTER_BYTES);
1815 1816 1817 1818 1819 1820 1821 1822
  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 已提交
1823
      tagLen += pCtx[i].resDataInfo.bytes;
1824
      pTagCtx[num++] = &pCtx[i];
L
Liu Jicong 已提交
1825
    } else if (1 /*(aAggs[functionId].status & FUNCSTATE_SELECTIVITY) != 0*/) {
1826 1827 1828 1829 1830 1831 1832 1833 1834 1835
      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) {
1836 1837 1838
    p->subsidiaryRes.pCtx = pTagCtx;
    p->subsidiaryRes.numOfCols = num;
    p->subsidiaryRes.bufLen = tagLen;
1839
  } else {
wafwerar's avatar
wafwerar 已提交
1840
    taosMemoryFreeClear(pTagCtx);
1841 1842 1843 1844 1845
  }

  return TSDB_CODE_SUCCESS;
}

1846
SqlFunctionCtx* createSqlFunctionCtx(SExprInfo* pExprInfo, int32_t numOfOutput, int32_t** rowCellInfoOffset) {
L
Liu Jicong 已提交
1847
  SqlFunctionCtx* pFuncCtx = (SqlFunctionCtx*)taosMemoryCalloc(numOfOutput, sizeof(SqlFunctionCtx));
H
Haojun Liao 已提交
1848 1849 1850 1851
  if (pFuncCtx == NULL) {
    return NULL;
  }

wafwerar's avatar
wafwerar 已提交
1852
  *rowCellInfoOffset = taosMemoryCalloc(numOfOutput, sizeof(int32_t));
H
Haojun Liao 已提交
1853
  if (*rowCellInfoOffset == 0) {
wafwerar's avatar
wafwerar 已提交
1854
    taosMemoryFreeClear(pFuncCtx);
H
Haojun Liao 已提交
1855 1856 1857 1858
    return NULL;
  }

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

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

1864
    pCtx->functionId = -1;
H
Haojun Liao 已提交
1865
    if (pExpr->pExpr->nodeType == QUERY_NODE_FUNCTION) {
H
Haojun Liao 已提交
1866
      SFuncExecEnv env = {0};
H
Haojun Liao 已提交
1867 1868
      pCtx->functionId = pExpr->pExpr->_function.pFunctNode->funcId;

H
Haojun Liao 已提交
1869
      if (fmIsAggFunc(pCtx->functionId) || fmIsNonstandardSQLFunc(pCtx->functionId)) {
1870 1871 1872 1873
        fmGetFuncExecFuncs(pCtx->functionId, &pCtx->fpSet);
        pCtx->fpSet.getEnv(pExpr->pExpr->_function.pFunctNode, &env);
      } else {
        fmGetScalarFuncExecFuncs(pCtx->functionId, &pCtx->sfp);
1874 1875 1876
        if (pCtx->sfp.getEnv != NULL) {
          pCtx->sfp.getEnv(pExpr->pExpr->_function.pFunctNode, &env);
        }
1877
      }
H
Haojun Liao 已提交
1878
      pCtx->resDataInfo.interBufSize = env.calcMemSize;
D
dapan1121 已提交
1879
    } else if (pExpr->pExpr->nodeType == QUERY_NODE_COLUMN || pExpr->pExpr->nodeType == QUERY_NODE_OPERATOR || pExpr->pExpr->nodeType == QUERY_NODE_VALUE) {
H
Haojun Liao 已提交
1880
      pCtx->resDataInfo.interBufSize = pFunct->resSchema.bytes; // for simple column, the intermediate buffer needs to hold one element.
H
Haojun Liao 已提交
1881
    }
H
Haojun Liao 已提交
1882

H
Haojun Liao 已提交
1883
    pCtx->input.numOfInputCols = pFunct->numOfParams;
wafwerar's avatar
wafwerar 已提交
1884 1885
    pCtx->input.pData = taosMemoryCalloc(pFunct->numOfParams, POINTER_BYTES);
    pCtx->input.pColumnDataAgg = taosMemoryCalloc(pFunct->numOfParams, POINTER_BYTES);
H
Haojun Liao 已提交
1886

1887
    pCtx->pTsOutput         = NULL;
L
Liu Jicong 已提交
1888
    pCtx->resDataInfo.bytes = pFunct->resSchema.bytes;
H
Haojun Liao 已提交
1889 1890
    pCtx->resDataInfo.type  = pFunct->resSchema.type;
    pCtx->order             = TSDB_ORDER_ASC;
1891 1892
    pCtx->start.key         = INT64_MIN;
    pCtx->end.key           = INT64_MIN;
H
Haojun Liao 已提交
1893
#if 0
H
Haojun Liao 已提交
1894
    for (int32_t j = 0; j < pCtx->numOfParams; ++j) {
H
Haojun Liao 已提交
1895 1896
//      int16_t type = pFunct->param[j].nType;
//      int16_t bytes = pFunct->param[j].nLen;
H
Haojun Liao 已提交
1897

H
Haojun Liao 已提交
1898 1899 1900 1901 1902
//      if (type == TSDB_DATA_TYPE_BINARY || type == TSDB_DATA_TYPE_NCHAR) {
//        taosVariantCreateFromBinary(&pCtx->param[j], pFunct->param[j].pz, bytes, type);
//      } else {
//        taosVariantCreateFromBinary(&pCtx->param[j], (char *)&pFunct->param[j].i, bytes, type);
//      }
H
Haojun Liao 已提交
1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938
    }

    // 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_TS_COMP) {
//      pCtx->param[0].i = pQueryAttr->vgId;  //TODO this should be the parameter from client
      pCtx->param[0].nType = TSDB_DATA_TYPE_BIGINT;
    } 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 已提交
1939
#endif
H
Haojun Liao 已提交
1940 1941
  }

L
Liu Jicong 已提交
1942 1943 1944
  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 已提交
1945
  }
H
Haojun Liao 已提交
1946 1947 1948 1949 1950

  setCtxTagColumnInfo(pFuncCtx, numOfOutput);
  return pFuncCtx;
}

1951
static void* destroySqlFunctionCtx(SqlFunctionCtx* pCtx, int32_t numOfOutput) {
1952 1953 1954 1955 1956 1957 1958 1959 1960 1961
  if (pCtx == NULL) {
    return NULL;
  }

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

    taosVariantDestroy(&pCtx[i].tag);
wafwerar's avatar
wafwerar 已提交
1962
    taosMemoryFreeClear(pCtx[i].subsidiaryRes.pCtx);
1963 1964
  }

wafwerar's avatar
wafwerar 已提交
1965
  taosMemoryFreeClear(pCtx);
1966 1967 1968
  return NULL;
}

L
Liu Jicong 已提交
1969
bool isTaskKilled(SExecTaskInfo* pTaskInfo) {
1970 1971
  // query has been executed more than tsShellActivityTimer, and the retrieve has not arrived
  // abort current query execution.
L
Liu Jicong 已提交
1972 1973
  if (pTaskInfo->owner != 0 &&
      ((taosGetTimestampSec() - pTaskInfo->cost.start / 1000) > 10 * getMaximumIdleDurationSec())
1974 1975
      /*(!needBuildResAfterQueryComplete(pTaskInfo))*/) {
    assert(pTaskInfo->cost.start != 0);
L
Liu Jicong 已提交
1976 1977 1978
    //    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;
1979 1980 1981 1982 1983
  }

  return false;
}

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

L
Liu Jicong 已提交
1986
static bool isCachedLastQuery(STaskAttr* pQueryAttr) {
1987 1988 1989 1990 1991 1992 1993 1994 1995
  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;
  }

1996 1997
  int32_t order = TSDB_ORDER_ASC;
  if (order != TSDB_ORDER_DESC || !TSWINDOW_IS_EQUAL(pQueryAttr->window, TSWINDOW_DESC_INITIALIZER)) {
1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016
    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 已提交
2017 2018 2019
// todo refactor : return window
void getAlignQueryTimeWindow(SInterval* pInterval, int32_t precision, int64_t key, int64_t keyFirst, int64_t keyLast,
                             STimeWindow* win) {
2020
  ASSERT(key >= keyFirst && key <= keyLast);
H
Haojun Liao 已提交
2021
  win->skey = taosTimeTruncate(key, pInterval, precision);
2022 2023

  /*
H
Haojun Liao 已提交
2024
   * if the realSkey > INT64_MAX - pInterval->interval, the query duration between
2025 2026
   * realSkey and realEkey must be less than one interval.Therefore, no need to adjust the query ranges.
   */
H
Haojun Liao 已提交
2027 2028
  if (keyFirst > (INT64_MAX - pInterval->interval)) {
    assert(keyLast - keyFirst < pInterval->interval);
2029 2030
    win->ekey = INT64_MAX;
  } else {
2031
    win->ekey = taosTimeAdd(win->skey, pInterval->interval, pInterval->intervalUnit, precision) - 1;
2032 2033 2034
  }
}

L
Liu Jicong 已提交
2035
static int32_t updateBlockLoadStatus(STaskAttr* pQuery, int32_t status) {
2036 2037 2038
  bool hasFirstLastFunc = false;
  bool hasOtherFunc = false;

2039
  if (status == BLK_DATA_DATA_LOAD || status == BLK_DATA_FILTEROUT) {
2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057
    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;
    }
  }

2058
  if (hasFirstLastFunc && status == BLK_DATA_NOT_LOAD) {
L
Liu Jicong 已提交
2059
    if (!hasOtherFunc) {
2060
      return BLK_DATA_FILTEROUT;
2061
    } else {
2062
      return BLK_DATA_DATA_LOAD;
2063 2064 2065 2066 2067 2068
    }
  }

  return status;
}

H
Haojun Liao 已提交
2069
static void doUpdateLastKey(STaskAttr* pQueryAttr) {
2070 2071 2072
  STimeWindow* win = &pQueryAttr->window;

  size_t num = taosArrayGetSize(pQueryAttr->tableGroupInfo.pGroupList);
L
Liu Jicong 已提交
2073
  for (int32_t i = 0; i < num; ++i) {
2074 2075 2076
    SArray* p1 = taosArrayGetP(pQueryAttr->tableGroupInfo.pGroupList, i);

    size_t len = taosArrayGetSize(p1);
L
Liu Jicong 已提交
2077 2078 2079 2080 2081 2082 2083
    for (int32_t j = 0; j < len; ++j) {
      //      STableKeyInfo* pInfo = taosArrayGet(p1, j);
      //
      //      // update the new lastkey if it is equalled to the value of the old skey
      //      if (pInfo->lastKey == win->ekey) {
      //        pInfo->lastKey = win->skey;
      //      }
2084 2085 2086 2087
    }
  }
}

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

H
Haojun Liao 已提交
2189 2190
static void getIntermediateBufInfo(STaskRuntimeEnv* pRuntimeEnv, int32_t* ps, int32_t* rowsize) {
  STaskAttr* pQueryAttr = pRuntimeEnv->pQueryAttr;
L
Liu Jicong 已提交
2191
  int32_t    MIN_ROWS_PER_PAGE = 4;
2192

L
Liu Jicong 已提交
2193 2194
  *rowsize = (int32_t)(pQueryAttr->resultRowSize *
                       getRowNumForMultioutput(pQueryAttr, pQueryAttr->topBotQuery, pQueryAttr->stableQuery));
2195 2196 2197 2198
  int32_t overhead = sizeof(SFilePage);

  // one page contains at least two rows
  *ps = DEFAULT_INTERN_BUF_PAGE_SIZE;
L
Liu Jicong 已提交
2199
  while (((*rowsize) * MIN_ROWS_PER_PAGE) > (*ps) - overhead) {
2200 2201 2202 2203 2204 2205
    *ps = ((*ps) << 1u);
  }
}

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

L
Liu Jicong 已提交
2206 2207 2208
// static FORCE_INLINE bool doFilterByBlockStatistics(STaskRuntimeEnv* pRuntimeEnv, SDataStatis *pDataStatis,
// SqlFunctionCtx *pCtx, int32_t numOfRows) {
//   STaskAttr* pQueryAttr = pRuntimeEnv->pQueryAttr;
2209
//
L
Liu Jicong 已提交
2210 2211 2212
//   if (pDataStatis == NULL || pQueryAttr->pFilters == NULL) {
//     return true;
//   }
2213
//
L
Liu Jicong 已提交
2214 2215
//   return filterRangeExecute(pQueryAttr->pFilters, pDataStatis, pQueryAttr->numOfCols, numOfRows);
// }
2216

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

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

2223
  if (true) {
L
Liu Jicong 已提交
2224
    //    getAlignQueryTimeWindow(pQueryAttr, pBlockInfo->window.skey, sk, ek, &w);
2225 2226 2227 2228 2229 2230
    assert(w.ekey >= pBlockInfo->window.skey);

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

L
Liu Jicong 已提交
2231 2232
    while (1) {
      //      getNextTimeWindow(pQueryAttr, &w);
2233 2234 2235 2236 2237 2238 2239 2240 2241 2242
      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 已提交
2243
    //    getAlignQueryTimeWindow(pQueryAttr, pBlockInfo->window.ekey, sk, ek, &w);
2244 2245 2246 2247 2248 2249
    assert(w.skey <= pBlockInfo->window.ekey);

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

L
Liu Jicong 已提交
2250 2251
    while (1) {
      //      getNextTimeWindow(pQueryAttr, &w);
2252 2253 2254 2255 2256 2257 2258 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
      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 已提交
2316
static void         doSetTagValueInParam(void* pTable, int32_t tagColId, SVariant* tag, int16_t type, int16_t bytes);
2317 2318

static uint32_t doFilterByBlockTimeWindow(STableScanInfo* pTableScanInfo, SSDataBlock* pBlock) {
H
Haojun Liao 已提交
2319
  SqlFunctionCtx* pCtx = pTableScanInfo->pCtx;
2320
  uint32_t        status = BLK_DATA_NOT_LOAD;
2321 2322 2323 2324

  int32_t numOfOutput = pTableScanInfo->numOfOutput;
  for (int32_t i = 0; i < numOfOutput; ++i) {
    int32_t functionId = pCtx[i].functionId;
H
Haojun Liao 已提交
2325
    int32_t colId = pTableScanInfo->pExpr[i].base.pParam[0].pCol->colId;
2326 2327 2328

    // group by + first/last should not apply the first/last block filter
    if (functionId < 0) {
2329
      status |= BLK_DATA_DATA_LOAD;
2330 2331
      return status;
    } else {
L
Liu Jicong 已提交
2332
      //      status |= aAggs[functionId].dataReqFunc(&pTableScanInfo->pCtx[i], &pBlock->info.window, colId);
2333
      //      if ((status & BLK_DATA_DATA_LOAD) == BLK_DATA_DATA_LOAD) {
L
Liu Jicong 已提交
2334 2335
      //        return status;
      //      }
2336 2337 2338 2339 2340 2341
    }
  }

  return status;
}

L
Liu Jicong 已提交
2342 2343
int32_t loadDataBlockOnDemand(SExecTaskInfo* pTaskInfo, STableScanInfo* pTableScanInfo, SSDataBlock* pBlock,
                              uint32_t* status) {
2344
  *status = BLK_DATA_NOT_LOAD;
2345

H
Haojun Liao 已提交
2346
  pBlock->pDataBlock = NULL;
L
Liu Jicong 已提交
2347
  pBlock->pBlockAgg = NULL;
H
Haojun Liao 已提交
2348

L
Liu Jicong 已提交
2349 2350
  //  int64_t groupId = pRuntimeEnv->current->groupIndex;
  //  bool    ascQuery = QUERY_IS_ASC_QUERY(pQueryAttr);
2351

H
Haojun Liao 已提交
2352
  STaskCostInfo* pCost = &pTaskInfo->cost;
2353 2354 2355

  pCost->totalBlocks += 1;
  pCost->totalRows += pBlock->info.rows;
H
Haojun Liao 已提交
2356
#if 0
2357 2358 2359
  // 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 已提交
2360
      (QUERY_IS_INTERVAL_QUERY(pQueryAttr) && overlapWithTimeWindow(pTaskInfo, &pBlock->info))) {
2361
    (*status) = BLK_DATA_DATA_LOAD;
2362 2363 2364
  }

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

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

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

    if (pBlock->pBlockAgg == NULL) {  // data block statistics does not exist, load data block
2414
//      pBlock->pDataBlock = tsdbRetrieveDataBlock(pTableScanInfo->pTsdbReadHandle, NULL);
2415 2416 2417
      pCost->totalCheckedRows += pBlock->info.rows;
    }
  } else {
2418
    assert((*status) == BLK_DATA_DATA_LOAD);
2419 2420 2421

    // load the data block statistics to perform further filter
    pCost->loadBlockStatis += 1;
2422
//    tsdbRetrieveDataBlockStatisInfo(pTableScanInfo->pTsdbReadHandle, &pBlock->pBlockAgg);
2423 2424 2425 2426 2427 2428

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

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

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

    pCost->totalCheckedRows += pBlockInfo->rows;
    pCost->loadBlocks += 1;
2468
//    pBlock->pDataBlock = tsdbRetrieveDataBlock(pTableScanInfo->pTsdbReadHandle, NULL);
2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480
//    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 已提交
2481
#endif
2482 2483 2484
  return TSDB_CODE_SUCCESS;
}

L
Liu Jicong 已提交
2485
int32_t binarySearchForKey(char* pValue, int num, TSKEY key, int order) {
2486 2487 2488 2489 2490 2491 2492 2493 2494
  int32_t midPos = -1;
  int32_t numOfRows;

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

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

L
Liu Jicong 已提交
2495
  TSKEY*  keyList = (TSKEY*)pValue;
2496 2497 2498 2499 2500 2501 2502 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
  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 已提交
2549
 * set tag value in SqlFunctionCtx
2550 2551
 * e.g.,tag information into input buffer
 */
L
Liu Jicong 已提交
2552
static void doSetTagValueInParam(void* pTable, int32_t tagColId, SVariant* tag, int16_t type, int16_t bytes) {
2553 2554 2555
  taosVariantDestroy(tag);

  char* val = NULL;
L
Liu Jicong 已提交
2556 2557 2558 2559 2560 2561
  //  if (tagColId == TSDB_TBNAME_COLUMN_INDEX) {
  //    val = tsdbGetTableName(pTable);
  //    assert(val != NULL);
  //  } else {
  //    val = tsdbGetTableTagVal(pTable, tagColId, type, bytes);
  //  }
2562 2563 2564 2565 2566 2567 2568 2569

  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 已提交
2570
    int32_t len = (varDataLen(val) > maxLen) ? maxLen : varDataLen(val);
2571
    taosVariantCreateFromBinary(tag, varDataVal(val), len, type);
L
Liu Jicong 已提交
2572
    // taosVariantCreateFromBinary(tag, varDataVal(val), varDataLen(val), type);
2573 2574 2575 2576 2577 2578 2579 2580
  } 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 已提交
2581
  for (int32_t i = 0; i < numOfTags; ++i) {
2582 2583 2584 2585 2586 2587 2588 2589
    if (pTagColList[i].colId == colId) {
      return &pTagColList[i];
    }
  }

  return NULL;
}

L
Liu Jicong 已提交
2590 2591
void setTagValue(SOperatorInfo* pOperatorInfo, void* pTable, SqlFunctionCtx* pCtx, int32_t numOfOutput) {
  SExprInfo* pExpr = pOperatorInfo->pExpr;
2592
  SExprInfo* pExprInfo = &pExpr[0];
L
Liu Jicong 已提交
2593
  int32_t    functionId = getExprFunctionId(pExprInfo);
2594
#if 0
2595 2596 2597
  if (pQueryAttr->numOfOutput == 1 && functionId == FUNCTION_TS_COMP && pQueryAttr->stableQuery) {
    assert(pExprInfo->base.numOfParams == 1);

L
Liu Jicong 已提交
2598
    //    int16_t      tagColId = (int16_t)pExprInfo->base.param[0].i;
H
Haojun Liao 已提交
2599
    int16_t      tagColId = -1;
2600 2601 2602
    SColumnInfo* pColInfo = doGetTagColumnInfoById(pQueryAttr->tagColList, pQueryAttr->numOfTags, tagColId);

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

2604 2605 2606 2607 2608 2609 2610 2611 2612
  } 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 已提交
2613
      if (!TSDB_COL_IS_TAG(pLocalExprInfo->base.pParam[0].pCol->flag)) {
2614 2615 2616 2617
        continue;
      }

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

L
Liu Jicong 已提交
2621 2622 2623
      if (IS_NUMERIC_TYPE(pLocalExprInfo->base.resSchema.type) ||
          pLocalExprInfo->base.resSchema.type == TSDB_DATA_TYPE_BOOL ||
          pLocalExprInfo->base.resSchema.type == TSDB_DATA_TYPE_TIMESTAMP) {
2624 2625 2626 2627
        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 已提交
2628
        }
2629 2630 2631 2632 2633 2634 2635 2636 2637 2638
      }

      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);
  }
2639 2640
#endif

2641 2642
}

H
Haojun Liao 已提交
2643
void copyToSDataBlock(SSDataBlock* pBlock, int32_t* offset, SGroupResInfo* pGroupResInfo, SDiskbasedBuf* pResBuf) {
2644 2645 2646 2647 2648 2649 2650
  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 已提交
2651 2652 2653
      //      if ((code = mergeIntoGroupResult(&pGroupResInfo, pRuntimeEnv, offset)) != TSDB_CODE_SUCCESS) {
      return;
      //      }
2654 2655
    }

L
Liu Jicong 已提交
2656
    //    doCopyToSDataBlock(pResBuf, pGroupResInfo, TSDB_ORDER_ASC, pBlock, );
2657 2658 2659 2660 2661 2662 2663 2664 2665 2666

    // 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 已提交
2667 2668 2669
    //    if (pBlock->info.rows >= threshold) {
    //      break;
    //    }
2670 2671 2672
  }
}

L
Liu Jicong 已提交
2673
static void updateTableQueryInfoForReverseScan(STableQueryInfo* pTableQueryInfo) {
2674 2675 2676 2677
  if (pTableQueryInfo == NULL) {
    return;
  }

L
Liu Jicong 已提交
2678 2679
  //  TSWAP(pTableQueryInfo->win.skey, pTableQueryInfo->win.ekey, TSKEY);
  //  pTableQueryInfo->lastKey = pTableQueryInfo->win.skey;
2680

L
Liu Jicong 已提交
2681 2682
  //  SWITCH_ORDER(pTableQueryInfo->cur.order);
  //  pTableQueryInfo->cur.vgroupIndex = -1;
2683 2684

  // set the index to be the end slot of result rows array
2685 2686 2687 2688 2689 2690
//  SResultRowInfo* pResultRowInfo = &pTableQueryInfo->resInfo;
//  if (pResultRowInfo->size > 0) {
//    pResultRowInfo->curPos = pResultRowInfo->size - 1;
//  } else {
//    pResultRowInfo->curPos = -1;
//  }
2691 2692
}

H
Haojun Liao 已提交
2693
void initResultRow(SResultRow* pResultRow) {
2694 2695 2696 2697 2698 2699
  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 已提交
2700 2701 2702
 * +------------+-----------------result column 1------------+------------------result column 2-----------+
 * | SResultRow | SResultRowEntryInfo | intermediate buffer1 | SResultRowEntryInfo | intermediate buffer 2|
 * +------------+--------------------------------------------+--------------------------------------------+
2703 2704
 *           offset[0]                                  offset[1]                                   offset[2]
 */
2705
// TODO refactor: some function move away
H
Haojun Liao 已提交
2706
void setFunctionResultOutput(SOptrBasicInfo* pInfo, SAggSupporter* pSup, int32_t stage, SExecTaskInfo* pTaskInfo) {
L
Liu Jicong 已提交
2707 2708 2709
  SqlFunctionCtx* pCtx = pInfo->pCtx;
  SSDataBlock*    pDataBlock = pInfo->pRes;
  int32_t*        rowCellInfoOffset = pInfo->rowCellInfoOffset;
H
Haojun Liao 已提交
2710

H
Haojun Liao 已提交
2711
  SResultRowInfo* pResultRowInfo = &pInfo->resultRowInfo;
H
Haojun Liao 已提交
2712
  initResultRowInfo(pResultRowInfo, 16);
H
Haojun Liao 已提交
2713

L
Liu Jicong 已提交
2714 2715 2716 2717
  int64_t     tid = 0;
  int64_t     groupId = 0;
  SResultRow* pRow = doSetResultOutBufByKey_rv(pSup->pResultBuf, pResultRowInfo, tid, (char*)&tid, sizeof(tid), true,
                                               groupId, pTaskInfo, false, pSup);
H
Haojun Liao 已提交
2718 2719 2720 2721 2722

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

L
Liu Jicong 已提交
2723
    pCtx[i].resultInfo = pEntry;
H
Haojun Liao 已提交
2724 2725 2726
    pCtx[i].currentStage = stage;

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

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

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

L
Liu Jicong 已提交
2739
  int32_t newSize = pDataBlock->info.rows + numOfInputRows + 5;  // extra output buffer
2740
  if ((*bufCapacity) < newSize) {
L
Liu Jicong 已提交
2741 2742
    for (int32_t i = 0; i < pDataBlock->info.numOfCols; ++i) {
      SColumnInfoData* pColInfo = taosArrayGet(pDataBlock->pDataBlock, i);
2743

wafwerar's avatar
wafwerar 已提交
2744
      char* p = taosMemoryRealloc(pColInfo->pData, newSize * pColInfo->info.bytes);
2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757
      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 已提交
2758
    SColumnInfoData* pColInfo = taosArrayGet(pDataBlock->pDataBlock, i);
2759 2760 2761 2762 2763
    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 已提交
2764 2765
    if (functionId == FUNCTION_TOP || functionId == FUNCTION_BOTTOM || functionId == FUNCTION_DIFF ||
        functionId == FUNCTION_DERIVATIVE) {
H
Haojun Liao 已提交
2766
//      if (i > 0) pBInfo->pCtx[i].pTsOutput = pBInfo->pCtx[i - 1].pOutput;
2767 2768 2769 2770
    }
  }
}

H
Haojun Liao 已提交
2771
void copyTsColoum(SSDataBlock* pRes, SqlFunctionCtx* pCtx, int32_t numOfOutput) {
2772 2773
  bool    needCopyTs = false;
  int32_t tsNum = 0;
L
Liu Jicong 已提交
2774
  char*   src = NULL;
2775 2776 2777 2778
  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 已提交
2779 2780
      if (i > 0 && pCtx[i - 1].functionId == FUNCTION_TS_DUMMY) {
        SColumnInfoData* pColRes = taosArrayGet(pRes->pDataBlock, i - 1);  // find ts data
2781 2782
        src = pColRes->pData;
      }
L
Liu Jicong 已提交
2783
    } else if (functionId == FUNCTION_TS_DUMMY) {
2784 2785 2786 2787 2788 2789 2790 2791 2792 2793
      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 已提交
2794
    if (functionId == FUNCTION_TS_DUMMY) {
2795 2796 2797 2798 2799 2800
      SColumnInfoData* pColRes = taosArrayGet(pRes->pDataBlock, i);
      memcpy(pColRes->pData, src, pColRes->info.bytes * pRes->info.rows);
    }
  }
}

H
Haojun Liao 已提交
2801
void initCtxOutputBuffer(SqlFunctionCtx* pCtx, int32_t size) {
2802 2803
  for (int32_t j = 0; j < size; ++j) {
    struct SResultRowEntryInfo* pResInfo = GET_RES_INFO(&pCtx[j]);
H
Haojun Liao 已提交
2804
    if (isRowEntryInitialized(pResInfo) || fmIsPseudoColumnFunc(pCtx[j].functionId) || pCtx[j].functionId == -1 || fmIsScalarFunc(pCtx[j].functionId)) {
2805 2806 2807
      continue;
    }

H
Haojun Liao 已提交
2808
    pCtx[j].fpSet.init(&pCtx[j], pCtx[j].resultInfo);
2809 2810 2811
  }
}

L
Liu Jicong 已提交
2812
void setTaskStatus(SExecTaskInfo* pTaskInfo, int8_t status) {
2813
  if (status == TASK_NOT_COMPLETED) {
H
Haojun Liao 已提交
2814
    pTaskInfo->status = status;
2815 2816
  } else {
    // QUERY_NOT_COMPLETED is not compatible with any other status, so clear its position first
2817
    CLEAR_QUERY_STATUS(pTaskInfo, TASK_NOT_COMPLETED);
H
Haojun Liao 已提交
2818
    pTaskInfo->status |= status;
2819 2820 2821
  }
}

2822 2823
void finalizeQueryResult(SqlFunctionCtx* pCtx, int32_t numOfOutput) {
  for (int32_t j = 0; j < numOfOutput; ++j) {
H
Haojun Liao 已提交
2824 2825 2826 2827
    if (pCtx[j].functionId == -1) {
      continue;
    }

2828 2829 2830 2831
    pCtx[j].fpSet.finalize(&pCtx[j]);
  }
}

L
Liu Jicong 已提交
2832 2833
void finalizeMultiTupleQueryResult(SqlFunctionCtx* pCtx, int32_t numOfOutput, SDiskbasedBuf* pBuf,
                                   SResultRowInfo* pResultRowInfo, int32_t* rowCellInfoOffset) {
2834 2835 2836
  for (int32_t i = 0; i < pResultRowInfo->size; ++i) {
    SResultRowPosition* pPos = &pResultRowInfo->pPosition[i];

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

    // TODO ignore the close status anyway.
//    if (!isResultRowClosed(pRow)) {
//      continue;
//    }
2844

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

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

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

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

    releaseBufPage(pBuf, bufPage);
  }
2864 2865
}

2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885
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) {
    SResultRowPosition* pPos = taosArrayGet(pUpdateList, i);

    SFilePage*  bufPage = getBufPage(pBuf, pPos->pageId);
    SResultRow* pRow = (SResultRow*)((char*)bufPage + pPos->offset);

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

      struct SResultRowEntryInfo* pResInfo = pCtx[j].resultInfo;
      if (isRowEntryCompleted(pResInfo) && isRowEntryInitialized(pResInfo)) {
        continue;
      }

      if (pCtx[j].fpSet.process) {  // TODO set the dummy function.
        pCtx[j].fpSet.finalize(&pCtx[j]);
2886
        pResInfo->initialized = true;
2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902
      }

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

    releaseBufPage(pBuf, bufPage);
    /*
     * set the number of output results for group by normal columns, the number of output rows usually is 1 except
     * the top and bottom query
     */
    //    buf->numOfRows = (uint16_t)getNumOfResult(pCtx, numOfOutput);
  }
}

L
Liu Jicong 已提交
2903 2904
STableQueryInfo* createTableQueryInfo(void* buf, bool groupbyColumn, STimeWindow win) {
  STableQueryInfo* pTableQueryInfo = buf;
2905 2906 2907
  pTableQueryInfo->lastKey = win.skey;

  // set more initial size of interval/groupby query
L
Liu Jicong 已提交
2908 2909
  //  if (/*QUERY_IS_INTERVAL_QUERY(pQueryAttr) || */groupbyColumn) {
  int32_t initialSize = 128;
2910 2911 2912 2913
//  int32_t code = initResultRowInfo(&pTableQueryInfo->resInfo, initialSize);
//  if (code != TSDB_CODE_SUCCESS) {
//    return NULL;
//  }
L
Liu Jicong 已提交
2914 2915
  //  } else { // in other aggregate query, do not initialize the windowResInfo
  //  }
2916 2917 2918 2919

  return pTableQueryInfo;
}

L
Liu Jicong 已提交
2920
void destroyTableQueryInfoImpl(STableQueryInfo* pTableQueryInfo) {
2921 2922 2923 2924
  if (pTableQueryInfo == NULL) {
    return;
  }

L
Liu Jicong 已提交
2925
  //  taosVariantDestroy(&pTableQueryInfo->tag);
2926
//  cleanupResultRowInfo(&pTableQueryInfo->resInfo);
2927 2928
}

H
Haojun Liao 已提交
2929
void setResultRowOutputBufInitCtx_rv(SResultRow* pResult, SqlFunctionCtx* pCtx, int32_t numOfOutput, int32_t* rowCellInfoOffset) {
2930 2931 2932 2933 2934 2935 2936
  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;
    }
2937 2938 2939 2940 2941

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

2942 2943 2944 2945 2946 2947
    if (!pResInfo->initialized) {
      if (pCtx[i].functionId != -1) {
        pCtx[i].fpSet.init(&pCtx[i], pResInfo);
      } else {
        pResInfo->initialized = true;
      }
2948 2949 2950 2951
    }
  }
}

2952 2953 2954 2955 2956 2957
void doFilter(const SNode* pFilterNode, SSDataBlock* pBlock) {
  if (pFilterNode == NULL) {
    return;
  }

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

H
Haojun Liao 已提交
2959
  // todo move to the initialization function
H
Haojun Liao 已提交
2960
  int32_t code = filterInitFromNode((SNode*)pFilterNode, &filter, 0);
2961 2962 2963 2964 2965 2966

  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 已提交
2967
  filterFreeInfo(filter);
2968

2969
  SSDataBlock* px = createOneDataBlock(pBlock, false);
2970 2971
  blockDataEnsureCapacity(px, pBlock->info.rows);

H
Haojun Liao 已提交
2972
  // todo extract method
2973 2974 2975 2976
  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 已提交
2977 2978 2979 2980 2981 2982 2983 2984 2985
    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;
        }
2986

D
dapan1121 已提交
2987 2988 2989 2990 2991 2992
        if (colDataIsNull_s(pSrc, j)) {
          colDataAppendNULL(pDst, numOfRow);
        } else {
          colDataAppend(pDst, numOfRow, colDataGetData(pSrc, j), false);
        }
        numOfRow += 1;
H
Haojun Liao 已提交
2993
      }
D
dapan1121 已提交
2994 2995
    } else {
      numOfRow = 0;
2996 2997 2998 2999 3000 3001
    }

    *pSrc = *pDst;
  }

  pBlock->info.rows = numOfRow;
3002
  blockDataUpdateTsWindow(pBlock);
3003 3004
}

H
Haojun Liao 已提交
3005
void doSetTableGroupOutputBuf(SAggOperatorInfo* pAggInfo, int32_t numOfOutput, uint64_t groupId, SExecTaskInfo* pTaskInfo) {
3006 3007 3008
  // for simple group by query without interval, all the tables belong to one group result.
  int64_t uid = 0;

3009 3010
  SResultRowInfo* pResultRowInfo = &pAggInfo->binfo.resultRowInfo;
  SqlFunctionCtx* pCtx = pAggInfo->binfo.pCtx;
L
Liu Jicong 已提交
3011
  int32_t*        rowCellInfoOffset = pAggInfo->binfo.rowCellInfoOffset;
3012

3013
  SResultRow* pResultRow =
H
Haojun Liao 已提交
3014 3015
      doSetResultOutBufByKey_rv(pAggInfo->aggSup.pResultBuf, pResultRowInfo, uid, (char*)&groupId, sizeof(groupId),
                                true, groupId, pTaskInfo, false, &pAggInfo->aggSup);
L
Liu Jicong 已提交
3016
  assert(pResultRow != NULL);
3017 3018 3019 3020 3021 3022

  /*
   * 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) {
H
Haojun Liao 已提交
3023
    int32_t ret = addNewWindowResultBuf(pResultRow, pAggInfo->aggSup.pResultBuf, groupId, pAggInfo->binfo.pRes->info.rowSize);
3024 3025 3026 3027 3028
    if (ret != TSDB_CODE_SUCCESS) {
      return;
    }
  }

H
Haojun Liao 已提交
3029
  setResultRowOutputBufInitCtx_rv(pResultRow, pCtx, numOfOutput, rowCellInfoOffset);
3030 3031
}

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

H
Haojun Liao 已提交
3037
  doSetTableGroupOutputBuf(pAggInfo, numOfOutput, groupId, pTaskInfo);
3038 3039

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

H
Haojun Liao 已提交
3043
void setCtxTagForJoin(STaskRuntimeEnv* pRuntimeEnv, SqlFunctionCtx* pCtx, SExprInfo* pExprInfo, void* pTable) {
H
Haojun Liao 已提交
3044
  STaskAttr* pQueryAttr = pRuntimeEnv->pQueryAttr;
3045

H
Haojun Liao 已提交
3046
  SExprBasicInfo* pExpr = &pExprInfo->base;
L
Liu Jicong 已提交
3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069
  //  if (pQueryAttr->stableQuery && (pRuntimeEnv->pTsBuf != NULL) &&
  //      (pExpr->functionId == FUNCTION_TS || pExpr->functionId == FUNCTION_PRJ) &&
  //      (pExpr->colInfo.colIndex == PRIMARYKEY_TIMESTAMP_COL_ID)) {
  //    assert(pExpr->numOfParams == 1);
  //
  //    int16_t      tagColId = (int16_t)pExprInfo->base.param[0].i;
  //    SColumnInfo* pColInfo = doGetTagColumnInfoById(pQueryAttr->tagColList, pQueryAttr->numOfTags, tagColId);
  //
  //    doSetTagValueInParam(pTable, tagColId, &pCtx->tag, pColInfo->type, pColInfo->bytes);
  //
  //    int16_t tagType = pCtx[0].tag.nType;
  //    if (tagType == TSDB_DATA_TYPE_BINARY || tagType == TSDB_DATA_TYPE_NCHAR) {
  //      //qDebug("QInfo:0x%"PRIx64" set tag value for join comparison, colId:%" PRId64 ", val:%s",
  //      GET_TASKID(pRuntimeEnv),
  ////             pExprInfo->base.param[0].i, pCtx[0].tag.pz);
  //    } else {
  //      //qDebug("QInfo:0x%"PRIx64" set tag value for join comparison, colId:%" PRId64 ", val:%" PRId64,
  //      GET_TASKID(pRuntimeEnv),
  ////             pExprInfo->base.param[0].i, pCtx[0].tag.i);
  //    }
  //  }
}

3070 3071 3072
/*
 * There are two cases to handle:
 *
L
Liu Jicong 已提交
3073 3074
 * 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.
3075 3076 3077 3078
 * 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.
 */
3079
void setIntervalQueryRange(STableQueryInfo* pTableQueryInfo, TSKEY key, STimeWindow* pQRange) {
3080 3081 3082 3083
//  SResultRowInfo*  pResultRowInfo = &pTableQueryInfo->resInfo;
//  if (pResultRowInfo->curPos != -1) {
//    return;
//  }
3084

3085
//  pTableQueryInfo->win.skey = key;
3086
//  STimeWindow win = {.skey = key, .ekey = pQRange->ekey};
3087 3088 3089 3090 3091 3092 3093

  /**
   * 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.
   */
3094 3095 3096 3097
//  STimeWindow w = TSWINDOW_INITIALIZER;
//
//  TSKEY sk = TMIN(win.skey, win.ekey);
//  TSKEY ek = TMAX(win.skey, win.ekey);
L
Liu Jicong 已提交
3098
  //  getAlignQueryTimeWindow(pQueryAttr, win.skey, sk, ek, &w);
3099

L
Liu Jicong 已提交
3100 3101 3102 3103 3104 3105 3106
  //  if (pResultRowInfo->prevSKey == TSKEY_INITIAL_VAL) {
  //    if (!QUERY_IS_ASC_QUERY(pQueryAttr)) {
  //      assert(win.ekey == pQueryAttr->window.ekey);
  //    }
  //
  //    pResultRowInfo->prevSKey = w.skey;
  //  }
3107

L
Liu Jicong 已提交
3108
  //  pTableQueryInfo->lastKey = pTableQueryInfo->win.skey;
3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119
}

/**
 * copyToOutputBuf support copy data in ascending/descending order
 * 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
 */
3120
int32_t doCopyToSDataBlock(SSDataBlock* pBlock, int32_t rowCapacity, SExprInfo* pExprInfo, SDiskbasedBuf* pBuf, SGroupResInfo* pGroupResInfo, int32_t orderType, int32_t* rowCellOffset) {
3121
  int32_t numOfRows = getNumOfTotalRes(pGroupResInfo);
L
Liu Jicong 已提交
3122
  int32_t numOfResult = pBlock->info.rows;  // there are already exists result rows
3123 3124 3125 3126

  int32_t start = 0;
  int32_t step = -1;

L
Liu Jicong 已提交
3127
  // qDebug("QInfo:0x%"PRIx64" start to copy data from windowResInfo to output buf", GET_TASKID(pRuntimeEnv));
3128 3129 3130 3131 3132 3133 3134 3135 3136 3137
  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;
  }

3138 3139
  int32_t nrows = pBlock->info.rows;

3140
  for (int32_t i = start; (i < numOfRows) && (i >= 0); i += step) {
3141
    SResultRowPosition* pPos = taosArrayGet(pGroupResInfo->pRows, i);
L
Liu Jicong 已提交
3142
    SFilePage*          page = getBufPage(pBuf, pPos->pageId);
3143 3144

    SResultRow* pRow = (SResultRow*)((char*)page + pPos->offset);
3145 3146 3147 3148 3149
    if (pRow->numOfRows == 0) {
      pGroupResInfo->index += 1;
      continue;
    }

3150
    // TODO copy multiple rows?
3151
    int32_t numOfRowsToCopy = pRow->numOfRows;
L
Liu Jicong 已提交
3152
    if (numOfResult + numOfRowsToCopy >= rowCapacity) {
3153 3154 3155 3156 3157 3158
      break;
    }

    pGroupResInfo->index += 1;

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

      SColumnInfoData*     pColInfoData = taosArrayGet(pBlock->pDataBlock, slotId);
3162
      SResultRowEntryInfo* pEntryInfo = getResultCell(pRow, j, rowCellOffset);
3163

3164
      char* in = GET_ROWCELL_INTERBUF(pEntryInfo);
H
Haojun Liao 已提交
3165
      colDataAppend(pColInfoData, nrows, in, pEntryInfo->isNullRes);
3166 3167
    }

3168 3169 3170
    releaseBufPage(pBuf, page);
    nrows += 1;

3171
    numOfResult += numOfRowsToCopy;
H
Haojun Liao 已提交
3172
    if (numOfResult == rowCapacity) {  // output buffer is full
3173 3174 3175 3176
      break;
    }
  }

L
Liu Jicong 已提交
3177
  // qDebug("QInfo:0x%"PRIx64" copy data to query buf completed", GET_TASKID(pRuntimeEnv));
3178 3179 3180 3181
  pBlock->info.rows = numOfResult;
  return 0;
}

3182 3183
void toSDatablock(SSDataBlock* pBlock, int32_t rowCapacity, SGroupResInfo* pGroupResInfo, SExprInfo* pExprInfo, SDiskbasedBuf* pBuf,
                  int32_t* rowCellOffset) {
3184 3185
  assert(pGroupResInfo->currentGroup <= pGroupResInfo->totalGroup);

3186
  blockDataCleanup(pBlock);
3187 3188 3189 3190
  if (!hasRemainDataInCurrentGroup(pGroupResInfo)) {
    return;
  }

3191
  int32_t orderType = TSDB_ORDER_ASC;
3192
  doCopyToSDataBlock(pBlock, rowCapacity, pExprInfo, pBuf, pGroupResInfo, orderType, rowCellOffset);
3193

H
Haojun Liao 已提交
3194 3195
  // add condition (pBlock->info.rows >= 1) just to runtime happy
  blockDataUpdateTsWindow(pBlock);
3196 3197
}

L
Liu Jicong 已提交
3198 3199
static void updateNumOfRowsInResultRows(SqlFunctionCtx* pCtx, int32_t numOfOutput, SResultRowInfo* pResultRowInfo,
                                        int32_t* rowCellInfoOffset) {
3200
  // update the number of result for each, only update the number of rows for the corresponding window result.
L
Liu Jicong 已提交
3201 3202 3203
  //  if (QUERY_IS_INTERVAL_QUERY(pQueryAttr)) {
  //    return;
  //  }
H
Haojun Liao 已提交
3204
#if 0
3205
  for (int32_t i = 0; i < pResultRowInfo->size; ++i) {
L
Liu Jicong 已提交
3206
    SResultRow* pResult = pResultRowInfo->pResult[i];
3207 3208 3209 3210 3211 3212 3213

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

3214 3215
      SResultRowEntryInfo* pCell = getResultCell(pResult, j, rowCellInfoOffset);
      pResult->numOfRows = (uint16_t)(TMAX(pResult->numOfRows, pCell->numOfRes));
3216 3217
    }
  }
H
Haojun Liao 已提交
3218 3219
#endif

3220 3221
}

L
Liu Jicong 已提交
3222
static int32_t compressQueryColData(SColumnInfoData* pColRes, int32_t numOfRows, char* data, int8_t compressed) {
3223 3224
  int32_t colSize = pColRes->info.bytes * numOfRows;
  return (*(tDataTypes[pColRes->info.type].compFunc))(pColRes->pData, colSize, numOfRows, data,
L
Liu Jicong 已提交
3225
                                                      colSize + COMP_OVERFLOW_BYTES, compressed, NULL, 0);
3226 3227
}

L
Liu Jicong 已提交
3228 3229 3230 3231 3232
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);
  //  }
3233 3234 3235 3236 3237 3238 3239

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

  return pOutput->info.rows;
}

3240
void publishOperatorProfEvent(SOperatorInfo* pOperator, EQueryProfEventType eventType) {
3241 3242
  SQueryProfEvent event = {0};

L
Liu Jicong 已提交
3243 3244
  event.eventType = eventType;
  event.eventTime = taosGetTimestampUs();
3245 3246 3247 3248
  event.operatorType = pOperator->operatorType;
//    if (pQInfo->summary.queryProfEvents) {
//      taosArrayPush(pQInfo->summary.queryProfEvents, &event);
//    }
3249 3250
}

L
Liu Jicong 已提交
3251
void publishQueryAbortEvent(SExecTaskInfo* pTaskInfo, int32_t code) {
3252 3253 3254 3255 3256
  SQueryProfEvent event;
  event.eventType = QUERY_PROF_QUERY_ABORT;
  event.eventTime = taosGetTimestampUs();
  event.abortCode = code;

3257 3258
  if (pTaskInfo->cost.queryProfEvents) {
    taosArrayPush(pTaskInfo->cost.queryProfEvents, &event);
3259 3260 3261
  }
}

L
Liu Jicong 已提交
3262
typedef struct {
3263 3264 3265 3266 3267 3268 3269
  uint8_t operatorType;
  int64_t beginTime;
  int64_t endTime;
  int64_t selfTime;
  int64_t descendantsTime;
} SOperatorStackItem;

L
Liu Jicong 已提交
3270 3271
static void doOperatorExecProfOnce(SOperatorStackItem* item, SQueryProfEvent* event, SArray* opStack,
                                   SHashObj* profResults) {
3272 3273 3274 3275 3276 3277 3278 3279
  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 已提交
3280
  uint8_t              operatorType = item->operatorType;
3281 3282 3283 3284 3285 3286 3287 3288 3289
  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 已提交
3290
    taosHashPut(profResults, &(operatorType), sizeof(operatorType), &opResult, sizeof(opResult));
3291 3292 3293
  }
}

3294 3295 3296 3297 3298 3299 3300 3301 3302 3303
void calculateOperatorProfResults(void) {
//  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;
//  }
3304 3305 3306 3307 3308

  SArray* opStack = taosArrayInit(32, sizeof(SOperatorStackItem));
  if (opStack == NULL) {
    return;
  }
3309
#if 0
L
Liu Jicong 已提交
3310
  size_t    size = taosArrayGetSize(pQInfo->summary.queryProfEvents);
3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331
  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);
      }
    }
  }
3332
#endif
3333 3334 3335
  taosArrayDestroy(opStack);
}

L
Liu Jicong 已提交
3336 3337
void queryCostStatis(SExecTaskInfo* pTaskInfo) {
  STaskCostInfo* pSummary = &pTaskInfo->cost;
3338

L
Liu Jicong 已提交
3339 3340 3341
  //  uint64_t hashSize = taosHashGetMemSize(pQInfo->runtimeEnv.pResultRowHashTable);
  //  hashSize += taosHashGetMemSize(pRuntimeEnv->tableqinfoGroupInfo.map);
  //  pSummary->hashSize = hashSize;
3342 3343 3344 3345

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

L
Liu Jicong 已提交
3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365
  //  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);
3366 3367 3368 3369

  if (pSummary->operatorProfResults) {
    SOperatorProfResult* opRes = taosHashIterate(pSummary->operatorProfResults, NULL);
    while (opRes != NULL) {
L
Liu Jicong 已提交
3370 3371
      // qDebug("QInfo:0x%" PRIx64 " :cost summary: operator : %d, exec times: %" PRId64 ", self time: %" PRId64,
      //             pQInfo->qId, opRes->operatorType, opRes->sumRunTimes, opRes->sumSelfTime);
3372 3373 3374 3375 3376
      opRes = taosHashIterate(pSummary->operatorProfResults, opRes);
    }
  }
}

L
Liu Jicong 已提交
3377 3378 3379
// static void updateOffsetVal(STaskRuntimeEnv *pRuntimeEnv, SDataBlockInfo *pBlockInfo) {
//   STaskAttr *pQueryAttr = pRuntimeEnv->pQueryAttr;
//   STableQueryInfo* pTableQueryInfo = pRuntimeEnv->current;
3380
//
L
Liu Jicong 已提交
3381
//   int32_t step = GET_FORWARD_DIRECTION_FACTOR(pQueryAttr->order.order);
3382
//
L
Liu Jicong 已提交
3383 3384 3385 3386
//   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;
//   }
3387
//
L
Liu Jicong 已提交
3388 3389 3390 3391 3392
//   if (QUERY_IS_ASC_QUERY(pQueryAttr)) {
//     pQueryAttr->pos = (int32_t)pQueryAttr->limit.offset;
//   } else {
//     pQueryAttr->pos = pBlockInfo->rows - (int32_t)pQueryAttr->limit.offset - 1;
//   }
3393
//
L
Liu Jicong 已提交
3394
//   assert(pQueryAttr->pos >= 0 && pQueryAttr->pos <= pBlockInfo->rows - 1);
3395
//
L
Liu Jicong 已提交
3396 3397
//   SArray *         pDataBlock = tsdbRetrieveDataBlock(pRuntimeEnv->pTsdbReadHandle, NULL);
//   SColumnInfoData *pColInfoData = taosArrayGet(pDataBlock, 0);
3398
//
L
Liu Jicong 已提交
3399 3400
//   // update the pQueryAttr->limit.offset value, and pQueryAttr->pos value
//   TSKEY *keys = (TSKEY *) pColInfoData->pData;
3401
//
L
Liu Jicong 已提交
3402 3403 3404
//   // update the offset value
//   pTableQueryInfo->lastKey = keys[pQueryAttr->pos];
//   pQueryAttr->limit.offset = 0;
3405
//
L
Liu Jicong 已提交
3406
//   int32_t numOfRes = tableApplyFunctionsOnBlock(pRuntimeEnv, pBlockInfo, NULL, binarySearchForKey, pDataBlock);
3407
//
L
Liu Jicong 已提交
3408 3409 3410 3411
//   //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);
// }
3412

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

3618
int32_t appendDownstream(SOperatorInfo* p, SOperatorInfo** pDownstream, int32_t num) {
H
Haojun Liao 已提交
3619
  if (p->pDownstream == NULL) {
H
Haojun Liao 已提交
3620
    assert(p->numOfDownstream == 0);
3621 3622
  }

wafwerar's avatar
wafwerar 已提交
3623
  p->pDownstream = taosMemoryCalloc(1, num * POINTER_BYTES);
3624 3625 3626 3627 3628 3629 3630
  if (p->pDownstream == NULL) {
    return TSDB_CODE_OUT_OF_MEMORY;
  }

  memcpy(p->pDownstream, pDownstream, num * POINTER_BYTES);
  p->numOfDownstream = num;
  return TSDB_CODE_SUCCESS;
3631 3632 3633 3634
}

static void doDestroyTableQueryInfo(STableGroupInfo* pTableqinfoGroupInfo);

3635
static void doTableQueryInfoTimeWindowCheck(SExecTaskInfo* pTaskInfo, STableQueryInfo* pTableQueryInfo, int32_t order) {
H
Haojun Liao 已提交
3636 3637
#if 0
    if (order == TSDB_ORDER_ASC) {
3638 3639
    assert(
        (pTableQueryInfo->win.skey <= pTableQueryInfo->win.ekey) &&
H
Haojun Liao 已提交
3640 3641
        (pTableQueryInfo->lastKey >= pTaskInfo->window.skey) &&
        (pTableQueryInfo->win.skey >= pTaskInfo->window.skey && pTableQueryInfo->win.ekey <= pTaskInfo->window.ekey));
3642 3643 3644
  } else {
    assert(
        (pTableQueryInfo->win.skey >= pTableQueryInfo->win.ekey) &&
H
Haojun Liao 已提交
3645 3646
        (pTableQueryInfo->lastKey <= pTaskInfo->window.skey) &&
        (pTableQueryInfo->win.skey <= pTaskInfo->window.skey && pTableQueryInfo->win.ekey >= pTaskInfo->window.ekey));
3647
  }
H
Haojun Liao 已提交
3648
#endif
3649 3650
}

L
Liu Jicong 已提交
3651 3652 3653 3654 3655 3656 3657 3658
// STsdbQueryCond createTsdbQueryCond(STaskAttr* pQueryAttr, STimeWindow* win) {
//   STsdbQueryCond cond = {
//       .colList   = pQueryAttr->tableCols,
//       .order     = pQueryAttr->order.order,
//       .numOfCols = pQueryAttr->numOfCols,
//       .type      = BLOCK_LOAD_OFFSET_SEQ_ORDER,
//       .loadExternalRows = false,
//   };
3659
//
L
Liu Jicong 已提交
3660 3661 3662
//   TIME_WINDOW_COPY(cond.twindow, *win);
//   return cond;
// }
3663 3664 3665

static STableIdInfo createTableIdInfo(STableQueryInfo* pTableQueryInfo) {
  STableIdInfo tidInfo;
L
Liu Jicong 已提交
3666 3667 3668 3669 3670
  //  STableId* id = TSDB_TABLEID(pTableQueryInfo->pTable);
  //
  //  tidInfo.uid = id->uid;
  //  tidInfo.tid = id->tid;
  //  tidInfo.key = pTableQueryInfo->lastKey;
3671 3672 3673 3674

  return tidInfo;
}

L
Liu Jicong 已提交
3675 3676 3677 3678
// 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;
3679
//
L
Liu Jicong 已提交
3680 3681 3682
//   if (pTableQueryInfo->pTable == NULL) {
//     return;
//   }
3683
//
L
Liu Jicong 已提交
3684 3685 3686 3687 3688 3689 3690 3691 3692
//   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));
//   }
// }
3693

3694
int32_t loadRemoteDataCallback(void* param, const SDataBuf* pMsg, int32_t code) {
L
Liu Jicong 已提交
3695
  SSourceDataInfo* pSourceDataInfo = (SSourceDataInfo*)param;
H
Haojun Liao 已提交
3696 3697
  if (code == TSDB_CODE_SUCCESS) {
    pSourceDataInfo->pRsp = pMsg->pData;
3698

H
Haojun Liao 已提交
3699 3700 3701 3702 3703 3704 3705
    SRetrieveTableRsp* pRsp = pSourceDataInfo->pRsp;
    pRsp->numOfRows = htonl(pRsp->numOfRows);
    pRsp->compLen   = htonl(pRsp->compLen);
    pRsp->useconds  = htobe64(pRsp->useconds);
  } else {
    pSourceDataInfo->code = code;
  }
H
Haojun Liao 已提交
3706

H
Haojun Liao 已提交
3707
  pSourceDataInfo->status = EX_SOURCE_DATA_READY;
3708
  tsem_post(&pSourceDataInfo->pEx->ready);
wmmhello's avatar
wmmhello 已提交
3709
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
3710 3711 3712 3713
}

static void destroySendMsgInfo(SMsgSendInfo* pMsgBody) {
  assert(pMsgBody != NULL);
wafwerar's avatar
wafwerar 已提交
3714 3715
  taosMemoryFreeClear(pMsgBody->msgInfo.pData);
  taosMemoryFreeClear(pMsgBody);
H
Haojun Liao 已提交
3716 3717
}

S
Shengliang Guan 已提交
3718
void qProcessFetchRsp(void* parent, SRpcMsg* pMsg, SEpSet* pEpSet) {
L
Liu Jicong 已提交
3719
  SMsgSendInfo* pSendInfo = (SMsgSendInfo*)pMsg->ahandle;
H
Haojun Liao 已提交
3720 3721 3722 3723 3724
  assert(pMsg->ahandle != NULL);

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

  if (pMsg->contLen > 0) {
wafwerar's avatar
wafwerar 已提交
3725
    buf.pData = taosMemoryCalloc(1, pMsg->contLen);
H
Haojun Liao 已提交
3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736
    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);
3737 3738
}

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

wafwerar's avatar
wafwerar 已提交
3742
  SResFetchReq* pMsg = taosMemoryCalloc(1, sizeof(SResFetchReq));
3743 3744 3745 3746
  if (NULL == pMsg) {
    pTaskInfo->code = TSDB_CODE_QRY_OUT_OF_MEMORY;
    return pTaskInfo->code;
  }
3747

L
Liu Jicong 已提交
3748 3749
  SDownstreamSourceNode* pSource = taosArrayGet(pExchangeInfo->pSources, sourceIndex);
  SSourceDataInfo*       pDataInfo = taosArrayGet(pExchangeInfo->pSourceDataInfo, sourceIndex);
3750

L
Liu Jicong 已提交
3751 3752
  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);
3753 3754 3755 3756 3757 3758 3759

  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 已提交
3760
  SMsgSendInfo* pMsgSendInfo = taosMemoryCalloc(1, sizeof(SMsgSendInfo));
3761
  if (NULL == pMsgSendInfo) {
wafwerar's avatar
wafwerar 已提交
3762
    taosMemoryFreeClear(pMsg);
3763 3764 3765
    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 已提交
3766 3767
  }

3768 3769 3770 3771 3772
  pMsgSendInfo->param = pDataInfo;
  pMsgSendInfo->msgInfo.pData = pMsg;
  pMsgSendInfo->msgInfo.len = sizeof(SResFetchReq);
  pMsgSendInfo->msgType = TDMT_VND_FETCH;
  pMsgSendInfo->fp = loadRemoteDataCallback;
3773

3774
  int64_t transporterId = 0;
L
Liu Jicong 已提交
3775
  int32_t code = asyncSendMsgToServer(pExchangeInfo->pTransporter, &pSource->addr.epSet, &transporterId, pMsgSendInfo);
3776 3777 3778
  return TSDB_CODE_SUCCESS;
}

3779 3780 3781
// TODO if only one or two columns required, how to extract data?
int32_t setSDataBlockFromFetchRsp(SSDataBlock* pRes, SLoadRemoteDataInfo* pLoadInfo, int32_t numOfRows, char* pData,
                                  int32_t compLen, int32_t numOfOutput, int64_t startTs, uint64_t* total, SArray* pColList) {
H
Haojun Liao 已提交
3782
  blockDataEnsureCapacity(pRes, numOfRows);
3783

H
Haojun Liao 已提交
3784 3785
  if (pColList == NULL) {  // data from other sources
    int32_t* colLen = (int32_t*)pData;
L
Liu Jicong 已提交
3786
    char*    pStart = pData + sizeof(int32_t) * numOfOutput;
H
Haojun Liao 已提交
3787

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

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

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

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

      memcpy(pColInfoData->pData, pStart, colLen[i]);
      pStart += colLen[i];
3808
    }
H
Haojun Liao 已提交
3809
  } else {  // extract data according to pColList
3810
    ASSERT(numOfOutput == taosArrayGetSize(pColList));
3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844
    char* pStart = pData;

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

    SSysTableSchema* pSchema = (SSysTableSchema*)pStart;
    for(int32_t i = 0; i < numOfCols; ++i) {
      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};
    for(int32_t i = 0; i < numOfCols; ++i) {
      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);

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

    for (int32_t i = 0; i < numOfCols; ++i) {
      colLen[i] = htonl(colLen[i]);
3845
      ASSERT(colLen[i] >= 0);
3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863

      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 已提交
3864 3865

    // data from mnode
3866 3867 3868
    for (int32_t i = 0; i < numOfCols; ++i) {
      SColumnInfoData* pSrc = taosArrayGet(block.pDataBlock, i);

L
Liu Jicong 已提交
3869 3870
      for (int32_t j = 0; j < numOfOutput; ++j) {
        int16_t colIndex = *(int16_t*)taosArrayGet(pColList, j);
3871

3872 3873
        if (colIndex - 1 == i) {
          SColumnInfoData* pColInfoData = taosArrayGet(pRes->pDataBlock, j);
3874
          colDataAssign(pColInfoData, pSrc, numOfRows);
3875 3876 3877
          break;
        }
      }
3878
    }
3879
  }
3880

H
Haojun Liao 已提交
3881
  pRes->info.rows = numOfRows;
3882

3883
  int64_t el = taosGetTimestampUs() - startTs;
3884

H
Haojun Liao 已提交
3885 3886
  pLoadInfo->totalRows += numOfRows;
  pLoadInfo->totalSize += compLen;
3887

H
Haojun Liao 已提交
3888 3889 3890
  if (total != NULL) {
    *total += numOfRows;
  }
3891

H
Haojun Liao 已提交
3892
  pLoadInfo->totalElapsed += el;
3893 3894
  return TSDB_CODE_SUCCESS;
}
3895

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

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

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

  doSetOperatorCompleted(pOperator);
  return NULL;
}

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

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

3929
      if (pDataInfo->status != EX_SOURCE_DATA_READY) {
3930 3931 3932
        continue;
      }

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

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

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

3956 3957 3958
      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 已提交
3959 3960
               GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->taskId, pRes->info.rows, pDataInfo->totalRows,
               pLoadInfo->totalRows, pLoadInfo->totalSize, i + 1, totalSources);
3961
        pDataInfo->status = EX_SOURCE_DATA_EXHAUSTED;
3962
      } else {
3963
        qDebug("%s fetch msg rsp from vgId:%d, taskId:0x%" PRIx64 " numOfRows:%d, totalRows:%" PRIu64 ", totalBytes:%" PRIu64,
H
Haojun Liao 已提交
3964 3965
               GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->taskId, pRes->info.rows, pLoadInfo->totalRows,
               pLoadInfo->totalSize);
3966 3967
      }

3968 3969
      if (pDataInfo->status != EX_SOURCE_DATA_EXHAUSTED) {
        pDataInfo->status = EX_SOURCE_DATA_NOT_READY;
3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988
        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 已提交
3989 3990 3991
static SSDataBlock* concurrentlyLoadRemoteData(SOperatorInfo* pOperator) {
  SExchangeInfo* pExchangeInfo = pOperator->info;
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
H
Haojun Liao 已提交
3992

H
Haojun Liao 已提交
3993 3994 3995
  if (pOperator->status == OP_RES_TO_RETURN) {
    return concurrentlyLoadRemoteDataImpl(pOperator, pExchangeInfo, pTaskInfo);
  }
3996

L
Liu Jicong 已提交
3997
  size_t  totalSources = taosArrayGetSize(pExchangeInfo->pSources);
3998 3999 4000
  int64_t startTs = taosGetTimestampUs();

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

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

  tsem_wait(&pExchangeInfo->ready);
H
Haojun Liao 已提交
4013 4014
  pOperator->status = OP_RES_TO_RETURN;
  return concurrentlyLoadRemoteDataImpl(pOperator, pExchangeInfo, pTaskInfo);
4015 4016
}

L
Liu Jicong 已提交
4017 4018 4019
static int32_t prepareConcurrentlyLoad(SOperatorInfo* pOperator) {
  SExchangeInfo* pExchangeInfo = pOperator->info;
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
4020

L
Liu Jicong 已提交
4021
  size_t  totalSources = taosArrayGetSize(pExchangeInfo->pSources);
4022 4023 4024
  int64_t startTs = taosGetTimestampUs();

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

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

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

H
Haojun Liao 已提交
4040
  return TSDB_CODE_SUCCESS;
4041 4042
}

L
Liu Jicong 已提交
4043 4044 4045
static SSDataBlock* seqLoadRemoteData(SOperatorInfo* pOperator) {
  SExchangeInfo* pExchangeInfo = pOperator->info;
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
4046

L
Liu Jicong 已提交
4047
  size_t  totalSources = taosArrayGetSize(pExchangeInfo->pSources);
4048
  int64_t startTs = taosGetTimestampUs();
4049

L
Liu Jicong 已提交
4050
  while (1) {
4051 4052
    if (pExchangeInfo->current >= totalSources) {
      return setAllSourcesCompleted(pOperator, startTs);
4053
    }
4054

4055 4056 4057
    doSendFetchDataRequest(pExchangeInfo, pTaskInfo, pExchangeInfo->current);
    tsem_wait(&pExchangeInfo->ready);

H
Haojun Liao 已提交
4058
    SSourceDataInfo* pDataInfo = taosArrayGet(pExchangeInfo->pSourceDataInfo, pExchangeInfo->current);
X
Xiaoyu Wang 已提交
4059
    SDownstreamSourceNode* pSource = taosArrayGet(pExchangeInfo->pSources, pExchangeInfo->current);
4060

H
Haojun Liao 已提交
4061 4062 4063 4064 4065 4066 4067
    if (pDataInfo->code != TSDB_CODE_SUCCESS) {
      qError("%s vgId:%d, taskID:0x%" PRIx64 " error happens, code:%s",
             GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->taskId, tstrerror(pDataInfo->code));
      pOperator->pTaskInfo->code = pDataInfo->code;
      return NULL;
    }

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

4075
      pDataInfo->status = EX_SOURCE_DATA_EXHAUSTED;
4076 4077 4078
      pExchangeInfo->current += 1;
      continue;
    }
H
Haojun Liao 已提交
4079

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

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

4092
      pDataInfo->status = EX_SOURCE_DATA_EXHAUSTED;
4093 4094
      pExchangeInfo->current += 1;
    } else {
L
Liu Jicong 已提交
4095 4096 4097 4098
      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);
4099 4100 4101 4102
    }

    return pExchangeInfo->pResult;
  }
4103 4104
}

L
Liu Jicong 已提交
4105
static int32_t prepareLoadRemoteData(SOperatorInfo* pOperator) {
4106
  if (OPTR_IS_OPENED(pOperator)) {
H
Haojun Liao 已提交
4107 4108 4109
    return TSDB_CODE_SUCCESS;
  }

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

4120
  OPTR_SET_OPENED(pOperator);
H
Haojun Liao 已提交
4121 4122 4123
  return TSDB_CODE_SUCCESS;
}

L
Liu Jicong 已提交
4124 4125 4126
static SSDataBlock* doLoadRemoteData(SOperatorInfo* pOperator, bool* newgroup) {
  SExchangeInfo* pExchangeInfo = pOperator->info;
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
4127

4128 4129
  pTaskInfo->code = pOperator->_openFn(pOperator);
  if (pTaskInfo->code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
4130 4131
    return NULL;
  }
4132

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

4136
  if (pOperator->status == OP_EXEC_DONE) {
L
Liu Jicong 已提交
4137 4138 4139
    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);
4140 4141 4142 4143
    return NULL;
  }

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

4145 4146 4147
  if (pExchangeInfo->seqLoadData) {
    return seqLoadRemoteData(pOperator);
  } else {
H
Haojun Liao 已提交
4148
    return concurrentlyLoadRemoteData(pOperator);
4149
  }
H
Haojun Liao 已提交
4150

4151
#if 0
H
Haojun Liao 已提交
4152
  _error:
wafwerar's avatar
wafwerar 已提交
4153 4154
  taosMemoryFreeClear(pMsg);
  taosMemoryFreeClear(pMsgSendInfo);
H
Haojun Liao 已提交
4155 4156 4157

  terrno = pTaskInfo->code;
  return NULL;
4158
#endif
H
Haojun Liao 已提交
4159
}
4160

H
Haojun Liao 已提交
4161
static int32_t initDataSource(int32_t numOfSources, SExchangeInfo* pInfo) {
4162
  pInfo->pSourceDataInfo = taosArrayInit(numOfSources, sizeof(SSourceDataInfo));
H
Haojun Liao 已提交
4163 4164
  if (pInfo->pSourceDataInfo == NULL) {
    return TSDB_CODE_OUT_OF_MEMORY;
4165 4166
  }

L
Liu Jicong 已提交
4167
  for (int32_t i = 0; i < numOfSources; ++i) {
4168
    SSourceDataInfo dataInfo = {0};
H
Haojun Liao 已提交
4169
    dataInfo.status = EX_SOURCE_DATA_NOT_READY;
L
Liu Jicong 已提交
4170 4171
    dataInfo.pEx = pInfo;
    dataInfo.index = i;
4172

H
Haojun Liao 已提交
4173 4174 4175 4176 4177 4178 4179 4180 4181 4182
    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 已提交
4183
SOperatorInfo* createExchangeOperatorInfo(const SNodeList* pSources, SSDataBlock* pBlock, SExecTaskInfo* pTaskInfo) {
L
Liu Jicong 已提交
4184
  SExchangeInfo* pInfo = taosMemoryCalloc(1, sizeof(SExchangeInfo));
wafwerar's avatar
wafwerar 已提交
4185
  SOperatorInfo* pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
4186 4187

  if (pInfo == NULL || pOperator == NULL) {
wafwerar's avatar
wafwerar 已提交
4188 4189
    taosMemoryFreeClear(pInfo);
    taosMemoryFreeClear(pOperator);
H
Haojun Liao 已提交
4190 4191
    terrno = TSDB_CODE_QRY_OUT_OF_MEMORY;
    return NULL;
H
Haojun Liao 已提交
4192 4193
  }

H
Haojun Liao 已提交
4194
  size_t numOfSources = LIST_LENGTH(pSources);
H
Haojun Liao 已提交
4195
  pInfo->pSources = taosArrayInit(numOfSources, sizeof(SDownstreamSourceNode));
H
Haojun Liao 已提交
4196 4197 4198
  pInfo->pSourceDataInfo = taosArrayInit(numOfSources, sizeof(SSourceDataInfo));
  if (pInfo->pSourceDataInfo == NULL || pInfo->pSources == NULL) {
    goto _error;
H
Haojun Liao 已提交
4199 4200
  }

L
Liu Jicong 已提交
4201 4202
  for (int32_t i = 0; i < numOfSources; ++i) {
    SNodeListNode* pNode = nodesListGetNode((SNodeList*)pSources, i);
H
Haojun Liao 已提交
4203 4204
    taosArrayPush(pInfo->pSources, pNode);
  }
4205

H
Haojun Liao 已提交
4206 4207 4208
  int32_t code = initDataSource(numOfSources, pInfo);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
4209
  }
H
Haojun Liao 已提交
4210

4211
  pInfo->pResult     = pBlock;
4212 4213 4214
  pInfo->seqLoadData = true;

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

4216
  pOperator->name         = "ExchangeOperator";
X
Xiaoyu Wang 已提交
4217
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_EXCHANGE;
4218
  pOperator->blockingOptr = false;
4219 4220 4221 4222 4223 4224 4225
  pOperator->status       = OP_NOT_OPENED;
  pOperator->info         = pInfo;
  pOperator->numOfOutput  = pBlock->info.numOfCols;
  pOperator->pTaskInfo    = pTaskInfo;
  pOperator->_openFn      = prepareLoadRemoteData;  // assign a dummy function.
  pOperator->getNextFn    = doLoadRemoteData;
  pOperator->closeFn      = destroyExchangeOperatorInfo;
4226

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

    pInfo->pTransporter = rpcOpen(&rpcInit);
    if (pInfo->pTransporter == NULL) {
L
Liu Jicong 已提交
4245
      return NULL;  // todo
H
Haojun Liao 已提交
4246 4247
    }
  }
S
Shengliang 已提交
4248
#endif
4249

4250
  return pOperator;
H
Haojun Liao 已提交
4251

L
Liu Jicong 已提交
4252
_error:
H
Haojun Liao 已提交
4253
  if (pInfo != NULL) {
H
Haojun Liao 已提交
4254
    destroyExchangeOperatorInfo(pInfo, numOfSources);
H
Haojun Liao 已提交
4255 4256
  }

wafwerar's avatar
wafwerar 已提交
4257 4258
  taosMemoryFreeClear(pInfo);
  taosMemoryFreeClear(pOperator);
H
Haojun Liao 已提交
4259
  pTaskInfo->code = TSDB_CODE_OUT_OF_MEMORY;
H
Haojun Liao 已提交
4260
  return NULL;
4261 4262
}

4263
static int32_t doInitAggInfoSup(SAggSupporter* pAggSup, SqlFunctionCtx* pCtx, int32_t numOfOutput, size_t keyBufSize, const char* pKey);
H
Haojun Liao 已提交
4264
static void    cleanupAggSup(SAggSupporter* pAggSup);
4265

4266
static void destroySortedMergeOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
4267
  SSortedMergeOperatorInfo* pInfo = (SSortedMergeOperatorInfo*)param;
H
Haojun Liao 已提交
4268
  taosArrayDestroy(pInfo->pSortInfo);
4269 4270 4271
  taosArrayDestroy(pInfo->groupInfo);

  if (pInfo->pSortHandle != NULL) {
H
Haojun Liao 已提交
4272
    tsortDestroySortHandle(pInfo->pSortHandle);
4273 4274
  }

H
Haojun Liao 已提交
4275
  blockDataDestroy(pInfo->binfo.pRes);
H
Haojun Liao 已提交
4276
  cleanupAggSup(&pInfo->aggSup);
4277
}
H
Haojun Liao 已提交
4278

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

X
Xiaoyu Wang 已提交
4282
  *dst = *src;
4283

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

L
Liu Jicong 已提交
4288 4289 4290 4291
  //  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 已提交
4292
}
4293

4294 4295
static SExprInfo* exprArrayDup(SArray* pExprList) {
  size_t numOfOutput = taosArrayGetSize(pExprList);
4296

wafwerar's avatar
wafwerar 已提交
4297
  SExprInfo* p = taosMemoryCalloc(numOfOutput, sizeof(SExprInfo));
4298 4299
  for (int32_t i = 0; i < numOfOutput; ++i) {
    SExprInfo* pExpr = taosArrayGetP(pExprList, i);
H
Haojun Liao 已提交
4300
    assignExprInfo(&p[i], pExpr);
4301 4302
  }

H
Haojun Liao 已提交
4303 4304
  return p;
}
4305

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

H
Haojun Liao 已提交
4311
    bool isNull = tsortIsNullVal(pTupleHandle, i);
H
Haojun Liao 已提交
4312 4313 4314
    if (isNull) {
      colDataAppend(pColInfo, pBlock->info.rows, NULL, true);
    } else {
H
Haojun Liao 已提交
4315
      char* pData = tsortGetValue(pTupleHandle, i);
H
Haojun Liao 已提交
4316 4317
      colDataAppend(pColInfo, pBlock->info.rows, pData, false);
    }
4318 4319
  }

4320 4321
  pBlock->info.rows += 1;
}
4322

H
Haojun Liao 已提交
4323
SSDataBlock* getSortedBlockData(SSortHandle* pHandle, SSDataBlock* pDataBlock, int32_t capacity) {
4324
  blockDataCleanup(pDataBlock);
D
dapan1121 已提交
4325
  blockDataEnsureCapacity(pDataBlock, capacity);
4326

wmmhello's avatar
wmmhello 已提交
4327 4328
  blockDataEnsureCapacity(pDataBlock, capacity);

L
Liu Jicong 已提交
4329
  while (1) {
H
Haojun Liao 已提交
4330
    STupleHandle* pTupleHandle = tsortNextTuple(pHandle);
4331 4332 4333
    if (pTupleHandle == NULL) {
      break;
    }
4334

4335 4336 4337
    appendOneRowToDataBlock(pDataBlock, pTupleHandle);
    if (pDataBlock->info.rows >= capacity) {
      return pDataBlock;
H
Haojun Liao 已提交
4338 4339
    }
  }
4340

L
Liu Jicong 已提交
4341
  return (pDataBlock->info.rows > 0) ? pDataBlock : NULL;
4342
}
4343

4344
SSDataBlock* loadNextDataBlock(void* param) {
L
Liu Jicong 已提交
4345 4346
  SOperatorInfo* pOperator = (SOperatorInfo*)param;
  bool           newgroup = false;
H
Haojun Liao 已提交
4347
  return pOperator->getNextFn(pOperator, &newgroup);
4348 4349
}

L
Liu Jicong 已提交
4350
static bool needToMerge(SSDataBlock* pBlock, SArray* groupInfo, char** buf, int32_t rowIndex) {
4351 4352 4353 4354
  size_t size = taosArrayGetSize(groupInfo);
  if (size == 0) {
    return true;
  }
4355

4356 4357
  for (int32_t i = 0; i < size; ++i) {
    int32_t* index = taosArrayGet(groupInfo, i);
4358

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

4362 4363 4364
    if ((isNull && buf[i] != NULL) || (!isNull && buf[i] == NULL)) {
      return false;
    }
4365

4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378
    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;
      }
4379 4380 4381
    }
  }

4382
  return 0;
4383 4384
}

L
Liu Jicong 已提交
4385 4386 4387
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
4388
    pCtx[j].startRow = rowIndex;
4389 4390
  }

4391 4392
  for (int32_t j = 0; j < numOfExpr; ++j) {
    int32_t functionId = pCtx[j].functionId;
L
Liu Jicong 已提交
4393 4394 4395 4396 4397 4398 4399 4400 4401
    //    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]);
    //    }
4402
  }
4403
}
4404

L
Liu Jicong 已提交
4405 4406
static void doFinalizeResultImpl(SqlFunctionCtx* pCtx, int32_t numOfExpr) {
  for (int32_t j = 0; j < numOfExpr; ++j) {
4407 4408 4409 4410
    int32_t functionId = pCtx[j].functionId;
    //    if (functionId == FUNC_TAG_DUMMY || functionId == FUNC_TS_DUMMY) {
    //      continue;
    //    }
4411

4412 4413 4414 4415
    //    if (functionId < 0) {
    //      SUdfInfo* pUdfInfo = taosArrayGet(pInfo->udfInfo, -1 * functionId - 1);
    //      doInvokeUdf(pUdfInfo, &pCtx[j], 0, TSDB_UDF_FUNC_FINALIZE);
    //    } else {
H
Haojun Liao 已提交
4416
    pCtx[j].fpSet.finalize(&pCtx[j]);
4417 4418
  }
}
4419

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

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

4427 4428 4429
    char* data = colDataGetData(pColInfo, rowIndex);
    memcpy(rowColData[i], data, colDataGetLength(pColInfo, rowIndex));
  }
4430

4431 4432
  return true;
}
4433

4434 4435
static void doMergeImpl(SOperatorInfo* pOperator, int32_t numOfExpr, SSDataBlock* pBlock) {
  SSortedMergeOperatorInfo* pInfo = pOperator->info;
4436

4437
  SqlFunctionCtx* pCtx = pInfo->binfo.pCtx;
L
Liu Jicong 已提交
4438
  for (int32_t i = 0; i < pBlock->info.numOfCols; ++i) {
4439 4440
    pCtx[i].size = 1;
  }
4441

L
Liu Jicong 已提交
4442
  for (int32_t i = 0; i < pBlock->info.rows; ++i) {
4443 4444 4445 4446 4447 4448 4449 4450 4451
    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 已提交
4452
        int32_t numOfRows = getNumOfResult(pInfo->binfo.pCtx, pOperator->numOfOutput, NULL);
4453
        //        setTagValueForMultipleRows(pCtx, pOperator->numOfOutput, numOfRows);
4454

4455
        // TODO check for available buffer;
H
Haojun Liao 已提交
4456

4457 4458 4459 4460 4461
        // next group info data
        pInfo->binfo.pRes->info.rows += numOfRows;
        for (int32_t j = 0; j < numOfExpr; ++j) {
          if (pCtx[j].functionId < 0) {
            continue;
4462
          }
4463

H
Haojun Liao 已提交
4464
          pCtx[j].fpSet.process(&pCtx[j]);
4465
        }
4466 4467 4468

        doMergeResultImpl(pInfo, pCtx, numOfExpr, i);
        pInfo->hasGroupVal = saveCurrentTuple(pInfo->groupVal, pInfo->groupInfo, pBlock, i);
H
Haojun Liao 已提交
4469
      }
4470 4471 4472 4473
    }
  }
}

4474 4475
static SSDataBlock* doMerge(SOperatorInfo* pOperator) {
  SSortedMergeOperatorInfo* pInfo = pOperator->info;
L
Liu Jicong 已提交
4476
  SSortHandle*              pHandle = pInfo->pSortHandle;
4477

4478
  SSDataBlock* pDataBlock = createOneDataBlock(pInfo->binfo.pRes, false);
4479
  blockDataEnsureCapacity(pDataBlock, pOperator->resultInfo.capacity);
4480

L
Liu Jicong 已提交
4481
  while (1) {
4482
    blockDataCleanup(pDataBlock);
4483
    while (1) {
H
Haojun Liao 已提交
4484
      STupleHandle* pTupleHandle = tsortNextTuple(pHandle);
4485 4486
      if (pTupleHandle == NULL) {
        break;
4487
      }
4488

4489 4490
      // build datablock for merge for one group
      appendOneRowToDataBlock(pDataBlock, pTupleHandle);
4491
      if (pDataBlock->info.rows >= pOperator->resultInfo.capacity) {
4492 4493
        break;
      }
4494
    }
4495

4496 4497 4498
    if (pDataBlock->info.rows == 0) {
      break;
    }
4499

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

4507
  doFinalizeResultImpl(pInfo->binfo.pCtx, pOperator->numOfOutput);
H
Haojun Liao 已提交
4508
  int32_t numOfRows = getNumOfResult(pInfo->binfo.pCtx, pOperator->numOfOutput, NULL);
4509
  //        setTagValueForMultipleRows(pCtx, pOperator->numOfOutput, numOfRows);
4510

4511
  // TODO check for available buffer;
4512

4513 4514
  // next group info data
  pInfo->binfo.pRes->info.rows += numOfRows;
L
Liu Jicong 已提交
4515
  return (pInfo->binfo.pRes->info.rows > 0) ? pInfo->binfo.pRes : NULL;
4516
}
4517

L
Liu Jicong 已提交
4518
static SSDataBlock* doSortedMerge(SOperatorInfo* pOperator, bool* newgroup) {
4519 4520
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
4521 4522
  }

L
Liu Jicong 已提交
4523
  SExecTaskInfo*            pTaskInfo = pOperator->pTaskInfo;
4524
  SSortedMergeOperatorInfo* pInfo = pOperator->info;
H
Haojun Liao 已提交
4525
  if (pOperator->status == OP_RES_TO_RETURN) {
4526
    return getSortedBlockData(pInfo->pSortHandle, pInfo->binfo.pRes, pOperator->resultInfo.capacity);
4527 4528
  }

4529
  int32_t numOfBufPage = pInfo->sortBufSize / pInfo->bufPageSize;
4530
  pInfo->pSortHandle = tsortCreateSortHandle(pInfo->pSortInfo, NULL, SORT_MULTISOURCE_MERGE, pInfo->bufPageSize, numOfBufPage,
L
Liu Jicong 已提交
4531
                                             pInfo->binfo.pRes, "GET_TASKID(pTaskInfo)");
H
Haojun Liao 已提交
4532

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

L
Liu Jicong 已提交
4535
  for (int32_t i = 0; i < pOperator->numOfDownstream; ++i) {
wmmhello's avatar
wmmhello 已提交
4536
    SSortSource* ps = taosMemoryCalloc(1, sizeof(SSortSource));
H
Haojun Liao 已提交
4537
    ps->param = pOperator->pDownstream[i];
H
Haojun Liao 已提交
4538
    tsortAddSource(pInfo->pSortHandle, ps);
4539 4540
  }

H
Haojun Liao 已提交
4541
  int32_t code = tsortOpen(pInfo->pSortHandle);
4542
  if (code != TSDB_CODE_SUCCESS) {
4543
    longjmp(pTaskInfo->env, terrno);
4544 4545
  }

H
Haojun Liao 已提交
4546
  pOperator->status = OP_RES_TO_RETURN;
4547
  return doMerge(pOperator);
4548
}
4549

L
Liu Jicong 已提交
4550 4551
static int32_t initGroupCol(SExprInfo* pExprInfo, int32_t numOfCols, SArray* pGroupInfo,
                            SSortedMergeOperatorInfo* pInfo) {
4552 4553
  if (pGroupInfo == NULL || taosArrayGetSize(pGroupInfo) == 0) {
    return 0;
H
Haojun Liao 已提交
4554 4555
  }

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

4578
  ASSERT(taosArrayGetSize(pGroupInfo) == taosArrayGetSize(plist));
H
Haojun Liao 已提交
4579

wafwerar's avatar
wafwerar 已提交
4580
  pInfo->groupVal = taosMemoryCalloc(1, (POINTER_BYTES * numOfGroupCol + len));
4581 4582 4583 4584
  if (pInfo->groupVal == NULL) {
    taosArrayDestroy(plist);
    return TSDB_CODE_OUT_OF_MEMORY;
  }
H
Haojun Liao 已提交
4585

4586
  int32_t offset = 0;
L
Liu Jicong 已提交
4587 4588
  char*   start = (char*)(pInfo->groupVal + (POINTER_BYTES * numOfGroupCol));
  for (int32_t i = 0; i < numOfGroupCol; ++i) {
4589 4590
    pInfo->groupVal[i] = start + offset;
    SColumn* pCol = taosArrayGet(plist, i);
H
Haojun Liao 已提交
4591
    offset += pCol->bytes;
4592
  }
H
Haojun Liao 已提交
4593

4594
  taosArrayDestroy(plist);
H
Haojun Liao 已提交
4595

4596 4597
  return TSDB_CODE_SUCCESS;
}
H
Haojun Liao 已提交
4598

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

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

4611 4612 4613
  if (pInfo->binfo.pCtx == NULL || pInfo->binfo.pRes == NULL) {
    goto _error;
  }
H
Haojun Liao 已提交
4614

4615 4616
  size_t keyBufSize = sizeof(int64_t) + sizeof(int64_t) + POINTER_BYTES;
  int32_t code = doInitAggInfoSup(&pInfo->aggSup, pInfo->binfo.pCtx, num, keyBufSize, pTaskInfo->id.str);
4617 4618 4619
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
H
Haojun Liao 已提交
4620

H
Haojun Liao 已提交
4621
  setFunctionResultOutput(&pInfo->binfo, &pInfo->aggSup, MAIN_SCAN, pTaskInfo);
H
Haojun Liao 已提交
4622
  code = initGroupCol(pExprInfo, num, pGroupInfo, pInfo);
4623 4624 4625
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
H
Haojun Liao 已提交
4626

L
Liu Jicong 已提交
4627 4628 4629 4630 4631
  //  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 已提交
4632

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

L
Liu Jicong 已提交
4635
  pOperator->name = "SortedMerge";
X
Xiaoyu Wang 已提交
4636
  // pOperator->operatorType = OP_SortedMerge;
4637
  pOperator->blockingOptr = true;
L
Liu Jicong 已提交
4638 4639 4640 4641
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
  pOperator->numOfOutput = num;
  pOperator->pExpr = pExprInfo;
H
Haojun Liao 已提交
4642

L
Liu Jicong 已提交
4643 4644 4645
  pOperator->pTaskInfo = pTaskInfo;
  pOperator->getNextFn = doSortedMerge;
  pOperator->closeFn = destroySortedMergeOperatorInfo;
H
Haojun Liao 已提交
4646

4647 4648 4649
  code = appendDownstream(pOperator, downstream, numOfDownstream);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
4650
  }
H
Haojun Liao 已提交
4651

4652
  return pOperator;
H
Haojun Liao 已提交
4653

L
Liu Jicong 已提交
4654
_error:
4655
  if (pInfo != NULL) {
H
Haojun Liao 已提交
4656
    destroySortedMergeOperatorInfo(pInfo, num);
H
Haojun Liao 已提交
4657 4658
  }

wafwerar's avatar
wafwerar 已提交
4659 4660
  taosMemoryFreeClear(pInfo);
  taosMemoryFreeClear(pOperator);
4661 4662
  terrno = TSDB_CODE_QRY_OUT_OF_MEMORY;
  return NULL;
H
Haojun Liao 已提交
4663 4664
}

L
Liu Jicong 已提交
4665
static SSDataBlock* doSort(SOperatorInfo* pOperator, bool* newgroup) {
4666 4667 4668 4669
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

L
Liu Jicong 已提交
4670
  SExecTaskInfo*     pTaskInfo = pOperator->pTaskInfo;
H
Haojun Liao 已提交
4671 4672
  SSortOperatorInfo* pInfo = pOperator->info;

H
Haojun Liao 已提交
4673
  if (pOperator->status == OP_RES_TO_RETURN) {
H
Haojun Liao 已提交
4674
    return getSortedBlockData(pInfo->pSortHandle, pInfo->pDataBlock, pInfo->numOfRowsInRes);
H
Haojun Liao 已提交
4675 4676
  }

4677
  int32_t numOfBufPage = pInfo->sortBufSize / pInfo->bufPageSize;
4678
  pInfo->pSortHandle = tsortCreateSortHandle(pInfo->pSortInfo, pInfo->inputSlotMap, SORT_SINGLESOURCE_SORT, pInfo->bufPageSize, numOfBufPage,
H
Haojun Liao 已提交
4679
                                             pInfo->pDataBlock, pTaskInfo->id.str);
4680

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

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

H
Haojun Liao 已提交
4687
  int32_t code = tsortOpen(pInfo->pSortHandle);
4688
  taosMemoryFreeClear(ps);
4689
  if (code != TSDB_CODE_SUCCESS) {
4690
    longjmp(pTaskInfo->env, terrno);
4691
  }
4692

H
Haojun Liao 已提交
4693
  pOperator->status = OP_RES_TO_RETURN;
H
Haojun Liao 已提交
4694
  return getSortedBlockData(pInfo->pSortHandle, pInfo->pDataBlock, pInfo->numOfRowsInRes);
4695 4696
}

4697
SOperatorInfo* createSortOperatorInfo(SOperatorInfo* downstream, SSDataBlock* pResBlock, SArray* pSortInfo, SArray* pIndexMap, SExecTaskInfo* pTaskInfo) {
H
Haojun Liao 已提交
4698
  SSortOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SSortOperatorInfo));
L
Liu Jicong 已提交
4699
  SOperatorInfo*     pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
4700 4701 4702
  int32_t rowSize = pResBlock->info.rowSize;

  if (pInfo == NULL || pOperator == NULL || rowSize > 100 * 1024 * 1024) {
wafwerar's avatar
wafwerar 已提交
4703 4704
    taosMemoryFreeClear(pInfo);
    taosMemoryFreeClear(pOperator);
H
Haojun Liao 已提交
4705 4706 4707
    terrno = TSDB_CODE_QRY_OUT_OF_MEMORY;
    return NULL;
  }
4708

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

wmmhello's avatar
wmmhello 已提交
4711
  pInfo->sortBufSize = pInfo->bufPageSize * 16;  // TODO dynamic set the available sort buffer
L
Liu Jicong 已提交
4712 4713 4714
  pInfo->numOfRowsInRes = 1024;
  pInfo->pDataBlock = pResBlock;
  pInfo->pSortInfo = pSortInfo;
4715
  pInfo->inputSlotMap = pIndexMap;
H
Haojun Liao 已提交
4716

H
Haojun Liao 已提交
4717
  pOperator->name         = "SortOperator";
L
Liu Jicong 已提交
4718 4719
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_SORT;
  pOperator->blockingOptr = true;
H
Haojun Liao 已提交
4720 4721
  pOperator->status       = OP_NOT_OPENED;
  pOperator->info         = pInfo;
4722

H
Haojun Liao 已提交
4723 4724 4725
  pOperator->pTaskInfo    = pTaskInfo;
  pOperator->getNextFn    = doSort;
  pOperator->closeFn      = destroyOrderOperatorInfo;
4726

4727
  int32_t code = appendDownstream(pOperator, &downstream, 1);
4728
  return pOperator;
H
Haojun Liao 已提交
4729 4730 4731 4732 4733 4734

  _error:
  pTaskInfo->code = TSDB_CODE_OUT_OF_MEMORY;
  taosMemoryFree(pInfo);
  taosMemoryFree(pOperator);
  return NULL;
4735 4736
}

L
Liu Jicong 已提交
4737
static int32_t getTableScanOrder(STableScanInfo* pTableScanInfo) { return pTableScanInfo->order; }
4738 4739

// this is a blocking operator
L
Liu Jicong 已提交
4740
static int32_t doOpenAggregateOptr(SOperatorInfo* pOperator) {
H
Haojun Liao 已提交
4741 4742
  if (OPTR_IS_OPENED(pOperator)) {
    return TSDB_CODE_SUCCESS;
4743 4744
  }

H
Haojun Liao 已提交
4745
  SExecTaskInfo*    pTaskInfo = pOperator->pTaskInfo;
4746
  SAggOperatorInfo* pAggInfo = pOperator->info;
H
Haojun Liao 已提交
4747

H
Haojun Liao 已提交
4748
  SOptrBasicInfo*   pInfo = &pAggInfo->binfo;
4749

H
Haojun Liao 已提交
4750
  int32_t        order = TSDB_ORDER_ASC;
H
Haojun Liao 已提交
4751
  SOperatorInfo* downstream = pOperator->pDownstream[0];
4752

H
Haojun Liao 已提交
4753 4754
  bool newgroup = true;
  while (1) {
H
Haojun Liao 已提交
4755
    publishOperatorProfEvent(downstream, QUERY_PROF_BEFORE_OPERATOR_EXEC);
H
Haojun Liao 已提交
4756
    SSDataBlock* pBlock = downstream->getNextFn(downstream, &newgroup);
H
Haojun Liao 已提交
4757
    publishOperatorProfEvent(downstream, QUERY_PROF_AFTER_OPERATOR_EXEC);
4758 4759 4760 4761

    if (pBlock == NULL) {
      break;
    }
H
Haojun Liao 已提交
4762 4763 4764
    //    if (pAggInfo->current != NULL) {
    //      setTagValue(pOperator, pAggInfo->current->pTable, pInfo->pCtx, pOperator->numOfOutput);
    //    }
4765

4766 4767 4768 4769 4770
    // there is an scalar expression that needs to be calculated before apply the group aggregation.
    if (pAggInfo->pScalarExprInfo != NULL) {
      projectApplyFunctions(pAggInfo->pScalarExprInfo, pBlock, pBlock, pAggInfo->pScalarCtx, pAggInfo->numOfScalarExpr, NULL);
    }

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

4776
#if 0   // test for encode/decode result info
4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787
    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);
      }
4788
    }
4789
#endif
4790 4791
  }

H
Haojun Liao 已提交
4792 4793 4794
  closeAllResultRows(&pAggInfo->binfo.resultRowInfo);
  finalizeMultiTupleQueryResult(pAggInfo->binfo.pCtx, pOperator->numOfOutput, pAggInfo->aggSup.pResultBuf,
                                &pAggInfo->binfo.resultRowInfo, pAggInfo->binfo.rowCellInfoOffset);
H
Haojun Liao 已提交
4795

H
Haojun Liao 已提交
4796
  initGroupResInfo(&pAggInfo->groupResInfo, &pAggInfo->binfo.resultRowInfo);
H
Haojun Liao 已提交
4797 4798 4799 4800
  OPTR_SET_OPENED(pOperator);
  return TSDB_CODE_SUCCESS;
}

L
Liu Jicong 已提交
4801 4802
static SSDataBlock* getAggregateResult(SOperatorInfo* pOperator, bool* newgroup) {
  SAggOperatorInfo* pAggInfo = pOperator->info;
H
Haojun Liao 已提交
4803 4804 4805 4806 4807 4808
  SOptrBasicInfo*   pInfo = &pAggInfo->binfo;

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

L
Liu Jicong 已提交
4809
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
H
Haojun Liao 已提交
4810 4811 4812 4813 4814
  pTaskInfo->code = pOperator->_openFn(pOperator);
  if (pTaskInfo->code != TSDB_CODE_SUCCESS) {
    return NULL;
  }

H
Haojun Liao 已提交
4815 4816 4817 4818 4819
  blockDataEnsureCapacity(pInfo->pRes, pOperator->resultInfo.capacity);
  toSDatablock(pInfo->pRes, pOperator->resultInfo.capacity, &pAggInfo->groupResInfo, pOperator->pExpr, pAggInfo->aggSup.pResultBuf, pInfo->rowCellInfoOffset);
  if (pInfo->pRes->info.rows == 0 || !hasRemainDataInCurrentGroup(&pAggInfo->groupResInfo)) {
    doSetOperatorCompleted(pOperator);
  }
4820

H
Haojun Liao 已提交
4821
  doSetOperatorCompleted(pOperator);
L
Liu Jicong 已提交
4822
  return (blockDataGetNumOfRows(pInfo->pRes) != 0) ? pInfo->pRes : NULL;
4823 4824
}

4825
void aggEncodeResultRow(SOperatorInfo* pOperator, SAggSupporter *pSup, SOptrBasicInfo *pInfo, char **result, int32_t *length) {
wmmhello's avatar
wmmhello 已提交
4826
  int32_t size = taosHashGetSize(pSup->pResultRowHashTable);
4827
  size_t  keyLen = sizeof(uint64_t) * 2;  // estimate the key length
wmmhello's avatar
wmmhello 已提交
4828
  int32_t totalSize = sizeof(int32_t) + size * (sizeof(int32_t) + keyLen + sizeof(int32_t) + pSup->resultRowSize);
wafwerar's avatar
wafwerar 已提交
4829
  *result = taosMemoryCalloc(1, totalSize);
L
Liu Jicong 已提交
4830
  if (*result == NULL) {
4831
    longjmp(pOperator->pTaskInfo->env, TSDB_CODE_OUT_OF_MEMORY);
wmmhello's avatar
wmmhello 已提交
4832 4833 4834
  }
  *(int32_t*)(*result) = size;
  int32_t offset = sizeof(int32_t);
4835 4836

  // prepare memory
4837
  SResultRowPosition* pos = &pInfo->resultRowInfo.cur;
4838 4839 4840 4841 4842
  void* pPage = getBufPage(pSup->pResultBuf, pos->pageId);
  SResultRow* pRow = (SResultRow*)((char*)pPage + pos->offset);
  setBufPageDirty(pPage, true);
  releaseBufPage(pSup->pResultBuf, pPage);

L
Liu Jicong 已提交
4843
  void*   pIter = taosHashIterate(pSup->pResultRowHashTable, NULL);
wmmhello's avatar
wmmhello 已提交
4844
  while (pIter) {
L
Liu Jicong 已提交
4845
    void*        key = taosHashGetKey(pIter, &keyLen);
4846
    SResultRowPosition* p1 = (SResultRowPosition*)pIter;
4847

4848 4849
    pPage = (SFilePage*) getBufPage(pSup->pResultBuf, p1->pageId);
    pRow = (SResultRow*)((char*)pPage + p1->offset);
4850 4851
    setBufPageDirty(pPage, true);
    releaseBufPage(pSup->pResultBuf, pPage);
wmmhello's avatar
wmmhello 已提交
4852 4853 4854

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

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

L
Liu Jicong 已提交
4881
  if (length) {
wmmhello's avatar
wmmhello 已提交
4882 4883 4884 4885 4886
    *length = offset;
  }
  return;
}

4887
bool aggDecodeResultRow(SOperatorInfo* pOperator, SAggSupporter *pSup, SOptrBasicInfo *pInfo, char* result, int32_t length) {
L
Liu Jicong 已提交
4888
  if (!result || length <= 0) {
wmmhello's avatar
wmmhello 已提交
4889 4890 4891 4892 4893 4894 4895
    return false;
  }

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

  int32_t offset = sizeof(int32_t);
L
Liu Jicong 已提交
4896
  while (count-- > 0 && length > offset) {
wmmhello's avatar
wmmhello 已提交
4897 4898 4899
    int32_t keyLen = *(int32_t*)(result + offset);
    offset += sizeof(int32_t);

L
Liu Jicong 已提交
4900 4901 4902
    uint64_t    tableGroupId = *(uint64_t*)(result + offset);
    SResultRow* resultRow = getNewResultRow_rv(pSup->pResultBuf, tableGroupId, pSup->resultRowSize);
    if (!resultRow) {
4903
      longjmp(pOperator->pTaskInfo->env, TSDB_CODE_TSC_INVALID_INPUT);
wmmhello's avatar
wmmhello 已提交
4904
    }
4905

wmmhello's avatar
wmmhello 已提交
4906
    // add a new result set for a new group
4907 4908
    SResultRowPosition pos = {.pageId = resultRow->pageId, .offset = resultRow->offset};
    taosHashPut(pSup->pResultRowHashTable, result + offset, keyLen, &pos, sizeof(SResultRowPosition));
wmmhello's avatar
wmmhello 已提交
4909 4910 4911

    offset += keyLen;
    int32_t valueLen = *(int32_t*)(result + offset);
L
Liu Jicong 已提交
4912
    if (valueLen != pSup->resultRowSize) {
4913
      longjmp(pOperator->pTaskInfo->env, TSDB_CODE_TSC_INVALID_INPUT);
wmmhello's avatar
wmmhello 已提交
4914 4915 4916 4917 4918 4919 4920 4921 4922 4923
    }
    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);
4924
    prepareResultListBuffer(&pInfo->resultRowInfo, pOperator->pTaskInfo->env);
4925
//    pInfo->resultRowInfo.cur = pInfo->resultRowInfo.size;
4926
    pInfo->resultRowInfo.pPosition[pInfo->resultRowInfo.size++] = (SResultRowPosition) {.pageId = resultRow->pageId, .offset = resultRow->offset};
4927
    pInfo->resultRowInfo.cur = (SResultRowPosition) {.pageId = resultRow->pageId, .offset = resultRow->offset};
wmmhello's avatar
wmmhello 已提交
4928 4929
  }

L
Liu Jicong 已提交
4930
  if (offset != length) {
4931
    longjmp(pOperator->pTaskInfo->env, TSDB_CODE_TSC_INVALID_INPUT);
wmmhello's avatar
wmmhello 已提交
4932 4933 4934 4935
  }
  return true;
}

L
Liu Jicong 已提交
4936
static SSDataBlock* doProjectOperation(SOperatorInfo* pOperator, bool* newgroup) {
4937
  SProjectOperatorInfo* pProjectInfo = pOperator->info;
L
Liu Jicong 已提交
4938
  SOptrBasicInfo*       pInfo = &pProjectInfo->binfo;
4939 4940

  SSDataBlock* pRes = pInfo->pRes;
4941
  blockDataCleanup(pRes);
4942 4943 4944 4945

  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }
4946
  
H
Haojun Liao 已提交
4947
#if 0
4948 4949 4950 4951 4952 4953
  if (pProjectInfo->existDataBlock) {  // TODO refactor
    SSDataBlock* pBlock = pProjectInfo->existDataBlock;
    pProjectInfo->existDataBlock = NULL;
    *newgroup = true;

    // todo dynamic set tags
L
Liu Jicong 已提交
4954 4955 4956
    //    if (pTableQueryInfo != NULL) {
    //      setTagValue(pOperator, pTableQueryInfo->pTable, pInfo->pCtx, pOperator->numOfOutput);
    //    }
4957 4958

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

H
Haojun Liao 已提交
4961
    blockDataEnsureCapacity(pInfo->pRes, pBlock->info.rows);
4962
    projectApplyFunctions(pOperator->pExpr, pInfo->pRes, pBlock, pInfo->pCtx, pOperator->numOfOutput);
L
Liu Jicong 已提交
4963
    if (pRes->info.rows >= pProjectInfo->binfo.capacity * 0.8) {
4964 4965 4966 4967 4968
      copyTsColoum(pRes, pInfo->pCtx, pOperator->numOfOutput);
      resetResultRowEntryResult(pInfo->pCtx, pOperator->numOfOutput);
      return pRes;
    }
  }
H
Haojun Liao 已提交
4969
#endif
4970

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

L
Liu Jicong 已提交
4973
  while (1) {
4974 4975
    bool prevVal = *newgroup;

H
Haojun Liao 已提交
4976
    // The downstream exec may change the value of the newgroup, so use a local variable instead.
H
Haojun Liao 已提交
4977 4978 4979
    publishOperatorProfEvent(downstream, QUERY_PROF_BEFORE_OPERATOR_EXEC);
    SSDataBlock* pBlock = downstream->getNextFn(downstream, newgroup);
    publishOperatorProfEvent(downstream, QUERY_PROF_AFTER_OPERATOR_EXEC);
4980 4981 4982

    if (pBlock == NULL) {
      *newgroup = prevVal;
4983
      setTaskStatus(pOperator->pTaskInfo, TASK_COMPLETED);
4984 4985 4986 4987 4988 4989 4990 4991
      break;
    }

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

    // todo dynamic set tags
H
Haojun Liao 已提交
4998 4999 5000 5001
    //    STableQueryInfo* pTableQueryInfo = pRuntimeEnv->current;
    //    if (pTableQueryInfo != NULL) {
    //      setTagValue(pOperator, pTableQueryInfo->pTable, pInfo->pCtx, pOperator->numOfOutput);
    //    }
5002 5003

    // the pDataBlock are always the same one, no need to call this again
5004
    setInputDataBlock(pOperator, pInfo->pCtx, pBlock, TSDB_ORDER_ASC, false);
5005 5006
    blockDataEnsureCapacity(pInfo->pRes, pInfo->pRes->info.rows + pBlock->info.rows);

H
Haojun Liao 已提交
5007
    projectApplyFunctions(pOperator->pExpr, pInfo->pRes, pBlock, pInfo->pCtx, pOperator->numOfOutput, pProjectInfo->pPseudoColInfo);
H
Haojun Liao 已提交
5008

H
Haojun Liao 已提交
5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040
    if (pProjectInfo->curSOffset > 0) {
      if (pProjectInfo->groupId == 0) {  // it is the first group
        pProjectInfo->groupId = pBlock->info.groupId;
        blockDataCleanup(pInfo->pRes);
        continue;
      } else if (pProjectInfo->groupId != pBlock->info.groupId) {
        pProjectInfo->curSOffset -= 1;

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

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

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

    pProjectInfo->groupId = pBlock->info.groupId;

H
Haojun Liao 已提交
5041
    // todo extract method
H
Haojun Liao 已提交
5042 5043 5044 5045 5046 5047 5048 5049 5050
    if (pProjectInfo->curOffset < pInfo->pRes->info.rows && pProjectInfo->curOffset > 0) {
      blockDataTrimFirstNRows(pInfo->pRes, pProjectInfo->curOffset);
      pProjectInfo->curOffset = 0;
    } else if (pProjectInfo->curOffset >= pInfo->pRes->info.rows) {
      pProjectInfo->curOffset -= pInfo->pRes->info.rows;
      blockDataCleanup(pInfo->pRes);
      continue;
    }

5051
    if (pRes->info.rows >= pOperator->resultInfo.threshold) {
5052 5053 5054
      break;
    }
  }
H
Haojun Liao 已提交
5055
  
H
Haojun Liao 已提交
5056
  if (pProjectInfo->limit.limit > 0 && pProjectInfo->curOutput + pInfo->pRes->info.rows >= pProjectInfo->limit.limit) {
H
Haojun Liao 已提交
5057 5058 5059 5060
    pInfo->pRes->info.rows = (int32_t)(pProjectInfo->limit.limit - pProjectInfo->curOutput);
  }

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

L
Liu Jicong 已提交
5062 5063
  //  copyTsColoum(pRes, pInfo->pCtx, pOperator->numOfOutput);
  return (pInfo->pRes->info.rows > 0) ? pInfo->pRes : NULL;
5064 5065
}

L
Liu Jicong 已提交
5066
static int32_t doOpenIntervalAgg(SOperatorInfo* pOperator) {
5067 5068
  if (OPTR_IS_OPENED(pOperator)) {
    return TSDB_CODE_SUCCESS;
5069 5070
  }

5071
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
H
Haojun Liao 已提交
5072
  STableIntervalOperatorInfo* pInfo = pOperator->info;
5073

5074
  int32_t order = TSDB_ORDER_ASC;
5075 5076
  //  STimeWindow win = {0};
  bool newgroup = false;
H
Haojun Liao 已提交
5077
  SOperatorInfo* downstream = pOperator->pDownstream[0];
5078

5079
  while (1) {
H
Haojun Liao 已提交
5080
    publishOperatorProfEvent(downstream, QUERY_PROF_BEFORE_OPERATOR_EXEC);
5081
    SSDataBlock* pBlock = downstream->getNextFn(downstream, &newgroup);
H
Haojun Liao 已提交
5082
    publishOperatorProfEvent(downstream, QUERY_PROF_AFTER_OPERATOR_EXEC);
5083 5084 5085 5086 5087

    if (pBlock == NULL) {
      break;
    }

5088
    //    setTagValue(pOperator, pRuntimeEnv->current->pTable, pInfo->pCtx, pOperator->numOfOutput);
5089
    // the pDataBlock are always the same one, no need to call this again
5090
    setInputDataBlock(pOperator, pInfo->binfo.pCtx, pBlock, order, true);
5091 5092 5093
    STableQueryInfo* pTableQueryInfo = pInfo->pCurrent;

    setIntervalQueryRange(pTableQueryInfo, pBlock->info.window.skey, &pTaskInfo->window);
H
Haojun Liao 已提交
5094
    hashIntervalAgg(pOperator, &pInfo->binfo.resultRowInfo, pBlock, 0);
5095

5096
#if 0   // test for encode/decode result info
5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107
    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);
      }
5108
    }
5109
#endif
5110 5111
  }

H
Haojun Liao 已提交
5112
  closeAllResultRows(&pInfo->binfo.resultRowInfo);
L
Liu Jicong 已提交
5113 5114
  finalizeMultiTupleQueryResult(pInfo->binfo.pCtx, pOperator->numOfOutput, pInfo->aggSup.pResultBuf,
                                &pInfo->binfo.resultRowInfo, pInfo->binfo.rowCellInfoOffset);
5115

H
Haojun Liao 已提交
5116
  initGroupResInfo(&pInfo->groupResInfo, &pInfo->binfo.resultRowInfo);
5117 5118 5119 5120
  OPTR_SET_OPENED(pOperator);
  return TSDB_CODE_SUCCESS;
}

L
Liu Jicong 已提交
5121
static SSDataBlock* doBuildIntervalResult(SOperatorInfo* pOperator, bool* newgroup) {
5122
  STableIntervalOperatorInfo* pInfo = pOperator->info;
L
Liu Jicong 已提交
5123
  SExecTaskInfo*              pTaskInfo = pOperator->pTaskInfo;
5124 5125 5126 5127 5128

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

5129 5130
  if (pInfo->execModel == OPTR_EXEC_MODEL_STREAM) {
    return pOperator->getStreamResFn(pOperator, newgroup);
5131 5132 5133 5134 5135
  } else {
    pTaskInfo->code = pOperator->_openFn(pOperator);
    if (pTaskInfo->code != TSDB_CODE_SUCCESS) {
      return NULL;
    }
5136

5137 5138
    blockDataEnsureCapacity(pInfo->binfo.pRes, pOperator->resultInfo.capacity);
    toSDatablock(pInfo->binfo.pRes, pOperator->resultInfo.capacity, &pInfo->groupResInfo, pOperator->pExpr,
5139
                 pInfo->aggSup.pResultBuf, pInfo->binfo.rowCellInfoOffset);
5140

5141 5142 5143
    if (pInfo->binfo.pRes->info.rows == 0 || !hasRemainDataInCurrentGroup(&pInfo->groupResInfo)) {
      doSetOperatorCompleted(pOperator);
    }
5144

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

5149
static SSDataBlock* doStreamIntervalAgg(SOperatorInfo *pOperator, bool* newgroup) {
5150 5151 5152 5153 5154 5155 5156 5157
  STableIntervalOperatorInfo* pInfo = pOperator->info;
  int32_t order = TSDB_ORDER_ASC;

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

  if (pOperator->status == OP_RES_TO_RETURN) {
5158
    toSDatablock(pInfo->binfo.pRes, pOperator->resultInfo.capacity, &pInfo->groupResInfo, pOperator->pExpr, pInfo->aggSup.pResultBuf, pInfo->binfo.rowCellInfoOffset);
5159 5160 5161
    if (pInfo->binfo.pRes->info.rows == 0 || !hasRemainDataInCurrentGroup(&pInfo->groupResInfo)) {
      pOperator->status = OP_EXEC_DONE;
    }
5162
    return pInfo->binfo.pRes->info.rows == 0 ? NULL : pInfo->binfo.pRes;
5163 5164 5165
  }

  //  STimeWindow win = {0};
5166
  *newgroup = false;
5167 5168 5169 5170 5171 5172
  SOperatorInfo* downstream = pOperator->pDownstream[0];

  SArray* pUpdated = NULL;

  while (1) {
    publishOperatorProfEvent(downstream, QUERY_PROF_BEFORE_OPERATOR_EXEC);
5173
    SSDataBlock* pBlock = downstream->getNextFn(downstream, newgroup);
5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184
    publishOperatorProfEvent(downstream, QUERY_PROF_AFTER_OPERATOR_EXEC);

    if (pBlock == NULL) {
      break;
    }

    // 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.

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

  finalizeUpdatedResult(pInfo->binfo.pCtx, pOperator->numOfOutput, pInfo->aggSup.pResultBuf, pUpdated, pInfo->binfo.rowCellInfoOffset);

H
Haojun Liao 已提交
5191
  initMultiResInfoFromArrayList(&pInfo->groupResInfo, pUpdated);
5192 5193
  blockDataEnsureCapacity(pInfo->binfo.pRes, pOperator->resultInfo.capacity);
  toSDatablock(pInfo->binfo.pRes, pOperator->resultInfo.capacity, &pInfo->groupResInfo, pOperator->pExpr, pInfo->aggSup.pResultBuf, pInfo->binfo.rowCellInfoOffset);
5194 5195 5196 5197 5198 5199 5200 5201

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

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

static SSDataBlock* doAllIntervalAgg(SOperatorInfo *pOperator, bool* newgroup) {
5202 5203 5204 5205
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

5206
  STimeSliceOperatorInfo* pSliceInfo = pOperator->info;
5207
  if (pOperator->status == OP_RES_TO_RETURN) {
L
Liu Jicong 已提交
5208
    //    toSDatablock(&pRuntimeEnv->groupResInfo, pRuntimeEnv, pIntervalInfo->pRes);
5209
    if (pSliceInfo->binfo.pRes->info.rows == 0 || !hasRemainDataInCurrentGroup(&pSliceInfo->groupResInfo)) {
5210 5211 5212
      doSetOperatorCompleted(pOperator);
    }

5213
    return pSliceInfo->binfo.pRes;
5214 5215
  }

5216 5217
  int32_t     order = TSDB_ORDER_ASC;
//  STimeWindow win = pQueryAttr->window;
H
Haojun Liao 已提交
5218
  SOperatorInfo* downstream = pOperator->pDownstream[0];
5219

L
Liu Jicong 已提交
5220
  while (1) {
H
Haojun Liao 已提交
5221
    publishOperatorProfEvent(downstream, QUERY_PROF_BEFORE_OPERATOR_EXEC);
H
Haojun Liao 已提交
5222
    SSDataBlock* pBlock = downstream->getNextFn(downstream, newgroup);
H
Haojun Liao 已提交
5223
    publishOperatorProfEvent(downstream, QUERY_PROF_AFTER_OPERATOR_EXEC);
5224 5225 5226 5227
    if (pBlock == NULL) {
      break;
    }

L
Liu Jicong 已提交
5228
    //    setTagValue(pOperator, pRuntimeEnv->current->pTable, pIntervalInfo->pCtx, pOperator->numOfOutput);
5229
    // the pDataBlock are always the same one, no need to call this again
5230
    setInputDataBlock(pOperator, pSliceInfo->binfo.pCtx, pBlock, order, true);
5231
//    hashAllIntervalAgg(pOperator, &pSliceInfo->binfo.resultRowInfo, pBlock, 0);
5232 5233 5234 5235
  }

  // restore the value
  pOperator->status = OP_RES_TO_RETURN;
5236
  closeAllResultRows(&pSliceInfo->binfo.resultRowInfo);
5237
  setTaskStatus(pOperator->pTaskInfo, TASK_COMPLETED);
5238
  finalizeQueryResult(pSliceInfo->binfo.pCtx, pOperator->numOfOutput);
5239

5240 5241
  initGroupResInfo(&pSliceInfo->groupResInfo, &pSliceInfo->binfo.resultRowInfo);
  //  toSDatablock(&pRuntimeEnv->groupResInfo, pRuntimeEnv, pSliceInfo->pRes);
5242

5243
  if (pSliceInfo->binfo.pRes->info.rows == 0 || !hasRemainDataInCurrentGroup(&pSliceInfo->groupResInfo)) {
5244 5245 5246
    pOperator->status = OP_EXEC_DONE;
  }

5247
  return pSliceInfo->binfo.pRes->info.rows == 0 ? NULL : pSliceInfo->binfo.pRes;
5248 5249
}

L
Liu Jicong 已提交
5250
static SSDataBlock* doSTableIntervalAgg(SOperatorInfo* pOperator, bool* newgroup) {
5251 5252 5253 5254
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

5255
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
5256

5257
  STableIntervalOperatorInfo* pInfo = pOperator->info;
5258 5259
  if (pOperator->status == OP_RES_TO_RETURN) {
    int64_t st = taosGetTimestampUs();
5260
    if (pInfo->binfo.pRes->info.rows == 0 || !hasRemainDataInCurrentGroup(&pInfo->groupResInfo)) {
5261 5262
      doSetOperatorCompleted(pOperator);
    }
5263 5264

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

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

L
Liu Jicong 已提交
5269
  while (1) {
H
Haojun Liao 已提交
5270
    publishOperatorProfEvent(downstream, QUERY_PROF_BEFORE_OPERATOR_EXEC);
H
Haojun Liao 已提交
5271
    SSDataBlock* pBlock = downstream->getNextFn(downstream, newgroup);
H
Haojun Liao 已提交
5272
    publishOperatorProfEvent(downstream, QUERY_PROF_AFTER_OPERATOR_EXEC);
5273 5274 5275 5276 5277 5278

    if (pBlock == NULL) {
      break;
    }

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

5283
    setIntervalQueryRange(pTableQueryInfo, pBlock->info.window.skey, &pTaskInfo->window);
5284
//    hashIntervalAgg(pOperator, &pTableQueryInfo->resInfo, pBlock, pBlock->info.groupId);
5285 5286
  }

5287 5288 5289
  closeAllResultRows(&pInfo->binfo.resultRowInfo);
  finalizeMultiTupleQueryResult(pInfo->binfo.pCtx, pOperator->numOfOutput, pInfo->aggSup.pResultBuf,
                                &pInfo->binfo.resultRowInfo, pInfo->binfo.rowCellInfoOffset);
5290

5291 5292 5293
  initGroupResInfo(&pInfo->groupResInfo, &pInfo->binfo.resultRowInfo);
  OPTR_SET_OPENED(pOperator);

5294 5295
  blockDataEnsureCapacity(pInfo->binfo.pRes, pOperator->resultInfo.capacity);
  toSDatablock(pInfo->binfo.pRes, pOperator->resultInfo.capacity, &pInfo->groupResInfo, pOperator->pExpr,
5296 5297 5298 5299
               pInfo->aggSup.pResultBuf, pInfo->binfo.rowCellInfoOffset);

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

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

5305 5306
static void doStateWindowAggImpl(SOperatorInfo* pOperator, SStateWindowOperatorInfo* pInfo, SSDataBlock* pBlock) {
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
5307 5308
  SOptrBasicInfo* pBInfo = &pInfo->binfo;

5309 5310
  SColumnInfoData* pStateColInfoData = taosArrayGet(pBlock->pDataBlock, pInfo->colIndex);
  int64_t gid = pBlock->info.groupId;
5311

5312 5313 5314 5315 5316 5317 5318 5319
  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;
5320

5321 5322 5323 5324 5325
  SWindowRowsSup* pRowSup = &pInfo->winSup;
  pRowSup->numOfRows = 0;
  
  for (int32_t j = 0; j < pBlock->info.rows; ++j) {
    if (colDataIsNull(pStateColInfoData, pBlock->info.rows, j, pBlock->pBlockAgg)) {
5326 5327
      continue;
    }
5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340

    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;
5341
      }
5342
    } else {  // a new state window started
5343
      SResultRow* pResult = NULL;
5344 5345 5346 5347 5348 5349 5350

      // 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,
                                               &pResult, gid, pInfo->binfo.pCtx, numOfOutput, pInfo->binfo.rowCellInfoOffset, &pInfo->aggSup, pTaskInfo);
5351
      if (ret != TSDB_CODE_SUCCESS) {  // null data, too many state code
5352
        longjmp(pTaskInfo->env, TSDB_CODE_QRY_APP_ERROR);
5353 5354
      }

5355 5356
      updateTimeWindowInfo(&pInfo->twAggSup.timeWindowData, &window, false);
      doApplyFunctions(pInfo->binfo.pCtx, &window, &pInfo->twAggSup.timeWindowData, pRowSup->startRowIndex, pRowSup->numOfRows, NULL, pBlock->info.rows, numOfOutput, TSDB_ORDER_ASC);
5357 5358 5359 5360

      // here we start a new session window
      doKeepNewWindowStartInfo(pRowSup, tsList, j);
      doKeepTuple(pRowSup, tsList[j]);
5361 5362 5363 5364
    }
  }

  SResultRow* pResult = NULL;
5365 5366 5367
  pRowSup->win.ekey = tsList[pBlock->info.rows - 1];
  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);
5368
  if (ret != TSDB_CODE_SUCCESS) {  // null data, too many state code
5369
    longjmp(pTaskInfo->env, TSDB_CODE_QRY_APP_ERROR);
5370 5371
  }

5372 5373
  updateTimeWindowInfo(&pInfo->twAggSup.timeWindowData, &pRowSup->win, false);
  doApplyFunctions(pInfo->binfo.pCtx, &pRowSup->win, &pInfo->twAggSup.timeWindowData, pRowSup->startRowIndex, pRowSup->numOfRows, NULL, pBlock->info.rows, numOfOutput, TSDB_ORDER_ASC);
5374 5375
}

L
Liu Jicong 已提交
5376
static SSDataBlock* doStateWindowAgg(SOperatorInfo* pOperator, bool* newgroup) {
5377 5378 5379 5380
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

5381
  SStateWindowOperatorInfo* pInfo = pOperator->info;
H
Haojun Liao 已提交
5382
  SExecTaskInfo*  pTaskInfo = pOperator->pTaskInfo;
5383
  SOptrBasicInfo* pBInfo    = &pInfo->binfo;
5384 5385

  if (pOperator->status == OP_RES_TO_RETURN) {
5386
    toSDatablock(pBInfo->pRes, pOperator->resultInfo.capacity, &pInfo->groupResInfo, pOperator->pExpr, pInfo->aggSup.pResultBuf, pBInfo->rowCellInfoOffset);
5387 5388 5389 5390
    if (pBInfo->pRes->info.rows == 0 || !hasRemainDataInCurrentGroup(&pInfo->groupResInfo)) {
      doSetOperatorCompleted(pOperator);
      return NULL;
    }
5391 5392 5393 5394

    return pBInfo->pRes;
  }

H
Haojun Liao 已提交
5395 5396 5397
  int32_t        order = TSDB_ORDER_ASC;
  STimeWindow    win = pTaskInfo->window;

H
Haojun Liao 已提交
5398
  SOperatorInfo* downstream = pOperator->pDownstream[0];
5399
  while (1) {
H
Haojun Liao 已提交
5400
    publishOperatorProfEvent(downstream, QUERY_PROF_BEFORE_OPERATOR_EXEC);
H
Haojun Liao 已提交
5401
    SSDataBlock* pBlock = downstream->getNextFn(downstream, newgroup);
H
Haojun Liao 已提交
5402
    publishOperatorProfEvent(downstream, QUERY_PROF_AFTER_OPERATOR_EXEC);
5403 5404 5405 5406

    if (pBlock == NULL) {
      break;
    }
H
Haojun Liao 已提交
5407

5408
    setInputDataBlock(pOperator, pBInfo->pCtx, pBlock, order, true);
5409
    doStateWindowAggImpl(pOperator, pInfo, pBlock);
5410 5411 5412 5413
  }

  pOperator->status = OP_RES_TO_RETURN;
  closeAllResultRows(&pBInfo->resultRowInfo);
5414
  finalizeMultiTupleQueryResult(pBInfo->pCtx, pOperator->numOfOutput, pInfo->aggSup.pResultBuf, &pBInfo->resultRowInfo, pBInfo->rowCellInfoOffset);
5415

5416
  initGroupResInfo(&pInfo->groupResInfo, &pBInfo->resultRowInfo);
5417 5418
  blockDataEnsureCapacity(pBInfo->pRes, pOperator->resultInfo.capacity);
  toSDatablock(pBInfo->pRes, pOperator->resultInfo.capacity, &pInfo->groupResInfo, pOperator->pExpr, pInfo->aggSup.pResultBuf, pBInfo->rowCellInfoOffset);
5419 5420 5421
  if (pBInfo->pRes->info.rows == 0 || !hasRemainDataInCurrentGroup(&pInfo->groupResInfo)) {
    doSetOperatorCompleted(pOperator);
  }
5422

L
Liu Jicong 已提交
5423
  return pBInfo->pRes->info.rows == 0 ? NULL : pBInfo->pRes;
5424 5425
}

L
Liu Jicong 已提交
5426
static SSDataBlock* doSessionWindowAgg(SOperatorInfo* pOperator, bool* newgroup) {
5427 5428 5429 5430
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

5431
  SSessionAggOperatorInfo* pInfo = pOperator->info;
L
Liu Jicong 已提交
5432
  SOptrBasicInfo*          pBInfo = &pInfo->binfo;
5433 5434

  if (pOperator->status == OP_RES_TO_RETURN) {
5435
    toSDatablock(pBInfo->pRes, pOperator->resultInfo.capacity, &pInfo->groupResInfo, pOperator->pExpr, pInfo->aggSup.pResultBuf, pBInfo->rowCellInfoOffset);
5436 5437 5438
    if (pBInfo->pRes->info.rows == 0 || !hasRemainDataInCurrentGroup(&pInfo->groupResInfo)) {
      doSetOperatorCompleted(pOperator);
      return NULL;
5439 5440 5441 5442 5443
    }

    return pBInfo->pRes;
  }

L
Liu Jicong 已提交
5444
  int32_t        order = TSDB_ORDER_ASC;
H
Haojun Liao 已提交
5445
  SOperatorInfo* downstream = pOperator->pDownstream[0];
5446

L
Liu Jicong 已提交
5447
  while (1) {
H
Haojun Liao 已提交
5448
    publishOperatorProfEvent(downstream, QUERY_PROF_BEFORE_OPERATOR_EXEC);
H
Haojun Liao 已提交
5449
    SSDataBlock* pBlock = downstream->getNextFn(downstream, newgroup);
H
Haojun Liao 已提交
5450
    publishOperatorProfEvent(downstream, QUERY_PROF_AFTER_OPERATOR_EXEC);
5451 5452 5453 5454 5455
    if (pBlock == NULL) {
      break;
    }

    // the pDataBlock are always the same one, no need to call this again
5456
    setInputDataBlock(pOperator, pBInfo->pCtx, pBlock, order, true);
5457
    doSessionWindowAggImpl(pOperator, pInfo, pBlock);
5458 5459 5460 5461 5462
  }

  // restore the value
  pOperator->status = OP_RES_TO_RETURN;
  closeAllResultRows(&pBInfo->resultRowInfo);
5463
  finalizeMultiTupleQueryResult(pBInfo->pCtx, pOperator->numOfOutput, pInfo->aggSup.pResultBuf, &pBInfo->resultRowInfo, pBInfo->rowCellInfoOffset);
5464

5465
  initGroupResInfo(&pInfo->groupResInfo, &pBInfo->resultRowInfo);
5466 5467
  blockDataEnsureCapacity(pBInfo->pRes, pOperator->resultInfo.capacity);
  toSDatablock(pBInfo->pRes, pOperator->resultInfo.capacity, &pInfo->groupResInfo, pOperator->pExpr, pInfo->aggSup.pResultBuf, pBInfo->rowCellInfoOffset);
5468 5469
  if (pBInfo->pRes->info.rows == 0 || !hasRemainDataInCurrentGroup(&pInfo->groupResInfo)) {
    doSetOperatorCompleted(pOperator);
5470 5471
  }

L
Liu Jicong 已提交
5472
  return pBInfo->pRes->info.rows == 0 ? NULL : pBInfo->pRes;
5473 5474
}

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

L
Liu Jicong 已提交
5479 5480
  int64_t ekey = Q_STATUS_EQUAL(pTaskInfo->status, TASK_COMPLETED) ? pTaskInfo->window.ekey
                                                                   : pInfo->existNewGroupBlock->info.window.ekey;
5481 5482
  taosResetFillInfo(pInfo->pFillInfo, getFillInfoStart(pInfo->pFillInfo));

5483
  taosFillSetStartInfo(pInfo->pFillInfo, pInfo->existNewGroupBlock->info.rows, ekey);
5484 5485
  taosFillSetInputDataBlock(pInfo->pFillInfo, pInfo->existNewGroupBlock);

H
Haojun Liao 已提交
5486
  doFillTimeIntervalGapsInResults(pInfo->pFillInfo, pInfo->pRes, pResultInfo->capacity, pInfo->p);
5487 5488 5489 5490
  pInfo->existNewGroupBlock = NULL;
  *newgroup = true;
}

L
Liu Jicong 已提交
5491 5492
static void doHandleRemainBlockFromNewGroup(SFillOperatorInfo* pInfo, SResultInfo* pResultInfo, bool* newgroup,
                                            SExecTaskInfo* pTaskInfo) {
5493 5494
  if (taosFillHasMoreResults(pInfo->pFillInfo)) {
    *newgroup = false;
H
Haojun Liao 已提交
5495 5496
    doFillTimeIntervalGapsInResults(pInfo->pFillInfo, pInfo->pRes, (int32_t)pResultInfo->capacity, pInfo->p);
    if (pInfo->pRes->info.rows > pResultInfo->threshold || (!pInfo->multigroupResult)) {
5497 5498 5499 5500 5501 5502
      return;
    }
  }

  // handle the cached new group data block
  if (pInfo->existNewGroupBlock) {
5503
    doHandleRemainBlockForNewGroupImpl(pInfo, pResultInfo, newgroup, pTaskInfo);
5504 5505 5506
  }
}

L
Liu Jicong 已提交
5507 5508 5509
static SSDataBlock* doFill(SOperatorInfo* pOperator, bool* newgroup) {
  SFillOperatorInfo* pInfo = pOperator->info;
  SExecTaskInfo*     pTaskInfo = pOperator->pTaskInfo;
5510

H
Haojun Liao 已提交
5511 5512
  SResultInfo* pResultInfo = &pOperator->resultInfo;
  blockDataCleanup(pInfo->pRes);
5513 5514 5515 5516
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

5517
  doHandleRemainBlockFromNewGroup(pInfo, pResultInfo, newgroup, pTaskInfo);
H
Haojun Liao 已提交
5518 5519 5520
  if (pInfo->pRes->info.rows > pResultInfo->threshold || (!pInfo->multigroupResult && pInfo->pRes->info.rows > 0)) {
    return pInfo->pRes;
  }
5521

H
Haojun Liao 已提交
5522
  SOperatorInfo* pDownstream = pOperator->pDownstream[0];
L
Liu Jicong 已提交
5523
  while (1) {
H
Haojun Liao 已提交
5524 5525 5526
    publishOperatorProfEvent(pDownstream, QUERY_PROF_BEFORE_OPERATOR_EXEC);
    SSDataBlock* pBlock = pDownstream->getNextFn(pDownstream, newgroup);
    publishOperatorProfEvent(pDownstream, QUERY_PROF_AFTER_OPERATOR_EXEC);
5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537

    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
5538
      taosFillSetStartInfo(pInfo->pFillInfo, 0, pTaskInfo->window.ekey);
5539 5540 5541 5542 5543 5544 5545
    } else {
      if (pBlock == NULL) {
        if (pInfo->totalInputRows == 0) {
          pOperator->status = OP_EXEC_DONE;
          return NULL;
        }

5546
        taosFillSetStartInfo(pInfo->pFillInfo, 0, pTaskInfo->window.ekey);
5547 5548 5549 5550 5551 5552 5553
      } else {
        pInfo->totalInputRows += pBlock->info.rows;
        taosFillSetStartInfo(pInfo->pFillInfo, pBlock->info.rows, pBlock->info.window.ekey);
        taosFillSetInputDataBlock(pInfo->pFillInfo, pBlock);
      }
    }

H
Haojun Liao 已提交
5554
    doFillTimeIntervalGapsInResults(pInfo->pFillInfo, pInfo->pRes, pInfo->capacity, pInfo->p);
5555 5556 5557 5558 5559

    // current group has no more result to return
    if (pInfo->pRes->info.rows > 0) {
      // 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
H
Haojun Liao 已提交
5560
      if (pInfo->pRes->info.rows > pResultInfo->threshold || pBlock == NULL || (!pInfo->multigroupResult)) {
5561 5562 5563
        return pInfo->pRes;
      }

5564
      doHandleRemainBlockFromNewGroup(pInfo, pResultInfo, newgroup, pTaskInfo);
H
Haojun Liao 已提交
5565
      if (pInfo->pRes->info.rows > pOperator->resultInfo.threshold || pBlock == NULL) {
5566 5567 5568 5569
        return pInfo->pRes;
      }
    } else if (pInfo->existNewGroupBlock) {  // try next group
      assert(pBlock != NULL);
5570
      doHandleRemainBlockForNewGroupImpl(pInfo, pResultInfo, newgroup, pTaskInfo);
H
Haojun Liao 已提交
5571
      if (pInfo->pRes->info.rows > pResultInfo->threshold) {
5572 5573 5574 5575 5576 5577 5578 5579 5580
        return pInfo->pRes;
      }
    } else {
      return NULL;
    }
  }
}

// todo set the attribute of query scan count
H
Haojun Liao 已提交
5581
static int32_t getNumOfScanTimes(STaskAttr* pQueryAttr) {
L
Liu Jicong 已提交
5582
  for (int32_t i = 0; i < pQueryAttr->numOfOutput; ++i) {
5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596
    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;
  }

H
Haojun Liao 已提交
5597 5598
  if (pOperator->closeFn != NULL) {
    pOperator->closeFn(pOperator->info, pOperator->numOfOutput);
5599 5600
  }

H
Haojun Liao 已提交
5601
  if (pOperator->pDownstream != NULL) {
L
Liu Jicong 已提交
5602
    for (int32_t i = 0; i < pOperator->numOfDownstream; ++i) {
H
Haojun Liao 已提交
5603
      destroyOperatorInfo(pOperator->pDownstream[i]);
5604 5605
    }

wafwerar's avatar
wafwerar 已提交
5606
    taosMemoryFreeClear(pOperator->pDownstream);
H
Haojun Liao 已提交
5607
    pOperator->numOfDownstream = 0;
5608 5609
  }

wafwerar's avatar
wafwerar 已提交
5610 5611
  taosMemoryFreeClear(pOperator->info);
  taosMemoryFreeClear(pOperator);
5612 5613
}

5614
int32_t doInitAggInfoSup(SAggSupporter* pAggSup, SqlFunctionCtx* pCtx, int32_t numOfOutput, size_t keyBufSize, const char* pKey) {
5615 5616
  _hash_fn_t hashFn = taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY);

H
Haojun Liao 已提交
5617
  pAggSup->resultRowSize       = getResultRowSize(pCtx, numOfOutput);
5618
  pAggSup->keyBuf              = taosMemoryCalloc(1, keyBufSize);
5619
  pAggSup->pResultRowHashTable = taosHashInit(10, hashFn, true, HASH_NO_LOCK);
H
Haojun Liao 已提交
5620
  pAggSup->pResultRowListSet   = taosHashInit(100, hashFn, false, HASH_NO_LOCK);
5621 5622 5623
  pAggSup->pResultRowArrayList = taosArrayInit(10, sizeof(SResultRowCell));

  if (pAggSup->keyBuf == NULL || pAggSup->pResultRowArrayList == NULL || pAggSup->pResultRowListSet == NULL ||
5624
      pAggSup->pResultRowHashTable == NULL) {
5625 5626 5627
    return TSDB_CODE_OUT_OF_MEMORY;
  }

H
Haojun Liao 已提交
5628 5629 5630 5631 5632
  int32_t code = createDiskbasedBuf(&pAggSup->pResultBuf, 4096, 4096 * 256, pKey, "/tmp/");
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

5633 5634 5635
  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
5636
static void cleanupAggSup(SAggSupporter* pAggSup) {
wafwerar's avatar
wafwerar 已提交
5637
  taosMemoryFreeClear(pAggSup->keyBuf);
5638 5639 5640
  taosHashCleanup(pAggSup->pResultRowHashTable);
  taosHashCleanup(pAggSup->pResultRowListSet);
  taosArrayDestroy(pAggSup->pResultRowArrayList);
H
Haojun Liao 已提交
5641
  destroyDiskbasedBuf(pAggSup->pResultBuf);
5642 5643
}

H
Haojun Liao 已提交
5644
int32_t initAggInfo(SOptrBasicInfo* pBasicInfo, SAggSupporter* pAggSup, SExprInfo* pExprInfo, int32_t numOfCols,
5645
                    SSDataBlock* pResultBlock, size_t keyBufSize, const char* pkey) {
5646
  pBasicInfo->pCtx = createSqlFunctionCtx(pExprInfo, numOfCols, &pBasicInfo->rowCellInfoOffset);
H
Haojun Liao 已提交
5647 5648
  pBasicInfo->pRes = pResultBlock;

5649
  doInitAggInfoSup(pAggSup, pBasicInfo->pCtx, numOfCols, keyBufSize, pkey);
5650
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
5651 5652
}

5653 5654 5655 5656 5657 5658 5659 5660 5661
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 已提交
5662
static STableQueryInfo* initTableQueryInfo(const STableGroupInfo* pTableGroupInfo) {
wafwerar's avatar
wafwerar 已提交
5663
  STableQueryInfo* pTableQueryInfo = taosMemoryCalloc(pTableGroupInfo->numOfTables, sizeof(STableQueryInfo));
H
Haojun Liao 已提交
5664 5665
  if (pTableQueryInfo == NULL) {
    return NULL;
H
Haojun Liao 已提交
5666
  }
H
Haojun Liao 已提交
5667 5668

  int32_t index = 0;
L
Liu Jicong 已提交
5669
  for (int32_t i = 0; i < taosArrayGetSize(pTableGroupInfo->pGroupList); ++i) {
H
Haojun Liao 已提交
5670
    SArray* pa = taosArrayGetP(pTableGroupInfo->pGroupList, i);
L
Liu Jicong 已提交
5671
    for (int32_t j = 0; j < taosArrayGetSize(pa); ++j) {
H
Haojun Liao 已提交
5672 5673
      STableKeyInfo* pk = taosArrayGet(pa, j);

H
Haojun Liao 已提交
5674
      STableQueryInfo* pTQueryInfo = &pTableQueryInfo[index++];
5675
//      pTQueryInfo->uid = pk->uid;
L
Liu Jicong 已提交
5676
      pTQueryInfo->lastKey = pk->lastKey;
5677
//      pTQueryInfo->groupIndex = i;
H
Haojun Liao 已提交
5678 5679
    }
  }
H
Haojun Liao 已提交
5680 5681

  STimeWindow win = {0, INT64_MAX};
H
Haojun Liao 已提交
5682 5683
  createTableQueryInfo(pTableQueryInfo, false, win);
  return pTableQueryInfo;
H
Haojun Liao 已提交
5684 5685
}

L
Liu Jicong 已提交
5686
SOperatorInfo* createAggregateOperatorInfo(SOperatorInfo* downstream, SExprInfo* pExprInfo, int32_t numOfCols,
5687 5688
                                           SSDataBlock* pResultBlock, SExprInfo* pScalarExprInfo,
                                           int32_t numOfScalarExpr, SExecTaskInfo* pTaskInfo, const STableGroupInfo* pTableGroupInfo) {
wafwerar's avatar
wafwerar 已提交
5689
  SAggOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SAggOperatorInfo));
L
Liu Jicong 已提交
5690
  SOperatorInfo*    pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
5691 5692 5693
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }
H
Haojun Liao 已提交
5694

H
Haojun Liao 已提交
5695
  int32_t numOfRows = 1;
5696
  size_t keyBufSize = sizeof(int64_t) + sizeof(int64_t) + POINTER_BYTES;
5697 5698 5699

  initResultSizeInfo(pOperator, numOfRows);
  int32_t code = initAggInfo(&pInfo->binfo, &pInfo->aggSup, pExprInfo, numOfCols, pResultBlock, keyBufSize, pTaskInfo->id.str);
H
Haojun Liao 已提交
5700 5701
  pInfo->pTableQueryInfo = initTableQueryInfo(pTableGroupInfo);
  if (code != TSDB_CODE_SUCCESS || pInfo->pTableQueryInfo == NULL) {
H
Haojun Liao 已提交
5702 5703
    goto _error;
  }
H
Haojun Liao 已提交
5704

H
Haojun Liao 已提交
5705 5706 5707 5708 5709 5710 5711
  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);

5712 5713
  pInfo->pScalarExprInfo = pScalarExprInfo;
  pInfo->numOfScalarExpr = numOfScalarExpr;
5714 5715 5716
  if (pInfo->pScalarExprInfo != NULL) {
    pInfo->pScalarCtx = createSqlFunctionCtx(pScalarExprInfo, numOfCols, &pInfo->rowCellInfoOffset);
  }
5717

H
Haojun Liao 已提交
5718
  pOperator->name         = "TableAggregate";
X
Xiaoyu Wang 已提交
5719
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_AGG;
5720
  pOperator->blockingOptr = true;
H
Haojun Liao 已提交
5721 5722 5723 5724 5725 5726 5727 5728
  pOperator->status       = OP_NOT_OPENED;
  pOperator->info         = pInfo;
  pOperator->pExpr        = pExprInfo;
  pOperator->numOfOutput  = numOfCols;
  pOperator->pTaskInfo    = pTaskInfo;
  pOperator->_openFn      = doOpenAggregateOptr;
  pOperator->getNextFn    = getAggregateResult;
  pOperator->closeFn      = destroyAggOperatorInfo;
H
Haojun Liao 已提交
5729

wmmhello's avatar
wmmhello 已提交
5730 5731
  pOperator->encodeResultRow = aggEncodeResultRow;
  pOperator->decodeResultRow = aggDecodeResultRow;
H
Haojun Liao 已提交
5732 5733 5734 5735 5736

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

  return pOperator;
L
Liu Jicong 已提交
5739
_error:
H
Haojun Liao 已提交
5740
  destroyAggOperatorInfo(pInfo, numOfCols);
wafwerar's avatar
wafwerar 已提交
5741 5742
  taosMemoryFreeClear(pInfo);
  taosMemoryFreeClear(pOperator);
H
Haojun Liao 已提交
5743 5744
  pTaskInfo->code = TSDB_CODE_OUT_OF_MEMORY;
  return NULL;
5745 5746
}

H
Haojun Liao 已提交
5747
void doDestroyBasicInfo(SOptrBasicInfo* pInfo, int32_t numOfOutput) {
5748 5749
  assert(pInfo != NULL);

5750
  destroySqlFunctionCtx(pInfo->pCtx, numOfOutput);
wafwerar's avatar
wafwerar 已提交
5751
  taosMemoryFreeClear(pInfo->rowCellInfoOffset);
5752 5753

  cleanupResultRowInfo(&pInfo->resultRowInfo);
H
Haojun Liao 已提交
5754
  pInfo->pRes = blockDataDestroy(pInfo->pRes);
5755 5756
}

H
Haojun Liao 已提交
5757
void destroyBasicOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
5758
  SOptrBasicInfo* pInfo = (SOptrBasicInfo*)param;
5759 5760
  doDestroyBasicInfo(pInfo, numOfOutput);
}
H
Haojun Liao 已提交
5761 5762

void destroyStateWindowOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
5763
  SStateWindowOperatorInfo* pInfo = (SStateWindowOperatorInfo*)param;
5764
  doDestroyBasicInfo(&pInfo->binfo, numOfOutput);
5765
  taosMemoryFreeClear(pInfo->stateKey.pData);
5766
}
H
Haojun Liao 已提交
5767 5768

void destroyAggOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
5769
  SAggOperatorInfo* pInfo = (SAggOperatorInfo*)param;
5770 5771
  doDestroyBasicInfo(&pInfo->binfo, numOfOutput);
}
5772

H
Haojun Liao 已提交
5773
void destroyIntervalOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
5774
  STableIntervalOperatorInfo* pInfo = (STableIntervalOperatorInfo*)param;
H
Haojun Liao 已提交
5775 5776 5777 5778 5779
  doDestroyBasicInfo(&pInfo->binfo, numOfOutput);
  cleanupAggSup(&pInfo->aggSup);
}

void destroySWindowOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
5780
  SSessionAggOperatorInfo* pInfo = (SSessionAggOperatorInfo*)param;
5781 5782 5783
  doDestroyBasicInfo(&pInfo->binfo, numOfOutput);
}

H
Haojun Liao 已提交
5784
void destroySFillOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
5785
  SFillOperatorInfo* pInfo = (SFillOperatorInfo*)param;
5786
  pInfo->pFillInfo = taosDestroyFillInfo(pInfo->pFillInfo);
H
Haojun Liao 已提交
5787
  pInfo->pRes = blockDataDestroy(pInfo->pRes);
wafwerar's avatar
wafwerar 已提交
5788
  taosMemoryFreeClear(pInfo->p);
5789 5790
}

H
Haojun Liao 已提交
5791
static void destroyProjectOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
5792
  SProjectOperatorInfo* pInfo = (SProjectOperatorInfo*)param;
5793 5794 5795
  doDestroyBasicInfo(&pInfo->binfo, numOfOutput);
}

H
Haojun Liao 已提交
5796
static void destroyTagScanOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
5797
  STagScanInfo* pInfo = (STagScanInfo*)param;
H
Haojun Liao 已提交
5798
  pInfo->pRes = blockDataDestroy(pInfo->pRes);
5799 5800
}

H
Haojun Liao 已提交
5801
static void destroyOrderOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
5802
  SSortOperatorInfo* pInfo = (SSortOperatorInfo*)param;
H
Haojun Liao 已提交
5803 5804
  pInfo->pDataBlock = blockDataDestroy(pInfo->pDataBlock);

H
Haojun Liao 已提交
5805
  taosArrayDestroy(pInfo->pSortInfo);
5806
  taosArrayDestroy(pInfo->inputSlotMap);
5807 5808
}

H
Haojun Liao 已提交
5809
void destroyExchangeOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
5810
  SExchangeInfo* pExInfo = (SExchangeInfo*)param;
H
Haojun Liao 已提交
5811 5812 5813 5814 5815 5816 5817 5818 5819
  taosArrayDestroy(pExInfo->pSources);
  taosArrayDestroy(pExInfo->pSourceDataInfo);
  if (pExInfo->pResult != NULL) {
    blockDataDestroy(pExInfo->pResult);
  }

  tsem_destroy(&pExInfo->ready);
}

H
Haojun Liao 已提交
5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830
static SArray* setRowTsColumnOutputInfo(SqlFunctionCtx* pCtx, int32_t numOfCols) {
  SArray* pList = taosArrayInit(4, sizeof(int32_t));
  for(int32_t i = 0; i < numOfCols; ++i) {
    if (fmIsPseudoColumnFunc(pCtx[i].functionId)) {
      taosArrayPush(pList, &i);
    }
  }

  return pList;
}

L
Liu Jicong 已提交
5831
SOperatorInfo* createProjectOperatorInfo(SOperatorInfo* downstream, SExprInfo* pExprInfo, int32_t num,
H
Haojun Liao 已提交
5832
                                         SSDataBlock* pResBlock, SLimit* pLimit, SLimit* pSlimit, SExecTaskInfo* pTaskInfo) {
wafwerar's avatar
wafwerar 已提交
5833
  SProjectOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SProjectOperatorInfo));
L
Liu Jicong 已提交
5834
  SOperatorInfo*        pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
5835 5836 5837
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }
5838

H
Haojun Liao 已提交
5839
  pInfo->limit      = *pLimit;
H
Haojun Liao 已提交
5840
  pInfo->slimit     = *pSlimit;
H
Haojun Liao 已提交
5841
  pInfo->curOffset  = pLimit->offset;
H
Haojun Liao 已提交
5842 5843
  pInfo->curSOffset = pSlimit->offset;

H
Haojun Liao 已提交
5844
  pInfo->binfo.pRes = pResBlock;
H
Haojun Liao 已提交
5845 5846 5847

  int32_t numOfCols = num;
  int32_t numOfRows = 4096;
5848
  size_t keyBufSize = sizeof(int64_t) + sizeof(int64_t) + POINTER_BYTES;
5849 5850 5851

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

H
Haojun Liao 已提交
5855
  pOperator->name         = "ProjectOperator";
H
Haojun Liao 已提交
5856
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_PROJECT;
5857
  pOperator->blockingOptr = false;
H
Haojun Liao 已提交
5858 5859 5860 5861 5862 5863 5864
  pOperator->status       = OP_NOT_OPENED;
  pOperator->info         = pInfo;
  pOperator->pExpr        = pExprInfo;
  pOperator->numOfOutput  = num;
  pOperator->_openFn      = operatorDummyOpenFn;
  pOperator->getNextFn    = doProjectOperation;
  pOperator->closeFn      = destroyProjectOperatorInfo;
L
Liu Jicong 已提交
5865 5866

  pOperator->pTaskInfo = pTaskInfo;
5867
  int32_t code = appendDownstream(pOperator, &downstream, 1);
H
Haojun Liao 已提交
5868
  if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
5869 5870
    goto _error;
  }
5871 5872

  return pOperator;
H
Haojun Liao 已提交
5873

L
Liu Jicong 已提交
5874
_error:
H
Haojun Liao 已提交
5875 5876
  pTaskInfo->code = TSDB_CODE_OUT_OF_MEMORY;
  return NULL;
5877 5878
}

L
Liu Jicong 已提交
5879
SOperatorInfo* createIntervalOperatorInfo(SOperatorInfo* downstream, SExprInfo* pExprInfo, int32_t numOfCols,
5880 5881 5882
                                          SSDataBlock* pResBlock, SInterval* pInterval, int32_t primaryTsSlotId,
                                          STimeWindowAggSupp *pTwAggSupp, const STableGroupInfo* pTableGroupInfo,
                                          SExecTaskInfo* pTaskInfo) {
wafwerar's avatar
wafwerar 已提交
5883
  STableIntervalOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(STableIntervalOperatorInfo));
L
Liu Jicong 已提交
5884
  SOperatorInfo*              pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
5885 5886 5887
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }
H
Haojun Liao 已提交
5888

5889 5890 5891 5892 5893 5894 5895 5896
  pInfo->order          = TSDB_ORDER_ASC;
  pInfo->interval       = *pInterval;
  pInfo->execModel      = pTaskInfo->execModel;
  pInfo->win            = pTaskInfo->window;
  pInfo->win.skey       = 0;
  pInfo->win.ekey       = INT64_MAX;
  pInfo->primaryTsIndex = primaryTsSlotId;
  pInfo->twAggSup       = *pTwAggSupp;
5897

5898
  int32_t numOfRows = 4096;
5899
  size_t keyBufSize = sizeof(int64_t) + sizeof(int64_t) + POINTER_BYTES;
5900 5901 5902

  initResultSizeInfo(pOperator, numOfRows);
  int32_t code = initAggInfo(&pInfo->binfo, &pInfo->aggSup, pExprInfo, numOfCols, pResBlock, keyBufSize, pTaskInfo->id.str);
5903
  initExecTimeWindowInfo(&pInfo->twAggSup.timeWindowData, &pInfo->win);
5904

L
Liu Jicong 已提交
5905 5906
  //  pInfo->pTableQueryInfo = initTableQueryInfo(pTableGroupInfo);
  if (code != TSDB_CODE_SUCCESS /* || pInfo->pTableQueryInfo == NULL*/) {
H
Haojun Liao 已提交
5907 5908
    goto _error;
  }
H
Haojun Liao 已提交
5909 5910

  initResultRowInfo(&pInfo->binfo.resultRowInfo, (int32_t)1);
5911

5912
  pOperator->name         = "TimeIntervalAggOperator";
H
Haojun Liao 已提交
5913
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_INTERVAL;
5914
  pOperator->blockingOptr = true;
H
Haojun Liao 已提交
5915 5916 5917 5918 5919 5920 5921
  pOperator->status       = OP_NOT_OPENED;
  pOperator->pExpr        = pExprInfo;
  pOperator->pTaskInfo    = pTaskInfo;
  pOperator->numOfOutput  = numOfCols;
  pOperator->info         = pInfo;
  pOperator->_openFn      = doOpenIntervalAgg;
  pOperator->getNextFn    = doBuildIntervalResult;
5922
  pOperator->getStreamResFn= doStreamIntervalAgg;
H
Haojun Liao 已提交
5923
  pOperator->closeFn      = destroyIntervalOperatorInfo;
5924 5925
  pOperator->encodeResultRow = aggEncodeResultRow;
  pOperator->decodeResultRow = aggDecodeResultRow;
5926

H
Haojun Liao 已提交
5927
  code = appendDownstream(pOperator, &downstream, 1);
H
Haojun Liao 已提交
5928 5929 5930 5931
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }

5932
  return pOperator;
H
Haojun Liao 已提交
5933

L
Liu Jicong 已提交
5934
_error:
H
Haojun Liao 已提交
5935
  destroyIntervalOperatorInfo(pInfo, numOfCols);
wafwerar's avatar
wafwerar 已提交
5936 5937
  taosMemoryFreeClear(pInfo);
  taosMemoryFreeClear(pOperator);
H
Haojun Liao 已提交
5938 5939
  pTaskInfo->code = code;
  return NULL;
5940 5941
}

5942 5943 5944 5945 5946 5947
SOperatorInfo* createTimeSliceOperatorInfo(SOperatorInfo* downstream, SExprInfo* pExprInfo, int32_t numOfCols, SSDataBlock* pResultBlock, SExecTaskInfo* pTaskInfo) {
  STimeSliceOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(STimeSliceOperatorInfo));
  SOperatorInfo* pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
  if (pOperator == NULL || pInfo == NULL) {
    goto _error;
  }
5948

H
Haojun Liao 已提交
5949
  initResultRowInfo(&pInfo->binfo.resultRowInfo, 8);
5950

5951
  pOperator->name         = "TimeSliceOperator";
L
Liu Jicong 已提交
5952
  //  pOperator->operatorType = OP_AllTimeWindow;
5953
  pOperator->blockingOptr = true;
5954 5955 5956 5957 5958 5959 5960
  pOperator->status       = OP_NOT_OPENED;
  pOperator->pExpr        = pExprInfo;
  pOperator->numOfOutput  = numOfCols;
  pOperator->info         = pInfo;
  pOperator->pTaskInfo    = pTaskInfo;
  pOperator->getNextFn    = doAllIntervalAgg;
  pOperator->closeFn      = destroyBasicOperatorInfo;
5961

L
Liu Jicong 已提交
5962
  int32_t code = appendDownstream(pOperator, &downstream, 1);
5963
  return pOperator;
5964 5965 5966 5967 5968 5969

  _error:
  taosMemoryFree(pInfo);
  taosMemoryFree(pOperator);
  pTaskInfo->code = TSDB_CODE_OUT_OF_MEMORY;
  return NULL;
5970 5971
}

5972 5973
SOperatorInfo* createStatewindowOperatorInfo(SOperatorInfo* downstream, SExprInfo* pExpr, int32_t numOfCols, SSDataBlock* pResBlock, STimeWindowAggSupp *pTwAggSup,
    SExecTaskInfo* pTaskInfo) {
wafwerar's avatar
wafwerar 已提交
5974
  SStateWindowOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SStateWindowOperatorInfo));
5975 5976 5977 5978
  SOperatorInfo* pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }
H
Haojun Liao 已提交
5979

L
Liu Jicong 已提交
5980
  pInfo->colIndex = -1;
5981
  size_t keyBufSize = sizeof(int64_t) + sizeof(int64_t) + POINTER_BYTES;
5982 5983 5984

  initResultSizeInfo(pOperator, 4096);
  initAggInfo(&pInfo->binfo, &pInfo->aggSup, pExpr, numOfCols, pResBlock, keyBufSize, pTaskInfo->id.str);
5985
  initResultRowInfo(&pInfo->binfo.resultRowInfo, 8);
5986

5987 5988 5989
  pInfo->twAggSup = *pTwAggSup;
  initExecTimeWindowInfo(&pInfo->twAggSup.timeWindowData, &pTaskInfo->window);

5990 5991
  pOperator->name         = "StateWindowOperator";
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_STATE_WINDOW;
5992
  pOperator->blockingOptr = true;
H
Haojun Liao 已提交
5993 5994 5995 5996 5997 5998 5999 6000
  pOperator->status       = OP_NOT_OPENED;
  pOperator->pExpr        = pExpr;
  pOperator->numOfOutput  = numOfCols;

  pOperator->pTaskInfo    = pTaskInfo;
  pOperator->info         = pInfo;
  pOperator->getNextFn    = doStateWindowAgg;
  pOperator->closeFn      = destroyStateWindowOperatorInfo;
6001 6002
  pOperator->encodeResultRow = aggEncodeResultRow;
  pOperator->decodeResultRow = aggDecodeResultRow;
6003

H
Haojun Liao 已提交
6004
  int32_t code = appendDownstream(pOperator, &downstream, 1);
6005
  return pOperator;
6006 6007 6008 6009

  _error:
  pTaskInfo->code = TSDB_CODE_SUCCESS;
  return NULL;
6010 6011
}

L
Liu Jicong 已提交
6012
SOperatorInfo* createSessionAggOperatorInfo(SOperatorInfo* downstream, SExprInfo* pExprInfo, int32_t numOfCols,
6013
                                            SSDataBlock* pResBlock, int64_t gap, STimeWindowAggSupp *pTwAggSupp, SExecTaskInfo* pTaskInfo) {
wafwerar's avatar
wafwerar 已提交
6014
  SSessionAggOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SSessionAggOperatorInfo));
L
Liu Jicong 已提交
6015
  SOperatorInfo*           pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
6016 6017 6018
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }
H
Haojun Liao 已提交
6019

H
Haojun Liao 已提交
6020
  int32_t numOfRows = 4096;
6021
  size_t keyBufSize = sizeof(int64_t) + sizeof(int64_t) + POINTER_BYTES;
6022 6023 6024

  initResultSizeInfo(pOperator, numOfRows);
  int32_t code = initAggInfo(&pInfo->binfo, &pInfo->aggSup, pExprInfo, numOfCols, pResBlock, keyBufSize, pTaskInfo->id.str);
H
Haojun Liao 已提交
6025 6026 6027
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
6028

6029
  pInfo->twAggSup = *pTwAggSupp;
H
Haojun Liao 已提交
6030
  initResultRowInfo(&pInfo->binfo.resultRowInfo, 8);
6031
  initExecTimeWindowInfo(&pInfo->twAggSup.timeWindowData, &pTaskInfo->window);
6032

6033 6034
  pInfo->gap              = gap;
  pInfo->binfo.pRes       = pResBlock;
6035
  pInfo->winSup.prevTs    = INT64_MIN;
6036 6037
  pInfo->reptScan         = false;
  pOperator->name         = "SessionWindowAggOperator";
H
Haojun Liao 已提交
6038
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_SESSION_WINDOW;
6039
  pOperator->blockingOptr = true;
6040 6041 6042 6043 6044 6045
  pOperator->status       = OP_NOT_OPENED;
  pOperator->pExpr        = pExprInfo;
  pOperator->numOfOutput  = numOfCols;
  pOperator->info         = pInfo;
  pOperator->getNextFn    = doSessionWindowAgg;
  pOperator->closeFn      = destroySWindowOperatorInfo;
6046 6047
  pOperator->encodeResultRow = aggEncodeResultRow;
  pOperator->decodeResultRow = aggDecodeResultRow;
6048
  pOperator->pTaskInfo    = pTaskInfo;
6049

H
Haojun Liao 已提交
6050
  code = appendDownstream(pOperator, &downstream, 1);
6051
  return pOperator;
H
Haojun Liao 已提交
6052

L
Liu Jicong 已提交
6053
_error:
H
Haojun Liao 已提交
6054 6055 6056 6057
  if (pInfo != NULL) {
    destroySWindowOperatorInfo(pInfo, numOfCols);
  }

wafwerar's avatar
wafwerar 已提交
6058 6059
  taosMemoryFreeClear(pInfo);
  taosMemoryFreeClear(pOperator);
H
Haojun Liao 已提交
6060 6061
  pTaskInfo->code = code;
  return NULL;
6062 6063
}

H
Haojun Liao 已提交
6064
static int32_t initFillInfo(SFillOperatorInfo* pInfo, SExprInfo* pExpr, int32_t numOfCols, int64_t* fillVal,
L
Liu Jicong 已提交
6065
                            STimeWindow win, int32_t capacity, const char* id, SInterval* pInterval, int32_t fillType) {
H
Haojun Liao 已提交
6066 6067 6068 6069 6070 6071 6072 6073 6074 6075
  struct SFillColInfo* pColInfo = createFillColInfo(pExpr, numOfCols, (int64_t*)fillVal);

  TSKEY sk = TMIN(win.skey, win.ekey);
  TSKEY ek = TMAX(win.skey, win.ekey);

  // TODO set correct time precision
  STimeWindow w = TSWINDOW_INITIALIZER;
  getAlignQueryTimeWindow(pInterval, TSDB_TIME_PRECISION_MILLI, win.skey, sk, ek, &w);

  int32_t order = TSDB_ORDER_ASC;
L
Liu Jicong 已提交
6076 6077
  pInfo->pFillInfo = taosCreateFillInfo(order, w.skey, 0, capacity, numOfCols, pInterval->sliding,
                                        pInterval->slidingUnit, (int8_t)pInterval->precision, fillType, pColInfo, id);
H
Haojun Liao 已提交
6078

wafwerar's avatar
wafwerar 已提交
6079
  pInfo->p = taosMemoryCalloc(numOfCols, POINTER_BYTES);
H
Haojun Liao 已提交
6080 6081 6082 6083 6084 6085 6086 6087

  if (pInfo->pFillInfo == NULL || pInfo->p == NULL) {
    return TSDB_CODE_OUT_OF_MEMORY;
  } else {
    return TSDB_CODE_SUCCESS;
  }
}

L
Liu Jicong 已提交
6088 6089 6090
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 已提交
6091
  SFillOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SFillOperatorInfo));
L
Liu Jicong 已提交
6092
  SOperatorInfo*     pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
6093

L
Liu Jicong 已提交
6094
  pInfo->pRes = pResBlock;
6095
  pInfo->multigroupResult = multigroupResult;
L
Liu Jicong 已提交
6096
  pInfo->intervalInfo = *pInterval;
6097

H
Haojun Liao 已提交
6098
  SResultInfo* pResultInfo = &pOperator->resultInfo;
L
Liu Jicong 已提交
6099 6100
  int32_t      code = initFillInfo(pInfo, pExpr, numOfCols, (int64_t*)fillVal, pTaskInfo->window, pResultInfo->capacity,
                                   pTaskInfo->id.str, pInterval, fillType);
6101 6102 6103
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
6104

L
Liu Jicong 已提交
6105
  pOperator->name = "FillOperator";
6106
  pOperator->blockingOptr = false;
L
Liu Jicong 已提交
6107 6108 6109 6110 6111 6112 6113 6114
  pOperator->status = OP_NOT_OPENED;
  //  pOperator->operatorType = OP_Fill;
  pOperator->pExpr = pExpr;
  pOperator->numOfOutput = numOfCols;
  pOperator->info = pInfo;
  pOperator->_openFn = operatorDummyOpenFn;
  pOperator->getNextFn = doFill;
  pOperator->pTaskInfo = pTaskInfo;
6115

L
Liu Jicong 已提交
6116
  pOperator->closeFn = destroySFillOperatorInfo;
H
Haojun Liao 已提交
6117

6118
  code = appendDownstream(pOperator, &downstream, 1);
6119
  return pOperator;
H
Haojun Liao 已提交
6120

L
Liu Jicong 已提交
6121
_error:
wafwerar's avatar
wafwerar 已提交
6122 6123
  taosMemoryFreeClear(pOperator);
  taosMemoryFreeClear(pInfo);
H
Haojun Liao 已提交
6124
  return NULL;
6125 6126
}

L
Liu Jicong 已提交
6127
static SSDataBlock* doTagScan(SOperatorInfo* pOperator, bool* newgroup) {
6128 6129 6130 6131 6132 6133
#if 0
  SOperatorInfo* pOperator = (SOperatorInfo*) param;
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

H
Haojun Liao 已提交
6134
  int32_t maxNumOfTables = (int32_t)pResultInfo->capacity;
6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155

  STagScanInfo *pInfo = pOperator->info;
  SSDataBlock  *pRes = pInfo->pRes;
  *newgroup = false;

  int32_t count = 0;
  SArray* pa = GET_TABLEGROUP(pRuntimeEnv, 0);

  int32_t functionId = getExprFunctionId(&pOperator->pExpr[0]);
  if (functionId == FUNCTION_TID_TAG) { // return the tags & table Id
    assert(pQueryAttr->numOfOutput == 1);

    SExprInfo* pExprInfo = &pOperator->pExpr[0];
    int32_t rsize = pExprInfo->base.resSchema.bytes;

    count = 0;

    int16_t bytes = pExprInfo->base.resSchema.bytes;
    int16_t type  = pExprInfo->base.resSchema.type;

    for(int32_t i = 0; i < pQueryAttr->numOfTags; ++i) {
6156
      if (pQueryAttr->tagColList[i].colId == pExprInfo->base.pColumns->info.colId) {
6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187
        bytes = pQueryAttr->tagColList[i].bytes;
        type = pQueryAttr->tagColList[i].type;
        break;
      }
    }

    SColumnInfoData* pColInfo = taosArrayGet(pRes->pDataBlock, 0);

    while(pInfo->curPos < pInfo->totalTables && count < maxNumOfTables) {
      int32_t i = pInfo->curPos++;
      STableQueryInfo *item = taosArrayGetP(pa, i);

      char *output = pColInfo->pData + count * rsize;
      varDataSetLen(output, rsize - VARSTR_HEADER_SIZE);

      output = varDataVal(output);
      STableId* id = TSDB_TABLEID(item->pTable);

      *(int16_t *)output = 0;
      output += sizeof(int16_t);

      *(int64_t *)output = id->uid;  // memory align problem, todo serialize
      output += sizeof(id->uid);

      *(int32_t *)output = id->tid;
      output += sizeof(id->tid);

      *(int32_t *)output = pQueryAttr->vgId;
      output += sizeof(pQueryAttr->vgId);

      char* data = NULL;
6188
      if (pExprInfo->base.pColumns->info.colId == TSDB_TBNAME_COLUMN_INDEX) {
6189 6190
        data = tsdbGetTableName(item->pTable);
      } else {
6191
        data = tsdbGetTableTagVal(item->pTable, pExprInfo->base.pColumns->info.colId, type, bytes);
6192 6193 6194 6195 6196 6197
      }

      doSetTagValueToResultBuf(output, data, type, bytes);
      count += 1;
    }

6198
    //qDebug("QInfo:0x%"PRIx64" create (tableId, tag) info completed, rows:%d", GET_TASKID(pRuntimeEnv), count);
6199 6200 6201 6202 6203 6204
  } else if (functionId == FUNCTION_COUNT) {// handle the "count(tbname)" query
    SColumnInfoData* pColInfo = taosArrayGet(pRes->pDataBlock, 0);
    *(int64_t*)pColInfo->pData = pInfo->totalTables;
    count = 1;

    pOperator->status = OP_EXEC_DONE;
6205
    //qDebug("QInfo:0x%"PRIx64" create count(tbname) query, res:%d rows:1", GET_TASKID(pRuntimeEnv), count);
6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218
  } else {  // return only the tags|table name etc.
    SExprInfo* pExprInfo = &pOperator->pExpr[0];  // todo use the column list instead of exprinfo

    count = 0;
    while(pInfo->curPos < pInfo->totalTables && count < maxNumOfTables) {
      int32_t i = pInfo->curPos++;

      STableQueryInfo* item = taosArrayGetP(pa, i);

      char *data = NULL, *dst = NULL;
      int16_t type = 0, bytes = 0;
      for(int32_t j = 0; j < pOperator->numOfOutput; ++j) {
        // not assign value in case of user defined constant output column
6219
        if (TSDB_COL_IS_UD_COL(pExprInfo[j].base.pColumns->flag)) {
6220 6221 6222 6223 6224 6225 6226
          continue;
        }

        SColumnInfoData* pColInfo = taosArrayGet(pRes->pDataBlock, j);
        type  = pExprInfo[j].base.resSchema.type;
        bytes = pExprInfo[j].base.resSchema.bytes;

6227
        if (pExprInfo[j].base.pColumns->info.colId == TSDB_TBNAME_COLUMN_INDEX) {
6228 6229
          data = tsdbGetTableName(item->pTable);
        } else {
6230
          data = tsdbGetTableTagVal(item->pTable, pExprInfo[j].base.pColumns->info.colId, type, bytes);
6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243
        }

        dst  = pColInfo->pData + count * pExprInfo[j].base.resSchema.bytes;
        doSetTagValueToResultBuf(dst, data, type, bytes);
      }

      count += 1;
    }

    if (pInfo->curPos >= pInfo->totalTables) {
      pOperator->status = OP_EXEC_DONE;
    }

6244
    //qDebug("QInfo:0x%"PRIx64" create tag values results completed, rows:%d", GET_TASKID(pRuntimeEnv), count);
6245 6246 6247
  }

  if (pOperator->status == OP_EXEC_DONE) {
6248
    setTaskStatus(pOperator->pRuntimeEnv, TASK_COMPLETED);
6249 6250 6251 6252 6253 6254
  }

  pRes->info.rows = count;
  return (pRes->info.rows == 0)? NULL:pInfo->pRes;

#endif
6255
  return TSDB_CODE_SUCCESS;
6256 6257
}

H
Haojun Liao 已提交
6258
SOperatorInfo* createTagScanOperatorInfo(STaskRuntimeEnv* pRuntimeEnv, SExprInfo* pExpr, int32_t numOfOutput) {
wafwerar's avatar
wafwerar 已提交
6259
  STagScanInfo* pInfo = taosMemoryCalloc(1, sizeof(STagScanInfo));
6260 6261 6262 6263 6264
  size_t numOfGroup = GET_NUM_OF_TABLEGROUP(pRuntimeEnv);
  assert(numOfGroup == 0 || numOfGroup == 1);

  pInfo->curPos = 0;

wafwerar's avatar
wafwerar 已提交
6265
  SOperatorInfo* pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
L
Liu Jicong 已提交
6266
  pOperator->name = "SeqTableTagScan";
X
Xiaoyu Wang 已提交
6267
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_TAG_SCAN;
6268
  pOperator->blockingOptr = false;
L
Liu Jicong 已提交
6269 6270
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
H
Haojun Liao 已提交
6271
  pOperator->getNextFn = doTagScan;
L
Liu Jicong 已提交
6272 6273
  pOperator->pExpr = pExpr;
  pOperator->numOfOutput = numOfOutput;
H
Haojun Liao 已提交
6274
  pOperator->closeFn = destroyTagScanOperatorInfo;
6275 6276 6277

  return pOperator;
}
H
Haojun Liao 已提交
6278

6279

L
Liu Jicong 已提交
6280
static int32_t getColumnIndexInSource(SQueriedTableInfo* pTableInfo, SExprBasicInfo* pExpr, SColumnInfo* pTagCols) {
6281 6282
  int32_t j = 0;

H
Haojun Liao 已提交
6283 6284
  if (TSDB_COL_IS_TAG(pExpr->pParam[0].pCol->type)) {
    if (pExpr->pParam[0].pCol->colId == TSDB_TBNAME_COLUMN_INDEX) {
6285 6286 6287
      return TSDB_TBNAME_COLUMN_INDEX;
    }

L
Liu Jicong 已提交
6288
    while (j < pTableInfo->numOfTags) {
H
Haojun Liao 已提交
6289
      if (pExpr->pParam[0].pCol->colId == pTagCols[j].colId) {
6290 6291 6292 6293 6294 6295
        return j;
      }

      j += 1;
    }

6296
  } /*else if (TSDB_COL_IS_UD_COL(pExpr->colInfo.flag)) {  // user specified column data
6297 6298 6299 6300 6301 6302 6303 6304 6305
    return TSDB_UD_COLUMN_INDEX;
  } else {
    while (j < pTableInfo->numOfCols) {
      if (pExpr->colInfo.colId == pTableInfo->colList[j].colId) {
        return j;
      }

      j += 1;
    }
6306
  }*/
6307 6308 6309 6310

  return INT32_MIN;  // return a less than TSDB_TBNAME_COLUMN_INDEX value
}

L
Liu Jicong 已提交
6311
bool validateExprColumnInfo(SQueriedTableInfo* pTableInfo, SExprBasicInfo* pExpr, SColumnInfo* pTagCols) {
6312 6313 6314 6315
  int32_t j = getColumnIndexInSource(pTableInfo, pExpr, pTagCols);
  return j != INT32_MIN;
}

L
Liu Jicong 已提交
6316 6317
static SResSchema createResSchema(int32_t type, int32_t bytes, int32_t slotId, int32_t scale, int32_t precision,
                                  const char* name) {
H
Haojun Liao 已提交
6318
  SResSchema s = {0};
6319 6320 6321 6322
  s.scale     = scale;
  s.type      = type;
  s.bytes     = bytes;
  s.slotId    = slotId;
H
Haojun Liao 已提交
6323
  s.precision = precision;
H
Haojun Liao 已提交
6324 6325 6326 6327
  strncpy(s.name, name, tListLen(s.name));

  return s;
}
H
Haojun Liao 已提交
6328

H
Haojun Liao 已提交
6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345
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;
  }

  pCol->slotId      = slotId;
  pCol->bytes       = pType->bytes;
  pCol->type        = pType->type;
  pCol->scale       = pType->scale;
  pCol->precision   = pType->precision;
  pCol->dataBlockId = blockId;

  return pCol;
}

H
Haojun Liao 已提交
6346
SExprInfo* createExprInfo(SNodeList* pNodeList, SNodeList* pGroupKeys, int32_t* numOfExprs) {
H
Haojun Liao 已提交
6347
  int32_t numOfFuncs = LIST_LENGTH(pNodeList);
H
Haojun Liao 已提交
6348 6349 6350 6351
  int32_t numOfGroupKeys = 0;
  if (pGroupKeys != NULL) {
    numOfGroupKeys = LIST_LENGTH(pGroupKeys);
  }
H
Haojun Liao 已提交
6352

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

L
Liu Jicong 已提交
6356
  for (int32_t i = 0; i < (*numOfExprs); ++i) {
H
Haojun Liao 已提交
6357 6358 6359 6360 6361 6362
    STargetNode* pTargetNode = NULL;
    if (i < numOfFuncs) {
      pTargetNode = (STargetNode*)nodesListGetNode(pNodeList, i);
    } else {
      pTargetNode = (STargetNode*)nodesListGetNode(pGroupKeys, i - numOfFuncs);
    }
H
Haojun Liao 已提交
6363

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

wafwerar's avatar
wafwerar 已提交
6366
    pExp->pExpr = taosMemoryCalloc(1, sizeof(tExprNode));
H
Haojun Liao 已提交
6367
    pExp->pExpr->_function.num = 1;
H
Haojun Liao 已提交
6368
    pExp->pExpr->_function.functionId = -1;
H
Haojun Liao 已提交
6369

6370
    int32_t type = nodeType(pTargetNode->pExpr);
H
Haojun Liao 已提交
6371
    // it is a project query, or group by column
6372
    if (type == QUERY_NODE_COLUMN) {
H
Haojun Liao 已提交
6373
      pExp->pExpr->nodeType = QUERY_NODE_COLUMN;
L
Liu Jicong 已提交
6374
      SColumnNode* pColNode = (SColumnNode*)pTargetNode->pExpr;
H
Haojun Liao 已提交
6375

G
Ganlin Zhao 已提交
6376 6377 6378
      pExp->base.pParam = taosMemoryCalloc(1, sizeof(SFunctParam));
      pExp->base.numOfParams = 1;

H
Haojun Liao 已提交
6379 6380
      SDataType* pType = &pColNode->node.resType;
      pExp->base.resSchema = createResSchema(pType->type, pType->bytes, pTargetNode->slotId, pType->scale, pType->precision, pColNode->colName);
H
Haojun Liao 已提交
6381 6382
      pExp->base.pParam[0].pCol = createColumn(pColNode->dataBlockId, pColNode->slotId, pType);
      pExp->base.pParam[0].type = FUNC_PARAM_TYPE_COLUMN;
6383
    } else if (type == QUERY_NODE_VALUE) {
6384 6385 6386 6387 6388 6389 6390 6391 6392 6393
      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;
      pExp->base.resSchema = createResSchema(pType->type, pType->bytes, pTargetNode->slotId, pType->scale, pType->precision, pValNode->node.aliasName);
      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;
6399
      pExp->base.resSchema = createResSchema(pType->type, pType->bytes, pTargetNode->slotId, pType->scale, pType->precision, pFuncNode->node.aliasName);
H
Haojun Liao 已提交
6400

H
Haojun Liao 已提交
6401
      pExp->pExpr->_function.functionId = pFuncNode->funcId;
H
Haojun Liao 已提交
6402
      pExp->pExpr->_function.pFunctNode = pFuncNode;
H
Haojun Liao 已提交
6403
      strncpy(pExp->pExpr->_function.functionName, pFuncNode->functionName, tListLen(pExp->pExpr->_function.functionName));
H
Haojun Liao 已提交
6404 6405

      int32_t numOfParam = LIST_LENGTH(pFuncNode->pParameterList);
G
Ganlin Zhao 已提交
6406 6407 6408 6409

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

H
Haojun Liao 已提交
6410
      for (int32_t j = 0; j < numOfParam; ++j) {
6411
        SNode* p1 = nodesListGetNode(pFuncNode->pParameterList, j);
G
Ganlin Zhao 已提交
6412
        if (p1->type == QUERY_NODE_COLUMN) {
H
Haojun Liao 已提交
6413
          SColumnNode* pcn = (SColumnNode*) p1;
G
Ganlin Zhao 已提交
6414 6415

          pExp->base.pParam[j].type = FUNC_PARAM_TYPE_COLUMN;
H
Haojun Liao 已提交
6416
          pExp->base.pParam[j].pCol = createColumn(pcn->dataBlockId, pcn->slotId, &pcn->node.resType);
G
Ganlin Zhao 已提交
6417 6418 6419
        } else if (p1->type == QUERY_NODE_VALUE) {
          SValueNode* pvn = (SValueNode*)p1;
          pExp->base.pParam[j].type = FUNC_PARAM_TYPE_VALUE;
6420
          valueNodeToVariant(pvn, &pExp->base.pParam[j].param);
G
Ganlin Zhao 已提交
6421
        }
H
Haojun Liao 已提交
6422
      }
6423
    } else if (type == QUERY_NODE_OPERATOR) {
H
Haojun Liao 已提交
6424
      pExp->pExpr->nodeType = QUERY_NODE_OPERATOR;
L
Liu Jicong 已提交
6425
      SOperatorNode* pNode = (SOperatorNode*)pTargetNode->pExpr;
6426

G
Ganlin Zhao 已提交
6427 6428 6429
      pExp->base.pParam = taosMemoryCalloc(1, sizeof(SFunctParam));
      pExp->base.numOfParams = 1;

6430
      SDataType* pType = &pNode->node.resType;
H
Haojun Liao 已提交
6431
      pExp->base.resSchema = createResSchema(pType->type, pType->bytes, pTargetNode->slotId, pType->scale, pType->precision, pNode->node.aliasName);
6432 6433 6434
      pExp->pExpr->_optrRoot.pRootNode = pTargetNode->pExpr;
    } else {
      ASSERT(0);
H
Haojun Liao 已提交
6435 6436 6437
    }
  }

H
Haojun Liao 已提交
6438
  return pExprs;
H
Haojun Liao 已提交
6439 6440
}

6441
static SExecTaskInfo* createExecTaskInfo(uint64_t queryId, uint64_t taskId, EOPTR_EXEC_MODEL model) {
wafwerar's avatar
wafwerar 已提交
6442
  SExecTaskInfo* pTaskInfo = taosMemoryCalloc(1, sizeof(SExecTaskInfo));
6443
  setTaskStatus(pTaskInfo, TASK_NOT_COMPLETED);
H
Haojun Liao 已提交
6444

6445
  pTaskInfo->cost.created = taosGetTimestampMs();
H
Haojun Liao 已提交
6446
  pTaskInfo->id.queryId = queryId;
6447
  pTaskInfo->execModel  = model;
H
Haojun Liao 已提交
6448

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

6453 6454
  return pTaskInfo;
}
H
Haojun Liao 已提交
6455

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

L
Liu Jicong 已提交
6459 6460
static int32_t doCreateTableGroup(void* metaHandle, int32_t tableType, uint64_t tableUid, STableGroupInfo* pGroupInfo,
                                  uint64_t queryId, uint64_t taskId);
6461 6462
static SArray* extractTableIdList(const STableGroupInfo* pTableGroupInfo);
static SArray* extractScanColumnId(SNodeList* pNodeList);
H
Haojun Liao 已提交
6463
static SArray* extractColumnInfo(SNodeList* pNodeList);
H
Haojun Liao 已提交
6464
static SArray* extractColMatchInfo(SNodeList* pNodeList, SDataBlockDescNode* pOutputNodeList, int32_t* numOfOutputCols);
6465

6466
static SArray* createSortInfo(SNodeList* pNodeList, SNodeList* pNodeListTarget);
6467
static SArray* createIndexMap(SNodeList* pNodeList);
6468
static SArray* extractPartitionColInfo(SNodeList* pNodeList);
H
Haojun Liao 已提交
6469

H
Haojun Liao 已提交
6470
SOperatorInfo* createOperatorTree(SPhysiNode* pPhyNode, SExecTaskInfo* pTaskInfo, SReadHandle* pHandle,
6471
                                  uint64_t queryId, uint64_t taskId, STableGroupInfo* pTableGroupInfo) {
6472 6473
  int32_t type = nodeType(pPhyNode);

X
Xiaoyu Wang 已提交
6474
  if (pPhyNode->pChildren == NULL || LIST_LENGTH(pPhyNode->pChildren) == 0) {
H
Haojun Liao 已提交
6475
    if (QUERY_NODE_PHYSICAL_PLAN_TABLE_SCAN == type) {
X
Xiaoyu Wang 已提交
6476
      SScanPhysiNode* pScanPhyNode = (SScanPhysiNode*)pPhyNode;
H
Haojun Liao 已提交
6477
      STableScanPhysiNode* pTableScanNode = (STableScanPhysiNode* ) pPhyNode;
H
Haojun Liao 已提交
6478

H
Haojun Liao 已提交
6479
      int32_t     numOfCols = 0;
H
Haojun Liao 已提交
6480
      tsdbReaderT pDataReader = doCreateDataReader(pTableScanNode, pHandle, pTableGroupInfo, (uint64_t)queryId, taskId);
6481 6482 6483 6484
      if (pDataReader == NULL) {
        return NULL;
      }

H
Haojun Liao 已提交
6485
      SArray* pColList = extractColMatchInfo(pScanPhyNode->pScanCols, pScanPhyNode->node.pOutputDataBlockDesc, &numOfCols);
6486
      SSDataBlock* pResBlock = createResDataBlock(pScanPhyNode->node.pOutputDataBlockDesc);
6487

6488 6489 6490 6491 6492 6493 6494 6495 6496 6497
      SInterval interval = {
          .interval     = pTableScanNode->interval,
          .sliding      = pTableScanNode->sliding,
          .intervalUnit = pTableScanNode->intervalUnit,
          .slidingUnit  = pTableScanNode->slidingUnit,
          .offset       = pTableScanNode->offset,
      };

      return createTableScanOperatorInfo(pDataReader, pScanPhyNode->order, numOfCols, pTableScanNode->dataRequired,
          pScanPhyNode->count, pScanPhyNode->reverse, pColList, pResBlock, pScanPhyNode->node.pConditions, &interval, pTableScanNode->ratio, pTaskInfo);
H
Haojun Liao 已提交
6498
    } else if (QUERY_NODE_PHYSICAL_PLAN_EXCHANGE == type) {
H
Haojun Liao 已提交
6499
      SExchangePhysiNode* pExchange = (SExchangePhysiNode*)pPhyNode;
6500
      SSDataBlock*        pResBlock = createResDataBlock(pExchange->node.pOutputDataBlockDesc);
H
Haojun Liao 已提交
6501
      return createExchangeOperatorInfo(pExchange->pSrcEndPoints, pResBlock, pTaskInfo);
H
Haojun Liao 已提交
6502
    } else if (QUERY_NODE_PHYSICAL_PLAN_STREAM_SCAN == type) {
H
Haojun Liao 已提交
6503
      SScanPhysiNode* pScanPhyNode = (SScanPhysiNode*)pPhyNode;  // simple child table.
6504

6505
      int32_t code = doCreateTableGroup(pHandle->meta, pScanPhyNode->tableType, pScanPhyNode->uid, pTableGroupInfo, queryId, taskId);
H
Haojun Liao 已提交
6506
      SArray* tableIdList = extractTableIdList(pTableGroupInfo);
H
Haojun Liao 已提交
6507

6508
      SSDataBlock* pResBlock = createResDataBlock(pScanPhyNode->node.pOutputDataBlockDesc);
6509 6510 6511 6512

      int32_t numOfCols = 0;
      SArray* pColList = extractColMatchInfo(pScanPhyNode->pScanCols, pScanPhyNode->node.pOutputDataBlockDesc, &numOfCols);
      SOperatorInfo* pOperator = createStreamScanOperatorInfo(pHandle->reader, pResBlock, pColList, tableIdList, pTaskInfo);
6513
      taosArrayDestroy(tableIdList);
H
Haojun Liao 已提交
6514
      return pOperator;
H
Haojun Liao 已提交
6515
    } else if (QUERY_NODE_PHYSICAL_PLAN_SYSTABLE_SCAN == type) {
L
Liu Jicong 已提交
6516
      SSystemTableScanPhysiNode* pSysScanPhyNode = (SSystemTableScanPhysiNode*)pPhyNode;
6517
      SSDataBlock*               pResBlock = createResDataBlock(pSysScanPhyNode->scan.node.pOutputDataBlockDesc);
H
Haojun Liao 已提交
6518

6519
      struct SScanPhysiNode* pScanNode = &pSysScanPhyNode->scan;
L
Liu Jicong 已提交
6520
      SArray*                colList = extractScanColumnId(pScanNode->pScanCols);
6521

L
Liu Jicong 已提交
6522 6523 6524
      SOperatorInfo* pOperator = createSysTableScanOperatorInfo(
          pHandle->meta, pResBlock, &pScanNode->tableName, pScanNode->node.pConditions, pSysScanPhyNode->mgmtEpSet,
          colList, pTaskInfo, pSysScanPhyNode->showRewrite, pSysScanPhyNode->accountId);
H
Haojun Liao 已提交
6525 6526 6527
      return pOperator;
    } else {
      ASSERT(0);
H
Haojun Liao 已提交
6528 6529 6530
    }
  }

6531 6532
  int32_t num = 0;
  size_t  size = LIST_LENGTH(pPhyNode->pChildren);
H
Haojun Liao 已提交
6533

6534 6535 6536 6537 6538
  SOperatorInfo** ops = taosMemoryCalloc(size, POINTER_BYTES);
  for(int32_t i = 0; i < size; ++i) {
    SPhysiNode* pChildNode = (SPhysiNode*)nodesListGetNode(pPhyNode->pChildren, i);
    ops[i] = createOperatorTree(pChildNode, pTaskInfo, pHandle, queryId, taskId, pTableGroupInfo);
  }
H
Haojun Liao 已提交
6539

6540
  SOperatorInfo* pOptr = NULL;
H
Haojun Liao 已提交
6541
  if (QUERY_NODE_PHYSICAL_PLAN_PROJECT == type) {
H
Haojun Liao 已提交
6542 6543 6544
    SProjectPhysiNode* pProjPhyNode = (SProjectPhysiNode*) pPhyNode;
    SExprInfo*   pExprInfo = createExprInfo(pProjPhyNode->pProjections, NULL, &num);

6545
    SSDataBlock* pResBlock = createResDataBlock(pPhyNode->pOutputDataBlockDesc);
H
Haojun Liao 已提交
6546
    SLimit limit = {.limit = pProjPhyNode->limit, .offset = pProjPhyNode->offset};
H
Haojun Liao 已提交
6547
    SLimit slimit = {.limit = pProjPhyNode->slimit, .offset = pProjPhyNode->soffset};
6548
    pOptr = createProjectOperatorInfo(ops[0], pExprInfo, num, pResBlock, &limit, &slimit, pTaskInfo);
H
Haojun Liao 已提交
6549 6550 6551
  } else if (QUERY_NODE_PHYSICAL_PLAN_AGG == type) {
    SAggPhysiNode* pAggNode = (SAggPhysiNode*)pPhyNode;
    SExprInfo*     pExprInfo = createExprInfo(pAggNode->pAggFuncs, pAggNode->pGroupKeys, &num);
6552
    SSDataBlock*   pResBlock = createResDataBlock(pPhyNode->pOutputDataBlockDesc);
H
Haojun Liao 已提交
6553

6554
    int32_t numOfScalarExpr = 0;
6555 6556 6557 6558 6559
    SExprInfo* pScalarExprInfo = NULL;
    if (pAggNode->pExprs != NULL) {
      pScalarExprInfo = createExprInfo(pAggNode->pExprs, NULL, &numOfScalarExpr);
    }

H
Haojun Liao 已提交
6560 6561
    if (pAggNode->pGroupKeys != NULL) {
      SArray* pColList = extractColumnInfo(pAggNode->pGroupKeys);
6562
      pOptr = createGroupOperatorInfo(ops[0], pExprInfo, num, pResBlock, pColList, pAggNode->node.pConditions, pScalarExprInfo, numOfScalarExpr, pTaskInfo, NULL);
H
Haojun Liao 已提交
6563
    } else {
6564
      pOptr = createAggregateOperatorInfo(ops[0], pExprInfo, num, pResBlock, pScalarExprInfo, numOfScalarExpr, pTaskInfo, pTableGroupInfo);
H
Haojun Liao 已提交
6565
    }
H
Haojun Liao 已提交
6566 6567
  } else if (QUERY_NODE_PHYSICAL_PLAN_INTERVAL == type) {
    SIntervalPhysiNode* pIntervalPhyNode = (SIntervalPhysiNode*)pPhyNode;
H
Haojun Liao 已提交
6568

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

H
Haojun Liao 已提交
6572 6573 6574 6575 6576 6577
    SInterval interval = {
        .interval     = pIntervalPhyNode->interval,
        .sliding      = pIntervalPhyNode->sliding,
        .intervalUnit = pIntervalPhyNode->intervalUnit,
        .slidingUnit  = pIntervalPhyNode->slidingUnit,
        .offset       = pIntervalPhyNode->offset,
X
Xiaoyu Wang 已提交
6578
        .precision    = ((SColumnNode*)pIntervalPhyNode->window.pTspk)->node.resType.precision
H
Haojun Liao 已提交
6579 6580
    };

6581 6582
    STimeWindowAggSupp as = {.waterMark = pIntervalPhyNode->window.watermark, .calTrigger = pIntervalPhyNode->window.triggerType};

6583
    int32_t primaryTsSlotId = ((SColumnNode*) pIntervalPhyNode->window.pTspk)->slotId;
6584
    pOptr = createIntervalOperatorInfo(ops[0], pExprInfo, num, pResBlock, &interval, primaryTsSlotId, &as, pTableGroupInfo, pTaskInfo);
H
Haojun Liao 已提交
6585
  } else if (QUERY_NODE_PHYSICAL_PLAN_SORT == type) {
H
Haojun Liao 已提交
6586
    SSortPhysiNode* pSortPhyNode = (SSortPhysiNode*)pPhyNode;
H
Haojun Liao 已提交
6587

6588
    SSDataBlock* pResBlock = createResDataBlock(pPhyNode->pOutputDataBlockDesc);
6589
    SArray*      info = createSortInfo(pSortPhyNode->pSortKeys, pSortPhyNode->pTargets);
6590
    SArray*      slotMap = createIndexMap(pSortPhyNode->pTargets);
6591
    pOptr = createSortOperatorInfo(ops[0], pResBlock, info, slotMap, pTaskInfo);
H
Haojun Liao 已提交
6592
  } else if (QUERY_NODE_PHYSICAL_PLAN_SESSION_WINDOW == type) {
H
Haojun Liao 已提交
6593 6594
    SSessionWinodwPhysiNode* pSessionNode = (SSessionWinodwPhysiNode*)pPhyNode;

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

H
Haojun Liao 已提交
6597
    SExprInfo*   pExprInfo = createExprInfo(pSessionNode->window.pFuncs, NULL, &num);
6598
    SSDataBlock* pResBlock = createResDataBlock(pPhyNode->pOutputDataBlockDesc);
6599
    pOptr = createSessionAggOperatorInfo(ops[0], pExprInfo, num, pResBlock, pSessionNode->gap, &as, pTaskInfo);
H
Haojun Liao 已提交
6600 6601
  } else if (QUERY_NODE_PHYSICAL_PLAN_PARTITION == type) {
    SPartitionPhysiNode* pPartNode = (SPartitionPhysiNode*) pPhyNode;
6602
    SArray* pColList = extractPartitionColInfo(pPartNode->pPartitionKeys);
6603
    SSDataBlock* pResBlock = createResDataBlock(pPhyNode->pOutputDataBlockDesc);
6604 6605

    SExprInfo* pExprInfo = createExprInfo(pPartNode->pTargets, NULL, &num);
6606
    pOptr = createPartitionOperatorInfo(ops[0], pExprInfo, num, pResBlock, pColList, pTaskInfo, NULL);
6607
  } else if (QUERY_NODE_PHYSICAL_PLAN_STATE_WINDOW == type) {
6608 6609
    SStateWinodwPhysiNode* pStateNode = (SStateWinodwPhysiNode*) pPhyNode;

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

6612
    SExprInfo* pExprInfo = createExprInfo(pStateNode->window.pFuncs, NULL, &num);
6613
    SSDataBlock* pResBlock = createResDataBlock(pPhyNode->pOutputDataBlockDesc);
6614
    pOptr = createStatewindowOperatorInfo(ops[0], pExprInfo, num, pResBlock, &as, pTaskInfo);
6615 6616
  } else if (QUERY_NODE_PHYSICAL_PLAN_JOIN == type) {
    SJoinPhysiNode* pJoinNode = (SJoinPhysiNode*) pPhyNode;
6617
    SSDataBlock* pResBlock = createResDataBlock(pPhyNode->pOutputDataBlockDesc);
6618 6619

    SExprInfo* pExprInfo = createExprInfo(pJoinNode->pTargets, NULL, &num);
6620
    pOptr = createJoinOperatorInfo(ops, size, pExprInfo, num, pResBlock, pJoinNode->pOnConditions, pTaskInfo);
H
Haojun Liao 已提交
6621 6622
  } else {
    ASSERT(0);
H
Haojun Liao 已提交
6623
  }
6624 6625 6626

  taosMemoryFree(ops);
  return pOptr;
6627
}
H
Haojun Liao 已提交
6628

L
Liu Jicong 已提交
6629 6630
static tsdbReaderT createDataReaderImpl(STableScanPhysiNode* pTableScanNode, STableGroupInfo* pGroupInfo,
                                        void* readHandle, uint64_t queryId, uint64_t taskId) {
H
Haojun Liao 已提交
6631
  STsdbQueryCond cond = {.loadExternalRows = false};
H
Haojun Liao 已提交
6632

L
Liu Jicong 已提交
6633
  cond.order = pTableScanNode->scan.order;
X
Xiaoyu Wang 已提交
6634
  cond.numOfCols = LIST_LENGTH(pTableScanNode->scan.pScanCols);
L
Liu Jicong 已提交
6635
  cond.colList = taosMemoryCalloc(cond.numOfCols, sizeof(SColumnInfo));
H
Haojun Liao 已提交
6636 6637 6638 6639 6640
  if (cond.colList == NULL) {
    terrno = TSDB_CODE_QRY_OUT_OF_MEMORY;
    return NULL;
  }

X
Xiaoyu Wang 已提交
6641
  cond.twindow = pTableScanNode->scanRange;
H
Haojun Liao 已提交
6642
  cond.type = BLOCK_LOAD_OFFSET_SEQ_ORDER;
L
Liu Jicong 已提交
6643
  //  cond.type = pTableScanNode->scanFlag;
H
Haojun Liao 已提交
6644

H
Haojun Liao 已提交
6645
  int32_t j = 0;
H
Haojun Liao 已提交
6646
  for (int32_t i = 0; i < cond.numOfCols; ++i) {
H
Haojun Liao 已提交
6647 6648
    STargetNode* pNode = (STargetNode*)nodesListGetNode(pTableScanNode->scan.pScanCols, i);
    SColumnNode* pColNode = (SColumnNode*)pNode->pExpr;
H
Haojun Liao 已提交
6649 6650 6651
    if (pColNode->colType == COLUMN_TYPE_TAG) {
      continue;
    }
H
Haojun Liao 已提交
6652

6653
    cond.colList[j].type  = pColNode->node.resType.type;
H
Haojun Liao 已提交
6654 6655 6656
    cond.colList[j].bytes = pColNode->node.resType.bytes;
    cond.colList[j].colId = pColNode->colId;
    j += 1;
H
Haojun Liao 已提交
6657 6658
  }

H
Haojun Liao 已提交
6659
  cond.numOfCols = j;
H
Haojun Liao 已提交
6660
  return tsdbQueryTables(readHandle, &cond, pGroupInfo, queryId, taskId);
H
Haojun Liao 已提交
6661
}
H
Haojun Liao 已提交
6662

6663
SArray* extractScanColumnId(SNodeList* pNodeList) {
L
Liu Jicong 已提交
6664
  size_t  numOfCols = LIST_LENGTH(pNodeList);
6665 6666 6667 6668 6669 6670
  SArray* pList = taosArrayInit(numOfCols, sizeof(int16_t));
  if (pList == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

L
Liu Jicong 已提交
6671
  for (int32_t i = 0; i < numOfCols; ++i) {
X
Xiaoyu Wang 已提交
6672
    for (int32_t j = 0; j < numOfCols; ++j) {
L
Liu Jicong 已提交
6673
      STargetNode* pNode = (STargetNode*)nodesListGetNode(pNodeList, j);
X
Xiaoyu Wang 已提交
6674
      if (pNode->slotId == i) {
L
Liu Jicong 已提交
6675
        SColumnNode* pColNode = (SColumnNode*)pNode->pExpr;
X
Xiaoyu Wang 已提交
6676 6677 6678 6679
        taosArrayPush(pList, &pColNode->colId);
        break;
      }
    }
6680 6681 6682 6683 6684
  }

  return pList;
}

H
Haojun Liao 已提交
6685
SArray* extractColumnInfo(SNodeList* pNodeList) {
L
Liu Jicong 已提交
6686
  size_t  numOfCols = LIST_LENGTH(pNodeList);
H
Haojun Liao 已提交
6687 6688 6689 6690 6691 6692
  SArray* pList = taosArrayInit(numOfCols, sizeof(SColumn));
  if (pList == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

L
Liu Jicong 已提交
6693 6694 6695
  for (int32_t i = 0; i < numOfCols; ++i) {
    STargetNode* pNode = (STargetNode*)nodesListGetNode(pNodeList, i);
    SColumnNode* pColNode = (SColumnNode*)pNode->pExpr;
H
Haojun Liao 已提交
6696

H
Haojun Liao 已提交
6697
    // todo extract method
H
Haojun Liao 已提交
6698 6699
    SColumn c = {0};
    c.slotId = pColNode->slotId;
H
Haojun Liao 已提交
6700 6701 6702
    c.colId  = pColNode->colId;
    c.type   = pColNode->node.resType.type;
    c.bytes  = pColNode->node.resType.bytes;
L
Liu Jicong 已提交
6703 6704
    c.precision = pColNode->node.resType.precision;
    c.scale = pColNode->node.resType.scale;
H
Haojun Liao 已提交
6705 6706 6707 6708 6709 6710 6711

    taosArrayPush(pList, &c);
  }

  return pList;
}

6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737
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;
    c.colId  = pColNode->colId;
    c.type   = pColNode->node.resType.type;
    c.bytes  = pColNode->node.resType.bytes;
    c.precision = pColNode->node.resType.precision;
    c.scale = pColNode->node.resType.scale;

    taosArrayPush(pList, &c);
  }

  return pList;
}

6738
SArray* createSortInfo(SNodeList* pNodeList, SNodeList* pNodeListTarget) {
L
Liu Jicong 已提交
6739
  size_t  numOfCols = LIST_LENGTH(pNodeList);
H
Haojun Liao 已提交
6740 6741 6742 6743 6744 6745
  SArray* pList = taosArrayInit(numOfCols, sizeof(SBlockOrderInfo));
  if (pList == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return pList;
  }

L
Liu Jicong 已提交
6746
  for (int32_t i = 0; i < numOfCols; ++i) {
6747
    
6748
    SOrderByExprNode* pSortKey = (SOrderByExprNode*)nodesListGetNode(pNodeList, i);
L
Liu Jicong 已提交
6749 6750
    SBlockOrderInfo   bi = {0};
    bi.order = (pSortKey->order == ORDER_ASC) ? TSDB_ORDER_ASC : TSDB_ORDER_DESC;
H
Haojun Liao 已提交
6751 6752 6753 6754
    bi.nullFirst = (pSortKey->nullOrder == NULL_ORDER_FIRST);

    SColumnNode* pColNode = (SColumnNode*)pSortKey->pExpr;

6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769
    bool found = false;
    for (int32_t j = 0; j < LIST_LENGTH(pNodeListTarget); ++j) {
      STargetNode* pTarget = (STargetNode*)nodesListGetNode(pNodeListTarget, j);

      SColumnNode* pColNodeT = (SColumnNode*)pTarget->pExpr;
      if(pColNode->slotId == pColNodeT->slotId){    // to find slotId in PhysiSort OutputDataBlockDesc
        bi.slotId = pTarget->slotId;
        found = true;
        break;
      }
    }

    if(!found){
      qError("sort slot id does not found");
    }
H
Haojun Liao 已提交
6770 6771 6772 6773 6774 6775
    taosArrayPush(pList, &bi);
  }

  return pList;
}

6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793
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 已提交
6794
SArray* extractColMatchInfo(SNodeList* pNodeList, SDataBlockDescNode* pOutputNodeList, int32_t* numOfOutputCols) {
L
Liu Jicong 已提交
6795
  size_t  numOfCols = LIST_LENGTH(pNodeList);
H
Haojun Liao 已提交
6796 6797 6798 6799 6800 6801
  SArray* pList = taosArrayInit(numOfCols, sizeof(SColMatchInfo));
  if (pList == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

L
Liu Jicong 已提交
6802 6803 6804
  for (int32_t i = 0; i < numOfCols; ++i) {
    STargetNode* pNode = (STargetNode*)nodesListGetNode(pNodeList, i);
    SColumnNode* pColNode = (SColumnNode*)pNode->pExpr;
H
Haojun Liao 已提交
6805 6806

    SColMatchInfo c = {0};
L
Liu Jicong 已提交
6807
    c.colId = pColNode->colId;
H
Haojun Liao 已提交
6808
    c.targetSlotId = pNode->slotId;
L
Liu Jicong 已提交
6809
    c.output = true;
H
Haojun Liao 已提交
6810 6811 6812
    taosArrayPush(pList, &c);
  }

H
Haojun Liao 已提交
6813 6814
  *numOfOutputCols = 0;
  int32_t num = LIST_LENGTH(pOutputNodeList->pSlots);
L
Liu Jicong 已提交
6815 6816
  for (int32_t i = 0; i < num; ++i) {
    SSlotDescNode* pNode = (SSlotDescNode*)nodesListGetNode(pOutputNodeList->pSlots, i);
6817 6818 6819 6820 6821 6822
    // todo: add reserve flag check
    if (pNode->slotId >= numOfCols) { // it is a column reserved for the arithmetic expression calculation
      (*numOfOutputCols) += 1;
      continue;
    }

H
Haojun Liao 已提交
6823
    SColMatchInfo* info = taosArrayGet(pList, pNode->slotId);
H
Haojun Liao 已提交
6824 6825 6826 6827 6828
    if (pNode->output) {
      (*numOfOutputCols) += 1;
    } else {
      info->output = false;
    }
H
Haojun Liao 已提交
6829 6830
  }

H
Haojun Liao 已提交
6831 6832 6833
  return pList;
}

H
Haojun Liao 已提交
6834
int32_t doCreateTableGroup(void* metaHandle, int32_t tableType, uint64_t tableUid, STableGroupInfo* pGroupInfo, uint64_t queryId, uint64_t taskId) {
6835
  int32_t code = 0;
H
Haojun Liao 已提交
6836
  if (tableType == TSDB_SUPER_TABLE) {
H
Haojun Liao 已提交
6837
    code = tsdbQuerySTableByTagCond(metaHandle, tableUid, 0, NULL, 0, 0, NULL, pGroupInfo, NULL, 0, queryId, taskId);
H
Haojun Liao 已提交
6838
  } else {  // Create one table group.
H
Haojun Liao 已提交
6839
    code = tsdbGetOneTableGroup(metaHandle, tableUid, 0, pGroupInfo);
6840 6841 6842 6843
  }

  return code;
}
H
Haojun Liao 已提交
6844

6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862
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 已提交
6863 6864
tsdbReaderT doCreateDataReader(STableScanPhysiNode* pTableScanNode, SReadHandle* pHandle,
                               STableGroupInfo* pTableGroupInfo, uint64_t queryId, uint64_t taskId) {
6865
  uint64_t uid = pTableScanNode->scan.uid;
L
Liu Jicong 已提交
6866 6867
  int32_t  code =
      doCreateTableGroup(pHandle->meta, pTableScanNode->scan.tableType, uid, pTableGroupInfo, queryId, taskId);
6868 6869
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
H
Haojun Liao 已提交
6870
  }
H
Haojun Liao 已提交
6871

H
Haojun Liao 已提交
6872
  if (pTableGroupInfo->numOfTables == 0) {
H
Haojun Liao 已提交
6873
    code = 0;
L
Liu Jicong 已提交
6874
    qDebug("no table qualified for query, TID:0x%" PRIx64 ", QID:0x%" PRIx64, taskId, queryId);
H
Haojun Liao 已提交
6875 6876
    goto _error;
  }
H
Haojun Liao 已提交
6877

H
Haojun Liao 已提交
6878
  return createDataReaderImpl(pTableScanNode, pTableGroupInfo, pHandle->reader, queryId, taskId);
H
Haojun Liao 已提交
6879

L
Liu Jicong 已提交
6880
_error:
H
Haojun Liao 已提交
6881 6882 6883 6884
  terrno = code;
  return NULL;
}

6885
int32_t createExecTaskInfoImpl(SSubplan* pPlan, SExecTaskInfo** pTaskInfo, SReadHandle* pHandle, uint64_t taskId, EOPTR_EXEC_MODEL model) {
H
Haojun Liao 已提交
6886 6887
  uint64_t queryId = pPlan->id.queryId;

H
Haojun Liao 已提交
6888
  int32_t code = TSDB_CODE_SUCCESS;
6889
  *pTaskInfo = createExecTaskInfo(queryId, taskId, model);
H
Haojun Liao 已提交
6890 6891 6892 6893
  if (*pTaskInfo == NULL) {
    code = TSDB_CODE_QRY_OUT_OF_MEMORY;
    goto _complete;
  }
H
Haojun Liao 已提交
6894

H
Haojun Liao 已提交
6895
  STableGroupInfo group = {0};
H
Haojun Liao 已提交
6896
  (*pTaskInfo)->pRoot = createOperatorTree(pPlan->pNode, *pTaskInfo, pHandle, queryId, taskId, &group);
D
dapan1121 已提交
6897
  if (NULL == (*pTaskInfo)->pRoot) {
L
Liu Jicong 已提交
6898
    code = terrno;
D
dapan1121 已提交
6899 6900
    goto _complete;
  }
H
Haojun Liao 已提交
6901

6902
  if ((*pTaskInfo)->pRoot == NULL) {
H
Haojun Liao 已提交
6903
    code = TSDB_CODE_QRY_OUT_OF_MEMORY;
H
Haojun Liao 已提交
6904
    goto _complete;
6905 6906
  }

H
Haojun Liao 已提交
6907 6908
  return code;

H
Haojun Liao 已提交
6909
_complete:
wafwerar's avatar
wafwerar 已提交
6910
  taosMemoryFreeClear(*pTaskInfo);
H
Haojun Liao 已提交
6911 6912 6913

  terrno = code;
  return code;
H
Haojun Liao 已提交
6914 6915
}

L
Liu Jicong 已提交
6916 6917
static int32_t updateOutputBufForTopBotQuery(SQueriedTableInfo* pTableInfo, SColumnInfo* pTagCols, SExprInfo* pExprs,
                                             int32_t numOfOutput, int32_t tagLen, bool superTable) {
6918 6919 6920 6921 6922 6923 6924 6925 6926
  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 已提交
6927 6928 6929 6930
        //        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);
6931 6932 6933 6934 6935 6936 6937
      }
    }
  }

  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
6938
void setResultBufSize(STaskAttr* pQueryAttr, SResultInfo* pResultInfo) {
6939 6940 6941 6942 6943 6944 6945 6946
  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;

H
Haojun Liao 已提交
6947 6948 6949 6950 6951 6952 6953 6954 6955 6956
//  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;
//  }
6957 6958

  pResultInfo->threshold = (int32_t)(pResultInfo->capacity * THRESHOLD_RATIO);
H
Haojun Liao 已提交
6959
  pResultInfo->totalRows = 0;
6960 6961
}

L
Liu Jicong 已提交
6962
// TODO refactor
6963
void freeColumnFilterInfo(SColumnFilterInfo* pFilter, int32_t numOfFilters) {
L
Liu Jicong 已提交
6964 6965 6966
  if (pFilter == NULL || numOfFilters == 0) {
    return;
  }
6967

L
Liu Jicong 已提交
6968 6969 6970
  for (int32_t i = 0; i < numOfFilters; i++) {
    if (pFilter[i].filterstr && pFilter[i].pz) {
      taosMemoryFree((void*)(pFilter[i].pz));
6971
    }
L
Liu Jicong 已提交
6972
  }
6973

L
Liu Jicong 已提交
6974
  taosMemoryFree(pFilter);
6975 6976 6977 6978
}

static void doDestroyTableQueryInfo(STableGroupInfo* pTableqinfoGroupInfo) {
  if (pTableqinfoGroupInfo->pGroupList != NULL) {
L
Liu Jicong 已提交
6979
    int32_t numOfGroups = (int32_t)taosArrayGetSize(pTableqinfoGroupInfo->pGroupList);
6980
    for (int32_t i = 0; i < numOfGroups; ++i) {
L
Liu Jicong 已提交
6981
      SArray* p = taosArrayGetP(pTableqinfoGroupInfo->pGroupList, i);
6982 6983

      size_t num = taosArrayGetSize(p);
L
Liu Jicong 已提交
6984
      for (int32_t j = 0; j < num; ++j) {
6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000
        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 已提交
7001
void doDestroyTask(SExecTaskInfo* pTaskInfo) {
H
Haojun Liao 已提交
7002 7003
  qDebug("%s execTask is freed", GET_TASKID(pTaskInfo));

H
Haojun Liao 已提交
7004
  doDestroyTableQueryInfo(&pTaskInfo->tableqinfoGroupInfo);
L
Liu Jicong 已提交
7005 7006
  //  taosArrayDestroy(pTaskInfo->summary.queryProfEvents);
  //  taosHashCleanup(pTaskInfo->summary.operatorProfResults);
7007

wafwerar's avatar
wafwerar 已提交
7008 7009 7010
  taosMemoryFreeClear(pTaskInfo->sql);
  taosMemoryFreeClear(pTaskInfo->id.str);
  taosMemoryFreeClear(pTaskInfo);
7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022
}

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 已提交
7023
      int32_t len = (varDataLen(val) > maxLen) ? maxLen : varDataLen(val);
7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035
      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 已提交
7036 7037
  //  size_t s3 = sizeof(STableCheckInfo);  buffer consumption in tsdb
  return (int64_t)(s1 * 1.5 * numOfTables);
7038 7039 7040 7041 7042 7043 7044
}

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 已提交
7045
    while (1) {
7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071
      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 已提交
7072

D
dapan1121 已提交
7073
int32_t getOperatorExplainExecInfo(SOperatorInfo *operatorInfo, SExplainExecInfo **pRes, int32_t *capacity, int32_t *resNum) {
D
dapan1121 已提交
7074 7075 7076 7077 7078
  if (*resNum >= *capacity) {
    *capacity += 10;
    
    *pRes = taosMemoryRealloc(*pRes, (*capacity) * sizeof(SExplainExecInfo));
    if (NULL == *pRes) {
D
dapan1121 已提交
7079
      qError("malloc %d failed", (*capacity) * (int32_t)sizeof(SExplainExecInfo));
D
dapan1121 已提交
7080 7081 7082 7083
      return TSDB_CODE_QRY_OUT_OF_MEMORY;
    }
  }

D
dapan1121 已提交
7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094
  (*pRes)[*resNum].numOfRows = operatorInfo->resultInfo.totalRows;
  (*pRes)[*resNum].startupCost = operatorInfo->cost.openCost;
  (*pRes)[*resNum].totalCost = operatorInfo->cost.totalCost;

  if (operatorInfo->getExplainFn) {
    int32_t code = (*operatorInfo->getExplainFn)(operatorInfo, &(*pRes)->verboseInfo);
    if (code) {
      qError("operator getExplainFn failed, error:%s", tstrerror(code));
      return code;
    }
  }
D
dapan1121 已提交
7095 7096 7097 7098
  
  ++(*resNum);
  
  int32_t code = 0;
D
dapan1121 已提交
7099 7100
  for (int32_t i = 0; i < operatorInfo->numOfDownstream; ++i) {
    code = getOperatorExplainExecInfo(operatorInfo->pDownstream[i], pRes, capacity, resNum);
D
dapan1121 已提交
7101 7102 7103 7104 7105 7106 7107
    if (code) {
      taosMemoryFreeClear(*pRes);
      return TSDB_CODE_QRY_OUT_OF_MEMORY;
    }
  }

  return TSDB_CODE_SUCCESS;
D
dapan1121 已提交
7108 7109
}

7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186
static SSDataBlock* doMergeJoin(struct SOperatorInfo* pOperator, bool* newgroup) {
  SJoinOperatorInfo* pJoinInfo = pOperator->info;
//  SOptrBasicInfo* pInfo = &pJoinInfo->binfo;

  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);
      pJoinInfo->pLeft = ds1->getNextFn(ds1, newgroup);
      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);
      pJoinInfo->pRight = ds2->getNextFn(ds2, newgroup);
      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);
    char* pLeftVal  = colDataGetData(pLeftCol, pJoinInfo->leftPos);

    SColumnInfoData* pRightCol = taosArrayGet(pJoinInfo->pRight->pDataBlock, pJoinInfo->rightCol.slotId);
    char* pRightVal = colDataGetData(pRightCol, pJoinInfo->rightPos);

    // only the timestamp match support for ordinary table
      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);

          SExprInfo* pExprInfo = &pOperator->pExpr[i];

          int32_t blockId = pExprInfo->base.pParam[0].pCol->dataBlockId;
          int32_t slotId = pExprInfo->base.pParam[0].pCol->slotId;

          SColumnInfoData* pSrc = NULL;
          if (pJoinInfo->pLeft->info.blockId == blockId) {
            pSrc = taosArrayGet(pJoinInfo->pLeft->pDataBlock, slotId);
          } else {
            pSrc = taosArrayGet(pJoinInfo->pRight->pDataBlock, slotId);
          }

          if (colDataIsNull_s(pSrc, pJoinInfo->leftPos)) {
            colDataAppendNULL(pDst, nrows);
          } else {
            char* p = colDataGetData(pSrc, pJoinInfo->leftPos);
            colDataAppend(pDst, nrows, p, false);
          }
        }

        pJoinInfo->leftPos += 1;
        pJoinInfo->rightPos += 1;

        nrows += 1;
      } else if (*(int64_t*) pLeftVal < *(int64_t*) pRightVal) {
        pJoinInfo->leftPos += 1;
D
dapan1121 已提交
7187

7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223
        if (pJoinInfo->leftPos >= pJoinInfo->pLeft->info.rows) {
          continue;
        }
      } else if (*(int64_t*) pLeftVal > *(int64_t*) pRightVal) {
        pJoinInfo->rightPos += 1;
        if (pJoinInfo->rightPos >= pJoinInfo->pRight->info.rows) {
          continue;
        }
      }

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

SOperatorInfo* createJoinOperatorInfo(SOperatorInfo** pDownstream, int32_t numOfDownstream, SExprInfo* pExprInfo, int32_t numOfCols, SSDataBlock* pResBlock, SNode* pOnCondition, SExecTaskInfo* pTaskInfo) {
  SJoinOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SJoinOperatorInfo));
  SOperatorInfo* pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
  if (pOperator == NULL || pInfo == NULL) {
    goto _error;
  }

  pOperator->resultInfo.capacity = 4096;
  pOperator->resultInfo.threshold = 4096 * 0.75;

//  initResultRowInf
//  o(&pInfo->binfo.resultRowInfo, 8);
  pInfo->pRes             = pResBlock;

  pOperator->name         = "JoinOperator";
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_JOIN;
7224
  pOperator->blockingOptr = false;
7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241
  pOperator->status       = OP_NOT_OPENED;
  pOperator->pExpr        = pExprInfo;
  pOperator->numOfOutput  = numOfCols;
  pOperator->info         = pInfo;
  pOperator->pTaskInfo    = pTaskInfo;
  pOperator->getNextFn    = doMergeJoin;
  pOperator->closeFn      = destroyBasicOperatorInfo;

  int32_t code = appendDownstream(pOperator, pDownstream, numOfDownstream);
  return pOperator;

  _error:
  taosMemoryFree(pInfo);
  taosMemoryFree(pOperator);
  pTaskInfo->code = TSDB_CODE_OUT_OF_MEMORY;
  return NULL;
}