executorimpl.c 324.3 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
#include <filter.h>
H
Haojun Liao 已提交
17 18
#include <function.h>
#include <functionMgt.h>
H
Haojun Liao 已提交
19
#include <libs/function/function.h>
H
Haojun Liao 已提交
20
#include <querynodes.h>
H
Haojun Liao 已提交
21
#include <tname.h>
22
#include "os.h"
23

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

32
#include "../../function/inc/taggfunction.h"
33 34
#include "executorimpl.h"
#include "function.h"
35
#include "query.h"
36 37
#include "tcompare.h"
#include "tcompression.h"
H
Haojun Liao 已提交
38
#include "thash.h"
39
#include "tsdb.h"
40
#include "ttypes.h"
L
Liu Jicong 已提交
41
#include "vnode.h"
42

H
Haojun Liao 已提交
43
#define IS_MAIN_SCAN(runtime)          ((runtime)->scanFlag == MAIN_SCAN)
44 45
#define IS_REVERSE_SCAN(runtime)       ((runtime)->scanFlag == REVERSE_SCAN)
#define IS_REPEAT_SCAN(runtime)        ((runtime)->scanFlag == REPEAT_SCAN)
H
Haojun Liao 已提交
46
#define SET_MAIN_SCAN_FLAG(runtime)  ((runtime)->scanFlag = MAIN_SCAN)
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
#define SET_REVERSE_SCAN_FLAG(runtime) ((runtime)->scanFlag = REVERSE_SCAN)

#define TSWINDOW_IS_EQUAL(t1, t2) (((t1).skey == (t2).skey) && ((t1).ekey == (t2).ekey))
#define SWITCH_ORDER(n) (((n) = ((n) == TSDB_ORDER_ASC) ? TSDB_ORDER_DESC : TSDB_ORDER_ASC))

#define SDATA_BLOCK_INITIALIZER (SDataBlockInfo) {{0}, 0}

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

#define MULTI_KEY_DELIM  "-"

enum {
  TS_JOIN_TS_EQUAL       = 0,
  TS_JOIN_TS_NOT_EQUALS  = 1,
  TS_JOIN_TAG_NOT_EQUALS = 2,
};

typedef enum SResultTsInterpType {
  RESULT_ROW_START_INTERP = 1,
  RESULT_ROW_END_INTERP   = 2,
} SResultTsInterpType;

#if 0
static UNUSED_FUNC void *u_malloc (size_t __size) {
wafwerar's avatar
wafwerar 已提交
71
  uint32_t v = taosRand();
72 73 74 75 76 77 78 79 80

  if (v % 1000 <= 0) {
    return NULL;
  } else {
    return malloc(__size);
  }
}

static UNUSED_FUNC void* u_calloc(size_t num, size_t __size) {
wafwerar's avatar
wafwerar 已提交
81
  uint32_t v = taosRand();
82 83 84 85 86 87 88 89
  if (v % 1000 <= 0) {
    return NULL;
  } else {
    return calloc(num, __size);
  }
}

static UNUSED_FUNC void* u_realloc(void* p, size_t __size) {
wafwerar's avatar
wafwerar 已提交
90
  uint32_t v = taosRand();
91 92 93 94 95 96 97 98 99 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
  if (v % 5 <= 1) {
    return NULL;
  } else {
    return realloc(p, __size);
  }
}

#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)

#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() {
S
Shengliang Guan 已提交
144
  return tsShellActivityTimer * 2;
145 146 147 148
}

static int32_t getExprFunctionId(SExprInfo *pExprInfo) {
  assert(pExprInfo != NULL && pExprInfo->pExpr != NULL && pExprInfo->pExpr->nodeType == TEXPR_UNARYEXPR_NODE);
149
  return 0;
150 151
}

H
Haojun Liao 已提交
152 153 154 155 156
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;
157 158 159
    return;
  }

H
Haojun Liao 已提交
160
  int64_t key = tw->skey, interval = pInterval->interval;
161
  //convert key to second
H
Haojun Liao 已提交
162
  key = convertTimePrecision(key, precision, TSDB_TIME_PRECISION_MILLI) / 1000;
163

H
Haojun Liao 已提交
164
  if (pInterval->intervalUnit == 'y') {
165 166 167 168 169
    interval *= 12;
  }

  struct tm tm;
  time_t t = (time_t)key;
wafwerar's avatar
wafwerar 已提交
170
  taosLocalTime(&t, &tm);
171 172 173 174

  int mon = (int)(tm.tm_year * 12 + tm.tm_mon + interval * factor);
  tm.tm_year = mon / 12;
  tm.tm_mon = mon % 12;
H
Haojun Liao 已提交
175
  tw->skey = convertTimePrecision((int64_t)mktime(&tm) * 1000L, TSDB_TIME_PRECISION_MILLI, precision);
176 177 178 179

  mon = (int)(mon + interval);
  tm.tm_year = mon / 12;
  tm.tm_mon = mon % 12;
H
Haojun Liao 已提交
180
  tw->ekey = convertTimePrecision((int64_t)mktime(&tm) * 1000L, TSDB_TIME_PRECISION_MILLI, precision);
181 182 183 184 185

  tw->ekey -= 1;
}

static void doSetTagValueToResultBuf(char* output, const char* val, int16_t type, int16_t bytes);
H
Haojun Liao 已提交
186
static void setResultOutputBuf(STaskRuntimeEnv* pRuntimeEnv, SResultRow* pResult, SqlFunctionCtx* pCtx,
187 188
                               int32_t numOfCols, int32_t* rowCellInfoOffset);

H
Haojun Liao 已提交
189
void setResultRowOutputBufInitCtx(STaskRuntimeEnv *pRuntimeEnv, SResultRow *pResult, SqlFunctionCtx* pCtx, int32_t numOfOutput, int32_t* rowCellInfoOffset);
H
Haojun Liao 已提交
190
static bool functionNeedToExecute(SqlFunctionCtx *pCtx);
191

H
Haojun Liao 已提交
192
static void setBlockStatisInfo(SqlFunctionCtx *pCtx, SSDataBlock* pSDataBlock, SColumn* pColumn);
193 194

static void destroyTableQueryInfoImpl(STableQueryInfo *pTableQueryInfo);
H
Haojun Liao 已提交
195
static bool hasMainOutput(STaskAttr *pQueryAttr);
196 197 198

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

H
Haojun Liao 已提交
199
static int32_t setTimestampListJoinInfo(STaskRuntimeEnv* pRuntimeEnv, SVariant* pTag, STableQueryInfo *pTableQueryInfo);
200 201
static void releaseQueryBuf(size_t numOfTables);
static int32_t binarySearchForKey(char *pValue, int num, TSKEY key, int order);
H
Haojun Liao 已提交
202
//static STsdbQueryCond createTsdbQueryCond(STaskAttr* pQueryAttr, STimeWindow* win);
203 204 205 206
static STableIdInfo createTableIdInfo(STableQueryInfo* pTableQueryInfo);

static void setTableScanFilterOperatorInfo(STableScanInfo* pTableScanInfo, SOperatorInfo* pDownstream);

H
Haojun Liao 已提交
207
static int32_t getNumOfScanTimes(STaskAttr* pQueryAttr);
208 209 210 211 212 213 214 215 216 217

static void destroyBasicOperatorInfo(void* param, int32_t numOfOutput);
static void destroySFillOperatorInfo(void* param, int32_t numOfOutput);
static void destroyGroupbyOperatorInfo(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 已提交
218

H
Haojun Liao 已提交
219
static void destroyIntervalOperatorInfo(void* param, int32_t numOfOutput);
H
Haojun Liao 已提交
220 221 222
static void destroyExchangeOperatorInfo(void* param, int32_t numOfOutput);
static void destroyConditionOperatorInfo(void* param, int32_t numOfOutput);

223
static void destroyOperatorInfo(SOperatorInfo* pOperator);
224
static void destroySysTableScannerOperatorInfo(void* param, int32_t numOfOutput);
225 226 227

static void doSetOperatorCompleted(SOperatorInfo* pOperator) {
  pOperator->status = OP_EXEC_DONE;
H
Haojun Liao 已提交
228
  if (pOperator->pTaskInfo != NULL) {
229
    setTaskStatus(pOperator->pTaskInfo, TASK_COMPLETED);
230 231 232
  }
}

233 234 235
#define OPTR_IS_OPENED(_optr)  (((_optr)->status & OP_OPENED) == OP_OPENED)
#define OPTR_SET_OPENED(_optr) ((_optr)->status |= OP_OPENED)

H
Haojun Liao 已提交
236
static int32_t operatorDummyOpenFn(SOperatorInfo *pOperator) {
237
  OPTR_SET_OPENED(pOperator);
H
Haojun Liao 已提交
238
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
239 240
}

H
Haojun Liao 已提交
241 242
static void operatorDummyCloseFn(void* param, int32_t numOfCols) {}

243
static int32_t doCopyToSDataBlock(SDiskbasedBuf *pBuf, SGroupResInfo* pGroupResInfo, int32_t orderType, SSDataBlock* pBlock, int32_t rowCapacity, int32_t* rowCellOffset);
244 245

static int32_t getGroupbyColumnIndex(SGroupbyExpr *pGroupbyExpr, SSDataBlock* pDataBlock);
H
Haojun Liao 已提交
246 247
static int32_t setGroupResultOutputBuf_rv(SOptrBasicInfo *binfo, int32_t numOfCols, char *pData, int16_t type, int16_t bytes, int32_t groupId,
                                          SDiskbasedBuf* pBuf, SExecTaskInfo* pTaskInfo, SAggSupporter* pAggSup);
H
Haojun Liao 已提交
248
static void initCtxOutputBuffer(SqlFunctionCtx* pCtx, int32_t size);
H
Haojun Liao 已提交
249 250
static void getAlignQueryTimeWindow(SInterval* pInterval, int32_t precision, int64_t key, int64_t keyFirst, int64_t keyLast, STimeWindow *win);

H
Haojun Liao 已提交
251
static void setResultBufSize(STaskAttr* pQueryAttr, SResultInfo* pResultInfo);
H
Haojun Liao 已提交
252 253 254
static void setCtxTagForJoin(STaskRuntimeEnv* pRuntimeEnv, SqlFunctionCtx* pCtx, SExprInfo* pExprInfo, void* pTable);
static void setParamForStableStddev(STaskRuntimeEnv* pRuntimeEnv, SqlFunctionCtx* pCtx, int32_t numOfOutput, SExprInfo* pExpr);
static void setParamForStableStddevByColData(STaskRuntimeEnv* pRuntimeEnv, SqlFunctionCtx* pCtx, int32_t numOfOutput, SExprInfo* pExpr, char* val, int16_t bytes);
255
static void doSetTableGroupOutputBuf(SAggOperatorInfo* pAggInfo, int32_t numOfOutput, int32_t tableGroupId, SExecTaskInfo* pTaskInfo);
256

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

typedef struct SRowCompSupporter {
H
Haojun Liao 已提交
260
  STaskRuntimeEnv *pRuntimeEnv;
261 262 263 264 265 266 267 268 269
  int16_t           dataOffset;
  __compar_fn_t     comFunc;
} SRowCompSupporter;

static int compareRowData(const void *a, const void *b, const void *userData) {
  const SResultRow *pRow1 = (const SResultRow *)a;
  const SResultRow *pRow2 = (const SResultRow *)b;

  SRowCompSupporter *supporter  = (SRowCompSupporter *)userData;
H
Haojun Liao 已提交
270
  STaskRuntimeEnv* pRuntimeEnv =  supporter->pRuntimeEnv;
271

272 273
  SFilePage *page1 = getBufPage(pRuntimeEnv->pResultBuf, pRow1->pageId);
  SFilePage *page2 = getBufPage(pRuntimeEnv->pResultBuf, pRow2->pageId);
274 275 276 277 278 279 280 281

  int16_t offset = supporter->dataOffset;
  char *in1  = getPosInResultPage(pRuntimeEnv->pQueryAttr, page1, pRow1->offset, offset);
  char *in2  = getPosInResultPage(pRuntimeEnv->pQueryAttr, page2, pRow2->offset, offset);

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

H
Haojun Liao 已提交
282
static void sortGroupResByOrderList(SGroupResInfo *pGroupResInfo, STaskRuntimeEnv *pRuntimeEnv, SSDataBlock* pDataBlock) {
283 284 285 286 287 288 289 290
  SArray *columnOrderList = getOrderCheckColumns(pRuntimeEnv->pQueryAttr);
  size_t size = taosArrayGetSize(columnOrderList);
  taosArrayDestroy(columnOrderList);

  if (size <= 0) {
    return;
  }

H
Haojun Liao 已提交
291
  int32_t orderId = pRuntimeEnv->pQueryAttr->order.col.colId;
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
  if (orderId <= 0) {
    return;
  }

  bool found = false;
  int16_t dataOffset = 0;

  for (int32_t j = 0; j < pDataBlock->info.numOfCols; ++j) {
    SColumnInfoData* pColInfoData = (SColumnInfoData *)taosArrayGet(pDataBlock->pDataBlock, j);
    if (orderId == j) {
      found = true;
      break;
    }

    dataOffset += pColInfoData->info.bytes;
  }

  if (found == false) {
    return;
  }

  int16_t type = pRuntimeEnv->pQueryAttr->pExpr1[orderId].base.resSchema.type;

  SRowCompSupporter support = {.pRuntimeEnv = pRuntimeEnv, .dataOffset = dataOffset, .comFunc = getComparFunc(type, 0)};
  taosArraySortPWithExt(pGroupResInfo->pRows, compareRowData, &support);
}

//setup the output buffer for each operator
SSDataBlock* createOutputBuf(SExprInfo* pExpr, int32_t numOfOutput, int32_t numOfRows) {
  const static int32_t minSize = 8;

  SSDataBlock *res = calloc(1, sizeof(SSDataBlock));
  res->info.numOfCols = numOfOutput;
  res->pDataBlock = taosArrayInit(numOfOutput, sizeof(SColumnInfoData));
  for (int32_t i = 0; i < numOfOutput; ++i) {
    SColumnInfoData idata = {{0}};
    idata.info.type  = pExpr[i].base.resSchema.type;
    idata.info.bytes = pExpr[i].base.resSchema.bytes;
    idata.info.colId = pExpr[i].base.resSchema.colId;

dengyihao's avatar
dengyihao 已提交
332
    int32_t size = TMAX(idata.info.bytes * numOfRows, minSize);
333 334 335 336 337 338 339
    idata.pData = calloc(1, size);  // at least to hold a pointer on x64 platform
    taosArrayPush(res->pDataBlock, &idata);
  }

  return res;
}

H
Haojun Liao 已提交
340 341
SSDataBlock* createOutputBuf_rv1(SDataBlockDescNode* pNode) {
  int32_t numOfCols = LIST_LENGTH(pNode->pSlots);
H
Haojun Liao 已提交
342

H
Haojun Liao 已提交
343 344 345 346
  SSDataBlock* pBlock = calloc(1, sizeof(SSDataBlock));
  pBlock->info.numOfCols = numOfCols;
  pBlock->pDataBlock = taosArrayInit(numOfCols, sizeof(SColumnInfoData));

H
Haojun Liao 已提交
347
  pBlock->info.blockId = pNode->dataBlockId;
H
Haojun Liao 已提交
348
  pBlock->info.rowSize = pNode->resultRowSize;
H
Haojun Liao 已提交
349

H
Haojun Liao 已提交
350 351 352
  for(int32_t i = 0; i < numOfCols; ++i) {
    SColumnInfoData idata = {{0}};
    SSlotDescNode* pDescNode = nodesListGetNode(pNode->pSlots, i);
H
Haojun Liao 已提交
353 354 355
    idata.info.type   = pDescNode->dataType.type;
    idata.info.bytes  = pDescNode->dataType.bytes;
    idata.info.scale  = pDescNode->dataType.scale;
H
Haojun Liao 已提交
356
    idata.info.slotId = pDescNode->slotId;
H
Haojun Liao 已提交
357 358 359
    idata.info.precision = pDescNode->dataType.precision;

    taosArrayPush(pBlock->pDataBlock, &idata);
H
Haojun Liao 已提交
360
  }
H
Haojun Liao 已提交
361 362

  return pBlock;
H
Haojun Liao 已提交
363 364
}

H
Haojun Liao 已提交
365
static bool isSelectivityWithTagsQuery(SqlFunctionCtx *pCtx, int32_t numOfOutput) {
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
  return true;
//  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);
}

H
Haojun Liao 已提交
385
static bool isProjQuery(STaskAttr *pQueryAttr) {
386 387 388 389 390 391 392 393 394 395
  for (int32_t i = 0; i < pQueryAttr->numOfOutput; ++i) {
    int32_t functId = getExprFunctionId(&pQueryAttr->pExpr1[i]);
    if (functId != FUNCTION_PRJ && functId != FUNCTION_TAGPRJ) {
      return false;
    }
  }

  return true;
}

H
Haojun Liao 已提交
396
static bool hasNull(SColumn* pColumn, SColumnDataAgg *pStatis) {
H
Haojun Liao 已提交
397
  if (TSDB_COL_IS_TAG(pColumn->flag) || TSDB_COL_IS_UD_COL(pColumn->flag) || pColumn->colId == PRIMARYKEY_TIMESTAMP_COL_ID) {
398 399 400 401 402 403 404 405 406 407
    return false;
  }

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

  return true;
}

H
Haojun Liao 已提交
408
static void prepareResultListBuffer(SResultRowInfo* pResultRowInfo, jmp_buf env) {
409 410
  int64_t newCapacity = 0;

411 412 413 414 415 416 417 418 419 420 421
  // 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 已提交
422 423 424 425
  if (newCapacity == pResultRowInfo->capacity) {
    newCapacity += 4;
  }

426 427
  char *t = realloc(pResultRowInfo->pResult, (size_t)(newCapacity * POINTER_BYTES));
  if (t == NULL) {
H
Haojun Liao 已提交
428
    longjmp(env, TSDB_CODE_QRY_OUT_OF_MEMORY);
429 430
  }

431
  pResultRowInfo->pPosition = realloc(pResultRowInfo->pPosition, newCapacity * sizeof(SResultRowPosition));
432 433 434 435
  pResultRowInfo->pResult = (SResultRow **)t;

  int32_t inc = (int32_t)newCapacity - pResultRowInfo->capacity;
  memset(&pResultRowInfo->pResult[pResultRowInfo->capacity], 0, POINTER_BYTES * inc);
436
  memset(&pResultRowInfo->pPosition[pResultRowInfo->capacity], 0, sizeof(SResultRowPosition));
437 438 439 440

  pResultRowInfo->capacity = (int32_t)newCapacity;
}

H
Haojun Liao 已提交
441
static bool chkResultRowFromKey(STaskRuntimeEnv *pRuntimeEnv, SResultRowInfo *pResultRowInfo, char *pData,
442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478
                                             int16_t bytes, bool masterscan, uint64_t uid) {
  bool existed = false;
  SET_RES_WINDOW_KEY(pRuntimeEnv->keyBuf, pData, bytes, uid);

  SResultRow **p1 =
      (SResultRow **)taosHashGet(pRuntimeEnv->pResultRowHashTable, pRuntimeEnv->keyBuf, GET_RES_WINDOW_KEY_LEN(bytes));

  // 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;
        assert(pResultRowInfo->curPos == -1);
      } else if (pResultRowInfo->size == 1) {
        existed = (pResultRowInfo->pResult[0] == (*p1));
      } else {  // check if current pResultRowInfo contains the existed pResultRow
        SET_RES_EXT_WINDOW_KEY(pRuntimeEnv->keyBuf, pData, bytes, uid, pResultRowInfo);
        int64_t* index = taosHashGet(pRuntimeEnv->pResultRowListSet, pRuntimeEnv->keyBuf, GET_RES_EXT_WINDOW_KEY_LEN(bytes));
        if (index != NULL) {
          existed = true;
        } else {
          existed = false;
        }
      }
    }

    return existed;
  }

  return p1 != NULL;
}


H
Haojun Liao 已提交
479
static SResultRow* doSetResultOutBufByKey(STaskRuntimeEnv* pRuntimeEnv, SResultRowInfo* pResultRowInfo, int64_t tid,
480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
                                          char* pData, int16_t bytes, bool masterscan, uint64_t tableGroupId) {
  bool existed = false;
  SET_RES_WINDOW_KEY(pRuntimeEnv->keyBuf, pData, bytes, tableGroupId);

  SResultRow **p1 =
      (SResultRow **)taosHashGet(pRuntimeEnv->pResultRowHashTable, pRuntimeEnv->keyBuf, GET_RES_WINDOW_KEY_LEN(bytes));

  // 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)? *p1:NULL;
    }

    if (p1 != NULL) {
      if (pResultRowInfo->size == 0) {
        existed = false;
        assert(pResultRowInfo->curPos == -1);
      } else if (pResultRowInfo->size == 1) {
        existed = (pResultRowInfo->pResult[0] == (*p1));
        pResultRowInfo->curPos = 0;
      } else {  // check if current pResultRowInfo contains the existed pResultRow
        SET_RES_EXT_WINDOW_KEY(pRuntimeEnv->keyBuf, pData, bytes, tid, pResultRowInfo);
        int64_t* index = taosHashGet(pRuntimeEnv->pResultRowListSet, pRuntimeEnv->keyBuf, GET_RES_EXT_WINDOW_KEY_LEN(bytes));
        if (index != NULL) {
          pResultRowInfo->curPos = (int32_t) *index;
          existed = true;
        } else {
          existed = false;
        }
      }
    }
  } else {
    // In case of group by column query, the required SResultRow object must be existed in the pResultRowInfo object.
    if (p1 != NULL) {
      return *p1;
    }
  }

  if (!existed) {
H
Haojun Liao 已提交
519
//    prepareResultListBuffer(pResultRowInfo, pRuntimeEnv);
520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552

    SResultRow *pResult = NULL;
    if (p1 == NULL) {
      pResult = getNewResultRow(pRuntimeEnv->pool);
      int32_t ret = initResultRow(pResult);
      if (ret != TSDB_CODE_SUCCESS) {
        longjmp(pRuntimeEnv->env, TSDB_CODE_QRY_OUT_OF_MEMORY);
      }

      // add a new result set for a new group
      taosHashPut(pRuntimeEnv->pResultRowHashTable, pRuntimeEnv->keyBuf, GET_RES_WINDOW_KEY_LEN(bytes), &pResult, POINTER_BYTES);
      SResultRowCell cell = {.groupId = tableGroupId, .pRow = pResult};
      taosArrayPush(pRuntimeEnv->pResultRowArrayList, &cell);
    } else {
      pResult = *p1;
    }

    pResultRowInfo->curPos = pResultRowInfo->size;
    pResultRowInfo->pResult[pResultRowInfo->size++] = pResult;

    int64_t index = pResultRowInfo->curPos;
    SET_RES_EXT_WINDOW_KEY(pRuntimeEnv->keyBuf, pData, bytes, tid, pResultRowInfo);
    taosHashPut(pRuntimeEnv->pResultRowListSet, pRuntimeEnv->keyBuf, GET_RES_EXT_WINDOW_KEY_LEN(bytes), &index, POINTER_BYTES);
  }

  // too many time window in query
  if (pResultRowInfo->size > MAX_INTERVAL_TIME_WINDOW) {
    longjmp(pRuntimeEnv->env, TSDB_CODE_QRY_TOO_MANY_TIMEWINDOW);
  }

  return pResultRowInfo->pResult[pResultRowInfo->curPos];
}

553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
SResultRow* getNewResultRow_rv(SDiskbasedBuf* pResultBuf, int64_t tableGroupId, int32_t interBufSize) {
  SFilePage *pData = NULL;

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

    if (pData->num + interBufSize + sizeof(SResultRow) > getBufPageSize(pResultBuf)) {
      // 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;

  pData->num += interBufSize + sizeof(SResultRow);

  return pResultRow;
}

static SResultRow* doSetResultOutBufByKey_rv(SDiskbasedBuf* pResultBuf, SResultRowInfo* pResultRowInfo, int64_t tid, char* pData, int16_t bytes,
594
    bool masterscan, uint64_t tableGroupId, SExecTaskInfo* pTaskInfo, bool isIntervalQuery, SAggSupporter* pSup) {
H
Haojun Liao 已提交
595
  bool existed = false;
596
  SET_RES_WINDOW_KEY(pSup->keyBuf, pData, bytes, tableGroupId);
H
Haojun Liao 已提交
597 598

  SResultRow **p1 =
599
      (SResultRow **)taosHashGet(pSup->pResultRowHashTable, pSup->keyBuf, GET_RES_WINDOW_KEY_LEN(bytes));
H
Haojun Liao 已提交
600 601 602 603 604 605 606 607 608 609 610 611 612 613 614

  // 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.
      return (p1 != NULL)? *p1:NULL;
    }

    if (p1 != NULL) {
      if (pResultRowInfo->size == 0) {
        existed = false;
        assert(pResultRowInfo->curPos == -1);
      } else if (pResultRowInfo->size == 1) {
        existed = (pResultRowInfo->pResult[0] == (*p1));
        pResultRowInfo->curPos = 0;
      } else {  // check if current pResultRowInfo contains the existed pResultRow
615 616
        SET_RES_EXT_WINDOW_KEY(pSup->keyBuf, pData, bytes, tid, pResultRowInfo);
        int64_t* index = taosHashGet(pSup->pResultRowListSet, pSup->keyBuf, GET_RES_EXT_WINDOW_KEY_LEN(bytes));
H
Haojun Liao 已提交
617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636
        if (index != NULL) {
          pResultRowInfo->curPos = (int32_t) *index;
          existed = true;
        } else {
          existed = false;
        }
      }
    }
  } else {
    // In case of group by column query, the required SResultRow object must be existed in the pResultRowInfo object.
    if (p1 != NULL) {
      return *p1;
    }
  }

  if (!existed) {
    prepareResultListBuffer(pResultRowInfo, pTaskInfo->env);

    SResultRow *pResult = NULL;
    if (p1 == NULL) {
637
      pResult = getNewResultRow_rv(pResultBuf, tableGroupId, pSup->resultRowSize);
H
Haojun Liao 已提交
638 639 640 641 642 643
      int32_t ret = initResultRow(pResult);
      if (ret != TSDB_CODE_SUCCESS) {
        longjmp(pTaskInfo->env, TSDB_CODE_QRY_OUT_OF_MEMORY);
      }

      // add a new result set for a new group
644
      taosHashPut(pSup->pResultRowHashTable, pSup->keyBuf, GET_RES_WINDOW_KEY_LEN(bytes), &pResult, POINTER_BYTES);
H
Haojun Liao 已提交
645
      SResultRowCell cell = {.groupId = tableGroupId, .pRow = pResult};
646
      taosArrayPush(pSup->pResultRowArrayList, &cell);
H
Haojun Liao 已提交
647 648 649 650 651
    } else {
      pResult = *p1;
    }

    pResultRowInfo->curPos = pResultRowInfo->size;
652
    pResultRowInfo->pPosition[pResultRowInfo->size] = (SResultRowPosition) {.pageId = pResult->pageId, .offset = pResult->offset};
H
Haojun Liao 已提交
653 654 655
    pResultRowInfo->pResult[pResultRowInfo->size++] = pResult;

    int64_t index = pResultRowInfo->curPos;
656 657
    SET_RES_EXT_WINDOW_KEY(pSup->keyBuf, pData, bytes, tid, pResultRowInfo);
    taosHashPut(pSup->pResultRowListSet, pSup->keyBuf, GET_RES_EXT_WINDOW_KEY_LEN(bytes), &index, POINTER_BYTES);
H
Haojun Liao 已提交
658 659 660 661 662 663 664 665 666 667
  }

  // too many time window in query
  if (pResultRowInfo->size > MAX_INTERVAL_TIME_WINDOW) {
    longjmp(pTaskInfo->env, TSDB_CODE_QRY_TOO_MANY_TIMEWINDOW);
  }

  return pResultRowInfo->pResult[pResultRowInfo->curPos];
}

H
Haojun Liao 已提交
668 669 670
static void getInitialStartTimeWindow(SInterval* pInterval, int32_t precision, TSKEY ts, STimeWindow* w, TSKEY ekey, bool ascQuery) {
  if (ascQuery) {
    getAlignQueryTimeWindow(pInterval, precision, ts, ts, ekey, w);
671 672
  } else {
    // the start position of the first time window in the endpoint that spreads beyond the queried last timestamp
H
Haojun Liao 已提交
673
    getAlignQueryTimeWindow(pInterval, precision, ts, ekey, ts, w);
674 675 676

    int64_t key = w->skey;
    while(key < ts) { // moving towards end
677
      key = taosTimeAdd(key, pInterval->sliding, pInterval->slidingUnit, precision);
678 679 680 681 682 683 684 685 686 687
      if (key >= ts) {
        break;
      }

      w->skey = key;
    }
  }
}

// get the correct time window according to the handled timestamp
H
Haojun Liao 已提交
688
static STimeWindow getActiveTimeWindow(SResultRowInfo * pResultRowInfo, int64_t ts, SInterval* pInterval, int32_t precision, STimeWindow* win) {
689 690 691
  STimeWindow w = {0};

 if (pResultRowInfo->curPos == -1) {  // the first window, from the previous stored value
H
Haojun Liao 已提交
692
    getInitialStartTimeWindow(pInterval, precision, ts, &w, win->ekey, true);
693
    w.ekey = taosTimeAdd(w.skey, pInterval->interval, pInterval->intervalUnit, precision) - 1;
694 695 696 697 698
  } else {
    w = getResultRow(pResultRowInfo, pResultRowInfo->curPos)->win;
  }

  if (w.skey > ts || w.ekey < ts) {
H
Haojun Liao 已提交
699 700 701
    if (pInterval->intervalUnit == 'n' || pInterval->intervalUnit == 'y') {
      w.skey = taosTimeTruncate(ts, pInterval, precision);
      w.ekey = taosTimeAdd(w.skey, pInterval->interval, pInterval->intervalUnit, precision) - 1;
702 703 704 705
    } else {
      int64_t st = w.skey;

      if (st > ts) {
H
Haojun Liao 已提交
706
        st -= ((st - ts + pInterval->sliding - 1) / pInterval->sliding) * pInterval->sliding;
707 708
      }

H
Haojun Liao 已提交
709
      int64_t et = st + pInterval->interval - 1;
710
      if (et < ts) {
H
Haojun Liao 已提交
711
        st += ((ts - et + pInterval->sliding - 1) / pInterval->sliding) * pInterval->sliding;
712 713 714
      }

      w.skey = st;
715
      w.ekey = taosTimeAdd(w.skey, pInterval->interval, pInterval->intervalUnit, precision) - 1;
716 717 718 719 720 721
    }
  }
  return w;
}

// get the correct time window according to the handled timestamp
H
Haojun Liao 已提交
722
static STimeWindow getCurrentActiveTimeWindow(SResultRowInfo * pResultRowInfo, int64_t ts, STaskAttr *pQueryAttr) {
723 724 725
  STimeWindow w = {0};

 if (pResultRowInfo->curPos == -1) {  // the first window, from the previous stored value
H
Haojun Liao 已提交
726
//    getInitialStartTimeWindow(pQueryAttr, ts, &w);
727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748

    if (pQueryAttr->interval.intervalUnit == 'n' || pQueryAttr->interval.intervalUnit == 'y') {
      w.ekey = taosTimeAdd(w.skey, pQueryAttr->interval.interval, pQueryAttr->interval.intervalUnit, pQueryAttr->precision) - 1;
    } else {
      w.ekey = w.skey + pQueryAttr->interval.interval - 1;
    }
  } else {
    w = getResultRow(pResultRowInfo, pResultRowInfo->curPos)->win;
  }

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

  return w;
}

// a new buffer page for each table. Needs to opt this design
749
static int32_t addNewWindowResultBuf(SResultRow *pWindowRes, SDiskbasedBuf *pResultBuf, int32_t tid, uint32_t size) {
750 751 752 753 754 755 756 757 758 759 760
  if (pWindowRes->pageId != -1) {
    return 0;
  }

  SFilePage *pData = NULL;

  // 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 已提交
761
    pData = getNewBufPage(pResultBuf, tid, &pageId);
762
    pData->num = sizeof(SFilePage);
763 764
  } else {
    SPageInfo* pi = getLastPageInfo(list);
765
    pData = getBufPage(pResultBuf, getPageId(pi));
766
    pageId = getPageId(pi);
767

768
    if (pData->num + size > getBufPageSize(pResultBuf)) {
769
      // release current page first, and prepare the next one
770
      releaseBufPageInfo(pResultBuf, pi);
771

H
Haojun Liao 已提交
772
      pData = getNewBufPage(pResultBuf, tid, &pageId);
773
      if (pData != NULL) {
774
        pData->num = sizeof(SFilePage);
775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794
      }
    }
  }

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

H
Haojun Liao 已提交
795
static bool chkWindowOutputBufByKey(STaskRuntimeEnv *pRuntimeEnv, SResultRowInfo *pResultRowInfo, STimeWindow *win,
H
Haojun Liao 已提交
796
                                       bool masterscan, SResultRow **pResult, int64_t groupId, SqlFunctionCtx* pCtx,
797 798 799 800 801
                                       int32_t numOfOutput, int32_t* rowCellInfoOffset) {
  assert(win->skey <= win->ekey);
  return chkResultRowFromKey(pRuntimeEnv, pResultRowInfo, (char *)&win->skey, TSDB_KEYSIZE, masterscan, groupId);
}

H
Haojun Liao 已提交
802
static int32_t setResultOutputBufByKey(STaskRuntimeEnv *pRuntimeEnv, SResultRowInfo *pResultRowInfo, int64_t tid, STimeWindow *win,
H
Haojun Liao 已提交
803
                                       bool masterscan, SResultRow **pResult, int64_t tableGroupId, SqlFunctionCtx* pCtx,
804 805
                                       int32_t numOfOutput, int32_t* rowCellInfoOffset) {
  assert(win->skey <= win->ekey);
806
  SDiskbasedBuf *pResultBuf = pRuntimeEnv->pResultBuf;
807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829

  SResultRow *pResultRow = doSetResultOutBufByKey(pRuntimeEnv, pResultRowInfo, tid, (char *)&win->skey, TSDB_KEYSIZE, masterscan, tableGroupId);
  if (pResultRow == NULL) {
    *pResult = NULL;
    return TSDB_CODE_SUCCESS;
  }

  // not assign result buffer yet, add new result buffer
  if (pResultRow->pageId == -1) {
    int32_t ret = addNewWindowResultBuf(pResultRow, pResultBuf, (int32_t) tableGroupId, pRuntimeEnv->pQueryAttr->intermediateResultRowSize);
    if (ret != TSDB_CODE_SUCCESS) {
      return -1;
    }
  }

  // set time window for current result
  pResultRow->win = (*win);
  *pResult = pResultRow;
  setResultRowOutputBufInitCtx(pRuntimeEnv, pResultRow, pCtx, numOfOutput, rowCellInfoOffset);

  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
830 831 832 833
static void setResultRowOutputBufInitCtx_rv(SDiskbasedBuf * pBuf, SResultRow *pResult, SqlFunctionCtx* pCtx, int32_t numOfOutput, int32_t* rowCellInfoOffset);

static int32_t setResultOutputBufByKey_rv(SResultRowInfo *pResultRowInfo, int64_t id, STimeWindow *win,
                                       bool masterscan, SResultRow **pResult, int64_t tableGroupId, SqlFunctionCtx* pCtx,
H
Haojun Liao 已提交
834
                                       int32_t numOfOutput, int32_t* rowCellInfoOffset, SAggSupporter *pAggSup, SExecTaskInfo* pTaskInfo) {
H
Haojun Liao 已提交
835
  assert(win->skey <= win->ekey);
H
Haojun Liao 已提交
836
  SResultRow *pResultRow = doSetResultOutBufByKey_rv(pAggSup->pResultBuf, pResultRowInfo, id, (char *)&win->skey, TSDB_KEYSIZE, masterscan, tableGroupId,
H
Haojun Liao 已提交
837 838 839 840 841 842 843 844 845 846
       pTaskInfo, true, pAggSup);

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

  // set time window for current result
  pResultRow->win = (*win);
  *pResult = pResultRow;
H
Haojun Liao 已提交
847
  setResultRowOutputBufInitCtx_rv(pAggSup->pResultBuf, pResultRow, pCtx, numOfOutput, rowCellInfoOffset);
H
Haojun Liao 已提交
848 849 850 851
  return TSDB_CODE_SUCCESS;
}


852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952
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 {
    pResult->endInterp   = true;
  }
}

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 {
    return pResult->endInterp   == true;
  }
}

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) {
  int32_t forwardStep = 0;

  if (order == TSDB_ORDER_ASC) {
    int32_t end = searchFn((char*) &pData[pos], numOfRows - pos, ekey, order);
    if (end >= 0) {
      forwardStep = end;

      if (pData[end + pos] == ekey) {
        forwardStep += 1;
      }
    }
  } else {
    int32_t end = searchFn((char *)pData, pos + 1, ekey, order);
    if (end >= 0) {
      forwardStep = pos - end;

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

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

static void doUpdateResultRowIndex(SResultRowInfo*pResultRowInfo, TSKEY lastKey, bool ascQuery, bool timeWindowInterpo) {
  int64_t skey = TSKEY_INITIAL_VAL;
  int32_t i = 0;
  for (i = pResultRowInfo->size - 1; i >= 0; --i) {
    SResultRow *pResult = pResultRowInfo->pResult[i];
    if (pResult->closed) {
      break;
    }

    // new closed result rows
    if (timeWindowInterpo) {
      if (pResult->endInterp && ((pResult->win.skey <= lastKey && ascQuery) || (pResult->win.skey >= lastKey && !ascQuery))) {
        if (i > 0) { // the first time window, the startInterp is false.
          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) {
//      assert(pResultRowInfo->current == NULL);
      assert(pResultRowInfo->curPos == -1);
      pResultRowInfo->curPos = -1;
    } else {
      pResultRowInfo->curPos = pResultRowInfo->size - 1;
    }
  } else {

    for (i = pResultRowInfo->size - 1; i >= 0; --i) {
      SResultRow *pResult = pResultRowInfo->pResult[i];
      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 已提交
953 954
static void updateResultRowInfoActiveIndex(SResultRowInfo* pResultRowInfo, const STimeWindow* pWin, TSKEY lastKey, bool ascQuery, bool interp) {
  if ((lastKey > pWin->ekey && ascQuery) || (lastKey < pWin->ekey && (!ascQuery))) {
955 956 957 958
    closeAllResultRows(pResultRowInfo);
    pResultRowInfo->curPos = pResultRowInfo->size - 1;
  } else {
    int32_t step = ascQuery ? 1 : -1;
H
Haojun Liao 已提交
959
    doUpdateResultRowIndex(pResultRowInfo, lastKey - step, ascQuery, interp);
960 961 962
  }
}

H
Haojun Liao 已提交
963 964
static int32_t getNumOfRowsInTimeWindow(SDataBlockInfo *pDataBlockInfo, TSKEY *pPrimaryColumn,
                                        int32_t startPos, TSKEY ekey, __block_search_fn_t searchFn, STableQueryInfo* item, int32_t order) {
965 966 967 968 969
  assert(startPos >= 0 && startPos < pDataBlockInfo->rows);

  int32_t num   = -1;
  int32_t step  = GET_FORWARD_DIRECTION_FACTOR(order);

H
Haojun Liao 已提交
970
  if (order == TSDB_ORDER_ASC) {
971 972
    if (ekey < pDataBlockInfo->window.ekey && pPrimaryColumn) {
      num = getForwardStepsInBlock(pDataBlockInfo->rows, searchFn, ekey, startPos, order, pPrimaryColumn);
H
Haojun Liao 已提交
973
      if (item != NULL) {
974 975 976 977
        item->lastKey = pPrimaryColumn[startPos + (num - 1)] + step;
      }
    } else {
      num = pDataBlockInfo->rows - startPos;
H
Haojun Liao 已提交
978
      if (item != NULL) {
979 980 981 982 983 984
        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 已提交
985
      if (item != NULL) {
986 987 988 989
        item->lastKey = pPrimaryColumn[startPos - (num - 1)] + step;
      }
    } else {
      num = startPos + 1;
H
Haojun Liao 已提交
990
      if (item != NULL) {
991 992 993 994 995 996 997 998 999
        item->lastKey = pDataBlockInfo->window.skey + step;
      }
    }
  }

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

H
Haojun Liao 已提交
1000
static void doApplyFunctions(SqlFunctionCtx* pCtx, STimeWindow* pWin, int32_t offset, int32_t forwardStep, TSKEY* tsCol,
1001
                             int32_t numOfTotal, int32_t numOfOutput, int32_t order) {
1002 1003 1004 1005
  for (int32_t k = 0; k < numOfOutput; ++k) {
    pCtx[k].startTs = pWin->skey;

    // keep it temporarialy
1006
    bool    hasAgg      = pCtx[k].input.colDataAggIsSet;
H
Haojun Liao 已提交
1007
    int32_t startOffset = pCtx[k].input.startRowIndex;
1008
    int32_t numOfRows   = pCtx[k].input.numOfRows;
1009

H
Haojun Liao 已提交
1010
    int32_t pos = (order == TSDB_ORDER_ASC) ? offset : offset - (forwardStep - 1);
1011 1012
    pCtx[k].input.startRowIndex = pos;
    pCtx[k].input.numOfRows = forwardStep;
1013 1014

    if (tsCol != NULL) {
H
Haojun Liao 已提交
1015
      pCtx[k].ptsList = tsCol;
1016 1017 1018 1019 1020 1021 1022 1023
    }

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

H
Haojun Liao 已提交
1024
    if (functionNeedToExecute(&pCtx[k])) {
1025
      pCtx[k].fpSet.process(&pCtx[k]);
1026 1027 1028
    }

    // restore it
1029 1030 1031
    pCtx[k].input.colDataAggIsSet = hasAgg;
    pCtx[k].input.startRowIndex = startOffset;
    pCtx[k].input.numOfRows = numOfRows;
1032 1033 1034
  }
}

H
Haojun Liao 已提交
1035 1036 1037 1038 1039 1040 1041
static int32_t getNextQualifiedWindow(SInterval* pInterval, STimeWindow* pNext, SDataBlockInfo* pDataBlockInfo,
                                      TSKEY* primaryKeys, int32_t prevPosition, STableIntervalOperatorInfo* pInfo) {
  int32_t order = pInfo->order;
  bool    ascQuery  = (order == TSDB_ORDER_ASC);

  int32_t precision = pInfo->precision;
  getNextTimeWindow(pInterval, precision, order, pNext);
1042 1043

  // next time window is not in current block
H
Haojun Liao 已提交
1044 1045
  if ((pNext->skey > pDataBlockInfo->window.ekey && order == TSDB_ORDER_ASC) ||
      (pNext->ekey < pDataBlockInfo->window.skey && order == TSDB_ORDER_DESC)) {
1046 1047 1048
    return -1;
  }

H
Haojun Liao 已提交
1049
  TSKEY startKey = ascQuery? pNext->skey:pNext->ekey;
1050 1051 1052
  int32_t startPos = 0;

  // tumbling time window query, a special case of sliding time window query
H
Haojun Liao 已提交
1053 1054
  if (pInterval->sliding == pInterval->interval && prevPosition != -1) {
    int32_t factor = GET_FORWARD_DIRECTION_FACTOR(order);
1055 1056
    startPos = prevPosition + factor;
  } else {
H
Haojun Liao 已提交
1057
    if (startKey <= pDataBlockInfo->window.skey && ascQuery) {
1058
      startPos = 0;
H
Haojun Liao 已提交
1059
    } else if (startKey >= pDataBlockInfo->window.ekey && !ascQuery) {
1060 1061
      startPos = pDataBlockInfo->rows - 1;
    } else {
H
Haojun Liao 已提交
1062
      startPos = binarySearchForKey((char *)primaryKeys, pDataBlockInfo->rows, startKey, order);
1063 1064 1065 1066
    }
  }

  /* interp query with fill should not skip time window */
H
Haojun Liao 已提交
1067 1068 1069
//  if (pQueryAttr->pointInterpQuery && pQueryAttr->fillType != TSDB_FILL_NONE) {
//    return startPos;
//  }
1070 1071 1072 1073 1074 1075

  /*
   * 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 已提交
1076
    if (ascQuery) {
1077 1078 1079 1080 1081
      assert(pDataBlockInfo->window.skey <= pNext->ekey);
    } else {
      assert(pDataBlockInfo->window.ekey >= pNext->skey);
    }
  } else {
H
Haojun Liao 已提交
1082
    if (ascQuery && primaryKeys[startPos] > pNext->ekey) {
1083
      TSKEY next = primaryKeys[startPos];
H
Haojun Liao 已提交
1084 1085 1086
      if (pInterval->intervalUnit == 'n' || pInterval->intervalUnit == 'y') {
        pNext->skey = taosTimeTruncate(next, pInterval, precision);
        pNext->ekey = taosTimeAdd(pNext->skey, pInterval->interval, pInterval->intervalUnit, precision) - 1;
1087
      } else {
H
Haojun Liao 已提交
1088 1089
        pNext->ekey += ((next - pNext->ekey + pInterval->sliding - 1)/pInterval->sliding) * pInterval->sliding;
        pNext->skey = pNext->ekey - pInterval->interval + 1;
1090
      }
H
Haojun Liao 已提交
1091
    } else if ((!ascQuery) && primaryKeys[startPos] < pNext->skey) {
1092
      TSKEY next = primaryKeys[startPos];
H
Haojun Liao 已提交
1093 1094 1095
      if (pInterval->intervalUnit == 'n' || pInterval->intervalUnit == 'y') {
        pNext->skey = taosTimeTruncate(next, pInterval, precision);
        pNext->ekey = taosTimeAdd(pNext->skey, pInterval->interval, pInterval->intervalUnit, precision) - 1;
1096
      } else {
H
Haojun Liao 已提交
1097 1098
        pNext->skey -= ((pNext->skey - next + pInterval->sliding - 1) / pInterval->sliding) * pInterval->sliding;
        pNext->ekey = pNext->skey + pInterval->interval - 1;
1099 1100 1101 1102 1103 1104 1105
      }
    }
  }

  return startPos;
}

H
Haojun Liao 已提交
1106
static FORCE_INLINE TSKEY reviseWindowEkey(STaskAttr *pQueryAttr, STimeWindow *pWindow) {
1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122
  TSKEY ekey = -1;
  if (QUERY_IS_ASC_QUERY(pQueryAttr)) {
    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 已提交
1123
static void setNotInterpoWindowKey(SqlFunctionCtx* pCtx, int32_t numOfOutput, int32_t type) {
1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134
  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 已提交
1135
static void saveDataBlockLastRow(char** pRow, SArray* pDataBlock, int32_t rowIndex, int32_t numOfCols) {
1136 1137 1138 1139
  if (pDataBlock == NULL) {
    return;
  }

H
Haojun Liao 已提交
1140
  for (int32_t k = 0; k < numOfCols; ++k) {
1141
    SColumnInfoData *pColInfo = taosArrayGet(pDataBlock, k);
H
Haojun Liao 已提交
1142
    memcpy(pRow[k], ((char*)pColInfo->pData) + (pColInfo->info.bytes * rowIndex), pColInfo->info.bytes);
1143 1144 1145
  }
}

H
Haojun Liao 已提交
1146
static TSKEY getStartTsKey(STimeWindow* win, const TSKEY* tsCols, int32_t rows, bool ascQuery) {
1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157
  TSKEY ts = TSKEY_INITIAL_VAL;
  if (tsCols == NULL) {
    ts = ascQuery? win->skey : win->ekey;
  } else {
    int32_t offset = ascQuery? 0:rows-1;
    ts = tsCols[offset];
  }

  return ts;
}

H
Haojun Liao 已提交
1158
static void doSetInputDataBlock(SOperatorInfo* pOperator, SqlFunctionCtx* pCtx, SSDataBlock* pBlock, int32_t order);
1159

H
Haojun Liao 已提交
1160
static void doSetInputDataBlockInfo(SOperatorInfo* pOperator, SqlFunctionCtx* pCtx, SSDataBlock* pBlock, int32_t order) {
1161 1162 1163 1164 1165
  for (int32_t i = 0; i < pOperator->numOfOutput; ++i) {
    pCtx[i].order = order;
    pCtx[i].size  = pBlock->info.rows;
    pCtx[i].currentStage = (uint8_t)pOperator->pRuntimeEnv->scanFlag;

1166
    setBlockStatisInfo(&pCtx[i], pBlock, NULL/*&pOperator->pExpr[i].base.colInfo*/);
1167 1168 1169
  }
}

H
Haojun Liao 已提交
1170
void setInputDataBlock(SOperatorInfo* pOperator, SqlFunctionCtx* pCtx, SSDataBlock* pBlock, int32_t order) {
H
Haojun Liao 已提交
1171 1172 1173 1174 1175
  if (pBlock->pDataBlock != NULL) {
    doSetInputDataBlock(pOperator, pCtx, pBlock, order);
  } else {
    doSetInputDataBlockInfo(pOperator, pCtx, pBlock, order);
  }
1176 1177
}

H
Haojun Liao 已提交
1178
static void doSetInputDataBlock(SOperatorInfo* pOperator, SqlFunctionCtx* pCtx, SSDataBlock* pBlock, int32_t order) {
1179 1180 1181
  for (int32_t i = 0; i < pOperator->numOfOutput; ++i) {
    pCtx[i].order = order;
    pCtx[i].size  = pBlock->info.rows;
H
Haojun Liao 已提交
1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235
    pCtx[i].currentStage = MAIN_SCAN;

    //    setBlockStatisInfo(&pCtx[i], pBlock, pOperator->pExpr[i].base.pColumns);
    int32_t slotId = pOperator->pExpr[i].base.pParam[0].pCol->slotId;

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

    // in case of the block distribution query, the inputBytes is not a constant value.
    pCtx[i].input.pData[0]  = taosArrayGet(pBlock->pDataBlock, slotId);
    pCtx[i].input.totalRows = pBlock->info.rows;
    pCtx[i].input.numOfRows = pBlock->info.rows;
    pCtx[i].input.startRowIndex = 0;

    ASSERT(pCtx[i].input.pData[0] != NULL);

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

static void doAggregateImpl(SOperatorInfo* pOperator, TSKEY startTs, SqlFunctionCtx* pCtx) {
1236
  for (int32_t k = 0; k < pOperator->numOfOutput; ++k) {
H
Haojun Liao 已提交
1237
    if (functionNeedToExecute(&pCtx[k])) {
1238
      pCtx[k].startTs = startTs;// this can be set during create the struct
H
Haojun Liao 已提交
1239
      pCtx[k].fpSet.process(&pCtx[k]);
1240 1241 1242 1243
    }
  }
}

H
Haojun Liao 已提交
1244
static void projectApplyFunctions(SSDataBlock* pResult, SqlFunctionCtx *pCtx, int32_t numOfOutput) {
1245
  for (int32_t k = 0; k < numOfOutput; ++k) {
H
Haojun Liao 已提交
1246 1247
    if (pCtx[k].fpSet.init == NULL) { // it is a project query
      SColumnInfoData* pColInfoData = taosArrayGet(pResult->pDataBlock, k);
1248
      colDataAssign(pColInfoData, pCtx[k].input.pData[0], pCtx[k].input.numOfRows);
H
Haojun Liao 已提交
1249
    } else { // TODO: arithmetic and other process.
1250
      ASSERT(0);
1251 1252
    }
  }
H
Haojun Liao 已提交
1253 1254

  pResult->info.rows = pCtx[0].input.numOfRows;
1255 1256 1257 1258
}

void doTimeWindowInterpolation(SOperatorInfo* pOperator, SOptrBasicInfo* pInfo, SArray* pDataBlock, TSKEY prevTs,
                               int32_t prevRowIndex, TSKEY curTs, int32_t curRowIndex, TSKEY windowKey, int32_t type) {
H
Haojun Liao 已提交
1259
  STaskRuntimeEnv *pRuntimeEnv = pOperator->pRuntimeEnv;
1260 1261
  SExprInfo* pExpr = pOperator->pExpr;

H
Haojun Liao 已提交
1262
  SqlFunctionCtx* pCtx = pInfo->pCtx;
1263 1264 1265 1266 1267 1268 1269 1270

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

1271
    SColIndex *      pColIndex = NULL/*&pExpr[k].base.colInfo*/;
1272 1273 1274
    int16_t          index = pColIndex->colIndex;
    SColumnInfoData *pColInfo = taosArrayGet(pDataBlock, index);

1275
//    assert(pColInfo->info.colId == pColIndex->info.colId && curTs != windowKey);
1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321
    double v1 = 0, v2 = 0, v = 0;

    if (prevRowIndex == -1) {
      GET_TYPED_DATA(v1, double, pColInfo->info.type, (char *)pRuntimeEnv->prevRow[index]);
    } else {
      GET_TYPED_DATA(v1, double, pColInfo->info.type, (char *)pColInfo->pData + prevRowIndex * pColInfo->info.bytes);
    }

    GET_TYPED_DATA(v2, double, pColInfo->info.type, (char *)pColInfo->pData + curRowIndex * pColInfo->info.bytes);

    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) {
            pCtx[k].start.ptr = (char *)pRuntimeEnv->prevRow[index];
          } else {
            pCtx[k].start.ptr = (char *)pColInfo->pData + prevRowIndex * pColInfo->info.bytes;
          }

          pCtx[k].end.ptr = (char *)pColInfo->pData + curRowIndex * pColInfo->info.bytes;
        }
      }
    } else if (functionId == FUNCTION_TWA) {
      SPoint point1 = (SPoint){.key = prevTs,    .val = &v1};
      SPoint point2 = (SPoint){.key = curTs,     .val = &v2};
      SPoint point  = (SPoint){.key = windowKey, .val = &v };

      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 已提交
1322
static bool setTimeWindowInterpolationStartTs(SOperatorInfo* pOperatorInfo, SqlFunctionCtx* pCtx, int32_t pos,
1323
                                              int32_t numOfRows, SArray* pDataBlock, const TSKEY* tsCols, STimeWindow* win) {
H
Haojun Liao 已提交
1324 1325
  STaskRuntimeEnv* pRuntimeEnv = pOperatorInfo->pRuntimeEnv;
  STaskAttr* pQueryAttr = pRuntimeEnv->pQueryAttr;
1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352

  bool ascQuery = QUERY_IS_ASC_QUERY(pQueryAttr);

  TSKEY curTs  = tsCols[pos];
  TSKEY lastTs = *(TSKEY *) pRuntimeEnv->prevRow[0];

  // 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
  TSKEY key = ascQuery? win->skey:win->ekey;
  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;
  }

  int32_t step = GET_FORWARD_DIRECTION_FACTOR(pQueryAttr->order.order);
  TSKEY   prevTs = ((pos == 0 && ascQuery) || (pos == (numOfRows - 1) && !ascQuery))? lastTs:tsCols[pos - step];

  doTimeWindowInterpolation(pOperatorInfo, pOperatorInfo->info, pDataBlock, prevTs, pos - step, curTs, pos,
      key, RESULT_ROW_START_INTERP);
  return true;
}

H
Haojun Liao 已提交
1353
static bool setTimeWindowInterpolationEndTs(SOperatorInfo* pOperatorInfo, SqlFunctionCtx* pCtx,
1354
    int32_t endRowIndex, SArray* pDataBlock, const TSKEY* tsCols, TSKEY blockEkey, STimeWindow* win) {
H
Haojun Liao 已提交
1355 1356
  STaskRuntimeEnv *pRuntimeEnv = pOperatorInfo->pRuntimeEnv;
  STaskAttr* pQueryAttr = pRuntimeEnv->pQueryAttr;
1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384
  int32_t numOfOutput = pOperatorInfo->numOfOutput;

  TSKEY   actualEndKey = tsCols[endRowIndex];

  TSKEY key = QUERY_IS_ASC_QUERY(pQueryAttr)? win->ekey:win->skey;

  // not ended in current data block, do not invoke interpolation
  if ((key > blockEkey && QUERY_IS_ASC_QUERY(pQueryAttr)) || (key < blockEkey && !QUERY_IS_ASC_QUERY(pQueryAttr))) {
    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;
  }

  int32_t step = GET_FORWARD_DIRECTION_FACTOR(pQueryAttr->order.order);
  int32_t nextRowIndex = endRowIndex + step;
  assert(nextRowIndex >= 0);

  TSKEY nextKey = tsCols[nextRowIndex];
  doTimeWindowInterpolation(pOperatorInfo, pOperatorInfo->info, pDataBlock, actualEndKey, endRowIndex, nextKey,
      nextRowIndex, key, RESULT_ROW_END_INTERP);
  return true;
}

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

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

  if (pBlock->pDataBlock == NULL){
//    tscError("pBlock->pDataBlock == NULL");
    return;
  }
H
Haojun Liao 已提交
1398

1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410
  SColumnInfoData *pColInfo = taosArrayGet(pBlock->pDataBlock, 0);

  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
    int32_t startRowIndex = startPos;
    bool interp = setTimeWindowInterpolationStartTs(pOperatorInfo, pCtx, startRowIndex, pBlock->info.rows, pBlock->pDataBlock,
        tsCols, win);
    if (interp) {
      setResultRowInterpo(pResult, RESULT_ROW_START_INTERP);
    }
  } else {
H
Haojun Liao 已提交
1411
    setNotInterpoWindowKey(pCtx, pOperatorInfo->numOfOutput, RESULT_ROW_START_INTERP);
1412 1413 1414
  }

  // point interpolation does not require the end key time window interpolation.
H
Haojun Liao 已提交
1415 1416 1417
//  if (pointInterpQuery) {
//    return;
//  }
1418 1419 1420 1421 1422 1423

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

H
Haojun Liao 已提交
1424
    TSKEY endKey = (order == TSDB_ORDER_ASC)? pBlock->info.window.ekey:pBlock->info.window.skey;
1425 1426 1427 1428 1429
    bool  interp = setTimeWindowInterpolationEndTs(pOperatorInfo, pCtx, endRowIndex, pBlock->pDataBlock, tsCols, endKey, win);
    if (interp) {
      setResultRowInterpo(pResult, RESULT_ROW_END_INTERP);
    }
  } else {
H
Haojun Liao 已提交
1430
    setNotInterpoWindowKey(pCtx, pOperatorInfo->numOfOutput, RESULT_ROW_END_INTERP);
1431 1432 1433 1434 1435 1436
  }
}

static void hashIntervalAgg(SOperatorInfo* pOperatorInfo, SResultRowInfo* pResultRowInfo, SSDataBlock* pSDataBlock, int32_t tableGroupId) {
  STableIntervalOperatorInfo* pInfo = (STableIntervalOperatorInfo*) pOperatorInfo->info;

H
Haojun Liao 已提交
1437 1438
  SExecTaskInfo* pTaskInfo = pOperatorInfo->pTaskInfo;
  int32_t numOfOutput = pOperatorInfo->numOfOutput;
1439

H
Haojun Liao 已提交
1440 1441
  int32_t step = 1;
  bool ascQuery = true;
1442 1443 1444 1445 1446 1447 1448

  int32_t prevIndex = pResultRowInfo->curPos;

  TSKEY* tsCols = NULL;
  if (pSDataBlock->pDataBlock != NULL) {
    SColumnInfoData* pColDataInfo = taosArrayGet(pSDataBlock->pDataBlock, 0);
    tsCols = (int64_t*) pColDataInfo->pData;
1449
    assert(tsCols[0] == pSDataBlock->info.window.skey && tsCols[pSDataBlock->info.rows - 1] == pSDataBlock->info.window.ekey);
1450 1451 1452
  }

  int32_t startPos = ascQuery? 0 : (pSDataBlock->info.rows - 1);
H
Haojun Liao 已提交
1453
  TSKEY ts = getStartTsKey(&pSDataBlock->info.window, tsCols, pSDataBlock->info.rows, ascQuery);
1454

H
Haojun Liao 已提交
1455 1456
  STimeWindow win = getActiveTimeWindow(pResultRowInfo, ts, &pInfo->interval, pInfo->precision, &pInfo->win);
  bool masterScan = true;
1457 1458

  SResultRow* pResult = NULL;
H
Haojun Liao 已提交
1459
  int32_t ret = setResultOutputBufByKey_rv(pResultRowInfo, pSDataBlock->info.uid, &win, masterScan, &pResult, tableGroupId, pInfo->binfo.pCtx,
H
Haojun Liao 已提交
1460
                                        numOfOutput, pInfo->binfo.rowCellInfoOffset, &pInfo->aggSup, pTaskInfo);
1461
  if (ret != TSDB_CODE_SUCCESS || pResult == NULL) {
H
Haojun Liao 已提交
1462
    longjmp(pTaskInfo->env, TSDB_CODE_QRY_OUT_OF_MEMORY);
1463 1464 1465
  }

  int32_t forwardStep = 0;
H
Haojun Liao 已提交
1466
  TSKEY   ekey = win.ekey;
1467
  forwardStep =
H
Haojun Liao 已提交
1468
      getNumOfRowsInTimeWindow(&pSDataBlock->info, tsCols, startPos, ekey, binarySearchForKey, NULL, TSDB_ORDER_ASC);
1469 1470 1471

  // prev time window not interpolation yet.
  int32_t curIndex = pResultRowInfo->curPos;
H
Haojun Liao 已提交
1472
  if (prevIndex != -1 && prevIndex < curIndex && pInfo->timeWindowInterpo) {
1473 1474 1475 1476 1477 1478 1479 1480
    for (int32_t j = prevIndex; j < curIndex; ++j) {  // previous time window may be all closed already.
      SResultRow* pRes = getResultRow(pResultRowInfo, j);
      if (pRes->closed) {
        assert(resultRowInterpolated(pRes, RESULT_ROW_START_INTERP) && resultRowInterpolated(pRes, RESULT_ROW_END_INTERP));
        continue;
      }

        STimeWindow w = pRes->win;
H
Haojun Liao 已提交
1481
        ret = setResultOutputBufByKey_rv(pResultRowInfo, pSDataBlock->info.uid, &w, masterScan, &pResult,
H
Haojun Liao 已提交
1482
                                      tableGroupId, pInfo->binfo.pCtx, numOfOutput, pInfo->binfo.rowCellInfoOffset, &pInfo->aggSup, pTaskInfo);
1483
        if (ret != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
1484
          longjmp(pTaskInfo->env, TSDB_CODE_QRY_OUT_OF_MEMORY);
1485 1486 1487 1488
        }

        assert(!resultRowInterpolated(pResult, RESULT_ROW_END_INTERP));

H
Haojun Liao 已提交
1489
        doTimeWindowInterpolation(pOperatorInfo, &pInfo->binfo, pSDataBlock->pDataBlock, *(TSKEY*)pInfo->pRow[0], -1,
1490 1491 1492
                                  tsCols[startPos], startPos, w.ekey, RESULT_ROW_END_INTERP);

        setResultRowInterpo(pResult, RESULT_ROW_END_INTERP);
H
Haojun Liao 已提交
1493
        setNotInterpoWindowKey(pInfo->binfo.pCtx, pOperatorInfo->numOfOutput, RESULT_ROW_START_INTERP);
1494

H
Haojun Liao 已提交
1495
        doApplyFunctions(pInfo->binfo.pCtx, &w, startPos, 0, tsCols, pSDataBlock->info.rows, numOfOutput, TSDB_ORDER_ASC);
1496 1497 1498
      }

    // restore current time window
H
Haojun Liao 已提交
1499
    ret = setResultOutputBufByKey_rv(pResultRowInfo, pSDataBlock->info.uid, &win, masterScan, &pResult, tableGroupId, pInfo->binfo.pCtx,
H
Haojun Liao 已提交
1500
                                  numOfOutput, pInfo->binfo.rowCellInfoOffset, &pInfo->aggSup, pTaskInfo);
1501
    if (ret != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
1502
      longjmp(pTaskInfo->env, TSDB_CODE_QRY_OUT_OF_MEMORY);
1503 1504 1505 1506
    }
  }

  // window start key interpolation
H
Haojun Liao 已提交
1507 1508
  doWindowBorderInterpolation(pOperatorInfo, pSDataBlock, pInfo->binfo.pCtx, pResult, &win, startPos, forwardStep, pInfo->order, false);
  doApplyFunctions(pInfo->binfo.pCtx, &win, startPos, forwardStep, tsCols, pSDataBlock->info.rows, numOfOutput, TSDB_ORDER_ASC);
1509 1510 1511 1512

  STimeWindow nextWin = win;
  while (1) {
    int32_t prevEndPos = (forwardStep - 1) * step + startPos;
H
Haojun Liao 已提交
1513
    startPos = getNextQualifiedWindow(&pInfo->interval, &nextWin, &pSDataBlock->info, tsCols, prevEndPos, pInfo);
1514 1515 1516 1517 1518
    if (startPos < 0) {
      break;
    }

    // null data, failed to allocate more memory buffer
H
Haojun Liao 已提交
1519
    int32_t code = setResultOutputBufByKey_rv(pResultRowInfo, pSDataBlock->info.uid, &nextWin, masterScan, &pResult, tableGroupId,
H
Haojun Liao 已提交
1520
                                           pInfo->binfo.pCtx, numOfOutput, pInfo->binfo.rowCellInfoOffset, &pInfo->aggSup, pTaskInfo);
1521
    if (code != TSDB_CODE_SUCCESS || pResult == NULL) {
H
Haojun Liao 已提交
1522
      longjmp(pTaskInfo->env, TSDB_CODE_QRY_OUT_OF_MEMORY);
1523 1524
    }

H
Haojun Liao 已提交
1525 1526
    ekey = nextWin.ekey;//reviseWindowEkey(pQueryAttr, &nextWin);
    forwardStep = getNumOfRowsInTimeWindow(&pSDataBlock->info, tsCols, startPos, ekey, binarySearchForKey, NULL, TSDB_ORDER_ASC);
1527 1528

    // window start(end) key interpolation
H
Haojun Liao 已提交
1529 1530
    doWindowBorderInterpolation(pOperatorInfo, pSDataBlock, pInfo->binfo.pCtx, pResult, &nextWin, startPos, forwardStep, pInfo->order, false);
    doApplyFunctions(pInfo->binfo.pCtx, &nextWin, startPos, forwardStep, tsCols, pSDataBlock->info.rows, numOfOutput, TSDB_ORDER_ASC);
1531 1532
  }

H
Haojun Liao 已提交
1533
  if (pInfo->timeWindowInterpo) {
1534
    int32_t rowIndex = ascQuery? (pSDataBlock->info.rows-1):0;
H
Haojun Liao 已提交
1535
    saveDataBlockLastRow(pInfo->pRow, pSDataBlock->pDataBlock, rowIndex, pSDataBlock->info.numOfCols);
1536 1537
  }

H
Haojun Liao 已提交
1538
//  updateResultRowInfoActiveIndex(pResultRowInfo, &pInfo->win, pRuntimeEnv->current->lastKey, true, false);
1539 1540 1541 1542 1543
}

static void hashAllIntervalAgg(SOperatorInfo* pOperatorInfo, SResultRowInfo* pResultRowInfo, SSDataBlock* pSDataBlock, int32_t tableGroupId) {
  STableIntervalOperatorInfo* pInfo = (STableIntervalOperatorInfo*) pOperatorInfo->info;

H
Haojun Liao 已提交
1544
  STaskRuntimeEnv* pRuntimeEnv = pOperatorInfo->pRuntimeEnv;
1545
  int32_t           numOfOutput = pOperatorInfo->numOfOutput;
H
Haojun Liao 已提交
1546
  STaskAttr*       pQueryAttr = pRuntimeEnv->pQueryAttr;
1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559

  int32_t step = GET_FORWARD_DIRECTION_FACTOR(pQueryAttr->order.order);
  bool ascQuery = QUERY_IS_ASC_QUERY(pQueryAttr);

  TSKEY* tsCols = NULL;
  if (pSDataBlock->pDataBlock != NULL) {
    SColumnInfoData* pColDataInfo = taosArrayGet(pSDataBlock->pDataBlock, 0);
    tsCols = (int64_t*) pColDataInfo->pData;
    assert(tsCols[0] == pSDataBlock->info.window.skey &&
           tsCols[pSDataBlock->info.rows - 1] == pSDataBlock->info.window.ekey);
  }

  int32_t startPos = ascQuery? 0 : (pSDataBlock->info.rows - 1);
H
Haojun Liao 已提交
1560
  TSKEY ts = getStartTsKey(&pSDataBlock->info.window, tsCols, pSDataBlock->info.rows, ascQuery);
1561 1562

  STimeWindow win = getCurrentActiveTimeWindow(pResultRowInfo, ts, pQueryAttr);
H
Haojun Liao 已提交
1563
  bool masterScan = IS_MAIN_SCAN(pRuntimeEnv);
1564 1565 1566 1567 1568 1569 1570 1571 1572

  SResultRow* pResult = NULL;
  int32_t forwardStep = 0;
  int32_t ret = 0;
  STimeWindow preWin = win;

  while (1) {
    // null data, failed to allocate more memory buffer
    ret = setResultOutputBufByKey(pRuntimeEnv, pResultRowInfo, pSDataBlock->info.uid, &win, masterScan, &pResult,
H
Haojun Liao 已提交
1573
                                  tableGroupId, pInfo->binfo.pCtx, numOfOutput, pInfo->binfo.rowCellInfoOffset);
1574 1575 1576 1577 1578
    if (ret != TSDB_CODE_SUCCESS) {
      longjmp(pRuntimeEnv->env, TSDB_CODE_QRY_OUT_OF_MEMORY);
    }

    TSKEY   ekey = reviseWindowEkey(pQueryAttr, &win);
H
Haojun Liao 已提交
1579
//    forwardStep = getNumOfRowsInTimeWindow(pRuntimeEnv, &pSDataBlock->info, tsCols, startPos, ekey, binarySearchForKey, true);
1580 1581

    // window start(end) key interpolation
H
Haojun Liao 已提交
1582 1583
//    doWindowBorderInterpolation(pOperatorInfo, pSDataBlock, pInfo->binfo.pCtx, pResult, &win, startPos, forwardStep);
//    doApplyFunctions(pRuntimeEnv, pInfo->binfo.pCtx, ascQuery ? &win : &preWin, startPos, forwardStep, tsCols, pSDataBlock->info.rows, numOfOutput);
1584 1585 1586
    preWin = win;

    int32_t prevEndPos = (forwardStep - 1) * step + startPos;
H
Haojun Liao 已提交
1587
//    startPos = getNextQualifiedWindow(pQueryAttr, &win, &pSDataBlock->info, tsCols, binarySearchForKey, prevEndPos);
1588 1589 1590
    if (startPos < 0) {
      if ((ascQuery && win.skey <= pQueryAttr->window.ekey) || ((!ascQuery) && win.ekey >= pQueryAttr->window.ekey)) {
        int32_t code = setResultOutputBufByKey(pRuntimeEnv, pResultRowInfo, pSDataBlock->info.uid, &win, masterScan, &pResult, tableGroupId,
H
Haojun Liao 已提交
1591
                                               pInfo->binfo.pCtx, numOfOutput, pInfo->binfo.rowCellInfoOffset);
1592 1593 1594 1595 1596 1597 1598
        if (code != TSDB_CODE_SUCCESS || pResult == NULL) {
          longjmp(pRuntimeEnv->env, TSDB_CODE_QRY_OUT_OF_MEMORY);
        }

        startPos = pSDataBlock->info.rows - 1;

        // window start(end) key interpolation
H
Haojun Liao 已提交
1599 1600
//        doWindowBorderInterpolation(pOperatorInfo, pSDataBlock, pInfo->binfo.pCtx, pResult, &win, startPos, forwardStep);
//        doApplyFunctions(pRuntimeEnv, pInfo->binfo.pCtx, ascQuery ? &win : &preWin, startPos, forwardStep, tsCols, pSDataBlock->info.rows, numOfOutput);
1601 1602 1603 1604 1605 1606 1607 1608 1609
      }

      break;
    }
    setResultRowInterpo(pResult, RESULT_ROW_END_INTERP);
  }

  if (pQueryAttr->timeWindowInterpo) {
    int32_t rowIndex = ascQuery? (pSDataBlock->info.rows-1):0;
H
Haojun Liao 已提交
1610
//    saveDataBlockLastRow(pRuntimeEnv, &pSDataBlock->info, pSDataBlock->pDataBlock, rowIndex);
1611 1612
  }

H
Haojun Liao 已提交
1613
//  updateResultRowInfoActiveIndex(pResultRowInfo, pQueryAttr, pRuntimeEnv->current->lastKey);
1614 1615
}

1616 1617 1618 1619 1620 1621 1622 1623
static bool groupKeyCompare(SGroupbyOperatorInfo* pInfo, SSDataBlock* pBlock, int32_t rowIndex, int32_t numOfGroupCols) {
  SColumnDataAgg* pColAgg = NULL;
  for (int32_t i = 0; i < numOfGroupCols; ++i) {
    SColumn*         pCol = taosArrayGet(pInfo->pGroupCols, i);
    SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, pCol->slotId);
    if (pBlock->pBlockAgg != NULL) {
      pColAgg = &pBlock->pBlockAgg[pCol->slotId];  // TODO is agg data matched?
    }
1624

1625
    bool isNull = colDataIsNull(pColInfoData, pBlock->info.rows, rowIndex, pColAgg);
1626

1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649
    SGroupKeys* pkey = taosArrayGet(pInfo->pGroupColVals, i);
    if (pkey->isNull && isNull) {
      continue;
    }

    if (isNull || pkey->isNull) {
      return false;
    }

    char* val = colDataGetData(pColInfoData, rowIndex);

    if (IS_VAR_DATA_TYPE(pkey->type)) {
      int32_t len = varDataLen(val);
      if (len == varDataLen(pkey->pData) && memcmp(varDataVal(pkey->pData), varDataVal(val), len) == 0) {
        continue;
      } else {
        return false;
      }
    } else {
      if (memcmp(pkey->pData, val, pkey->bytes) != 0) {
        return false;
      }
    }
1650 1651
  }

1652 1653
  return true;
}
1654

1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689
static void keepGroupKeys(SGroupbyOperatorInfo* pInfo, SSDataBlock* pBlock, int32_t rowIndex, int32_t numOfGroupCols) {
  SColumnDataAgg* pColAgg = NULL;

  for (int32_t i = 0; i < numOfGroupCols; ++i) {
    SColumn*         pCol = taosArrayGet(pInfo->pGroupCols, i);
    SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, pCol->slotId);

    if (pBlock->pBlockAgg != NULL) {
      pColAgg = &pBlock->pBlockAgg[pCol->slotId];  // TODO is agg data matched?
    }

    SGroupKeys* pkey = taosArrayGet(pInfo->pGroupColVals, i);
    if (colDataIsNull(pColInfoData, pBlock->info.rows, rowIndex, pColAgg)) {
      pkey->isNull = true;
    } else {
      char* val = colDataGetData(pColInfoData, rowIndex);
      if (IS_VAR_DATA_TYPE(pkey->type)) {
        memcpy(pkey->pData, val, varDataTLen(val));
      } else {
        memcpy(pkey->pData, val, pkey->bytes);
      }
    }
  }
}

static int32_t generatedHashKey(void* pKey, int32_t* length, SArray* pGroupColVals) {
  ASSERT(pKey != NULL);
  size_t numOfGroupCols = taosArrayGetSize(pGroupColVals);

  char* isNull = (char*) pKey;
  char* pStart = (char*) pKey + sizeof(int8_t) * numOfGroupCols;
  for(int32_t i = 0; i < numOfGroupCols; ++i) {
    SGroupKeys* pkey = taosArrayGet(pGroupColVals, i);
    if (pkey->isNull) {
      isNull[i] = 1;
1690 1691 1692
      continue;
    }

1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707
    isNull[i] = 0;
    if (IS_VAR_DATA_TYPE(pkey->type)) {
      varDataCopy(pStart, pkey->pData);
      pStart += varDataTLen(pkey->pData);
      ASSERT(varDataTLen(pkey->pData) <= pkey->bytes);
    } else {
      memcpy(pStart, pkey->pData, pkey->bytes);
      pStart += pkey->bytes;
    }
  }

  *length = (pStart - (char*) pKey);
  return 0;
}

1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727
// assign the group keys or user input constant values if required
static void doAssignGroupKeys(SqlFunctionCtx* pCtx, int32_t numOfOutput, int32_t totalRows, int32_t rowIndex) {
  for(int32_t i = 0; i < numOfOutput; ++i) {
    if (pCtx[i].functionId == -1) {
      SResultRowEntryInfo* pEntryInfo = GET_RES_INFO(&pCtx[i]);

      SColumnInfoData* pColInfoData = pCtx[i].input.pData[0];
      if (!colDataIsNull(pColInfoData, totalRows, rowIndex, NULL)) {
        char* dest = GET_ROWCELL_INTERBUF(pEntryInfo);
        char* data = colDataGetData(pColInfoData, rowIndex);

        // set result exists, todo refactor
        memcpy(dest, data, pColInfoData->info.bytes);
        pEntryInfo->hasResult = DATA_SET_FLAG;
        pEntryInfo->numOfRes = 1;
      }
    }
  }
}

1728 1729 1730 1731
static void doHashGroupbyAgg(SOperatorInfo* pOperator, SSDataBlock *pBlock) {
  SExecTaskInfo *pTaskInfo = pOperator->pTaskInfo;
  SGroupbyOperatorInfo *pInfo = pOperator->info;

1732
  SqlFunctionCtx* pCtx = pInfo->binfo.pCtx;
1733 1734 1735 1736 1737 1738 1739 1740
  int32_t numOfGroupCols = taosArrayGetSize(pInfo->pGroupCols);
//  if (type == TSDB_DATA_TYPE_FLOAT || type == TSDB_DATA_TYPE_DOUBLE) {
    //qError("QInfo:0x%"PRIx64" group by not supported on double/float columns, abort", GET_TASKID(pRuntimeEnv));
//    return;
//  }

  int32_t len = 0;
  STimeWindow w = TSWINDOW_INITIALIZER;
H
Haojun Liao 已提交
1741

1742 1743
  int32_t num = 0;
  for (int32_t j = 0; j < pBlock->info.rows; ++j) {
1744
    // Compare with the previous row of this column, and do not set the output buffer again if they are identical.
1745 1746 1747
    if (!pInfo->isInit) {
      keepGroupKeys(pInfo, pBlock, j, numOfGroupCols);
      pInfo->isInit = true;
1748 1749 1750 1751
      num++;
      continue;
    }

1752 1753 1754 1755
    bool equal = groupKeyCompare(pInfo, pBlock, j, numOfGroupCols);
    if (equal) {
      num++;
      continue;
1756 1757
    }

1758 1759 1760
    /*int32_t ret = */generatedHashKey(pInfo->keyBuf, &len, pInfo->pGroupColVals);
    int32_t ret = setGroupResultOutputBuf_rv(&(pInfo->binfo), pOperator->numOfOutput, pInfo->keyBuf, TSDB_DATA_TYPE_VARCHAR, len, 0,
                                             pInfo->aggSup.pResultBuf, pTaskInfo, &pInfo->aggSup);
1761
    if (ret != TSDB_CODE_SUCCESS) {  // null data, too many state code
H
Haojun Liao 已提交
1762
      longjmp(pTaskInfo->env, TSDB_CODE_QRY_APP_ERROR);
1763 1764
    }

1765 1766 1767 1768 1769
    int32_t rowIndex = j - num;
    doApplyFunctions(pCtx, &w, rowIndex, num, NULL, pBlock->info.rows, pOperator->numOfOutput, TSDB_ORDER_ASC);

    // assign the group keys or user input constant values if required
    doAssignGroupKeys(pCtx, pOperator->numOfOutput, pBlock->info.rows, rowIndex);
1770
    keepGroupKeys(pInfo, pBlock, j, numOfGroupCols);
1771 1772 1773 1774
    num = 1;
  }

  if (num > 0) {
1775 1776
    /*int32_t ret = */generatedHashKey(pInfo->keyBuf, &len, pInfo->pGroupColVals);
    int32_t ret = setGroupResultOutputBuf_rv(&(pInfo->binfo), pOperator->numOfOutput, pInfo->keyBuf, TSDB_DATA_TYPE_VARCHAR, len, 0,
H
Haojun Liao 已提交
1777 1778 1779
                                             pInfo->aggSup.pResultBuf, pTaskInfo, &pInfo->aggSup);
    if (ret != TSDB_CODE_SUCCESS) {
      longjmp(pTaskInfo->env, TSDB_CODE_QRY_APP_ERROR);
1780 1781
    }

1782 1783 1784
    int32_t rowIndex = pBlock->info.rows - num;
    doApplyFunctions(pCtx, &w, rowIndex, num, NULL, pBlock->info.rows, pOperator->numOfOutput, TSDB_ORDER_ASC);
    doAssignGroupKeys(pCtx, pOperator->numOfOutput, pBlock->info.rows, rowIndex);
1785 1786 1787
  }
}

H
Haojun Liao 已提交
1788
static void doSessionWindowAggImpl(SOperatorInfo* pOperator, SSessionAggOperatorInfo *pInfo, SSDataBlock *pSDataBlock) {
H
Haojun Liao 已提交
1789
  STaskRuntimeEnv* pRuntimeEnv = pOperator->pRuntimeEnv;
1790 1791 1792 1793 1794
  STableQueryInfo*  item = pRuntimeEnv->current;

  // primary timestamp column
  SColumnInfoData* pColInfoData = taosArrayGet(pSDataBlock->pDataBlock, 0);

H
Haojun Liao 已提交
1795
  bool    masterScan = IS_MAIN_SCAN(pRuntimeEnv);
1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831
  SOptrBasicInfo* pBInfo = &pInfo->binfo;

  int64_t gap = pOperator->pRuntimeEnv->pQueryAttr->sw.gap;
  pInfo->numOfRows = 0;
  if (IS_REPEAT_SCAN(pRuntimeEnv) && !pInfo->reptScan) {
    pInfo->reptScan = true;
    pInfo->prevTs = INT64_MIN;
  }

  TSKEY* tsList = (TSKEY*)pColInfoData->pData;
  for (int32_t j = 0; j < pSDataBlock->info.rows; ++j) {
    if (pInfo->prevTs == INT64_MIN) {
      pInfo->curWindow.skey = tsList[j];
      pInfo->curWindow.ekey = tsList[j];
      pInfo->prevTs = tsList[j];
      pInfo->numOfRows = 1;
      pInfo->start = j;
    } else if (tsList[j] - pInfo->prevTs <= gap && (tsList[j] - pInfo->prevTs) >= 0) {
      pInfo->curWindow.ekey = tsList[j];
      pInfo->prevTs = tsList[j];
      pInfo->numOfRows += 1;
      if (j == 0 && pInfo->start != 0) {
        pInfo->numOfRows = 1;
        pInfo->start = 0;
      }
    } else {  // start a new session window
      SResultRow* pResult = NULL;

      pInfo->curWindow.ekey = pInfo->curWindow.skey;
      int32_t ret = setResultOutputBufByKey(pRuntimeEnv, &pBInfo->resultRowInfo, pSDataBlock->info.uid, &pInfo->curWindow, masterScan,
                                            &pResult, item->groupIndex, pBInfo->pCtx, pOperator->numOfOutput,
                                            pBInfo->rowCellInfoOffset);
      if (ret != TSDB_CODE_SUCCESS) {  // null data, too many state code
        longjmp(pRuntimeEnv->env, TSDB_CODE_QRY_APP_ERROR);
      }

H
Haojun Liao 已提交
1832 1833
//      doApplyFunctions(pRuntimeEnv, pBInfo->pCtx, &pInfo->curWindow, pInfo->start, pInfo->numOfRows, tsList,
//                       pSDataBlock->info.rows, pOperator->numOfOutput);
1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852

      pInfo->curWindow.skey = tsList[j];
      pInfo->curWindow.ekey = tsList[j];
      pInfo->prevTs = tsList[j];
      pInfo->numOfRows = 1;
      pInfo->start = j;
    }
  }

  SResultRow* pResult = NULL;

  pInfo->curWindow.ekey = pInfo->curWindow.skey;
  int32_t ret = setResultOutputBufByKey(pRuntimeEnv, &pBInfo->resultRowInfo, pSDataBlock->info.uid, &pInfo->curWindow, masterScan,
                                        &pResult, item->groupIndex, pBInfo->pCtx, pOperator->numOfOutput,
                                        pBInfo->rowCellInfoOffset);
  if (ret != TSDB_CODE_SUCCESS) {  // null data, too many state code
    longjmp(pRuntimeEnv->env, TSDB_CODE_QRY_APP_ERROR);
  }

H
Haojun Liao 已提交
1853 1854
//  doApplyFunctions(pRuntimeEnv, pBInfo->pCtx, &pInfo->curWindow, pInfo->start, pInfo->numOfRows, tsList,
//                   pSDataBlock->info.rows, pOperator->numOfOutput);
1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873
}

static void setResultRowKey(SResultRow* pResultRow, char* pData, int16_t type) {
  if (IS_VAR_DATA_TYPE(type)) {
    if (pResultRow->key == NULL) {
      pResultRow->key = malloc(varDataTLen(pData));
      varDataCopy(pResultRow->key, pData);
    } else {
      assert(memcmp(pResultRow->key, pData, varDataTLen(pData)) == 0);
    }
  } else {
    int64_t v = -1;
    GET_TYPED_DATA(v, int64_t, type, pData);

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

H
Haojun Liao 已提交
1874 1875
static int32_t setGroupResultOutputBuf_rv(SOptrBasicInfo *binfo, int32_t numOfCols, char *pData, int16_t type, int16_t bytes, int32_t groupId,
    SDiskbasedBuf* pBuf, SExecTaskInfo* pTaskInfo, SAggSupporter* pAggSup) {
1876
  SResultRowInfo *pResultRowInfo    = &binfo->resultRowInfo;
H
Haojun Liao 已提交
1877
  SqlFunctionCtx *pCtx              = binfo->pCtx;
1878

1879 1880
  SResultRow *pResultRow = doSetResultOutBufByKey_rv(pBuf, pResultRowInfo, groupId, (char *)pData, bytes, true, groupId,
      pTaskInfo, true, pAggSup);
1881 1882 1883 1884
  assert (pResultRow != NULL);

  setResultRowKey(pResultRow, pData, type);

H
Haojun Liao 已提交
1885
  setResultRowOutputBufInitCtx_rv(pBuf, pResultRow, pCtx, numOfCols, binfo->rowCellInfoOffset);
1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910
  return TSDB_CODE_SUCCESS;
}

static int32_t getGroupbyColumnIndex(SGroupbyExpr *pGroupbyExpr, SSDataBlock* pDataBlock) {
  size_t num = taosArrayGetSize(pGroupbyExpr->columnInfo);
  for (int32_t k = 0; k < num; ++k) {
    SColIndex* pColIndex = taosArrayGet(pGroupbyExpr->columnInfo, k);
    if (TSDB_COL_IS_TAG(pColIndex->flag)) {
      continue;
    }

    int32_t colId = pColIndex->colId;

    for (int32_t i = 0; i < pDataBlock->info.numOfCols; ++i) {
      SColumnInfoData* pColInfo = taosArrayGet(pDataBlock->pDataBlock, i);
      if (pColInfo->info.colId == colId) {
        return i;
      }
    }
  }

  assert(0);
  return -1;
}

H
Haojun Liao 已提交
1911
static bool functionNeedToExecute(SqlFunctionCtx *pCtx) {
1912 1913 1914 1915
  struct SResultRowEntryInfo *pResInfo = GET_RES_INFO(pCtx);

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

1920 1921 1922 1923 1924 1925 1926 1927 1928
  if (functionId == FUNCTION_TS) {
    return true;
  }

  if (isRowEntryCompleted(pResInfo) || functionId == FUNCTION_TAG_DUMMY || functionId == FUNCTION_TS_DUMMY) {
    return false;
  }

  if (functionId == FUNCTION_FIRST_DST || functionId == FUNCTION_FIRST) {
H
Haojun Liao 已提交
1929
//    return QUERY_IS_ASC_QUERY(pQueryAttr);
1930 1931 1932 1933
  }

  // denote the order type
  if ((functionId == FUNCTION_LAST_DST || functionId == FUNCTION_LAST)) {
H
Haojun Liao 已提交
1934
//    return pCtx->param[0].i == pQueryAttr->order.order;
1935 1936 1937
  }

  // in the reverse table scan, only the following functions need to be executed
H
Haojun Liao 已提交
1938 1939 1940 1941
//  if (IS_REVERSE_SCAN(pRuntimeEnv) ||
//      (pRuntimeEnv->scanFlag == REPEAT_SCAN && functionId != FUNCTION_STDDEV && functionId != FUNCTION_PERCT)) {
//    return false;
//  }
1942 1943 1944 1945

  return true;
}

H
Haojun Liao 已提交
1946
void setBlockStatisInfo(SqlFunctionCtx *pCtx, SSDataBlock* pSDataBlock, SColumn* pColumn) {
1947 1948
  SColumnDataAgg *pAgg = NULL;

H
Haojun Liao 已提交
1949 1950
  if (pSDataBlock->pBlockAgg != NULL && TSDB_COL_IS_NORMAL_COL(pColumn->flag)) {
    pAgg = &pSDataBlock->pBlockAgg[pCtx->columnIndex];
1951 1952 1953 1954 1955 1956 1957 1958

    pCtx->agg = *pAgg;
    pCtx->isAggSet  = true;
    assert(pCtx->agg.numOfNull <= pSDataBlock->info.rows);
  } else {
    pCtx->isAggSet = false;
  }

H
Haojun Liao 已提交
1959
  pCtx->hasNull = hasNull(pColumn, pAgg);
1960 1961

  // set the statistics data for primary time stamp column
H
Haojun Liao 已提交
1962
  if (pCtx->functionId == FUNCTION_SPREAD && pColumn->colId == PRIMARYKEY_TIMESTAMP_COL_ID) {
1963 1964 1965 1966 1967 1968 1969
    pCtx->isAggSet  = true;
    pCtx->agg.min = pSDataBlock->info.window.skey;
    pCtx->agg.max = pSDataBlock->info.window.ekey;
  }
}

// set the output buffer for the selectivity + tag query
H
Haojun Liao 已提交
1970
static int32_t setCtxTagColumnInfo(SqlFunctionCtx *pCtx, int32_t numOfOutput) {
1971 1972 1973 1974 1975 1976 1977
  if (!isSelectivityWithTagsQuery(pCtx, numOfOutput)) {
    return TSDB_CODE_SUCCESS;
  }

  int32_t num = 0;
  int16_t tagLen = 0;

H
Haojun Liao 已提交
1978 1979
  SqlFunctionCtx*  p = NULL;
  SqlFunctionCtx** pTagCtx = calloc(numOfOutput, POINTER_BYTES);
1980 1981 1982 1983 1984 1985 1986 1987
  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 已提交
1988
      tagLen += pCtx[i].resDataInfo.bytes;
1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000
      pTagCtx[num++] = &pCtx[i];
    } else if (1/*(aAggs[functionId].status & FUNCSTATE_SELECTIVITY) != 0*/) {
      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) {
2001 2002 2003
    p->subsidiaryRes.pCtx = pTagCtx;
    p->subsidiaryRes.numOfCols = num;
    p->subsidiaryRes.bufLen = tagLen;
2004 2005 2006 2007 2008 2009 2010
  } else {
    tfree(pTagCtx);
  }

  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
2011
static SqlFunctionCtx* createSqlFunctionCtx(STaskRuntimeEnv* pRuntimeEnv, SExprInfo* pExpr, int32_t numOfOutput,
2012
                                            int32_t** rowCellInfoOffset) {
H
Haojun Liao 已提交
2013
  STaskAttr* pQueryAttr = pRuntimeEnv->pQueryAttr;
2014

H
Haojun Liao 已提交
2015
  SqlFunctionCtx * pFuncCtx = (SqlFunctionCtx *)calloc(numOfOutput, sizeof(SqlFunctionCtx));
2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026
  if (pFuncCtx == NULL) {
    return NULL;
  }

  *rowCellInfoOffset = calloc(numOfOutput, sizeof(int32_t));
  if (*rowCellInfoOffset == 0) {
    tfree(pFuncCtx);
    return NULL;
  }

  for (int32_t i = 0; i < numOfOutput; ++i) {
H
Haojun Liao 已提交
2027
    SExprBasicInfo *pFunct = &pExpr[i].base;
H
Haojun Liao 已提交
2028
    SqlFunctionCtx* pCtx = &pFuncCtx[i];
2029
#if 0
H
Haojun Liao 已提交
2030
    SColIndex *pIndex = &pFunct->colInfo;
2031 2032 2033 2034 2035 2036 2037

    if (TSDB_COL_REQ_NULL(pIndex->flag)) {
      pCtx->requireNull = true;
      pIndex->flag &= ~(TSDB_COL_NULL);
    } else {
      pCtx->requireNull = false;
    }
2038
#endif
H
Haojun Liao 已提交
2039 2040
//    pCtx->inputBytes = pFunct->colBytes;
//    pCtx->inputType  = pFunct->colType;
2041 2042 2043

    pCtx->ptsOutputBuf = NULL;

H
Haojun Liao 已提交
2044 2045
    pCtx->resDataInfo.bytes  = pFunct->resSchema.bytes;
    pCtx->resDataInfo.type   = pFunct->resSchema.type;
2046 2047

    pCtx->order        = pQueryAttr->order.order;
H
Haojun Liao 已提交
2048
//    pCtx->functionId   = pFunct->functionId;
2049
    pCtx->stableQuery  = pQueryAttr->stableQuery;
2050
//    pCtx->resDataInfo.interBufSize = pFunct->interBytes;
2051 2052 2053
    pCtx->start.key    = INT64_MIN;
    pCtx->end.key      = INT64_MIN;

H
Haojun Liao 已提交
2054
    pCtx->numOfParams  = pFunct->numOfParams;
2055
    for (int32_t j = 0; j < pCtx->numOfParams; ++j) {
H
Haojun Liao 已提交
2056 2057
      int16_t type = pFunct->pParam[j].param.nType;
      int16_t bytes = pFunct->pParam[j].param.nType;
2058 2059

      if (type == TSDB_DATA_TYPE_BINARY || type == TSDB_DATA_TYPE_NCHAR) {
H
Haojun Liao 已提交
2060
//        taosVariantCreateFromBinary(&pCtx->param[j], pFunct->param[j].pz, bytes, type);
2061
      } else {
H
Haojun Liao 已提交
2062
//        taosVariantCreateFromBinary(&pCtx->param[j], (char *)&pFunct->param[j].i, bytes, type);
2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077
      }
    }

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

H
Haojun Liao 已提交
2078
      pCtx->param[1].i = pQueryAttr->order.col.colId;
2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098
    } 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) {
2099
//      pCtx->param[1].pz = (char*) getScalarFuncSupport(pRuntimeEnv->scalarSup, i);
2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111
    }
  }

//  for(int32_t i = 1; i < numOfOutput; ++i) {
//    (*rowCellInfoOffset)[i] = (int32_t)((*rowCellInfoOffset)[i - 1] + sizeof(SResultRowEntryInfo) + pExpr[i - 1].base.interBytes);
//  }

  setCtxTagColumnInfo(pFuncCtx, numOfOutput);

  return pFuncCtx;
}

H
Haojun Liao 已提交
2112
static SqlFunctionCtx* createSqlFunctionCtx_rv(SExprInfo* pExprInfo, int32_t numOfOutput, int32_t** rowCellInfoOffset) {
H
Haojun Liao 已提交
2113
  SqlFunctionCtx * pFuncCtx = (SqlFunctionCtx *)calloc(numOfOutput, sizeof(SqlFunctionCtx));
H
Haojun Liao 已提交
2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124
  if (pFuncCtx == NULL) {
    return NULL;
  }

  *rowCellInfoOffset = calloc(numOfOutput, sizeof(int32_t));
  if (*rowCellInfoOffset == 0) {
    tfree(pFuncCtx);
    return NULL;
  }

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

H
Haojun Liao 已提交
2127
    SExprBasicInfo *pFunct = &pExpr->base;
H
Haojun Liao 已提交
2128
    SqlFunctionCtx* pCtx = &pFuncCtx[i];
H
Haojun Liao 已提交
2129

H
Haojun Liao 已提交
2130 2131
    if (pExpr->pExpr->_function.pFunctNode != NULL) {
      SFuncExecEnv env = {0};
H
Haojun Liao 已提交
2132 2133 2134
      pCtx->functionId = pExpr->pExpr->_function.pFunctNode->funcId;

      fmGetFuncExecFuncs(pCtx->functionId, &pCtx->fpSet);
H
Haojun Liao 已提交
2135 2136
      pCtx->fpSet.getEnv(pExpr->pExpr->_function.pFunctNode, &env);
      pCtx->resDataInfo.interBufSize = env.calcMemSize;
H
Haojun Liao 已提交
2137 2138
    } else {
      pCtx->functionId = -1;
H
Haojun Liao 已提交
2139
    }
H
Haojun Liao 已提交
2140

H
Haojun Liao 已提交
2141
    pCtx->input.numOfInputCols = pFunct->numOfParams;
H
Haojun Liao 已提交
2142 2143
    pCtx->input.pData = calloc(pFunct->numOfParams, POINTER_BYTES);
    pCtx->input.pColumnDataAgg = calloc(pFunct->numOfParams, POINTER_BYTES);
H
Haojun Liao 已提交
2144

H
Haojun Liao 已提交
2145 2146 2147 2148 2149 2150 2151
    pCtx->ptsOutputBuf       = NULL;
    pCtx->resDataInfo.bytes  = pFunct->resSchema.bytes;
    pCtx->resDataInfo.type   = pFunct->resSchema.type;
    pCtx->order              = TSDB_ORDER_ASC;
    pCtx->start.key          = INT64_MIN;
    pCtx->end.key            = INT64_MIN;
#if 0
H
Haojun Liao 已提交
2152
    for (int32_t j = 0; j < pCtx->numOfParams; ++j) {
H
Haojun Liao 已提交
2153 2154
//      int16_t type = pFunct->param[j].nType;
//      int16_t bytes = pFunct->param[j].nLen;
H
Haojun Liao 已提交
2155

H
Haojun Liao 已提交
2156 2157 2158 2159 2160
//      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 已提交
2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196
    }

    // 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 已提交
2197
#endif
H
Haojun Liao 已提交
2198 2199
  }

H
Haojun Liao 已提交
2200
  for(int32_t i = 1; i < numOfOutput; ++i) {
H
Haojun Liao 已提交
2201
    (*rowCellInfoOffset)[i] = (int32_t)((*rowCellInfoOffset)[i - 1] + sizeof(SResultRowEntryInfo) + pFuncCtx[i - 1].resDataInfo.interBufSize);
H
Haojun Liao 已提交
2202
  }
H
Haojun Liao 已提交
2203 2204 2205 2206 2207

  setCtxTagColumnInfo(pFuncCtx, numOfOutput);
  return pFuncCtx;
}

2208
static void* destroySqlFunctionCtx(SqlFunctionCtx* pCtx, int32_t numOfOutput) {
2209 2210 2211 2212 2213 2214 2215 2216 2217 2218
  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);
2219
    tfree(pCtx[i].subsidiaryRes.pCtx);
2220 2221 2222 2223 2224 2225
  }

  tfree(pCtx);
  return NULL;
}

H
Haojun Liao 已提交
2226
static int32_t setupQueryRuntimeEnv(STaskRuntimeEnv *pRuntimeEnv, int32_t numOfTables, SArray* pOperator, void* merger) {
2227
  //qDebug("QInfo:0x%"PRIx64" setup runtime env", GET_TASKID(pRuntimeEnv));
H
Haojun Liao 已提交
2228
  STaskAttr *pQueryAttr = pRuntimeEnv->pQueryAttr;
2229 2230 2231 2232 2233 2234 2235

  pRuntimeEnv->prevGroupId = INT32_MIN;
  pRuntimeEnv->pQueryAttr = pQueryAttr;

  pRuntimeEnv->pResultRowHashTable = taosHashInit(numOfTables, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true, HASH_NO_LOCK);
  pRuntimeEnv->pResultRowListSet = taosHashInit(numOfTables * 10, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), false, HASH_NO_LOCK);
  pRuntimeEnv->keyBuf  = malloc(pQueryAttr->maxTableColumnWidth + sizeof(int64_t) + POINTER_BYTES);
H
Haojun Liao 已提交
2236
//  pRuntimeEnv->pool    = initResultRowPool(getResultRowSize(pRuntimeEnv));
2237 2238 2239 2240 2241 2242 2243 2244
  pRuntimeEnv->pResultRowArrayList = taosArrayInit(numOfTables, sizeof(SResultRowCell));

  pRuntimeEnv->prevRow = malloc(POINTER_BYTES * pQueryAttr->numOfCols + pQueryAttr->srcRowSize);
  pRuntimeEnv->tagVal  = malloc(pQueryAttr->tagLen);

  // NOTE: pTableCheckInfo need to update the query time range and the lastKey info
  pRuntimeEnv->pTableRetrieveTsMap = taosHashInit(numOfTables, taosGetDefaultHashFunction(TSDB_DATA_TYPE_INT), false, HASH_NO_LOCK);

D
dapan1121 已提交
2245
  //pRuntimeEnv->scalarSup = createScalarFuncSupport(pQueryAttr->numOfOutput);
2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263

  if (pRuntimeEnv->scalarSup == NULL || pRuntimeEnv->pResultRowHashTable == NULL || pRuntimeEnv->keyBuf == NULL ||
      pRuntimeEnv->prevRow == NULL  || pRuntimeEnv->tagVal == NULL) {
    goto _clean;
  }

  if (pQueryAttr->numOfCols) {
    char* start = POINTER_BYTES * pQueryAttr->numOfCols + (char*) pRuntimeEnv->prevRow;
    pRuntimeEnv->prevRow[0] = start;
    for(int32_t i = 1; i < pQueryAttr->numOfCols; ++i) {
      pRuntimeEnv->prevRow[i] = pRuntimeEnv->prevRow[i - 1] + pQueryAttr->tableCols[i-1].bytes;
    }

    if (pQueryAttr->tableCols[0].type == TSDB_DATA_TYPE_TIMESTAMP) {
      *(int64_t*) pRuntimeEnv->prevRow[0] = INT64_MIN;
    }
  }

2264
  //qDebug("QInfo:0x%"PRIx64" init runtime environment completed", GET_TASKID(pRuntimeEnv));
2265 2266 2267 2268 2269 2270

  // group by normal column, sliding window query, interval query are handled by interval query processor
  // interval (down sampling operation)
  return TSDB_CODE_SUCCESS;

_clean:
D
dapan1121 已提交
2271
  //destroyScalarFuncSupport(pRuntimeEnv->scalarSup, pRuntimeEnv->pQueryAttr->numOfOutput);
2272 2273 2274 2275 2276 2277 2278 2279
  tfree(pRuntimeEnv->pResultRowHashTable);
  tfree(pRuntimeEnv->keyBuf);
  tfree(pRuntimeEnv->prevRow);
  tfree(pRuntimeEnv->tagVal);

  return TSDB_CODE_QRY_OUT_OF_MEMORY;
}

H
Haojun Liao 已提交
2280 2281
static void doFreeQueryHandle(STaskRuntimeEnv* pRuntimeEnv) {
  STaskAttr* pQueryAttr = pRuntimeEnv->pQueryAttr;
2282

2283
//  tsdbCleanupReadHandle(pRuntimeEnv->pTsdbReadHandle);
2284
  pRuntimeEnv->pTsdbReadHandle = NULL;
2285 2286 2287 2288 2289

//  SMemRef* pMemRef = &pQueryAttr->memRef;
//  assert(pMemRef->ref == 0 && pMemRef->snapshot.imem == NULL && pMemRef->snapshot.mem == NULL);
}

H
Haojun Liao 已提交
2290
static void destroyTsComp(STaskRuntimeEnv *pRuntimeEnv, STaskAttr *pQueryAttr) {
2291 2292 2293
  if (pQueryAttr->tsCompQuery && pRuntimeEnv->outputBuf && pRuntimeEnv->outputBuf->pDataBlock && taosArrayGetSize(pRuntimeEnv->outputBuf->pDataBlock) > 0) {
    SColumnInfoData* pColInfoData = taosArrayGet(pRuntimeEnv->outputBuf->pDataBlock, 0);
    if (pColInfoData) {
2294 2295 2296 2297
      TdFilePtr pFile = *(TdFilePtr *)pColInfoData->pData;  // TODO refactor
      if (pFile != NULL) {
        taosCloseFile(&pFile);
        *(TdFilePtr *)pColInfoData->pData = NULL;
2298 2299 2300 2301 2302
      }
    }
  }
}

2303
bool isTaskKilled(SExecTaskInfo *pTaskInfo) {
2304 2305
  // query has been executed more than tsShellActivityTimer, and the retrieve has not arrived
  // abort current query execution.
2306 2307
  if (pTaskInfo->owner != 0 && ((taosGetTimestampSec() - pTaskInfo->cost.start/1000) > 10*getMaximumIdleDurationSec())
      /*(!needBuildResAfterQueryComplete(pTaskInfo))*/) {
2308

2309 2310
    assert(pTaskInfo->cost.start != 0);
//    qDebug("QInfo:%" PRIu64 " retrieve not arrive beyond %d ms, abort current query execution, start:%" PRId64
2311
//           ", current:%d", pQInfo->qId, 1, pQInfo->startExecTs, taosGetTimestampSec());
H
Haojun Liao 已提交
2312
//    return true;
2313 2314 2315 2316 2317
  }

  return false;
}

H
Haojun Liao 已提交
2318
void setTaskKilled(SExecTaskInfo *pTaskInfo) { pTaskInfo->code = TSDB_CODE_TSC_QUERY_CANCELLED;}
2319

H
Haojun Liao 已提交
2320
//static bool isFixedOutputQuery(STaskAttr* pQueryAttr) {
2321 2322 2323 2324 2325 2326 2327 2328 2329 2330
//  if (QUERY_IS_INTERVAL_QUERY(pQueryAttr)) {
//    return false;
//  }
//
//  // Note:top/bottom query is fixed output query
//  if (pQueryAttr->topBotQuery || pQueryAttr->groupbyColumn || pQueryAttr->tsCompQuery) {
//    return true;
//  }
//
//  for (int32_t i = 0; i < pQueryAttr->numOfOutput; ++i) {
H
Haojun Liao 已提交
2331
//    SExprBasicInfo *pExpr = &pQueryAttr->pExpr1[i].base;
2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345
//
//    if (pExpr->functionId == FUNCTION_TS || pExpr->functionId == FUNCTION_TS_DUMMY) {
//      continue;
//    }
//
//    if (!IS_MULTIOUTPUT(aAggs[pExpr->functionId].status)) {
//      return true;
//    }
//  }
//
//  return false;
//}

// todo refactor with isLastRowQuery
H
Haojun Liao 已提交
2346
//bool isPointInterpoQuery(STaskAttr *pQueryAttr) {
2347 2348 2349 2350 2351 2352 2353 2354 2355 2356
//  for (int32_t i = 0; i < pQueryAttr->numOfOutput; ++i) {
//    int32_t functionId = pQueryAttr->pExpr1[i].base.functionId;
//    if (functionId == FUNCTION_INTERP) {
//      return true;
//    }
//  }
//
//  return false;
//}

H
Haojun Liao 已提交
2357
static bool isFirstLastRowQuery(STaskAttr *pQueryAttr) {
2358 2359 2360 2361 2362 2363 2364 2365 2366 2367
  for (int32_t i = 0; i < pQueryAttr->numOfOutput; ++i) {
    int32_t functionID = getExprFunctionId(&pQueryAttr->pExpr1[i]);
    if (functionID == FUNCTION_LAST_ROW) {
      return true;
    }
  }

  return false;
}

H
Haojun Liao 已提交
2368
static bool isCachedLastQuery(STaskAttr *pQueryAttr) {
2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397
  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;
  }

  if (pQueryAttr->order.order != TSDB_ORDER_DESC || !TSWINDOW_IS_EQUAL(pQueryAttr->window, TSWINDOW_DESC_INITIALIZER)) {
    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;
}

/////////////////////////////////////////////////////////////////////////////////////////////
H
Haojun Liao 已提交
2398 2399
//todo refactor : return window
void getAlignQueryTimeWindow(SInterval* pInterval, int32_t precision, int64_t key, int64_t keyFirst, int64_t keyLast, STimeWindow *win) {
2400
  ASSERT(key >= keyFirst && key <= keyLast);
H
Haojun Liao 已提交
2401
  win->skey = taosTimeTruncate(key, pInterval, precision);
2402 2403

  /*
H
Haojun Liao 已提交
2404
   * if the realSkey > INT64_MAX - pInterval->interval, the query duration between
2405 2406
   * realSkey and realEkey must be less than one interval.Therefore, no need to adjust the query ranges.
   */
H
Haojun Liao 已提交
2407 2408
  if (keyFirst > (INT64_MAX - pInterval->interval)) {
    assert(keyLast - keyFirst < pInterval->interval);
2409 2410
    win->ekey = INT64_MAX;
  } else {
2411
    win->ekey = taosTimeAdd(win->skey, pInterval->interval, pInterval->intervalUnit, precision) - 1;
2412 2413 2414 2415 2416 2417
  }
}

/*
 * todo add more parameters to check soon..
 */
H
Haojun Liao 已提交
2418
bool colIdCheck(STaskAttr *pQueryAttr, uint64_t qId) {
2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431
  // load data column information is incorrect
  for (int32_t i = 0; i < pQueryAttr->numOfCols - 1; ++i) {
    if (pQueryAttr->tableCols[i].colId == pQueryAttr->tableCols[i + 1].colId) {
      //qError("QInfo:0x%"PRIx64" invalid data load column for query", qId);
      return false;
    }
  }

  return true;
}

// todo ignore the avg/sum/min/max/count/stddev/top/bottom functions, of which
// the scan order is not matter
H
Haojun Liao 已提交
2432
static bool onlyOneQueryType(STaskAttr *pQueryAttr, int32_t functId, int32_t functIdDst) {
2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448
  for (int32_t i = 0; i < pQueryAttr->numOfOutput; ++i) {
    int32_t functionId = getExprFunctionId(&pQueryAttr->pExpr1[i]);

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

    if (functionId != functId && functionId != functIdDst) {
      return false;
    }
  }

  return true;
}

H
Haojun Liao 已提交
2449
static bool onlyFirstQuery(STaskAttr *pQueryAttr) { return onlyOneQueryType(pQueryAttr, FUNCTION_FIRST, FUNCTION_FIRST_DST); }
2450

H
Haojun Liao 已提交
2451
static bool onlyLastQuery(STaskAttr *pQueryAttr) { return onlyOneQueryType(pQueryAttr, FUNCTION_LAST, FUNCTION_LAST_DST); }
2452

H
Haojun Liao 已提交
2453
static bool notContainSessionOrStateWindow(STaskAttr *pQueryAttr) { return !(pQueryAttr->sw.gap > 0 || pQueryAttr->stateWindow); }
2454

H
Haojun Liao 已提交
2455
static int32_t updateBlockLoadStatus(STaskAttr *pQuery, int32_t status) {
2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488
  bool hasFirstLastFunc = false;
  bool hasOtherFunc = false;

  if (status == BLK_DATA_ALL_NEEDED || status == BLK_DATA_DISCARD) {
    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;
    }
  }

  if (hasFirstLastFunc && status == BLK_DATA_NO_NEEDED) {
    if(!hasOtherFunc) {
      return BLK_DATA_DISCARD;
    } else {
      return BLK_DATA_ALL_NEEDED;
    }
  }

  return status;
}

H
Haojun Liao 已提交
2489
static void doUpdateLastKey(STaskAttr* pQueryAttr) {
2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507
  STimeWindow* win = &pQueryAttr->window;

  size_t num = taosArrayGetSize(pQueryAttr->tableGroupInfo.pGroupList);
  for(int32_t i = 0; i < num; ++i) {
    SArray* p1 = taosArrayGetP(pQueryAttr->tableGroupInfo.pGroupList, i);

    size_t len = taosArrayGetSize(p1);
    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;
//      }
    }
  }
}

H
Haojun Liao 已提交
2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602
//static void updateDataCheckOrder(SQInfo *pQInfo, SQueryTableReq* pQueryMsg, bool stableQuery) {
//  STaskAttr* pQueryAttr = pQInfo->runtimeEnv.pQueryAttr;
//
//  // 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;
//
//  // 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);
//
//    pQueryAttr->order.order = TSDB_ORDER_ASC;
//    if (pQueryAttr->window.skey > pQueryAttr->window.ekey) {
//      TSWAP(pQueryAttr->window.skey, pQueryAttr->window.ekey, TSKEY);
//    }
//
//    pQueryAttr->needReverseScan = false;
//    return;
//  }
//
//  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);
//    }
//
//    pQueryAttr->needReverseScan = false;
//    doUpdateLastKey(pQueryAttr);
//    return;
//  }
//
//  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);
//    }
//
//    pQueryAttr->order.order = TSDB_ORDER_ASC;
//    return;
//  }
//
//  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,
////               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,
////                 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_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,
////                 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;
//      }
//    }
//  }
//}
2603

H
Haojun Liao 已提交
2604 2605
static void getIntermediateBufInfo(STaskRuntimeEnv* pRuntimeEnv, int32_t* ps, int32_t* rowsize) {
  STaskAttr* pQueryAttr = pRuntimeEnv->pQueryAttr;
2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619
  int32_t MIN_ROWS_PER_PAGE = 4;

  *rowsize = (int32_t)(pQueryAttr->resultRowSize * getRowNumForMultioutput(pQueryAttr, pQueryAttr->topBotQuery, pQueryAttr->stableQuery));
  int32_t overhead = sizeof(SFilePage);

  // one page contains at least two rows
  *ps = DEFAULT_INTERN_BUF_PAGE_SIZE;
  while(((*rowsize) * MIN_ROWS_PER_PAGE) > (*ps) - overhead) {
    *ps = ((*ps) << 1u);
  }
}

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

H
Haojun Liao 已提交
2620
//static FORCE_INLINE bool doFilterByBlockStatistics(STaskRuntimeEnv* pRuntimeEnv, SDataStatis *pDataStatis, SqlFunctionCtx *pCtx, int32_t numOfRows) {
H
Haojun Liao 已提交
2621
//  STaskAttr* pQueryAttr = pRuntimeEnv->pQueryAttr;
2622 2623 2624 2625 2626 2627 2628 2629
//
//  if (pDataStatis == NULL || pQueryAttr->pFilters == NULL) {
//    return true;
//  }
//
//  return filterRangeExecute(pQueryAttr->pFilters, pDataStatis, pQueryAttr->numOfCols, numOfRows);
//}

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

dengyihao's avatar
dengyihao 已提交
2633 2634
  TSKEY sk = TMIN(pQueryAttr->window.skey, pQueryAttr->window.ekey);
  TSKEY ek = TMAX(pQueryAttr->window.skey, pQueryAttr->window.ekey);
2635 2636

  if (QUERY_IS_ASC_QUERY(pQueryAttr)) {
H
Haojun Liao 已提交
2637
//    getAlignQueryTimeWindow(pQueryAttr, pBlockInfo->window.skey, sk, ek, &w);
2638 2639 2640 2641 2642 2643 2644
    assert(w.ekey >= pBlockInfo->window.skey);

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

    while(1) {
H
Haojun Liao 已提交
2645
//      getNextTimeWindow(pQueryAttr, &w);
2646 2647 2648 2649 2650 2651 2652 2653 2654 2655
      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 {
H
Haojun Liao 已提交
2656
//    getAlignQueryTimeWindow(pQueryAttr, pBlockInfo->window.ekey, sk, ek, &w);
2657 2658 2659 2660 2661 2662 2663
    assert(w.skey <= pBlockInfo->window.ekey);

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

    while(1) {
H
Haojun Liao 已提交
2664
//      getNextTimeWindow(pQueryAttr, &w);
2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678
      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;
}

H
Haojun Liao 已提交
2679
static int32_t doTSJoinFilter(STaskRuntimeEnv *pRuntimeEnv, TSKEY key, bool ascQuery) {
2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804
  STSElem elem = tsBufGetElem(pRuntimeEnv->pTsBuf);

#if defined(_DEBUG_VIEW)
  printf("elem in comp ts file:%" PRId64 ", key:%" PRId64 ", tag:%"PRIu64", query order:%d, ts order:%d, traverse:%d, index:%d\n",
         elem.ts, key, elem.tag.i, pQueryAttr->order.order, pRuntimeEnv->pTsBuf->tsOrder,
         pRuntimeEnv->pTsBuf->cur.order, pRuntimeEnv->pTsBuf->cur.tsIndex);
#endif

  if (ascQuery) {
    if (key < elem.ts) {
      return TS_JOIN_TS_NOT_EQUALS;
    } else if (key > elem.ts) {
      longjmp(pRuntimeEnv->env, TSDB_CODE_QRY_INCONSISTAN);
    }
  } else {
    if (key > elem.ts) {
      return TS_JOIN_TS_NOT_EQUALS;
    } else if (key < elem.ts) {
      longjmp(pRuntimeEnv->env, TSDB_CODE_QRY_INCONSISTAN);
    }
  }

  return TS_JOIN_TS_EQUAL;
}

bool doFilterDataBlock(SSingleColumnFilterInfo* pFilterInfo, int32_t numOfFilterCols, int32_t numOfRows, int8_t* p) {
  bool all = true;

  for (int32_t i = 0; i < numOfRows; ++i) {
    bool qualified = false;

    for (int32_t k = 0; k < numOfFilterCols; ++k) {
      char* pElem = (char*)pFilterInfo[k].pData + pFilterInfo[k].info.bytes * i;

      qualified = false;
      for (int32_t j = 0; j < pFilterInfo[k].numOfFilters; ++j) {
        SColumnFilterElem* pFilterElem = NULL;
//        SColumnFilterElem* pFilterElem = &pFilterInfo[k].pFilters[j];

        bool isnull = isNull(pElem, pFilterInfo[k].info.type);
        if (isnull) {
//          if (pFilterElem->fp == isNullOperator) {
//            qualified = true;
//            break;
//          } else {
//            continue;
//          }
        } else {
//          if (pFilterElem->fp == notNullOperator) {
//            qualified = true;
//            break;
//          } else if (pFilterElem->fp == isNullOperator) {
//            continue;
//          }
        }

        if (pFilterElem->fp(pFilterElem, pElem, pElem, pFilterInfo[k].info.type)) {
          qualified = true;
          break;
        }
      }

      if (!qualified) {
        break;
      }
    }

    p[i] = qualified ? 1 : 0;
    if (!qualified) {
      all = false;
    }
  }

  return all;
}

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

H
Haojun Liao 已提交
2805
void filterRowsInDataBlock(STaskRuntimeEnv* pRuntimeEnv, SSingleColumnFilterInfo* pFilterInfo, int32_t numOfFilterCols,
2806 2807 2808 2809 2810
                           SSDataBlock* pBlock, bool ascQuery) {
  int32_t numOfRows = pBlock->info.rows;

  int8_t *p = calloc(numOfRows, sizeof(int8_t));
  bool    all = true;
H
Haojun Liao 已提交
2811
#if 0
2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838
  if (pRuntimeEnv->pTsBuf != NULL) {
    SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, 0);

    TSKEY* k = (TSKEY*) pColInfoData->pData;
    for (int32_t i = 0; i < numOfRows; ++i) {
      int32_t offset = ascQuery? i:(numOfRows - i - 1);
      int32_t ret = doTSJoinFilter(pRuntimeEnv, k[offset], ascQuery);
      if (ret == TS_JOIN_TAG_NOT_EQUALS) {
        break;
      } else if (ret == TS_JOIN_TS_NOT_EQUALS) {
        all = false;
        continue;
      } else {
        assert(ret == TS_JOIN_TS_EQUAL);
        p[offset] = true;
      }

      if (!tsBufNextPos(pRuntimeEnv->pTsBuf)) {
        break;
      }
    }

    // save the cursor status
    pRuntimeEnv->current->cur = tsBufGetCursor(pRuntimeEnv->pTsBuf);
  } else {
    all = doFilterDataBlock(pFilterInfo, numOfFilterCols, numOfRows, p);
  }
H
Haojun Liao 已提交
2839
#endif
2840 2841 2842 2843 2844 2845 2846 2847

  if (!all) {
    doCompactSDataBlock(pBlock, numOfRows, p);
  }

  tfree(p);
}

H
Haojun Liao 已提交
2848
void filterColRowsInDataBlock(STaskRuntimeEnv* pRuntimeEnv, SSDataBlock* pBlock, bool ascQuery) {
2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877
 int32_t numOfRows = pBlock->info.rows;

 int8_t *p = NULL;
 bool    all = true;

 if (pRuntimeEnv->pTsBuf != NULL) {
   SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, 0);   
   p = calloc(numOfRows, sizeof(int8_t));
   
   TSKEY* k = (TSKEY*) pColInfoData->pData;
   for (int32_t i = 0; i < numOfRows; ++i) {
     int32_t offset = ascQuery? i:(numOfRows - i - 1);
     int32_t ret = doTSJoinFilter(pRuntimeEnv, k[offset], ascQuery);
     if (ret == TS_JOIN_TAG_NOT_EQUALS) {
       break;
     } else if (ret == TS_JOIN_TS_NOT_EQUALS) {
       all = false;
       continue;
     } else {
       assert(ret == TS_JOIN_TS_EQUAL);
       p[offset] = true;
     }

     if (!tsBufNextPos(pRuntimeEnv->pTsBuf)) {
       break;
     }
   }

   // save the cursor status
H
Haojun Liao 已提交
2878
//   pRuntimeEnv->current->cur = tsBufGetCursor(pRuntimeEnv->pTsBuf);
2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898
 } else {
//   all = filterExecute(pRuntimeEnv->pQueryAttr->pFilters, numOfRows, &p, pBlock->pBlockAgg, pRuntimeEnv->pQueryAttr->numOfCols);
 }

 if (!all) {
   if (p) {
     doCompactSDataBlock(pBlock, numOfRows, p);
   } else {
     pBlock->info.rows = 0;
     pBlock->pBlockAgg = NULL;  // clean the block statistics info
   }
 }

 tfree(p);
}

static SColumnInfo* doGetTagColumnInfoById(SColumnInfo* pTagColList, int32_t numOfTags, int16_t colId);
static void doSetTagValueInParam(void* pTable, int32_t tagColId, SVariant *tag, int16_t type, int16_t bytes);

static uint32_t doFilterByBlockTimeWindow(STableScanInfo* pTableScanInfo, SSDataBlock* pBlock) {
H
Haojun Liao 已提交
2899
  SqlFunctionCtx* pCtx = pTableScanInfo->pCtx;
2900 2901 2902 2903 2904
  uint32_t status = BLK_DATA_NO_NEEDED;

  int32_t numOfOutput = pTableScanInfo->numOfOutput;
  for (int32_t i = 0; i < numOfOutput; ++i) {
    int32_t functionId = pCtx[i].functionId;
H
Haojun Liao 已提交
2905
    int32_t colId = pTableScanInfo->pExpr[i].base.pParam[0].pCol->colId;
2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935

    // group by + first/last should not apply the first/last block filter
    if (functionId < 0) {
      status |= BLK_DATA_ALL_NEEDED;
      return status;
    } else {
//      status |= aAggs[functionId].dataReqFunc(&pTableScanInfo->pCtx[i], &pBlock->info.window, colId);
//      if ((status & BLK_DATA_ALL_NEEDED) == BLK_DATA_ALL_NEEDED) {
//        return status;
//      }
    }
  }

  return status;
}

void doSetFilterColumnInfo(SSingleColumnFilterInfo* pFilterInfo, int32_t numOfFilterCols, SSDataBlock* pBlock) {
  // set the initial static data value filter expression
  for (int32_t i = 0; i < numOfFilterCols; ++i) {
    for (int32_t j = 0; j < pBlock->info.numOfCols; ++j) {
      SColumnInfoData* pColInfo = taosArrayGet(pBlock->pDataBlock, j);

      if (pFilterInfo[i].info.colId == pColInfo->info.colId) {
        pFilterInfo[i].pData = pColInfo->pData;
        break;
      }
    }
  }
}

2936
int32_t loadDataBlock(SExecTaskInfo *pTaskInfo, STableScanInfo* pTableScanInfo, SSDataBlock* pBlock, uint32_t* status) {
H
Haojun Liao 已提交
2937 2938 2939 2940 2941 2942 2943 2944
  STaskCostInfo* pCost = &pTaskInfo->cost;

  pCost->totalBlocks += 1;
  pCost->totalRows += pBlock->info.rows;

  pCost->totalCheckedRows += pBlock->info.rows;
  pCost->loadBlocks += 1;

H
Haojun Liao 已提交
2945 2946
  *status = BLK_DATA_ALL_NEEDED;

2947
  pBlock->pDataBlock = tsdbRetrieveDataBlock(pTableScanInfo->pTsdbReadHandle, NULL);
H
Haojun Liao 已提交
2948 2949
  if (pBlock->pDataBlock == NULL) {
    return terrno;
2950 2951
  } else {
    return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
2952 2953 2954
  }
}

2955
int32_t loadDataBlockOnDemand(SExecTaskInfo *pTaskInfo, STableScanInfo* pTableScanInfo, SSDataBlock* pBlock, uint32_t* status) {
2956 2957
  *status = BLK_DATA_NO_NEEDED;

H
Haojun Liao 已提交
2958 2959 2960 2961 2962
  pBlock->pDataBlock = NULL;
  pBlock->pBlockAgg  = NULL;

//  int64_t groupId = pRuntimeEnv->current->groupIndex;
//  bool    ascQuery = QUERY_IS_ASC_QUERY(pQueryAttr);
2963

H
Haojun Liao 已提交
2964
  STaskCostInfo* pCost = &pTaskInfo->cost;
2965 2966 2967

  pCost->totalBlocks += 1;
  pCost->totalRows += pBlock->info.rows;
H
Haojun Liao 已提交
2968
#if 0
2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992
  if (pRuntimeEnv->pTsBuf != NULL) {
    (*status) = BLK_DATA_ALL_NEEDED;

    if (pQueryAttr->stableQuery) {  // todo refactor
      SExprInfo*   pExprInfo = &pTableScanInfo->pExpr[0];
      int16_t      tagId = (int16_t)pExprInfo->base.param[0].i;
      SColumnInfo* pColInfo = doGetTagColumnInfoById(pQueryAttr->tagColList, pQueryAttr->numOfTags, tagId);

      // compare tag first
      SVariant t = {0};
      doSetTagValueInParam(pRuntimeEnv->current->pTable, tagId, &t, pColInfo->type, pColInfo->bytes);
      setTimestampListJoinInfo(pRuntimeEnv, &t, pRuntimeEnv->current);

      STSElem elem = tsBufGetElem(pRuntimeEnv->pTsBuf);
      if (!tsBufIsValidElem(&elem) || (tsBufIsValidElem(&elem) && (taosVariantCompare(&t, elem.tag) != 0))) {
        (*status) = BLK_DATA_DISCARD;
        return TSDB_CODE_SUCCESS;
      }
    }
  }

  // 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 已提交
2993
      (QUERY_IS_INTERVAL_QUERY(pQueryAttr) && overlapWithTimeWindow(pTaskInfo, &pBlock->info))) {
2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005
    (*status) = BLK_DATA_ALL_NEEDED;
  }

  // check if this data block is required to load
  if ((*status) != BLK_DATA_ALL_NEEDED) {
    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 已提交
3006
      bool  masterScan = IS_MAIN_SCAN(pRuntimeEnv);
3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034
      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 {
      (*status) = BLK_DATA_ALL_NEEDED;
    }
  }

  SDataBlockInfo* pBlockInfo = &pBlock->info;
H
Haojun Liao 已提交
3035
//  *status = updateBlockLoadStatus(pRuntimeEnv->pQueryAttr, *status);
3036 3037 3038 3039 3040 3041 3042 3043

  if ((*status) == BLK_DATA_NO_NEEDED || (*status) == BLK_DATA_DISCARD) {
    //qDebug("QInfo:0x%"PRIx64" data block discard, brange:%" PRId64 "-%" PRId64 ", rows:%d", pQInfo->qId, pBlockInfo->window.skey,
//           pBlockInfo->window.ekey, pBlockInfo->rows);
    pCost->discardBlocks += 1;
  } else if ((*status) == BLK_DATA_STATIS_NEEDED) {
    // this function never returns error?
    pCost->loadBlockStatis += 1;
3044
//    tsdbRetrieveDataBlockStatisInfo(pTableScanInfo->pTsdbReadHandle, &pBlock->pBlockAgg);
3045 3046

    if (pBlock->pBlockAgg == NULL) {  // data block statistics does not exist, load data block
3047
//      pBlock->pDataBlock = tsdbRetrieveDataBlock(pTableScanInfo->pTsdbReadHandle, NULL);
3048 3049 3050 3051 3052 3053 3054
      pCost->totalCheckedRows += pBlock->info.rows;
    }
  } else {
    assert((*status) == BLK_DATA_ALL_NEEDED);

    // load the data block statistics to perform further filter
    pCost->loadBlockStatis += 1;
3055
//    tsdbRetrieveDataBlockStatisInfo(pTableScanInfo->pTsdbReadHandle, &pBlock->pBlockAgg);
3056 3057 3058 3059 3060 3061

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

H
Haojun Liao 已提交
3062
          bool  masterScan = IS_MAIN_SCAN(pRuntimeEnv);
3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100
          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
            pCost->discardBlocks += 1;
            //qDebug("QInfo:0x%"PRIx64" data block discard, brange:%" PRId64 "-%" PRId64 ", rows:%d", pQInfo->qId,
//                   pBlockInfo->window.skey, pBlockInfo->window.ekey, pBlockInfo->rows);
            (*status) = BLK_DATA_DISCARD;
            return TSDB_CODE_SUCCESS;
          }
        }
      }
    }

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

    pCost->totalCheckedRows += pBlockInfo->rows;
    pCost->loadBlocks += 1;
3101
//    pBlock->pDataBlock = tsdbRetrieveDataBlock(pTableScanInfo->pTsdbReadHandle, NULL);
3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113
//    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 已提交
3114
#endif
3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181
  return TSDB_CODE_SUCCESS;
}

int32_t binarySearchForKey(char *pValue, int num, TSKEY key, int order) {
  int32_t midPos = -1;
  int32_t numOfRows;

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

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

  TSKEY * keyList = (TSKEY *)pValue;
  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 已提交
3182
 * set tag value in SqlFunctionCtx
3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222
 * e.g.,tag information into input buffer
 */
static void doSetTagValueInParam(void* pTable, int32_t tagColId, SVariant *tag, int16_t type, int16_t bytes) {
  taosVariantDestroy(tag);

  char* val = NULL;
//  if (tagColId == TSDB_TBNAME_COLUMN_INDEX) {
//    val = tsdbGetTableName(pTable);
//    assert(val != NULL);
//  } else {
//    val = tsdbGetTableTagVal(pTable, tagColId, type, bytes);
//  }

  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;
    int32_t len = (varDataLen(val) > maxLen)? maxLen:varDataLen(val);
    taosVariantCreateFromBinary(tag, varDataVal(val), len, type);
    //taosVariantCreateFromBinary(tag, varDataVal(val), varDataLen(val), type);
  } else {
    taosVariantCreateFromBinary(tag, val, bytes, type);
  }
}

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

  for(int32_t i = 0; i < numOfTags; ++i) {
    if (pTagColList[i].colId == colId) {
      return &pTagColList[i];
    }
  }

  return NULL;
}

H
Haojun Liao 已提交
3223
void setTagValue(SOperatorInfo* pOperatorInfo, void *pTable, SqlFunctionCtx* pCtx, int32_t numOfOutput) {
H
Haojun Liao 已提交
3224
  STaskRuntimeEnv* pRuntimeEnv = pOperatorInfo->pRuntimeEnv;
3225 3226

  SExprInfo  *pExpr      = pOperatorInfo->pExpr;
H
Haojun Liao 已提交
3227
  STaskAttr *pQueryAttr = pRuntimeEnv->pQueryAttr;
3228 3229 3230 3231 3232 3233 3234

  SExprInfo* pExprInfo = &pExpr[0];
  int32_t functionId = getExprFunctionId(pExprInfo);

  if (pQueryAttr->numOfOutput == 1 && functionId == FUNCTION_TS_COMP && pQueryAttr->stableQuery) {
    assert(pExprInfo->base.numOfParams == 1);

H
Haojun Liao 已提交
3235 3236
//    int16_t      tagColId = (int16_t)pExprInfo->base.param[0].i;
    int16_t      tagColId = -1;
3237 3238 3239
    SColumnInfo* pColInfo = doGetTagColumnInfoById(pQueryAttr->tagColList, pQueryAttr->numOfTags, tagColId);

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

3241 3242 3243 3244 3245 3246 3247 3248 3249
  } 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 已提交
3250
      if (!TSDB_COL_IS_TAG(pLocalExprInfo->base.pParam[0].pCol->flag)) {
3251 3252 3253 3254
        continue;
      }

      // todo use tag column index to optimize performance
H
Haojun Liao 已提交
3255
      doSetTagValueInParam(pTable, pLocalExprInfo->base.pParam[0].pCol->colId, &pCtx[idx].tag, pLocalExprInfo->base.resSchema.type,
3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282
                           pLocalExprInfo->base.resSchema.bytes);

      if (IS_NUMERIC_TYPE(pLocalExprInfo->base.resSchema.type)
          || pLocalExprInfo->base.resSchema.type == TSDB_DATA_TYPE_BOOL
          || pLocalExprInfo->base.resSchema.type == TSDB_DATA_TYPE_TIMESTAMP) {
        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);
        }      
      }

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

    //todo : use index to avoid iterator all possible output columns
    if (pQueryAttr->stableQuery && pQueryAttr->stabledev && (pRuntimeEnv->prevResult != NULL)) {
      setParamForStableStddev(pRuntimeEnv, pCtx, numOfOutput, pExprInfo);
    }
  }

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

H
Haojun Liao 已提交
3283
void copyToSDataBlock(SSDataBlock* pBlock, int32_t* offset, SGroupResInfo* pGroupResInfo, SDiskbasedBuf* pResBuf) {
3284 3285 3286 3287 3288 3289 3290
  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);
H
Haojun Liao 已提交
3291
//      if ((code = mergeIntoGroupResult(&pGroupResInfo, pRuntimeEnv, offset)) != TSDB_CODE_SUCCESS) {
3292
        return;
H
Haojun Liao 已提交
3293
//      }
3294 3295
    }

H
Haojun Liao 已提交
3296
//    doCopyToSDataBlock(pResBuf, pGroupResInfo, TSDB_ORDER_ASC, pBlock, );
3297 3298 3299 3300 3301 3302 3303 3304 3305 3306

    // 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
H
Haojun Liao 已提交
3307 3308 3309
//    if (pBlock->info.rows >= threshold) {
//      break;
//    }
3310 3311 3312 3313 3314 3315 3316 3317
  }
}

static void updateTableQueryInfoForReverseScan(STableQueryInfo *pTableQueryInfo) {
  if (pTableQueryInfo == NULL) {
    return;
  }

H
Haojun Liao 已提交
3318 3319
//  TSWAP(pTableQueryInfo->win.skey, pTableQueryInfo->win.ekey, TSKEY);
//  pTableQueryInfo->lastKey = pTableQueryInfo->win.skey;
3320

H
Haojun Liao 已提交
3321 3322
//  SWITCH_ORDER(pTableQueryInfo->cur.order);
//  pTableQueryInfo->cur.vgroupIndex = -1;
3323 3324 3325 3326 3327 3328 3329 3330 3331 3332

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

H
Haojun Liao 已提交
3333 3334
static void setupQueryRangeForReverseScan(STableScanInfo* pTableScanInfo) {
#if 0
3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352
  int32_t numOfGroups = (int32_t)(GET_NUM_OF_TABLEGROUP(pRuntimeEnv));
  for(int32_t i = 0; i < numOfGroups; ++i) {
    SArray *group = GET_TABLEGROUP(pRuntimeEnv, i);
    SArray *tableKeyGroup = taosArrayGetP(pQueryAttr->tableGroupInfo.pGroupList, i);

    size_t t = taosArrayGetSize(group);
    for (int32_t j = 0; j < t; ++j) {
      STableQueryInfo *pCheckInfo = taosArrayGetP(group, j);
      updateTableQueryInfoForReverseScan(pCheckInfo);

      // update the last key in tableKeyInfo list, the tableKeyInfo is used to build the tsdbQueryHandle and decide
      // the start check timestamp of tsdbQueryHandle
//      STableKeyInfo *pTableKeyInfo = taosArrayGet(tableKeyGroup, j);
//      pTableKeyInfo->lastKey = pCheckInfo->lastKey;
//
//      assert(pCheckInfo->pTable == pTableKeyInfo->pTable);
    }
  }
H
Haojun Liao 已提交
3353 3354
#endif

3355 3356
}

H
Haojun Liao 已提交
3357
void switchCtxOrder(SqlFunctionCtx* pCtx, int32_t numOfOutput) {
3358 3359 3360 3361 3362
  for (int32_t i = 0; i < numOfOutput; ++i) {
    SWITCH_ORDER(pCtx[i].order);
  }
}

3363
// TODO fix this bug.
3364 3365 3366 3367 3368 3369 3370 3371
int32_t initResultRow(SResultRow *pResultRow) {
  pResultRow->pEntryInfo = (struct SResultRowEntryInfo*)((char*)pResultRow + sizeof(SResultRow));
  return TSDB_CODE_SUCCESS;
}

/*
 * 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 已提交
3372 3373 3374
 * +------------+-----------------result column 1------------+------------------result column 2-----------+
 * | SResultRow | SResultRowEntryInfo | intermediate buffer1 | SResultRowEntryInfo | intermediate buffer 2|
 * +------------+--------------------------------------------+--------------------------------------------+
3375 3376
 *           offset[0]                                  offset[1]                                   offset[2]
 */
3377
// TODO refactor: some function move away
H
Haojun Liao 已提交
3378
void setFunctionResultOutput(SOptrBasicInfo* pInfo, SAggSupporter* pSup, int32_t stage, SExecTaskInfo* pTaskInfo) {
H
Haojun Liao 已提交
3379
  SqlFunctionCtx* pCtx           = pInfo->pCtx;
H
Haojun Liao 已提交
3380 3381 3382 3383 3384
  SSDataBlock* pDataBlock        = pInfo->pRes;
  int32_t* rowCellInfoOffset     = pInfo->rowCellInfoOffset;
  SResultRowInfo* pResultRowInfo = &pInfo->resultRowInfo;

  int64_t tid = 0;
H
Haojun Liao 已提交
3385
  int64_t groupId = 0;
H
Haojun Liao 已提交
3386
  SResultRow* pRow = doSetResultOutBufByKey_rv(pSup->pResultBuf, pResultRowInfo, tid, (char *)&tid, sizeof(tid), true, groupId, pTaskInfo, false, pSup);
H
Haojun Liao 已提交
3387 3388 3389 3390 3391 3392 3393 3394 3395

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

    pCtx[i].resultInfo   = pEntry;
    pCtx[i].currentStage = stage;

    // set the timestamp output buffer for top/bottom/diff query
H
Haojun Liao 已提交
3396 3397 3398 3399
//    int32_t fid = pCtx[i].functionId;
//    if (fid == FUNCTION_TOP || fid == FUNCTION_BOTTOM || fid == FUNCTION_DIFF || fid == FUNCTION_DERIVATIVE) {
//      if (i > 0) pCtx[i].ptsOutputBuf = pCtx[i-1].pOutput;
//    }
H
Haojun Liao 已提交
3400 3401 3402 3403 3404
  }

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

3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439
void updateOutputBuf(SOptrBasicInfo* pBInfo, int32_t *bufCapacity, int32_t numOfInputRows) {
  SSDataBlock* pDataBlock = pBInfo->pRes;

  int32_t newSize = pDataBlock->info.rows + numOfInputRows + 5; // extra output buffer
  if ((*bufCapacity) < newSize) {
    for(int32_t i = 0; i < pDataBlock->info.numOfCols; ++i) {
      SColumnInfoData *pColInfo = taosArrayGet(pDataBlock->pDataBlock, i);

      char* p = realloc(pColInfo->pData, newSize * pColInfo->info.bytes);
      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) {
    SColumnInfoData *pColInfo = taosArrayGet(pDataBlock->pDataBlock, i);
    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;

    if (functionId == FUNCTION_TOP || functionId == FUNCTION_BOTTOM || functionId == FUNCTION_DIFF || functionId == FUNCTION_DERIVATIVE) {
      if (i > 0) pBInfo->pCtx[i].ptsOutputBuf = pBInfo->pCtx[i-1].pOutput;
    }
  }
}

H
Haojun Liao 已提交
3440
void copyTsColoum(SSDataBlock* pRes, SqlFunctionCtx* pCtx, int32_t numOfOutput) {
3441 3442 3443 3444 3445 3446 3447
  bool    needCopyTs = false;
  int32_t tsNum = 0;
  char *src = NULL;
  for (int32_t i = 0; i < numOfOutput; i++) {
    int32_t functionId = pCtx[i].functionId;
    if (functionId == FUNCTION_DIFF || functionId == FUNCTION_DERIVATIVE) {
      needCopyTs = true;
H
Haojun Liao 已提交
3448
      if (i > 0  && pCtx[i-1].functionId == FUNCTION_TS_DUMMY) {
3449 3450 3451
        SColumnInfoData* pColRes = taosArrayGet(pRes->pDataBlock, i - 1); // find ts data
        src = pColRes->pData;
      }
H
Haojun Liao 已提交
3452
    } else if(functionId == FUNCTION_TS_DUMMY) {
3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482
      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;
    if(functionId == FUNCTION_TS_DUMMY) {
      SColumnInfoData* pColRes = taosArrayGet(pRes->pDataBlock, i);
      memcpy(pColRes->pData, src, pColRes->info.bytes * pRes->info.rows);
    }
  }
}

void clearOutputBuf(SOptrBasicInfo* pBInfo, int32_t *bufCapacity) {
  SSDataBlock* pDataBlock = pBInfo->pRes;

  for (int32_t i = 0; i < pDataBlock->info.numOfCols; ++i) {
    SColumnInfoData *pColInfo = taosArrayGet(pDataBlock->pDataBlock, i);

    int32_t functionId = pBInfo->pCtx[i].functionId;
    if (functionId < 0) {
      memset(pBInfo->pCtx[i].pOutput, 0, pColInfo->info.bytes * (*bufCapacity));
    }
  }
}

H
Haojun Liao 已提交
3483
void initCtxOutputBuffer(SqlFunctionCtx* pCtx, int32_t size) {
3484 3485
  for (int32_t j = 0; j < size; ++j) {
    struct SResultRowEntryInfo* pResInfo = GET_RES_INFO(&pCtx[j]);
H
Haojun Liao 已提交
3486
    if (isRowEntryInitialized(pResInfo) || pCtx[j].functionId == -1) {
3487 3488 3489
      continue;
    }

H
Haojun Liao 已提交
3490
    pCtx[j].fpSet.init(&pCtx[j], pCtx[j].resultInfo);
3491 3492 3493
  }
}

3494 3495
void setTaskStatus(SExecTaskInfo *pTaskInfo, int8_t status) {
  if (status == TASK_NOT_COMPLETED) {
H
Haojun Liao 已提交
3496
    pTaskInfo->status = status;
3497 3498
  } else {
    // QUERY_NOT_COMPLETED is not compatible with any other status, so clear its position first
3499
    CLEAR_QUERY_STATUS(pTaskInfo, TASK_NOT_COMPLETED);
H
Haojun Liao 已提交
3500
    pTaskInfo->status |= status;
3501 3502 3503
  }
}

H
Haojun Liao 已提交
3504
static void setupEnvForReverseScan(STableScanInfo *pTableScanInfo, SqlFunctionCtx* pCtx, int32_t numOfOutput) {
H
Haojun Liao 已提交
3505 3506 3507 3508 3509
//  if (pRuntimeEnv->pTsBuf) {
//    SWITCH_ORDER(pRuntimeEnv->pTsBuf->cur.order);
//    bool ret = tsBufNextPos(pRuntimeEnv->pTsBuf);
//    assert(ret);
//  }
3510 3511

  // reverse order time range
H
Haojun Liao 已提交
3512 3513
  SET_REVERSE_SCAN_FLAG(pTableScanInfo);
//  setTaskStatus(pTableScanInfo, QUERY_NOT_COMPLETED);
3514 3515 3516

  switchCtxOrder(pCtx, numOfOutput);

H
Haojun Liao 已提交
3517 3518
  SWITCH_ORDER(pTableScanInfo->order);
  setupQueryRangeForReverseScan(pTableScanInfo);
3519 3520 3521 3522

  pTableScanInfo->times        = 1;
  pTableScanInfo->current      = 0;
  pTableScanInfo->reverseTimes = 0;
3523 3524
}

3525 3526
void finalizeQueryResult(SqlFunctionCtx* pCtx, int32_t numOfOutput) {
  for (int32_t j = 0; j < numOfOutput; ++j) {
H
Haojun Liao 已提交
3527 3528 3529 3530
    if (pCtx[j].functionId == -1) {
      continue;
    }

3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544
    pCtx[j].fpSet.finalize(&pCtx[j]);
  }
}

void finalizeMultiTupleQueryResult(SqlFunctionCtx* pCtx, int32_t numOfOutput, SDiskbasedBuf *pBuf, SResultRowInfo* pResultRowInfo, int32_t* rowCellInfoOffset) {
  for (int32_t i = 0; i < pResultRowInfo->size; ++i) {
    SResultRowPosition* pPos = &pResultRowInfo->pPosition[i];

    SFilePage* bufPage = getBufPage(pBuf, pPos->pageId);
    SResultRow* pRow = (SResultRow*)((char*)bufPage + pPos->offset);
    if (!isResultRowClosed(pResultRowInfo, i)) {
      continue;
    }

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

H
Haojun Liao 已提交
3548
      struct SResultRowEntryInfo* pResInfo = pCtx[j].resultInfo;
3549 3550 3551 3552
      if (isRowEntryCompleted(pResInfo) && isRowEntryInitialized(pResInfo)) {
        continue;
      }

H
Haojun Liao 已提交
3553 3554 3555
      if (pCtx[j].fpSet.process) { // TODO set the dummy function.
        pCtx[j].fpSet.finalize(&pCtx[j]);
      }
3556 3557 3558 3559

      if (pRow->numOfRows < pResInfo->numOfRes) {
        pRow->numOfRows = pResInfo->numOfRes;
      }
3560
    }
3561 3562 3563 3564 3565 3566 3567 3568

    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);
  }
3569 3570
}

H
Haojun Liao 已提交
3571
static bool hasMainOutput(STaskAttr *pQueryAttr) {
3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582
  for (int32_t i = 0; i < pQueryAttr->numOfOutput; ++i) {
    int32_t functionId = getExprFunctionId(&pQueryAttr->pExpr1[i]);

    if (functionId != FUNCTION_TS && functionId != FUNCTION_TAG && functionId != FUNCTION_TAGPRJ) {
      return true;
    }
  }

  return false;
}

H
Haojun Liao 已提交
3583
STableQueryInfo *createTableQueryInfo(void* buf, bool groupbyColumn, STimeWindow win) {
3584 3585 3586 3587
  STableQueryInfo *pTableQueryInfo = buf;
  pTableQueryInfo->lastKey = win.skey;

  // set more initial size of interval/groupby query
H
Haojun Liao 已提交
3588
//  if (/*QUERY_IS_INTERVAL_QUERY(pQueryAttr) || */groupbyColumn) {
3589
    int32_t initialSize = 128;
3590
    int32_t code = initResultRowInfo(&pTableQueryInfo->resInfo, initialSize);
3591 3592 3593
    if (code != TSDB_CODE_SUCCESS) {
      return NULL;
    }
H
Haojun Liao 已提交
3594 3595
//  } else { // in other aggregate query, do not initialize the windowResInfo
//  }
3596 3597 3598 3599 3600 3601 3602

  return pTableQueryInfo;
}

STableQueryInfo* createTmpTableQueryInfo(STimeWindow win) {
  STableQueryInfo* pTableQueryInfo = calloc(1, sizeof(STableQueryInfo));

H
Haojun Liao 已提交
3603
//  pTableQueryInfo->win = win;
3604 3605 3606 3607
  pTableQueryInfo->lastKey = win.skey;

  // set more initial size of interval/groupby query
  int32_t initialSize = 16;
3608
  int32_t code = initResultRowInfo(&pTableQueryInfo->resInfo, initialSize);
3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621
  if (code != TSDB_CODE_SUCCESS) {
    tfree(pTableQueryInfo);
    return NULL;
  }

  return pTableQueryInfo;
}

void destroyTableQueryInfoImpl(STableQueryInfo *pTableQueryInfo) {
  if (pTableQueryInfo == NULL) {
    return;
  }

3622
//  taosVariantDestroy(&pTableQueryInfo->tag);
3623 3624 3625
  cleanupResultRowInfo(&pTableQueryInfo->resInfo);
}

H
Haojun Liao 已提交
3626
void setResultRowOutputBufInitCtx(STaskRuntimeEnv *pRuntimeEnv, SResultRow *pResult, SqlFunctionCtx* pCtx,
3627 3628
    int32_t numOfOutput, int32_t* rowCellInfoOffset) {
  // Note: pResult->pos[i]->num == 0, there is only fixed number of results for each group
3629
  SFilePage* bufPage = getBufPage(pRuntimeEnv->pResultBuf, pResult->pageId);
3630 3631 3632 3633 3634 3635 3636

  int32_t offset = 0;
  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)) {
H
Haojun Liao 已提交
3637
      offset += pCtx[i].resDataInfo.bytes;
3638 3639 3640 3641
      continue;
    }

    pCtx[i].pOutput = getPosInResultPage(pRuntimeEnv->pQueryAttr, bufPage, pResult->offset, offset);
H
Haojun Liao 已提交
3642
    offset += pCtx[i].resDataInfo.bytes;
3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658

    int32_t functionId = pCtx[i].functionId;
    if (functionId < 0) {
      continue;
    }

    if (functionId == FUNCTION_TOP || functionId == FUNCTION_BOTTOM || functionId == FUNCTION_DIFF) {
      if(i > 0) pCtx[i].ptsOutputBuf = pCtx[i-1].pOutput;
    }

//    if (!pResInfo->initialized) {
//      aAggs[functionId].init(&pCtx[i], pResInfo);
//    }
  }
}

3659 3660 3661 3662 3663 3664 3665 3666 3667
void setResultRowOutputBufInitCtx_rv(SDiskbasedBuf * pBuf, SResultRow *pResult, SqlFunctionCtx* pCtx, int32_t numOfOutput, int32_t* rowCellInfoOffset) {
  // Note: pResult->pos[i]->num == 0, there is only fixed number of results for each group
  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;
    }
3668 3669 3670 3671 3672 3673 3674
//    int32_t functionId = pCtx[i].functionId;
//    if (functionId < 0) {
//      continue;
//    }
//    if (functionId == FUNCTION_TOP || functionId == FUNCTION_BOTTOM || functionId == FUNCTION_DIFF) {
//      if (i > 0) pCtx[i].ptsOutputBuf = pCtx[i - 1].pOutput;
//    }
3675

H
Haojun Liao 已提交
3676
    if (!pResInfo->initialized && pCtx[i].functionId != -1) {
3677
      pCtx[i].fpSet.init(&pCtx[i], pResInfo);
3678 3679 3680 3681 3682
    }
  }
}

void doSetTableGroupOutputBuf(SAggOperatorInfo* pAggInfo, int32_t numOfOutput, int32_t tableGroupId, SExecTaskInfo* pTaskInfo) {
3683 3684 3685 3686
  // for simple group by query without interval, all the tables belong to one group result.
  int64_t uid = 0;
  int64_t tid = 0;

3687 3688 3689 3690
  SResultRowInfo* pResultRowInfo = &pAggInfo->binfo.resultRowInfo;
  SqlFunctionCtx* pCtx = pAggInfo->binfo.pCtx;
  int32_t* rowCellInfoOffset = pAggInfo->binfo.rowCellInfoOffset;

3691
  SResultRow* pResultRow =
3692
      doSetResultOutBufByKey_rv(pAggInfo->pResultBuf, pResultRowInfo, tid, (char*)&tableGroupId, sizeof(tableGroupId), true, uid, pTaskInfo, false, &pAggInfo->aggSup);
3693 3694 3695 3696 3697 3698 3699
  assert (pResultRow != NULL);

  /*
   * 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 已提交
3700
    int32_t ret = addNewWindowResultBuf(pResultRow, pAggInfo->pResultBuf, tableGroupId, pAggInfo->binfo.pRes->info.rowSize);
3701 3702 3703 3704 3705
    if (ret != TSDB_CODE_SUCCESS) {
      return;
    }
  }

3706
  setResultRowOutputBufInitCtx_rv(pAggInfo->pResultBuf, pResultRow, pCtx, numOfOutput, rowCellInfoOffset);
3707 3708
}

3709
void setExecutionContext(int32_t numOfOutput, int32_t tableGroupId, TSKEY nextKey, SExecTaskInfo* pTaskInfo, STableQueryInfo *pTableQueryInfo, SAggOperatorInfo* pAggInfo) {
3710 3711
  // lastKey needs to be updated
  pTableQueryInfo->lastKey = nextKey;
3712
  if (pAggInfo->groupId != INT32_MIN && pAggInfo->groupId == tableGroupId) {
3713 3714 3715
    return;
  }

3716
  doSetTableGroupOutputBuf(pAggInfo, numOfOutput, tableGroupId, pTaskInfo);
3717 3718

  // record the current active group id
3719
  pAggInfo->groupId = tableGroupId;
3720 3721
}

H
Haojun Liao 已提交
3722
void setResultOutputBuf(STaskRuntimeEnv *pRuntimeEnv, SResultRow *pResult, SqlFunctionCtx* pCtx,
3723 3724
    int32_t numOfCols, int32_t* rowCellInfoOffset) {
  // Note: pResult->pos[i]->num == 0, there is only fixed number of results for each group
3725
  SFilePage *page = getBufPage(pRuntimeEnv->pResultBuf, pResult->pageId);
3726 3727 3728 3729

  int16_t offset = 0;
  for (int32_t i = 0; i < numOfCols; ++i) {
    pCtx[i].pOutput = getPosInResultPage(pRuntimeEnv->pQueryAttr, page, pResult->offset, offset);
H
Haojun Liao 已提交
3730
    offset += pCtx[i].resDataInfo.bytes;
3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744

    int32_t functionId = pCtx[i].functionId;
    if (functionId == FUNCTION_TOP || functionId == FUNCTION_BOTTOM || functionId == FUNCTION_DIFF || functionId == FUNCTION_DERIVATIVE) {
      if(i > 0) pCtx[i].ptsOutputBuf = pCtx[i-1].pOutput;
    }

    /*
     * set the output buffer information and intermediate buffer,
     * not all queries require the interResultBuf, such as COUNT
     */
    pCtx[i].resultInfo = getResultCell(pResult, i, rowCellInfoOffset);
  }
}

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

H
Haojun Liao 已提交
3748
  SExprBasicInfo* pExpr = &pExprInfo->base;
3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760
//  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) {
3761
//      //qDebug("QInfo:0x%"PRIx64" set tag value for join comparison, colId:%" PRId64 ", val:%s", GET_TASKID(pRuntimeEnv),
3762 3763
////             pExprInfo->base.param[0].i, pCtx[0].tag.pz);
//    } else {
3764
//      //qDebug("QInfo:0x%"PRIx64" set tag value for join comparison, colId:%" PRId64 ", val:%" PRId64, GET_TASKID(pRuntimeEnv),
3765 3766 3767 3768 3769
////             pExprInfo->base.param[0].i, pCtx[0].tag.i);
//    }
//  }
}

H
Haojun Liao 已提交
3770 3771
int32_t setTimestampListJoinInfo(STaskRuntimeEnv* pRuntimeEnv, SVariant* pTag, STableQueryInfo *pTableQueryInfo) {
  STaskAttr* pQueryAttr = pRuntimeEnv->pQueryAttr;
3772 3773

  assert(pRuntimeEnv->pTsBuf != NULL);
H
Haojun Liao 已提交
3774
#if 0
3775 3776 3777 3778 3779 3780 3781 3782 3783
  // both the master and supplement scan needs to set the correct ts comp start position
  if (pTableQueryInfo->cur.vgroupIndex == -1) {
    taosVariantAssign(&pTableQueryInfo->tag, pTag);

    STSElem elem = tsBufGetElemStartPos(pRuntimeEnv->pTsBuf, pQueryAttr->vgId, &pTableQueryInfo->tag);

    // failed to find data with the specified tag value and vnodeId
    if (!tsBufIsValidElem(&elem)) {
      if (pTag->nType == TSDB_DATA_TYPE_BINARY || pTag->nType == TSDB_DATA_TYPE_NCHAR) {
3784
        //qError("QInfo:0x%"PRIx64" failed to find tag:%s in ts_comp", GET_TASKID(pRuntimeEnv), pTag->pz);
3785
      } else {
3786
        //qError("QInfo:0x%"PRIx64" failed to find tag:%" PRId64 " in ts_comp", GET_TASKID(pRuntimeEnv), pTag->i);
3787 3788 3789 3790 3791 3792 3793 3794
      }

      return -1;
    }

    // Keep the cursor info of current table
    pTableQueryInfo->cur = tsBufGetCursor(pRuntimeEnv->pTsBuf);
    if (pTag->nType == TSDB_DATA_TYPE_BINARY || pTag->nType == TSDB_DATA_TYPE_NCHAR) {
3795
      //qDebug("QInfo:0x%"PRIx64" find tag:%s start pos in ts_comp, blockIndex:%d, tsIndex:%d", GET_TASKID(pRuntimeEnv), pTag->pz, pTableQueryInfo->cur.blockIndex, pTableQueryInfo->cur.tsIndex);
3796
    } else {
3797
      //qDebug("QInfo:0x%"PRIx64" find tag:%"PRId64" start pos in ts_comp, blockIndex:%d, tsIndex:%d", GET_TASKID(pRuntimeEnv), pTag->i, pTableQueryInfo->cur.blockIndex, pTableQueryInfo->cur.tsIndex);
3798 3799 3800 3801 3802
    }

  } else {
    tsBufSetCursor(pRuntimeEnv->pTsBuf, &pTableQueryInfo->cur);
    if (pTag->nType == TSDB_DATA_TYPE_BINARY || pTag->nType == TSDB_DATA_TYPE_NCHAR) {
3803
      //qDebug("QInfo:0x%"PRIx64" find tag:%s start pos in ts_comp, blockIndex:%d, tsIndex:%d", GET_TASKID(pRuntimeEnv), pTag->pz, pTableQueryInfo->cur.blockIndex, pTableQueryInfo->cur.tsIndex);
3804
    } else {
3805
      //qDebug("QInfo:0x%"PRIx64" find tag:%"PRId64" start pos in ts_comp, blockIndex:%d, tsIndex:%d", GET_TASKID(pRuntimeEnv), pTag->i, pTableQueryInfo->cur.blockIndex, pTableQueryInfo->cur.tsIndex);
3806 3807
    }
  }
H
Haojun Liao 已提交
3808
#endif
3809 3810 3811 3812
  return 0;
}

// TODO refactor: this funciton should be merged with setparamForStableStddevColumnData function.
H
Haojun Liao 已提交
3813
void setParamForStableStddev(STaskRuntimeEnv* pRuntimeEnv, SqlFunctionCtx* pCtx, int32_t numOfOutput, SExprInfo* pExprInfo) {
3814
#if 0
H
Haojun Liao 已提交
3815
  STaskAttr* pQueryAttr = pRuntimeEnv->pQueryAttr;
3816 3817 3818 3819 3820 3821 3822 3823

  int32_t numOfExprs = pQueryAttr->numOfOutput;
  for(int32_t i = 0; i < numOfExprs; ++i) {
    SExprInfo* pExprInfo1 = &(pExprInfo[i]);
    if (pExprInfo1->base.functionId != FUNCTION_STDDEV_DST) {
      continue;
    }

H
Haojun Liao 已提交
3824
    SExprBasicInfo* pExpr = &pExprInfo1->base;
3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836

    pCtx[i].param[0].arr = NULL;
    pCtx[i].param[0].nType = TSDB_DATA_TYPE_INT;  // avoid freeing the memory by setting the type to be int

    // TODO use hash to speedup this loop
    int32_t numOfGroup = (int32_t)taosArrayGetSize(pRuntimeEnv->prevResult);
    for (int32_t j = 0; j < numOfGroup; ++j) {
      SInterResult* p = taosArrayGet(pRuntimeEnv->prevResult, j);
      if (pQueryAttr->tagLen == 0 || memcmp(p->tags, pRuntimeEnv->tagVal, pQueryAttr->tagLen) == 0) {
        int32_t numOfCols = (int32_t)taosArrayGetSize(p->pResult);
        for (int32_t k = 0; k < numOfCols; ++k) {
          SStddevInterResult* pres = taosArrayGet(p->pResult, k);
3837
          if (pres->info.colId == pExpr->colInfo.colId) {
3838 3839 3840 3841 3842 3843 3844 3845 3846 3847
            pCtx[i].param[0].arr = pres->pResult;
            break;
          }
        }
      }
    }
  }
#endif
}

H
Haojun Liao 已提交
3848
void setParamForStableStddevByColData(STaskRuntimeEnv* pRuntimeEnv, SqlFunctionCtx* pCtx, int32_t numOfOutput, SExprInfo* pExpr, char* val, int16_t bytes) {
H
Haojun Liao 已提交
3849
  STaskAttr* pQueryAttr = pRuntimeEnv->pQueryAttr;
3850 3851 3852
#if 0
  int32_t numOfExprs = pQueryAttr->numOfOutput;
  for(int32_t i = 0; i < numOfExprs; ++i) {
H
Haojun Liao 已提交
3853
    SExprBasicInfo* pExpr1 = &pExpr[i].base;
3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868
    if (pExpr1->functionId != FUNCTION_STDDEV_DST) {
      continue;
    }

    pCtx[i].param[0].arr = NULL;
    pCtx[i].param[0].nType = TSDB_DATA_TYPE_INT;  // avoid freeing the memory by setting the type to be int

    // TODO use hash to speedup this loop
    int32_t numOfGroup = (int32_t)taosArrayGetSize(pRuntimeEnv->prevResult);
    for (int32_t j = 0; j < numOfGroup; ++j) {
      SInterResult* p = taosArrayGet(pRuntimeEnv->prevResult, j);
      if (bytes == 0 || memcmp(p->tags, val, bytes) == 0) {
        int32_t numOfCols = (int32_t)taosArrayGetSize(p->pResult);
        for (int32_t k = 0; k < numOfCols; ++k) {
          SStddevInterResult* pres = taosArrayGet(p->pResult, k);
3869
          if (pres->info.colId == pExpr1->colInfo.colId) {
3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888
            pCtx[i].param[0].arr = pres->pResult;
            break;
          }
        }
      }
    }
  }
#endif
}

/*
 * There are two cases to handle:
 *
 * 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.
 * 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.
 */
H
Haojun Liao 已提交
3889 3890
void setIntervalQueryRange(STaskRuntimeEnv *pRuntimeEnv, TSKEY key) {
  STaskAttr           *pQueryAttr = pRuntimeEnv->pQueryAttr;
3891 3892 3893 3894 3895 3896 3897
  STableQueryInfo  *pTableQueryInfo = pRuntimeEnv->current;
  SResultRowInfo   *pResultRowInfo = &pTableQueryInfo->resInfo;

  if (pResultRowInfo->curPos != -1) {
    return;
  }

H
Haojun Liao 已提交
3898
//  pTableQueryInfo->win.skey = key;
3899 3900 3901 3902 3903 3904 3905 3906 3907 3908
  STimeWindow win = {.skey = key, .ekey = pQueryAttr->window.ekey};

  /**
   * 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.
   */
  STimeWindow w = TSWINDOW_INITIALIZER;

dengyihao's avatar
dengyihao 已提交
3909 3910
  TSKEY sk = TMIN(win.skey, win.ekey);
  TSKEY ek = TMAX(win.skey, win.ekey);
H
Haojun Liao 已提交
3911
//  getAlignQueryTimeWindow(pQueryAttr, win.skey, sk, ek, &w);
3912 3913 3914 3915 3916 3917 3918 3919 3920

//  if (pResultRowInfo->prevSKey == TSKEY_INITIAL_VAL) {
//    if (!QUERY_IS_ASC_QUERY(pQueryAttr)) {
//      assert(win.ekey == pQueryAttr->window.ekey);
//    }
//
//    pResultRowInfo->prevSKey = w.skey;
//  }

H
Haojun Liao 已提交
3921
//  pTableQueryInfo->lastKey = pTableQueryInfo->win.skey;
3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932
}

/**
 * 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
 */
3933
static int32_t doCopyToSDataBlock(SDiskbasedBuf *pBuf, SGroupResInfo* pGroupResInfo, int32_t orderType, SSDataBlock* pBlock, int32_t rowCapacity, int32_t* rowCellOffset) {
3934 3935 3936 3937 3938 3939
  int32_t numOfRows = getNumOfTotalRes(pGroupResInfo);
  int32_t numOfResult = pBlock->info.rows; // there are already exists result rows

  int32_t start = 0;
  int32_t step = -1;

3940
  //qDebug("QInfo:0x%"PRIx64" start to copy data from windowResInfo to output buf", GET_TASKID(pRuntimeEnv));
3941 3942 3943 3944 3945 3946 3947 3948 3949 3950
  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;
  }

3951 3952
  int32_t nrows = pBlock->info.rows;

3953
  for (int32_t i = start; (i < numOfRows) && (i >= 0); i += step) {
3954 3955 3956 3957
    SResultRowPosition* pPos = taosArrayGet(pGroupResInfo->pRows, i);
    SFilePage *page = getBufPage(pBuf, pPos->pageId);

    SResultRow* pRow = (SResultRow*)((char*)page + pPos->offset);
3958 3959 3960 3961 3962
    if (pRow->numOfRows == 0) {
      pGroupResInfo->index += 1;
      continue;
    }

3963
    // TODO copy multiple rows?
3964
    int32_t numOfRowsToCopy = pRow->numOfRows;
H
Haojun Liao 已提交
3965
    if (numOfResult + numOfRowsToCopy  >= rowCapacity) {
3966 3967 3968 3969 3970 3971 3972
      break;
    }

    pGroupResInfo->index += 1;

    for (int32_t j = 0; j < pBlock->info.numOfCols; ++j) {
      SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, j);
3973
      SResultRowEntryInfo* pEntryInfo = getResultCell(pRow, j, rowCellOffset);
3974

3975 3976
      char* in = GET_ROWCELL_INTERBUF(pEntryInfo);
      colDataAppend(pColInfoData, nrows, in, pEntryInfo->numOfRes == 0);
3977 3978
    }

3979 3980 3981
    releaseBufPage(pBuf, page);
    nrows += 1;

3982
    numOfResult += numOfRowsToCopy;
H
Haojun Liao 已提交
3983
    if (numOfResult == rowCapacity) {  // output buffer is full
3984 3985 3986 3987
      break;
    }
  }

3988
  //qDebug("QInfo:0x%"PRIx64" copy data to query buf completed", GET_TASKID(pRuntimeEnv));
3989 3990 3991 3992
  pBlock->info.rows = numOfResult;
  return 0;
}

3993
static void toSDatablock(SGroupResInfo *pGroupResInfo, SDiskbasedBuf* pBuf, SSDataBlock* pBlock, int32_t rowCapacity, int32_t* rowCellOffset) {
3994 3995
  assert(pGroupResInfo->currentGroup <= pGroupResInfo->totalGroup);

3996
  blockDataCleanup(pBlock);
3997 3998 3999 4000
  if (!hasRemainDataInCurrentGroup(pGroupResInfo)) {
    return;
  }

H
Haojun Liao 已提交
4001
  int32_t orderType = TSDB_ORDER_ASC;//(pQueryAttr->pGroupbyExpr != NULL) ? pQueryAttr->pGroupbyExpr->orderType : TSDB_ORDER_ASC;
4002
  doCopyToSDataBlock(pBuf, pGroupResInfo, orderType, pBlock, rowCapacity, rowCellOffset);
4003

H
Haojun Liao 已提交
4004 4005
  // add condition (pBlock->info.rows >= 1) just to runtime happy
  blockDataUpdateTsWindow(pBlock);
4006 4007
}

4008
static void updateNumOfRowsInResultRows(SqlFunctionCtx* pCtx, int32_t numOfOutput,
4009 4010
                                        SResultRowInfo* pResultRowInfo, int32_t* rowCellInfoOffset) {
  // update the number of result for each, only update the number of rows for the corresponding window result.
4011 4012 4013
//  if (QUERY_IS_INTERVAL_QUERY(pQueryAttr)) {
//    return;
//  }
4014 4015 4016 4017 4018 4019 4020 4021 4022 4023

  for (int32_t i = 0; i < pResultRowInfo->size; ++i) {
    SResultRow *pResult = pResultRowInfo->pResult[i];

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

4024 4025
      SResultRowEntryInfo* pCell = getResultCell(pResult, j, rowCellInfoOffset);
      pResult->numOfRows = (uint16_t)(TMAX(pResult->numOfRows, pCell->numOfRes));
4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055
    }
  }
}

static int32_t compressQueryColData(SColumnInfoData *pColRes, int32_t numOfRows, char *data, int8_t compressed) {
  int32_t colSize = pColRes->info.bytes * numOfRows;
  return (*(tDataTypes[pColRes->info.type].compFunc))(pColRes->pData, colSize, numOfRows, data,
                                                                 colSize + COMP_OVERFLOW_BYTES, compressed, NULL, 0);
}

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

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

  return pOutput->info.rows;
}

void publishOperatorProfEvent(SOperatorInfo* operatorInfo, EQueryProfEventType eventType) {
  SQueryProfEvent event = {0};

  event.eventType    = eventType;
  event.eventTime    = taosGetTimestampUs();
  event.operatorType = operatorInfo->operatorType;

  if (operatorInfo->pRuntimeEnv) {
H
Haojun Liao 已提交
4056 4057 4058 4059
//    SQInfo* pQInfo = operatorInfo->pRuntimeEnv->qinfo;
//    if (pQInfo->summary.queryProfEvents) {
//      taosArrayPush(pQInfo->summary.queryProfEvents, &event);
//    }
4060 4061 4062
  }
}

4063
void publishQueryAbortEvent(SExecTaskInfo * pTaskInfo, int32_t code) {
4064 4065 4066 4067 4068
  SQueryProfEvent event;
  event.eventType = QUERY_PROF_QUERY_ABORT;
  event.eventTime = taosGetTimestampUs();
  event.abortCode = code;

4069 4070
  if (pTaskInfo->cost.queryProfEvents) {
    taosArrayPush(pTaskInfo->cost.queryProfEvents, &event);
4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147
  }
}

typedef struct  {
  uint8_t operatorType;
  int64_t beginTime;
  int64_t endTime;
  int64_t selfTime;
  int64_t descendantsTime;
} SOperatorStackItem;

static void doOperatorExecProfOnce(SOperatorStackItem* item, SQueryProfEvent* event, SArray* opStack, SHashObj* profResults) {
  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;
  }

  uint8_t operatorType = item->operatorType;
  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;
    taosHashPut(profResults, &(operatorType), sizeof(operatorType),
                &opResult, sizeof(opResult));
  }
}

void calculateOperatorProfResults(SQInfo* pQInfo) {
  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;
  }

  SArray* opStack = taosArrayInit(32, sizeof(SOperatorStackItem));
  if (opStack == NULL) {
    return;
  }

  size_t size = taosArrayGetSize(pQInfo->summary.queryProfEvents);
  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);
      }
    }
  }

  taosArrayDestroy(opStack);
}

H
Haojun Liao 已提交
4148 4149
void queryCostStatis(SExecTaskInfo *pTaskInfo) {
  STaskCostInfo *pSummary = &pTaskInfo->cost;
4150

H
Haojun Liao 已提交
4151 4152 4153
//  uint64_t hashSize = taosHashGetMemSize(pQInfo->runtimeEnv.pResultRowHashTable);
//  hashSize += taosHashGetMemSize(pRuntimeEnv->tableqinfoGroupInfo.map);
//  pSummary->hashSize = hashSize;
4154 4155 4156 4157

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

H
Haojun Liao 已提交
4158 4159 4160 4161 4162 4163 4164 4165 4166 4167
//  SResultRowPool* p = pTaskInfo->pool;
//  if (p != NULL) {
//    pSummary->winInfoSize = getResultRowPoolMemSize(p);
//    pSummary->numOfTimeWindows = getNumOfAllocatedResultRows(p);
//  } else {
//    pSummary->winInfoSize = 0;
//    pSummary->numOfTimeWindows = 0;
//  }
//
//  calculateOperatorProfResults(pQInfo);
4168

H
Haojun Liao 已提交
4169
  qDebug("%s :cost summary: elapsed time:%"PRId64" us, first merge:%"PRId64" us, total blocks:%d, "
H
Haojun Liao 已提交
4170
         "load block statis:%d, load data block:%d, total rows:%"PRId64 ", check rows:%"PRId64,
H
Haojun Liao 已提交
4171
         GET_TASKID(pTaskInfo), pSummary->elapsedTime, pSummary->firstStageMergeTime, pSummary->totalBlocks, pSummary->loadBlockStatis,
H
Haojun Liao 已提交
4172 4173
         pSummary->loadBlocks, pSummary->totalRows, pSummary->totalCheckedRows);
//
4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186
  //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);

  if (pSummary->operatorProfResults) {
    SOperatorProfResult* opRes = taosHashIterate(pSummary->operatorProfResults, NULL);
    while (opRes != NULL) {
      //qDebug("QInfo:0x%" PRIx64 " :cost summary: operator : %d, exec times: %" PRId64 ", self time: %" PRId64,
//             pQInfo->qId, opRes->operatorType, opRes->sumRunTimes, opRes->sumSelfTime);
      opRes = taosHashIterate(pSummary->operatorProfResults, opRes);
    }
  }
}

H
Haojun Liao 已提交
4187 4188
//static void updateOffsetVal(STaskRuntimeEnv *pRuntimeEnv, SDataBlockInfo *pBlockInfo) {
//  STaskAttr *pQueryAttr = pRuntimeEnv->pQueryAttr;
4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206
//  STableQueryInfo* pTableQueryInfo = pRuntimeEnv->current;
//
//  int32_t step = GET_FORWARD_DIRECTION_FACTOR(pQueryAttr->order.order);
//
//  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;
//  }
//
//  if (QUERY_IS_ASC_QUERY(pQueryAttr)) {
//    pQueryAttr->pos = (int32_t)pQueryAttr->limit.offset;
//  } else {
//    pQueryAttr->pos = pBlockInfo->rows - (int32_t)pQueryAttr->limit.offset - 1;
//  }
//
//  assert(pQueryAttr->pos >= 0 && pQueryAttr->pos <= pBlockInfo->rows - 1);
//
4207
//  SArray *         pDataBlock = tsdbRetrieveDataBlock(pRuntimeEnv->pTsdbReadHandle, NULL);
4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218
//  SColumnInfoData *pColInfoData = taosArrayGet(pDataBlock, 0);
//
//  // update the pQueryAttr->limit.offset value, and pQueryAttr->pos value
//  TSKEY *keys = (TSKEY *) pColInfoData->pData;
//
//  // update the offset value
//  pTableQueryInfo->lastKey = keys[pQueryAttr->pos];
//  pQueryAttr->limit.offset = 0;
//
//  int32_t numOfRes = tableApplyFunctionsOnBlock(pRuntimeEnv, pBlockInfo, NULL, binarySearchForKey, pDataBlock);
//
4219
//  //qDebug("QInfo:0x%"PRIx64" check data block, brange:%" PRId64 "-%" PRId64 ", numBlocksOfStep:%d, numOfRes:%d, lastKey:%"PRId64, GET_TASKID(pRuntimeEnv),
4220 4221 4222
//         pBlockInfo->window.skey, pBlockInfo->window.ekey, pBlockInfo->rows, numOfRes, pQuery->current->lastKey);
//}

H
Haojun Liao 已提交
4223 4224
//void skipBlocks(STaskRuntimeEnv *pRuntimeEnv) {
//  STaskAttr *pQueryAttr = pRuntimeEnv->pQueryAttr;
4225 4226 4227 4228 4229 4230 4231 4232 4233
//
//  if (pQueryAttr->limit.offset <= 0 || pQueryAttr->numOfFilterCols > 0) {
//    return;
//  }
//
//  pQueryAttr->pos = 0;
//  int32_t step = GET_FORWARD_DIRECTION_FACTOR(pQueryAttr->order.order);
//
//  STableQueryInfo* pTableQueryInfo = pRuntimeEnv->current;
4234
//  TsdbQueryHandleT pTsdbReadHandle = pRuntimeEnv->pTsdbReadHandle;
4235 4236
//
//  SDataBlockInfo blockInfo = SDATA_BLOCK_INITIALIZER;
4237 4238
//  while (tsdbNextDataBlock(pTsdbReadHandle)) {
//    if (isTaskKilled(pRuntimeEnv->qinfo)) {
4239 4240 4241
//      longjmp(pRuntimeEnv->env, TSDB_CODE_TSC_QUERY_CANCELLED);
//    }
//
4242
//    tsdbRetrieveDataBlockInfo(pTsdbReadHandle, &blockInfo);
4243 4244 4245 4246 4247 4248
//
//    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;
//
4249
//      //qDebug("QInfo:0x%"PRIx64" skip rows:%d, offset:%" PRId64, GET_TASKID(pRuntimeEnv), blockInfo.rows,
4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261
//             pQuery->limit.offset);
//    } else {  // find the appropriated start position in current block
//      updateOffsetVal(pRuntimeEnv, &blockInfo);
//      break;
//    }
//  }
//
//  if (terrno != TSDB_CODE_SUCCESS) {
//    longjmp(pRuntimeEnv->env, terrno);
//  }
//}

H
Haojun Liao 已提交
4262 4263
//static TSKEY doSkipIntervalProcess(STaskRuntimeEnv* pRuntimeEnv, STimeWindow* win, SDataBlockInfo* pBlockInfo, STableQueryInfo* pTableQueryInfo) {
//  STaskAttr *pQueryAttr = pRuntimeEnv->pQueryAttr;
4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274
//  SResultRowInfo *pWindowResInfo = &pRuntimeEnv->resultRowInfo;
//
//  assert(pQueryAttr->limit.offset == 0);
//  STimeWindow tw = *win;
//  getNextTimeWindow(pQueryAttr, &tw);
//
//  if ((tw.skey <= pBlockInfo->window.ekey && QUERY_IS_ASC_QUERY(pQueryAttr)) ||
//      (tw.ekey >= pBlockInfo->window.skey && !QUERY_IS_ASC_QUERY(pQueryAttr))) {
//
//    // load the data block and check data remaining in current data block
//    // TODO optimize performance
4275
//    SArray *         pDataBlock = tsdbRetrieveDataBlock(pRuntimeEnv->pTsdbReadHandle, NULL);
4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297
//    SColumnInfoData *pColInfoData = taosArrayGet(pDataBlock, 0);
//
//    tw = *win;
//    int32_t startPos =
//        getNextQualifiedWindow(pQueryAttr, &tw, pBlockInfo, pColInfoData->pData, binarySearchForKey, -1);
//    assert(startPos >= 0);
//
//    // set the abort info
//    pQueryAttr->pos = startPos;
//
//    // reset the query start timestamp
//    pTableQueryInfo->win.skey = ((TSKEY *)pColInfoData->pData)[startPos];
//    pQueryAttr->window.skey = pTableQueryInfo->win.skey;
//    TSKEY key = pTableQueryInfo->win.skey;
//
//    pWindowResInfo->prevSKey = tw.skey;
//    int32_t index = pRuntimeEnv->resultRowInfo.curIndex;
//
//    int32_t numOfRes = tableApplyFunctionsOnBlock(pRuntimeEnv, pBlockInfo, NULL, binarySearchForKey, pDataBlock);
//    pRuntimeEnv->resultRowInfo.curIndex = index;  // restore the window index
//
//    //qDebug("QInfo:0x%"PRIx64" check data block, brange:%" PRId64 "-%" PRId64 ", numOfRows:%d, numOfRes:%d, lastKey:%" PRId64,
4298
//           GET_TASKID(pRuntimeEnv), pBlockInfo->window.skey, pBlockInfo->window.ekey, pBlockInfo->rows, numOfRes,
4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312
//           pQueryAttr->current->lastKey);
//
//    return key;
//  } else {  // do nothing
//    pQueryAttr->window.skey      = tw.skey;
//    pWindowResInfo->prevSKey = tw.skey;
//    pTableQueryInfo->lastKey = tw.skey;
//
//    return tw.skey;
//  }
//
//  return true;
//}

H
Haojun Liao 已提交
4313 4314
//static bool skipTimeInterval(STaskRuntimeEnv *pRuntimeEnv, TSKEY* start) {
//  STaskAttr *pQueryAttr = pRuntimeEnv->pQueryAttr;
4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339
//  if (QUERY_IS_ASC_QUERY(pQueryAttr)) {
//    assert(*start <= pRuntimeEnv->current->lastKey);
//  } else {
//    assert(*start >= pRuntimeEnv->current->lastKey);
//  }
//
//  // 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;
//  }
//
//  /*
//   * 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);
//
//  STimeWindow w = TSWINDOW_INITIALIZER;
//  bool ascQuery = QUERY_IS_ASC_QUERY(pQueryAttr);
//
//  SResultRowInfo *pWindowResInfo = &pRuntimeEnv->resultRowInfo;
//  STableQueryInfo *pTableQueryInfo = pRuntimeEnv->current;
//
//  SDataBlockInfo blockInfo = SDATA_BLOCK_INITIALIZER;
4340 4341
//  while (tsdbNextDataBlock(pRuntimeEnv->pTsdbReadHandle)) {
//    tsdbRetrieveDataBlockInfo(pRuntimeEnv->pTsdbReadHandle, &blockInfo);
4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386
//
//    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;
//    }
//
//    // the first time window
//    STimeWindow win = getActiveTimeWindow(pWindowResInfo, pWindowResInfo->prevSKey, pQueryAttr);
//
//    while (pQueryAttr->limit.offset > 0) {
//      STimeWindow tw = win;
//
//      if ((win.ekey <= blockInfo.window.ekey && ascQuery) || (win.ekey >= blockInfo.window.skey && !ascQuery)) {
//        pQueryAttr->limit.offset -= 1;
//        pWindowResInfo->prevSKey = win.skey;
//
//        // 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;
//        }
//      }
//
//      if (pQueryAttr->limit.offset == 0) {
//        *start = doSkipIntervalProcess(pRuntimeEnv, &win, &blockInfo, pTableQueryInfo);
//        return true;
//      }
//
//      // current window does not ended in current data block, try next data block
//      getNextTimeWindow(pQueryAttr, &tw);
//
//      /*
//       * 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)) {
//
4387
//        SArray *pDataBlock = tsdbRetrieveDataBlock(pRuntimeEnv->pTsdbReadHandle, NULL);
4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422
//        SColumnInfoData *pColInfoData = taosArrayGet(pDataBlock, 0);
//
//        if ((win.ekey > blockInfo.window.ekey && ascQuery) || (win.ekey < blockInfo.window.skey && !ascQuery)) {
//          pQueryAttr->limit.offset -= 1;
//        }
//
//        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);
//
//          // 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.
//      }
//    }
//  }
//
//  // check for error
//  if (terrno != TSDB_CODE_SUCCESS) {
//    longjmp(pRuntimeEnv->env, terrno);
//  }
//
//  return true;
//}

4423
int32_t appendDownstream(SOperatorInfo* p, SOperatorInfo** pDownstream, int32_t num) {
H
Haojun Liao 已提交
4424
  if (p->pDownstream == NULL) {
H
Haojun Liao 已提交
4425
    assert(p->numOfDownstream == 0);
4426 4427
  }

4428 4429 4430 4431 4432 4433 4434 4435
  p->pDownstream = calloc(1, num * POINTER_BYTES);
  if (p->pDownstream == NULL) {
    return TSDB_CODE_OUT_OF_MEMORY;
  }

  memcpy(p->pDownstream, pDownstream, num * POINTER_BYTES);
  p->numOfDownstream = num;
  return TSDB_CODE_SUCCESS;
4436 4437 4438 4439
}

static void doDestroyTableQueryInfo(STableGroupInfo* pTableqinfoGroupInfo);

H
Haojun Liao 已提交
4440 4441
static int32_t setupQueryHandle(void* tsdb, STaskRuntimeEnv* pRuntimeEnv, int64_t qId, bool isSTableQuery) {
  STaskAttr *pQueryAttr = pRuntimeEnv->pQueryAttr;
4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466
#if 0
  // TODO set the tags scan handle
  if (onlyQueryTags(pQueryAttr)) {
    return TSDB_CODE_SUCCESS;
  }

  STsdbQueryCond cond = createTsdbQueryCond(pQueryAttr, &pQueryAttr->window);
  if (pQueryAttr->tsCompQuery || pQueryAttr->pointInterpQuery) {
    cond.type = BLOCK_LOAD_TABLE_SEQ_ORDER;
  }

  if (!isSTableQuery
    && (pRuntimeEnv->tableqinfoGroupInfo.numOfTables == 1)
    && (cond.order == TSDB_ORDER_ASC)
    && (!QUERY_IS_INTERVAL_QUERY(pQueryAttr))
    && (!pQueryAttr->groupbyColumn)
    && (!pQueryAttr->simpleAgg)
  ) {
    SArray* pa = GET_TABLEGROUP(pRuntimeEnv, 0);
    STableQueryInfo* pCheckInfo = taosArrayGetP(pa, 0);
    cond.twindow = pCheckInfo->win;
  }

  terrno = TSDB_CODE_SUCCESS;
  if (isFirstLastRowQuery(pQueryAttr)) {
4467
    pRuntimeEnv->pTsdbReadHandle = tsdbQueryLastRow(tsdb, &cond, &pQueryAttr->tableGroupInfo, qId, &pQueryAttr->memRef);
4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487

    // update the query time window
    pQueryAttr->window = cond.twindow;
    if (pQueryAttr->tableGroupInfo.numOfTables == 0) {
      pRuntimeEnv->tableqinfoGroupInfo.numOfTables = 0;
    } else {
      size_t numOfGroups = GET_NUM_OF_TABLEGROUP(pRuntimeEnv);
      for(int32_t i = 0; i < numOfGroups; ++i) {
        SArray *group = GET_TABLEGROUP(pRuntimeEnv, i);

        size_t t = taosArrayGetSize(group);
        for (int32_t j = 0; j < t; ++j) {
          STableQueryInfo *pCheckInfo = taosArrayGetP(group, j);

          pCheckInfo->win = pQueryAttr->window;
          pCheckInfo->lastKey = pCheckInfo->win.skey;
        }
      }
    }
  } else if (isCachedLastQuery(pQueryAttr)) {
4488
    pRuntimeEnv->pTsdbReadHandle = tsdbQueryCacheLast(tsdb, &cond, &pQueryAttr->tableGroupInfo, qId, &pQueryAttr->memRef);
4489
  } else if (pQueryAttr->pointInterpQuery) {
4490
    pRuntimeEnv->pTsdbReadHandle = tsdbQueryRowsInExternalWindow(tsdb, &cond, &pQueryAttr->tableGroupInfo, qId, &pQueryAttr->memRef);
4491
  } else {
4492
    pRuntimeEnv->pTsdbReadHandle = tsdbQueryTables(tsdb, &cond, &pQueryAttr->tableGroupInfo, qId, &pQueryAttr->memRef);
4493 4494 4495 4496 4497 4498 4499
  }
#endif
  return terrno;
}

int32_t doInitQInfo(SQInfo* pQInfo, STSBuf* pTsBuf, void* tsdb, void* sourceOptr, int32_t tbScanner, SArray* pOperator,
    void* param) {
H
Haojun Liao 已提交
4500
  STaskRuntimeEnv *pRuntimeEnv = &pQInfo->runtimeEnv;
4501

H
Haojun Liao 已提交
4502
  STaskAttr *pQueryAttr = pQInfo->runtimeEnv.pQueryAttr;
4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531
  pQueryAttr->tsdb = tsdb;

  if (tsdb != NULL) {
    int32_t code = setupQueryHandle(tsdb, pRuntimeEnv, pQInfo->qId, pQueryAttr->stableQuery);
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }
  }

  pQueryAttr->interBufSize = getOutputInterResultBufSize(pQueryAttr);

  pRuntimeEnv->groupResInfo.totalGroup = (int32_t) (pQueryAttr->stableQuery? GET_NUM_OF_TABLEGROUP(pRuntimeEnv):0);
  pRuntimeEnv->enableGroupData = false;

  pRuntimeEnv->pQueryAttr = pQueryAttr;
  pRuntimeEnv->pTsBuf = pTsBuf;
  pRuntimeEnv->cur.vgroupIndex = -1;
  setResultBufSize(pQueryAttr, &pRuntimeEnv->resultInfo);

  if (sourceOptr != NULL) {
    assert(pRuntimeEnv->proot == NULL);
    pRuntimeEnv->proot = sourceOptr;
  }

  if (pTsBuf != NULL) {
    int16_t order = (pQueryAttr->order.order == pRuntimeEnv->pTsBuf->tsOrder) ? TSDB_ORDER_ASC : TSDB_ORDER_DESC;
    tsBufSetTraverseOrder(pRuntimeEnv->pTsBuf, order);
  }

H
Haojun Liao 已提交
4532
  int32_t ps = 4096;
4533 4534 4535
  getIntermediateBufInfo(pRuntimeEnv, &ps, &pQueryAttr->intermediateResultRowSize);

  int32_t TENMB = 1024*1024*10;
H
Haojun Liao 已提交
4536
  int32_t code = createDiskbasedBuf(&pRuntimeEnv->pResultBuf, ps, TENMB, "", "/tmp");
4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

  // create runtime environment
  int32_t numOfTables = (int32_t)pQueryAttr->tableGroupInfo.numOfTables;
  pQInfo->summary.tableInfoSize += (numOfTables * sizeof(STableQueryInfo));
  pQInfo->summary.queryProfEvents = taosArrayInit(512, sizeof(SQueryProfEvent));
  if (pQInfo->summary.queryProfEvents == NULL) {
    //qDebug("QInfo:0x%"PRIx64" failed to allocate query prof events array", pQInfo->qId);
  }

  pQInfo->summary.operatorProfResults =
      taosHashInit(8, taosGetDefaultHashFunction(TSDB_DATA_TYPE_TINYINT), true, HASH_NO_LOCK);

  if (pQInfo->summary.operatorProfResults == NULL) {
    //qDebug("QInfo:0x%"PRIx64" failed to allocate operator prof results hash", pQInfo->qId);
  }

  code = setupQueryRuntimeEnv(pRuntimeEnv, (int32_t) pQueryAttr->tableGroupInfo.numOfTables, pOperator, param);
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

H
Haojun Liao 已提交
4561
//  setTaskStatus(pOperator->pTaskInfo, QUERY_NOT_COMPLETED);
4562 4563 4564
  return TSDB_CODE_SUCCESS;
}

4565
static void doTableQueryInfoTimeWindowCheck(SExecTaskInfo* pTaskInfo, STableQueryInfo* pTableQueryInfo, int32_t order) {
H
Haojun Liao 已提交
4566 4567
#if 0
    if (order == TSDB_ORDER_ASC) {
4568 4569
    assert(
        (pTableQueryInfo->win.skey <= pTableQueryInfo->win.ekey) &&
H
Haojun Liao 已提交
4570 4571
        (pTableQueryInfo->lastKey >= pTaskInfo->window.skey) &&
        (pTableQueryInfo->win.skey >= pTaskInfo->window.skey && pTableQueryInfo->win.ekey <= pTaskInfo->window.ekey));
4572 4573 4574
  } else {
    assert(
        (pTableQueryInfo->win.skey >= pTableQueryInfo->win.ekey) &&
H
Haojun Liao 已提交
4575 4576
        (pTableQueryInfo->lastKey <= pTaskInfo->window.skey) &&
        (pTableQueryInfo->win.skey <= pTaskInfo->window.skey && pTableQueryInfo->win.ekey >= pTaskInfo->window.ekey));
4577
  }
H
Haojun Liao 已提交
4578 4579
#endif

4580 4581
}

H
Haojun Liao 已提交
4582
//STsdbQueryCond createTsdbQueryCond(STaskAttr* pQueryAttr, STimeWindow* win) {
4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623
//  STsdbQueryCond cond = {
//      .colList   = pQueryAttr->tableCols,
//      .order     = pQueryAttr->order.order,
//      .numOfCols = pQueryAttr->numOfCols,
//      .type      = BLOCK_LOAD_OFFSET_SEQ_ORDER,
//      .loadExternalRows = false,
//  };
//
//  TIME_WINDOW_COPY(cond.twindow, *win);
//  return cond;
//}

static STableIdInfo createTableIdInfo(STableQueryInfo* pTableQueryInfo) {
  STableIdInfo tidInfo;
//  STableId* id = TSDB_TABLEID(pTableQueryInfo->pTable);
//
//  tidInfo.uid = id->uid;
//  tidInfo.tid = id->tid;
//  tidInfo.key = pTableQueryInfo->lastKey;

  return tidInfo;
}

//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;
//
//  if (pTableQueryInfo->pTable == NULL) {
//    return;
//  }
//
//  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));
//  }
//}

H
Haojun Liao 已提交
4624
static void doCloseAllTimeWindow(STaskRuntimeEnv* pRuntimeEnv) {
4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636
  size_t numOfGroup = GET_NUM_OF_TABLEGROUP(pRuntimeEnv);
  for (int32_t i = 0; i < numOfGroup; ++i) {
    SArray* group = GET_TABLEGROUP(pRuntimeEnv, i);

    size_t num = taosArrayGetSize(group);
    for (int32_t j = 0; j < num; ++j) {
      STableQueryInfo* item = taosArrayGetP(group, j);
      closeAllResultRows(&item->resInfo);
    }
  }
}

H
Haojun Liao 已提交
4637
static SSDataBlock* doTableScanImpl(SOperatorInfo *pOperator, bool* newgroup) {
4638
  STableScanInfo   *pTableScanInfo = pOperator->info;
4639
  SExecTaskInfo    *pTaskInfo = pOperator->pTaskInfo;
H
Haojun Liao 已提交
4640

4641
  SSDataBlock      *pBlock = &pTableScanInfo->block;
H
Haojun Liao 已提交
4642
  STableGroupInfo  *pTableGroupInfo = &pOperator->pTaskInfo->tableqinfoGroupInfo;
4643 4644

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

4646 4647 4648
  while (tsdbNextDataBlock(pTableScanInfo->pTsdbReadHandle)) {
    if (isTaskKilled(pOperator->pTaskInfo)) {
      longjmp(pOperator->pTaskInfo->env, TSDB_CODE_TSC_QUERY_CANCELLED);
4649 4650 4651
    }

    pTableScanInfo->numOfBlocks += 1;
4652
    tsdbRetrieveDataBlockInfo(pTableScanInfo->pTsdbReadHandle, &pBlock->info);
4653 4654

    // todo opt
H
Haojun Liao 已提交
4655 4656 4657 4658 4659 4660 4661 4662 4663 4664
//    if (pTableGroupInfo->numOfTables > 1 || (pRuntimeEnv->current == NULL && pTableGroupInfo->numOfTables == 1)) {
//      STableQueryInfo** pTableQueryInfo =
//          (STableQueryInfo**)taosHashGet(pTableGroupInfo->map, &pBlock->info.uid, sizeof(pBlock->info.uid));
//      if (pTableQueryInfo == NULL) {
//        break;
//      }
//
//      pRuntimeEnv->current = *pTableQueryInfo;
//      doTableQueryInfoTimeWindowCheck(pTaskInfo, *pTableQueryInfo, pTableScanInfo->order);
//    }
4665 4666

    // this function never returns error?
H
Haojun Liao 已提交
4667
    uint32_t status = BLK_DATA_ALL_NEEDED;
H
Haojun Liao 已提交
4668 4669
    int32_t code = loadDataBlock(pTaskInfo, pTableScanInfo, pBlock, &status);
//    int32_t  code = loadDataBlockOnDemand(pOperator->pRuntimeEnv, pTableScanInfo, pBlock, &status);
4670
    if (code != TSDB_CODE_SUCCESS) {
4671
      longjmp(pOperator->pTaskInfo->env, code);
4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684
    }

    // current block is ignored according to filter result by block statistics data, continue load the next block
    if (status == BLK_DATA_DISCARD || pBlock->info.rows == 0) {
      continue;
    }

    return pBlock;
  }

  return NULL;
}

H
Haojun Liao 已提交
4685
static SSDataBlock* doTableScan(SOperatorInfo *pOperator, bool *newgroup) {
H
Haojun Liao 已提交
4686
  STableScanInfo *pTableScanInfo = pOperator->info;
4687
  SExecTaskInfo  *pTaskInfo = pOperator->pTaskInfo;
4688

H
Haojun Liao 已提交
4689
  // The read handle is not initialized yet, since no qualified tables exists
H
Haojun Liao 已提交
4690 4691 4692 4693
  if (pTableScanInfo->pTsdbReadHandle == NULL) {
    return NULL;
  }

4694 4695 4696 4697 4698 4699 4700 4701 4702 4703
  SResultRowInfo* pResultRowInfo = pTableScanInfo->pResultRowInfo;
  *newgroup = false;

  while (pTableScanInfo->current < pTableScanInfo->times) {
    SSDataBlock* p = doTableScanImpl(pOperator, newgroup);
    if (p != NULL) {
      return p;
    }

    if (++pTableScanInfo->current >= pTableScanInfo->times) {
4704
      if (pTableScanInfo->reverseTimes <= 0/* || isTsdbCacheLastRow(pTableScanInfo->pTsdbReadHandle)*/) {
4705 4706 4707 4708 4709 4710 4711 4712
        return NULL;
      } else {
        break;
      }
    }

    // do prepare for the next round table scan operation
//    STsdbQueryCond cond = createTsdbQueryCond(pQueryAttr, &pQueryAttr->window);
4713
//    tsdbResetQueryHandle(pTableScanInfo->pTsdbReadHandle, &cond);
4714

4715
    setTaskStatus(pTaskInfo, TASK_NOT_COMPLETED);
H
Haojun Liao 已提交
4716
    pTableScanInfo->scanFlag = REPEAT_SCAN;
4717

H
Haojun Liao 已提交
4718 4719 4720 4721 4722
//    if (pTaskInfo->pTsBuf) {
//      bool ret = tsBufNextPos(pRuntimeEnv->pTsBuf);
//      assert(ret);
//    }
//
4723 4724 4725 4726
    if (pResultRowInfo->size > 0) {
      pResultRowInfo->curPos = 0;
    }

H
Haojun Liao 已提交
4727
    qDebug("%s start to repeat scan data blocks due to query func required, qrange:%" PRId64 "-%" PRId64,
4728
           GET_TASKID(pTaskInfo), pTaskInfo->window.skey, pTaskInfo->window.ekey);
4729 4730 4731
  }

  SSDataBlock *p = NULL;
H
Haojun Liao 已提交
4732
  // todo refactor
4733
  if (pTableScanInfo->reverseTimes > 0) {
H
Haojun Liao 已提交
4734
    setupEnvForReverseScan(pTableScanInfo, pTableScanInfo->pCtx, pTableScanInfo->numOfOutput);
4735
//    STsdbQueryCond cond = createTsdbQueryCond(pQueryAttr, &pQueryAttr->window);
4736
//    tsdbResetQueryHandle(pTableScanInfo->pTsdbReadHandle, &cond);
4737

H
Haojun Liao 已提交
4738
    qDebug("%s start to reverse scan data blocks due to query func required, qrange:%" PRId64 "-%" PRId64,
4739
           GET_TASKID(pTaskInfo), pTaskInfo->window.skey, pTaskInfo->window.ekey);
4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750

    if (pResultRowInfo->size > 0) {
      pResultRowInfo->curPos = pResultRowInfo->size - 1;
    }

    p = doTableScanImpl(pOperator, newgroup);
  }

  return p;
}

H
Haojun Liao 已提交
4751
static SSDataBlock* doBlockInfoScan(SOperatorInfo *pOperator, bool* newgroup) {
4752 4753 4754 4755 4756 4757 4758 4759 4760 4761
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

  STableScanInfo *pTableScanInfo = pOperator->info;
  *newgroup = false;
#if 0
  STableBlockDist tableBlockDist = {0};
  tableBlockDist.numOfTables     = (int32_t)pOperator->pRuntimeEnv->tableqinfoGroupInfo.numOfTables;

S
Shengliang Guan 已提交
4762 4763
  int32_t numRowSteps = TSDB_DEFAULT_MAX_ROW_FBLOCK / TSDB_BLOCK_DIST_STEP_ROWS;
  if (TSDB_DEFAULT_MAX_ROW_FBLOCK % TSDB_BLOCK_DIST_STEP_ROWS != 0) {
4764 4765 4766 4767 4768 4769 4770
    ++numRowSteps;
  }
  tableBlockDist.dataBlockInfos  = taosArrayInit(numRowSteps, sizeof(SFileBlockInfo));
  taosArraySetSize(tableBlockDist.dataBlockInfos, numRowSteps);
  tableBlockDist.maxRows = INT_MIN;
  tableBlockDist.minRows = INT_MAX;

4771 4772
  tsdbGetFileBlocksDistInfo(pTableScanInfo->pTsdbReadHandle, &tableBlockDist);
  tableBlockDist.numOfRowsInMemTable = (int32_t) tsdbGetNumOfRowsInMemTable(pTableScanInfo->pTsdbReadHandle);
4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795

  SSDataBlock* pBlock = &pTableScanInfo->block;
  pBlock->info.rows   = 1;
  pBlock->info.numOfCols = 1;

  SBufferWriter bw = tbufInitWriter(NULL, false);
  blockDistInfoToBinary(&tableBlockDist, &bw);
  SColumnInfoData* pColInfo = taosArrayGet(pBlock->pDataBlock, 0);

  int32_t len = (int32_t) tbufTell(&bw);
  pColInfo->pData = malloc(len + sizeof(int32_t));

  *(int32_t*) pColInfo->pData = len;
  memcpy(pColInfo->pData + sizeof(int32_t), tbufGetData(&bw, false), len);

  tbufCloseWriter(&bw);

  SArray* g = GET_TABLEGROUP(pOperator->pRuntimeEnv, 0);
  pOperator->pRuntimeEnv->current = taosArrayGetP(g, 0);

  pOperator->status = OP_EXEC_DONE;
  return pBlock;
#endif
4796 4797
}

H
Haojun Liao 已提交
4798
static SSDataBlock* doStreamBlockScan(SOperatorInfo *pOperator, bool* newgroup) {
4799
  // NOTE: this operator does never check if current status is done or not
4800 4801 4802
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
  SStreamBlockScanInfo* pInfo = pOperator->info;

L
Liu Jicong 已提交
4803

4804 4805 4806 4807 4808
  pTaskInfo->code = pOperator->_openFn(pOperator);
  if (pTaskInfo->code != TSDB_CODE_SUCCESS) {
    return NULL;
  }

H
Haojun Liao 已提交
4809
  if (pInfo->blockType == STREAM_DATA_TYPE_SSDATA_BLOCK) {
4810 4811 4812 4813 4814 4815 4816 4817
    if (pInfo->blockValid) {
      pInfo->blockValid = false;  // this block can only be used once.
      return pInfo->pRes;
    } else {
      return NULL;
    }
  }

4818
  SDataBlockInfo* pBlockInfo = &pInfo->pRes->info;
H
Haojun Liao 已提交
4819
  blockDataCleanup(pInfo->pRes);
H
Haojun Liao 已提交
4820

4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848
  while (tqNextDataBlock(pInfo->readerHandle)) {
    pTaskInfo->code = tqRetrieveDataBlockInfo(pInfo->readerHandle, pBlockInfo);
    if (pTaskInfo->code != TSDB_CODE_SUCCESS) {
      terrno = pTaskInfo->code;
      return NULL;
    }

    if (pBlockInfo->rows == 0) {
      return NULL;
    }

    pInfo->pRes->pDataBlock = tqRetrieveDataBlock(pInfo->readerHandle);
    if (pInfo->pRes->pDataBlock == NULL) {
      // TODO add log
      pTaskInfo->code = terrno;
      return NULL;
    }

    break;
  }

  // record the scan action.
  pInfo->numOfExec++;
  pInfo->numOfRows += pBlockInfo->rows;

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

4849
int32_t loadRemoteDataCallback(void* param, const SDataBuf* pMsg, int32_t code) {
4850 4851
  SSourceDataInfo* pSourceDataInfo = (SSourceDataInfo*) param;
  pSourceDataInfo->pRsp = pMsg->pData;
4852

4853 4854 4855 4856
  SRetrieveTableRsp* pRsp = pSourceDataInfo->pRsp;
  pRsp->numOfRows = htonl(pRsp->numOfRows);
  pRsp->useconds  = htobe64(pRsp->useconds);
  pRsp->compLen   = htonl(pRsp->compLen);
H
Haojun Liao 已提交
4857

H
Haojun Liao 已提交
4858
  pSourceDataInfo->status = EX_SOURCE_DATA_READY;
4859
  tsem_post(&pSourceDataInfo->pEx->ready);
H
Haojun Liao 已提交
4860 4861 4862 4863 4864 4865 4866 4867
}

static void destroySendMsgInfo(SMsgSendInfo* pMsgBody) {
  assert(pMsgBody != NULL);
  tfree(pMsgBody->msgInfo.pData);
  tfree(pMsgBody);
}

S
Shengliang Guan 已提交
4868
void qProcessFetchRsp(void* parent, SRpcMsg* pMsg, SEpSet* pEpSet) {
H
Haojun Liao 已提交
4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886
  SMsgSendInfo *pSendInfo = (SMsgSendInfo *) pMsg->ahandle;
  assert(pMsg->ahandle != NULL);

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

  if (pMsg->contLen > 0) {
    buf.pData = calloc(1, pMsg->contLen);
    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);
4887 4888
}

4889 4890
static int32_t doSendFetchDataRequest(SExchangeInfo *pExchangeInfo, SExecTaskInfo *pTaskInfo, int32_t sourceIndex) {
  size_t totalSources = taosArrayGetSize(pExchangeInfo->pSources);
4891

4892 4893 4894 4895 4896
  SResFetchReq* pMsg = calloc(1, sizeof(SResFetchReq));
  if (NULL == pMsg) {
    pTaskInfo->code = TSDB_CODE_QRY_OUT_OF_MEMORY;
    return pTaskInfo->code;
  }
4897

X
Xiaoyu Wang 已提交
4898
  SDownstreamSourceNode *pSource = taosArrayGet(pExchangeInfo->pSources, sourceIndex);
4899
  SSourceDataInfo   *pDataInfo = taosArrayGet(pExchangeInfo->pSourceDataInfo, sourceIndex);
4900

4901
  qDebug("%s build fetch msg and send to vgId:%d, ep:%s, taskId:0x%" PRIx64 ", %d/%" PRIzu,
L
Liu Jicong 已提交
4902
         GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->addr.epSet.eps[0].fqdn, pSource->taskId, sourceIndex, totalSources);
4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915

  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
  SMsgSendInfo* pMsgSendInfo = calloc(1, sizeof(SMsgSendInfo));
  if (NULL == pMsgSendInfo) {
    tfree(pMsg);
    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 已提交
4916 4917
  }

4918 4919 4920 4921 4922
  pMsgSendInfo->param = pDataInfo;
  pMsgSendInfo->msgInfo.pData = pMsg;
  pMsgSendInfo->msgInfo.len = sizeof(SResFetchReq);
  pMsgSendInfo->msgType = TDMT_VND_FETCH;
  pMsgSendInfo->fp = loadRemoteDataCallback;
4923

4924
  int64_t transporterId = 0;
L
Liu Jicong 已提交
4925
  int32_t code = asyncSendMsgToServer(pExchangeInfo->pTransporter, &pSource->addr.epSet, &transporterId, pMsgSendInfo);
4926 4927 4928
  return TSDB_CODE_SUCCESS;
}

4929
// TODO if only one or two columnss required, how to extract data?
H
Haojun Liao 已提交
4930
static int32_t setSDataBlockFromFetchRsp(SSDataBlock* pRes, SLoadRemoteDataInfo* pLoadInfo, int32_t numOfRows, char* pData, int32_t compLen,
4931
    int32_t numOfOutput, int64_t startTs, uint64_t* total, SArray* pColList) {
H
Haojun Liao 已提交
4932
  blockDataEnsureCapacity(pRes, numOfRows);
4933

H
Haojun Liao 已提交
4934 4935 4936 4937
  if (pColList == NULL) {  // data from other sources
    int32_t* colLen = (int32_t*)pData;
    char* pStart = pData + sizeof(int32_t) * numOfOutput;

4938
    for (int32_t i = 0; i < numOfOutput; ++i) {
H
Haojun Liao 已提交
4939 4940 4941
      colLen[i] = htonl(colLen[i]);
      ASSERT(colLen[i] > 0);

4942
      SColumnInfoData* pColInfoData = taosArrayGet(pRes->pDataBlock, i);
H
Haojun Liao 已提交
4943 4944 4945
      if (IS_VAR_DATA_TYPE(pColInfoData->info.type)) {
        pColInfoData->varmeta.length = colLen[i];
        pColInfoData->varmeta.allocLen = colLen[i];
4946

H
Haojun Liao 已提交
4947 4948 4949 4950 4951 4952 4953
        memcpy(pColInfoData->varmeta.offset, pStart, sizeof(int32_t)*numOfRows);
        pStart += sizeof(int32_t)*numOfRows;

        pColInfoData->pData = malloc(colLen[i]);
      } else {
        memcpy(pColInfoData->nullbitmap, pStart, BitmapLen(numOfRows));
        pStart += BitmapLen(numOfRows);
4954
      }
H
Haojun Liao 已提交
4955 4956 4957

      memcpy(pColInfoData->pData, pStart, colLen[i]);
      pStart += colLen[i];
4958
    }
H
Haojun Liao 已提交
4959
  } else {  // extract data according to pColList
4960
    ASSERT(numOfOutput == taosArrayGetSize(pColList));
H
Haojun Liao 已提交
4961 4962

    // data from mnode
4963
    for(int32_t i = 0; i < numOfOutput; ++i) {
4964

4965 4966 4967 4968
      for(int32_t j = 0; j < numOfOutput; ++j) {
        int16_t colIndex = *(int16_t*) taosArrayGet(pColList, j);
        if (colIndex - 1 == i) {
          SColumnInfoData* pColInfoData = taosArrayGet(pRes->pDataBlock, j);
4969

4970 4971 4972 4973 4974 4975 4976
          for (int32_t k = 0; k < numOfRows; ++k) {
            colDataAppend(pColInfoData, k, pData, false);
            pData += pColInfoData->info.bytes;
          }
          break;
        }
      }
4977
    }
4978
  }
4979

H
Haojun Liao 已提交
4980
  pRes->info.rows = numOfRows;
4981

4982
  int64_t el = taosGetTimestampUs() - startTs;
4983

H
Haojun Liao 已提交
4984 4985
  pLoadInfo->totalRows += numOfRows;
  pLoadInfo->totalSize += compLen;
4986

H
Haojun Liao 已提交
4987 4988 4989
  if (total != NULL) {
    *total += numOfRows;
  }
4990

H
Haojun Liao 已提交
4991
  pLoadInfo->totalElapsed += el;
4992 4993
  return TSDB_CODE_SUCCESS;
}
4994

4995 4996 4997
static void* setAllSourcesCompleted(SOperatorInfo *pOperator, int64_t startTs) {
  SExchangeInfo *pExchangeInfo = pOperator->info;
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
H
Haojun Liao 已提交
4998

4999
  int64_t el = taosGetTimestampUs() - startTs;
H
Haojun Liao 已提交
5000 5001
  SLoadRemoteDataInfo* pLoadInfo = &pExchangeInfo->loadInfo;
  pLoadInfo->totalElapsed += el;
H
Haojun Liao 已提交
5002

5003 5004
  size_t totalSources = taosArrayGetSize(pExchangeInfo->pSources);
  qDebug("%s all %"PRIzu" sources are exhausted, total rows: %"PRIu64" bytes:%"PRIu64", elapsed:%.2f ms", GET_TASKID(pTaskInfo), totalSources,
H
Haojun Liao 已提交
5005
         pLoadInfo->totalRows, pLoadInfo->totalSize, pLoadInfo->totalElapsed/1000.0);
5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020

  doSetOperatorCompleted(pOperator);
  return NULL;
}

static SSDataBlock* concurrentlyLoadRemoteDataImpl(SOperatorInfo *pOperator, SExchangeInfo *pExchangeInfo, SExecTaskInfo *pTaskInfo) {
  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);

H
Haojun Liao 已提交
5021
      if (pDataInfo->status == DATA_EXHAUSTED) {
5022
        completed += 1;
H
Haojun Liao 已提交
5023 5024
        continue;
      }
5025

H
Haojun Liao 已提交
5026
      if (pDataInfo->status != DATA_READY) {
5027 5028 5029 5030
        continue;
      }

      SRetrieveTableRsp* pRsp = pDataInfo->pRsp;
X
Xiaoyu Wang 已提交
5031
      SDownstreamSourceNode* pSource = taosArrayGet(pExchangeInfo->pSources, i);
5032 5033

      SSDataBlock* pRes = pExchangeInfo->pResult;
H
Haojun Liao 已提交
5034
      SLoadRemoteDataInfo* pLoadInfo = &pExchangeInfo->loadInfo;
5035 5036 5037
      if (pRsp->numOfRows == 0) {
        qDebug("%s vgId:%d, taskID:0x%" PRIx64 " index:%d completed, rowsOfSource:%" PRIu64 ", totalRows:%" PRIu64 " try next",
               GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->taskId, i + 1, pDataInfo->totalRows,
H
Haojun Liao 已提交
5038
               pExchangeInfo->loadInfo.totalRows);
H
Haojun Liao 已提交
5039
        pDataInfo->status = DATA_EXHAUSTED;
5040 5041 5042
        completed += 1;
        continue;
      }
H
Haojun Liao 已提交
5043

H
Haojun Liao 已提交
5044 5045
      SRetrieveTableRsp* pTableRsp = pDataInfo->pRsp;
      code = setSDataBlockFromFetchRsp(pExchangeInfo->pResult, pLoadInfo, pTableRsp->numOfRows,
5046
                                       pTableRsp->data, pTableRsp->compLen, pOperator->numOfOutput, startTs, &pDataInfo->totalRows, NULL);
5047
      if (code != 0) {
5048 5049 5050
        goto _error;
      }

5051 5052 5053 5054
      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,
               GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->taskId, pRes->info.rows,
H
Haojun Liao 已提交
5055
               pDataInfo->totalRows, pLoadInfo->totalRows, pLoadInfo->totalSize, i + 1,
5056
               totalSources);
H
Haojun Liao 已提交
5057
        pDataInfo->status = DATA_EXHAUSTED;
5058 5059
      } else {
        qDebug("%s fetch msg rsp from vgId:%d, taskId:0x%" PRIx64 " numOfRows:%d, totalRows:%" PRIu64 ", totalBytes:%" PRIu64,
H
Haojun Liao 已提交
5060 5061
               GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->taskId, pRes->info.rows, pLoadInfo->totalRows,
               pLoadInfo->totalSize);
5062 5063
      }

H
Haojun Liao 已提交
5064 5065
      if (pDataInfo->status != DATA_EXHAUSTED) {
        pDataInfo->status = DATA_NOT_READY;
5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084
        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;
}

H
Haojun Liao 已提交
5085
static SSDataBlock* concurrentlyLoadRemoteData(SOperatorInfo *pOperator) {
5086 5087
  SExchangeInfo *pExchangeInfo = pOperator->info;
  SExecTaskInfo *pTaskInfo = pOperator->pTaskInfo;
H
Haojun Liao 已提交
5088

H
Haojun Liao 已提交
5089 5090 5091
  if (pOperator->status == OP_RES_TO_RETURN) {
    return concurrentlyLoadRemoteDataImpl(pOperator, pExchangeInfo, pTaskInfo);
  }
5092 5093 5094 5095 5096 5097 5098 5099

  size_t totalSources = taosArrayGetSize(pExchangeInfo->pSources);
  int64_t startTs = taosGetTimestampUs();

  // Asynchronously send all fetch requests to all sources.
  for(int32_t i = 0; i < totalSources; ++i) {
    int32_t code = doSendFetchDataRequest(pExchangeInfo, pTaskInfo, i);
    if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
5100
      return NULL;
5101 5102 5103 5104 5105 5106 5107 5108
    }
  }

  int64_t endTs = taosGetTimestampUs();
  qDebug("%s send all fetch request to %"PRIzu" sources completed, elapsed:%"PRId64, GET_TASKID(pTaskInfo), totalSources, endTs - startTs);

  tsem_wait(&pExchangeInfo->ready);

H
Haojun Liao 已提交
5109 5110
  pOperator->status = OP_RES_TO_RETURN;
  return concurrentlyLoadRemoteDataImpl(pOperator, pExchangeInfo, pTaskInfo);
5111 5112
}

H
Haojun Liao 已提交
5113
static int32_t prepareConcurrentlyLoad(SOperatorInfo *pOperator) {
5114 5115 5116 5117 5118 5119 5120 5121 5122 5123
  SExchangeInfo *pExchangeInfo = pOperator->info;
  SExecTaskInfo *pTaskInfo = pOperator->pTaskInfo;

  size_t totalSources = taosArrayGetSize(pExchangeInfo->pSources);
  int64_t startTs = taosGetTimestampUs();

  // Asynchronously send all fetch requests to all sources.
  for(int32_t i = 0; i < totalSources; ++i) {
    int32_t code = doSendFetchDataRequest(pExchangeInfo, pTaskInfo, i);
    if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
5124 5125
      pTaskInfo->code = code;
      return code;
5126 5127 5128 5129 5130 5131 5132
    }
  }

  int64_t endTs = taosGetTimestampUs();
  qDebug("%s send all fetch request to %"PRIzu" sources completed, elapsed:%"PRId64, GET_TASKID(pTaskInfo), totalSources, endTs - startTs);

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

H
Haojun Liao 已提交
5135
  return TSDB_CODE_SUCCESS;
5136 5137 5138 5139 5140 5141 5142 5143
}

static SSDataBlock* seqLoadRemoteData(SOperatorInfo *pOperator) {
  SExchangeInfo *pExchangeInfo = pOperator->info;
  SExecTaskInfo *pTaskInfo = pOperator->pTaskInfo;

  size_t totalSources = taosArrayGetSize(pExchangeInfo->pSources);
  int64_t startTs = taosGetTimestampUs();
5144

5145 5146 5147
  while(1) {
    if (pExchangeInfo->current >= totalSources) {
      return setAllSourcesCompleted(pOperator, startTs);
5148
    }
5149

5150 5151 5152 5153 5154
    doSendFetchDataRequest(pExchangeInfo, pTaskInfo, pExchangeInfo->current);

    tsem_wait(&pExchangeInfo->ready);

    SSourceDataInfo* pDataInfo = taosArrayGet(pExchangeInfo->pSourceDataInfo, pExchangeInfo->current);
X
Xiaoyu Wang 已提交
5155
    SDownstreamSourceNode* pSource = taosArrayGet(pExchangeInfo->pSources, pExchangeInfo->current);
5156 5157

    SRetrieveTableRsp* pRsp = pDataInfo->pRsp;
H
Haojun Liao 已提交
5158 5159
    SLoadRemoteDataInfo* pLoadInfo = &pExchangeInfo->loadInfo;

5160 5161 5162
    if (pRsp->numOfRows == 0) {
      qDebug("%s vgId:%d, taskID:0x%"PRIx64" %d of total completed, rowsOfSource:%"PRIu64", totalRows:%"PRIu64" try next",
             GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->taskId, pExchangeInfo->current + 1,
H
Haojun Liao 已提交
5163
             pDataInfo->totalRows, pLoadInfo->totalRows);
H
Haojun Liao 已提交
5164

H
Haojun Liao 已提交
5165
      pDataInfo->status = DATA_EXHAUSTED;
5166 5167 5168
      pExchangeInfo->current += 1;
      continue;
    }
H
Haojun Liao 已提交
5169

5170
    SSDataBlock* pRes = pExchangeInfo->pResult;
H
Haojun Liao 已提交
5171 5172
    SRetrieveTableRsp* pTableRsp = pDataInfo->pRsp;
    int32_t code = setSDataBlockFromFetchRsp(pExchangeInfo->pResult, pLoadInfo, pTableRsp->numOfRows,
5173
                                             pTableRsp->data, pTableRsp->compLen, pOperator->numOfOutput, startTs, &pDataInfo->totalRows, NULL);
5174 5175

    if (pRsp->completed == 1) {
H
Haojun Liao 已提交
5176
      qDebug("%s fetch msg rsp from vgId:%d, taskId:0x%" PRIx64 " numOfRows:%d, rowsOfSource:%" PRIu64
5177 5178
                 ", totalRows:%" PRIu64 ", totalBytes:%" PRIu64 " try next %d/%" PRIzu,
             GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->taskId, pRes->info.rows,
H
Haojun Liao 已提交
5179
             pDataInfo->totalRows, pLoadInfo->totalRows, pLoadInfo->totalSize, pExchangeInfo->current + 1,
5180
             totalSources);
5181

H
Haojun Liao 已提交
5182
      pDataInfo->status = DATA_EXHAUSTED;
5183 5184
      pExchangeInfo->current += 1;
    } else {
H
Haojun Liao 已提交
5185
      qDebug("%s fetch msg rsp from vgId:%d, taskId:0x%" PRIx64 " numOfRows:%d, totalRows:%" PRIu64 ", totalBytes:%" PRIu64,
H
Haojun Liao 已提交
5186
             GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->taskId, pRes->info.rows, pLoadInfo->totalRows, pLoadInfo->totalSize);
5187 5188 5189 5190
    }

    return pExchangeInfo->pResult;
  }
5191 5192
}

H
Haojun Liao 已提交
5193
static int32_t prepareLoadRemoteData(SOperatorInfo *pOperator) {
5194
  if (OPTR_IS_OPENED(pOperator)) {
H
Haojun Liao 已提交
5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207
    return TSDB_CODE_SUCCESS;
  }

  SExchangeInfo *pExchangeInfo = pOperator->info;
  if (pExchangeInfo->seqLoadData) {
    // do nothing for sequentially load data
  } else {
    int32_t code = prepareConcurrentlyLoad(pOperator);
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }
  }

5208
  OPTR_SET_OPENED(pOperator);
H
Haojun Liao 已提交
5209 5210 5211
  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
5212
static SSDataBlock* doLoadRemoteData(SOperatorInfo *pOperator, bool* newgroup) {
5213 5214 5215
  SExchangeInfo *pExchangeInfo = pOperator->info;
  SExecTaskInfo *pTaskInfo = pOperator->pTaskInfo;

5216 5217
  pTaskInfo->code = pOperator->_openFn(pOperator);
  if (pTaskInfo->code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
5218 5219
    return NULL;
  }
5220

5221
  size_t totalSources = taosArrayGetSize(pExchangeInfo->pSources);
H
Haojun Liao 已提交
5222
  SLoadRemoteDataInfo* pLoadInfo = &pExchangeInfo->loadInfo;
H
Haojun Liao 已提交
5223

5224 5225
  if (pOperator->status == OP_EXEC_DONE) {
    qDebug("%s all %"PRIzu" source(s) are exhausted, total rows:%"PRIu64" bytes:%"PRIu64", elapsed:%.2f ms", GET_TASKID(pTaskInfo), totalSources,
H
Haojun Liao 已提交
5226
           pLoadInfo->totalRows, pLoadInfo->totalSize, pLoadInfo->totalElapsed/1000.0);
5227 5228 5229 5230
    return NULL;
  }

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

5232 5233 5234
  if (pExchangeInfo->seqLoadData) {
    return seqLoadRemoteData(pOperator);
  } else {
H
Haojun Liao 已提交
5235
    return concurrentlyLoadRemoteData(pOperator);
5236
  }
H
Haojun Liao 已提交
5237

5238
#if 0
H
Haojun Liao 已提交
5239 5240 5241 5242 5243 5244
  _error:
  tfree(pMsg);
  tfree(pMsgSendInfo);

  terrno = pTaskInfo->code;
  return NULL;
5245
#endif
H
Haojun Liao 已提交
5246
}
5247

H
Haojun Liao 已提交
5248
static int32_t initDataSource(int32_t numOfSources, SExchangeInfo* pInfo) {
5249
  pInfo->pSourceDataInfo = taosArrayInit(numOfSources, sizeof(SSourceDataInfo));
H
Haojun Liao 已提交
5250 5251
  if (pInfo->pSourceDataInfo == NULL) {
    return TSDB_CODE_OUT_OF_MEMORY;
5252 5253 5254 5255
  }

  for(int32_t i = 0; i < numOfSources; ++i) {
    SSourceDataInfo dataInfo = {0};
H
Haojun Liao 已提交
5256
    dataInfo.status = EX_SOURCE_DATA_NOT_READY;
5257 5258 5259
    dataInfo.pEx    = pInfo;
    dataInfo.index  = i;

H
Haojun Liao 已提交
5260 5261 5262 5263 5264 5265 5266 5267 5268 5269
    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 已提交
5270
SOperatorInfo* createExchangeOperatorInfo(const SNodeList* pSources, SSDataBlock* pBlock, SExecTaskInfo* pTaskInfo) {
H
Haojun Liao 已提交
5271
  SExchangeInfo* pInfo     = calloc(1, sizeof(SExchangeInfo));
H
Haojun Liao 已提交
5272 5273 5274
  SOperatorInfo* pOperator = calloc(1, sizeof(SOperatorInfo));

  if (pInfo == NULL || pOperator == NULL) {
H
Haojun Liao 已提交
5275 5276 5277 5278
    tfree(pInfo);
    tfree(pOperator);
    terrno = TSDB_CODE_QRY_OUT_OF_MEMORY;
    return NULL;
H
Haojun Liao 已提交
5279 5280
  }

H
Haojun Liao 已提交
5281
  size_t numOfSources = LIST_LENGTH(pSources);
H
Haojun Liao 已提交
5282
  pInfo->pSources = taosArrayInit(numOfSources, sizeof(SDownstreamSourceNode));
H
Haojun Liao 已提交
5283 5284 5285
  pInfo->pSourceDataInfo = taosArrayInit(numOfSources, sizeof(SSourceDataInfo));
  if (pInfo->pSourceDataInfo == NULL || pInfo->pSources == NULL) {
    goto _error;
H
Haojun Liao 已提交
5286 5287 5288 5289 5290 5291
  }

  for(int32_t i = 0; i < numOfSources; ++i) {
    SNodeListNode* pNode = nodesListGetNode((SNodeList*) pSources, i);
    taosArrayPush(pInfo->pSources, pNode);
  }
5292

H
Haojun Liao 已提交
5293 5294 5295
  int32_t code = initDataSource(numOfSources, pInfo);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
5296
  }
H
Haojun Liao 已提交
5297

H
Haojun Liao 已提交
5298 5299
  size_t size        = pBlock->info.numOfCols;
  pInfo->pResult     = pBlock;
5300 5301 5302
  pInfo->seqLoadData = true;

  tsem_init(&pInfo->ready, 0, 0);
5303 5304

  pOperator->name         = "ExchangeOperator";
X
Xiaoyu Wang 已提交
5305
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_EXCHANGE;
5306
  pOperator->blockingOptr = false;
H
Haojun Liao 已提交
5307
  pOperator->status       = OP_NOT_OPENED;
5308
  pOperator->info         = pInfo;
H
Haojun Liao 已提交
5309
  pOperator->numOfOutput  = size;
5310
  pOperator->pTaskInfo    = pTaskInfo;
5311
  pOperator->_openFn      = prepareLoadRemoteData;  // assign a dummy function.
H
Haojun Liao 已提交
5312
  pOperator->getNextFn    = doLoadRemoteData;
H
Haojun Liao 已提交
5313
  pOperator->closeFn      = destroyExchangeOperatorInfo;
5314

S
Shengliang Guan 已提交
5315
#if 1
H
Haojun Liao 已提交
5316
  { // todo refactor
H
Haojun Liao 已提交
5317 5318 5319
    SRpcInit rpcInit;
    memset(&rpcInit, 0, sizeof(rpcInit));
    rpcInit.localPort = 0;
H
Haojun Liao 已提交
5320
    rpcInit.label = "EX";
H
Haojun Liao 已提交
5321
    rpcInit.numOfThreads = 1;
S
Shengliang Guan 已提交
5322
    rpcInit.cfp = qProcessFetchRsp;
S
Shengliang Guan 已提交
5323
    rpcInit.sessions = tsMaxConnections;
H
Haojun Liao 已提交
5324 5325
    rpcInit.connType = TAOS_CONN_CLIENT;
    rpcInit.user = (char *)"root";
S
Shengliang Guan 已提交
5326
    rpcInit.idleTime = tsShellActivityTimer * 1000;
H
Haojun Liao 已提交
5327
    rpcInit.ckey = "key";
S
Shengliang Guan 已提交
5328
    rpcInit.spi = 1;
H
Haojun Liao 已提交
5329 5330 5331 5332 5333 5334 5335
    rpcInit.secret = (char *)"dcc5bed04851fec854c035b2e40263b6";

    pInfo->pTransporter = rpcOpen(&rpcInit);
    if (pInfo->pTransporter == NULL) {
      return NULL; // todo
    }
  }
S
Shengliang 已提交
5336
#endif
5337

5338
  return pOperator;
H
Haojun Liao 已提交
5339 5340 5341

  _error:
  if (pInfo != NULL) {
H
Haojun Liao 已提交
5342
    destroyExchangeOperatorInfo(pInfo, numOfSources);
H
Haojun Liao 已提交
5343 5344 5345 5346
  }

  tfree(pInfo);
  tfree(pOperator);
H
Haojun Liao 已提交
5347
  pTaskInfo->code = TSDB_CODE_OUT_OF_MEMORY;
H
Haojun Liao 已提交
5348
  return NULL;
5349 5350
}

H
Haojun Liao 已提交
5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364
SSDataBlock* createResultDataBlock(const SArray* pExprInfo) {
  SSDataBlock* pResBlock = calloc(1, sizeof(SSDataBlock));
  if (pResBlock == NULL) {
    return NULL;
  }

  size_t numOfCols = taosArrayGetSize(pExprInfo);
  pResBlock->pDataBlock = taosArrayInit(numOfCols, sizeof(SColumnInfoData));

  SArray* pResult = pResBlock->pDataBlock;
  for(int32_t i = 0; i < numOfCols; ++i) {
    SColumnInfoData colInfoData = {0};
    SExprInfo* p = taosArrayGetP(pExprInfo, i);

H
Haojun Liao 已提交
5365
    SResSchema* pSchema = &p->base.resSchema;
H
Haojun Liao 已提交
5366 5367 5368
    colInfoData.info.type  = pSchema->type;
    colInfoData.info.colId = pSchema->colId;
    colInfoData.info.bytes = pSchema->bytes;
H
Haojun Liao 已提交
5369 5370
    colInfoData.info.scale = pSchema->scale;
    colInfoData.info.precision = pSchema->precision;
H
Haojun Liao 已提交
5371 5372 5373 5374 5375 5376
    taosArrayPush(pResult, &colInfoData);
  }

  return pResBlock;
}

H
Haojun Liao 已提交
5377
SOperatorInfo* createTableScanOperatorInfo(void* pTsdbReadHandle, int32_t order, int32_t numOfOutput, int32_t repeatTime, int32_t reverseTime, SExecTaskInfo* pTaskInfo) {
5378 5379 5380 5381 5382 5383 5384 5385
  assert(repeatTime > 0);

  STableScanInfo* pInfo    = calloc(1, sizeof(STableScanInfo));
  SOperatorInfo* pOperator = calloc(1, sizeof(SOperatorInfo));
  if (pInfo == NULL || pOperator == NULL) {
    tfree(pInfo);
    tfree(pOperator);

H
Haojun Liao 已提交
5386
    pTaskInfo->code = TSDB_CODE_QRY_OUT_OF_MEMORY;
5387 5388 5389
    return NULL;
  }

H
Haojun Liao 已提交
5390
  pInfo->pTsdbReadHandle = pTsdbReadHandle;
5391 5392 5393 5394 5395
  pInfo->times             = repeatTime;
  pInfo->reverseTimes      = reverseTime;
  pInfo->order             = order;
  pInfo->current           = 0;
  pInfo->scanFlag          = MAIN_SCAN;
H
Haojun Liao 已提交
5396
  pOperator->name          = "TableScanOperator";
X
Xiaoyu Wang 已提交
5397
  pOperator->operatorType  = QUERY_NODE_PHYSICAL_PLAN_TABLE_SCAN;
5398
  pOperator->blockingOptr  = false;
H
Haojun Liao 已提交
5399
  pOperator->status        = OP_NOT_OPENED;
5400 5401
  pOperator->info          = pInfo;
  pOperator->numOfOutput   = numOfOutput;
H
Haojun Liao 已提交
5402
  pOperator->getNextFn     = doTableScan;
5403 5404 5405 5406 5407
  pOperator->pTaskInfo     = pTaskInfo;

  return pOperator;
}

H
Haojun Liao 已提交
5408
SOperatorInfo* createTableSeqScanOperatorInfo(void* pTsdbReadHandle, STaskRuntimeEnv* pRuntimeEnv) {
5409 5410
  STableScanInfo* pInfo = calloc(1, sizeof(STableScanInfo));

H
Haojun Liao 已提交
5411
  pInfo->pTsdbReadHandle     = pTsdbReadHandle;
5412 5413 5414 5415 5416 5417 5418 5419 5420
  pInfo->times            = 1;
  pInfo->reverseTimes     = 0;
  pInfo->order            = pRuntimeEnv->pQueryAttr->order.order;
  pInfo->current          = 0;
  pInfo->prevGroupId      = -1;
  pRuntimeEnv->enableGroupData = true;

  SOperatorInfo* pOperator = calloc(1, sizeof(SOperatorInfo));
  pOperator->name         = "TableSeqScanOperator";
X
Xiaoyu Wang 已提交
5421
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_TABLE_SEQ_SCAN;
5422
  pOperator->blockingOptr = false;
H
Haojun Liao 已提交
5423
  pOperator->status       = OP_NOT_OPENED;
5424 5425 5426
  pOperator->info         = pInfo;
  pOperator->numOfOutput  = pRuntimeEnv->pQueryAttr->numOfCols;
  pOperator->pRuntimeEnv  = pRuntimeEnv;
H
Haojun Liao 已提交
5427
  pOperator->getNextFn    = doTableScanImpl;
5428 5429 5430 5431

  return pOperator;
}

H
Haojun Liao 已提交
5432
SOperatorInfo* createTableBlockInfoScanOperator(void* pTsdbReadHandle, STaskRuntimeEnv* pRuntimeEnv) {
5433 5434
  STableScanInfo* pInfo = calloc(1, sizeof(STableScanInfo));

H
Haojun Liao 已提交
5435
  pInfo->pTsdbReadHandle     = pTsdbReadHandle;
5436 5437 5438 5439 5440 5441 5442 5443 5444 5445
  pInfo->block.pDataBlock = taosArrayInit(1, sizeof(SColumnInfoData));

  SColumnInfoData infoData = {{0}};
  infoData.info.type = TSDB_DATA_TYPE_BINARY;
  infoData.info.bytes = 1024;
  infoData.info.colId = 0;
  taosArrayPush(pInfo->block.pDataBlock, &infoData);

  SOperatorInfo* pOperator = calloc(1, sizeof(SOperatorInfo));
  pOperator->name         = "TableBlockInfoScanOperator";
H
Haojun Liao 已提交
5446
//  pOperator->operatorType = OP_TableBlockInfoScan;
5447
  pOperator->blockingOptr = false;
H
Haojun Liao 已提交
5448
  pOperator->status       = OP_NOT_OPENED;
5449
  pOperator->info         = pInfo;
H
Haojun Liao 已提交
5450
//  pOperator->numOfOutput  = pRuntimeEnv->pQueryAttr->numOfCols;
H
Haojun Liao 已提交
5451
  pOperator->getNextFn = doBlockInfoScan;
5452 5453 5454 5455

  return pOperator;
}

5456
SOperatorInfo* createStreamScanOperatorInfo(void *streamReadHandle, SSDataBlock* pResBlock, SArray* pColList, SArray* pTableIdList, SExecTaskInfo* pTaskInfo) {
5457 5458 5459 5460 5461 5462 5463 5464 5465
  SStreamBlockScanInfo* pInfo = calloc(1, sizeof(SStreamBlockScanInfo));
  SOperatorInfo* pOperator = calloc(1, sizeof(SOperatorInfo));
  if (pInfo == NULL || pOperator == NULL) {
    tfree(pInfo);
    tfree(pOperator);
    terrno = TSDB_CODE_QRY_OUT_OF_MEMORY;
    return NULL;
  }

L
Liu Jicong 已提交
5466 5467
  // set the extract column id to streamHandle
  tqReadHandleSetColIdList((STqReadHandle* )streamReadHandle, pColList);
5468 5469 5470 5471 5472 5473
  int32_t code = tqReadHandleSetTbUidList(streamReadHandle, pTableIdList);
  if (code != 0) {
    tfree(pInfo);
    tfree(pOperator);
    return NULL;
  }
H
Haojun Liao 已提交
5474

5475 5476
  pInfo->readerHandle      = streamReadHandle;
  pInfo->pRes              = pResBlock;
H
Haojun Liao 已提交
5477

5478
  pOperator->name          = "StreamBlockScanOperator";
X
Xiaoyu Wang 已提交
5479
  pOperator->operatorType  = QUERY_NODE_PHYSICAL_PLAN_STREAM_SCAN;
5480
  pOperator->blockingOptr  = false;
H
Haojun Liao 已提交
5481
  pOperator->status        = OP_NOT_OPENED;
5482
  pOperator->info          = pInfo;
5483
  pOperator->numOfOutput   = pResBlock->info.numOfCols;
5484
  pOperator->_openFn       = operatorDummyOpenFn;
H
Haojun Liao 已提交
5485 5486
  pOperator->getNextFn     = doStreamBlockScan;
  pOperator->closeFn       = operatorDummyCloseFn;
5487
  pOperator->pTaskInfo     = pTaskInfo;
L
Liu Jicong 已提交
5488
  return pOperator;
H
Haojun Liao 已提交
5489 5490
}

5491
static int32_t loadSysTableContentCb(void* param, const SDataBuf* pMsg, int32_t code) {
H
Haojun Liao 已提交
5492
  SSysTableScanInfo* pScanResInfo = (SSysTableScanInfo*) param;
X
Xiaoyu Wang 已提交
5493 5494
  if (TSDB_CODE_SUCCESS == code) {
    pScanResInfo->pRsp = pMsg->pData;
5495

X
Xiaoyu Wang 已提交
5496 5497 5498 5499 5500 5501
    SRetrieveMetaTableRsp* pRsp = pScanResInfo->pRsp;
    pRsp->numOfRows = htonl(pRsp->numOfRows);
    pRsp->useconds  = htobe64(pRsp->useconds);
    pRsp->handle    = htobe64(pRsp->handle);
    pRsp->compLen   = htonl(pRsp->compLen);
  }
5502

H
Haojun Liao 已提交
5503
  tsem_post(&pScanResInfo->ready);
5504 5505
}

H
Haojun Liao 已提交
5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544

static SSDataBlock* doFilterResult(SSysTableScanInfo* pInfo) {
  if (pInfo->pCondition == NULL) {
    return pInfo->pRes->info.rows == 0? NULL:pInfo->pRes;
  }

  SFilterInfo* filter = NULL;
  int32_t      code = filterInitFromNode(pInfo->pCondition, &filter, 0);

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

  int8_t* rowRes = NULL;
  bool    keep = filterExecute(filter, pInfo->pRes, &rowRes, NULL, param1.numOfCols);

  SSDataBlock* px = createOneDataBlock(pInfo->pRes);
  blockDataEnsureCapacity(px, pInfo->pRes->info.rows);

  //TODO refactor
  int32_t numOfRow = 0;
  for (int32_t i = 0; i < pInfo->pRes->info.numOfCols; ++i) {
    SColumnInfoData* pDest = taosArrayGet(px->pDataBlock, i);
    SColumnInfoData* pSrc = taosArrayGet(pInfo->pRes->pDataBlock, i);

    numOfRow = 0;
    for (int32_t j = 0; j < pInfo->pRes->info.rows; ++j) {
      if (rowRes[j] == 0) {
        continue;
      }

      colDataAppend(pDest, numOfRow, colDataGetData(pSrc, j), false);
      numOfRow += 1;
    }
  }

  px->info.rows = numOfRow;
  pInfo->pRes = px;

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

H
Haojun Liao 已提交
5547
static SSDataBlock* doSysTableScan(SOperatorInfo *pOperator, bool* newgroup) {
5548 5549 5550 5551
// build message and send to mnode to fetch the content of system tables.
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
  SSysTableScanInfo* pInfo = pOperator->info;

5552 5553 5554 5555 5556
  // retrieve local table list info from vnode
  if (pInfo->type == TSDB_MGMT_TABLE_TABLE) {
    if (pInfo->pCur == NULL) {
      pInfo->pCur = metaOpenTbCursor(pInfo->readHandle);
    }
5557

H
Haojun Liao 已提交
5558
    blockDataCleanup(pInfo->pRes);
5559

H
Haojun Liao 已提交
5560 5561
    int32_t tableNameSlotId = 1;
    SColumnInfoData* pTableNameCol = taosArrayGet(pInfo->pRes->pDataBlock, tableNameSlotId);
5562

5563 5564
    char *  name = NULL;
    int32_t numOfRows = 0;
5565 5566

    char n[TSDB_TABLE_NAME_LEN] = {0};
5567
    while ((name = metaTbCursorNext(pInfo->pCur)) != NULL) {
5568 5569
      STR_TO_VARSTR(n, name);
      colDataAppend(pTableNameCol, numOfRows, n, false);
5570 5571 5572 5573
      numOfRows += 1;
      if (numOfRows >= pInfo->capacity) {
        break;
      }
H
Haojun Liao 已提交
5574 5575

      for(int32_t i = 0; i < pInfo->pRes->info.numOfCols; ++i) {
H
Haojun Liao 已提交
5576
        if (i == tableNameSlotId) {
H
Haojun Liao 已提交
5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589
          continue;
        }

        SColumnInfoData* pColInfoData = taosArrayGet(pInfo->pRes->pDataBlock, i);
        int64_t tmp = 0;
        char t[10] = {0};
        STR_TO_VARSTR(t, "_");
        if (IS_VAR_DATA_TYPE(pColInfoData->info.type)) {
          colDataAppend(pColInfoData, numOfRows, t, false);
        } else {
          colDataAppend(pColInfoData, numOfRows, (char*) &tmp, false);
        }
      }
5590
    }
5591

H
Haojun Liao 已提交
5592
    pInfo->loadInfo.totalRows += numOfRows;
5593
    pInfo->pRes->info.rows = numOfRows;
5594

5595 5596 5597 5598
//    pInfo->elapsedTime;
//    pInfo->totalBytes;
    return (pInfo->pRes->info.rows == 0)? NULL:pInfo->pRes;
  } else {  // load the meta from mnode of the given epset
H
Haojun Liao 已提交
5599
    int64_t startTs = taosGetTimestampUs();
5600

H
Haojun Liao 已提交
5601
    pInfo->req.type = pInfo->type;
H
Haojun Liao 已提交
5602 5603
    strncpy(pInfo->req.tb, tNameGetTableName(&pInfo->name), tListLen(pInfo->req.tb));

H
Haojun Liao 已提交
5604 5605 5606
    int32_t contLen = tSerializeSRetrieveTableReq(NULL, 0, &pInfo->req);
    char* buf1 = calloc(1, contLen);
    tSerializeSRetrieveTableReq(buf1, contLen, &pInfo->req);
5607

5608 5609 5610 5611 5612 5613 5614 5615
    // send the fetch remote task result reques
    SMsgSendInfo* pMsgSendInfo = calloc(1, sizeof(SMsgSendInfo));
    if (NULL == pMsgSendInfo) {
      qError("%s prepare message %d failed", GET_TASKID(pTaskInfo), (int32_t)sizeof(SMsgSendInfo));
      pTaskInfo->code = TSDB_CODE_QRY_OUT_OF_MEMORY;
      return NULL;
    }

H
Haojun Liao 已提交
5616 5617 5618
    pMsgSendInfo->param = pInfo;
    pMsgSendInfo->msgInfo.pData = buf1;
    pMsgSendInfo->msgInfo.len = contLen;
5619
    pMsgSendInfo->msgType = TDMT_MND_SYSTABLE_RETRIEVE;
H
Haojun Liao 已提交
5620
    pMsgSendInfo->fp = loadSysTableContentCb;
5621 5622 5623 5624

    int64_t transporterId = 0;
    int32_t code = asyncSendMsgToServer(pInfo->pTransporter, &pInfo->epSet, &transporterId, pMsgSendInfo);
    tsem_wait(&pInfo->ready);
H
Haojun Liao 已提交
5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636

    SRetrieveMetaTableRsp* pRsp = pInfo->pRsp;
    pInfo->req.showId = pRsp->handle;

    if (pRsp->numOfRows == 0) {
//      qDebug("%s vgId:%d, taskID:0x%"PRIx64" %d of total completed, rowsOfSource:%"PRIu64", totalRows:%"PRIu64" try next",
//             GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->taskId, pExchangeInfo->current + 1,
//             pDataInfo->totalRows, pExchangeInfo->totalRows);
      return NULL;
    }

    SRetrieveMetaTableRsp* pTableRsp = pInfo->pRsp;
H
Haojun Liao 已提交
5637
    setSDataBlockFromFetchRsp(pInfo->pRes, &pInfo->loadInfo, pTableRsp->numOfRows,
5638
                              pTableRsp->data, pTableRsp->compLen, pOperator->numOfOutput, startTs, NULL, pInfo->scanCols);
H
Haojun Liao 已提交
5639

H
Haojun Liao 已提交
5640
    return doFilterResult(pInfo);
5641
  }
5642 5643 5644 5645

  return NULL;
}

H
Haojun Liao 已提交
5646
SOperatorInfo* createSysTableScanOperatorInfo(void* pSysTableReadHandle, SSDataBlock* pResBlock, const SName* pName,
5647
                                              SNode* pCondition, SEpSet epset, SArray* colList, SExecTaskInfo* pTaskInfo) {
5648 5649 5650 5651 5652 5653 5654 5655 5656
  SSysTableScanInfo* pInfo = calloc(1, sizeof(SSysTableScanInfo));
  SOperatorInfo* pOperator = calloc(1, sizeof(SOperatorInfo));
  if (pInfo == NULL || pOperator == NULL) {
    tfree(pInfo);
    tfree(pOperator);
    terrno = TSDB_CODE_QRY_OUT_OF_MEMORY;
    return NULL;
  }

H
Haojun Liao 已提交
5657 5658 5659
  pInfo->pRes       = pResBlock;
  pInfo->capacity   = 4096;
  pInfo->pCondition = pCondition;
5660
  pInfo->scanCols   = colList;
H
Haojun Liao 已提交
5661

H
Haojun Liao 已提交
5662
  // TODO remove it
H
Haojun Liao 已提交
5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696
  int32_t tableType = 0;
  const char* name = tNameGetTableName(pName);
  if (strncasecmp(name, TSDB_INS_TABLE_USER_DATABASES, tListLen(pName->tname)) == 0) {
    tableType = TSDB_MGMT_TABLE_DB;
  } else if (strncasecmp(name, TSDB_INS_TABLE_USER_USERS, tListLen(pName->tname)) == 0) {
    tableType = TSDB_MGMT_TABLE_USER;
  } else if (strncasecmp(name, TSDB_INS_TABLE_DNODES, tListLen(pName->tname)) == 0) {
    tableType = TSDB_MGMT_TABLE_DNODE;
  } else if (strncasecmp(name, TSDB_INS_TABLE_MNODES, tListLen(pName->tname)) == 0) {
    tableType = TSDB_MGMT_TABLE_MNODE;
  } else if (strncasecmp(name, TSDB_INS_TABLE_MODULES, tListLen(pName->tname)) == 0) {
    tableType = TSDB_MGMT_TABLE_MODULE;
  } else if (strncasecmp(name, TSDB_INS_TABLE_QNODES, tListLen(pName->tname)) == 0) {
    tableType = TSDB_MGMT_TABLE_QNODE;
  } else if (strncasecmp(name, TSDB_INS_TABLE_USER_FUNCTIONS, tListLen(pName->tname)) == 0) {
    tableType = TSDB_MGMT_TABLE_FUNC;
  } else if (strncasecmp(name, TSDB_INS_TABLE_USER_INDEXES, tListLen(pName->tname)) == 0) {
//    tableType = TSDB_MGMT_TABLE_INDEX;
  } else if (strncasecmp(name, TSDB_INS_TABLE_USER_STABLES, tListLen(pName->tname)) == 0) {
    tableType = TSDB_MGMT_TABLE_STB;
  } else if (strncasecmp(name, TSDB_INS_TABLE_USER_STREAMS, tListLen(pName->tname)) == 0) {
    tableType = TSDB_MGMT_TABLE_STREAMS;
  } else if (strncasecmp(name, TSDB_INS_TABLE_USER_TABLES, tListLen(pName->tname)) == 0) {
    tableType = TSDB_MGMT_TABLE_TABLE;
  } else if (strncasecmp(name, TSDB_INS_TABLE_VGROUPS, tListLen(pName->tname)) == 0) {
    tableType = TSDB_MGMT_TABLE_VGROUP;
  } else if (strncasecmp(name, TSDB_INS_TABLE_USER_TABLE_DISTRIBUTED, tListLen(pName->tname)) == 0) {
//    tableType = TSDB_MGMT_TABLE_DIST;
  } else {
    ASSERT(0);
  }

  tNameAssign(&pInfo->name, pName);
  pInfo->type = tableType;
5697 5698 5699 5700 5701 5702 5703
  if (pInfo->type == TSDB_MGMT_TABLE_TABLE) {
    pInfo->readHandle = pSysTableReadHandle;
    blockDataEnsureCapacity(pInfo->pRes, pInfo->capacity);
  } else {
    tsem_init(&pInfo->ready, 0, 0);
    pInfo->epSet = epset;

5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725
#if 1
    { // todo refactor
      SRpcInit rpcInit;
      memset(&rpcInit, 0, sizeof(rpcInit));
      rpcInit.localPort = 0;
      rpcInit.label = "DB-META";
      rpcInit.numOfThreads = 1;
      rpcInit.cfp = qProcessFetchRsp;
      rpcInit.sessions = tsMaxConnections;
      rpcInit.connType = TAOS_CONN_CLIENT;
      rpcInit.user = (char *)"root";
      rpcInit.idleTime = tsShellActivityTimer * 1000;
      rpcInit.ckey = "key";
      rpcInit.spi = 1;
      rpcInit.secret = (char *)"dcc5bed04851fec854c035b2e40263b6";

      pInfo->pTransporter = rpcOpen(&rpcInit);
      if (pInfo->pTransporter == NULL) {
        return NULL; // todo
      }
    }
#endif
5726 5727
  }

5728 5729 5730
  pOperator->name          = "SysTableScanOperator";
  pOperator->operatorType  = QUERY_NODE_PHYSICAL_PLAN_SYSTABLE_SCAN;
  pOperator->blockingOptr  = false;
H
Haojun Liao 已提交
5731
  pOperator->status        = OP_NOT_OPENED;
5732
  pOperator->info          = pInfo;
H
Haojun Liao 已提交
5733
  pOperator->numOfOutput   = pResBlock->info.numOfCols;
H
Haojun Liao 已提交
5734
  pOperator->getNextFn     = doSysTableScan;
5735
  pOperator->closeFn       = destroySysTableScannerOperatorInfo;
5736 5737 5738 5739 5740
  pOperator->pTaskInfo     = pTaskInfo;

  return pOperator;
}

H
Haojun Liao 已提交
5741
SArray* getOrderCheckColumns(STaskAttr* pQuery) {
5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764
  int32_t numOfCols = (pQuery->pGroupbyExpr == NULL)? 0: taosArrayGetSize(pQuery->pGroupbyExpr->columnInfo);

  SArray* pOrderColumns = NULL;
  if (numOfCols > 0) {
    pOrderColumns = taosArrayDup(pQuery->pGroupbyExpr->columnInfo);
  } else {
    pOrderColumns = taosArrayInit(4, sizeof(SColIndex));
  }

  if (pQuery->interval.interval > 0) {
    if (pOrderColumns == NULL) {
      pOrderColumns = taosArrayInit(1, sizeof(SColIndex));
    }

    SColIndex colIndex = {.colIndex = 0, .colId = 0, .flag = TSDB_COL_NORMAL};
    taosArrayPush(pOrderColumns, &colIndex);
  }

  {
    numOfCols = (int32_t) taosArrayGetSize(pOrderColumns);
    for(int32_t i = 0; i < numOfCols; ++i) {
      SColIndex* index = taosArrayGet(pOrderColumns, i);
      for(int32_t j = 0; j < pQuery->numOfOutput; ++j) {
H
Haojun Liao 已提交
5765
        SExprBasicInfo* pExpr = &pQuery->pExpr1[j].base;
5766 5767
        int32_t functionId = getExprFunctionId(&pQuery->pExpr1[j]);

H
Haojun Liao 已提交
5768
        if (index->colId == pExpr->pParam[0].pCol->colId &&
5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779
            (functionId == FUNCTION_PRJ || functionId == FUNCTION_TAG || functionId == FUNCTION_TS)) {
          index->colIndex = j;
          index->colId = pExpr->resSchema.colId;
        }
      }
    }
  }

  return pOrderColumns;
}

H
Haojun Liao 已提交
5780
SArray* getResultGroupCheckColumns(STaskAttr* pQuery) {
5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794
  int32_t numOfCols = (pQuery->pGroupbyExpr == NULL)? 0 : taosArrayGetSize(pQuery->pGroupbyExpr->columnInfo);

  SArray* pOrderColumns = NULL;
  if (numOfCols > 0) {
    pOrderColumns = taosArrayDup(pQuery->pGroupbyExpr->columnInfo);
  } else {
    pOrderColumns = taosArrayInit(4, sizeof(SColIndex));
  }

  for(int32_t i = 0; i < numOfCols; ++i) {
    SColIndex* index = taosArrayGet(pOrderColumns, i);

    bool found = false;
    for(int32_t j = 0; j < pQuery->numOfOutput; ++j) {
H
Haojun Liao 已提交
5795
      SExprBasicInfo* pExpr = &pQuery->pExpr1[j].base;
5796 5797 5798
      int32_t functionId = getExprFunctionId(&pQuery->pExpr1[j]);

      // FUNCTION_TAG_DUMMY function needs to be ignored
H
Haojun Liao 已提交
5799 5800 5801 5802 5803 5804 5805 5806
//      if (index->colId == pExpr->pColumns->info.colId &&
//          ((TSDB_COL_IS_TAG(pExpr->pColumns->flag) && functionId == FUNCTION_TAG) ||
//           (TSDB_COL_IS_NORMAL_COL(pExpr->pColumns->flag) && functionId == FUNCTION_PRJ))) {
//        index->colIndex = j;
//        index->colId = pExpr->resSchema.colId;
//        found = true;
//        break;
//      }
5807 5808 5809 5810 5811 5812 5813 5814
    }

    assert(found && index->colIndex >= 0 && index->colIndex < pQuery->numOfOutput);
  }

  return pOrderColumns;
}

H
Haojun Liao 已提交
5815
static int32_t doInitAggInfoSup(SAggSupporter* pAggSup, SqlFunctionCtx *pCtx, int32_t numOfOutput, const char* pKey);
H
Haojun Liao 已提交
5816
static void cleanupAggSup(SAggSupporter* pAggSup);
5817

5818
static void destroySortedMergeOperatorInfo(void* param, int32_t numOfOutput) {
H
Haojun Liao 已提交
5819 5820
  SSortedMergeOperatorInfo* pInfo = (SSortedMergeOperatorInfo*) param;
  taosArrayDestroy(pInfo->orderInfo);
5821 5822 5823
  taosArrayDestroy(pInfo->groupInfo);

  if (pInfo->pSortHandle != NULL) {
H
Haojun Liao 已提交
5824
    tsortDestroySortHandle(pInfo->pSortHandle);
5825
  }
H
Haojun Liao 已提交
5826
  blockDataDestroy(pInfo->binfo.pRes);
5827

H
Haojun Liao 已提交
5828
  cleanupAggSup(&pInfo->aggSup);
5829
}
H
Haojun Liao 已提交
5830

5831 5832 5833
static void destroySlimitOperatorInfo(void* param, int32_t numOfOutput) {
  SSLimitOperatorInfo *pInfo = (SSLimitOperatorInfo*) param;
  taosArrayDestroy(pInfo->orderColumnList);
H
Haojun Liao 已提交
5834
  pInfo->pRes = blockDataDestroy(pInfo->pRes);
5835 5836 5837
  tfree(pInfo->prevRow);
}

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

X
Xiaoyu Wang 已提交
5841
  *dst = *src;
5842

X
Xiaoyu Wang 已提交
5843
  dst->pExpr = exprdup(src->pExpr);
H
Haojun Liao 已提交
5844 5845
  dst->base.pParam = calloc(src->base.numOfParams, sizeof(SColumn));
  memcpy(dst->base.pParam, src->base.pParam, sizeof(SColumn) * src->base.numOfParams);
5846

H
Haojun Liao 已提交
5847 5848 5849 5850
//  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 已提交
5851
}
5852

5853 5854
static SExprInfo* exprArrayDup(SArray* pExprList) {
  size_t numOfOutput = taosArrayGetSize(pExprList);
5855

H
Haojun Liao 已提交
5856
  SExprInfo* p = calloc(numOfOutput, sizeof(SExprInfo));
5857 5858
  for (int32_t i = 0; i < numOfOutput; ++i) {
    SExprInfo* pExpr = taosArrayGetP(pExprList, i);
H
Haojun Liao 已提交
5859
    assignExprInfo(&p[i], pExpr);
5860 5861
  }

H
Haojun Liao 已提交
5862 5863
  return p;
}
5864

H
Haojun Liao 已提交
5865
// TODO merge aggregate super table
5866
static void appendOneRowToDataBlock(SSDataBlock *pBlock, STupleHandle* pTupleHandle) {
5867 5868
  for (int32_t i = 0; i < pBlock->info.numOfCols; ++i) {
    SColumnInfoData* pColInfo = taosArrayGet(pBlock->pDataBlock, i);
5869

H
Haojun Liao 已提交
5870
    bool isNull = tsortIsNullVal(pTupleHandle, i);
H
Haojun Liao 已提交
5871 5872 5873
    if (isNull) {
      colDataAppend(pColInfo, pBlock->info.rows, NULL, true);
    } else {
H
Haojun Liao 已提交
5874
      char* pData = tsortGetValue(pTupleHandle, i);
H
Haojun Liao 已提交
5875 5876
      colDataAppend(pColInfo, pBlock->info.rows, pData, false);
    }
5877 5878
  }

5879 5880
  pBlock->info.rows += 1;
}
5881

5882
static SSDataBlock* getSortedBlockData(SSortHandle* pHandle, SSDataBlock* pDataBlock, bool hasVarCol, int32_t capacity) {
5883
  blockDataCleanup(pDataBlock);
5884

H
Haojun Liao 已提交
5885
  while(1) {
H
Haojun Liao 已提交
5886
    STupleHandle* pTupleHandle = tsortNextTuple(pHandle);
5887 5888 5889
    if (pTupleHandle == NULL) {
      break;
    }
5890

5891 5892 5893
    appendOneRowToDataBlock(pDataBlock, pTupleHandle);
    if (pDataBlock->info.rows >= capacity) {
      return pDataBlock;
H
Haojun Liao 已提交
5894 5895
    }
  }
5896

5897
  return (pDataBlock->info.rows > 0)? pDataBlock:NULL;
5898
}
5899

5900
SSDataBlock* loadNextDataBlock(void* param) {
H
Haojun Liao 已提交
5901 5902
  SOperatorInfo* pOperator = (SOperatorInfo*) param;
  bool newgroup = false;
5903

H
Haojun Liao 已提交
5904
  return pOperator->getNextFn(pOperator, &newgroup);
5905 5906
}

5907 5908 5909 5910 5911
static bool needToMerge(SSDataBlock* pBlock, SArray* groupInfo, char **buf, int32_t rowIndex) {
  size_t size = taosArrayGetSize(groupInfo);
  if (size == 0) {
    return true;
  }
5912

5913 5914
  for (int32_t i = 0; i < size; ++i) {
    int32_t* index = taosArrayGet(groupInfo, i);
5915

5916 5917
    SColumnInfoData* pColInfo = taosArrayGet(pBlock->pDataBlock, *index);
    bool isNull = colDataIsNull(pColInfo, rowIndex, pBlock->info.rows, NULL);
5918

5919 5920 5921
    if ((isNull && buf[i] != NULL) || (!isNull && buf[i] == NULL)) {
      return false;
    }
5922

5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935
    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;
      }
5936 5937 5938
    }
  }

5939
  return 0;
5940 5941
}

5942 5943 5944
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
    pCtx[j].startRow = rowIndex;
5945 5946
  }

5947 5948
  for (int32_t j = 0; j < numOfExpr; ++j) {
    int32_t functionId = pCtx[j].functionId;
H
Haojun Liao 已提交
5949
//    pCtx[j].fpSet->addInput(&pCtx[j]);
5950 5951 5952 5953 5954 5955 5956 5957

//    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]);
//    }
5958
  }
5959
}
5960

5961 5962 5963 5964 5965 5966
static void doFinalizeResultImpl(SqlFunctionCtx *pCtx, int32_t numOfExpr) {
  for(int32_t j = 0; j < numOfExpr; ++j) {
    int32_t functionId = pCtx[j].functionId;
    //    if (functionId == FUNC_TAG_DUMMY || functionId == FUNC_TS_DUMMY) {
    //      continue;
    //    }
5967

5968 5969 5970 5971
    //    if (functionId < 0) {
    //      SUdfInfo* pUdfInfo = taosArrayGet(pInfo->udfInfo, -1 * functionId - 1);
    //      doInvokeUdf(pUdfInfo, &pCtx[j], 0, TSDB_UDF_FUNC_FINALIZE);
    //    } else {
H
Haojun Liao 已提交
5972
    pCtx[j].fpSet.finalize(&pCtx[j]);
5973 5974
  }
}
5975

5976 5977
static bool saveCurrentTuple(char** rowColData, SArray* pColumnList, SSDataBlock* pBlock, int32_t rowIndex) {
  int32_t size = (int32_t) taosArrayGetSize(pColumnList);
5978

5979 5980 5981
  for(int32_t i = 0; i < size; ++i) {
    int32_t* index = taosArrayGet(pColumnList, i);
    SColumnInfoData* pColInfo = taosArrayGet(pBlock->pDataBlock, *index);
H
Haojun Liao 已提交
5982

5983 5984 5985
    char* data = colDataGetData(pColInfo, rowIndex);
    memcpy(rowColData[i], data, colDataGetLength(pColInfo, rowIndex));
  }
5986

5987 5988
  return true;
}
5989

5990 5991
static void doMergeImpl(SOperatorInfo* pOperator, int32_t numOfExpr, SSDataBlock* pBlock) {
  SSortedMergeOperatorInfo* pInfo = pOperator->info;
5992

5993 5994 5995 5996
  SqlFunctionCtx* pCtx = pInfo->binfo.pCtx;
  for(int32_t i = 0; i < pBlock->info.numOfCols; ++i) {
    pCtx[i].size = 1;
  }
5997

5998 5999 6000 6001 6002 6003 6004 6005 6006 6007
  for(int32_t i = 0; i < pBlock->info.rows; ++i) {
    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 已提交
6008
        int32_t numOfRows = getNumOfResult(pInfo->binfo.pCtx, pOperator->numOfOutput, NULL);
6009
        //        setTagValueForMultipleRows(pCtx, pOperator->numOfOutput, numOfRows);
6010

6011
        // TODO check for available buffer;
H
Haojun Liao 已提交
6012

6013 6014 6015 6016 6017
        // next group info data
        pInfo->binfo.pRes->info.rows += numOfRows;
        for (int32_t j = 0; j < numOfExpr; ++j) {
          if (pCtx[j].functionId < 0) {
            continue;
6018
          }
6019

H
Haojun Liao 已提交
6020
          pCtx[j].fpSet.process(&pCtx[j]);
6021
        }
6022 6023 6024

        doMergeResultImpl(pInfo, pCtx, numOfExpr, i);
        pInfo->hasGroupVal = saveCurrentTuple(pInfo->groupVal, pInfo->groupInfo, pBlock, i);
H
Haojun Liao 已提交
6025
      }
6026 6027 6028 6029
    }
  }
}

6030 6031 6032
static SSDataBlock* doMerge(SOperatorInfo* pOperator) {
  SSortedMergeOperatorInfo* pInfo = pOperator->info;
  SSortHandle* pHandle = pInfo->pSortHandle;
6033

6034 6035 6036 6037 6038
  SSDataBlock* pDataBlock = createOneDataBlock(pInfo->binfo.pRes);
  blockDataEnsureCapacity(pDataBlock, pInfo->binfo.capacity);

  while(1) {

6039
    blockDataCleanup(pDataBlock);
6040
    while (1) {
H
Haojun Liao 已提交
6041
      STupleHandle* pTupleHandle = tsortNextTuple(pHandle);
6042 6043
      if (pTupleHandle == NULL) {
        break;
6044
      }
6045

6046 6047 6048 6049 6050
      // build datablock for merge for one group
      appendOneRowToDataBlock(pDataBlock, pTupleHandle);
      if (pDataBlock->info.rows >= pInfo->binfo.capacity) {
        break;
      }
6051
    }
6052

6053 6054 6055
    if (pDataBlock->info.rows == 0) {
      break;
    }
6056

6057 6058 6059 6060 6061
    setInputDataBlock(pOperator, pInfo->binfo.pCtx, pDataBlock, TSDB_ORDER_ASC);
    //  updateOutputBuf(&pInfo->binfo, &pAggInfo->bufCapacity, pBlock->info.rows * pAggInfo->resultRowFactor, pOperator->pRuntimeEnv, true);
    doMergeImpl(pOperator, pOperator->numOfOutput, pDataBlock);
    // flush to tuple store, and after all data have been handled, return to upstream node or sink node
  }
6062

6063
  doFinalizeResultImpl(pInfo->binfo.pCtx, pOperator->numOfOutput);
H
Haojun Liao 已提交
6064
  int32_t numOfRows = getNumOfResult(pInfo->binfo.pCtx, pOperator->numOfOutput, NULL);
6065
  //        setTagValueForMultipleRows(pCtx, pOperator->numOfOutput, numOfRows);
6066

6067
  // TODO check for available buffer;
6068

6069 6070 6071 6072
  // next group info data
  pInfo->binfo.pRes->info.rows += numOfRows;
  return (pInfo->binfo.pRes->info.rows > 0)? pInfo->binfo.pRes:NULL;
}
6073

H
Haojun Liao 已提交
6074
static SSDataBlock* doSortedMerge(SOperatorInfo *pOperator, bool* newgroup) {
6075 6076
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
6077 6078
  }

6079
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
6080
  SSortedMergeOperatorInfo* pInfo = pOperator->info;
H
Haojun Liao 已提交
6081
  if (pOperator->status == OP_RES_TO_RETURN) {
6082
    return getSortedBlockData(pInfo->pSortHandle, pInfo->binfo.pRes, pInfo->hasVarCol, pInfo->binfo.capacity);
6083 6084
  }

H
Haojun Liao 已提交
6085
  SSchema* p = blockDataExtractSchema(pInfo->binfo.pRes, NULL);
6086
  int32_t numOfBufPage = pInfo->sortBufSize / pInfo->bufPageSize;
H
Haojun Liao 已提交
6087
  pInfo->pSortHandle = tsortCreateSortHandle(pInfo->orderInfo, pInfo->nullFirst, SORT_MULTISOURCE_MERGE, pInfo->bufPageSize,
H
Haojun Liao 已提交
6088
                                        numOfBufPage, p, pInfo->binfo.pRes->info.numOfCols, "GET_TASKID(pTaskInfo)");
H
Haojun Liao 已提交
6089

6090
  tfree(p);
H
Haojun Liao 已提交
6091
  tsortSetFetchRawDataFp(pInfo->pSortHandle, loadNextDataBlock);
6092

6093
  for(int32_t i = 0; i < pOperator->numOfDownstream; ++i) {
H
Haojun Liao 已提交
6094
    SGenericSource* ps = calloc(1, sizeof(SGenericSource));
H
Haojun Liao 已提交
6095
    ps->param = pOperator->pDownstream[i];
H
Haojun Liao 已提交
6096
    tsortAddSource(pInfo->pSortHandle, ps);
6097 6098
  }

H
Haojun Liao 已提交
6099
  int32_t code = tsortOpen(pInfo->pSortHandle);
6100
  if (code != TSDB_CODE_SUCCESS) {
6101
    longjmp(pTaskInfo->env, terrno);
6102 6103
  }

H
Haojun Liao 已提交
6104
  pOperator->status = OP_RES_TO_RETURN;
6105
  return doMerge(pOperator);
6106
}
6107

H
Haojun Liao 已提交
6108
static SArray* createBlockOrder(SExprInfo* pExprInfo, int32_t numOfCols, SArray* pOrderVal) {
6109 6110 6111 6112 6113 6114 6115 6116
  SArray* pOrderInfo = taosArrayInit(1, sizeof(SBlockOrderInfo));

  size_t numOfOrder = taosArrayGetSize(pOrderVal);
  for (int32_t j = 0; j < numOfOrder; ++j) {
    SBlockOrderInfo orderInfo = {0};
    SOrder*         pOrder = taosArrayGet(pOrderVal, j);
    orderInfo.order = pOrder->order;

H
Haojun Liao 已提交
6117 6118
    for (int32_t i = 0; i < numOfCols; ++i) {
      SExprInfo* pExpr = &pExprInfo[i];
H
Haojun Liao 已提交
6119
      if (pExpr->base.resSchema.colId == pOrder->col.colId) {
6120 6121 6122
        orderInfo.colIndex = i;
        break;
      }
6123
    }
6124

6125 6126
    taosArrayPush(pOrderInfo, &orderInfo);
  }
H
Haojun Liao 已提交
6127

6128
  return pOrderInfo;
H
Haojun Liao 已提交
6129 6130
}

H
Haojun Liao 已提交
6131
static int32_t initGroupCol(SExprInfo* pExprInfo, int32_t numOfCols, SArray* pGroupInfo, SSortedMergeOperatorInfo* pInfo) {
6132 6133
  if (pGroupInfo == NULL || taosArrayGetSize(pGroupInfo) == 0) {
    return 0;
H
Haojun Liao 已提交
6134 6135
  }

6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146
  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;
  }

  size_t  numOfGroupCol = taosArrayGetSize(pInfo->groupInfo);
  for(int32_t i = 0; i < numOfGroupCol; ++i) {
    SColumn* pCol = taosArrayGet(pGroupInfo, i);
H
Haojun Liao 已提交
6147 6148
    for(int32_t j = 0; j < numOfCols; ++j) {
      SExprInfo* pe = &pExprInfo[j];
H
Haojun Liao 已提交
6149
      if (pe->base.resSchema.colId == pCol->colId) {
6150 6151
        taosArrayPush(plist, pCol);
        taosArrayPush(pInfo->groupInfo, &j);
H
Haojun Liao 已提交
6152
        len += pCol->bytes;
6153 6154
        break;
      }
H
Haojun Liao 已提交
6155 6156 6157
    }
  }

6158
  ASSERT(taosArrayGetSize(pGroupInfo) == taosArrayGetSize(plist));
H
Haojun Liao 已提交
6159

6160 6161 6162 6163 6164
  pInfo->groupVal = calloc(1, (POINTER_BYTES * numOfGroupCol + len));
  if (pInfo->groupVal == NULL) {
    taosArrayDestroy(plist);
    return TSDB_CODE_OUT_OF_MEMORY;
  }
H
Haojun Liao 已提交
6165

6166 6167 6168 6169 6170
  int32_t offset = 0;
  char   *start = (char*)(pInfo->groupVal + (POINTER_BYTES * numOfGroupCol));
  for(int32_t i = 0; i < numOfGroupCol; ++i) {
    pInfo->groupVal[i] = start + offset;
    SColumn* pCol = taosArrayGet(plist, i);
H
Haojun Liao 已提交
6171
    offset += pCol->bytes;
6172
  }
H
Haojun Liao 已提交
6173

6174
  taosArrayDestroy(plist);
H
Haojun Liao 已提交
6175

6176 6177
  return TSDB_CODE_SUCCESS;
}
H
Haojun Liao 已提交
6178

H
Haojun Liao 已提交
6179
SOperatorInfo* createSortedMergeOperatorInfo(SOperatorInfo** downstream, int32_t numOfDownstream, SExprInfo* pExprInfo, int32_t num, SArray* pOrderVal, SArray* pGroupInfo, SExecTaskInfo* pTaskInfo) {
6180 6181 6182
  SSortedMergeOperatorInfo* pInfo = calloc(1, sizeof(SSortedMergeOperatorInfo));
  SOperatorInfo* pOperator = calloc(1, sizeof(SOperatorInfo));
  if (pInfo == NULL || pOperator == NULL) {
6183
    goto _error;
6184
  }
H
Haojun Liao 已提交
6185

H
Haojun Liao 已提交
6186
  pInfo->binfo.pCtx   = createSqlFunctionCtx_rv(pExprInfo, num, &pInfo->binfo.rowCellInfoOffset);
6187
  initResultRowInfo(&pInfo->binfo.resultRowInfo, (int32_t)1);
H
Haojun Liao 已提交
6188

6189 6190 6191
  if (pInfo->binfo.pCtx == NULL || pInfo->binfo.pRes == NULL) {
    goto _error;
  }
H
Haojun Liao 已提交
6192

H
Haojun Liao 已提交
6193
  int32_t code = doInitAggInfoSup(&pInfo->aggSup, pInfo->binfo.pCtx, num, pTaskInfo->id.str);
6194 6195 6196
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
H
Haojun Liao 已提交
6197

H
Haojun Liao 已提交
6198
  setFunctionResultOutput(&pInfo->binfo, &pInfo->aggSup, MAIN_SCAN, pTaskInfo);
H
Haojun Liao 已提交
6199
  code = initGroupCol(pExprInfo, num, pGroupInfo, pInfo);
6200 6201 6202
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
H
Haojun Liao 已提交
6203

6204 6205
//  pInfo->resultRowFactor = (int32_t)(getRowNumForMultioutput(pRuntimeEnv->pQueryAttr,
//      pRuntimeEnv->pQueryAttr->topBotQuery, false));
6206 6207
  pInfo->sortBufSize    = 1024 * 16; // 1MB
  pInfo->bufPageSize    = 1024;
H
Haojun Liao 已提交
6208
  pInfo->orderInfo      = createBlockOrder(pExprInfo, num, pOrderVal);
H
Haojun Liao 已提交
6209

6210
  pInfo->binfo.capacity = blockDataGetCapacityInRow(pInfo->binfo.pRes, pInfo->bufPageSize);
H
Haojun Liao 已提交
6211

6212
  pOperator->name         = "SortedMerge";
X
Xiaoyu Wang 已提交
6213
  // pOperator->operatorType = OP_SortedMerge;
6214
  pOperator->blockingOptr = true;
H
Haojun Liao 已提交
6215
  pOperator->status       = OP_NOT_OPENED;
6216
  pOperator->info         = pInfo;
H
Haojun Liao 已提交
6217 6218
  pOperator->numOfOutput  = num;
  pOperator->pExpr        = pExprInfo;
H
Haojun Liao 已提交
6219

6220
  pOperator->pTaskInfo    = pTaskInfo;
H
Haojun Liao 已提交
6221 6222
  pOperator->getNextFn    = doSortedMerge;
  pOperator->closeFn      = destroySortedMergeOperatorInfo;
H
Haojun Liao 已提交
6223

6224 6225 6226
  code = appendDownstream(pOperator, downstream, numOfDownstream);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
6227
  }
H
Haojun Liao 已提交
6228

6229
  return pOperator;
H
Haojun Liao 已提交
6230

6231 6232
  _error:
  if (pInfo != NULL) {
H
Haojun Liao 已提交
6233
    destroySortedMergeOperatorInfo(pInfo, num);
H
Haojun Liao 已提交
6234 6235
  }

6236 6237 6238 6239
  tfree(pInfo);
  tfree(pOperator);
  terrno = TSDB_CODE_QRY_OUT_OF_MEMORY;
  return NULL;
H
Haojun Liao 已提交
6240 6241
}

H
Haojun Liao 已提交
6242
static SSDataBlock* doSort(SOperatorInfo *pOperator, bool* newgroup) {
6243 6244 6245 6246
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

6247
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
6248
  SOrderOperatorInfo* pInfo = pOperator->info;
H
Haojun Liao 已提交
6249
  if (pOperator->status == OP_RES_TO_RETURN) {
6250
    return getSortedBlockData(pInfo->pSortHandle, pInfo->pDataBlock, pInfo->hasVarCol, pInfo->numOfRowsInRes);
H
Haojun Liao 已提交
6251 6252
  }

6253 6254
  SSchema* p = blockDataExtractSchema(pInfo->pDataBlock, NULL);
  int32_t numOfBufPage = pInfo->sortBufSize / pInfo->bufPageSize;
H
Haojun Liao 已提交
6255
  pInfo->pSortHandle = tsortCreateSortHandle(pInfo->orderInfo, pInfo->nullFirst, SORT_SINGLESOURCE_SORT, pInfo->bufPageSize,
6256
                                        numOfBufPage, p, pInfo->pDataBlock->info.numOfCols, "GET_TASKID(pTaskInfo)");
6257

6258
  tfree(p);
H
Haojun Liao 已提交
6259
  tsortSetFetchRawDataFp(pInfo->pSortHandle, loadNextDataBlock);
H
Haojun Liao 已提交
6260

H
Haojun Liao 已提交
6261 6262
  SGenericSource* ps = calloc(1, sizeof(SGenericSource));
  ps->param = pOperator;
H
Haojun Liao 已提交
6263
  tsortAddSource(pInfo->pSortHandle, ps);
6264

6265
  // TODO set error code;
H
Haojun Liao 已提交
6266
  int32_t code = tsortOpen(pInfo->pSortHandle);
6267
  if (code != TSDB_CODE_SUCCESS) {
6268
    longjmp(pTaskInfo->env, terrno);
6269
  }
6270

H
Haojun Liao 已提交
6271
  pOperator->status = OP_RES_TO_RETURN;
6272
  return getSortedBlockData(pInfo->pSortHandle, pInfo->pDataBlock, pInfo->hasVarCol, pInfo->numOfRowsInRes);
6273 6274
}

H
Haojun Liao 已提交
6275
SOperatorInfo *createOrderOperatorInfo(SOperatorInfo* downstream, SExprInfo* pExprInfo, int32_t numOfCols, SArray* pOrderVal, SExecTaskInfo* pTaskInfo) {
6276
  SOrderOperatorInfo* pInfo = calloc(1, sizeof(SOrderOperatorInfo));
H
Haojun Liao 已提交
6277 6278 6279
  SOperatorInfo* pOperator = calloc(1, sizeof(SOperatorInfo));
  if (pInfo == NULL || pOperator == NULL) {
    tfree(pInfo);
H
Haojun Liao 已提交
6280
    tfree(pOperator);
H
Haojun Liao 已提交
6281 6282 6283
    terrno = TSDB_CODE_QRY_OUT_OF_MEMORY;
    return NULL;
  }
6284

H
Haojun Liao 已提交
6285 6286 6287 6288
  pInfo->sortBufSize    = 1024 * 16; // 1MB
  pInfo->bufPageSize    = 1024;
  pInfo->numOfRowsInRes = 1024;

H
Haojun Liao 已提交
6289
  pInfo->orderInfo  = createBlockOrder(pExprInfo, numOfCols, pOrderVal);
6290

H
Haojun Liao 已提交
6291 6292
  for(int32_t i = 0; i < numOfCols; ++i) {
    if (IS_VAR_DATA_TYPE(pExprInfo[i].base.resSchema.type)) {
6293 6294 6295 6296 6297
      pInfo->hasVarCol = true;
      break;
    }
  }

6298
  if (pInfo->orderInfo == NULL || pInfo->pDataBlock == NULL) {
H
Haojun Liao 已提交
6299
    tfree(pOperator);
H
Haojun Liao 已提交
6300
    destroyOrderOperatorInfo(pInfo, numOfCols);
H
Haojun Liao 已提交
6301 6302 6303 6304 6305
    tfree(pInfo);

    terrno = TSDB_CODE_QRY_OUT_OF_MEMORY;
    return NULL;
  }
6306

H
Haojun Liao 已提交
6307
  pOperator->name          = "Order";
X
Xiaoyu Wang 已提交
6308
  pOperator->operatorType  = QUERY_NODE_PHYSICAL_PLAN_SORT;
6309
  pOperator->blockingOptr  = true;
H
Haojun Liao 已提交
6310
  pOperator->status        = OP_NOT_OPENED;
6311
  pOperator->info          = pInfo;
6312 6313

  pOperator->pTaskInfo     = pTaskInfo;
H
Haojun Liao 已提交
6314
  pOperator->getNextFn = doSort;
H
Haojun Liao 已提交
6315
  pOperator->closeFn = destroyOrderOperatorInfo;
6316

6317
  int32_t code = appendDownstream(pOperator, &downstream, 1);
6318 6319 6320 6321 6322 6323 6324 6325
  return pOperator;
}

static int32_t getTableScanOrder(STableScanInfo* pTableScanInfo) {
  return pTableScanInfo->order;
}

// this is a blocking operator
H
Haojun Liao 已提交
6326 6327 6328
static int32_t doOpenAggregateOptr(SOperatorInfo *pOperator) {
  if (OPTR_IS_OPENED(pOperator)) {
    return TSDB_CODE_SUCCESS;
6329 6330 6331
  }

  SAggOperatorInfo* pAggInfo = pOperator->info;
H
Haojun Liao 已提交
6332
  SOptrBasicInfo*   pInfo = &pAggInfo->binfo;
6333

H
Haojun Liao 已提交
6334
  int32_t        order = TSDB_ORDER_ASC;
H
Haojun Liao 已提交
6335
  SOperatorInfo* downstream = pOperator->pDownstream[0];
6336

H
Haojun Liao 已提交
6337 6338
  bool newgroup = true;
  while (1) {
H
Haojun Liao 已提交
6339
    publishOperatorProfEvent(downstream, QUERY_PROF_BEFORE_OPERATOR_EXEC);
H
Haojun Liao 已提交
6340
    SSDataBlock* pBlock = downstream->getNextFn(downstream, &newgroup);
H
Haojun Liao 已提交
6341
    publishOperatorProfEvent(downstream, QUERY_PROF_AFTER_OPERATOR_EXEC);
6342 6343 6344 6345 6346

    if (pBlock == NULL) {
      break;
    }

H
Haojun Liao 已提交
6347 6348 6349
    //    if (pAggInfo->current != NULL) {
    //      setTagValue(pOperator, pAggInfo->current->pTable, pInfo->pCtx, pOperator->numOfOutput);
    //    }
6350 6351 6352

    // the pDataBlock are always the same one, no need to call this again
    setInputDataBlock(pOperator, pInfo->pCtx, pBlock, order);
H
Haojun Liao 已提交
6353
    doAggregateImpl(pOperator, 0, pInfo->pCtx);
6354 6355
  }

6356
  finalizeQueryResult(pInfo->pCtx, pOperator->numOfOutput);
H
Haojun Liao 已提交
6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375

  OPTR_SET_OPENED(pOperator);
  return TSDB_CODE_SUCCESS;
}

static SSDataBlock* getAggregateResult(SOperatorInfo *pOperator, bool* newgroup) {
  SAggOperatorInfo *pAggInfo = pOperator->info;
  SOptrBasicInfo*   pInfo = &pAggInfo->binfo;

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

  SExecTaskInfo  *pTaskInfo = pOperator->pTaskInfo;
  pTaskInfo->code = pOperator->_openFn(pOperator);
  if (pTaskInfo->code != TSDB_CODE_SUCCESS) {
    return NULL;
  }

H
Haojun Liao 已提交
6376
  getNumOfResult(pInfo->pCtx, pOperator->numOfOutput, pInfo->pRes);
H
Haojun Liao 已提交
6377
  doSetOperatorCompleted(pOperator);
6378

H
Haojun Liao 已提交
6379
  return (blockDataGetNumOfRows(pInfo->pRes) != 0)? pInfo->pRes:NULL;
6380 6381
}

wmmhello's avatar
wmmhello 已提交
6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486
static void aggEncodeResultRow(SOperatorInfo* pOperator, char **result, int32_t *length) {
  SAggOperatorInfo *pAggInfo = pOperator->info;
  SAggSupporter   *pSup = &pAggInfo->aggSup;

  int32_t size = taosHashGetSize(pSup->pResultRowHashTable);
  size_t keyLen = POINTER_BYTES;    // estimate the key length
  int32_t totalSize = sizeof(int32_t) + size * (sizeof(int32_t) + keyLen + sizeof(int32_t) + pSup->resultRowSize);
  *result = calloc(1, totalSize);
  if(*result == NULL){
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return;
  }
  *(int32_t*)(*result) = size;
  int32_t offset = sizeof(int32_t);
  void *pIter = taosHashIterate(pSup->pResultRowHashTable, NULL);
  while (pIter) {
    void *key = taosHashGetKey(pIter, &keyLen);
    SResultRow **p1 = (SResultRow **)pIter;

    // recalculate the result size
    int32_t realTotalSize = offset + sizeof(int32_t) + keyLen + sizeof(int32_t) + pSup->resultRowSize;
    if (realTotalSize > totalSize){
      char *tmp = realloc(*result, realTotalSize);
      if (tmp == NULL){
        terrno = TSDB_CODE_OUT_OF_MEMORY;
        free(*result);
        *result = NULL;
        return;
      }else{
        *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);
    memcpy(*result + offset, *p1, pSup->resultRowSize);
    offset += pSup->resultRowSize;

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

  if(length) {
    *length = offset;
  }
  return;
}

static bool aggDecodeResultRow(SOperatorInfo* pOperator, char *result, int32_t length) {
  if (!result || length <= 0){
    return false;
  }

  SAggOperatorInfo *pAggInfo = pOperator->info;
  SAggSupporter    *pSup     = &pAggInfo->aggSup;
  SOptrBasicInfo   *pInfo    = &pAggInfo->binfo;

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

  int32_t offset = sizeof(int32_t);
  while(count-- > 0 && length > offset){
    int32_t keyLen = *(int32_t*)(result + offset);
    offset += sizeof(int32_t);

    uint64_t tableGroupId = *(uint64_t *)(result + offset);
    SResultRow *resultRow = getNewResultRow_rv(pSup->pResultBuf, tableGroupId, pSup->resultRowSize);
    if (!resultRow){
      terrno = TSDB_CODE_TSC_INVALID_INPUT;
      return false;
    }
    // add a new result set for a new group
    taosHashPut(pSup->pResultRowHashTable, result + offset, keyLen, &resultRow, POINTER_BYTES);

    offset += keyLen;
    int32_t valueLen = *(int32_t*)(result + offset);
    if (valueLen != pSup->resultRowSize){
      terrno = TSDB_CODE_TSC_INVALID_INPUT;
      return false;
    }
    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);

    pInfo->resultRowInfo.pPosition[pInfo->resultRowInfo.size++] = (SResultRowPosition) {.pageId = resultRow->pageId, .offset = resultRow->offset};
  }

  if (offset != length){
    terrno = TSDB_CODE_TSC_INVALID_INPUT;
    return false;
  }
  return true;
}

H
Haojun Liao 已提交
6487
static SSDataBlock* doMultiTableAggregate(SOperatorInfo *pOperator, bool* newgroup) {
6488 6489 6490 6491 6492 6493
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

  SAggOperatorInfo* pAggInfo = pOperator->info;
  SOptrBasicInfo* pInfo = &pAggInfo->binfo;
6494
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
6495 6496

  if (pOperator->status == OP_RES_TO_RETURN) {
6497
    toSDatablock(&pAggInfo->groupResInfo, pAggInfo->pResultBuf, pInfo->pRes, pAggInfo->binfo.capacity, pAggInfo->binfo.rowCellInfoOffset);
6498

H
Haojun Liao 已提交
6499
    if (pInfo->pRes->info.rows == 0 || !hasRemainDataInCurrentGroup(&pAggInfo->groupResInfo)) {
6500 6501 6502 6503 6504 6505
      pOperator->status = OP_EXEC_DONE;
    }

    return pInfo->pRes;
  }

6506
  // table scan order
H
Haojun Liao 已提交
6507
  int32_t order = TSDB_ORDER_ASC;
H
Haojun Liao 已提交
6508
  SOperatorInfo* downstream = pOperator->pDownstream[0];
6509 6510

  while(1) {
H
Haojun Liao 已提交
6511
    publishOperatorProfEvent(downstream, QUERY_PROF_BEFORE_OPERATOR_EXEC);
H
Haojun Liao 已提交
6512
    SSDataBlock* pBlock = downstream->getNextFn(downstream, newgroup);
H
Haojun Liao 已提交
6513
    publishOperatorProfEvent(downstream, QUERY_PROF_AFTER_OPERATOR_EXEC);
6514 6515 6516 6517 6518

    if (pBlock == NULL) {
      break;
    }

H
Haojun Liao 已提交
6519
//    setTagValue(pOperator, pRuntimeEnv->current->pTable, pInfo->pCtx, pOperator->numOfOutput);
H
Haojun Liao 已提交
6520
//    if (downstream->operatorType == OP_TableScan) {
H
Haojun Liao 已提交
6521
//      STableScanInfo* pScanInfo = downstream->info;
H
Haojun Liao 已提交
6522 6523
//      order = getTableScanOrder(pScanInfo);
//    }
6524 6525 6526 6527 6528

    // the pDataBlock are always the same one, no need to call this again
    setInputDataBlock(pOperator, pInfo->pCtx, pBlock, order);

    TSKEY key = 0;
6529
    if (order == TSDB_ORDER_ASC) {
6530 6531 6532 6533 6534 6535 6536
      key = pBlock->info.window.ekey;
      TSKEY_MAX_ADD(key, 1);
    } else {
      key = pBlock->info.window.skey;
      TSKEY_MIN_SUB(key, -1);
    }
    
6537
    setExecutionContext(pOperator->numOfOutput, pAggInfo->current->groupIndex, key, pTaskInfo, pAggInfo->current, pAggInfo);
H
Haojun Liao 已提交
6538
    doAggregateImpl(pOperator, 0, pInfo->pCtx);
6539 6540 6541 6542
  }

  pOperator->status = OP_RES_TO_RETURN;
  closeAllResultRows(&pInfo->resultRowInfo);
6543
  updateNumOfRowsInResultRows(pInfo->pCtx, pOperator->numOfOutput, &pInfo->resultRowInfo, pInfo->rowCellInfoOffset);
6544

H
Haojun Liao 已提交
6545
  initGroupResInfo(&pAggInfo->groupResInfo, &pInfo->resultRowInfo);
6546
  toSDatablock(&pAggInfo->groupResInfo, pAggInfo->pResultBuf, pInfo->pRes, pAggInfo->binfo.capacity, pAggInfo->binfo.rowCellInfoOffset);
6547

H
Haojun Liao 已提交
6548
  if (pInfo->pRes->info.rows == 0 || !hasRemainDataInCurrentGroup(&pAggInfo->groupResInfo)) {
6549 6550 6551 6552 6553 6554
    doSetOperatorCompleted(pOperator);
  }

  return pInfo->pRes;
}

H
Haojun Liao 已提交
6555
static SSDataBlock* doProjectOperation(SOperatorInfo *pOperator, bool* newgroup) {
6556 6557 6558 6559
  SProjectOperatorInfo* pProjectInfo = pOperator->info;
  SOptrBasicInfo *pInfo = &pProjectInfo->binfo;

  SSDataBlock* pRes = pInfo->pRes;
6560
  blockDataCleanup(pRes);
6561 6562

  if (pProjectInfo->existDataBlock) {  // TODO refactor
H
Haojun Liao 已提交
6563
//    STableQueryInfo* pTableQueryInfo = pRuntimeEnv->current;
6564 6565 6566 6567 6568
    SSDataBlock* pBlock = pProjectInfo->existDataBlock;
    pProjectInfo->existDataBlock = NULL;
    *newgroup = true;

    // todo dynamic set tags
H
Haojun Liao 已提交
6569
//    if (pTableQueryInfo != NULL) {
H
Haojun Liao 已提交
6570
//      setTagValue(pOperator, pTableQueryInfo->pTable, pInfo->pCtx, pOperator->numOfOutput);
H
Haojun Liao 已提交
6571
//    }
6572 6573

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

H
Haojun Liao 已提交
6576 6577
    blockDataEnsureCapacity(pInfo->pRes, pBlock->info.rows);
    projectApplyFunctions(pInfo->pRes, pInfo->pCtx, pOperator->numOfOutput);
6578

H
Haojun Liao 已提交
6579
    pRes->info.rows = getNumOfResult(pInfo->pCtx, pOperator->numOfOutput, NULL);
H
Haojun Liao 已提交
6580
    if (pRes->info.rows >= pProjectInfo->binfo.capacity*0.8) {
6581 6582 6583 6584 6585 6586
      copyTsColoum(pRes, pInfo->pCtx, pOperator->numOfOutput);
      resetResultRowEntryResult(pInfo->pCtx, pOperator->numOfOutput);
      return pRes;
    }
  }

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

6589 6590 6591
  while(1) {
    bool prevVal = *newgroup;

H
Haojun Liao 已提交
6592
    // The downstream exec may change the value of the newgroup, so use a local variable instead.
H
Haojun Liao 已提交
6593 6594 6595
    publishOperatorProfEvent(downstream, QUERY_PROF_BEFORE_OPERATOR_EXEC);
    SSDataBlock* pBlock = downstream->getNextFn(downstream, newgroup);
    publishOperatorProfEvent(downstream, QUERY_PROF_AFTER_OPERATOR_EXEC);
6596 6597 6598 6599

    if (pBlock == NULL) {
      assert(*newgroup == false);
      *newgroup = prevVal;
6600
      setTaskStatus(pOperator->pTaskInfo, TASK_COMPLETED);
6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614
      break;
    }

    // Return result of the previous group in the firstly.
    if (*newgroup) {
      if (pRes->info.rows > 0) {
        pProjectInfo->existDataBlock = pBlock;
        break;
      } else { // init output buffer for a new group data
        initCtxOutputBuffer(pInfo->pCtx, pOperator->numOfOutput);
      }
    }

    // todo dynamic set tags
H
Haojun Liao 已提交
6615 6616 6617 6618
    //    STableQueryInfo* pTableQueryInfo = pRuntimeEnv->current;
    //    if (pTableQueryInfo != NULL) {
    //      setTagValue(pOperator, pTableQueryInfo->pTable, pInfo->pCtx, pOperator->numOfOutput);
    //    }
6619 6620

    // the pDataBlock are always the same one, no need to call this again
H
Haojun Liao 已提交
6621
    setInputDataBlock(pOperator, pInfo->pCtx, pBlock, TSDB_ORDER_ASC);
6622
    updateOutputBuf(pInfo, &pInfo->capacity, pBlock->info.rows);
6623

H
Haojun Liao 已提交
6624
    projectApplyFunctions(pInfo->pRes, pInfo->pCtx, pOperator->numOfOutput);
H
Haojun Liao 已提交
6625
    if (pRes->info.rows >= pProjectInfo->threshold) {
6626 6627 6628
      break;
    }
  }
H
Haojun Liao 已提交
6629

6630 6631 6632 6633
  copyTsColoum(pRes, pInfo->pCtx, pOperator->numOfOutput);
  return (pInfo->pRes->info.rows > 0)? pInfo->pRes:NULL;
}

H
Haojun Liao 已提交
6634
static SSDataBlock* doLimit(SOperatorInfo *pOperator, bool* newgroup) {
6635 6636 6637 6638 6639 6640 6641
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

  SLimitOperatorInfo* pInfo = pOperator->info;

  SSDataBlock* pBlock = NULL;
H
Haojun Liao 已提交
6642 6643
  SOperatorInfo* pDownstream = pOperator->pDownstream[0];

6644
  while (1) {
H
Haojun Liao 已提交
6645 6646 6647
    publishOperatorProfEvent(pDownstream, QUERY_PROF_BEFORE_OPERATOR_EXEC);
    pBlock = pDownstream->getNextFn(pDownstream, newgroup);
    publishOperatorProfEvent(pDownstream, QUERY_PROF_AFTER_OPERATOR_EXEC);
6648 6649 6650 6651 6652 6653

    if (pBlock == NULL) {
      doSetOperatorCompleted(pOperator);
      return NULL;
    }

H
Haojun Liao 已提交
6654
    if (pInfo->currentOffset == 0) {
6655
      break;
H
Haojun Liao 已提交
6656 6657 6658 6659
    } else if (pInfo->currentOffset >= pBlock->info.rows) {
      pInfo->currentOffset -= pBlock->info.rows;
    } else { // TODO handle the data movement
      int32_t remain = (int32_t)(pBlock->info.rows - pInfo->currentOffset);
6660 6661 6662 6663 6664 6665
      pBlock->info.rows = remain;

      for (int32_t i = 0; i < pBlock->info.numOfCols; ++i) {
        SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, i);

        int16_t bytes = pColInfoData->info.bytes;
H
Haojun Liao 已提交
6666
        memmove(pColInfoData->pData, pColInfoData->pData + bytes * pInfo->currentOffset, remain * bytes);
6667 6668
      }

H
Haojun Liao 已提交
6669
      pInfo->currentOffset = 0;
6670 6671 6672 6673
      break;
    }
  }

H
Haojun Liao 已提交
6674 6675 6676
  if (pInfo->currentRows + pBlock->info.rows >= pInfo->limit.limit) {
    pBlock->info.rows = (int32_t)(pInfo->limit.limit - pInfo->currentRows);
    pInfo->currentRows = pInfo->limit.limit;
6677 6678 6679

    doSetOperatorCompleted(pOperator);
  } else {
H
Haojun Liao 已提交
6680
    pInfo->currentRows += pBlock->info.rows;
6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692
  }

  return pBlock;
}

static SSDataBlock* doFilter(void* param, bool* newgroup) {
  SOperatorInfo *pOperator = (SOperatorInfo *)param;
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

  SFilterOperatorInfo* pCondInfo = pOperator->info;
H
Haojun Liao 已提交
6693
  STaskRuntimeEnv* pRuntimeEnv = pOperator->pRuntimeEnv;
6694 6695

  while (1) {
H
Haojun Liao 已提交
6696
    publishOperatorProfEvent(pOperator->pDownstream[0], QUERY_PROF_BEFORE_OPERATOR_EXEC);
H
Haojun Liao 已提交
6697
    SSDataBlock *pBlock = pOperator->pDownstream[0]->getNextFn(pOperator->pDownstream[0], newgroup);
H
Haojun Liao 已提交
6698
    publishOperatorProfEvent(pOperator->pDownstream[0], QUERY_PROF_AFTER_OPERATOR_EXEC);
6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716

    if (pBlock == NULL) {
      break;
    }

    doSetFilterColumnInfo(pCondInfo->pFilterInfo, pCondInfo->numOfFilterCols, pBlock);
    assert(pRuntimeEnv->pTsBuf == NULL);
    filterRowsInDataBlock(pRuntimeEnv, pCondInfo->pFilterInfo, pCondInfo->numOfFilterCols, pBlock, true);

    if (pBlock->info.rows > 0) {
      return pBlock;
    }
  }

  doSetOperatorCompleted(pOperator);
  return NULL;
}

6717 6718 6719
static int32_t doOpenIntervalAgg(SOperatorInfo *pOperator) {
  if (OPTR_IS_OPENED(pOperator)) {
    return TSDB_CODE_SUCCESS;
6720 6721
  }

H
Haojun Liao 已提交
6722
  STableIntervalOperatorInfo* pInfo = pOperator->info;
6723

6724 6725 6726
  //  int32_t order = pQueryAttr->order.order;
  //  STimeWindow win = pQueryAttr->window;
  bool newgroup = false;
H
Haojun Liao 已提交
6727
  SOperatorInfo* downstream = pOperator->pDownstream[0];
6728

6729
  while (1) {
H
Haojun Liao 已提交
6730
    publishOperatorProfEvent(downstream, QUERY_PROF_BEFORE_OPERATOR_EXEC);
6731
    SSDataBlock* pBlock = downstream->getNextFn(downstream, &newgroup);
H
Haojun Liao 已提交
6732
    publishOperatorProfEvent(downstream, QUERY_PROF_AFTER_OPERATOR_EXEC);
6733 6734 6735 6736 6737

    if (pBlock == NULL) {
      break;
    }

6738
    //    setTagValue(pOperator, pRuntimeEnv->current->pTable, pInfo->pCtx, pOperator->numOfOutput);
6739 6740

    // the pDataBlock are always the same one, no need to call this again
H
Haojun Liao 已提交
6741 6742
    setInputDataBlock(pOperator, pInfo->binfo.pCtx, pBlock, TSDB_ORDER_ASC);
    hashIntervalAgg(pOperator, &pInfo->binfo.resultRowInfo, pBlock, 0);
6743 6744
  }

H
Haojun Liao 已提交
6745
  closeAllResultRows(&pInfo->binfo.resultRowInfo);
H
Haojun Liao 已提交
6746
  finalizeMultiTupleQueryResult(pInfo->binfo.pCtx, pOperator->numOfOutput, pInfo->aggSup.pResultBuf, &pInfo->binfo.resultRowInfo, pInfo->binfo.rowCellInfoOffset);
6747

H
Haojun Liao 已提交
6748
  initGroupResInfo(&pInfo->groupResInfo, &pInfo->binfo.resultRowInfo);
6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766
  OPTR_SET_OPENED(pOperator);
  return TSDB_CODE_SUCCESS;
}

static SSDataBlock* doIntervalAgg(SOperatorInfo *pOperator, bool* newgroup) {
  STableIntervalOperatorInfo* pInfo = pOperator->info;
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;

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

  pTaskInfo->code = pOperator->_openFn(pOperator);
  if (pTaskInfo->code != TSDB_CODE_SUCCESS) {
    return NULL;
  }

  blockDataEnsureCapacity(pInfo->binfo.pRes, pInfo->binfo.capacity);
H
Haojun Liao 已提交
6767
  toSDatablock(&pInfo->groupResInfo, pInfo->aggSup.pResultBuf, pInfo->binfo.pRes, pInfo->binfo.capacity, pInfo->binfo.rowCellInfoOffset);
6768

H
Haojun Liao 已提交
6769
  if (pInfo->binfo.pRes->info.rows == 0 || !hasRemainDataInCurrentGroup(&pInfo->groupResInfo)) {
6770 6771 6772
    doSetOperatorCompleted(pOperator);
  }

H
Haojun Liao 已提交
6773
  return pInfo->binfo.pRes->info.rows == 0? NULL:pInfo->binfo.pRes;
6774 6775
}

H
Haojun Liao 已提交
6776
static SSDataBlock* doAllIntervalAgg(SOperatorInfo *pOperator, bool* newgroup) {
6777 6778 6779 6780 6781 6782
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

  STableIntervalOperatorInfo* pIntervalInfo = pOperator->info;

H
Haojun Liao 已提交
6783
  STaskRuntimeEnv* pRuntimeEnv = pOperator->pRuntimeEnv;
6784
  if (pOperator->status == OP_RES_TO_RETURN) {
H
Haojun Liao 已提交
6785
//    toSDatablock(&pRuntimeEnv->groupResInfo, pRuntimeEnv, pIntervalInfo->pRes);
6786

H
Haojun Liao 已提交
6787
    if (pIntervalInfo->binfo.pRes->info.rows == 0 || !hasRemainDataInCurrentGroup(&pRuntimeEnv->groupResInfo)) {
6788 6789 6790
      doSetOperatorCompleted(pOperator);
    }

H
Haojun Liao 已提交
6791
    return pIntervalInfo->binfo.pRes;
6792 6793
  }

H
Haojun Liao 已提交
6794
  STaskAttr* pQueryAttr = pRuntimeEnv->pQueryAttr;
6795 6796 6797
  int32_t order = pQueryAttr->order.order;
  STimeWindow win = pQueryAttr->window;

H
Haojun Liao 已提交
6798
  SOperatorInfo* downstream = pOperator->pDownstream[0];
6799 6800

  while(1) {
H
Haojun Liao 已提交
6801
    publishOperatorProfEvent(downstream, QUERY_PROF_BEFORE_OPERATOR_EXEC);
H
Haojun Liao 已提交
6802
    SSDataBlock* pBlock = downstream->getNextFn(downstream, newgroup);
H
Haojun Liao 已提交
6803
    publishOperatorProfEvent(downstream, QUERY_PROF_AFTER_OPERATOR_EXEC);
6804 6805 6806 6807 6808

    if (pBlock == NULL) {
      break;
    }

H
Haojun Liao 已提交
6809
//    setTagValue(pOperator, pRuntimeEnv->current->pTable, pIntervalInfo->pCtx, pOperator->numOfOutput);
6810 6811

    // the pDataBlock are always the same one, no need to call this again
H
Haojun Liao 已提交
6812 6813
    setInputDataBlock(pOperator, pIntervalInfo->binfo.pCtx, pBlock, pQueryAttr->order.order);
    hashAllIntervalAgg(pOperator, &pIntervalInfo->binfo.resultRowInfo, pBlock, 0);
6814 6815 6816 6817 6818 6819 6820
  }

  // restore the value
  pQueryAttr->order.order = order;
  pQueryAttr->window = win;

  pOperator->status = OP_RES_TO_RETURN;
H
Haojun Liao 已提交
6821
  closeAllResultRows(&pIntervalInfo->binfo.resultRowInfo);
6822
  setTaskStatus(pOperator->pTaskInfo, TASK_COMPLETED);
6823
  finalizeQueryResult(pIntervalInfo->binfo.pCtx, pOperator->numOfOutput);
6824

H
Haojun Liao 已提交
6825
  initGroupResInfo(&pRuntimeEnv->groupResInfo, &pIntervalInfo->binfo.resultRowInfo);
H
Haojun Liao 已提交
6826
//  toSDatablock(&pRuntimeEnv->groupResInfo, pRuntimeEnv, pIntervalInfo->pRes);
6827

H
Haojun Liao 已提交
6828
  if (pIntervalInfo->binfo.pRes->info.rows == 0 || !hasRemainDataInCurrentGroup(&pRuntimeEnv->groupResInfo)) {
6829 6830 6831
    pOperator->status = OP_EXEC_DONE;
  }

H
Haojun Liao 已提交
6832
  return pIntervalInfo->binfo.pRes->info.rows == 0? NULL:pIntervalInfo->binfo.pRes;
6833 6834
}

H
Haojun Liao 已提交
6835
static SSDataBlock* doSTableIntervalAgg(SOperatorInfo *pOperator, bool* newgroup) {
6836 6837 6838 6839 6840
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

  STableIntervalOperatorInfo* pIntervalInfo = pOperator->info;
H
Haojun Liao 已提交
6841
  STaskRuntimeEnv* pRuntimeEnv = pOperator->pRuntimeEnv;
6842 6843 6844 6845

  if (pOperator->status == OP_RES_TO_RETURN) {
    int64_t st = taosGetTimestampUs();

H
Haojun Liao 已提交
6846
//    copyToSDataBlock(NULL, 3000, pIntervalInfo->pRes, pIntervalInfo->rowCellInfoOffset);
H
Haojun Liao 已提交
6847
    if (pIntervalInfo->binfo.pRes->info.rows == 0 || !hasRemainData(&pRuntimeEnv->groupResInfo)) {
6848 6849
      doSetOperatorCompleted(pOperator);
    }
H
Haojun Liao 已提交
6850
    return pIntervalInfo->binfo.pRes;
6851 6852
  }

H
Haojun Liao 已提交
6853
  STaskAttr* pQueryAttr = pRuntimeEnv->pQueryAttr;
6854 6855
  int32_t order = pQueryAttr->order.order;

H
Haojun Liao 已提交
6856
  SOperatorInfo* downstream = pOperator->pDownstream[0];
6857 6858

  while(1) {
H
Haojun Liao 已提交
6859
    publishOperatorProfEvent(downstream, QUERY_PROF_BEFORE_OPERATOR_EXEC);
H
Haojun Liao 已提交
6860
    SSDataBlock* pBlock = downstream->getNextFn(downstream, newgroup);
H
Haojun Liao 已提交
6861
    publishOperatorProfEvent(downstream, QUERY_PROF_AFTER_OPERATOR_EXEC);
6862 6863 6864 6865 6866 6867 6868 6869

    if (pBlock == NULL) {
      break;
    }

    // the pDataBlock are always the same one, no need to call this again
    STableQueryInfo* pTableQueryInfo = pRuntimeEnv->current;

H
Haojun Liao 已提交
6870
//    setTagValue(pOperator, pTableQueryInfo->pTable, pIntervalInfo->pCtx, pOperator->numOfOutput);
H
Haojun Liao 已提交
6871
    setInputDataBlock(pOperator, pIntervalInfo->binfo.pCtx, pBlock, pQueryAttr->order.order);
6872 6873 6874 6875 6876 6877 6878 6879
    setIntervalQueryRange(pRuntimeEnv, pBlock->info.window.skey);

    hashIntervalAgg(pOperator, &pTableQueryInfo->resInfo, pBlock, pTableQueryInfo->groupIndex);
  }

  pOperator->status = OP_RES_TO_RETURN;
  pQueryAttr->order.order = order;   // TODO : restore the order
  doCloseAllTimeWindow(pRuntimeEnv);
6880
  setTaskStatus(pOperator->pTaskInfo, TASK_COMPLETED);
6881

H
Haojun Liao 已提交
6882
//  copyToSDataBlock(pRuntimeEnv, 3000, pIntervalInfo->pRes, pIntervalInfo->rowCellInfoOffset);
H
Haojun Liao 已提交
6883
  if (pIntervalInfo->binfo.pRes->info.rows == 0 || !hasRemainData(&pRuntimeEnv->groupResInfo)) {
6884 6885 6886
    pOperator->status = OP_EXEC_DONE;
  }

H
Haojun Liao 已提交
6887
  return pIntervalInfo->binfo.pRes;
6888 6889
}

H
Haojun Liao 已提交
6890
static SSDataBlock* doAllSTableIntervalAgg(SOperatorInfo *pOperator, bool* newgroup) {
6891 6892 6893 6894 6895
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

  STableIntervalOperatorInfo* pIntervalInfo = pOperator->info;
H
Haojun Liao 已提交
6896
  STaskRuntimeEnv* pRuntimeEnv = pOperator->pRuntimeEnv;
6897 6898

  if (pOperator->status == OP_RES_TO_RETURN) {
H
Haojun Liao 已提交
6899
//    copyToSDataBlock(pRuntimeEnv, 3000, pIntervalInfo->pRes, pIntervalInfo->rowCellInfoOffset);
H
Haojun Liao 已提交
6900
    if (pIntervalInfo->binfo.pRes->info.rows == 0 || !hasRemainData(&pRuntimeEnv->groupResInfo)) {
6901 6902 6903
      pOperator->status = OP_EXEC_DONE;
    }

H
Haojun Liao 已提交
6904
    return pIntervalInfo->binfo.pRes;
6905 6906
  }

H
Haojun Liao 已提交
6907
  STaskAttr* pQueryAttr = pRuntimeEnv->pQueryAttr;
6908 6909
  int32_t order = pQueryAttr->order.order;

H
Haojun Liao 已提交
6910
  SOperatorInfo* downstream = pOperator->pDownstream[0];
6911 6912

  while(1) {
H
Haojun Liao 已提交
6913
    publishOperatorProfEvent(downstream, QUERY_PROF_BEFORE_OPERATOR_EXEC);
H
Haojun Liao 已提交
6914
    SSDataBlock* pBlock = downstream->getNextFn(downstream, newgroup);
H
Haojun Liao 已提交
6915
    publishOperatorProfEvent(downstream, QUERY_PROF_AFTER_OPERATOR_EXEC);
6916 6917 6918 6919 6920 6921 6922 6923

    if (pBlock == NULL) {
      break;
    }

    // the pDataBlock are always the same one, no need to call this again
    STableQueryInfo* pTableQueryInfo = pRuntimeEnv->current;

H
Haojun Liao 已提交
6924
//    setTagValue(pOperator, pTableQueryInfo->pTable, pIntervalInfo->pCtx, pOperator->numOfOutput);
H
Haojun Liao 已提交
6925
    setInputDataBlock(pOperator, pIntervalInfo->binfo.pCtx, pBlock, pQueryAttr->order.order);
6926 6927 6928 6929 6930 6931 6932 6933
    setIntervalQueryRange(pRuntimeEnv, pBlock->info.window.skey);

    hashAllIntervalAgg(pOperator, &pTableQueryInfo->resInfo, pBlock, pTableQueryInfo->groupIndex);
  }

  pOperator->status = OP_RES_TO_RETURN;
  pQueryAttr->order.order = order;   // TODO : restore the order
  doCloseAllTimeWindow(pRuntimeEnv);
6934
  setTaskStatus(pOperator->pTaskInfo, TASK_COMPLETED);
6935 6936

  int64_t st = taosGetTimestampUs();
H
Haojun Liao 已提交
6937
//  copyToSDataBlock(pRuntimeEnv, 3000, pIntervalInfo->pRes, pIntervalInfo->rowCellInfoOffset);
H
Haojun Liao 已提交
6938
  if (pIntervalInfo->binfo.pRes->info.rows == 0 || !hasRemainData(&pRuntimeEnv->groupResInfo)) {
6939 6940 6941
    pOperator->status = OP_EXEC_DONE;
  }

H
Haojun Liao 已提交
6942 6943
//  SQInfo* pQInfo = pRuntimeEnv->qinfo;
//  pQInfo->summary.firstStageMergeTime += (taosGetTimestampUs() - st);
6944

H
Haojun Liao 已提交
6945
  return pIntervalInfo->binfo.pRes;
6946 6947 6948
}

static void doStateWindowAggImpl(SOperatorInfo* pOperator, SStateWindowOperatorInfo *pInfo, SSDataBlock *pSDataBlock) {
H
Haojun Liao 已提交
6949
  STaskRuntimeEnv* pRuntimeEnv = pOperator->pRuntimeEnv;
6950 6951 6952 6953 6954
  STableQueryInfo*  item = pRuntimeEnv->current;
  SColumnInfoData* pColInfoData = taosArrayGet(pSDataBlock->pDataBlock, pInfo->colIndex);

  SOptrBasicInfo* pBInfo = &pInfo->binfo;

H
Haojun Liao 已提交
6955
  bool    masterScan = IS_MAIN_SCAN(pRuntimeEnv);
6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996
  int16_t     bytes = pColInfoData->info.bytes;
  int16_t     type = pColInfoData->info.type;

  SColumnInfoData* pTsColInfoData = taosArrayGet(pSDataBlock->pDataBlock, 0);
  TSKEY* tsList = (TSKEY*)pTsColInfoData->pData;
  if (IS_REPEAT_SCAN(pRuntimeEnv) && !pInfo->reptScan) {
    pInfo->reptScan = true;
    tfree(pInfo->prevData);
  }

  pInfo->numOfRows = 0;
  for (int32_t j = 0; j < pSDataBlock->info.rows; ++j) {
    char* val = ((char*)pColInfoData->pData) + bytes * j;
    if (isNull(val, type)) {
      continue;
    }
    if (pInfo->prevData == NULL) {
      pInfo->prevData = malloc(bytes);
      memcpy(pInfo->prevData, val, bytes);
      pInfo->numOfRows = 1;
      pInfo->curWindow.skey = tsList[j];
      pInfo->curWindow.ekey = tsList[j];
      pInfo->start = j;

    } else if (memcmp(pInfo->prevData, val, bytes) == 0) {
      pInfo->curWindow.ekey = tsList[j];
      pInfo->numOfRows += 1;
      //pInfo->start = j;
      if (j == 0 && pInfo->start != 0) {
        pInfo->numOfRows = 1;
        pInfo->start = 0;
      }
    } else {
      SResultRow* pResult = NULL;
      pInfo->curWindow.ekey = pInfo->curWindow.skey;
      int32_t ret = setResultOutputBufByKey(pRuntimeEnv, &pBInfo->resultRowInfo, pSDataBlock->info.uid, &pInfo->curWindow, masterScan,
                                            &pResult, item->groupIndex, pBInfo->pCtx, pOperator->numOfOutput,
                                            pBInfo->rowCellInfoOffset);
      if (ret != TSDB_CODE_SUCCESS) {  // null data, too many state code
        longjmp(pRuntimeEnv->env, TSDB_CODE_QRY_APP_ERROR);
      }
H
Haojun Liao 已提交
6997 6998
//      doApplyFunctions(pRuntimeEnv, pBInfo->pCtx, &pInfo->curWindow, pInfo->start, pInfo->numOfRows, tsList,
//                       pSDataBlock->info.rows, pOperator->numOfOutput);
6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018

      pInfo->curWindow.skey = tsList[j];
      pInfo->curWindow.ekey = tsList[j];
      memcpy(pInfo->prevData, val, bytes);
      pInfo->numOfRows = 1;
      pInfo->start = j;

    }
  }

  SResultRow* pResult = NULL;

  pInfo->curWindow.ekey = pInfo->curWindow.skey;
  int32_t ret = setResultOutputBufByKey(pRuntimeEnv, &pBInfo->resultRowInfo, pSDataBlock->info.uid, &pInfo->curWindow, masterScan,
                                        &pResult, item->groupIndex, pBInfo->pCtx, pOperator->numOfOutput,
                                        pBInfo->rowCellInfoOffset);
  if (ret != TSDB_CODE_SUCCESS) {  // null data, too many state code
    longjmp(pRuntimeEnv->env, TSDB_CODE_QRY_APP_ERROR);
  }

H
Haojun Liao 已提交
7019 7020
//  doApplyFunctions(pRuntimeEnv, pBInfo->pCtx, &pInfo->curWindow, pInfo->start, pInfo->numOfRows, tsList,
//                   pSDataBlock->info.rows, pOperator->numOfOutput);
7021 7022
}

H
Haojun Liao 已提交
7023
static SSDataBlock* doStateWindowAgg(SOperatorInfo *pOperator, bool* newgroup) {
7024 7025 7026 7027 7028 7029 7030
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

  SStateWindowOperatorInfo* pWindowInfo = pOperator->info;
  SOptrBasicInfo* pBInfo = &pWindowInfo->binfo;

H
Haojun Liao 已提交
7031
  STaskRuntimeEnv* pRuntimeEnv = pOperator->pRuntimeEnv;
7032
  if (pOperator->status == OP_RES_TO_RETURN) {
H
Haojun Liao 已提交
7033
//    toSDatablock(&pRuntimeEnv->groupResInfo, pRuntimeEnv, pBInfo->pRes);
7034 7035 7036 7037 7038 7039 7040 7041

    if (pBInfo->pRes->info.rows == 0 || !hasRemainDataInCurrentGroup(&pRuntimeEnv->groupResInfo)) {
      pOperator->status = OP_EXEC_DONE;
    }

    return pBInfo->pRes;
  }

H
Haojun Liao 已提交
7042
  STaskAttr* pQueryAttr = pRuntimeEnv->pQueryAttr;
7043 7044
  int32_t order = pQueryAttr->order.order;
  STimeWindow win = pQueryAttr->window;
H
Haojun Liao 已提交
7045
  SOperatorInfo* downstream = pOperator->pDownstream[0];
7046
  while (1) {
H
Haojun Liao 已提交
7047
    publishOperatorProfEvent(downstream, QUERY_PROF_BEFORE_OPERATOR_EXEC);
H
Haojun Liao 已提交
7048
    SSDataBlock* pBlock = downstream->getNextFn(downstream, newgroup);
H
Haojun Liao 已提交
7049
    publishOperatorProfEvent(downstream, QUERY_PROF_AFTER_OPERATOR_EXEC);
7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066

    if (pBlock == NULL) {
      break;
    }
    setInputDataBlock(pOperator, pBInfo->pCtx, pBlock, pQueryAttr->order.order);
    if (pWindowInfo->colIndex == -1) {
      pWindowInfo->colIndex = getGroupbyColumnIndex(pRuntimeEnv->pQueryAttr->pGroupbyExpr, pBlock);
    }
    doStateWindowAggImpl(pOperator,  pWindowInfo, pBlock);
  }

  // restore the value
  pQueryAttr->order.order = order;
  pQueryAttr->window = win;

  pOperator->status = OP_RES_TO_RETURN;
  closeAllResultRows(&pBInfo->resultRowInfo);
7067
  setTaskStatus(pOperator->pTaskInfo, TASK_COMPLETED);
7068
  finalizeQueryResult(pBInfo->pCtx, pOperator->numOfOutput);
7069 7070

  initGroupResInfo(&pRuntimeEnv->groupResInfo, &pBInfo->resultRowInfo);
H
Haojun Liao 已提交
7071
//  toSDatablock(&pRuntimeEnv->groupResInfo, pRuntimeEnv, pBInfo->pRes);
7072 7073 7074 7075 7076 7077 7078 7079

  if (pBInfo->pRes->info.rows == 0 || !hasRemainDataInCurrentGroup(&pRuntimeEnv->groupResInfo)) {
    pOperator->status = OP_EXEC_DONE;
  }

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

H
Haojun Liao 已提交
7080
static SSDataBlock* doSessionWindowAgg(SOperatorInfo *pOperator, bool* newgroup) {
7081 7082 7083 7084
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

H
Haojun Liao 已提交
7085
  SSessionAggOperatorInfo* pWindowInfo = pOperator->info;
7086 7087 7088
  SOptrBasicInfo* pBInfo = &pWindowInfo->binfo;

  if (pOperator->status == OP_RES_TO_RETURN) {
H
Haojun Liao 已提交
7089
//    toSDatablock(&pRuntimeEnv->groupResInfo, pRuntimeEnv, pBInfo->pRes);
H
Haojun Liao 已提交
7090
    if (pBInfo->pRes->info.rows == 0/* || !hasRemainDataInCurrentGroup(&pRuntimeEnv->groupResInfo)*/) {
7091 7092 7093 7094 7095 7096
      pOperator->status = OP_EXEC_DONE;
    }

    return pBInfo->pRes;
  }

H
Haojun Liao 已提交
7097
  int32_t order = TSDB_ORDER_ASC;
H
Haojun Liao 已提交
7098
  SOperatorInfo* downstream = pOperator->pDownstream[0];
7099 7100

  while(1) {
H
Haojun Liao 已提交
7101
    publishOperatorProfEvent(downstream, QUERY_PROF_BEFORE_OPERATOR_EXEC);
H
Haojun Liao 已提交
7102
    SSDataBlock* pBlock = downstream->getNextFn(downstream, newgroup);
H
Haojun Liao 已提交
7103
    publishOperatorProfEvent(downstream, QUERY_PROF_AFTER_OPERATOR_EXEC);
7104 7105 7106 7107 7108
    if (pBlock == NULL) {
      break;
    }

    // the pDataBlock are always the same one, no need to call this again
H
Haojun Liao 已提交
7109
    setInputDataBlock(pOperator, pBInfo->pCtx, pBlock, order);
7110 7111 7112 7113 7114 7115
    doSessionWindowAggImpl(pOperator, pWindowInfo, pBlock);
  }

  // restore the value
  pOperator->status = OP_RES_TO_RETURN;
  closeAllResultRows(&pBInfo->resultRowInfo);
H
Haojun Liao 已提交
7116
//  setTaskStatus(pOperator->pTaskInfo, QUERY_COMPLETED);
7117
  finalizeQueryResult(pBInfo->pCtx, pOperator->numOfOutput);
7118

H
Haojun Liao 已提交
7119
//  initGroupResInfo(&pBInfo->groupResInfo, &pBInfo->resultRowInfo);
H
Haojun Liao 已提交
7120
//  toSDatablock(&pRuntimeEnv->groupResInfo, pRuntimeEnv, pBInfo->pRes);
H
Haojun Liao 已提交
7121
  if (pBInfo->pRes->info.rows == 0/* || !hasRemainDataInCurrentGroup(&pRuntimeEnv->groupResInfo)*/) {
7122 7123 7124 7125 7126 7127
    pOperator->status = OP_EXEC_DONE;
  }

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

H
Haojun Liao 已提交
7128
static SSDataBlock* hashGroupbyAggregate(SOperatorInfo *pOperator, bool* newgroup) {
7129 7130 7131 7132 7133 7134
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

  SGroupbyOperatorInfo *pInfo = pOperator->info;
  if (pOperator->status == OP_RES_TO_RETURN) {
H
Haojun Liao 已提交
7135 7136
    toSDatablock(&pInfo->groupResInfo, pInfo->aggSup.pResultBuf, pInfo->binfo.pRes, pInfo->binfo.capacity, pInfo->binfo.rowCellInfoOffset);
    if (pInfo->binfo.pRes->info.rows == 0|| !hasRemainDataInCurrentGroup(&pInfo->groupResInfo)) {
7137 7138 7139 7140 7141
      pOperator->status = OP_EXEC_DONE;
    }
    return pInfo->binfo.pRes;
  }

H
Haojun Liao 已提交
7142
  int32_t order = TSDB_ORDER_ASC;
H
Haojun Liao 已提交
7143
  SOperatorInfo* downstream = pOperator->pDownstream[0];
7144 7145

  while(1) {
H
Haojun Liao 已提交
7146
    publishOperatorProfEvent(downstream, QUERY_PROF_BEFORE_OPERATOR_EXEC);
H
Haojun Liao 已提交
7147
    SSDataBlock* pBlock = downstream->getNextFn(downstream, newgroup);
H
Haojun Liao 已提交
7148
    publishOperatorProfEvent(downstream, QUERY_PROF_AFTER_OPERATOR_EXEC);
7149 7150 7151 7152 7153
    if (pBlock == NULL) {
      break;
    }

    // the pDataBlock are always the same one, no need to call this again
H
Haojun Liao 已提交
7154
    setInputDataBlock(pOperator, pInfo->binfo.pCtx, pBlock, order);
H
Haojun Liao 已提交
7155
//    setTagValue(pOperator, pRuntimeEnv->current->pTable, pInfo->binfo.pCtx, pOperator->numOfOutput);
7156
    doHashGroupbyAgg(pOperator, pBlock);
7157 7158 7159 7160 7161
  }

  pOperator->status = OP_RES_TO_RETURN;
  closeAllResultRows(&pInfo->binfo.resultRowInfo);

H
Haojun Liao 已提交
7162
  finalizeMultiTupleQueryResult(pInfo->binfo.pCtx, pOperator->numOfOutput, pInfo->aggSup.pResultBuf, &pInfo->binfo.resultRowInfo, pInfo->binfo.rowCellInfoOffset);
H
Haojun Liao 已提交
7163
//  if (!pRuntimeEnv->pQueryAttr->stableQuery) { // finalize include the update of result rows
H
Haojun Liao 已提交
7164
//    finalizeQueryResult(pInfo->binfo.pCtx, pOperator->numOfOutput);
H
Haojun Liao 已提交
7165 7166 7167
//  } else {
//    updateNumOfRowsInResultRows(pInfo->binfo.pCtx, pOperator->numOfOutput, &pInfo->binfo.resultRowInfo, pInfo->binfo.rowCellInfoOffset);
//  }
7168

H
Haojun Liao 已提交
7169
  blockDataEnsureCapacity(pInfo->binfo.pRes, pInfo->binfo.capacity);
H
Haojun Liao 已提交
7170
  initGroupResInfo(&pInfo->groupResInfo, &pInfo->binfo.resultRowInfo);
H
Haojun Liao 已提交
7171 7172
  toSDatablock(&pInfo->groupResInfo, pInfo->aggSup.pResultBuf, pInfo->binfo.pRes, pInfo->binfo.capacity, pInfo->binfo.rowCellInfoOffset);
  if (pInfo->binfo.pRes->info.rows == 0 || !hasRemainDataInCurrentGroup(&pInfo->groupResInfo)) {
7173 7174 7175 7176 7177 7178
    pOperator->status = OP_EXEC_DONE;
  }

  return pInfo->binfo.pRes;
}

H
Haojun Liao 已提交
7179
static void doHandleRemainBlockForNewGroupImpl(SFillOperatorInfo *pInfo, SResultInfo* pResultInfo, bool* newgroup, SExecTaskInfo* pTaskInfo) {
7180
  pInfo->totalInputRows = pInfo->existNewGroupBlock->info.rows;
H
Haojun Liao 已提交
7181

7182
  int64_t ekey = Q_STATUS_EQUAL(pTaskInfo->status, TASK_COMPLETED)? pTaskInfo->window.ekey:pInfo->existNewGroupBlock->info.window.ekey;
7183 7184
  taosResetFillInfo(pInfo->pFillInfo, getFillInfoStart(pInfo->pFillInfo));

7185
  taosFillSetStartInfo(pInfo->pFillInfo, pInfo->existNewGroupBlock->info.rows, ekey);
7186 7187
  taosFillSetInputDataBlock(pInfo->pFillInfo, pInfo->existNewGroupBlock);

H
Haojun Liao 已提交
7188
  doFillTimeIntervalGapsInResults(pInfo->pFillInfo, pInfo->pRes, pResultInfo->capacity, pInfo->p);
7189 7190 7191 7192
  pInfo->existNewGroupBlock = NULL;
  *newgroup = true;
}

7193
static void doHandleRemainBlockFromNewGroup(SFillOperatorInfo *pInfo, SResultInfo *pResultInfo, bool *newgroup, SExecTaskInfo* pTaskInfo) {
7194 7195
  if (taosFillHasMoreResults(pInfo->pFillInfo)) {
    *newgroup = false;
H
Haojun Liao 已提交
7196 7197
    doFillTimeIntervalGapsInResults(pInfo->pFillInfo, pInfo->pRes, (int32_t)pResultInfo->capacity, pInfo->p);
    if (pInfo->pRes->info.rows > pResultInfo->threshold || (!pInfo->multigroupResult)) {
7198 7199 7200 7201 7202 7203
      return;
    }
  }

  // handle the cached new group data block
  if (pInfo->existNewGroupBlock) {
7204
    doHandleRemainBlockForNewGroupImpl(pInfo, pResultInfo, newgroup, pTaskInfo);
7205 7206 7207
  }
}

H
Haojun Liao 已提交
7208
static SSDataBlock* doFill(SOperatorInfo *pOperator, bool* newgroup) {
7209
  SFillOperatorInfo *pInfo = pOperator->info;
7210
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
7211

H
Haojun Liao 已提交
7212 7213
  SResultInfo* pResultInfo = &pOperator->resultInfo;
  blockDataCleanup(pInfo->pRes);
7214 7215 7216 7217
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

7218
  doHandleRemainBlockFromNewGroup(pInfo, pResultInfo, newgroup, pTaskInfo);
H
Haojun Liao 已提交
7219 7220 7221
  if (pInfo->pRes->info.rows > pResultInfo->threshold || (!pInfo->multigroupResult && pInfo->pRes->info.rows > 0)) {
    return pInfo->pRes;
  }
7222

H
Haojun Liao 已提交
7223
  SOperatorInfo* pDownstream = pOperator->pDownstream[0];
7224
  while(1) {
H
Haojun Liao 已提交
7225 7226 7227
    publishOperatorProfEvent(pDownstream, QUERY_PROF_BEFORE_OPERATOR_EXEC);
    SSDataBlock* pBlock = pDownstream->getNextFn(pDownstream, newgroup);
    publishOperatorProfEvent(pDownstream, QUERY_PROF_AFTER_OPERATOR_EXEC);
7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238

    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
7239
      taosFillSetStartInfo(pInfo->pFillInfo, 0, pTaskInfo->window.ekey);
7240 7241 7242 7243 7244 7245 7246
    } else {
      if (pBlock == NULL) {
        if (pInfo->totalInputRows == 0) {
          pOperator->status = OP_EXEC_DONE;
          return NULL;
        }

7247
        taosFillSetStartInfo(pInfo->pFillInfo, 0, pTaskInfo->window.ekey);
7248 7249 7250 7251 7252 7253 7254
      } else {
        pInfo->totalInputRows += pBlock->info.rows;
        taosFillSetStartInfo(pInfo->pFillInfo, pBlock->info.rows, pBlock->info.window.ekey);
        taosFillSetInputDataBlock(pInfo->pFillInfo, pBlock);
      }
    }

H
Haojun Liao 已提交
7255
    doFillTimeIntervalGapsInResults(pInfo->pFillInfo, pInfo->pRes, pInfo->capacity, pInfo->p);
7256 7257 7258 7259 7260

    // 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 已提交
7261
      if (pInfo->pRes->info.rows > pResultInfo->threshold || pBlock == NULL || (!pInfo->multigroupResult)) {
7262 7263 7264
        return pInfo->pRes;
      }

7265
      doHandleRemainBlockFromNewGroup(pInfo, pResultInfo, newgroup, pTaskInfo);
H
Haojun Liao 已提交
7266
      if (pInfo->pRes->info.rows > pOperator->resultInfo.threshold || pBlock == NULL) {
7267 7268 7269 7270
        return pInfo->pRes;
      }
    } else if (pInfo->existNewGroupBlock) {  // try next group
      assert(pBlock != NULL);
7271
      doHandleRemainBlockForNewGroupImpl(pInfo, pResultInfo, newgroup, pTaskInfo);
H
Haojun Liao 已提交
7272
      if (pInfo->pRes->info.rows > pResultInfo->threshold) {
7273 7274 7275 7276 7277 7278 7279 7280 7281
        return pInfo->pRes;
      }
    } else {
      return NULL;
    }
  }
}

// todo set the attribute of query scan count
H
Haojun Liao 已提交
7282
static int32_t getNumOfScanTimes(STaskAttr* pQueryAttr) {
7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297
  for(int32_t i = 0; i < pQueryAttr->numOfOutput; ++i) {
    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 已提交
7298 7299
  if (pOperator->closeFn != NULL) {
    pOperator->closeFn(pOperator->info, pOperator->numOfOutput);
7300 7301
  }

H
Haojun Liao 已提交
7302
  if (pOperator->pDownstream != NULL) {
H
Haojun Liao 已提交
7303
    for(int32_t i = 0; i < pOperator->numOfDownstream; ++i) {
H
Haojun Liao 已提交
7304
      destroyOperatorInfo(pOperator->pDownstream[i]);
7305 7306
    }

H
Haojun Liao 已提交
7307
    tfree(pOperator->pDownstream);
H
Haojun Liao 已提交
7308
    pOperator->numOfDownstream = 0;
7309 7310 7311 7312 7313 7314
  }

  tfree(pOperator->info);
  tfree(pOperator);
}

H
Haojun Liao 已提交
7315
int32_t doInitAggInfoSup(SAggSupporter* pAggSup, SqlFunctionCtx *pCtx, int32_t numOfOutput, const char* pKey) {
7316 7317
  _hash_fn_t hashFn = taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY);

7318
  pAggSup->resultRowSize       = getResultRowSize(pCtx, numOfOutput);
7319 7320 7321 7322 7323 7324
  pAggSup->keyBuf              = calloc(1, sizeof(int64_t) + sizeof(int64_t) + POINTER_BYTES);
  pAggSup->pResultRowHashTable = taosHashInit(10, hashFn, true, HASH_NO_LOCK);
  pAggSup->pResultRowListSet   = taosHashInit(100, hashFn, false, HASH_NO_LOCK);
  pAggSup->pResultRowArrayList = taosArrayInit(10, sizeof(SResultRowCell));

  if (pAggSup->keyBuf == NULL || pAggSup->pResultRowArrayList == NULL || pAggSup->pResultRowListSet == NULL ||
7325
      pAggSup->pResultRowHashTable == NULL) {
7326 7327 7328
    return TSDB_CODE_OUT_OF_MEMORY;
  }

H
Haojun Liao 已提交
7329 7330 7331 7332 7333
  int32_t code = createDiskbasedBuf(&pAggSup->pResultBuf, 4096, 4096 * 256, pKey, "/tmp/");
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

7334 7335 7336
  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
7337
static void cleanupAggSup(SAggSupporter* pAggSup) {
7338 7339 7340 7341
  tfree(pAggSup->keyBuf);
  taosHashCleanup(pAggSup->pResultRowHashTable);
  taosHashCleanup(pAggSup->pResultRowListSet);
  taosArrayDestroy(pAggSup->pResultRowArrayList);
H
Haojun Liao 已提交
7342
  destroyDiskbasedBuf(pAggSup->pResultBuf);
7343 7344
}

H
Haojun Liao 已提交
7345
static int32_t initAggInfo(SOptrBasicInfo* pBasicInfo, SAggSupporter* pAggSup, SExprInfo* pExprInfo, int32_t numOfCols,
H
Haojun Liao 已提交
7346
                           int32_t numOfRows, SSDataBlock* pResultBlock, const char* pkey) {
H
Haojun Liao 已提交
7347 7348 7349 7350
  pBasicInfo->pCtx = createSqlFunctionCtx_rv(pExprInfo, numOfCols, &pBasicInfo->rowCellInfoOffset);
  pBasicInfo->pRes = pResultBlock;
  pBasicInfo->capacity = numOfRows;

H
Haojun Liao 已提交
7351
  doInitAggInfoSup(pAggSup, pBasicInfo->pCtx, numOfCols, pkey);
H
Haojun Liao 已提交
7352 7353 7354 7355 7356 7357
}

static STableQueryInfo* initTableQueryInfo(const STableGroupInfo* pTableGroupInfo) {
  STableQueryInfo* pTableQueryInfo = calloc(pTableGroupInfo->numOfTables, sizeof(STableQueryInfo));
  if (pTableQueryInfo == NULL) {
    return NULL;
H
Haojun Liao 已提交
7358
  }
H
Haojun Liao 已提交
7359 7360 7361 7362 7363 7364 7365

  int32_t index = 0;
  for(int32_t i = 0; i < taosArrayGetSize(pTableGroupInfo->pGroupList); ++i) {
    SArray* pa = taosArrayGetP(pTableGroupInfo->pGroupList, i);
    for(int32_t j = 0; j < taosArrayGetSize(pa); ++j) {
      STableKeyInfo* pk = taosArrayGet(pa, j);

H
Haojun Liao 已提交
7366
      STableQueryInfo* pTQueryInfo = &pTableQueryInfo[index++];
H
Haojun Liao 已提交
7367 7368 7369 7370 7371
      pTQueryInfo->uid        = pk->uid;
      pTQueryInfo->lastKey    = pk->lastKey;
      pTQueryInfo->groupIndex = i;
    }
  }
H
Haojun Liao 已提交
7372 7373

  STimeWindow win = {0, INT64_MAX};
H
Haojun Liao 已提交
7374 7375
  createTableQueryInfo(pTableQueryInfo, false, win);
  return pTableQueryInfo;
H
Haojun Liao 已提交
7376 7377
}

H
Haojun Liao 已提交
7378
SOperatorInfo* createAggregateOperatorInfo(SOperatorInfo* downstream, SExprInfo* pExprInfo, int32_t numOfCols, SSDataBlock* pResultBlock,
H
Haojun Liao 已提交
7379
                                           SExecTaskInfo* pTaskInfo, const STableGroupInfo* pTableGroupInfo) {
H
Haojun Liao 已提交
7380
  SAggOperatorInfo* pInfo = calloc(1, sizeof(SAggOperatorInfo));
H
Haojun Liao 已提交
7381 7382 7383 7384
  SOperatorInfo* pOperator = calloc(1, sizeof(SOperatorInfo));
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }
H
Haojun Liao 已提交
7385 7386

  //(int32_t)(getRowNumForMultioutput(pQueryAttr, pQueryAttr->topBotQuery, pQueryAttr->stableQuery));
H
Haojun Liao 已提交
7387
  int32_t numOfRows = 1;
H
Haojun Liao 已提交
7388
  int32_t code = initAggInfo(&pInfo->binfo, &pInfo->aggSup, pExprInfo, numOfCols, numOfRows, pResultBlock, pTaskInfo->id.str);
H
Haojun Liao 已提交
7389 7390
  pInfo->pTableQueryInfo = initTableQueryInfo(pTableGroupInfo);
  if (code != TSDB_CODE_SUCCESS || pInfo->pTableQueryInfo == NULL) {
H
Haojun Liao 已提交
7391 7392
    goto _error;
  }
H
Haojun Liao 已提交
7393

H
Haojun Liao 已提交
7394
  setFunctionResultOutput(&pInfo->binfo, &pInfo->aggSup, MAIN_SCAN, pTaskInfo);
7395 7396

  pOperator->name         = "TableAggregate";
X
Xiaoyu Wang 已提交
7397
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_AGG;
7398
  pOperator->blockingOptr = true;
H
Haojun Liao 已提交
7399
  pOperator->status       = OP_NOT_OPENED;
7400
  pOperator->info         = pInfo;
H
Haojun Liao 已提交
7401 7402
  pOperator->pExpr        = pExprInfo;
  pOperator->numOfOutput  = numOfCols;
7403

H
Haojun Liao 已提交
7404
  pOperator->pTaskInfo    = pTaskInfo;
H
Haojun Liao 已提交
7405 7406
  pOperator->_openFn      = doOpenAggregateOptr;
  pOperator->getNextFn    = getAggregateResult;
H
Haojun Liao 已提交
7407
  pOperator->closeFn      = destroyAggOperatorInfo;
wmmhello's avatar
wmmhello 已提交
7408 7409
  pOperator->encodeResultRow = aggEncodeResultRow;
  pOperator->decodeResultRow = aggDecodeResultRow;
H
Haojun Liao 已提交
7410 7411 7412 7413 7414

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

  return pOperator;
H
Haojun Liao 已提交
7417 7418 7419 7420 7421 7422
  _error:
  destroyAggOperatorInfo(pInfo, numOfCols);
  tfree(pInfo);
  tfree(pOperator);
  pTaskInfo->code = TSDB_CODE_OUT_OF_MEMORY;
  return NULL;
7423 7424 7425 7426 7427
}

static void doDestroyBasicInfo(SOptrBasicInfo* pInfo, int32_t numOfOutput) {
  assert(pInfo != NULL);

7428
  destroySqlFunctionCtx(pInfo->pCtx, numOfOutput);
7429 7430 7431
  tfree(pInfo->rowCellInfoOffset);

  cleanupResultRowInfo(&pInfo->resultRowInfo);
H
Haojun Liao 已提交
7432
  pInfo->pRes = blockDataDestroy(pInfo->pRes);
7433 7434
}

H
Haojun Liao 已提交
7435
void destroyBasicOperatorInfo(void* param, int32_t numOfOutput) {
7436 7437 7438
  SOptrBasicInfo* pInfo = (SOptrBasicInfo*) param;
  doDestroyBasicInfo(pInfo, numOfOutput);
}
H
Haojun Liao 已提交
7439 7440

void destroyStateWindowOperatorInfo(void* param, int32_t numOfOutput) {
7441 7442 7443 7444
  SStateWindowOperatorInfo* pInfo = (SStateWindowOperatorInfo*) param;
  doDestroyBasicInfo(&pInfo->binfo, numOfOutput);
  tfree(pInfo->prevData);
}
H
Haojun Liao 已提交
7445 7446

void destroyAggOperatorInfo(void* param, int32_t numOfOutput) {
7447 7448 7449
  SAggOperatorInfo* pInfo = (SAggOperatorInfo*) param;
  doDestroyBasicInfo(&pInfo->binfo, numOfOutput);
}
7450

H
Haojun Liao 已提交
7451 7452 7453 7454 7455 7456 7457
void destroyIntervalOperatorInfo(void* param, int32_t numOfOutput) {
  STableIntervalOperatorInfo* pInfo = (STableIntervalOperatorInfo*) param;
  doDestroyBasicInfo(&pInfo->binfo, numOfOutput);
  cleanupAggSup(&pInfo->aggSup);
}

void destroySWindowOperatorInfo(void* param, int32_t numOfOutput) {
H
Haojun Liao 已提交
7458
  SSessionAggOperatorInfo* pInfo = (SSessionAggOperatorInfo*) param;
7459 7460 7461
  doDestroyBasicInfo(&pInfo->binfo, numOfOutput);
}

H
Haojun Liao 已提交
7462
void destroySFillOperatorInfo(void* param, int32_t numOfOutput) {
7463 7464
  SFillOperatorInfo* pInfo = (SFillOperatorInfo*) param;
  pInfo->pFillInfo = taosDestroyFillInfo(pInfo->pFillInfo);
H
Haojun Liao 已提交
7465
  pInfo->pRes = blockDataDestroy(pInfo->pRes);
7466 7467 7468
  tfree(pInfo->p);
}

H
Haojun Liao 已提交
7469
void destroyGroupbyOperatorInfo(void* param, int32_t numOfOutput) {
7470 7471
  SGroupbyOperatorInfo* pInfo = (SGroupbyOperatorInfo*) param;
  doDestroyBasicInfo(&pInfo->binfo, numOfOutput);
7472 7473 7474
  tfree(pInfo->keyBuf);
  taosArrayDestroy(pInfo->pGroupCols);
  taosArrayDestroy(pInfo->pGroupColVals);
7475 7476
}

H
Haojun Liao 已提交
7477
static void destroyProjectOperatorInfo(void* param, int32_t numOfOutput) {
7478 7479 7480 7481
  SProjectOperatorInfo* pInfo = (SProjectOperatorInfo*) param;
  doDestroyBasicInfo(&pInfo->binfo, numOfOutput);
}

H
Haojun Liao 已提交
7482
static void destroyTagScanOperatorInfo(void* param, int32_t numOfOutput) {
7483
  STagScanInfo* pInfo = (STagScanInfo*) param;
H
Haojun Liao 已提交
7484
  pInfo->pRes = blockDataDestroy(pInfo->pRes);
7485 7486
}

H
Haojun Liao 已提交
7487
static void destroyOrderOperatorInfo(void* param, int32_t numOfOutput) {
7488
  SOrderOperatorInfo* pInfo = (SOrderOperatorInfo*) param;
H
Haojun Liao 已提交
7489 7490
  pInfo->pDataBlock = blockDataDestroy(pInfo->pDataBlock);

7491
  taosArrayDestroy(pInfo->orderInfo);
7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503
}

static void destroyConditionOperatorInfo(void* param, int32_t numOfOutput) {
  SFilterOperatorInfo* pInfo = (SFilterOperatorInfo*) param;
  doDestroyFilterInfo(pInfo->pFilterInfo, pInfo->numOfFilterCols);
}

static void destroyDistinctOperatorInfo(void* param, int32_t numOfOutput) {
  SDistinctOperatorInfo* pInfo = (SDistinctOperatorInfo*) param;
  taosHashCleanup(pInfo->pSet);
  tfree(pInfo->buf);
  taosArrayDestroy(pInfo->pDistinctDataInfo);
H
Haojun Liao 已提交
7504
  pInfo->pRes = blockDataDestroy(pInfo->pRes);
7505 7506
}

7507 7508 7509 7510 7511 7512 7513 7514 7515 7516
static void destroySysTableScannerOperatorInfo(void* param, int32_t numOfOutput) {
  SSysTableScanInfo* pInfo = (SSysTableScanInfo*) param;
  tsem_destroy(&pInfo->ready);
  blockDataDestroy(pInfo->pRes);

  if (pInfo->type == TSDB_MGMT_TABLE_TABLE) {
    metaCloseTbCursor(pInfo->pCur);
  }
}

H
Haojun Liao 已提交
7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527
void destroyExchangeOperatorInfo(void* param, int32_t numOfOutput) {
  SExchangeInfo* pExInfo = (SExchangeInfo*) param;
  taosArrayDestroy(pExInfo->pSources);
  taosArrayDestroy(pExInfo->pSourceDataInfo);
  if (pExInfo->pResult != NULL) {
    blockDataDestroy(pExInfo->pResult);
  }

  tsem_destroy(&pExInfo->ready);
}

H
Haojun Liao 已提交
7528
SOperatorInfo* createMultiTableAggOperatorInfo(SOperatorInfo* downstream, SExprInfo* pExprInfo, int32_t numOfCols, SSDataBlock* pResBlock, SExecTaskInfo* pTaskInfo, const STableGroupInfo* pTableGroupInfo) {
7529 7530
  SAggOperatorInfo* pInfo = calloc(1, sizeof(SAggOperatorInfo));

H
Haojun Liao 已提交
7531
  int32_t numOfRows = 1;
H
Haojun Liao 已提交
7532
  int32_t code = initAggInfo(&pInfo->binfo, &pInfo->aggSup, pExprInfo, numOfCols, numOfRows, pResBlock, pTaskInfo->id.str);
H
Haojun Liao 已提交
7533 7534 7535 7536
  pInfo->pTableQueryInfo = initTableQueryInfo(pTableGroupInfo);
  if (code != TSDB_CODE_SUCCESS || pInfo->pTableQueryInfo == NULL) {
    goto _error;
  }
H
Haojun Liao 已提交
7537 7538

  size_t  tableGroup = taosArrayGetSize(pTableGroupInfo->pGroupList);
7539
  initResultRowInfo(&pInfo->binfo.resultRowInfo, (int32_t)tableGroup);
7540 7541 7542

  SOperatorInfo* pOperator = calloc(1, sizeof(SOperatorInfo));
  pOperator->name         = "MultiTableAggregate";
X
Xiaoyu Wang 已提交
7543
  // pOperator->operatorType = OP_MultiTableAggregate;
7544
  pOperator->blockingOptr = true;
H
Haojun Liao 已提交
7545
  pOperator->status       = OP_NOT_OPENED;
7546
  pOperator->info         = pInfo;
H
Haojun Liao 已提交
7547 7548
  pOperator->pExpr        = pExprInfo;
  pOperator->numOfOutput  = numOfCols;
H
Haojun Liao 已提交
7549
  pOperator->pTaskInfo    = pTaskInfo;
7550

H
Haojun Liao 已提交
7551
  pOperator->getNextFn = doMultiTableAggregate;
H
Haojun Liao 已提交
7552
  pOperator->closeFn = destroyAggOperatorInfo;
H
Haojun Liao 已提交
7553 7554 7555 7556
  code = appendDownstream(pOperator, &downstream, 1);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
7557 7558

  return pOperator;
H
Haojun Liao 已提交
7559 7560 7561

_error:
  return NULL;
7562 7563
}

H
Haojun Liao 已提交
7564
SOperatorInfo* createProjectOperatorInfo(SOperatorInfo* downstream, SExprInfo* pExprInfo, int32_t num, SSDataBlock* pResBlock, SExecTaskInfo* pTaskInfo) {
7565
  SProjectOperatorInfo* pInfo = calloc(1, sizeof(SProjectOperatorInfo));
H
Haojun Liao 已提交
7566 7567 7568 7569
  SOperatorInfo* pOperator = calloc(1, sizeof(SOperatorInfo));
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }
7570

H
Haojun Liao 已提交
7571 7572
  pInfo->binfo.pRes = pResBlock;
  pInfo->binfo.pCtx = createSqlFunctionCtx_rv(pExprInfo, num, &pInfo->binfo.rowCellInfoOffset);
H
Haojun Liao 已提交
7573 7574 7575
  if (pInfo->binfo.pCtx == NULL) {
    goto _error;
  }
7576

H
Haojun Liao 已提交
7577
//  initResultRowInfo(&pBInfo->resultRowInfo, 8);
H
Haojun Liao 已提交
7578
//  setFunctionResultOutput(pBInfo, MAIN_SCAN);
7579 7580

  pOperator->name         = "ProjectOperator";
H
Haojun Liao 已提交
7581
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_PROJECT;
7582
  pOperator->blockingOptr = false;
H
Haojun Liao 已提交
7583
  pOperator->status       = OP_NOT_OPENED;
7584
  pOperator->info         = pInfo;
H
Haojun Liao 已提交
7585 7586 7587 7588
  pOperator->pExpr        = pExprInfo;
  pOperator->numOfOutput  = num;
  pOperator->_openFn      = operatorDummyOpenFn;
  pOperator->getNextFn    = doProjectOperation;
H
Haojun Liao 已提交
7589
  pOperator->closeFn      = destroyProjectOperatorInfo;
H
Haojun Liao 已提交
7590 7591

  pOperator->pTaskInfo    = pTaskInfo;
7592
  int32_t code = appendDownstream(pOperator, &downstream, 1);
H
Haojun Liao 已提交
7593
  if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
7594 7595
    goto _error;
  }
7596 7597

  return pOperator;
H
Haojun Liao 已提交
7598 7599 7600 7601

  _error:
  pTaskInfo->code = TSDB_CODE_OUT_OF_MEMORY;
  return NULL;
7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636
}

SColumnInfo* extractColumnFilterInfo(SExprInfo* pExpr, int32_t numOfOutput, int32_t* numOfFilterCols) {
#if 0
  SColumnInfo* pCols = calloc(numOfOutput, sizeof(SColumnInfo));

  int32_t numOfFilter = 0;
  for(int32_t i = 0; i < numOfOutput; ++i) {
    if (pExpr[i].base.flist.numOfFilters > 0) {
      numOfFilter += 1;
    }

    pCols[i].type  = pExpr[i].base.resSchema.type;
    pCols[i].bytes = pExpr[i].base.resSchema.bytes;
    pCols[i].colId = pExpr[i].base.resSchema.colId;

    pCols[i].flist.numOfFilters = pExpr[i].base.flist.numOfFilters;
    if (pCols[i].flist.numOfFilters != 0) { 
      pCols[i].flist.filterInfo   = calloc(pCols[i].flist.numOfFilters, sizeof(SColumnFilterInfo));
      memcpy(pCols[i].flist.filterInfo, pExpr[i].base.flist.filterInfo, pCols[i].flist.numOfFilters * sizeof(SColumnFilterInfo));
    } else {
      // avoid runtime error
      pCols[i].flist.filterInfo   = NULL; 
    }
  }

  assert(numOfFilter > 0);

  *numOfFilterCols = numOfFilter;
  return pCols;
#endif

  return 0;
}

H
Haojun Liao 已提交
7637
SOperatorInfo* createLimitOperatorInfo(SOperatorInfo* downstream, SLimit* pLimit, SExecTaskInfo* pTaskInfo) {
7638 7639
  SLimitOperatorInfo* pInfo = calloc(1, sizeof(SLimitOperatorInfo));
  SOperatorInfo* pOperator = calloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
7640 7641 7642 7643 7644 7645
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }

  pInfo->limit            = *pLimit;
  pInfo->currentOffset    = pLimit->offset;
7646 7647

  pOperator->name         = "LimitOperator";
H
Haojun Liao 已提交
7648
//  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_LIMIT;
7649
  pOperator->blockingOptr = false;
H
Haojun Liao 已提交
7650
  pOperator->status       = OP_NOT_OPENED;
H
Haojun Liao 已提交
7651
  pOperator->_openFn      = operatorDummyOpenFn;
H
Haojun Liao 已提交
7652
  pOperator->getNextFn    = doLimit;
7653
  pOperator->info         = pInfo;
H
Haojun Liao 已提交
7654
  pOperator->pTaskInfo    = pTaskInfo;
H
Haojun Liao 已提交
7655
  int32_t code = appendDownstream(pOperator, &downstream, 1);
7656 7657

  return pOperator;
H
Haojun Liao 已提交
7658 7659 7660 7661 7662
  _error:
  tfree(pInfo);
  tfree(pOperator);
  terrno = TSDB_CODE_OUT_OF_MEMORY;
  return NULL;
7663 7664
}

H
Haojun Liao 已提交
7665
SOperatorInfo* createIntervalOperatorInfo(SOperatorInfo* downstream, SExprInfo* pExprInfo, int32_t numOfCols, SSDataBlock* pResBlock, SInterval* pInterval,
7666
                                          const STableGroupInfo* pTableGroupInfo, SExecTaskInfo* pTaskInfo) {
7667
  STableIntervalOperatorInfo* pInfo = calloc(1, sizeof(STableIntervalOperatorInfo));
H
Haojun Liao 已提交
7668
  SOperatorInfo* pOperator = calloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
7669 7670 7671
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }
H
Haojun Liao 已提交
7672

7673
  pInfo->order     = TSDB_ORDER_ASC;
H
Haojun Liao 已提交
7674
  pInfo->precision = TSDB_TIME_PRECISION_MILLI;
7675 7676
  pInfo->win       = pTaskInfo->window;
  pInfo->interval  = *pInterval;
H
Haojun Liao 已提交
7677

7678 7679 7680 7681
  pInfo->win.skey = INT64_MIN;
  pInfo->win.ekey = INT64_MAX;

  int32_t numOfRows = 4096;
H
Haojun Liao 已提交
7682
  int32_t code = initAggInfo(&pInfo->binfo, &pInfo->aggSup, pExprInfo, numOfCols, numOfRows, pResBlock, pTaskInfo->id.str);
H
Haojun Liao 已提交
7683 7684 7685 7686
//  pInfo->pTableQueryInfo = initTableQueryInfo(pTableGroupInfo);
  if (code != TSDB_CODE_SUCCESS/* || pInfo->pTableQueryInfo == NULL*/) {
    goto _error;
  }
H
Haojun Liao 已提交
7687 7688

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

  pOperator->name         = "TimeIntervalAggOperator";
H
Haojun Liao 已提交
7691
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_INTERVAL;
7692
  pOperator->blockingOptr = true;
H
Haojun Liao 已提交
7693
  pOperator->status       = OP_NOT_OPENED;
H
Haojun Liao 已提交
7694
  pOperator->pExpr        = pExprInfo;
H
Haojun Liao 已提交
7695
  pOperator->pTaskInfo    = pTaskInfo;
H
Haojun Liao 已提交
7696
  pOperator->numOfOutput  = numOfCols;
7697
  pOperator->info         = pInfo;
7698
  pOperator->_openFn      = doOpenIntervalAgg;
H
Haojun Liao 已提交
7699 7700
  pOperator->getNextFn    = doIntervalAgg;
  pOperator->closeFn      = destroyIntervalOperatorInfo;
7701

H
Haojun Liao 已提交
7702
  code = appendDownstream(pOperator, &downstream, 1);
H
Haojun Liao 已提交
7703 7704 7705 7706
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }

7707
  return pOperator;
H
Haojun Liao 已提交
7708 7709 7710 7711 7712 7713 7714

  _error:
  destroyIntervalOperatorInfo(pInfo, numOfCols);
  tfree(pInfo);
  tfree(pOperator);
  pTaskInfo->code = code;
  return NULL;
7715 7716
}

H
Haojun Liao 已提交
7717
SOperatorInfo* createAllTimeIntervalOperatorInfo(STaskRuntimeEnv* pRuntimeEnv, SOperatorInfo* downstream, SExprInfo* pExpr, int32_t numOfOutput) {
7718 7719
  STableIntervalOperatorInfo* pInfo = calloc(1, sizeof(STableIntervalOperatorInfo));

H
Haojun Liao 已提交
7720
  pInfo->binfo.pCtx = createSqlFunctionCtx(pRuntimeEnv, pExpr, numOfOutput, &pInfo->binfo.rowCellInfoOffset);
H
Haojun Liao 已提交
7721
//  pInfo->binfo.pRes = createOutputBuf(pExpr, numOfOutput, pResultInfo->capacity);
H
Haojun Liao 已提交
7722
  initResultRowInfo(&pInfo->binfo.resultRowInfo, 8);
7723 7724 7725 7726

  SOperatorInfo* pOperator = calloc(1, sizeof(SOperatorInfo));

  pOperator->name         = "AllTimeIntervalAggOperator";
H
Haojun Liao 已提交
7727
//  pOperator->operatorType = OP_AllTimeWindow;
7728
  pOperator->blockingOptr = true;
H
Haojun Liao 已提交
7729
  pOperator->status       = OP_NOT_OPENED;
7730 7731 7732 7733
  pOperator->pExpr        = pExpr;
  pOperator->numOfOutput  = numOfOutput;
  pOperator->info         = pInfo;
  pOperator->pRuntimeEnv  = pRuntimeEnv;
H
Haojun Liao 已提交
7734
  pOperator->getNextFn = doAllIntervalAgg;
H
Haojun Liao 已提交
7735
  pOperator->closeFn = destroyBasicOperatorInfo;
7736

7737
    int32_t code = appendDownstream(pOperator, &downstream, 1);
7738 7739 7740
  return pOperator;
}

H
Haojun Liao 已提交
7741
SOperatorInfo* createStatewindowOperatorInfo(STaskRuntimeEnv* pRuntimeEnv, SOperatorInfo* downstream, SExprInfo* pExpr, int32_t numOfOutput) {
7742 7743 7744
  SStateWindowOperatorInfo* pInfo = calloc(1, sizeof(SStateWindowOperatorInfo));
  pInfo->colIndex   = -1;
  pInfo->reptScan   = false;
H
Haojun Liao 已提交
7745
  pInfo->binfo.pCtx = createSqlFunctionCtx(pRuntimeEnv, pExpr, numOfOutput, &pInfo->binfo.rowCellInfoOffset);
H
Haojun Liao 已提交
7746
//  pInfo->binfo.pRes = createOutputBuf(pExpr, numOfOutput, pResultInfo->capacity);
7747
  initResultRowInfo(&pInfo->binfo.resultRowInfo, 8);
7748 7749 7750

  SOperatorInfo* pOperator = calloc(1, sizeof(SOperatorInfo));
  pOperator->name         = "StateWindowOperator";
H
Haojun Liao 已提交
7751
//  pOperator->operatorType = OP_StateWindow;
7752
  pOperator->blockingOptr = true;
H
Haojun Liao 已提交
7753
  pOperator->status       = OP_NOT_OPENED;
7754 7755 7756 7757
  pOperator->pExpr        = pExpr;
  pOperator->numOfOutput  = numOfOutput;
  pOperator->info         = pInfo;
  pOperator->pRuntimeEnv  = pRuntimeEnv;
H
Haojun Liao 已提交
7758
  pOperator->getNextFn = doStateWindowAgg;
H
Haojun Liao 已提交
7759
  pOperator->closeFn = destroyStateWindowOperatorInfo;
7760

H
Haojun Liao 已提交
7761
  int32_t code = appendDownstream(pOperator, &downstream, 1);
7762 7763 7764
  return pOperator;
}

H
Haojun Liao 已提交
7765 7766
SOperatorInfo* createSessionAggOperatorInfo(SOperatorInfo* downstream, SExprInfo* pExprInfo, int32_t numOfCols, SSDataBlock* pResBlock, SExecTaskInfo* pTaskInfo) {
  SSessionAggOperatorInfo* pInfo = calloc(1, sizeof(SSessionAggOperatorInfo));
H
Haojun Liao 已提交
7767 7768 7769 7770
  SOperatorInfo* pOperator = calloc(1, sizeof(SOperatorInfo));
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }
H
Haojun Liao 已提交
7771

H
Haojun Liao 已提交
7772
  int32_t code = doInitAggInfoSup(&pInfo->aggSup, pInfo->binfo.pCtx, numOfCols, pTaskInfo->id.str);
H
Haojun Liao 已提交
7773 7774 7775
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
7776

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

H
Haojun Liao 已提交
7779 7780 7781
  pInfo->binfo.pRes       = pResBlock;
  pInfo->prevTs           = INT64_MIN;
  pInfo->reptScan         = false;
7782
  pOperator->name         = "SessionWindowAggOperator";
H
Haojun Liao 已提交
7783
//  pOperator->operatorType = OP_SessionWindow;
7784
  pOperator->blockingOptr = true;
H
Haojun Liao 已提交
7785
  pOperator->status       = OP_NOT_OPENED;
H
Haojun Liao 已提交
7786 7787
  pOperator->pExpr        = pExprInfo;
  pOperator->numOfOutput  = numOfCols;
7788
  pOperator->info         = pInfo;
H
Haojun Liao 已提交
7789 7790 7791
  pOperator->getNextFn    = doSessionWindowAgg;
  pOperator->closeFn      = destroySWindowOperatorInfo;
  pOperator->pTaskInfo    = pTaskInfo;
7792

H
Haojun Liao 已提交
7793
  code = appendDownstream(pOperator, &downstream, 1);
7794
  return pOperator;
H
Haojun Liao 已提交
7795 7796 7797 7798 7799 7800 7801 7802 7803 7804

  _error:
  if (pInfo != NULL) {
    destroySWindowOperatorInfo(pInfo, numOfCols);
  }

  tfree(pInfo);
  tfree(pOperator);
  pTaskInfo->code = code;
  return NULL;
7805 7806
}

H
Haojun Liao 已提交
7807
SOperatorInfo* createMultiTableTimeIntervalOperatorInfo(STaskRuntimeEnv* pRuntimeEnv, SOperatorInfo* downstream, SExprInfo* pExpr, int32_t numOfOutput) {
7808 7809
  STableIntervalOperatorInfo* pInfo = calloc(1, sizeof(STableIntervalOperatorInfo));

H
Haojun Liao 已提交
7810
  pInfo->binfo.pCtx = createSqlFunctionCtx(pRuntimeEnv, pExpr, numOfOutput, &pInfo->binfo.rowCellInfoOffset);
H
Haojun Liao 已提交
7811
//  pInfo->binfo.pRes = createOutputBuf(pExpr, numOfOutput, pResultInfo->capacity);
H
Haojun Liao 已提交
7812
  initResultRowInfo(&pInfo->binfo.resultRowInfo, 8);
7813 7814 7815

  SOperatorInfo* pOperator = calloc(1, sizeof(SOperatorInfo));
  pOperator->name         = "MultiTableTimeIntervalOperator";
H
Haojun Liao 已提交
7816
//  pOperator->operatorType = OP_MultiTableTimeInterval;
7817
  pOperator->blockingOptr = true;
H
Haojun Liao 已提交
7818
  pOperator->status       = OP_NOT_OPENED;
7819 7820 7821 7822 7823
  pOperator->pExpr        = pExpr;
  pOperator->numOfOutput  = numOfOutput;
  pOperator->info         = pInfo;
  pOperator->pRuntimeEnv  = pRuntimeEnv;

H
Haojun Liao 已提交
7824
  pOperator->getNextFn = doSTableIntervalAgg;
H
Haojun Liao 已提交
7825
  pOperator->closeFn = destroyBasicOperatorInfo;
7826

7827
    int32_t code = appendDownstream(pOperator, &downstream, 1);
7828 7829 7830
  return pOperator;
}

H
Haojun Liao 已提交
7831
SOperatorInfo* createAllMultiTableTimeIntervalOperatorInfo(STaskRuntimeEnv* pRuntimeEnv, SOperatorInfo* downstream, SExprInfo* pExpr, int32_t numOfOutput) {
7832 7833
  STableIntervalOperatorInfo* pInfo = calloc(1, sizeof(STableIntervalOperatorInfo));

H
Haojun Liao 已提交
7834
  pInfo->binfo.pCtx = createSqlFunctionCtx(pRuntimeEnv, pExpr, numOfOutput, &pInfo->binfo.rowCellInfoOffset);
H
Haojun Liao 已提交
7835
//  pInfo->binfo.pRes = createOutputBuf(pExpr, numOfOutput, pResultInfo->capacity);
H
Haojun Liao 已提交
7836
  initResultRowInfo(&pInfo->binfo.resultRowInfo, 8);
7837 7838 7839

  SOperatorInfo* pOperator = calloc(1, sizeof(SOperatorInfo));
  pOperator->name         = "AllMultiTableTimeIntervalOperator";
H
Haojun Liao 已提交
7840
//  pOperator->operatorType = OP_AllMultiTableTimeInterval;
7841
  pOperator->blockingOptr = true;
H
Haojun Liao 已提交
7842
  pOperator->status       = OP_NOT_OPENED;
7843 7844 7845 7846 7847
  pOperator->pExpr        = pExpr;
  pOperator->numOfOutput  = numOfOutput;
  pOperator->info         = pInfo;
  pOperator->pRuntimeEnv  = pRuntimeEnv;

H
Haojun Liao 已提交
7848
  pOperator->getNextFn = doAllSTableIntervalAgg;
H
Haojun Liao 已提交
7849
  pOperator->closeFn = destroyBasicOperatorInfo;
7850

7851
    int32_t code = appendDownstream(pOperator, &downstream, 1);
7852 7853 7854 7855

  return pOperator;
}

7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888
static int32_t initGroupOptrInfo(SGroupbyOperatorInfo *pInfo, SArray* pGroupColList) {
  pInfo->pGroupColVals = taosArrayInit(4, sizeof(SGroupKeys));
  if (pInfo->pGroupColVals == NULL) {
    return TSDB_CODE_OUT_OF_MEMORY;
  }

  int32_t numOfGroupCols = taosArrayGetSize(pGroupColList);
  for(int32_t i = 0; i < numOfGroupCols; ++i) {
    SColumn* pCol = taosArrayGet(pGroupColList, i);
    pInfo->groupKeyLen += pCol->bytes;

    struct SGroupKeys key = {0};
    key.bytes  = pCol->bytes;
    key.type   = pCol->type;
    key.isNull = false;
    key.pData  = calloc(1, pCol->bytes);
    if (key.pData == NULL) {
      return TSDB_CODE_OUT_OF_MEMORY;
    }

    taosArrayPush(pInfo->pGroupColVals, &key);
  }

  int32_t nullFlagSize = sizeof(int8_t) * numOfGroupCols;
  pInfo->keyBuf = calloc(1, pInfo->groupKeyLen + nullFlagSize);

  if (pInfo->keyBuf == NULL) {
    return TSDB_CODE_OUT_OF_MEMORY;
  }

  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
7889 7890
SOperatorInfo* createGroupOperatorInfo(SOperatorInfo* downstream, SExprInfo* pExprInfo, int32_t numOfCols, SSDataBlock* pResultBlock,
                                       SArray* pGroupColList, SExecTaskInfo* pTaskInfo, const STableGroupInfo* pTableGroupInfo) {
7891
  SGroupbyOperatorInfo* pInfo = calloc(1, sizeof(SGroupbyOperatorInfo));
H
Haojun Liao 已提交
7892 7893 7894 7895
  SOperatorInfo* pOperator = calloc(1, sizeof(SOperatorInfo));
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }
7896

H
Haojun Liao 已提交
7897 7898
  pInfo->pGroupCols = pGroupColList;
  initAggInfo(&pInfo->binfo, &pInfo->aggSup, pExprInfo, numOfCols, 4096, pResultBlock, pTaskInfo->id.str);
7899
  initResultRowInfo(&pInfo->binfo.resultRowInfo, 8);
7900

7901 7902 7903 7904 7905
  int32_t code = initGroupOptrInfo(pInfo, pGroupColList);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }

7906 7907
  pOperator->name         = "GroupbyAggOperator";
  pOperator->blockingOptr = true;
H
Haojun Liao 已提交
7908
  pOperator->status       = OP_NOT_OPENED;
H
Haojun Liao 已提交
7909
//  pOperator->operatorType = OP_Groupby;
H
Haojun Liao 已提交
7910 7911
  pOperator->pExpr        = pExprInfo;
  pOperator->numOfOutput  = numOfCols;
7912
  pOperator->info         = pInfo;
H
Haojun Liao 已提交
7913 7914 7915
  pOperator->_openFn      = operatorDummyOpenFn;
  pOperator->getNextFn    = hashGroupbyAggregate;
  pOperator->closeFn      = destroyGroupbyOperatorInfo;
7916

7917
  code = appendDownstream(pOperator, &downstream, 1);
7918
  return pOperator;
H
Haojun Liao 已提交
7919 7920 7921 7922 7923

  _error:
  tfree(pInfo);
  tfree(pOperator);
  return NULL;
7924 7925
}

H
Haojun Liao 已提交
7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952
static int32_t initFillInfo(SFillOperatorInfo* pInfo, SExprInfo* pExpr, int32_t numOfCols, int64_t* fillVal,
                         STimeWindow win, int32_t capacity, const char* id, SInterval* pInterval, int32_t fillType) {
  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;
  pInfo->pFillInfo =
      taosCreateFillInfo(order, w.skey, 0, capacity, numOfCols, pInterval->sliding,
                         pInterval->slidingUnit, (int8_t)pInterval->precision, fillType, pColInfo, id);

  pInfo->p = calloc(numOfCols, POINTER_BYTES);

  if (pInfo->pFillInfo == NULL || pInfo->p == NULL) {
    return TSDB_CODE_OUT_OF_MEMORY;
  } else {
    return TSDB_CODE_SUCCESS;
  }
}

SOperatorInfo* createFillOperatorInfo(SOperatorInfo* downstream, SExprInfo* pExpr, int32_t numOfCols, SInterval* pInterval, SSDataBlock* pResBlock,
    int32_t fillType, char* fillVal, bool multigroupResult, SExecTaskInfo* pTaskInfo) {
7953
  SFillOperatorInfo* pInfo = calloc(1, sizeof(SFillOperatorInfo));
H
Haojun Liao 已提交
7954 7955 7956
  SOperatorInfo* pOperator = calloc(1, sizeof(SOperatorInfo));

  pInfo->pRes             = pResBlock;
7957
  pInfo->multigroupResult = multigroupResult;
H
Haojun Liao 已提交
7958
  pInfo->intervalInfo     = *pInterval;
7959

H
Haojun Liao 已提交
7960
  SResultInfo* pResultInfo = &pOperator->resultInfo;
7961 7962 7963 7964
  int32_t code = initFillInfo(pInfo, pExpr, numOfCols, (int64_t*) fillVal, pTaskInfo->window, pResultInfo->capacity, pTaskInfo->id.str, pInterval, fillType);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
7965 7966 7967

  pOperator->name         = "FillOperator";
  pOperator->blockingOptr = false;
H
Haojun Liao 已提交
7968
  pOperator->status       = OP_NOT_OPENED;
H
Haojun Liao 已提交
7969
//  pOperator->operatorType = OP_Fill;
7970
  pOperator->pExpr        = pExpr;
H
Haojun Liao 已提交
7971
  pOperator->numOfOutput  = numOfCols;
7972
  pOperator->info         = pInfo;
H
Haojun Liao 已提交
7973 7974 7975
  pOperator->_openFn      = operatorDummyOpenFn;
  pOperator->getNextFn    = doFill;
  pOperator->pTaskInfo    = pTaskInfo;
7976

H
Haojun Liao 已提交
7977 7978
  pOperator->closeFn      = destroySFillOperatorInfo;

7979
  code = appendDownstream(pOperator, &downstream, 1);
7980
  return pOperator;
H
Haojun Liao 已提交
7981 7982 7983 7984 7985

  _error:
  tfree(pOperator);
  tfree(pInfo);
  return NULL;
7986 7987
}

H
Haojun Liao 已提交
7988
SOperatorInfo* createSLimitOperatorInfo(STaskRuntimeEnv* pRuntimeEnv, SOperatorInfo* downstream, SExprInfo* pExpr, int32_t numOfOutput, void* pMerger, bool multigroupResult) {
7989
  SSLimitOperatorInfo* pInfo = calloc(1, sizeof(SSLimitOperatorInfo));
H
Haojun Liao 已提交
7990
  SOperatorInfo* pOperator = calloc(1, sizeof(SOperatorInfo));
7991

H
Haojun Liao 已提交
7992 7993 7994
//  pInfo->orderColumnList = getResultGroupCheckColumns(pQueryAttr);
//  pInfo->slimit          = pQueryAttr->slimit;
//  pInfo->limit           = pQueryAttr->limit;
H
Haojun Liao 已提交
7995
//  pInfo->capacity        = pResultInfo->capacity;
H
Haojun Liao 已提交
7996 7997 7998
//  pInfo->threshold       = (int64_t)(pInfo->capacity * 0.8);
//  pInfo->currentOffset   = pQueryAttr->limit.offset;
//  pInfo->currentGroupOffset = pQueryAttr->slimit.offset;
7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017
  pInfo->multigroupResult= multigroupResult;

  // TODO refactor
  int32_t len = 0;
  for(int32_t i = 0; i < numOfOutput; ++i) {
    len += pExpr[i].base.resSchema.bytes;
  }

  int32_t numOfCols = (pInfo->orderColumnList != NULL)? (int32_t) taosArrayGetSize(pInfo->orderColumnList):0;
  pInfo->prevRow = calloc(1, (POINTER_BYTES * numOfCols + len));

  int32_t offset = POINTER_BYTES * numOfCols;
  for(int32_t i = 0; i < numOfCols; ++i) {
    pInfo->prevRow[i] = (char*)pInfo->prevRow + offset;

    SColIndex* index = taosArrayGet(pInfo->orderColumnList, i);
    offset += pExpr[index->colIndex].base.resSchema.bytes;
  }

H
Haojun Liao 已提交
8018
  pInfo->pRes = createOutputBuf(pExpr, numOfOutput, pOperator->resultInfo.capacity);
8019 8020 8021


  pOperator->name         = "SLimitOperator";
X
Xiaoyu Wang 已提交
8022
  // pOperator->operatorType = OP_SLimit;
8023
  pOperator->blockingOptr = false;
H
Haojun Liao 已提交
8024
  pOperator->status       = OP_NOT_OPENED;
8025
//  pOperator->exec         = doSLimit;
8026
  pOperator->info         = pInfo;
H
Haojun Liao 已提交
8027
  pOperator->pRuntimeEnv  = pRuntimeEnv;
H
Haojun Liao 已提交
8028
  pOperator->closeFn = destroySlimitOperatorInfo;
8029

H
Haojun Liao 已提交
8030
    int32_t code = appendDownstream(pOperator, &downstream, 1);
8031 8032 8033
  return pOperator;
}

H
Haojun Liao 已提交
8034
static SSDataBlock* doTagScan(SOperatorInfo *pOperator, bool* newgroup) {
8035 8036 8037 8038 8039 8040
#if 0
  SOperatorInfo* pOperator = (SOperatorInfo*) param;
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

H
Haojun Liao 已提交
8041
  STaskRuntimeEnv* pRuntimeEnv = pOperator->pRuntimeEnv;
H
Haojun Liao 已提交
8042
  int32_t maxNumOfTables = (int32_t)pResultInfo->capacity;
8043 8044 8045 8046 8047 8048 8049 8050 8051 8052

  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
H
Haojun Liao 已提交
8053
    STaskAttr* pQueryAttr = pRuntimeEnv->pQueryAttr;
8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064
    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) {
8065
      if (pQueryAttr->tagColList[i].colId == pExprInfo->base.pColumns->info.colId) {
8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096
        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;
8097
      if (pExprInfo->base.pColumns->info.colId == TSDB_TBNAME_COLUMN_INDEX) {
8098 8099
        data = tsdbGetTableName(item->pTable);
      } else {
8100
        data = tsdbGetTableTagVal(item->pTable, pExprInfo->base.pColumns->info.colId, type, bytes);
8101 8102 8103 8104 8105 8106
      }

      doSetTagValueToResultBuf(output, data, type, bytes);
      count += 1;
    }

8107
    //qDebug("QInfo:0x%"PRIx64" create (tableId, tag) info completed, rows:%d", GET_TASKID(pRuntimeEnv), count);
8108 8109 8110 8111 8112 8113
  } 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;
8114
    //qDebug("QInfo:0x%"PRIx64" create count(tbname) query, res:%d rows:1", GET_TASKID(pRuntimeEnv), count);
8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127
  } 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
8128
        if (TSDB_COL_IS_UD_COL(pExprInfo[j].base.pColumns->flag)) {
8129 8130 8131 8132 8133 8134 8135
          continue;
        }

        SColumnInfoData* pColInfo = taosArrayGet(pRes->pDataBlock, j);
        type  = pExprInfo[j].base.resSchema.type;
        bytes = pExprInfo[j].base.resSchema.bytes;

8136
        if (pExprInfo[j].base.pColumns->info.colId == TSDB_TBNAME_COLUMN_INDEX) {
8137 8138
          data = tsdbGetTableName(item->pTable);
        } else {
8139
          data = tsdbGetTableTagVal(item->pTable, pExprInfo[j].base.pColumns->info.colId, type, bytes);
8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152
        }

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

8153
    //qDebug("QInfo:0x%"PRIx64" create tag values results completed, rows:%d", GET_TASKID(pRuntimeEnv), count);
8154 8155 8156
  }

  if (pOperator->status == OP_EXEC_DONE) {
8157
    setTaskStatus(pOperator->pRuntimeEnv, TASK_COMPLETED);
8158 8159 8160 8161 8162 8163 8164 8165
  }

  pRes->info.rows = count;
  return (pRes->info.rows == 0)? NULL:pInfo->pRes;

#endif
}

H
Haojun Liao 已提交
8166
SOperatorInfo* createTagScanOperatorInfo(STaskRuntimeEnv* pRuntimeEnv, SExprInfo* pExpr, int32_t numOfOutput) {
8167
  STagScanInfo* pInfo = calloc(1, sizeof(STagScanInfo));
H
Haojun Liao 已提交
8168
//  pInfo->pRes = createOutputBuf(pExpr, numOfOutput, pResultInfo->capacity);
8169 8170 8171 8172 8173 8174 8175 8176 8177

  size_t numOfGroup = GET_NUM_OF_TABLEGROUP(pRuntimeEnv);
  assert(numOfGroup == 0 || numOfGroup == 1);

  pInfo->totalTables = pRuntimeEnv->tableqinfoGroupInfo.numOfTables;
  pInfo->curPos = 0;

  SOperatorInfo* pOperator = calloc(1, sizeof(SOperatorInfo));
  pOperator->name         = "SeqTableTagScan";
X
Xiaoyu Wang 已提交
8178
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_TAG_SCAN;
8179
  pOperator->blockingOptr = false;
H
Haojun Liao 已提交
8180
  pOperator->status       = OP_NOT_OPENED;
8181
  pOperator->info         = pInfo;
H
Haojun Liao 已提交
8182
  pOperator->getNextFn = doTagScan;
8183 8184 8185
  pOperator->pExpr        = pExpr;
  pOperator->numOfOutput  = numOfOutput;
  pOperator->pRuntimeEnv  = pRuntimeEnv;
H
Haojun Liao 已提交
8186
  pOperator->closeFn = destroyTagScanOperatorInfo;
8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237

  return pOperator;
}
static bool initMultiDistinctInfo(SDistinctOperatorInfo *pInfo, SOperatorInfo* pOperator, SSDataBlock *pBlock) {
  if (taosArrayGetSize(pInfo->pDistinctDataInfo) == pOperator->numOfOutput) {
     // distinct info already inited  
    return true;
  }
  for (int i = 0; i < pOperator->numOfOutput; i++) {
//    pInfo->totalBytes += pOperator->pExpr[i].base.colBytes;
  }
  for (int i = 0; i < pOperator->numOfOutput; i++) {
    int numOfBlock = (int)(taosArrayGetSize(pBlock->pDataBlock));
    assert(i < numOfBlock);
    for (int j = 0; j < numOfBlock; j++) {
      SColumnInfoData* pColDataInfo = taosArrayGet(pBlock->pDataBlock, j);
      if (pColDataInfo->info.colId == pOperator->pExpr[i].base.resSchema.colId) {
        SDistinctDataInfo item = {.index = j, .type = pColDataInfo->info.type, .bytes = pColDataInfo->info.bytes};
        taosArrayInsert(pInfo->pDistinctDataInfo, i, &item);
      }
    }
  }
  pInfo->totalBytes += (int32_t)strlen(MULTI_KEY_DELIM) * (pOperator->numOfOutput);
  pInfo->buf        =  calloc(1, pInfo->totalBytes);
  return  taosArrayGetSize(pInfo->pDistinctDataInfo) == pOperator->numOfOutput ? true : false;
}

static void buildMultiDistinctKey(SDistinctOperatorInfo *pInfo, SSDataBlock *pBlock, int32_t rowId) {
  char *p = pInfo->buf;
  memset(p, 0, pInfo->totalBytes); 

  for (int i = 0; i < taosArrayGetSize(pInfo->pDistinctDataInfo); i++) {
    SDistinctDataInfo* pDistDataInfo = (SDistinctDataInfo *)taosArrayGet(pInfo->pDistinctDataInfo, i); 
    SColumnInfoData*   pColDataInfo = taosArrayGet(pBlock->pDataBlock, pDistDataInfo->index);
    char *val = ((char *)pColDataInfo->pData) + pColDataInfo->info.bytes * rowId;
    if (isNull(val, pDistDataInfo->type)) { 
      p += pDistDataInfo->bytes; 
      continue;
    }
    if (IS_VAR_DATA_TYPE(pDistDataInfo->type)) {
      memcpy(p, varDataVal(val), varDataLen(val));
      p += varDataLen(val);
    } else {
      memcpy(p, val, pDistDataInfo->bytes);
      p += pDistDataInfo->bytes;
    }
    memcpy(p, MULTI_KEY_DELIM, strlen(MULTI_KEY_DELIM));
    p += strlen(MULTI_KEY_DELIM);
  }
}

H
Haojun Liao 已提交
8238
static SSDataBlock* hashDistinct(SOperatorInfo *pOperator, bool* newgroup) {
8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

  SDistinctOperatorInfo* pInfo = pOperator->info;
  SSDataBlock* pRes = pInfo->pRes;

  pRes->info.rows = 0;
  SSDataBlock* pBlock = NULL;
   
  while(1) {
H
Haojun Liao 已提交
8250
    publishOperatorProfEvent(pOperator->pDownstream[0], QUERY_PROF_BEFORE_OPERATOR_EXEC);
H
Haojun Liao 已提交
8251
    pBlock = pOperator->pDownstream[0]->getNextFn(pOperator->pDownstream[0], newgroup);
H
Haojun Liao 已提交
8252
    publishOperatorProfEvent(pOperator->pDownstream[0], QUERY_PROF_AFTER_OPERATOR_EXEC);
8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302

    if (pBlock == NULL) {
      doSetOperatorCompleted(pOperator);
      break;
    }
    if (!initMultiDistinctInfo(pInfo, pOperator, pBlock)) {
      doSetOperatorCompleted(pOperator);
      break;
    }
    // ensure result output buf 
    if (pRes->info.rows + pBlock->info.rows > pInfo->outputCapacity) {
      int32_t newSize = pRes->info.rows + pBlock->info.rows;
      for (int i = 0; i < taosArrayGetSize(pRes->pDataBlock); i++) {
        SColumnInfoData*   pResultColInfoData = taosArrayGet(pRes->pDataBlock, i);
        SDistinctDataInfo* pDistDataInfo = taosArrayGet(pInfo->pDistinctDataInfo,  i);
        char* tmp = realloc(pResultColInfoData->pData, newSize * pDistDataInfo->bytes);
        if (tmp == NULL) {
          return NULL;
        } else {
          pResultColInfoData->pData = tmp;
        }
      }
      pInfo->outputCapacity = newSize;
    }

    for (int32_t i = 0; i < pBlock->info.rows; i++) {
      buildMultiDistinctKey(pInfo, pBlock, i);
      if (taosHashGet(pInfo->pSet, pInfo->buf, pInfo->totalBytes) == NULL) {
        int32_t dummy;
        taosHashPut(pInfo->pSet, pInfo->buf, pInfo->totalBytes, &dummy, sizeof(dummy));
        for (int j = 0; j < taosArrayGetSize(pRes->pDataBlock); j++) {
          SDistinctDataInfo* pDistDataInfo = taosArrayGet(pInfo->pDistinctDataInfo, j);  // distinct meta info
          SColumnInfoData*   pColInfoData = taosArrayGet(pBlock->pDataBlock, pDistDataInfo->index); //src
          SColumnInfoData*   pResultColInfoData = taosArrayGet(pRes->pDataBlock, j);  // dist 

          char* val = ((char*)pColInfoData->pData) + pDistDataInfo->bytes * i;
          char *start = pResultColInfoData->pData +  pDistDataInfo->bytes * pInfo->pRes->info.rows; 
          memcpy(start, val, pDistDataInfo->bytes);
        }
        pRes->info.rows += 1;
      } 
    }

    if (pRes->info.rows >= pInfo->threshold) {
      break;
    }
  }
  return (pInfo->pRes->info.rows > 0)? pInfo->pRes:NULL;
}

H
Haojun Liao 已提交
8303
SOperatorInfo* createDistinctOperatorInfo(STaskRuntimeEnv* pRuntimeEnv, SOperatorInfo* downstream, SExprInfo* pExpr, int32_t numOfOutput) {
8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316
  SDistinctOperatorInfo* pInfo = calloc(1, sizeof(SDistinctOperatorInfo));
  pInfo->totalBytes      = 0;
  pInfo->buf             = NULL;
  pInfo->threshold       = tsMaxNumOfDistinctResults; // distinct result threshold
  pInfo->outputCapacity  = 4096;
  pInfo->pDistinctDataInfo = taosArrayInit(numOfOutput, sizeof(SDistinctDataInfo)); 
  pInfo->pSet = taosHashInit(64, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), false, HASH_NO_LOCK);
  pInfo->pRes = createOutputBuf(pExpr, numOfOutput, (int32_t) pInfo->outputCapacity);
  

  SOperatorInfo* pOperator = calloc(1, sizeof(SOperatorInfo));
  pOperator->name         = "DistinctOperator";
  pOperator->blockingOptr = false;
H
Haojun Liao 已提交
8317
  pOperator->status       = OP_NOT_OPENED;
H
Haojun Liao 已提交
8318
//  pOperator->operatorType = OP_Distinct;
8319 8320 8321 8322
  pOperator->pExpr        = pExpr;
  pOperator->numOfOutput  = numOfOutput;
  pOperator->info         = pInfo;
  pOperator->pRuntimeEnv  = pRuntimeEnv;
H
Haojun Liao 已提交
8323
  pOperator->getNextFn = hashDistinct;
8324
  pOperator->pExpr        = pExpr; 
H
Haojun Liao 已提交
8325
  pOperator->closeFn = destroyDistinctOperatorInfo;
8326

8327
    int32_t code = appendDownstream(pOperator, &downstream, 1);
8328 8329 8330
  return pOperator;
}

H
Haojun Liao 已提交
8331
static int32_t getColumnIndexInSource(SQueriedTableInfo *pTableInfo, SExprBasicInfo *pExpr, SColumnInfo* pTagCols) {
8332 8333
  int32_t j = 0;

H
Haojun Liao 已提交
8334 8335
  if (TSDB_COL_IS_TAG(pExpr->pParam[0].pCol->type)) {
    if (pExpr->pParam[0].pCol->colId == TSDB_TBNAME_COLUMN_INDEX) {
8336 8337 8338 8339
      return TSDB_TBNAME_COLUMN_INDEX;
    }

    while(j < pTableInfo->numOfTags) {
H
Haojun Liao 已提交
8340
      if (pExpr->pParam[0].pCol->colId == pTagCols[j].colId) {
8341 8342 8343 8344 8345 8346
        return j;
      }

      j += 1;
    }

8347
  } /*else if (TSDB_COL_IS_UD_COL(pExpr->colInfo.flag)) {  // user specified column data
8348 8349 8350 8351 8352 8353 8354 8355 8356
    return TSDB_UD_COLUMN_INDEX;
  } else {
    while (j < pTableInfo->numOfCols) {
      if (pExpr->colInfo.colId == pTableInfo->colList[j].colId) {
        return j;
      }

      j += 1;
    }
8357
  }*/
8358 8359 8360 8361

  return INT32_MIN;  // return a less than TSDB_TBNAME_COLUMN_INDEX value
}

H
Haojun Liao 已提交
8362
bool validateExprColumnInfo(SQueriedTableInfo *pTableInfo, SExprBasicInfo *pExpr, SColumnInfo* pTagCols) {
8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397
  int32_t j = getColumnIndexInSource(pTableInfo, pExpr, pTagCols);
  return j != INT32_MIN;
}

static int32_t deserializeColFilterInfo(SColumnFilterInfo* pColFilters, int16_t numOfFilters, char** pMsg) {
  for (int32_t f = 0; f < numOfFilters; ++f) {
    SColumnFilterInfo *pFilterMsg = (SColumnFilterInfo *)(*pMsg);

    SColumnFilterInfo *pColFilter = &pColFilters[f];
    pColFilter->filterstr = htons(pFilterMsg->filterstr);

    (*pMsg) += sizeof(SColumnFilterInfo);

    if (pColFilter->filterstr) {
      pColFilter->len = htobe64(pFilterMsg->len);

      pColFilter->pz = (int64_t)calloc(1, (size_t)(pColFilter->len + 1 * TSDB_NCHAR_SIZE)); // note: null-terminator
      if (pColFilter->pz == 0) {
        return TSDB_CODE_QRY_OUT_OF_MEMORY;
      }

      memcpy((void *)pColFilter->pz, (*pMsg), (size_t)pColFilter->len);
      (*pMsg) += (pColFilter->len + 1);
    } else {
      pColFilter->lowerBndi = htobe64(pFilterMsg->lowerBndi);
      pColFilter->upperBndi = htobe64(pFilterMsg->upperBndi);
    }

    pColFilter->lowerRelOptr = htons(pFilterMsg->lowerRelOptr);
    pColFilter->upperRelOptr = htons(pFilterMsg->upperRelOptr);
  }

  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
8398 8399 8400 8401 8402 8403
static SResSchema createResSchema(int32_t type, int32_t bytes, int32_t slotId, int32_t scale, int32_t precision, const char* name) {
  SResSchema s = {0};
  s.scale = scale;
  s.type  = type;
  s.bytes = bytes;
  s.colId = slotId;
H
Haojun Liao 已提交
8404
  s.precision = precision;
H
Haojun Liao 已提交
8405 8406 8407 8408
  strncpy(s.name, name, tListLen(s.name));

  return s;
}
H
Haojun Liao 已提交
8409

H
Haojun Liao 已提交
8410
SExprInfo* createExprInfo(SNodeList* pNodeList, SNodeList* pGroupKeys, int32_t* numOfExprs) {
H
Haojun Liao 已提交
8411
  int32_t numOfFuncs = LIST_LENGTH(pNodeList);
H
Haojun Liao 已提交
8412 8413 8414 8415
  int32_t numOfGroupKeys = 0;
  if (pGroupKeys != NULL) {
    numOfGroupKeys = LIST_LENGTH(pGroupKeys);
  }
H
Haojun Liao 已提交
8416

H
Haojun Liao 已提交
8417 8418
  *numOfExprs = numOfFuncs + numOfGroupKeys;
  SExprInfo* pExprs = calloc(*numOfExprs, sizeof(SExprInfo));
H
Haojun Liao 已提交
8419

H
Haojun Liao 已提交
8420 8421 8422 8423 8424 8425 8426
  for(int32_t i = 0; i < (*numOfExprs); ++i) {
    STargetNode* pTargetNode = NULL;
    if (i < numOfFuncs) {
      pTargetNode = (STargetNode*)nodesListGetNode(pNodeList, i);
    } else {
      pTargetNode = (STargetNode*)nodesListGetNode(pGroupKeys, i - numOfFuncs);
    }
H
Haojun Liao 已提交
8427

H
Haojun Liao 已提交
8428
    SExprInfo* pExp = &pExprs[pTargetNode->slotId];
H
Haojun Liao 已提交
8429 8430 8431

    pExp->pExpr = calloc(1, sizeof(tExprNode));
    pExp->pExpr->_function.num = 1;
H
Haojun Liao 已提交
8432
    pExp->pExpr->_function.functionId = -1;
H
Haojun Liao 已提交
8433 8434 8435 8436 8437 8438 8439

    pExp->base.pParam = calloc(1, sizeof(SFunctParam));
    pExp->base.numOfParams = 1;

    pExp->base.pParam[0].pCol = calloc(1, sizeof(SColumn));
    SColumn* pCol = pExp->base.pParam[0].pCol;

H
Haojun Liao 已提交
8440
    // it is a project query, or group by column
H
Haojun Liao 已提交
8441 8442 8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454
    if (nodeType(pTargetNode->pExpr) == QUERY_NODE_COLUMN) {
      SColumnNode* pColNode = (SColumnNode*) pTargetNode->pExpr;

      SDataType* pType = &pColNode->node.resType;
      pExp->base.resSchema = createResSchema(pType->type, pType->bytes, pTargetNode->slotId, pType->scale, pType->precision, pColNode->colName);
      pCol->slotId    = pColNode->slotId;
      pCol->bytes     = pType->bytes;
      pCol->type      = pType->type;
      pCol->scale     = pType->scale;
      pCol->precision = pType->precision;
    } else {
      SFunctionNode* pFuncNode = (SFunctionNode*)pTargetNode->pExpr;

      SDataType* pType = &pFuncNode->node.resType;
H
Haojun Liao 已提交
8455
      pExp->base.resSchema = createResSchema(pType->type, pType->bytes, pTargetNode->slotId, pType->scale, pType->precision, pFuncNode->node.aliasName);
H
Haojun Liao 已提交
8456

H
Haojun Liao 已提交
8457
      pExp->pExpr->_function.functionId = pFuncNode->funcId;
H
Haojun Liao 已提交
8458
      pExp->pExpr->_function.pFunctNode = pFuncNode;
H
Haojun Liao 已提交
8459
      strncpy(pExp->pExpr->_function.functionName, pFuncNode->functionName, tListLen(pExp->pExpr->_function.functionName));
H
Haojun Liao 已提交
8460 8461 8462 8463 8464 8465 8466

      // TODO: value parameter needs to be handled
      int32_t numOfParam = LIST_LENGTH(pFuncNode->pParameterList);
      for (int32_t j = 0; j < numOfParam; ++j) {
        SNode*       p1 = nodesListGetNode(pFuncNode->pParameterList, j);
        SColumnNode* pcn = (SColumnNode*)p1;

H
Haojun Liao 已提交
8467 8468 8469 8470 8471
        pCol->slotId      = pcn->slotId;
        pCol->bytes       = pcn->node.resType.bytes;
        pCol->type        = pcn->node.resType.type;
        pCol->scale       = pcn->node.resType.scale;
        pCol->precision   = pcn->node.resType.precision;
H
Haojun Liao 已提交
8472 8473
        pCol->dataBlockId = pcn->dataBlockId;
      }
H
Haojun Liao 已提交
8474 8475 8476
    }
  }

H
Haojun Liao 已提交
8477
  return pExprs;
H
Haojun Liao 已提交
8478 8479
}

H
Haojun Liao 已提交
8480
static SExecTaskInfo* createExecTaskInfo(uint64_t queryId, uint64_t taskId) {
8481 8482
  SExecTaskInfo* pTaskInfo = calloc(1, sizeof(SExecTaskInfo));
  setTaskStatus(pTaskInfo, TASK_NOT_COMPLETED);
H
Haojun Liao 已提交
8483

8484
  pTaskInfo->cost.created = taosGetTimestampMs();
H
Haojun Liao 已提交
8485
  pTaskInfo->id.queryId = queryId;
H
Haojun Liao 已提交
8486 8487

  char* p = calloc(1, 128);
H
Haojun Liao 已提交
8488
  snprintf(p, 128, "TID:0x%"PRIx64" QID:0x%"PRIx64, taskId, queryId);
8489
  pTaskInfo->id.str = strdup(p);
H
Haojun Liao 已提交
8490

8491 8492
  return pTaskInfo;
}
H
Haojun Liao 已提交
8493

H
Haojun Liao 已提交
8494
static tsdbReaderT doCreateDataReader(STableScanPhysiNode* pTableScanNode, SReadHandle* pHandle, STableGroupInfo *pTableGroupInfo, uint64_t queryId, uint64_t taskId);
H
Haojun Liao 已提交
8495

H
Haojun Liao 已提交
8496
static int32_t doCreateTableGroup(void* metaHandle, int32_t tableType, uint64_t tableUid, STableGroupInfo* pGroupInfo, uint64_t queryId, uint64_t taskId);
8497 8498
static SArray* extractTableIdList(const STableGroupInfo* pTableGroupInfo);
static SArray* extractScanColumnId(SNodeList* pNodeList);
H
Haojun Liao 已提交
8499
static SArray* extractColumnInfo(SNodeList* pNodeList);
H
Haojun Liao 已提交
8500

X
Xiaoyu Wang 已提交
8501 8502 8503 8504
SOperatorInfo* doCreateOperatorTreeNode(SPhysiNode* pPhyNode, SExecTaskInfo* pTaskInfo, SReadHandle* pHandle, uint64_t queryId, uint64_t taskId, STableGroupInfo* pTableGroupInfo) {
  if (pPhyNode->pChildren == NULL || LIST_LENGTH(pPhyNode->pChildren) == 0) {
    if (QUERY_NODE_PHYSICAL_PLAN_TABLE_SCAN == nodeType(pPhyNode)) {
      SScanPhysiNode* pScanPhyNode = (SScanPhysiNode*)pPhyNode;
H
Haojun Liao 已提交
8505

H
Haojun Liao 已提交
8506
      size_t      numOfCols = LIST_LENGTH(pScanPhyNode->pScanCols);
H
Haojun Liao 已提交
8507
      tsdbReaderT pDataReader = doCreateDataReader((STableScanPhysiNode*)pPhyNode, pHandle, pTableGroupInfo, (uint64_t)queryId, taskId);
H
Haojun Liao 已提交
8508
      return createTableScanOperatorInfo(pDataReader, pScanPhyNode->order, numOfCols, pScanPhyNode->count, pScanPhyNode->reverse, pTaskInfo);
X
Xiaoyu Wang 已提交
8509
    } else if (QUERY_NODE_PHYSICAL_PLAN_EXCHANGE == nodeType(pPhyNode)) {
H
Haojun Liao 已提交
8510 8511 8512
      SExchangePhysiNode* pExchange = (SExchangePhysiNode*)pPhyNode;
      SSDataBlock* pResBlock = createOutputBuf_rv1(pExchange->node.pOutputDataBlockDesc);
      return createExchangeOperatorInfo(pExchange->pSrcEndPoints, pResBlock, pTaskInfo);
X
Xiaoyu Wang 已提交
8513
    } else if (QUERY_NODE_PHYSICAL_PLAN_STREAM_SCAN == nodeType(pPhyNode)) {
H
Haojun Liao 已提交
8514
      SScanPhysiNode* pScanPhyNode = (SScanPhysiNode*)pPhyNode;  // simple child table.
8515

H
Haojun Liao 已提交
8516 8517
      int32_t code = doCreateTableGroup(pHandle->meta, pScanPhyNode->tableType, pScanPhyNode->uid, pTableGroupInfo, queryId, taskId);
      SArray* tableIdList = extractTableIdList(pTableGroupInfo);
H
Haojun Liao 已提交
8518

8519 8520
      SSDataBlock* pResBlock = createOutputBuf_rv1(pScanPhyNode->node.pOutputDataBlockDesc);
      SArray* colList = extractScanColumnId(pScanPhyNode->pScanCols);
H
Haojun Liao 已提交
8521

8522 8523
      SOperatorInfo* pOperator = createStreamScanOperatorInfo(pHandle->reader, pResBlock, colList, tableIdList, pTaskInfo);
      taosArrayDestroy(tableIdList);
H
Haojun Liao 已提交
8524
      return pOperator;
H
Haojun Liao 已提交
8525 8526 8527 8528
    } else if (QUERY_NODE_PHYSICAL_PLAN_SYSTABLE_SCAN == nodeType(pPhyNode)) {
      SSystemTableScanPhysiNode * pSysScanPhyNode = (SSystemTableScanPhysiNode*)pPhyNode;
      SSDataBlock* pResBlock = createOutputBuf_rv1(pSysScanPhyNode->scan.node.pOutputDataBlockDesc);

8529 8530 8531 8532 8533
      struct SScanPhysiNode* pScanNode = &pSysScanPhyNode->scan;
      SArray* colList = extractScanColumnId(pScanNode->pScanCols);

      SOperatorInfo* pOperator = createSysTableScanOperatorInfo(pHandle->meta, pResBlock, &pScanNode->tableName,
                                                                pScanNode->node.pConditions, pSysScanPhyNode->mgmtEpSet, colList, pTaskInfo);
H
Haojun Liao 已提交
8534 8535 8536
      return pOperator;
    } else {
      ASSERT(0);
H
Haojun Liao 已提交
8537 8538 8539
    }
  }

H
Haojun Liao 已提交
8540 8541 8542 8543 8544 8545 8546 8547 8548
  if (QUERY_NODE_PHYSICAL_PLAN_PROJECT == nodeType(pPhyNode)) {
    size_t size = LIST_LENGTH(pPhyNode->pChildren);
    assert(size == 1);

    for (int32_t i = 0; i < size; ++i) {
      SPhysiNode*    pChildNode = (SPhysiNode*)nodesListGetNode(pPhyNode->pChildren, i);
      SOperatorInfo* op = doCreateOperatorTreeNode(pChildNode, pTaskInfo, pHandle, queryId, taskId, pTableGroupInfo);

      int32_t    num = 0;
H
Haojun Liao 已提交
8549
      SExprInfo* pExprInfo = createExprInfo(((SProjectPhysiNode*)pPhyNode)->pProjections, NULL, &num);
H
Haojun Liao 已提交
8550 8551 8552 8553
      SSDataBlock* pResBlock = createOutputBuf_rv1(pPhyNode->pOutputDataBlockDesc);
      return createProjectOperatorInfo(op, pExprInfo, num, pResBlock, pTaskInfo);
    }
  } else if (QUERY_NODE_PHYSICAL_PLAN_AGG == nodeType(pPhyNode)) {
X
Xiaoyu Wang 已提交
8554
    size_t size = LIST_LENGTH(pPhyNode->pChildren);
H
Haojun Liao 已提交
8555 8556
    assert(size == 1);

H
Haojun Liao 已提交
8557
    for (int32_t i = 0; i < size; ++i) {
H
Haojun Liao 已提交
8558
      SPhysiNode*    pChildNode = (SPhysiNode*)nodesListGetNode(pPhyNode->pChildren, i);
H
Haojun Liao 已提交
8559
      SOperatorInfo* op = doCreateOperatorTreeNode(pChildNode, pTaskInfo, pHandle, queryId, taskId, pTableGroupInfo);
H
Haojun Liao 已提交
8560

H
Haojun Liao 已提交
8561
      int32_t num = 0;
H
Haojun Liao 已提交
8562 8563 8564

      SAggPhysiNode* pAggNode = (SAggPhysiNode*)pPhyNode;
      SExprInfo* pExprInfo = createExprInfo(pAggNode->pAggFuncs, pAggNode->pGroupKeys, &num);
H
Haojun Liao 已提交
8565
      SSDataBlock* pResBlock = createOutputBuf_rv1(pPhyNode->pOutputDataBlockDesc);
H
Haojun Liao 已提交
8566 8567 8568 8569 8570 8571 8572

      if (pAggNode->pGroupKeys != NULL) {
        SArray* pColList = extractColumnInfo(pAggNode->pGroupKeys);
        return createGroupOperatorInfo(op, pExprInfo, num, pResBlock, pColList, pTaskInfo, NULL);
      } else {
        return createAggregateOperatorInfo(op, pExprInfo, num, pResBlock, pTaskInfo, pTableGroupInfo);
      }
H
Haojun Liao 已提交
8573
    }
H
Haojun Liao 已提交
8574 8575 8576 8577 8578 8579 8580 8581
  } else if (QUERY_NODE_PHYSICAL_PLAN_INTERVAL == nodeType(pPhyNode)) {
    size_t size = LIST_LENGTH(pPhyNode->pChildren);
    assert(size == 1);

    for (int32_t i = 0; i < size; ++i) {
      SPhysiNode*    pChildNode = (SPhysiNode*)nodesListGetNode(pPhyNode->pChildren, i);
      SOperatorInfo* op = doCreateOperatorTreeNode(pChildNode, pTaskInfo, pHandle, queryId, taskId, pTableGroupInfo);

8582 8583
      SIntervalPhysiNode* pIntervalPhyNode = (SIntervalPhysiNode*)pPhyNode;

H
Haojun Liao 已提交
8584
      int32_t num = 0;
X
Xiaoyu Wang 已提交
8585
      SExprInfo* pExprInfo = createExprInfo(pIntervalPhyNode->window.pFuncs, NULL, &num);
H
Haojun Liao 已提交
8586
      SSDataBlock* pResBlock = createOutputBuf_rv1(pPhyNode->pOutputDataBlockDesc);
8587

H
Haojun Liao 已提交
8588 8589 8590
      SInterval interval = {.interval = pIntervalPhyNode->interval, .sliding = pIntervalPhyNode->sliding,
                            .intervalUnit = pIntervalPhyNode->intervalUnit,
                            .slidingUnit = pIntervalPhyNode->slidingUnit, .offset = pIntervalPhyNode->offset};
8591
      return createIntervalOperatorInfo(op, pExprInfo, num, pResBlock, &interval, pTableGroupInfo, pTaskInfo);
H
Haojun Liao 已提交
8592
    }
X
Xiaoyu Wang 已提交
8593
  } /*else if (pPhyNode->info.type == OP_MultiTableAggregate) {
H
Haojun Liao 已提交
8594 8595 8596
    size_t size = taosArrayGetSize(pPhyNode->pChildren);
    assert(size == 1);

H
Haojun Liao 已提交
8597
    for (int32_t i = 0; i < size; ++i) {
X
Xiaoyu Wang 已提交
8598
      SPhysiNode*      pChildNode = taosArrayGetP(pPhyNode->pChildren, i);
H
Haojun Liao 已提交
8599 8600
      SOperatorInfo* op = doCreateOperatorTreeNode(pChildNode, pTaskInfo, pHandle, queryId, taskId, pTableGroupInfo);
      return createMultiTableAggOperatorInfo(op, pPhyNode->pTargets, pTaskInfo, pTableGroupInfo);
8601
    }
X
Xiaoyu Wang 已提交
8602
  }*/
8603
}
H
Haojun Liao 已提交
8604

X
Xiaoyu Wang 已提交
8605
static tsdbReaderT createDataReaderImpl(STableScanPhysiNode* pTableScanNode, STableGroupInfo* pGroupInfo, void* readHandle, uint64_t queryId, uint64_t taskId) {
H
Haojun Liao 已提交
8606
  STsdbQueryCond cond = {.loadExternalRows = false};
H
Haojun Liao 已提交
8607

H
Haojun Liao 已提交
8608
  cond.order     = pTableScanNode->scan.order;
X
Xiaoyu Wang 已提交
8609
  cond.numOfCols = LIST_LENGTH(pTableScanNode->scan.pScanCols);
H
Haojun Liao 已提交
8610
  cond.colList   = calloc(cond.numOfCols, sizeof(SColumnInfo));
H
Haojun Liao 已提交
8611 8612 8613 8614 8615
  if (cond.colList == NULL) {
    terrno = TSDB_CODE_QRY_OUT_OF_MEMORY;
    return NULL;
  }

X
Xiaoyu Wang 已提交
8616
  cond.twindow = pTableScanNode->scanRange;
H
Haojun Liao 已提交
8617
  cond.type = BLOCK_LOAD_OFFSET_SEQ_ORDER;
H
Haojun Liao 已提交
8618
//  cond.type = pTableScanNode->scanFlag;
H
Haojun Liao 已提交
8619

H
Haojun Liao 已提交
8620
  int32_t j = 0;
H
Haojun Liao 已提交
8621
  for (int32_t i = 0; i < cond.numOfCols; ++i) {
H
Haojun Liao 已提交
8622 8623
    STargetNode* pNode = (STargetNode*)nodesListGetNode(pTableScanNode->scan.pScanCols, i);
    SColumnNode* pColNode = (SColumnNode*)pNode->pExpr;
H
Haojun Liao 已提交
8624 8625 8626
    if (pColNode->colType == COLUMN_TYPE_TAG) {
      continue;
    }
H
Haojun Liao 已提交
8627

H
Haojun Liao 已提交
8628 8629 8630 8631
    cond.colList[j].type  = pColNode->node.resType.type;
    cond.colList[j].bytes = pColNode->node.resType.bytes;
    cond.colList[j].colId = pColNode->colId;
    j += 1;
H
Haojun Liao 已提交
8632 8633
  }

H
Haojun Liao 已提交
8634
  cond.numOfCols = j;
H
Haojun Liao 已提交
8635
  return tsdbQueryTables(readHandle, &cond, pGroupInfo, queryId, taskId);
H
Haojun Liao 已提交
8636
}
H
Haojun Liao 已提交
8637

8638 8639 8640 8641 8642 8643 8644 8645 8646 8647 8648 8649 8650 8651 8652 8653 8654
SArray* extractScanColumnId(SNodeList* pNodeList) {
  size_t numOfCols = LIST_LENGTH(pNodeList);
  SArray* pList = taosArrayInit(numOfCols, sizeof(int16_t));
  if (pList == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

  for(int32_t i = 0; i < numOfCols; ++i) {
    STargetNode* pNode = (STargetNode*) nodesListGetNode(pNodeList, i);
    SColumnNode* pColNode = (SColumnNode*) pNode->pExpr;
    taosArrayPush(pList, &pColNode->colId);
  }

  return pList;
}

H
Haojun Liao 已提交
8655 8656 8657 8658 8659 8660 8661 8662 8663 8664 8665 8666 8667 8668 8669 8670 8671 8672 8673 8674 8675 8676 8677 8678 8679 8680
SArray* extractColumnInfo(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) {
    STargetNode* pNode = (STargetNode*) nodesListGetNode(pNodeList, i);
    SColumnNode* pColNode = (SColumnNode*) pNode->pExpr;

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

8681
int32_t doCreateTableGroup(void* metaHandle, int32_t tableType, uint64_t tableUid, STableGroupInfo* pGroupInfo, uint64_t queryId, uint64_t taskId) {
8682
  int32_t code = 0;
H
Haojun Liao 已提交
8683
  if (tableType == TSDB_SUPER_TABLE) {
H
Haojun Liao 已提交
8684
    code = tsdbQuerySTableByTagCond(metaHandle, tableUid, 0, NULL, 0, 0, NULL, pGroupInfo, NULL, 0, queryId, taskId);
H
Haojun Liao 已提交
8685
  } else {  // Create one table group.
H
Haojun Liao 已提交
8686
    code = tsdbGetOneTableGroup(metaHandle, tableUid, 0, pGroupInfo);
8687 8688 8689 8690
  }

  return code;
}
H
Haojun Liao 已提交
8691

8692 8693 8694 8695 8696 8697 8698 8699 8700 8701 8702 8703 8704 8705 8706 8707 8708 8709
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;
}

H
Haojun Liao 已提交
8710
tsdbReaderT doCreateDataReader(STableScanPhysiNode* pTableScanNode, SReadHandle* pHandle, STableGroupInfo *pTableGroupInfo, uint64_t queryId, uint64_t taskId) {
8711
  uint64_t uid = pTableScanNode->scan.uid;
H
Haojun Liao 已提交
8712
  int32_t code = doCreateTableGroup(pHandle->meta, pTableScanNode->scan.tableType, uid, pTableGroupInfo, queryId, taskId);
8713 8714
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
H
Haojun Liao 已提交
8715
  }
H
Haojun Liao 已提交
8716

H
Haojun Liao 已提交
8717
  if (pTableGroupInfo->numOfTables == 0) {
H
Haojun Liao 已提交
8718
    code = 0;
H
Haojun Liao 已提交
8719
    qDebug("no table qualified for query, TID:0x%"PRIx64", QID:0x%"PRIx64, taskId, queryId);
H
Haojun Liao 已提交
8720 8721
    goto _error;
  }
H
Haojun Liao 已提交
8722

H
Haojun Liao 已提交
8723
  return createDataReaderImpl(pTableScanNode, pTableGroupInfo, pHandle->reader, queryId, taskId);
H
Haojun Liao 已提交
8724

H
Haojun Liao 已提交
8725 8726 8727 8728 8729
  _error:
  terrno = code;
  return NULL;
}

H
Haojun Liao 已提交
8730
int32_t createExecTaskInfoImpl(SSubplan* pPlan, SExecTaskInfo** pTaskInfo, SReadHandle* pHandle, uint64_t taskId) {
H
Haojun Liao 已提交
8731 8732
  uint64_t queryId = pPlan->id.queryId;

H
Haojun Liao 已提交
8733
  int32_t code = TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
8734
  *pTaskInfo = createExecTaskInfo(queryId, taskId);
H
Haojun Liao 已提交
8735 8736 8737 8738
  if (*pTaskInfo == NULL) {
    code = TSDB_CODE_QRY_OUT_OF_MEMORY;
    goto _complete;
  }
H
Haojun Liao 已提交
8739

H
Haojun Liao 已提交
8740 8741
  STableGroupInfo group = {0};
  (*pTaskInfo)->pRoot = doCreateOperatorTreeNode(pPlan->pNode, *pTaskInfo, pHandle, queryId, taskId, &group);
D
dapan1121 已提交
8742 8743
  if (NULL == (*pTaskInfo)->pRoot) {
  	code = terrno;
D
dapan1121 已提交
8744 8745
    goto _complete;
  }
H
Haojun Liao 已提交
8746

8747
  if ((*pTaskInfo)->pRoot == NULL) {
H
Haojun Liao 已提交
8748
    code = TSDB_CODE_QRY_OUT_OF_MEMORY;
H
Haojun Liao 已提交
8749
    goto _complete;
8750 8751
  }

H
Haojun Liao 已提交
8752 8753
  return code;

H
Haojun Liao 已提交
8754 8755 8756 8757 8758
_complete:
  tfree(*pTaskInfo);

  terrno = code;
  return code;
H
Haojun Liao 已提交
8759 8760
}

8761 8762 8763 8764 8765 8766 8767 8768 8769 8770 8771 8772 8773 8774 8775 8776 8777 8778 8779 8780 8781 8782 8783 8784 8785 8786 8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820 8821 8822 8823 8824 8825 8826 8827 8828 8829 8830 8831 8832 8833 8834 8835 8836 8837 8838 8839 8840 8841 8842 8843 8844 8845 8846 8847 8848 8849 8850 8851 8852 8853 8854 8855 8856 8857 8858 8859 8860 8861 8862 8863 8864 8865 8866 8867 8868 8869 8870 8871 8872 8873 8874 8875 8876 8877 8878 8879 8880 8881 8882 8883 8884 8885 8886 8887 8888 8889 8890 8891 8892 8893 8894 8895 8896 8897 8898 8899 8900 8901
int32_t cloneExprFilterInfo(SColumnFilterInfo **dst, SColumnFilterInfo* src, int32_t filterNum) {
  if (filterNum <= 0) {
    return TSDB_CODE_SUCCESS;
  }

  *dst = calloc(filterNum, sizeof(*src));
  if (*dst == NULL) {
    return TSDB_CODE_QRY_OUT_OF_MEMORY;
  }

  memcpy(*dst, src, sizeof(*src) * filterNum);

  for (int32_t i = 0; i < filterNum; i++) {
    if ((*dst)[i].filterstr && dst[i]->len > 0) {
      void *pz = calloc(1, (size_t)(*dst)[i].len + 1);

      if (pz == NULL) {
        if (i == 0) {
          free(*dst);
        } else {
          freeColumnFilterInfo(*dst, i);
        }

        return TSDB_CODE_QRY_OUT_OF_MEMORY;
      }

      memcpy(pz, (void *)src->pz, (size_t)src->len + 1);

      (*dst)[i].pz = (int64_t)pz;
    }
  }

  return TSDB_CODE_SUCCESS;
}

static int32_t updateOutputBufForTopBotQuery(SQueriedTableInfo* pTableInfo, SColumnInfo* pTagCols, SExprInfo* pExprs, int32_t numOfOutput, int32_t tagLen, bool superTable) {
  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];
//        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);
      }
    }
  }

  return TSDB_CODE_SUCCESS;
}

// TODO tag length should be passed from client, refactor
int32_t createQueryFilter(char *data, uint16_t len, SFilterInfo** pFilters) {
  tExprNode* expr = NULL;
  
  TRY(TSDB_MAX_TAG_CONDITIONS) {
    expr = exprTreeFromBinary(data, len);
  } CATCH( code ) {
    CLEANUP_EXECUTE();
    return code;
  } END_TRY

  if (expr == NULL) {
    //qError("failed to create expr tree");
    return TSDB_CODE_QRY_APP_ERROR;
  }

//  int32_t ret = filterInitFromTree(expr, pFilters, 0);
//  tExprTreeDestroy(expr, NULL);

//  return ret;
}

//int32_t doCreateFilterInfo(SColumnInfo* pCols, int32_t numOfCols, int32_t numOfFilterCols, SSingleColumnFilterInfo** pFilterInfo, uint64_t qId) {
//  *pFilterInfo = calloc(1, sizeof(SSingleColumnFilterInfo) * numOfFilterCols);
//  if (*pFilterInfo == NULL) {
//    return TSDB_CODE_QRY_OUT_OF_MEMORY;
//  }
//
//  for (int32_t i = 0, j = 0; i < numOfCols; ++i) {
//    if (pCols[i].flist.numOfFilters > 0) {
//      SSingleColumnFilterInfo* pFilter = &((*pFilterInfo)[j]);
//
//      memcpy(&pFilter->info, &pCols[i], sizeof(SColumnInfo));
//      pFilter->info = pCols[i];
//
//      pFilter->numOfFilters = pCols[i].flist.numOfFilters;
//      pFilter->pFilters = calloc(pFilter->numOfFilters, sizeof(SColumnFilterElem));
//      if (pFilter->pFilters == NULL) {
//        return TSDB_CODE_QRY_OUT_OF_MEMORY;
//      }
//
//      for (int32_t f = 0; f < pFilter->numOfFilters; ++f) {
//        SColumnFilterElem* pSingleColFilter = &pFilter->pFilters[f];
//        pSingleColFilter->filterInfo = pCols[i].flist.filterInfo[f];
//
//        int32_t lower = pSingleColFilter->filterInfo.lowerRelOptr;
//        int32_t upper = pSingleColFilter->filterInfo.upperRelOptr;
//        if (lower == TSDB_RELATION_INVALID && upper == TSDB_RELATION_INVALID) {
//          //qError("QInfo:0x%"PRIx64" invalid filter info", qId);
//          return TSDB_CODE_QRY_INVALID_MSG;
//        }
//
//        pSingleColFilter->fp = getFilterOperator(lower, upper);
//        if (pSingleColFilter->fp == NULL) {
//          //qError("QInfo:0x%"PRIx64" invalid filter info", qId);
//          return TSDB_CODE_QRY_INVALID_MSG;
//        }
//
//        pSingleColFilter->bytes = pCols[i].bytes;
//
//        if (lower == TSDB_RELATION_IN) {
////          buildFilterSetFromBinary(&pSingleColFilter->q, (char *)(pSingleColFilter->filterInfo.pz), (int32_t)(pSingleColFilter->filterInfo.len));
//        }
//      }
//
//      j++;
//    }
//  }
//
//  return TSDB_CODE_SUCCESS;
//}

void* doDestroyFilterInfo(SSingleColumnFilterInfo* pFilterInfo, int32_t numOfFilterCols) {
//  for (int32_t i = 0; i < numOfFilterCols; ++i) {
//    if (pFilterInfo[i].numOfFilters > 0) {
//      if (pFilterInfo[i].pFilters->filterInfo.lowerRelOptr == TSDB_RELATION_IN) {
//        taosHashCleanup((SHashObj *)(pFilterInfo[i].pFilters->q));
//      }
//      tfree(pFilterInfo[i].pFilters);
//    }
//  }
//
//  tfree(pFilterInfo);
  return NULL;
}

H
Haojun Liao 已提交
8902
int32_t createFilterInfo(STaskAttr* pQueryAttr, uint64_t qId) {
8903 8904 8905 8906 8907 8908 8909 8910 8911 8912
  for (int32_t i = 0; i < pQueryAttr->numOfCols; ++i) {
//    if (pQueryAttr->tableCols[i].flist.numOfFilters > 0 && pQueryAttr->tableCols[i].flist.filterInfo != NULL) {
//      pQueryAttr->numOfFilterCols++;
//    }
  }

  if (pQueryAttr->numOfFilterCols == 0) {
    return TSDB_CODE_SUCCESS;
  }

8913 8914
//  doCreateFilterInfo(pQueryAttr->tableCols, pQueryAttr->numOfCols, pQueryAttr->numOfFilterCols,
//                     &pQueryAttr->pFilterInfo, qId);
8915 8916 8917 8918 8919 8920

  pQueryAttr->createFilterOperator = true;

  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
8921
static void doUpdateExprColumnIndex(STaskAttr *pQueryAttr) {
8922 8923 8924
  assert(pQueryAttr->pExpr1 != NULL && pQueryAttr != NULL);

  for (int32_t k = 0; k < pQueryAttr->numOfOutput; ++k) {
H
Haojun Liao 已提交
8925
    SExprBasicInfo *pSqlExprMsg = &pQueryAttr->pExpr1[k].base;
8926 8927 8928 8929 8930
//    if (pSqlExprMsg->functionId == FUNCTION_ARITHM) {
//      continue;
//    }

    // todo opt performance
8931
    SColIndex *pColIndex = NULL;/*&pSqlExprMsg->colInfo;*/
8932 8933 8934 8935 8936 8937 8938 8939 8940 8941 8942 8943 8944 8945 8946 8947 8948 8949 8950 8951 8952 8953 8954 8955 8956 8957
    if (TSDB_COL_IS_NORMAL_COL(pColIndex->flag)) {
      int32_t f = 0;
      for (f = 0; f < pQueryAttr->numOfCols; ++f) {
        if (pColIndex->colId == pQueryAttr->tableCols[f].colId) {
          pColIndex->colIndex = f;
          break;
        }
      }

      assert(f < pQueryAttr->numOfCols);
    } else if (pColIndex->colId <= TSDB_UD_COLUMN_INDEX) {
      // do nothing for user-defined constant value result columns
    } else {
      int32_t f = 0;
      for (f = 0; f < pQueryAttr->numOfTags; ++f) {
        if (pColIndex->colId == pQueryAttr->tagColList[f].colId) {
          pColIndex->colIndex = f;
          break;
        }
      }

      assert(f < pQueryAttr->numOfTags || pColIndex->colId == TSDB_TBNAME_COLUMN_INDEX);
    }
  }
}

H
Haojun Liao 已提交
8958
void setResultBufSize(STaskAttr* pQueryAttr, SResultInfo* pResultInfo) {
8959 8960 8961 8962 8963 8964 8965 8966 8967 8968 8969 8970 8971 8972 8973 8974 8975 8976 8977 8978
  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;

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

  pResultInfo->threshold = (int32_t)(pResultInfo->capacity * THRESHOLD_RATIO);
H
Haojun Liao 已提交
8979
  pResultInfo->totalRows = 0;
8980 8981 8982 8983 8984 8985 8986 8987 8988 8989 8990 8991 8992 8993 8994 8995 8996 8997 8998 8999 9000 9001 9002 9003 9004 9005 9006 9007 9008 9009 9010 9011 9012 9013 9014 9015 9016 9017 9018 9019 9020
}

//TODO refactor
void freeColumnFilterInfo(SColumnFilterInfo* pFilter, int32_t numOfFilters) {
    if (pFilter == NULL || numOfFilters == 0) {
      return;
    }

    for (int32_t i = 0; i < numOfFilters; i++) {
      if (pFilter[i].filterstr && pFilter[i].pz) {
        free((void*)(pFilter[i].pz));
      }
    }

    free(pFilter);
}

static void doDestroyTableQueryInfo(STableGroupInfo* pTableqinfoGroupInfo) {
  if (pTableqinfoGroupInfo->pGroupList != NULL) {
    int32_t numOfGroups = (int32_t) taosArrayGetSize(pTableqinfoGroupInfo->pGroupList);
    for (int32_t i = 0; i < numOfGroups; ++i) {
      SArray *p = taosArrayGetP(pTableqinfoGroupInfo->pGroupList, i);

      size_t num = taosArrayGetSize(p);
      for(int32_t j = 0; j < num; ++j) {
        STableQueryInfo* item = taosArrayGetP(p, j);
        destroyTableQueryInfoImpl(item);
      }

      taosArrayDestroy(p);
    }
  }

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

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

H
Haojun Liao 已提交
9021
void doDestroyTask(SExecTaskInfo *pTaskInfo) {
H
Haojun Liao 已提交
9022 9023
  qDebug("%s execTask is freed", GET_TASKID(pTaskInfo));

H
Haojun Liao 已提交
9024 9025 9026
  doDestroyTableQueryInfo(&pTaskInfo->tableqinfoGroupInfo);
//  taosArrayDestroy(pTaskInfo->summary.queryProfEvents);
//  taosHashCleanup(pTaskInfo->summary.operatorProfResults);
9027

9028 9029 9030
  tfree(pTaskInfo->sql);
  tfree(pTaskInfo->id.str);
  tfree(pTaskInfo);
9031 9032 9033 9034 9035 9036 9037 9038 9039 9040 9041 9042 9043 9044 9045 9046 9047 9048 9049 9050 9051 9052 9053 9054 9055 9056
}

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;
      int32_t len = (varDataLen(val) > maxLen)? maxLen:varDataLen(val);
      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);
//  size_t s3 = sizeof(STableCheckInfo);  buffer consumption in tsdb
H
Haojun Liao 已提交
9057
  return (int64_t)(s1* 1.5 * numOfTables);
9058 9059 9060 9061 9062 9063 9064 9065 9066 9067 9068 9069 9070 9071 9072 9073 9074 9075 9076 9077 9078 9079 9080 9081 9082 9083 9084 9085 9086 9087 9088 9089 9090 9091 9092
}

int32_t checkForQueryBuf(size_t numOfTables) {
  int64_t t = getQuerySupportBufSize(numOfTables);
  if (tsQueryBufferSizeBytes < 0) {
    return TSDB_CODE_SUCCESS;
  } else if (tsQueryBufferSizeBytes > 0) {

    while(1) {
      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);
}