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

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

31 32
#include "executorimpl.h"
#include "function.h"
33
#include "query.h"
34 35
#include "tcompare.h"
#include "tcompression.h"
H
Haojun Liao 已提交
36
#include "thash.h"
H
Hongze Cheng 已提交
37
#include "vnode.h"
38
#include "ttypes.h"
L
Liu Jicong 已提交
39
#include "vnode.h"
40

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

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

L
Liu Jicong 已提交
49 50
#define SDATA_BLOCK_INITIALIZER \
  (SDataBlockInfo) { {0}, 0 }
51 52 53 54

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

enum {
L
Liu Jicong 已提交
55 56
  TS_JOIN_TS_EQUAL = 0,
  TS_JOIN_TS_NOT_EQUALS = 1,
57 58 59 60 61
  TS_JOIN_TAG_NOT_EQUALS = 2,
};

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

H
Haojun Liao 已提交
65

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

  if (v % 1000 <= 0) {
    return NULL;
  } else {
wafwerar's avatar
wafwerar 已提交
73
    return taosMemoryMalloc(__size);
74 75 76 77
  }
}

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

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

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

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

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

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

int32_t getMaximumIdleDurationSec() { return tsShellActivityTimer * 2; }

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

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

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

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

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

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

  mon = (int)(mon + interval);
  tm.tm_year = mon / 12;
  tm.tm_mon = mon % 12;
181
  tw->ekey = convertTimePrecision((int64_t)taosMktime(&tm) * 1000L, TSDB_TIME_PRECISION_MILLI, precision);
182 183 184 185 186

  tw->ekey -= 1;
}

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

L
Liu Jicong 已提交
189
static void setBlockStatisInfo(SqlFunctionCtx* pCtx, SSDataBlock* pSDataBlock, SColumn* pColumn);
190

L
Liu Jicong 已提交
191 192
static void destroyTableQueryInfoImpl(STableQueryInfo* pTableQueryInfo);
static bool hasMainOutput(STaskAttr* pQueryAttr);
193 194 195

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

L
Liu Jicong 已提交
196 197 198 199
static int32_t setTimestampListJoinInfo(STaskRuntimeEnv* pRuntimeEnv, SVariant* pTag, STableQueryInfo* pTableQueryInfo);
static void    releaseQueryBuf(size_t numOfTables);
static int32_t binarySearchForKey(char* pValue, int num, TSKEY key, int order);
// static STsdbQueryCond createTsdbQueryCond(STaskAttr* pQueryAttr, STimeWindow* win);
200 201
static STableIdInfo createTableIdInfo(STableQueryInfo* pTableQueryInfo);

H
Haojun Liao 已提交
202
static int32_t getNumOfScanTimes(STaskAttr* pQueryAttr);
203 204 205 206 207 208 209 210 211

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

H
Haojun Liao 已提交
213
static void destroyIntervalOperatorInfo(void* param, int32_t numOfOutput);
H
Haojun Liao 已提交
214 215 216
static void destroyExchangeOperatorInfo(void* param, int32_t numOfOutput);
static void destroyConditionOperatorInfo(void* param, int32_t numOfOutput);

217
static void destroyOperatorInfo(SOperatorInfo* pOperator);
218
static void destroySysTableScannerOperatorInfo(void* param, int32_t numOfOutput);
219

220
void doSetOperatorCompleted(SOperatorInfo* pOperator) {
221
  pOperator->status = OP_EXEC_DONE;
H
Haojun Liao 已提交
222
  if (pOperator->pTaskInfo != NULL) {
223
    setTaskStatus(pOperator->pTaskInfo, TASK_COMPLETED);
224 225
  }
}
226

227 228 229
#define OPTR_IS_OPENED(_optr)  (((_optr)->status & OP_OPENED) == OP_OPENED)
#define OPTR_SET_OPENED(_optr) ((_optr)->status |= OP_OPENED)

H
Haojun Liao 已提交
230
int32_t operatorDummyOpenFn(SOperatorInfo* pOperator) {
231
  OPTR_SET_OPENED(pOperator);
H
Haojun Liao 已提交
232
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
233 234
}

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

237 238
static int32_t doCopyToSDataBlock(SSDataBlock* pBlock, int32_t rowCapacity, SExprInfo* pExprInfo, SDiskbasedBuf* pBuf, SGroupResInfo* pGroupResInfo,
                                  int32_t orderType, int32_t* rowCellOffset);
L
Liu Jicong 已提交
239 240 241
static void    initCtxOutputBuffer(SqlFunctionCtx* pCtx, int32_t size);
static void    getAlignQueryTimeWindow(SInterval* pInterval, int32_t precision, int64_t key, int64_t keyFirst,
                                       int64_t keyLast, STimeWindow* win);
H
Haojun Liao 已提交
242

H
Haojun Liao 已提交
243
static void setResultBufSize(STaskAttr* pQueryAttr, SResultInfo* pResultInfo);
H
Haojun Liao 已提交
244
static void setCtxTagForJoin(STaskRuntimeEnv* pRuntimeEnv, SqlFunctionCtx* pCtx, SExprInfo* pExprInfo, void* pTable);
L
Liu Jicong 已提交
245 246
static void doSetTableGroupOutputBuf(SAggOperatorInfo* pAggInfo, int32_t numOfOutput, int32_t tableGroupId,
                                     SExecTaskInfo* pTaskInfo);
247

H
Haojun Liao 已提交
248
SArray* getOrderCheckColumns(STaskAttr* pQuery);
249 250

typedef struct SRowCompSupporter {
L
Liu Jicong 已提交
251 252 253
  STaskRuntimeEnv* pRuntimeEnv;
  int16_t          dataOffset;
  __compar_fn_t    comFunc;
254 255
} SRowCompSupporter;

L
Liu Jicong 已提交
256 257 258
static int compareRowData(const void* a, const void* b, const void* userData) {
  const SResultRow* pRow1 = (const SResultRow*)a;
  const SResultRow* pRow2 = (const SResultRow*)b;
259

L
Liu Jicong 已提交
260 261
  SRowCompSupporter* supporter = (SRowCompSupporter*)userData;
  STaskRuntimeEnv*   pRuntimeEnv = supporter->pRuntimeEnv;
262

L
Liu Jicong 已提交
263 264
  SFilePage* page1 = getBufPage(pRuntimeEnv->pResultBuf, pRow1->pageId);
  SFilePage* page2 = getBufPage(pRuntimeEnv->pResultBuf, pRow2->pageId);
265 266

  int16_t offset = supporter->dataOffset;
L
Liu Jicong 已提交
267 268
  char*   in1 = getPosInResultPage(pRuntimeEnv->pQueryAttr, page1, pRow1->offset, offset);
  char*   in2 = getPosInResultPage(pRuntimeEnv->pQueryAttr, page2, pRow2->offset, offset);
269 270 271 272

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

L
Liu Jicong 已提交
273
// setup the output buffer for each operator
H
Haojun Liao 已提交
274 275
SSDataBlock* createOutputBuf_rv1(SDataBlockDescNode* pNode) {
  int32_t numOfCols = LIST_LENGTH(pNode->pSlots);
H
Haojun Liao 已提交
276

wafwerar's avatar
wafwerar 已提交
277
  SSDataBlock* pBlock = taosMemoryCalloc(1, sizeof(SSDataBlock));
H
Haojun Liao 已提交
278 279 280
  pBlock->info.numOfCols = numOfCols;
  pBlock->pDataBlock = taosArrayInit(numOfCols, sizeof(SColumnInfoData));

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

L
Liu Jicong 已提交
284
  for (int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
285
    SColumnInfoData idata = {{0}};
L
Liu Jicong 已提交
286
    SSlotDescNode*  pDescNode = nodesListGetNode(pNode->pSlots, i);
H
Haojun Liao 已提交
287 288
    if (!pDescNode->output) {
      continue;
H
Haojun Liao 已提交
289
    }
H
Haojun Liao 已提交
290

291
    idata.info.type  = pDescNode->dataType.type;
L
Liu Jicong 已提交
292 293
    idata.info.bytes = pDescNode->dataType.bytes;
    idata.info.scale = pDescNode->dataType.scale;
H
Haojun Liao 已提交
294
    idata.info.slotId = pDescNode->slotId;
H
Haojun Liao 已提交
295 296
    idata.info.precision = pDescNode->dataType.precision;

H
Hongze Cheng 已提交
297 298 299 300
    if (IS_VAR_DATA_TYPE(idata.info.type)) {
      pBlock->info.hasVarCol = true;
    }

H
Haojun Liao 已提交
301
    taosArrayPush(pBlock->pDataBlock, &idata);
H
Haojun Liao 已提交
302
  }
H
Haojun Liao 已提交
303 304

  return pBlock;
H
Haojun Liao 已提交
305 306
}

L
Liu Jicong 已提交
307
static bool isSelectivityWithTagsQuery(SqlFunctionCtx* pCtx, int32_t numOfOutput) {
308
  return true;
L
Liu Jicong 已提交
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
  //  bool    hasTags = false;
  //  int32_t numOfSelectivity = 0;
  //
  //  for (int32_t i = 0; i < numOfOutput; ++i) {
  //    int32_t functId = pCtx[i].functionId;
  //    if (functId == FUNCTION_TAG_DUMMY || functId == FUNCTION_TS_DUMMY) {
  //      hasTags = true;
  //      continue;
  //    }
  //
  //    if ((aAggs[functId].status & FUNCSTATE_SELECTIVITY) != 0) {
  //      numOfSelectivity++;
  //    }
  //  }
  //
  //  return (numOfSelectivity > 0 && hasTags);
}

static bool hasNull(SColumn* pColumn, SColumnDataAgg* pStatis) {
  if (TSDB_COL_IS_TAG(pColumn->flag) || TSDB_COL_IS_UD_COL(pColumn->flag) ||
      pColumn->colId == PRIMARYKEY_TIMESTAMP_COL_ID) {
330 331 332 333 334 335 336 337 338 339
    return false;
  }

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

  return true;
}

H
Haojun Liao 已提交
340
static void prepareResultListBuffer(SResultRowInfo* pResultRowInfo, jmp_buf env) {
341 342
  int64_t newCapacity = 0;

343 344 345 346 347 348 349 350 351 352 353
  // 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 已提交
354 355 356 357
  if (newCapacity == pResultRowInfo->capacity) {
    newCapacity += 4;
  }

wafwerar's avatar
wafwerar 已提交
358
  pResultRowInfo->pPosition = taosMemoryRealloc(pResultRowInfo->pPosition, newCapacity * sizeof(SResultRowPosition));
359 360

  int32_t inc = (int32_t)newCapacity - pResultRowInfo->capacity;
wmmhello's avatar
wmmhello 已提交
361
  memset(&pResultRowInfo->pPosition[pResultRowInfo->capacity], 0, sizeof(SResultRowPosition) * inc);
362 363 364
  pResultRowInfo->capacity = (int32_t)newCapacity;
}

L
Liu Jicong 已提交
365 366
static bool chkResultRowFromKey(STaskRuntimeEnv* pRuntimeEnv, SResultRowInfo* pResultRowInfo, char* pData,
                                int16_t bytes, bool masterscan, uint64_t uid) {
367 368 369
  bool existed = false;
  SET_RES_WINDOW_KEY(pRuntimeEnv->keyBuf, pData, bytes, uid);

L
Liu Jicong 已提交
370 371
  SResultRow** p1 =
      (SResultRow**)taosHashGet(pRuntimeEnv->pResultRowHashTable, pRuntimeEnv->keyBuf, GET_RES_WINDOW_KEY_LEN(bytes));
372 373 374 375 376 377 378 379 380 381 382

  // in case of repeat scan/reverse scan, no new time window added.
  if (QUERY_IS_INTERVAL_QUERY(pRuntimeEnv->pQueryAttr)) {
    if (!masterscan) {  // the *p1 may be NULL in case of sliding+offset exists.
      return p1 != NULL;
    }

    if (p1 != NULL) {
      if (pResultRowInfo->size == 0) {
        existed = false;
      } else if (pResultRowInfo->size == 1) {
H
Haojun Liao 已提交
383
//        existed = (pResultRowInfo->pResult[0] == (*p1));
384 385
      } else {  // check if current pResultRowInfo contains the existed pResultRow
        SET_RES_EXT_WINDOW_KEY(pRuntimeEnv->keyBuf, pData, bytes, uid, pResultRowInfo);
L
Liu Jicong 已提交
386 387
        int64_t* index =
            taosHashGet(pRuntimeEnv->pResultRowListSet, pRuntimeEnv->keyBuf, GET_RES_EXT_WINDOW_KEY_LEN(bytes));
388 389 390 391 392 393 394 395 396 397 398 399 400 401
        if (index != NULL) {
          existed = true;
        } else {
          existed = false;
        }
      }
    }

    return existed;
  }

  return p1 != NULL;
}

402
SResultRow* getNewResultRow_rv(SDiskbasedBuf* pResultBuf, int64_t tableGroupId, int32_t interBufSize) {
L
Liu Jicong 已提交
403
  SFilePage* pData = NULL;
404 405 406 407 408 409 410 411 412 413 414 415 416

  // in the first scan, new space needed for results
  int32_t pageId = -1;
  SIDList list = getDataBufPagesIdList(pResultBuf, tableGroupId);

  if (taosArrayGetSize(list) == 0) {
    pData = getNewBufPage(pResultBuf, tableGroupId, &pageId);
    pData->num = sizeof(SFilePage);
  } else {
    SPageInfo* pi = getLastPageInfo(list);
    pData = getBufPage(pResultBuf, getPageId(pi));
    pageId = getPageId(pi);

wmmhello's avatar
wmmhello 已提交
417
    if (pData->num + interBufSize > getBufPageSize(pResultBuf)) {
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
      // release current page first, and prepare the next one
      releaseBufPageInfo(pResultBuf, pi);

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

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

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

wmmhello's avatar
wmmhello 已提交
437
  pData->num += interBufSize;
438 439 440 441

  return pResultRow;
}

L
Liu Jicong 已提交
442 443 444
static SResultRow* doSetResultOutBufByKey_rv(SDiskbasedBuf* pResultBuf, SResultRowInfo* pResultRowInfo, int64_t tid,
                                             char* pData, int16_t bytes, bool masterscan, uint64_t tableGroupId,
                                             SExecTaskInfo* pTaskInfo, bool isIntervalQuery, SAggSupporter* pSup) {
H
Haojun Liao 已提交
445
  bool existInCurrentResusltRowInfo = false;
446
  SET_RES_WINDOW_KEY(pSup->keyBuf, pData, bytes, tableGroupId);
H
Haojun Liao 已提交
447

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

  // in case of repeat scan/reverse scan, no new time window added.
  if (isIntervalQuery) {
    if (!masterscan) {  // the *p1 may be NULL in case of sliding+offset exists.
H
Haojun Liao 已提交
453 454 455 456 457
      if (p1 != NULL) {
        return getResultRowByPos(pResultBuf, p1);
      } else {
        return NULL;
      }
H
Haojun Liao 已提交
458 459 460 461
    }

    if (p1 != NULL) {
      if (pResultRowInfo->size == 0) {
H
Haojun Liao 已提交
462
        existInCurrentResusltRowInfo = false;  // this time window created by other timestamp that does not belongs to current table.
H
Haojun Liao 已提交
463 464
        assert(pResultRowInfo->curPos == -1);
      } else if (pResultRowInfo->size == 1) {
C
Cary Xu 已提交
465 466 467
        // ASSERT(0);
        SResultRowPosition* p = &pResultRowInfo->pPosition[0];
        existInCurrentResusltRowInfo = (p->pageId == p1->pageId && p->offset == p1->offset);
H
Haojun Liao 已提交
468
      } else {  // check if current pResultRowInfo contains the existInCurrentResusltRowInfo pResultRow
469 470
        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 已提交
471
        if (index != NULL) {
H
Haojun Liao 已提交
472 473 474
          // TODO check the scan order for current opened time window
//          pResultRowInfo->curPos = (int32_t)*index;
          existInCurrentResusltRowInfo = true;
H
Haojun Liao 已提交
475
        } else {
H
Haojun Liao 已提交
476
          existInCurrentResusltRowInfo = false;
H
Haojun Liao 已提交
477 478 479 480
        }
      }
    }
  } else {
H
Haojun Liao 已提交
481
    // In case of group by column query, the required SResultRow object must be existInCurrentResusltRowInfo in the pResultRowInfo object.
H
Haojun Liao 已提交
482
    if (p1 != NULL) {
H
Haojun Liao 已提交
483
      return getResultRowByPos(pResultBuf, p1);
H
Haojun Liao 已提交
484 485 486
    }
  }

H
Haojun Liao 已提交
487 488 489 490 491 492 493 494 495 496
  SResultRow* pResult = NULL;
  if (!existInCurrentResusltRowInfo) {
    // 1. close current opened time window
    if (pResultRowInfo->curPos != -1) {  // todo extract function
      SResultRowPosition* pos = &pResultRowInfo->pPosition[pResultRowInfo->curPos];
      SFilePage* pPage = getBufPage(pResultBuf, pos->pageId);
      SResultRow* pRow = (SResultRow*)((char*)pPage + pos->offset);
      closeResultRow(pRow);
      releaseBufPage(pResultBuf, pPage);
    }
H
Haojun Liao 已提交
497

H
Haojun Liao 已提交
498
    prepareResultListBuffer(pResultRowInfo, pTaskInfo->env);
H
Haojun Liao 已提交
499
    if (p1 == NULL) {
500
      pResult = getNewResultRow_rv(pResultBuf, tableGroupId, pSup->resultRowSize);
H
Haojun Liao 已提交
501
      initResultRow(pResult);
H
Haojun Liao 已提交
502 503

      // add a new result set for a new group
H
Haojun Liao 已提交
504
      SResultRowPosition pos = {.pageId = pResult->pageId, .offset = pResult->offset};
wmmhello's avatar
wmmhello 已提交
505
      taosHashPut(pSup->pResultRowHashTable, pSup->keyBuf, GET_RES_WINDOW_KEY_LEN(bytes), &pos, sizeof(SResultRowPosition));
H
Haojun Liao 已提交
506
      SResultRowCell cell = {.groupId = tableGroupId, .pos = pos};
507
      taosArrayPush(pSup->pResultRowArrayList, &cell);
H
Haojun Liao 已提交
508
    } else {
H
Haojun Liao 已提交
509
      pResult = getResultRowByPos(pResultBuf, p1);
H
Haojun Liao 已提交
510 511
    }

H
Haojun Liao 已提交
512
    // 2. set the new time window to be the new active time window
H
Haojun Liao 已提交
513
    pResultRowInfo->curPos = pResultRowInfo->size;
H
Haojun Liao 已提交
514
    pResultRowInfo->pPosition[pResultRowInfo->size++] = (SResultRowPosition){.pageId = pResult->pageId, .offset = pResult->offset};
H
Haojun Liao 已提交
515 516

    int64_t index = pResultRowInfo->curPos;
517 518
    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);
C
Cary Xu 已提交
519 520
  } else {
    pResult = getResultRowByPos(pResultBuf, p1);
H
Haojun Liao 已提交
521 522 523 524 525 526 527
  }

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

H
Haojun Liao 已提交
528
  return pResult;
H
Haojun Liao 已提交
529 530
}

L
Liu Jicong 已提交
531 532
static void getInitialStartTimeWindow(SInterval* pInterval, int32_t precision, TSKEY ts, STimeWindow* w, TSKEY ekey,
                                      bool ascQuery) {
H
Haojun Liao 已提交
533 534
  if (ascQuery) {
    getAlignQueryTimeWindow(pInterval, precision, ts, ts, ekey, w);
535 536
  } else {
    // the start position of the first time window in the endpoint that spreads beyond the queried last timestamp
H
Haojun Liao 已提交
537
    getAlignQueryTimeWindow(pInterval, precision, ts, ekey, ts, w);
538 539

    int64_t key = w->skey;
L
Liu Jicong 已提交
540
    while (key < ts) {  // moving towards end
541
      key = taosTimeAdd(key, pInterval->sliding, pInterval->slidingUnit, precision);
542 543 544 545 546 547 548 549 550 551
      if (key >= ts) {
        break;
      }

      w->skey = key;
    }
  }
}

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

L
Liu Jicong 已提交
556
  if (pResultRowInfo->curPos == -1) {  // the first window, from the previous stored value
H
Haojun Liao 已提交
557
    getInitialStartTimeWindow(pInterval, precision, ts, &w, win->ekey, true);
558
    w.ekey = taosTimeAdd(w.skey, pInterval->interval, pInterval->intervalUnit, precision) - 1;
559
  } else {
H
Haojun Liao 已提交
560
    w = getResultRow(pBuf, pResultRowInfo, pResultRowInfo->curPos)->win;
561 562 563
  }

  if (w.skey > ts || w.ekey < ts) {
H
Haojun Liao 已提交
564 565 566
    if (pInterval->intervalUnit == 'n' || pInterval->intervalUnit == 'y') {
      w.skey = taosTimeTruncate(ts, pInterval, precision);
      w.ekey = taosTimeAdd(w.skey, pInterval->interval, pInterval->intervalUnit, precision) - 1;
567 568 569 570
    } else {
      int64_t st = w.skey;

      if (st > ts) {
H
Haojun Liao 已提交
571
        st -= ((st - ts + pInterval->sliding - 1) / pInterval->sliding) * pInterval->sliding;
572 573
      }

H
Haojun Liao 已提交
574
      int64_t et = st + pInterval->interval - 1;
575
      if (et < ts) {
H
Haojun Liao 已提交
576
        st += ((ts - et + pInterval->sliding - 1) / pInterval->sliding) * pInterval->sliding;
577 578 579
      }

      w.skey = st;
580
      w.ekey = taosTimeAdd(w.skey, pInterval->interval, pInterval->intervalUnit, precision) - 1;
581 582 583 584 585 586
    }
  }
  return w;
}

// get the correct time window according to the handled timestamp
L
Liu Jicong 已提交
587
static STimeWindow getCurrentActiveTimeWindow(SResultRowInfo* pResultRowInfo, int64_t ts, STaskAttr* pQueryAttr) {
588
  STimeWindow w = {0};
H
Haojun Liao 已提交
589
#if 0
L
Liu Jicong 已提交
590 591
  if (pResultRowInfo->curPos == -1) {  // the first window, from the previous stored value
                                       //    getInitialStartTimeWindow(pQueryAttr, ts, &w);
592 593

    if (pQueryAttr->interval.intervalUnit == 'n' || pQueryAttr->interval.intervalUnit == 'y') {
L
Liu Jicong 已提交
594 595 596
      w.ekey =
          taosTimeAdd(w.skey, pQueryAttr->interval.interval, pQueryAttr->interval.intervalUnit, pQueryAttr->precision) -
          1;
597 598 599 600
    } else {
      w.ekey = w.skey + pQueryAttr->interval.interval - 1;
    }
  } else {
H
Haojun Liao 已提交
601
    w = pRow->win;
602 603 604 605 606 607 608 609 610
  }

  /*
   * query border check, skey should not be bounded by the query time range, since the value skey will
   * be used as the time window index value. So we only change ekey of time window accordingly.
   */
  if (w.ekey > pQueryAttr->window.ekey && QUERY_IS_ASC_QUERY(pQueryAttr)) {
    w.ekey = pQueryAttr->window.ekey;
  }
H
Haojun Liao 已提交
611
#endif
612 613 614 615 616

  return w;
}

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

L
Liu Jicong 已提交
622
  SFilePage* pData = NULL;
623 624 625 626 627 628

  // 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 已提交
629
    pData = getNewBufPage(pResultBuf, tid, &pageId);
630
    pData->num = sizeof(SFilePage);
631 632
  } else {
    SPageInfo* pi = getLastPageInfo(list);
633
    pData = getBufPage(pResultBuf, getPageId(pi));
634
    pageId = getPageId(pi);
635

636
    if (pData->num + size > getBufPageSize(pResultBuf)) {
637
      // release current page first, and prepare the next one
638
      releaseBufPageInfo(pResultBuf, pi);
639

H
Haojun Liao 已提交
640
      pData = getNewBufPage(pResultBuf, tid, &pageId);
641
      if (pData != NULL) {
642
        pData->num = sizeof(SFilePage);
643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662
      }
    }
  }

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

  // set the number of rows in current disk page
  if (pWindowRes->pageId == -1) {  // not allocated yet, allocate new buffer
    pWindowRes->pageId = pageId;
    pWindowRes->offset = (int32_t)pData->num;

    pData->num += size;
    assert(pWindowRes->pageId >= 0);
  }

  return 0;
}

L
Liu Jicong 已提交
663 664 665
static bool chkWindowOutputBufByKey(STaskRuntimeEnv* pRuntimeEnv, SResultRowInfo* pResultRowInfo, STimeWindow* win,
                                    bool masterscan, SResultRow** pResult, int64_t groupId, SqlFunctionCtx* pCtx,
                                    int32_t numOfOutput, int32_t* rowCellInfoOffset) {
666
  assert(win->skey <= win->ekey);
L
Liu Jicong 已提交
667
  return chkResultRowFromKey(pRuntimeEnv, pResultRowInfo, (char*)&win->skey, TSDB_KEYSIZE, masterscan, groupId);
668 669
}

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

L
Liu Jicong 已提交
672 673 674 675
static int32_t setResultOutputBufByKey_rv(SResultRowInfo* pResultRowInfo, int64_t id, STimeWindow* win, bool masterscan,
                                          SResultRow** pResult, int64_t tableGroupId, SqlFunctionCtx* pCtx,
                                          int32_t numOfOutput, int32_t* rowCellInfoOffset, SAggSupporter* pAggSup,
                                          SExecTaskInfo* pTaskInfo) {
H
Haojun Liao 已提交
676
  assert(win->skey <= win->ekey);
L
Liu Jicong 已提交
677 678
  SResultRow* pResultRow = doSetResultOutBufByKey_rv(pAggSup->pResultBuf, pResultRowInfo, id, (char*)&win->skey,
                                                     TSDB_KEYSIZE, masterscan, tableGroupId, pTaskInfo, true, pAggSup);
H
Haojun Liao 已提交
679 680 681 682 683 684 685 686 687

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

  // set time window for current result
  pResultRow->win = (*win);
  *pResult = pResultRow;
H
Haojun Liao 已提交
688
  setResultRowOutputBufInitCtx_rv(pResultRow, pCtx, numOfOutput, rowCellInfoOffset);
H
Haojun Liao 已提交
689 690 691
  return TSDB_CODE_SUCCESS;
}

692 693 694 695 696
static void setResultRowInterpo(SResultRow* pResult, SResultTsInterpType type) {
  assert(pResult != NULL && (type == RESULT_ROW_START_INTERP || type == RESULT_ROW_END_INTERP));
  if (type == RESULT_ROW_START_INTERP) {
    pResult->startInterp = true;
  } else {
L
Liu Jicong 已提交
697
    pResult->endInterp = true;
698 699 700 701 702 703 704 705
  }
}

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

L
Liu Jicong 已提交
710 711
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) {
712 713 714
  int32_t forwardStep = 0;

  if (order == TSDB_ORDER_ASC) {
L
Liu Jicong 已提交
715
    int32_t end = searchFn((char*)&pData[pos], numOfRows - pos, ekey, order);
716 717 718 719 720 721 722 723
    if (end >= 0) {
      forwardStep = end;

      if (pData[end + pos] == ekey) {
        forwardStep += 1;
      }
    }
  } else {
L
Liu Jicong 已提交
724
    int32_t end = searchFn((char*)pData, pos + 1, ekey, order);
725 726 727 728 729 730 731 732 733 734 735 736 737
    if (end >= 0) {
      forwardStep = pos - end;

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

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

H
Haojun Liao 已提交
738
static void doUpdateResultRowIndex(SResultRowInfo* pResultRowInfo, TSKEY lastKey, bool ascQuery, bool timeWindowInterpo) {
739
  int64_t skey = TSKEY_INITIAL_VAL;
H
Haojun Liao 已提交
740
#if 0
741 742
  int32_t i = 0;
  for (i = pResultRowInfo->size - 1; i >= 0; --i) {
L
Liu Jicong 已提交
743
    SResultRow* pResult = pResultRowInfo->pResult[i];
744 745 746 747 748 749
    if (pResult->closed) {
      break;
    }

    // new closed result rows
    if (timeWindowInterpo) {
L
Liu Jicong 已提交
750 751 752
      if (pResult->endInterp &&
          ((pResult->win.skey <= lastKey && ascQuery) || (pResult->win.skey >= lastKey && !ascQuery))) {
        if (i > 0) {  // the first time window, the startInterp is false.
753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771
          assert(pResult->startInterp);
        }

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

  // all result rows are closed, set the last one to be the skey
  if (skey == TSKEY_INITIAL_VAL) {
    if (pResultRowInfo->size == 0) {
L
Liu Jicong 已提交
772
      //      assert(pResultRowInfo->current == NULL);
773 774 775 776 777 778 779
      assert(pResultRowInfo->curPos == -1);
      pResultRowInfo->curPos = -1;
    } else {
      pResultRowInfo->curPos = pResultRowInfo->size - 1;
    }
  } else {
    for (i = pResultRowInfo->size - 1; i >= 0; --i) {
L
Liu Jicong 已提交
780
      SResultRow* pResult = pResultRowInfo->pResult[i];
781 782 783 784 785 786 787 788 789 790 791
      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 已提交
792
#endif
793 794
}

L
Liu Jicong 已提交
795 796
static void updateResultRowInfoActiveIndex(SResultRowInfo* pResultRowInfo, const STimeWindow* pWin, TSKEY lastKey,
                                           bool ascQuery, bool interp) {
H
Haojun Liao 已提交
797
  if ((lastKey > pWin->ekey && ascQuery) || (lastKey < pWin->ekey && (!ascQuery))) {
798 799 800 801
    closeAllResultRows(pResultRowInfo);
    pResultRowInfo->curPos = pResultRowInfo->size - 1;
  } else {
    int32_t step = ascQuery ? 1 : -1;
H
Haojun Liao 已提交
802
    doUpdateResultRowIndex(pResultRowInfo, lastKey - step, ascQuery, interp);
803 804 805
  }
}

L
Liu Jicong 已提交
806 807 808
static int32_t getNumOfRowsInTimeWindow(SDataBlockInfo* pDataBlockInfo, TSKEY* pPrimaryColumn, int32_t startPos,
                                        TSKEY ekey, __block_search_fn_t searchFn, STableQueryInfo* item,
                                        int32_t order) {
809 810
  assert(startPos >= 0 && startPos < pDataBlockInfo->rows);

L
Liu Jicong 已提交
811 812
  int32_t num = -1;
  int32_t step = GET_FORWARD_DIRECTION_FACTOR(order);
813

H
Haojun Liao 已提交
814
  if (order == TSDB_ORDER_ASC) {
815 816
    if (ekey < pDataBlockInfo->window.ekey && pPrimaryColumn) {
      num = getForwardStepsInBlock(pDataBlockInfo->rows, searchFn, ekey, startPos, order, pPrimaryColumn);
H
Haojun Liao 已提交
817
      if (item != NULL) {
818 819 820 821
        item->lastKey = pPrimaryColumn[startPos + (num - 1)] + step;
      }
    } else {
      num = pDataBlockInfo->rows - startPos;
H
Haojun Liao 已提交
822
      if (item != NULL) {
823 824 825 826 827 828
        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 已提交
829
      if (item != NULL) {
830 831 832 833
        item->lastKey = pPrimaryColumn[startPos - (num - 1)] + step;
      }
    } else {
      num = startPos + 1;
H
Haojun Liao 已提交
834
      if (item != NULL) {
835 836 837 838 839 840 841 842 843
        item->lastKey = pDataBlockInfo->window.skey + step;
      }
    }
  }

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

844 845 846 847 848
//  query_range_start, query_range_end, window_duration, window_start, window_end
static void initExecTimeWindowInfo(SColumnInfoData* pColData, STimeWindow* pQueryWindow) {
  pColData->info.type = TSDB_DATA_TYPE_TIMESTAMP;
  pColData->info.bytes = sizeof(int64_t);

H
Haojun Liao 已提交
849
  colInfoDataEnsureCapacity(pColData, 5);
850 851 852 853 854 855 856 857 858
  colDataAppendInt64(pColData, 0, &pQueryWindow->skey);
  colDataAppendInt64(pColData, 1, &pQueryWindow->ekey);

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

859
static void updateTimeWindowInfo(SColumnInfoData* pColData, STimeWindow* pWin, bool includeEndpoint) {
860
  int64_t* ts = (int64_t*)pColData->pData;
861
  int32_t delta = includeEndpoint? 1:0;
862

863
  int64_t duration = pWin->ekey - pWin->skey + delta;
864 865
  ts[2] = duration;       // set the duration
  ts[3] = pWin->skey;     // window start key
866
  ts[4] = pWin->ekey + delta; // window end key
867 868
}

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

H
Haojun Liao 已提交
874
    // keep it temporarily
875 876
    bool    hasAgg      = pCtx[k].input.colDataAggIsSet;
    int32_t numOfRows   = pCtx[k].input.numOfRows;
H
Haojun Liao 已提交
877
    int32_t startOffset = pCtx[k].input.startRowIndex;
878

H
Haojun Liao 已提交
879
    int32_t pos = (order == TSDB_ORDER_ASC) ? offset : offset - (forwardStep - 1);
880 881
    pCtx[k].input.startRowIndex = pos;
    pCtx[k].input.numOfRows = forwardStep;
882 883

    if (tsCol != NULL) {
H
Haojun Liao 已提交
884
      pCtx[k].ptsList = tsCol;
885 886 887 888 889 890 891 892
    }

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

893 894 895 896
    if (fmIsWindowPseudoColumnFunc(pCtx[k].functionId)) {
      SResultRowEntryInfo* pEntryInfo = GET_RES_INFO(&pCtx[k]);
      char* p = GET_ROWCELL_INTERBUF(pEntryInfo);

897 898 899 900 901 902 903 904
      SColumnInfoData idata = {0};
      idata.info.type  = TSDB_DATA_TYPE_BIGINT;
      idata.info.bytes = tDataTypes[TSDB_DATA_TYPE_BIGINT].bytes;
      idata.pData      = p;

      SScalarParam out = {.columnData = &idata};
      SScalarParam tw = {.numOfRows = 5, .columnData = pTimeWindowData};
      pCtx[k].sfp.process(&tw, 1, &out);
905 906 907 908
      pEntryInfo->numOfRes = 1;
      continue;
    }

H
Haojun Liao 已提交
909
    if (functionNeedToExecute(&pCtx[k])) {
910
      pCtx[k].fpSet.process(&pCtx[k]);
911 912 913
    }

    // restore it
914 915 916
    pCtx[k].input.colDataAggIsSet = hasAgg;
    pCtx[k].input.startRowIndex = startOffset;
    pCtx[k].input.numOfRows = numOfRows;
917 918 919
  }
}

H
Haojun Liao 已提交
920 921 922
static int32_t getNextQualifiedWindow(SInterval* pInterval, STimeWindow* pNext, SDataBlockInfo* pDataBlockInfo,
                                      TSKEY* primaryKeys, int32_t prevPosition, STableIntervalOperatorInfo* pInfo) {
  int32_t order = pInfo->order;
L
Liu Jicong 已提交
923
  bool    ascQuery = (order == TSDB_ORDER_ASC);
H
Haojun Liao 已提交
924

925
  int32_t precision = pInterval->precision;
H
Haojun Liao 已提交
926
  getNextTimeWindow(pInterval, precision, order, pNext);
927 928

  // next time window is not in current block
H
Haojun Liao 已提交
929 930
  if ((pNext->skey > pDataBlockInfo->window.ekey && order == TSDB_ORDER_ASC) ||
      (pNext->ekey < pDataBlockInfo->window.skey && order == TSDB_ORDER_DESC)) {
931 932 933
    return -1;
  }

L
Liu Jicong 已提交
934
  TSKEY   startKey = ascQuery ? pNext->skey : pNext->ekey;
935 936 937
  int32_t startPos = 0;

  // tumbling time window query, a special case of sliding time window query
H
Haojun Liao 已提交
938 939
  if (pInterval->sliding == pInterval->interval && prevPosition != -1) {
    int32_t factor = GET_FORWARD_DIRECTION_FACTOR(order);
940 941
    startPos = prevPosition + factor;
  } else {
H
Haojun Liao 已提交
942
    if (startKey <= pDataBlockInfo->window.skey && ascQuery) {
943
      startPos = 0;
H
Haojun Liao 已提交
944
    } else if (startKey >= pDataBlockInfo->window.ekey && !ascQuery) {
945 946
      startPos = pDataBlockInfo->rows - 1;
    } else {
L
Liu Jicong 已提交
947
      startPos = binarySearchForKey((char*)primaryKeys, pDataBlockInfo->rows, startKey, order);
948 949 950 951
    }
  }

  /* interp query with fill should not skip time window */
L
Liu Jicong 已提交
952 953 954
  //  if (pQueryAttr->pointInterpQuery && pQueryAttr->fillType != TSDB_FILL_NONE) {
  //    return startPos;
  //  }
955 956 957 958 959 960

  /*
   * 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 已提交
961
    if (ascQuery) {
962 963 964 965 966
      assert(pDataBlockInfo->window.skey <= pNext->ekey);
    } else {
      assert(pDataBlockInfo->window.ekey >= pNext->skey);
    }
  } else {
H
Haojun Liao 已提交
967
    if (ascQuery && primaryKeys[startPos] > pNext->ekey) {
968
      TSKEY next = primaryKeys[startPos];
H
Haojun Liao 已提交
969 970 971
      if (pInterval->intervalUnit == 'n' || pInterval->intervalUnit == 'y') {
        pNext->skey = taosTimeTruncate(next, pInterval, precision);
        pNext->ekey = taosTimeAdd(pNext->skey, pInterval->interval, pInterval->intervalUnit, precision) - 1;
972
      } else {
L
Liu Jicong 已提交
973
        pNext->ekey += ((next - pNext->ekey + pInterval->sliding - 1) / pInterval->sliding) * pInterval->sliding;
H
Haojun Liao 已提交
974
        pNext->skey = pNext->ekey - pInterval->interval + 1;
975
      }
H
Haojun Liao 已提交
976
    } else if ((!ascQuery) && primaryKeys[startPos] < pNext->skey) {
977
      TSKEY next = primaryKeys[startPos];
H
Haojun Liao 已提交
978 979 980
      if (pInterval->intervalUnit == 'n' || pInterval->intervalUnit == 'y') {
        pNext->skey = taosTimeTruncate(next, pInterval, precision);
        pNext->ekey = taosTimeAdd(pNext->skey, pInterval->interval, pInterval->intervalUnit, precision) - 1;
981
      } else {
H
Haojun Liao 已提交
982 983
        pNext->skey -= ((pNext->skey - next + pInterval->sliding - 1) / pInterval->sliding) * pInterval->sliding;
        pNext->ekey = pNext->skey + pInterval->interval - 1;
984 985 986 987 988 989 990
      }
    }
  }

  return startPos;
}

L
Liu Jicong 已提交
991
static FORCE_INLINE TSKEY reviseWindowEkey(STaskAttr* pQueryAttr, STimeWindow* pWindow) {
992
  TSKEY ekey = -1;
993 994
  int32_t order = TSDB_ORDER_ASC;
  if (order == TSDB_ORDER_ASC) {
995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008
    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 已提交
1009
static void setNotInterpoWindowKey(SqlFunctionCtx* pCtx, int32_t numOfOutput, int32_t type) {
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
  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 已提交
1021
static void saveDataBlockLastRow(char** pRow, SArray* pDataBlock, int32_t rowIndex, int32_t numOfCols) {
1022 1023 1024 1025
  if (pDataBlock == NULL) {
    return;
  }

H
Haojun Liao 已提交
1026
  for (int32_t k = 0; k < numOfCols; ++k) {
L
Liu Jicong 已提交
1027
    SColumnInfoData* pColInfo = taosArrayGet(pDataBlock, k);
H
Haojun Liao 已提交
1028
    memcpy(pRow[k], ((char*)pColInfo->pData) + (pColInfo->info.bytes * rowIndex), pColInfo->info.bytes);
1029 1030 1031
  }
}

H
Haojun Liao 已提交
1032
static TSKEY getStartTsKey(STimeWindow* win, const TSKEY* tsCols, int32_t rows, bool ascQuery) {
1033 1034
  TSKEY ts = TSKEY_INITIAL_VAL;
  if (tsCols == NULL) {
L
Liu Jicong 已提交
1035
    ts = ascQuery ? win->skey : win->ekey;
1036
  } else {
L
Liu Jicong 已提交
1037
    int32_t offset = ascQuery ? 0 : rows - 1;
1038 1039 1040 1041 1042 1043
    ts = tsCols[offset];
  }

  return ts;
}

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

L
Liu Jicong 已提交
1046 1047
static void doSetInputDataBlockInfo(SOperatorInfo* pOperator, SqlFunctionCtx* pCtx, SSDataBlock* pBlock,
                                    int32_t order) {
1048 1049
  for (int32_t i = 0; i < pOperator->numOfOutput; ++i) {
    pCtx[i].order = order;
L
Liu Jicong 已提交
1050
    pCtx[i].size = pBlock->info.rows;
1051 1052
    pCtx[i].currentStage = (uint8_t)pOperator->pRuntimeEnv->scanFlag;

L
Liu Jicong 已提交
1053
    setBlockStatisInfo(&pCtx[i], pBlock, NULL /*&pOperator->pExpr[i].base.colInfo*/);
1054 1055 1056
  }
}

H
Haojun Liao 已提交
1057
void setInputDataBlock(SOperatorInfo* pOperator, SqlFunctionCtx* pCtx, SSDataBlock* pBlock, int32_t order) {
H
Haojun Liao 已提交
1058 1059 1060 1061 1062
  if (pBlock->pDataBlock != NULL) {
    doSetInputDataBlock(pOperator, pCtx, pBlock, order);
  } else {
    doSetInputDataBlockInfo(pOperator, pCtx, pBlock, order);
  }
1063 1064
}

H
Haojun Liao 已提交
1065
static void doSetInputDataBlock(SOperatorInfo* pOperator, SqlFunctionCtx* pCtx, SSDataBlock* pBlock, int32_t order) {
1066 1067
  for (int32_t i = 0; i < pOperator->numOfOutput; ++i) {
    pCtx[i].order = order;
L
Liu Jicong 已提交
1068
    pCtx[i].size = pBlock->info.rows;
H
Haojun Liao 已提交
1069 1070
    pCtx[i].currentStage = MAIN_SCAN;

1071 1072 1073
    SExprInfo* pOneExpr = &pOperator->pExpr[i];
    for (int32_t j = 0; j < pOneExpr->base.numOfParams; ++j) {
      SFunctParam *pFuncParam = &pOneExpr->base.pParam[j];
G
Ganlin Zhao 已提交
1074 1075 1076 1077 1078 1079 1080 1081 1082
      if (pFuncParam->type == FUNC_PARAM_TYPE_COLUMN) {
        int32_t slotId = pFuncParam->pCol->slotId;
        pCtx[i].input.pData[j]  = 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[j] != NULL);
      }
    }
H
Haojun Liao 已提交
1083

H
Haojun Liao 已提交
1084
    //    setBlockStatisInfo(&pCtx[i], pBlock, pOperator->pExpr[i].base.pColumns);
H
Haojun Liao 已提交
1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100
    //      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.
G
Ganlin Zhao 已提交
1101 1102 1103 1104
    //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;
H
Haojun Liao 已提交
1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132


    //        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) {
1133
  for (int32_t k = 0; k < pOperator->numOfOutput; ++k) {
H
Haojun Liao 已提交
1134
    if (functionNeedToExecute(&pCtx[k])) {
L
Liu Jicong 已提交
1135
      pCtx[k].startTs = startTs;  // this can be set during create the struct
H
Haojun Liao 已提交
1136
      pCtx[k].fpSet.process(&pCtx[k]);
1137 1138 1139 1140
    }
  }
}

H
Haojun Liao 已提交
1141
static void setPseudoOutputColInfo(SSDataBlock* pResult, SqlFunctionCtx* pCtx, SArray* pPseudoList) {
1142
  size_t num = (pPseudoList != NULL)? taosArrayGetSize(pPseudoList):0;
H
Haojun Liao 已提交
1143 1144 1145 1146 1147
  for (int32_t i = 0; i < num; ++i) {
    pCtx[i].pOutput = taosArrayGet(pResult->pDataBlock, i);
  }
}

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

1152
  for (int32_t k = 0; k < numOfOutput; ++k) {
1153 1154 1155
    int32_t outputSlotId = pExpr[k].base.resSchema.slotId;
    SqlFunctionCtx* pfCtx = &pCtx[k];

L
Liu Jicong 已提交
1156
    if (pExpr[k].pExpr->nodeType == QUERY_NODE_COLUMN) {  // it is a project query
1157 1158
      SColumnInfoData* pColInfoData = taosArrayGet(pResult->pDataBlock, outputSlotId);
      colDataAssign(pColInfoData, pfCtx->input.pData[0], pfCtx->input.numOfRows);
1159

1160
      pResult->info.rows = pSrcBlock->info.rows;
1161
    } else if (pExpr[k].pExpr->nodeType == QUERY_NODE_VALUE) {
1162
      SColumnInfoData* pColInfoData = taosArrayGet(pResult->pDataBlock, outputSlotId);
1163
      for (int32_t i = 0; i < pSrcBlock->info.rows; ++i) {
1164
        colDataAppend(pColInfoData, i, taosVariantGet(&pExpr[k].base.pParam[0].param, pExpr[k].base.pParam[0].param.nType), TSDB_DATA_TYPE_NULL == pExpr[k].base.pParam[0].param.nType);
1165 1166
      }
      pResult->info.rows = pSrcBlock->info.rows;
H
Haojun Liao 已提交
1167
    } else if (pExpr[k].pExpr->nodeType == QUERY_NODE_OPERATOR) {
1168 1169 1170
      SArray* pBlockList = taosArrayInit(4, POINTER_BYTES);
      taosArrayPush(pBlockList, &pSrcBlock);

1171
      SScalarParam dest = {0};
1172
      dest.columnData = taosArrayGet(pResult->pDataBlock, outputSlotId);
1173 1174 1175 1176 1177 1178

      scalarCalculate(pExpr[k].pExpr->_optrRoot.pRootNode, pBlockList, &dest);
      pResult->info.rows = dest.numOfRows;

      taosArrayDestroy(pBlockList);
    } else if (pExpr[k].pExpr->nodeType == QUERY_NODE_FUNCTION) {
1179
      ASSERT(!fmIsAggFunc(pfCtx->functionId));
1180

1181
      if (fmIsPseudoColumnFunc(pfCtx->functionId)) {
H
Haojun Liao 已提交
1182
        // do nothing
1183
      } else if (fmIsNonstandardSQLFunc(pfCtx->functionId)) {
H
Haojun Liao 已提交
1184
        // todo set the correct timestamp column
1185
        pfCtx->input.pPTS = taosArrayGet(pSrcBlock->pDataBlock, 1);
1186

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

1190 1191
        pfCtx->pOutput = taosArrayGet(pResult->pDataBlock, outputSlotId);
        pfCtx->offset  = pResult->info.rows;  // set the start offset
H
Haojun Liao 已提交
1192

1193 1194
        if (taosArrayGetSize(pPseudoList) > 0) {
          int32_t* outputColIndex = taosArrayGet(pPseudoList, 0);
1195
          pfCtx->pTsOutput = (SColumnInfoData*)pCtx[*outputColIndex].pOutput;
1196
        }
H
Haojun Liao 已提交
1197

1198
        int32_t numOfRows = pfCtx->fpSet.process(pfCtx);
H
Haojun Liao 已提交
1199
        pResult->info.rows += numOfRows;
H
Haojun Liao 已提交
1200 1201 1202
      } else {
        SArray* pBlockList = taosArrayInit(4, POINTER_BYTES);
        taosArrayPush(pBlockList, &pSrcBlock);
G
Ganlin Zhao 已提交
1203

H
Haojun Liao 已提交
1204
        SScalarParam dest = {0};
1205
        dest.columnData = taosArrayGet(pResult->pDataBlock, outputSlotId);
H
Haojun Liao 已提交
1206 1207 1208 1209 1210

        scalarCalculate((SNode*)pExpr[k].pExpr->_function.pFunctNode, pBlockList, &dest);
        pResult->info.rows = dest.numOfRows;
        taosArrayDestroy(pBlockList);
      }
1211
    } else {
1212
      ASSERT(0);
1213 1214 1215 1216 1217 1218
    }
  }
}

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

H
Haojun Liao 已提交
1222
  SqlFunctionCtx* pCtx = pInfo->pCtx;
1223 1224 1225 1226 1227 1228 1229 1230

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

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

L
Liu Jicong 已提交
1235
    //    assert(pColInfo->info.colId == pColIndex->info.colId && curTs != windowKey);
1236 1237 1238
    double v1 = 0, v2 = 0, v = 0;

    if (prevRowIndex == -1) {
L
Liu Jicong 已提交
1239
      GET_TYPED_DATA(v1, double, pColInfo->info.type, (char*)pRuntimeEnv->prevRow[index]);
1240
    } else {
L
Liu Jicong 已提交
1241
      GET_TYPED_DATA(v1, double, pColInfo->info.type, (char*)pColInfo->pData + prevRowIndex * pColInfo->info.bytes);
1242 1243
    }

L
Liu Jicong 已提交
1244
    GET_TYPED_DATA(v2, double, pColInfo->info.type, (char*)pColInfo->pData + curRowIndex * pColInfo->info.bytes);
1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255

    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) {
L
Liu Jicong 已提交
1256
            pCtx[k].start.ptr = (char*)pRuntimeEnv->prevRow[index];
1257
          } else {
L
Liu Jicong 已提交
1258
            pCtx[k].start.ptr = (char*)pColInfo->pData + prevRowIndex * pColInfo->info.bytes;
1259 1260
          }

L
Liu Jicong 已提交
1261
          pCtx[k].end.ptr = (char*)pColInfo->pData + curRowIndex * pColInfo->info.bytes;
1262 1263 1264
        }
      }
    } else if (functionId == FUNCTION_TWA) {
L
Liu Jicong 已提交
1265 1266 1267
      SPoint point1 = (SPoint){.key = prevTs, .val = &v1};
      SPoint point2 = (SPoint){.key = curTs, .val = &v2};
      SPoint point = (SPoint){.key = windowKey, .val = &v};
1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281

      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 已提交
1282
static bool setTimeWindowInterpolationStartTs(SOperatorInfo* pOperatorInfo, SqlFunctionCtx* pCtx, int32_t pos,
H
Haojun Liao 已提交
1283 1284
                                              int32_t numOfRows, SArray* pDataBlock, const TSKEY* tsCols, STimeWindow* win) {
  bool  ascQuery = true;
L
Liu Jicong 已提交
1285
  TSKEY curTs = tsCols[pos];
H
Haojun Liao 已提交
1286
  TSKEY lastTs = 0;//*(TSKEY*)pRuntimeEnv->prevRow[0];
1287 1288 1289

  // lastTs == INT64_MIN and pos == 0 means this is the first time window, interpolation is not needed.
  // start exactly from this point, no need to do interpolation
L
Liu Jicong 已提交
1290
  TSKEY key = ascQuery ? win->skey : win->ekey;
1291 1292 1293 1294 1295 1296 1297 1298 1299 1300
  if (key == curTs) {
    setNotInterpoWindowKey(pCtx, pOperatorInfo->numOfOutput, RESULT_ROW_START_INTERP);
    return true;
  }

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

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

H
Haojun Liao 已提交
1304
  doTimeWindowInterpolation(pOperatorInfo, pOperatorInfo->info, pDataBlock, prevTs, pos - step, curTs, pos, key, RESULT_ROW_START_INTERP);
1305 1306 1307
  return true;
}

L
Liu Jicong 已提交
1308 1309 1310
static bool setTimeWindowInterpolationEndTs(SOperatorInfo* pOperatorInfo, SqlFunctionCtx* pCtx, int32_t endRowIndex,
                                            SArray* pDataBlock, const TSKEY* tsCols, TSKEY blockEkey,
                                            STimeWindow* win) {
H
Haojun Liao 已提交
1311 1312
  int32_t order = TSDB_ORDER_ASC;
  int32_t numOfOutput = pOperatorInfo->numOfOutput;
1313

L
Liu Jicong 已提交
1314
  TSKEY actualEndKey = tsCols[endRowIndex];
H
Haojun Liao 已提交
1315
  TSKEY key = order ? win->ekey : win->skey;
1316 1317

  // not ended in current data block, do not invoke interpolation
H
Haojun Liao 已提交
1318
  if ((key > blockEkey /*&& QUERY_IS_ASC_QUERY(pQueryAttr)*/) || (key < blockEkey /*&& !QUERY_IS_ASC_QUERY(pQueryAttr)*/)) {
1319 1320 1321 1322 1323 1324 1325 1326 1327 1328
    setNotInterpoWindowKey(pCtx, numOfOutput, RESULT_ROW_END_INTERP);
    return false;
  }

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

H
Haojun Liao 已提交
1329
  int32_t step = GET_FORWARD_DIRECTION_FACTOR(order);
1330 1331 1332 1333 1334
  int32_t nextRowIndex = endRowIndex + step;
  assert(nextRowIndex >= 0);

  TSKEY nextKey = tsCols[nextRowIndex];
  doTimeWindowInterpolation(pOperatorInfo, pOperatorInfo->info, pDataBlock, actualEndKey, endRowIndex, nextKey,
L
Liu Jicong 已提交
1335
                            nextRowIndex, key, RESULT_ROW_END_INTERP);
1336 1337 1338
  return true;
}

H
Haojun Liao 已提交
1339
static void doWindowBorderInterpolation(SOperatorInfo* pOperatorInfo, SSDataBlock* pBlock, SqlFunctionCtx* pCtx,
L
Liu Jicong 已提交
1340 1341
                                        SResultRow* pResult, STimeWindow* win, int32_t startPos, int32_t forwardStep,
                                        int32_t order, bool timeWindowInterpo) {
H
Haojun Liao 已提交
1342
  if (!timeWindowInterpo) {
1343 1344 1345 1346
    return;
  }

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

L
Liu Jicong 已提交
1349 1350
  if (pBlock->pDataBlock == NULL) {
    //    tscError("pBlock->pDataBlock == NULL");
1351 1352
    return;
  }
H
Haojun Liao 已提交
1353

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

L
Liu Jicong 已提交
1356 1357 1358
  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
1359
    int32_t startRowIndex = startPos;
L
Liu Jicong 已提交
1360 1361
    bool    interp = setTimeWindowInterpolationStartTs(pOperatorInfo, pCtx, startRowIndex, pBlock->info.rows,
                                                       pBlock->pDataBlock, tsCols, win);
1362 1363 1364 1365
    if (interp) {
      setResultRowInterpo(pResult, RESULT_ROW_START_INTERP);
    }
  } else {
H
Haojun Liao 已提交
1366
    setNotInterpoWindowKey(pCtx, pOperatorInfo->numOfOutput, RESULT_ROW_START_INTERP);
1367 1368 1369
  }

  // point interpolation does not require the end key time window interpolation.
L
Liu Jicong 已提交
1370 1371 1372
  //  if (pointInterpQuery) {
  //    return;
  //  }
1373 1374 1375 1376 1377 1378

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

L
Liu Jicong 已提交
1379 1380 1381
    TSKEY endKey = (order == TSDB_ORDER_ASC) ? pBlock->info.window.ekey : pBlock->info.window.skey;
    bool  interp =
        setTimeWindowInterpolationEndTs(pOperatorInfo, pCtx, endRowIndex, pBlock->pDataBlock, tsCols, endKey, win);
1382 1383 1384 1385
    if (interp) {
      setResultRowInterpo(pResult, RESULT_ROW_END_INTERP);
    }
  } else {
H
Haojun Liao 已提交
1386
    setNotInterpoWindowKey(pCtx, pOperatorInfo->numOfOutput, RESULT_ROW_END_INTERP);
1387 1388 1389
  }
}

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

H
Haojun Liao 已提交
1393
  SExecTaskInfo* pTaskInfo = pOperatorInfo->pTaskInfo;
L
Liu Jicong 已提交
1394
  int32_t        numOfOutput = pOperatorInfo->numOfOutput;
1395

1396 1397 1398 1399 1400
  SArray* pUpdated = NULL;
  if (pInfo->execModel == OPTR_EXEC_MODEL_STREAM) {
    pUpdated = taosArrayInit(4, sizeof(SResultRowPosition));
  }

H
Haojun Liao 已提交
1401
  int32_t step = 1;
1402
  bool    ascScan = true;
1403 1404 1405 1406 1407

  int32_t prevIndex = pResultRowInfo->curPos;

  TSKEY* tsCols = NULL;
  if (pSDataBlock->pDataBlock != NULL) {
1408
    SColumnInfoData* pColDataInfo = taosArrayGet(pSDataBlock->pDataBlock, pInfo->primaryTsIndex);
L
Liu Jicong 已提交
1409
    tsCols = (int64_t*)pColDataInfo->pData;
H
Haojun Liao 已提交
1410 1411
//    assert(tsCols[0] == pSDataBlock->info.window.skey && tsCols[pSDataBlock->info.rows - 1] ==
//           pSDataBlock->info.window.ekey);
1412 1413
  }

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

H
Haojun Liao 已提交
1417
  STimeWindow win = getActiveTimeWindow(pInfo->aggSup.pResultBuf, pResultRowInfo, ts, &pInfo->interval, pInfo->interval.precision, &pInfo->win);
L
Liu Jicong 已提交
1418
  bool        masterScan = true;
1419 1420

  SResultRow* pResult = NULL;
L
Liu Jicong 已提交
1421 1422 1423
  int32_t     ret = setResultOutputBufByKey_rv(pResultRowInfo, pSDataBlock->info.uid, &win, masterScan, &pResult,
                                               tableGroupId, pInfo->binfo.pCtx, numOfOutput, pInfo->binfo.rowCellInfoOffset,
                                               &pInfo->aggSup, pTaskInfo);
1424
  if (ret != TSDB_CODE_SUCCESS || pResult == NULL) {
H
Haojun Liao 已提交
1425
    longjmp(pTaskInfo->env, TSDB_CODE_QRY_OUT_OF_MEMORY);
1426 1427
  }

1428 1429 1430 1431 1432
  if (pInfo->execModel == OPTR_EXEC_MODEL_STREAM) {
    SResultRowPosition pos = {.pageId = pResult->pageId, .offset = pResult->offset};
    taosArrayPush(pUpdated, &pos);
  }

1433
  int32_t forwardStep = 0;
H
Haojun Liao 已提交
1434
  TSKEY   ekey = win.ekey;
1435
  forwardStep =
H
Haojun Liao 已提交
1436
      getNumOfRowsInTimeWindow(&pSDataBlock->info, tsCols, startPos, ekey, binarySearchForKey, NULL, TSDB_ORDER_ASC);
1437 1438 1439

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

#if 0
H
Haojun Liao 已提交
1442
  if (prevIndex != -1 && prevIndex < curIndex && pInfo->timeWindowInterpo) {
1443 1444 1445
    for (int32_t j = prevIndex; j < curIndex; ++j) {  // previous time window may be all closed already.
      SResultRow* pRes = getResultRow(pResultRowInfo, j);
      if (pRes->closed) {
1446
        assert(resultRowInterpolated(pRes, RESULT_ROW_START_INTERP) && resultRowInterpolated(pRes, RESULT_ROW_END_INTERP));
1447 1448 1449
        continue;
      }

L
Liu Jicong 已提交
1450 1451 1452 1453 1454 1455 1456
      STimeWindow w = pRes->win;
      ret = setResultOutputBufByKey_rv(pResultRowInfo, pSDataBlock->info.uid, &w, masterScan, &pResult, tableGroupId,
                                       pInfo->binfo.pCtx, numOfOutput, pInfo->binfo.rowCellInfoOffset, &pInfo->aggSup,
                                       pTaskInfo);
      if (ret != TSDB_CODE_SUCCESS) {
        longjmp(pTaskInfo->env, TSDB_CODE_QRY_OUT_OF_MEMORY);
      }
1457

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

L
Liu Jicong 已提交
1462 1463
      setResultRowInterpo(pResult, RESULT_ROW_END_INTERP);
      setNotInterpoWindowKey(pInfo->binfo.pCtx, pOperatorInfo->numOfOutput, RESULT_ROW_START_INTERP);
1464

1465
      doApplyFunctions(pInfo->binfo.pCtx, &w, &pInfo->timeWindowData, startPos, 0, tsCols, pSDataBlock->info.rows, numOfOutput, TSDB_ORDER_ASC);
L
Liu Jicong 已提交
1466
    }
1467 1468

    // restore current time window
L
Liu Jicong 已提交
1469 1470 1471
    ret = setResultOutputBufByKey_rv(pResultRowInfo, pSDataBlock->info.uid, &win, masterScan, &pResult, tableGroupId,
                                     pInfo->binfo.pCtx, numOfOutput, pInfo->binfo.rowCellInfoOffset, &pInfo->aggSup,
                                     pTaskInfo);
1472
    if (ret != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
1473
      longjmp(pTaskInfo->env, TSDB_CODE_QRY_OUT_OF_MEMORY);
1474 1475
    }
  }
H
Haojun Liao 已提交
1476
#endif
1477 1478

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

  updateTimeWindowInfo(&pInfo->timeWindowData, &win, true);
1482
  doApplyFunctions(pInfo->binfo.pCtx, &win, &pInfo->timeWindowData, startPos, forwardStep, tsCols, pSDataBlock->info.rows, numOfOutput, TSDB_ORDER_ASC);
1483 1484 1485 1486

  STimeWindow nextWin = win;
  while (1) {
    int32_t prevEndPos = (forwardStep - 1) * step + startPos;
H
Haojun Liao 已提交
1487
    startPos = getNextQualifiedWindow(&pInfo->interval, &nextWin, &pSDataBlock->info, tsCols, prevEndPos, pInfo);
1488 1489 1490 1491 1492
    if (startPos < 0) {
      break;
    }

    // null data, failed to allocate more memory buffer
L
Liu Jicong 已提交
1493 1494 1495
    int32_t code = setResultOutputBufByKey_rv(pResultRowInfo, pSDataBlock->info.uid, &nextWin, masterScan, &pResult,
                                              tableGroupId, pInfo->binfo.pCtx, numOfOutput,
                                              pInfo->binfo.rowCellInfoOffset, &pInfo->aggSup, pTaskInfo);
1496
    if (code != TSDB_CODE_SUCCESS || pResult == NULL) {
H
Haojun Liao 已提交
1497
      longjmp(pTaskInfo->env, TSDB_CODE_QRY_OUT_OF_MEMORY);
1498 1499
    }

1500 1501 1502 1503 1504
    if (pInfo->execModel == OPTR_EXEC_MODEL_STREAM) {
      SResultRowPosition pos = {.pageId = pResult->pageId, .offset = pResult->offset};
      taosArrayPush(pUpdated, &pos);
    }

L
Liu Jicong 已提交
1505 1506 1507
    ekey = nextWin.ekey;  // reviseWindowEkey(pQueryAttr, &nextWin);
    forwardStep =
        getNumOfRowsInTimeWindow(&pSDataBlock->info, tsCols, startPos, ekey, binarySearchForKey, NULL, TSDB_ORDER_ASC);
1508 1509

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

H
Haojun Liao 已提交
1513
    updateTimeWindowInfo(&pInfo->timeWindowData, &nextWin, true);
1514
    doApplyFunctions(pInfo->binfo.pCtx, &nextWin, &pInfo->timeWindowData, startPos, forwardStep, tsCols, pSDataBlock->info.rows, numOfOutput, TSDB_ORDER_ASC);
1515 1516
  }

H
Haojun Liao 已提交
1517
  if (pInfo->timeWindowInterpo) {
1518
    int32_t rowIndex = ascScan ? (pSDataBlock->info.rows - 1) : 0;
H
Haojun Liao 已提交
1519
    saveDataBlockLastRow(pInfo->pRow, pSDataBlock->pDataBlock, rowIndex, pSDataBlock->info.numOfCols);
1520 1521
  }

1522
  return pUpdated;
L
Liu Jicong 已提交
1523
  //  updateResultRowInfoActiveIndex(pResultRowInfo, &pInfo->win, pRuntimeEnv->current->lastKey, true, false);
1524 1525
}

L
Liu Jicong 已提交
1526 1527 1528
static void hashAllIntervalAgg(SOperatorInfo* pOperatorInfo, SResultRowInfo* pResultRowInfo, SSDataBlock* pSDataBlock,
                               int32_t tableGroupId) {
  STableIntervalOperatorInfo* pInfo = (STableIntervalOperatorInfo*)pOperatorInfo->info;
1529

H
Haojun Liao 已提交
1530
  STaskRuntimeEnv* pRuntimeEnv = pOperatorInfo->pRuntimeEnv;
L
Liu Jicong 已提交
1531
  int32_t          numOfOutput = pOperatorInfo->numOfOutput;
1532

H
Haojun Liao 已提交
1533 1534
  int32_t step = 1;//GET_FORWARD_DIRECTION_FACTOR(pQueryAttr->order.order);
  bool    ascQuery = true;
1535 1536 1537 1538

  TSKEY* tsCols = NULL;
  if (pSDataBlock->pDataBlock != NULL) {
    SColumnInfoData* pColDataInfo = taosArrayGet(pSDataBlock->pDataBlock, 0);
L
Liu Jicong 已提交
1539
    tsCols = (int64_t*)pColDataInfo->pData;
1540 1541 1542 1543
    assert(tsCols[0] == pSDataBlock->info.window.skey &&
           tsCols[pSDataBlock->info.rows - 1] == pSDataBlock->info.window.ekey);
  }

L
Liu Jicong 已提交
1544 1545
  int32_t startPos = ascQuery ? 0 : (pSDataBlock->info.rows - 1);
  TSKEY   ts = getStartTsKey(&pSDataBlock->info.window, tsCols, pSDataBlock->info.rows, ascQuery);
1546

H
Haojun Liao 已提交
1547
  STimeWindow win = {0};//getCurrentActiveTimeWindow(pResultRowInfo, ts, pQueryAttr);
L
Liu Jicong 已提交
1548
  bool        masterScan = IS_MAIN_SCAN(pRuntimeEnv);
1549 1550

  SResultRow* pResult = NULL;
L
Liu Jicong 已提交
1551 1552
  int32_t     forwardStep = 0;
  int32_t     ret = 0;
1553 1554 1555 1556
  STimeWindow preWin = win;

  while (1) {
    // null data, failed to allocate more memory buffer
1557 1558
//    ret = setResultOutputBufByKey(pRuntimeEnv, pResultRowInfo, pSDataBlock->info.uid, &win, masterScan, &pResult,
//                                  tableGroupId, pInfo->binfo.pCtx, numOfOutput, pInfo->binfo.rowCellInfoOffset);
1559 1560 1561 1562
    if (ret != TSDB_CODE_SUCCESS) {
      longjmp(pRuntimeEnv->env, TSDB_CODE_QRY_OUT_OF_MEMORY);
    }

H
Haojun Liao 已提交
1563
    TSKEY ekey = 0;//reviseWindowEkey(pQueryAttr, &win);
L
Liu Jicong 已提交
1564 1565
    //    forwardStep = getNumOfRowsInTimeWindow(pRuntimeEnv, &pSDataBlock->info, tsCols, startPos, ekey,
    //    binarySearchForKey, true);
1566 1567

    // window start(end) key interpolation
L
Liu Jicong 已提交
1568 1569 1570
    //    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);
1571 1572 1573
    preWin = win;

    int32_t prevEndPos = (forwardStep - 1) * step + startPos;
L
Liu Jicong 已提交
1574 1575
    //    startPos = getNextQualifiedWindow(pQueryAttr, &win, &pSDataBlock->info, tsCols, binarySearchForKey,
    //    prevEndPos);
1576
    if (startPos < 0) {
H
Haojun Liao 已提交
1577 1578 1579 1580 1581 1582 1583 1584 1585
//      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, pInfo->binfo.pCtx, numOfOutput, pInfo->binfo.rowCellInfoOffset);
//        if (code != TSDB_CODE_SUCCESS || pResult == NULL) {
//          longjmp(pRuntimeEnv->env, TSDB_CODE_QRY_OUT_OF_MEMORY);
//        }
//
//        startPos = pSDataBlock->info.rows - 1;
1586 1587

        // window start(end) key interpolation
L
Liu Jicong 已提交
1588 1589 1590
        //        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);
H
Haojun Liao 已提交
1591
//      }
1592 1593 1594 1595 1596 1597

      break;
    }
    setResultRowInterpo(pResult, RESULT_ROW_END_INTERP);
  }

H
Haojun Liao 已提交
1598 1599
//  if (pQueryAttr->timeWindowInterpo) {
//    int32_t rowIndex = ascQuery ? (pSDataBlock->info.rows - 1) : 0;
L
Liu Jicong 已提交
1600
    //    saveDataBlockLastRow(pRuntimeEnv, &pSDataBlock->info, pSDataBlock->pDataBlock, rowIndex);
H
Haojun Liao 已提交
1601
//  }
1602

L
Liu Jicong 已提交
1603
  //  updateResultRowInfoActiveIndex(pResultRowInfo, pQueryAttr, pRuntimeEnv->current->lastKey);
1604 1605
}

1606 1607 1608 1609
static void doKeepTuple(SWindowRowsSup* pRowSup, int64_t ts) {
  pRowSup->win.ekey  = ts;
  pRowSup->prevTs    = ts;
  pRowSup->numOfRows += 1;
1610 1611
}

1612 1613 1614 1615
static void doKeepNewWindowStartInfo(SWindowRowsSup* pRowSup, const int64_t* tsList, int32_t rowIndex) {
  pRowSup->startRowIndex = rowIndex;
  pRowSup->numOfRows     = 0;
  pRowSup->win.skey      = tsList[rowIndex];
1616 1617
}

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

1622
  // todo find the correct time stamp column slot
1623
  SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, 0);
1624

1625 1626 1627
  bool    masterScan = true;
  int32_t numOfOutput = pOperator->numOfOutput;
  int64_t gid = pBlock->info.groupId;
1628

H
Haojun Liao 已提交
1629
  int64_t gap = pInfo->gap;
1630

1631
  if (!pInfo->reptScan) {
1632
    pInfo->reptScan = true;
1633
    pInfo->winSup.prevTs = INT64_MIN;
1634 1635
  }

1636 1637 1638
  SWindowRowsSup* pRowSup = &pInfo->winSup;
  pRowSup->numOfRows = 0;

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

      // keep the time window for the closed time window.
1655
      STimeWindow window = pRowSup->win;
1656

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

1664
      // pInfo->numOfRows data belong to the current session window
1665
      updateTimeWindowInfo(&pInfo->timeWindowData, &window, false);
1666
      doApplyFunctions(pInfo->binfo.pCtx, &window, &pInfo->timeWindowData, pRowSup->startRowIndex, pRowSup->numOfRows, NULL, pBlock->info.rows, numOfOutput, TSDB_ORDER_ASC);
1667

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

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

1682 1683
  updateTimeWindowInfo(&pInfo->timeWindowData, &pRowSup->win, false);
  doApplyFunctions(pInfo->binfo.pCtx, &pRowSup->win, &pInfo->timeWindowData, pRowSup->startRowIndex, pRowSup->numOfRows, NULL, pBlock->info.rows, numOfOutput, TSDB_ORDER_ASC);
1684 1685 1686 1687
}

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

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

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

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

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

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

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

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

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

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

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

  return true;
}

L
Liu Jicong 已提交
1749 1750
void setBlockStatisInfo(SqlFunctionCtx* pCtx, SSDataBlock* pSDataBlock, SColumn* pColumn) {
  SColumnDataAgg* pAgg = NULL;
1751

H
Haojun Liao 已提交
1752 1753
  if (pSDataBlock->pBlockAgg != NULL && TSDB_COL_IS_NORMAL_COL(pColumn->flag)) {
    pAgg = &pSDataBlock->pBlockAgg[pCtx->columnIndex];
1754 1755

    pCtx->agg = *pAgg;
L
Liu Jicong 已提交
1756
    pCtx->isAggSet = true;
1757 1758 1759 1760 1761
    assert(pCtx->agg.numOfNull <= pSDataBlock->info.rows);
  } else {
    pCtx->isAggSet = false;
  }

H
Haojun Liao 已提交
1762
  pCtx->hasNull = hasNull(pColumn, pAgg);
1763 1764

  // set the statistics data for primary time stamp column
H
Haojun Liao 已提交
1765
  if (pCtx->functionId == FUNCTION_SPREAD && pColumn->colId == PRIMARYKEY_TIMESTAMP_COL_ID) {
L
Liu Jicong 已提交
1766
    pCtx->isAggSet = true;
1767 1768 1769 1770 1771 1772
    pCtx->agg.min = pSDataBlock->info.window.skey;
    pCtx->agg.max = pSDataBlock->info.window.ekey;
  }
}

// set the output buffer for the selectivity + tag query
L
Liu Jicong 已提交
1773
static int32_t setCtxTagColumnInfo(SqlFunctionCtx* pCtx, int32_t numOfOutput) {
1774 1775 1776 1777 1778 1779 1780
  if (!isSelectivityWithTagsQuery(pCtx, numOfOutput)) {
    return TSDB_CODE_SUCCESS;
  }

  int32_t num = 0;
  int16_t tagLen = 0;

H
Haojun Liao 已提交
1781
  SqlFunctionCtx*  p = NULL;
wafwerar's avatar
wafwerar 已提交
1782
  SqlFunctionCtx** pTagCtx = taosMemoryCalloc(numOfOutput, POINTER_BYTES);
1783 1784 1785 1786 1787 1788 1789 1790
  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 已提交
1791
      tagLen += pCtx[i].resDataInfo.bytes;
1792
      pTagCtx[num++] = &pCtx[i];
L
Liu Jicong 已提交
1793
    } else if (1 /*(aAggs[functionId].status & FUNCSTATE_SELECTIVITY) != 0*/) {
1794 1795 1796 1797 1798 1799 1800 1801 1802 1803
      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) {
1804 1805 1806
    p->subsidiaryRes.pCtx = pTagCtx;
    p->subsidiaryRes.numOfCols = num;
    p->subsidiaryRes.bufLen = tagLen;
1807
  } else {
wafwerar's avatar
wafwerar 已提交
1808
    taosMemoryFreeClear(pTagCtx);
1809 1810 1811 1812 1813
  }

  return TSDB_CODE_SUCCESS;
}

1814
SqlFunctionCtx* createSqlFunctionCtx(SExprInfo* pExprInfo, int32_t numOfOutput, int32_t** rowCellInfoOffset) {
L
Liu Jicong 已提交
1815
  SqlFunctionCtx* pFuncCtx = (SqlFunctionCtx*)taosMemoryCalloc(numOfOutput, sizeof(SqlFunctionCtx));
H
Haojun Liao 已提交
1816 1817 1818 1819
  if (pFuncCtx == NULL) {
    return NULL;
  }

wafwerar's avatar
wafwerar 已提交
1820
  *rowCellInfoOffset = taosMemoryCalloc(numOfOutput, sizeof(int32_t));
H
Haojun Liao 已提交
1821
  if (*rowCellInfoOffset == 0) {
wafwerar's avatar
wafwerar 已提交
1822
    taosMemoryFreeClear(pFuncCtx);
H
Haojun Liao 已提交
1823 1824 1825 1826
    return NULL;
  }

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

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

1832
    pCtx->functionId = -1;
H
Haojun Liao 已提交
1833
    if (pExpr->pExpr->nodeType == QUERY_NODE_FUNCTION) {
H
Haojun Liao 已提交
1834
      SFuncExecEnv env = {0};
H
Haojun Liao 已提交
1835 1836
      pCtx->functionId = pExpr->pExpr->_function.pFunctNode->funcId;

H
Haojun Liao 已提交
1837
      if (fmIsAggFunc(pCtx->functionId) || fmIsNonstandardSQLFunc(pCtx->functionId)) {
1838 1839 1840 1841
        fmGetFuncExecFuncs(pCtx->functionId, &pCtx->fpSet);
        pCtx->fpSet.getEnv(pExpr->pExpr->_function.pFunctNode, &env);
      } else {
        fmGetScalarFuncExecFuncs(pCtx->functionId, &pCtx->sfp);
1842 1843 1844
        if (pCtx->sfp.getEnv != NULL) {
          pCtx->sfp.getEnv(pExpr->pExpr->_function.pFunctNode, &env);
        }
1845
      }
H
Haojun Liao 已提交
1846
      pCtx->resDataInfo.interBufSize = env.calcMemSize;
D
dapan1121 已提交
1847
    } else if (pExpr->pExpr->nodeType == QUERY_NODE_COLUMN || pExpr->pExpr->nodeType == QUERY_NODE_OPERATOR || pExpr->pExpr->nodeType == QUERY_NODE_VALUE) {
H
Haojun Liao 已提交
1848
      pCtx->resDataInfo.interBufSize = pFunct->resSchema.bytes; // for simple column, the intermediate buffer needs to hold one element.
H
Haojun Liao 已提交
1849
    }
H
Haojun Liao 已提交
1850

H
Haojun Liao 已提交
1851
    pCtx->input.numOfInputCols = pFunct->numOfParams;
wafwerar's avatar
wafwerar 已提交
1852 1853
    pCtx->input.pData = taosMemoryCalloc(pFunct->numOfParams, POINTER_BYTES);
    pCtx->input.pColumnDataAgg = taosMemoryCalloc(pFunct->numOfParams, POINTER_BYTES);
H
Haojun Liao 已提交
1854

1855
    pCtx->pTsOutput         = NULL;
L
Liu Jicong 已提交
1856
    pCtx->resDataInfo.bytes = pFunct->resSchema.bytes;
H
Haojun Liao 已提交
1857 1858
    pCtx->resDataInfo.type  = pFunct->resSchema.type;
    pCtx->order             = TSDB_ORDER_ASC;
1859 1860
    pCtx->start.key         = INT64_MIN;
    pCtx->end.key           = INT64_MIN;
H
Haojun Liao 已提交
1861
#if 0
H
Haojun Liao 已提交
1862
    for (int32_t j = 0; j < pCtx->numOfParams; ++j) {
H
Haojun Liao 已提交
1863 1864
//      int16_t type = pFunct->param[j].nType;
//      int16_t bytes = pFunct->param[j].nLen;
H
Haojun Liao 已提交
1865

H
Haojun Liao 已提交
1866 1867 1868 1869 1870
//      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 已提交
1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906
    }

    // 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 已提交
1907
#endif
H
Haojun Liao 已提交
1908 1909
  }

L
Liu Jicong 已提交
1910 1911 1912
  for (int32_t i = 1; i < numOfOutput; ++i) {
    (*rowCellInfoOffset)[i] =
        (int32_t)((*rowCellInfoOffset)[i - 1] + sizeof(SResultRowEntryInfo) + pFuncCtx[i - 1].resDataInfo.interBufSize);
H
Haojun Liao 已提交
1913
  }
H
Haojun Liao 已提交
1914 1915 1916 1917 1918

  setCtxTagColumnInfo(pFuncCtx, numOfOutput);
  return pFuncCtx;
}

1919
static void* destroySqlFunctionCtx(SqlFunctionCtx* pCtx, int32_t numOfOutput) {
1920 1921 1922 1923 1924 1925 1926 1927 1928 1929
  if (pCtx == NULL) {
    return NULL;
  }

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

    taosVariantDestroy(&pCtx[i].tag);
wafwerar's avatar
wafwerar 已提交
1930
    taosMemoryFreeClear(pCtx[i].subsidiaryRes.pCtx);
1931 1932
  }

wafwerar's avatar
wafwerar 已提交
1933
  taosMemoryFreeClear(pCtx);
1934 1935 1936
  return NULL;
}

L
Liu Jicong 已提交
1937
bool isTaskKilled(SExecTaskInfo* pTaskInfo) {
1938 1939
  // query has been executed more than tsShellActivityTimer, and the retrieve has not arrived
  // abort current query execution.
L
Liu Jicong 已提交
1940 1941
  if (pTaskInfo->owner != 0 &&
      ((taosGetTimestampSec() - pTaskInfo->cost.start / 1000) > 10 * getMaximumIdleDurationSec())
1942 1943
      /*(!needBuildResAfterQueryComplete(pTaskInfo))*/) {
    assert(pTaskInfo->cost.start != 0);
L
Liu Jicong 已提交
1944 1945 1946
    //    qDebug("QInfo:%" PRIu64 " retrieve not arrive beyond %d ms, abort current query execution, start:%" PRId64
    //           ", current:%d", pQInfo->qId, 1, pQInfo->startExecTs, taosGetTimestampSec());
    //    return true;
1947 1948 1949 1950 1951
  }

  return false;
}

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

L
Liu Jicong 已提交
1954
static bool isCachedLastQuery(STaskAttr* pQueryAttr) {
1955 1956 1957 1958 1959 1960 1961 1962 1963
  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;
  }

1964 1965
  int32_t order = TSDB_ORDER_ASC;
  if (order != TSDB_ORDER_DESC || !TSWINDOW_IS_EQUAL(pQueryAttr->window, TSWINDOW_DESC_INITIALIZER)) {
1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984
    return false;
  }

  if (pQueryAttr->groupbyColumn) {
    return false;
  }

  if (pQueryAttr->interval.interval > 0) {
    return false;
  }

  if (pQueryAttr->numOfFilterCols > 0 || pQueryAttr->havingNum > 0) {
    return false;
  }

  return true;
}

/////////////////////////////////////////////////////////////////////////////////////////////
L
Liu Jicong 已提交
1985 1986 1987
// todo refactor : return window
void getAlignQueryTimeWindow(SInterval* pInterval, int32_t precision, int64_t key, int64_t keyFirst, int64_t keyLast,
                             STimeWindow* win) {
1988
  ASSERT(key >= keyFirst && key <= keyLast);
H
Haojun Liao 已提交
1989
  win->skey = taosTimeTruncate(key, pInterval, precision);
1990 1991

  /*
H
Haojun Liao 已提交
1992
   * if the realSkey > INT64_MAX - pInterval->interval, the query duration between
1993 1994
   * realSkey and realEkey must be less than one interval.Therefore, no need to adjust the query ranges.
   */
H
Haojun Liao 已提交
1995 1996
  if (keyFirst > (INT64_MAX - pInterval->interval)) {
    assert(keyLast - keyFirst < pInterval->interval);
1997 1998
    win->ekey = INT64_MAX;
  } else {
1999
    win->ekey = taosTimeAdd(win->skey, pInterval->interval, pInterval->intervalUnit, precision) - 1;
2000 2001 2002
  }
}

L
Liu Jicong 已提交
2003
static int32_t updateBlockLoadStatus(STaskAttr* pQuery, int32_t status) {
2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026
  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) {
L
Liu Jicong 已提交
2027
    if (!hasOtherFunc) {
2028 2029 2030 2031 2032 2033 2034 2035 2036
      return BLK_DATA_DISCARD;
    } else {
      return BLK_DATA_ALL_NEEDED;
    }
  }

  return status;
}

H
Haojun Liao 已提交
2037
static void doUpdateLastKey(STaskAttr* pQueryAttr) {
2038 2039 2040
  STimeWindow* win = &pQueryAttr->window;

  size_t num = taosArrayGetSize(pQueryAttr->tableGroupInfo.pGroupList);
L
Liu Jicong 已提交
2041
  for (int32_t i = 0; i < num; ++i) {
2042 2043 2044
    SArray* p1 = taosArrayGetP(pQueryAttr->tableGroupInfo.pGroupList, i);

    size_t len = taosArrayGetSize(p1);
L
Liu Jicong 已提交
2045 2046 2047 2048 2049 2050 2051
    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;
      //      }
2052 2053 2054 2055
    }
  }
}

L
Liu Jicong 已提交
2056 2057
// static void updateDataCheckOrder(SQInfo *pQInfo, SQueryTableReq* pQueryMsg, bool stableQuery) {
//   STaskAttr* pQueryAttr = pQInfo->runtimeEnv.pQueryAttr;
H
Haojun Liao 已提交
2058
//
L
Liu Jicong 已提交
2059 2060 2061 2062
//   // in case of point-interpolation query, use asc order scan
//   char msg[] = "QInfo:0x%"PRIx64" scan order changed for %s query, old:%d, new:%d, qrange exchanged, old qrange:%"
//   PRId64
//                "-%" PRId64 ", new qrange:%" PRId64 "-%" PRId64;
H
Haojun Liao 已提交
2063
//
L
Liu Jicong 已提交
2064 2065 2066 2067 2068
//   // todo handle the case the the order irrelevant query type mixed up with order critical query type
//   // descending order query for last_row query
//   if (isFirstLastRowQuery(pQueryAttr)) {
//     //qDebug("QInfo:0x%"PRIx64" scan order changed for last_row query, old:%d, new:%d", pQInfo->qId,
//     pQueryAttr->order.order, TSDB_ORDER_ASC);
H
Haojun Liao 已提交
2069
//
L
Liu Jicong 已提交
2070 2071 2072 2073
//     pQueryAttr->order.order = TSDB_ORDER_ASC;
//     if (pQueryAttr->window.skey > pQueryAttr->window.ekey) {
//       TSWAP(pQueryAttr->window.skey, pQueryAttr->window.ekey, TSKEY);
//     }
H
Haojun Liao 已提交
2074
//
L
Liu Jicong 已提交
2075 2076 2077
//     pQueryAttr->needReverseScan = false;
//     return;
//   }
H
Haojun Liao 已提交
2078
//
L
Liu Jicong 已提交
2079 2080 2081 2082 2083
//   if (pQueryAttr->groupbyColumn && pQueryAttr->order.order == TSDB_ORDER_DESC) {
//     pQueryAttr->order.order = TSDB_ORDER_ASC;
//     if (pQueryAttr->window.skey > pQueryAttr->window.ekey) {
//       TSWAP(pQueryAttr->window.skey, pQueryAttr->window.ekey, TSKEY);
//     }
H
Haojun Liao 已提交
2084
//
L
Liu Jicong 已提交
2085 2086 2087 2088
//     pQueryAttr->needReverseScan = false;
//     doUpdateLastKey(pQueryAttr);
//     return;
//   }
H
Haojun Liao 已提交
2089
//
L
Liu Jicong 已提交
2090 2091 2092 2093 2094 2095
//   if (pQueryAttr->pointInterpQuery && pQueryAttr->interval.interval == 0) {
//     if (!QUERY_IS_ASC_QUERY(pQueryAttr)) {
//       //qDebug(msg, pQInfo->qId, "interp", pQueryAttr->order.order, TSDB_ORDER_ASC, pQueryAttr->window.skey,
//       pQueryAttr->window.ekey, pQueryAttr->window.ekey, pQueryAttr->window.skey); TSWAP(pQueryAttr->window.skey,
//       pQueryAttr->window.ekey, TSKEY);
//     }
H
Haojun Liao 已提交
2096
//
L
Liu Jicong 已提交
2097 2098 2099
//     pQueryAttr->order.order = TSDB_ORDER_ASC;
//     return;
//   }
H
Haojun Liao 已提交
2100
//
L
Liu Jicong 已提交
2101 2102 2103 2104
//   if (pQueryAttr->interval.interval == 0) {
//     if (onlyFirstQuery(pQueryAttr)) {
//       if (!QUERY_IS_ASC_QUERY(pQueryAttr)) {
//         //qDebug(msg, pQInfo->qId, "only-first", pQueryAttr->order.order, TSDB_ORDER_ASC, pQueryAttr->window.skey,
H
Haojun Liao 已提交
2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130
////               pQueryAttr->window.ekey, pQueryAttr->window.ekey, pQueryAttr->window.skey);
//
//        TSWAP(pQueryAttr->window.skey, pQueryAttr->window.ekey, TSKEY);
//        doUpdateLastKey(pQueryAttr);
//      }
//
//      pQueryAttr->order.order = TSDB_ORDER_ASC;
//      pQueryAttr->needReverseScan = false;
//    } else if (onlyLastQuery(pQueryAttr) && notContainSessionOrStateWindow(pQueryAttr)) {
//      if (QUERY_IS_ASC_QUERY(pQueryAttr)) {
//        //qDebug(msg, pQInfo->qId, "only-last", pQueryAttr->order.order, TSDB_ORDER_DESC, pQueryAttr->window.skey,
////               pQueryAttr->window.ekey, pQueryAttr->window.ekey, pQueryAttr->window.skey);
//
//        TSWAP(pQueryAttr->window.skey, pQueryAttr->window.ekey, TSKEY);
//        doUpdateLastKey(pQueryAttr);
//      }
//
//      pQueryAttr->order.order = TSDB_ORDER_DESC;
//      pQueryAttr->needReverseScan = false;
//    }
//
//  } else {  // interval query
//    if (stableQuery) {
//      if (onlyFirstQuery(pQueryAttr)) {
//        if (!QUERY_IS_ASC_QUERY(pQueryAttr)) {
//          //qDebug(msg, pQInfo->qId, "only-first stable", pQueryAttr->order.order, TSDB_ORDER_ASC,
L
Liu Jicong 已提交
2131 2132
////                 pQueryAttr->window.skey, pQueryAttr->window.ekey, pQueryAttr->window.ekey,
/// pQueryAttr->window.skey);
H
Haojun Liao 已提交
2133 2134 2135 2136 2137 2138 2139 2140 2141 2142
//
//          TSWAP(pQueryAttr->window.skey, pQueryAttr->window.ekey, TSKEY);
//          doUpdateLastKey(pQueryAttr);
//        }
//
//        pQueryAttr->order.order = TSDB_ORDER_ASC;
//        pQueryAttr->needReverseScan = false;
//      } else if (onlyLastQuery(pQueryAttr)) {
//        if (QUERY_IS_ASC_QUERY(pQueryAttr)) {
//          //qDebug(msg, pQInfo->qId, "only-last stable", pQueryAttr->order.order, TSDB_ORDER_DESC,
L
Liu Jicong 已提交
2143 2144
////                 pQueryAttr->window.skey, pQueryAttr->window.ekey, pQueryAttr->window.ekey,
/// pQueryAttr->window.skey);
H
Haojun Liao 已提交
2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155
//
//          TSWAP(pQueryAttr->window.skey, pQueryAttr->window.ekey, TSKEY);
//          doUpdateLastKey(pQueryAttr);
//        }
//
//        pQueryAttr->order.order = TSDB_ORDER_DESC;
//        pQueryAttr->needReverseScan = false;
//      }
//    }
//  }
//}
2156

H
Haojun Liao 已提交
2157 2158
static void getIntermediateBufInfo(STaskRuntimeEnv* pRuntimeEnv, int32_t* ps, int32_t* rowsize) {
  STaskAttr* pQueryAttr = pRuntimeEnv->pQueryAttr;
L
Liu Jicong 已提交
2159
  int32_t    MIN_ROWS_PER_PAGE = 4;
2160

L
Liu Jicong 已提交
2161 2162
  *rowsize = (int32_t)(pQueryAttr->resultRowSize *
                       getRowNumForMultioutput(pQueryAttr, pQueryAttr->topBotQuery, pQueryAttr->stableQuery));
2163 2164 2165 2166
  int32_t overhead = sizeof(SFilePage);

  // one page contains at least two rows
  *ps = DEFAULT_INTERN_BUF_PAGE_SIZE;
L
Liu Jicong 已提交
2167
  while (((*rowsize) * MIN_ROWS_PER_PAGE) > (*ps) - overhead) {
2168 2169 2170 2171 2172 2173
    *ps = ((*ps) << 1u);
  }
}

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

L
Liu Jicong 已提交
2174 2175 2176
// static FORCE_INLINE bool doFilterByBlockStatistics(STaskRuntimeEnv* pRuntimeEnv, SDataStatis *pDataStatis,
// SqlFunctionCtx *pCtx, int32_t numOfRows) {
//   STaskAttr* pQueryAttr = pRuntimeEnv->pQueryAttr;
2177
//
L
Liu Jicong 已提交
2178 2179 2180
//   if (pDataStatis == NULL || pQueryAttr->pFilters == NULL) {
//     return true;
//   }
2181
//
L
Liu Jicong 已提交
2182 2183
//   return filterRangeExecute(pQueryAttr->pFilters, pDataStatis, pQueryAttr->numOfCols, numOfRows);
// }
2184

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

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

2191
  if (true) {
L
Liu Jicong 已提交
2192
    //    getAlignQueryTimeWindow(pQueryAttr, pBlockInfo->window.skey, sk, ek, &w);
2193 2194 2195 2196 2197 2198
    assert(w.ekey >= pBlockInfo->window.skey);

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

L
Liu Jicong 已提交
2199 2200
    while (1) {
      //      getNextTimeWindow(pQueryAttr, &w);
2201 2202 2203 2204 2205 2206 2207 2208 2209 2210
      if (w.skey > pBlockInfo->window.ekey) {
        break;
      }

      assert(w.ekey > pBlockInfo->window.ekey);
      if (w.skey <= pBlockInfo->window.ekey && w.skey > pBlockInfo->window.skey) {
        return true;
      }
    }
  } else {
L
Liu Jicong 已提交
2211
    //    getAlignQueryTimeWindow(pQueryAttr, pBlockInfo->window.ekey, sk, ek, &w);
2212 2213 2214 2215 2216 2217
    assert(w.skey <= pBlockInfo->window.ekey);

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

L
Liu Jicong 已提交
2218 2219
    while (1) {
      //      getNextTimeWindow(pQueryAttr, &w);
2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233
      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;
}

L
Liu Jicong 已提交
2234
static int32_t doTSJoinFilter(STaskRuntimeEnv* pRuntimeEnv, TSKEY key, bool ascQuery) {
2235 2236 2237
  STSElem elem = tsBufGetElem(pRuntimeEnv->pTsBuf);

#if defined(_DEBUG_VIEW)
L
Liu Jicong 已提交
2238 2239
  printf("elem in comp ts file:%" PRId64 ", key:%" PRId64 ", tag:%" PRIu64
         ", query order:%d, ts order:%d, traverse:%d, index:%d\n",
2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309
         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;
}

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 已提交
2310
void filterColRowsInDataBlock(STaskRuntimeEnv* pRuntimeEnv, SSDataBlock* pBlock, bool ascQuery) {
L
Liu Jicong 已提交
2311
  int32_t numOfRows = pBlock->info.rows;
2312

L
Liu Jicong 已提交
2313 2314
  int8_t* p = NULL;
  bool    all = true;
2315

L
Liu Jicong 已提交
2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337
  if (pRuntimeEnv->pTsBuf != NULL) {
    SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, 0);
    p = taosMemoryCalloc(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;
      }
    }
2338

L
Liu Jicong 已提交
2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353
    // save the cursor status
    //   pRuntimeEnv->current->cur = tsBufGetCursor(pRuntimeEnv->pTsBuf);
  } 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
    }
  }
2354

L
Liu Jicong 已提交
2355
  taosMemoryFreeClear(p);
2356 2357 2358
}

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

static uint32_t doFilterByBlockTimeWindow(STableScanInfo* pTableScanInfo, SSDataBlock* pBlock) {
H
Haojun Liao 已提交
2362
  SqlFunctionCtx* pCtx = pTableScanInfo->pCtx;
L
Liu Jicong 已提交
2363
  uint32_t        status = BLK_DATA_NO_NEEDED;
2364 2365 2366 2367

  int32_t numOfOutput = pTableScanInfo->numOfOutput;
  for (int32_t i = 0; i < numOfOutput; ++i) {
    int32_t functionId = pCtx[i].functionId;
H
Haojun Liao 已提交
2368
    int32_t colId = pTableScanInfo->pExpr[i].base.pParam[0].pCol->colId;
2369 2370 2371 2372 2373 2374

    // group by + first/last should not apply the first/last block filter
    if (functionId < 0) {
      status |= BLK_DATA_ALL_NEEDED;
      return status;
    } else {
L
Liu Jicong 已提交
2375 2376 2377 2378
      //      status |= aAggs[functionId].dataReqFunc(&pTableScanInfo->pCtx[i], &pBlock->info.window, colId);
      //      if ((status & BLK_DATA_ALL_NEEDED) == BLK_DATA_ALL_NEEDED) {
      //        return status;
      //      }
2379 2380 2381 2382 2383 2384
    }
  }

  return status;
}

L
Liu Jicong 已提交
2385 2386
int32_t loadDataBlockOnDemand(SExecTaskInfo* pTaskInfo, STableScanInfo* pTableScanInfo, SSDataBlock* pBlock,
                              uint32_t* status) {
2387 2388
  *status = BLK_DATA_NO_NEEDED;

H
Haojun Liao 已提交
2389
  pBlock->pDataBlock = NULL;
L
Liu Jicong 已提交
2390
  pBlock->pBlockAgg = NULL;
H
Haojun Liao 已提交
2391

L
Liu Jicong 已提交
2392 2393
  //  int64_t groupId = pRuntimeEnv->current->groupIndex;
  //  bool    ascQuery = QUERY_IS_ASC_QUERY(pQueryAttr);
2394

H
Haojun Liao 已提交
2395
  STaskCostInfo* pCost = &pTaskInfo->cost;
2396 2397 2398

  pCost->totalBlocks += 1;
  pCost->totalRows += pBlock->info.rows;
H
Haojun Liao 已提交
2399
#if 0
2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423
  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 已提交
2424
      (QUERY_IS_INTERVAL_QUERY(pQueryAttr) && overlapWithTimeWindow(pTaskInfo, &pBlock->info))) {
2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436
    (*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 已提交
2437
      bool  masterScan = IS_MAIN_SCAN(pRuntimeEnv);
2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465
      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 已提交
2466
//  *status = updateBlockLoadStatus(pRuntimeEnv->pQueryAttr, *status);
2467 2468 2469 2470 2471 2472 2473 2474

  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;
2475
//    tsdbRetrieveDataBlockStatisInfo(pTableScanInfo->pTsdbReadHandle, &pBlock->pBlockAgg);
2476 2477

    if (pBlock->pBlockAgg == NULL) {  // data block statistics does not exist, load data block
2478
//      pBlock->pDataBlock = tsdbRetrieveDataBlock(pTableScanInfo->pTsdbReadHandle, NULL);
2479 2480 2481 2482 2483 2484 2485
      pCost->totalCheckedRows += pBlock->info.rows;
    }
  } else {
    assert((*status) == BLK_DATA_ALL_NEEDED);

    // load the data block statistics to perform further filter
    pCost->loadBlockStatis += 1;
2486
//    tsdbRetrieveDataBlockStatisInfo(pTableScanInfo->pTsdbReadHandle, &pBlock->pBlockAgg);
2487 2488 2489 2490 2491 2492

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

H
Haojun Liao 已提交
2493
          bool  masterScan = IS_MAIN_SCAN(pRuntimeEnv);
2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531
          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;
2532
//    pBlock->pDataBlock = tsdbRetrieveDataBlock(pTableScanInfo->pTsdbReadHandle, NULL);
2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544
//    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 已提交
2545
#endif
2546 2547 2548
  return TSDB_CODE_SUCCESS;
}

L
Liu Jicong 已提交
2549
int32_t binarySearchForKey(char* pValue, int num, TSKEY key, int order) {
2550 2551 2552 2553 2554 2555 2556 2557 2558
  int32_t midPos = -1;
  int32_t numOfRows;

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

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

L
Liu Jicong 已提交
2559
  TSKEY*  keyList = (TSKEY*)pValue;
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 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612
  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 已提交
2613
 * set tag value in SqlFunctionCtx
2614 2615
 * e.g.,tag information into input buffer
 */
L
Liu Jicong 已提交
2616
static void doSetTagValueInParam(void* pTable, int32_t tagColId, SVariant* tag, int16_t type, int16_t bytes) {
2617 2618 2619
  taosVariantDestroy(tag);

  char* val = NULL;
L
Liu Jicong 已提交
2620 2621 2622 2623 2624 2625
  //  if (tagColId == TSDB_TBNAME_COLUMN_INDEX) {
  //    val = tsdbGetTableName(pTable);
  //    assert(val != NULL);
  //  } else {
  //    val = tsdbGetTableTagVal(pTable, tagColId, type, bytes);
  //  }
2626 2627 2628 2629 2630 2631 2632 2633

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

  if (type == TSDB_DATA_TYPE_BINARY || type == TSDB_DATA_TYPE_NCHAR) {
    int32_t maxLen = bytes - VARSTR_HEADER_SIZE;
L
Liu Jicong 已提交
2634
    int32_t len = (varDataLen(val) > maxLen) ? maxLen : varDataLen(val);
2635
    taosVariantCreateFromBinary(tag, varDataVal(val), len, type);
L
Liu Jicong 已提交
2636
    // taosVariantCreateFromBinary(tag, varDataVal(val), varDataLen(val), type);
2637 2638 2639 2640 2641 2642 2643 2644
  } else {
    taosVariantCreateFromBinary(tag, val, bytes, type);
  }
}

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

L
Liu Jicong 已提交
2645
  for (int32_t i = 0; i < numOfTags; ++i) {
2646 2647 2648 2649 2650 2651 2652 2653
    if (pTagColList[i].colId == colId) {
      return &pTagColList[i];
    }
  }

  return NULL;
}

L
Liu Jicong 已提交
2654 2655
void setTagValue(SOperatorInfo* pOperatorInfo, void* pTable, SqlFunctionCtx* pCtx, int32_t numOfOutput) {
  SExprInfo* pExpr = pOperatorInfo->pExpr;
2656
  SExprInfo* pExprInfo = &pExpr[0];
L
Liu Jicong 已提交
2657
  int32_t    functionId = getExprFunctionId(pExprInfo);
2658
#if 0
2659 2660 2661
  if (pQueryAttr->numOfOutput == 1 && functionId == FUNCTION_TS_COMP && pQueryAttr->stableQuery) {
    assert(pExprInfo->base.numOfParams == 1);

L
Liu Jicong 已提交
2662
    //    int16_t      tagColId = (int16_t)pExprInfo->base.param[0].i;
H
Haojun Liao 已提交
2663
    int16_t      tagColId = -1;
2664 2665 2666
    SColumnInfo* pColInfo = doGetTagColumnInfoById(pQueryAttr->tagColList, pQueryAttr->numOfTags, tagColId);

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

2668 2669 2670 2671 2672 2673 2674 2675 2676
  } 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 已提交
2677
      if (!TSDB_COL_IS_TAG(pLocalExprInfo->base.pParam[0].pCol->flag)) {
2678 2679 2680 2681
        continue;
      }

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

L
Liu Jicong 已提交
2685 2686 2687
      if (IS_NUMERIC_TYPE(pLocalExprInfo->base.resSchema.type) ||
          pLocalExprInfo->base.resSchema.type == TSDB_DATA_TYPE_BOOL ||
          pLocalExprInfo->base.resSchema.type == TSDB_DATA_TYPE_TIMESTAMP) {
2688 2689 2690 2691
        memcpy(pRuntimeEnv->tagVal + offset, &pCtx[idx].tag.i, pLocalExprInfo->base.resSchema.bytes);
      } else {
        if (pCtx[idx].tag.pz != NULL) {
          memcpy(pRuntimeEnv->tagVal + offset, pCtx[idx].tag.pz, pCtx[idx].tag.nLen);
L
Liu Jicong 已提交
2692
        }
2693 2694 2695 2696 2697 2698 2699 2700 2701 2702
      }

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

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

2705 2706
}

H
Haojun Liao 已提交
2707
void copyToSDataBlock(SSDataBlock* pBlock, int32_t* offset, SGroupResInfo* pGroupResInfo, SDiskbasedBuf* pResBuf) {
2708 2709 2710 2711 2712 2713 2714
  pBlock->info.rows = 0;

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

L
Liu Jicong 已提交
2720
    //    doCopyToSDataBlock(pResBuf, pGroupResInfo, TSDB_ORDER_ASC, pBlock, );
2721 2722 2723 2724 2725 2726 2727 2728 2729 2730

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

    // enough results in data buffer, return
L
Liu Jicong 已提交
2731 2732 2733
    //    if (pBlock->info.rows >= threshold) {
    //      break;
    //    }
2734 2735 2736
  }
}

L
Liu Jicong 已提交
2737
static void updateTableQueryInfoForReverseScan(STableQueryInfo* pTableQueryInfo) {
2738 2739 2740 2741
  if (pTableQueryInfo == NULL) {
    return;
  }

L
Liu Jicong 已提交
2742 2743
  //  TSWAP(pTableQueryInfo->win.skey, pTableQueryInfo->win.ekey, TSKEY);
  //  pTableQueryInfo->lastKey = pTableQueryInfo->win.skey;
2744

L
Liu Jicong 已提交
2745 2746
  //  SWITCH_ORDER(pTableQueryInfo->cur.order);
  //  pTableQueryInfo->cur.vgroupIndex = -1;
2747 2748 2749 2750 2751 2752 2753 2754 2755 2756

  // 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 已提交
2757
void initResultRow(SResultRow* pResultRow) {
2758 2759 2760 2761 2762 2763
  pResultRow->pEntryInfo = (struct SResultRowEntryInfo*)((char*)pResultRow + sizeof(SResultRow));
}

/*
 * The start of each column SResultRowEntryInfo is denote by RowCellInfoOffset.
 * Note that in case of top/bottom query, the whole multiple rows of result is treated as only one row of results.
H
Haojun Liao 已提交
2764 2765 2766
 * +------------+-----------------result column 1------------+------------------result column 2-----------+
 * | SResultRow | SResultRowEntryInfo | intermediate buffer1 | SResultRowEntryInfo | intermediate buffer 2|
 * +------------+--------------------------------------------+--------------------------------------------+
2767 2768
 *           offset[0]                                  offset[1]                                   offset[2]
 */
2769
// TODO refactor: some function move away
H
Haojun Liao 已提交
2770
void setFunctionResultOutput(SOptrBasicInfo* pInfo, SAggSupporter* pSup, int32_t stage, SExecTaskInfo* pTaskInfo) {
L
Liu Jicong 已提交
2771 2772 2773
  SqlFunctionCtx* pCtx = pInfo->pCtx;
  SSDataBlock*    pDataBlock = pInfo->pRes;
  int32_t*        rowCellInfoOffset = pInfo->rowCellInfoOffset;
H
Haojun Liao 已提交
2774

H
Haojun Liao 已提交
2775
  SResultRowInfo* pResultRowInfo = &pInfo->resultRowInfo;
H
Haojun Liao 已提交
2776
  initResultRowInfo(pResultRowInfo, 16);
H
Haojun Liao 已提交
2777

L
Liu Jicong 已提交
2778 2779 2780 2781
  int64_t     tid = 0;
  int64_t     groupId = 0;
  SResultRow* pRow = doSetResultOutBufByKey_rv(pSup->pResultBuf, pResultRowInfo, tid, (char*)&tid, sizeof(tid), true,
                                               groupId, pTaskInfo, false, pSup);
H
Haojun Liao 已提交
2782 2783 2784 2785 2786

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

L
Liu Jicong 已提交
2787
    pCtx[i].resultInfo = pEntry;
H
Haojun Liao 已提交
2788 2789 2790
    pCtx[i].currentStage = stage;

    // set the timestamp output buffer for top/bottom/diff query
L
Liu Jicong 已提交
2791 2792
    //    int32_t fid = pCtx[i].functionId;
    //    if (fid == FUNCTION_TOP || fid == FUNCTION_BOTTOM || fid == FUNCTION_DIFF || fid == FUNCTION_DERIVATIVE) {
H
Haojun Liao 已提交
2793
    //      if (i > 0) pCtx[i].pTsOutput = pCtx[i-1].pOutput;
L
Liu Jicong 已提交
2794
    //    }
H
Haojun Liao 已提交
2795 2796 2797 2798 2799
  }

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

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

L
Liu Jicong 已提交
2803
  int32_t newSize = pDataBlock->info.rows + numOfInputRows + 5;  // extra output buffer
2804
  if ((*bufCapacity) < newSize) {
L
Liu Jicong 已提交
2805 2806
    for (int32_t i = 0; i < pDataBlock->info.numOfCols; ++i) {
      SColumnInfoData* pColInfo = taosArrayGet(pDataBlock->pDataBlock, i);
2807

wafwerar's avatar
wafwerar 已提交
2808
      char* p = taosMemoryRealloc(pColInfo->pData, newSize * pColInfo->info.bytes);
2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821
      if (p != NULL) {
        pColInfo->pData = p;

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

  for (int32_t i = 0; i < pDataBlock->info.numOfCols; ++i) {
L
Liu Jicong 已提交
2822
    SColumnInfoData* pColInfo = taosArrayGet(pDataBlock->pDataBlock, i);
2823 2824 2825 2826 2827
    pBInfo->pCtx[i].pOutput = pColInfo->pData + pColInfo->info.bytes * pDataBlock->info.rows;

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

L
Liu Jicong 已提交
2828 2829
    if (functionId == FUNCTION_TOP || functionId == FUNCTION_BOTTOM || functionId == FUNCTION_DIFF ||
        functionId == FUNCTION_DERIVATIVE) {
H
Haojun Liao 已提交
2830
//      if (i > 0) pBInfo->pCtx[i].pTsOutput = pBInfo->pCtx[i - 1].pOutput;
2831 2832 2833 2834
    }
  }
}

H
Haojun Liao 已提交
2835
void copyTsColoum(SSDataBlock* pRes, SqlFunctionCtx* pCtx, int32_t numOfOutput) {
2836 2837
  bool    needCopyTs = false;
  int32_t tsNum = 0;
L
Liu Jicong 已提交
2838
  char*   src = NULL;
2839 2840 2841 2842
  for (int32_t i = 0; i < numOfOutput; i++) {
    int32_t functionId = pCtx[i].functionId;
    if (functionId == FUNCTION_DIFF || functionId == FUNCTION_DERIVATIVE) {
      needCopyTs = true;
L
Liu Jicong 已提交
2843 2844
      if (i > 0 && pCtx[i - 1].functionId == FUNCTION_TS_DUMMY) {
        SColumnInfoData* pColRes = taosArrayGet(pRes->pDataBlock, i - 1);  // find ts data
2845 2846
        src = pColRes->pData;
      }
L
Liu Jicong 已提交
2847
    } else if (functionId == FUNCTION_TS_DUMMY) {
2848 2849 2850 2851 2852 2853 2854 2855 2856 2857
      tsNum++;
    }
  }

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

  for (int32_t i = 0; i < numOfOutput; i++) {
    int32_t functionId = pCtx[i].functionId;
L
Liu Jicong 已提交
2858
    if (functionId == FUNCTION_TS_DUMMY) {
2859 2860 2861 2862 2863 2864
      SColumnInfoData* pColRes = taosArrayGet(pRes->pDataBlock, i);
      memcpy(pColRes->pData, src, pColRes->info.bytes * pRes->info.rows);
    }
  }
}

H
Haojun Liao 已提交
2865
void initCtxOutputBuffer(SqlFunctionCtx* pCtx, int32_t size) {
2866 2867
  for (int32_t j = 0; j < size; ++j) {
    struct SResultRowEntryInfo* pResInfo = GET_RES_INFO(&pCtx[j]);
H
Haojun Liao 已提交
2868
    if (isRowEntryInitialized(pResInfo) || fmIsPseudoColumnFunc(pCtx[j].functionId) || pCtx[j].functionId == -1 || fmIsScalarFunc(pCtx[j].functionId)) {
2869 2870 2871
      continue;
    }

H
Haojun Liao 已提交
2872
    pCtx[j].fpSet.init(&pCtx[j], pCtx[j].resultInfo);
2873 2874 2875
  }
}

L
Liu Jicong 已提交
2876
void setTaskStatus(SExecTaskInfo* pTaskInfo, int8_t status) {
2877
  if (status == TASK_NOT_COMPLETED) {
H
Haojun Liao 已提交
2878
    pTaskInfo->status = status;
2879 2880
  } else {
    // QUERY_NOT_COMPLETED is not compatible with any other status, so clear its position first
2881
    CLEAR_QUERY_STATUS(pTaskInfo, TASK_NOT_COMPLETED);
H
Haojun Liao 已提交
2882
    pTaskInfo->status |= status;
2883 2884 2885
  }
}

2886 2887
void finalizeQueryResult(SqlFunctionCtx* pCtx, int32_t numOfOutput) {
  for (int32_t j = 0; j < numOfOutput; ++j) {
H
Haojun Liao 已提交
2888 2889 2890 2891
    if (pCtx[j].functionId == -1) {
      continue;
    }

2892 2893 2894 2895
    pCtx[j].fpSet.finalize(&pCtx[j]);
  }
}

L
Liu Jicong 已提交
2896 2897
void finalizeMultiTupleQueryResult(SqlFunctionCtx* pCtx, int32_t numOfOutput, SDiskbasedBuf* pBuf,
                                   SResultRowInfo* pResultRowInfo, int32_t* rowCellInfoOffset) {
2898 2899 2900
  for (int32_t i = 0; i < pResultRowInfo->size; ++i) {
    SResultRowPosition* pPos = &pResultRowInfo->pPosition[i];

L
Liu Jicong 已提交
2901
    SFilePage*  bufPage = getBufPage(pBuf, pPos->pageId);
2902
    SResultRow* pRow = (SResultRow*)((char*)bufPage + pPos->offset);
H
Haojun Liao 已提交
2903 2904 2905 2906 2907

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

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

H
Haojun Liao 已提交
2912
      struct SResultRowEntryInfo* pResInfo = pCtx[j].resultInfo;
2913 2914 2915 2916
      if (isRowEntryCompleted(pResInfo) && isRowEntryInitialized(pResInfo)) {
        continue;
      }

H
Haojun Liao 已提交
2917
      if (pCtx[j].fpSet.process) {  // TODO set the dummy function, to avoid the check for null ptr.
H
Haojun Liao 已提交
2918 2919
        pCtx[j].fpSet.finalize(&pCtx[j]);
      }
2920 2921 2922 2923

      if (pRow->numOfRows < pResInfo->numOfRes) {
        pRow->numOfRows = pResInfo->numOfRes;
      }
2924
    }
2925 2926 2927

    releaseBufPage(pBuf, bufPage);
  }
2928 2929
}

2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949
void finalizeUpdatedResult(SqlFunctionCtx* pCtx, int32_t numOfOutput, SDiskbasedBuf* pBuf, SArray* pUpdateList,
                           int32_t* rowCellInfoOffset) {
  size_t num = taosArrayGetSize(pUpdateList);

  for (int32_t i = 0; i < num; ++i) {
    SResultRowPosition* pPos = taosArrayGet(pUpdateList, i);

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

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

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

      if (pCtx[j].fpSet.process) {  // TODO set the dummy function.
        pCtx[j].fpSet.finalize(&pCtx[j]);
2950
        pResInfo->initialized = true;
2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966
      }

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

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

L
Liu Jicong 已提交
2967
static bool hasMainOutput(STaskAttr* pQueryAttr) {
2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978
  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;
}

L
Liu Jicong 已提交
2979 2980
STableQueryInfo* createTableQueryInfo(void* buf, bool groupbyColumn, STimeWindow win) {
  STableQueryInfo* pTableQueryInfo = buf;
2981 2982 2983
  pTableQueryInfo->lastKey = win.skey;

  // set more initial size of interval/groupby query
L
Liu Jicong 已提交
2984 2985 2986 2987 2988 2989 2990 2991
  //  if (/*QUERY_IS_INTERVAL_QUERY(pQueryAttr) || */groupbyColumn) {
  int32_t initialSize = 128;
  int32_t code = initResultRowInfo(&pTableQueryInfo->resInfo, initialSize);
  if (code != TSDB_CODE_SUCCESS) {
    return NULL;
  }
  //  } else { // in other aggregate query, do not initialize the windowResInfo
  //  }
2992 2993 2994 2995

  return pTableQueryInfo;
}

L
Liu Jicong 已提交
2996
void destroyTableQueryInfoImpl(STableQueryInfo* pTableQueryInfo) {
2997 2998 2999 3000
  if (pTableQueryInfo == NULL) {
    return;
  }

L
Liu Jicong 已提交
3001
  //  taosVariantDestroy(&pTableQueryInfo->tag);
3002 3003 3004
  cleanupResultRowInfo(&pTableQueryInfo->resInfo);
}

H
Haojun Liao 已提交
3005
void setResultRowOutputBufInitCtx_rv(SResultRow* pResult, SqlFunctionCtx* pCtx, int32_t numOfOutput, int32_t* rowCellInfoOffset) {
3006 3007 3008 3009 3010 3011 3012
  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;
    }
3013 3014 3015 3016 3017

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

H
Haojun Liao 已提交
3018
    if (!pResInfo->initialized && pCtx[i].functionId != -1) {
3019
      pCtx[i].fpSet.init(&pCtx[i], pResInfo);
3020 3021 3022 3023
    }
  }
}

3024 3025 3026 3027 3028 3029
void doFilter(const SNode* pFilterNode, SSDataBlock* pBlock) {
  if (pFilterNode == NULL) {
    return;
  }

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

H
Haojun Liao 已提交
3031
  // todo move to the initialization function
H
Haojun Liao 已提交
3032
  int32_t code = filterInitFromNode((SNode*)pFilterNode, &filter, 0);
3033 3034 3035 3036 3037 3038

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

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

3041
  SSDataBlock* px = createOneDataBlock(pBlock, false);
3042 3043
  blockDataEnsureCapacity(px, pBlock->info.rows);

H
Haojun Liao 已提交
3044
  // todo extract method
3045 3046 3047 3048
  int32_t numOfRow = 0;
  for (int32_t i = 0; i < pBlock->info.numOfCols; ++i) {
    SColumnInfoData* pDst = taosArrayGet(px->pDataBlock, i);
    SColumnInfoData* pSrc = taosArrayGet(pBlock->pDataBlock, i);
D
dapan1121 已提交
3049 3050 3051 3052 3053 3054 3055 3056 3057
    if (keep) {
      colDataAssign(pDst, pSrc, pBlock->info.rows);
      numOfRow = pBlock->info.rows;
    } else if (NULL != rowRes) {
      numOfRow = 0;
      for (int32_t j = 0; j < pBlock->info.rows; ++j) {
        if (rowRes[j] == 0) {
          continue;
        }
3058

D
dapan1121 已提交
3059 3060 3061 3062 3063 3064
        if (colDataIsNull_s(pSrc, j)) {
          colDataAppendNULL(pDst, numOfRow);
        } else {
          colDataAppend(pDst, numOfRow, colDataGetData(pSrc, j), false);
        }
        numOfRow += 1;
H
Haojun Liao 已提交
3065
      }
D
dapan1121 已提交
3066 3067
    } else {
      numOfRow = 0;
3068 3069 3070 3071 3072 3073
    }

    *pSrc = *pDst;
  }

  pBlock->info.rows = numOfRow;
3074
  blockDataUpdateTsWindow(pBlock);
3075 3076
}

H
Haojun Liao 已提交
3077
void doSetTableGroupOutputBuf(SAggOperatorInfo* pAggInfo, int32_t numOfOutput, int32_t tableGroupId, SExecTaskInfo* pTaskInfo) {
3078 3079 3080 3081
  // for simple group by query without interval, all the tables belong to one group result.
  int64_t uid = 0;
  int64_t tid = 0;

3082 3083
  SResultRowInfo* pResultRowInfo = &pAggInfo->binfo.resultRowInfo;
  SqlFunctionCtx* pCtx = pAggInfo->binfo.pCtx;
L
Liu Jicong 已提交
3084
  int32_t*        rowCellInfoOffset = pAggInfo->binfo.rowCellInfoOffset;
3085

3086
  SResultRow* pResultRow =
L
Liu Jicong 已提交
3087 3088 3089
      doSetResultOutBufByKey_rv(pAggInfo->pResultBuf, pResultRowInfo, tid, (char*)&tableGroupId, sizeof(tableGroupId),
                                true, uid, pTaskInfo, false, &pAggInfo->aggSup);
  assert(pResultRow != NULL);
3090 3091 3092 3093 3094 3095

  /*
   * 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 已提交
3096
    int32_t ret = addNewWindowResultBuf(pResultRow, pAggInfo->pResultBuf, tableGroupId, pAggInfo->binfo.pRes->info.rowSize);
3097 3098 3099 3100 3101
    if (ret != TSDB_CODE_SUCCESS) {
      return;
    }
  }

H
Haojun Liao 已提交
3102
  setResultRowOutputBufInitCtx_rv(pResultRow, pCtx, numOfOutput, rowCellInfoOffset);
3103 3104
}

L
Liu Jicong 已提交
3105 3106
void setExecutionContext(int32_t numOfOutput, int32_t tableGroupId, TSKEY nextKey, SExecTaskInfo* pTaskInfo,
                         STableQueryInfo* pTableQueryInfo, SAggOperatorInfo* pAggInfo) {
3107 3108
  // lastKey needs to be updated
  pTableQueryInfo->lastKey = nextKey;
3109
  if (pAggInfo->groupId != INT32_MIN && pAggInfo->groupId == tableGroupId) {
3110 3111 3112
    return;
  }

3113
  doSetTableGroupOutputBuf(pAggInfo, numOfOutput, tableGroupId, pTaskInfo);
3114 3115

  // record the current active group id
3116
  pAggInfo->groupId = tableGroupId;
3117 3118
}

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

H
Haojun Liao 已提交
3122
  SExprBasicInfo* pExpr = &pExprInfo->base;
L
Liu Jicong 已提交
3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146
  //  if (pQueryAttr->stableQuery && (pRuntimeEnv->pTsBuf != NULL) &&
  //      (pExpr->functionId == FUNCTION_TS || pExpr->functionId == FUNCTION_PRJ) &&
  //      (pExpr->colInfo.colIndex == PRIMARYKEY_TIMESTAMP_COL_ID)) {
  //    assert(pExpr->numOfParams == 1);
  //
  //    int16_t      tagColId = (int16_t)pExprInfo->base.param[0].i;
  //    SColumnInfo* pColInfo = doGetTagColumnInfoById(pQueryAttr->tagColList, pQueryAttr->numOfTags, tagColId);
  //
  //    doSetTagValueInParam(pTable, tagColId, &pCtx->tag, pColInfo->type, pColInfo->bytes);
  //
  //    int16_t tagType = pCtx[0].tag.nType;
  //    if (tagType == TSDB_DATA_TYPE_BINARY || tagType == TSDB_DATA_TYPE_NCHAR) {
  //      //qDebug("QInfo:0x%"PRIx64" set tag value for join comparison, colId:%" PRId64 ", val:%s",
  //      GET_TASKID(pRuntimeEnv),
  ////             pExprInfo->base.param[0].i, pCtx[0].tag.pz);
  //    } else {
  //      //qDebug("QInfo:0x%"PRIx64" set tag value for join comparison, colId:%" PRId64 ", val:%" PRId64,
  //      GET_TASKID(pRuntimeEnv),
  ////             pExprInfo->base.param[0].i, pCtx[0].tag.i);
  //    }
  //  }
}

int32_t setTimestampListJoinInfo(STaskRuntimeEnv* pRuntimeEnv, SVariant* pTag, STableQueryInfo* pTableQueryInfo) {
H
Haojun Liao 已提交
3147
  STaskAttr* pQueryAttr = pRuntimeEnv->pQueryAttr;
3148 3149

  assert(pRuntimeEnv->pTsBuf != NULL);
H
Haojun Liao 已提交
3150
#if 0
3151 3152 3153 3154 3155 3156 3157 3158 3159
  // 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) {
3160
        //qError("QInfo:0x%"PRIx64" failed to find tag:%s in ts_comp", GET_TASKID(pRuntimeEnv), pTag->pz);
3161
      } else {
3162
        //qError("QInfo:0x%"PRIx64" failed to find tag:%" PRId64 " in ts_comp", GET_TASKID(pRuntimeEnv), pTag->i);
3163 3164 3165 3166 3167 3168 3169 3170
      }

      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) {
3171
      //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);
3172
    } else {
3173
      //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);
3174 3175 3176 3177 3178
    }

  } else {
    tsBufSetCursor(pRuntimeEnv->pTsBuf, &pTableQueryInfo->cur);
    if (pTag->nType == TSDB_DATA_TYPE_BINARY || pTag->nType == TSDB_DATA_TYPE_NCHAR) {
3179
      //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);
3180
    } else {
3181
      //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);
3182 3183
    }
  }
H
Haojun Liao 已提交
3184
#endif
3185 3186 3187 3188 3189 3190
  return 0;
}

/*
 * There are two cases to handle:
 *
L
Liu Jicong 已提交
3191 3192
 * 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.
3193 3194 3195 3196
 * 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.
 */
L
Liu Jicong 已提交
3197 3198 3199 3200
void setIntervalQueryRange(STaskRuntimeEnv* pRuntimeEnv, TSKEY key) {
  STaskAttr*       pQueryAttr = pRuntimeEnv->pQueryAttr;
  STableQueryInfo* pTableQueryInfo = pRuntimeEnv->current;
  SResultRowInfo*  pResultRowInfo = &pTableQueryInfo->resInfo;
3201 3202 3203 3204 3205

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

L
Liu Jicong 已提交
3206
  //  pTableQueryInfo->win.skey = key;
3207 3208 3209 3210 3211 3212 3213 3214 3215 3216
  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 已提交
3217 3218
  TSKEY sk = TMIN(win.skey, win.ekey);
  TSKEY ek = TMAX(win.skey, win.ekey);
L
Liu Jicong 已提交
3219
  //  getAlignQueryTimeWindow(pQueryAttr, win.skey, sk, ek, &w);
3220

L
Liu Jicong 已提交
3221 3222 3223 3224 3225 3226 3227
  //  if (pResultRowInfo->prevSKey == TSKEY_INITIAL_VAL) {
  //    if (!QUERY_IS_ASC_QUERY(pQueryAttr)) {
  //      assert(win.ekey == pQueryAttr->window.ekey);
  //    }
  //
  //    pResultRowInfo->prevSKey = w.skey;
  //  }
3228

L
Liu Jicong 已提交
3229
  //  pTableQueryInfo->lastKey = pTableQueryInfo->win.skey;
3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240
}

/**
 * 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
 */
3241
int32_t doCopyToSDataBlock(SSDataBlock* pBlock, int32_t rowCapacity, SExprInfo* pExprInfo, SDiskbasedBuf* pBuf, SGroupResInfo* pGroupResInfo, int32_t orderType, int32_t* rowCellOffset) {
3242
  int32_t numOfRows = getNumOfTotalRes(pGroupResInfo);
L
Liu Jicong 已提交
3243
  int32_t numOfResult = pBlock->info.rows;  // there are already exists result rows
3244 3245 3246 3247

  int32_t start = 0;
  int32_t step = -1;

L
Liu Jicong 已提交
3248
  // qDebug("QInfo:0x%"PRIx64" start to copy data from windowResInfo to output buf", GET_TASKID(pRuntimeEnv));
3249 3250 3251 3252 3253 3254 3255 3256 3257 3258
  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;
  }

3259 3260
  int32_t nrows = pBlock->info.rows;

3261
  for (int32_t i = start; (i < numOfRows) && (i >= 0); i += step) {
3262
    SResultRowPosition* pPos = taosArrayGet(pGroupResInfo->pRows, i);
L
Liu Jicong 已提交
3263
    SFilePage*          page = getBufPage(pBuf, pPos->pageId);
3264 3265

    SResultRow* pRow = (SResultRow*)((char*)page + pPos->offset);
3266 3267 3268 3269 3270
    if (pRow->numOfRows == 0) {
      pGroupResInfo->index += 1;
      continue;
    }

3271
    // TODO copy multiple rows?
3272
    int32_t numOfRowsToCopy = pRow->numOfRows;
L
Liu Jicong 已提交
3273
    if (numOfResult + numOfRowsToCopy >= rowCapacity) {
3274 3275 3276 3277 3278 3279
      break;
    }

    pGroupResInfo->index += 1;

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

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

3285
      char* in = GET_ROWCELL_INTERBUF(pEntryInfo);
H
Haojun Liao 已提交
3286
      colDataAppend(pColInfoData, nrows, in, pEntryInfo->isNullRes);
3287 3288
    }

3289 3290 3291
    releaseBufPage(pBuf, page);
    nrows += 1;

3292
    numOfResult += numOfRowsToCopy;
H
Haojun Liao 已提交
3293
    if (numOfResult == rowCapacity) {  // output buffer is full
3294 3295 3296 3297
      break;
    }
  }

L
Liu Jicong 已提交
3298
  // qDebug("QInfo:0x%"PRIx64" copy data to query buf completed", GET_TASKID(pRuntimeEnv));
3299 3300 3301 3302
  pBlock->info.rows = numOfResult;
  return 0;
}

3303 3304
void toSDatablock(SSDataBlock* pBlock, int32_t rowCapacity, SGroupResInfo* pGroupResInfo, SExprInfo* pExprInfo, SDiskbasedBuf* pBuf,
                  int32_t* rowCellOffset) {
3305 3306
  assert(pGroupResInfo->currentGroup <= pGroupResInfo->totalGroup);

3307
  blockDataCleanup(pBlock);
3308 3309 3310 3311
  if (!hasRemainDataInCurrentGroup(pGroupResInfo)) {
    return;
  }

3312
  int32_t orderType = TSDB_ORDER_ASC;
3313
  doCopyToSDataBlock(pBlock, rowCapacity, pExprInfo, pBuf, pGroupResInfo, orderType, rowCellOffset);
3314

H
Haojun Liao 已提交
3315 3316
  // add condition (pBlock->info.rows >= 1) just to runtime happy
  blockDataUpdateTsWindow(pBlock);
3317 3318
}

L
Liu Jicong 已提交
3319 3320
static void updateNumOfRowsInResultRows(SqlFunctionCtx* pCtx, int32_t numOfOutput, SResultRowInfo* pResultRowInfo,
                                        int32_t* rowCellInfoOffset) {
3321
  // update the number of result for each, only update the number of rows for the corresponding window result.
L
Liu Jicong 已提交
3322 3323 3324
  //  if (QUERY_IS_INTERVAL_QUERY(pQueryAttr)) {
  //    return;
  //  }
H
Haojun Liao 已提交
3325
#if 0
3326
  for (int32_t i = 0; i < pResultRowInfo->size; ++i) {
L
Liu Jicong 已提交
3327
    SResultRow* pResult = pResultRowInfo->pResult[i];
3328 3329 3330 3331 3332 3333 3334

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

3335 3336
      SResultRowEntryInfo* pCell = getResultCell(pResult, j, rowCellInfoOffset);
      pResult->numOfRows = (uint16_t)(TMAX(pResult->numOfRows, pCell->numOfRes));
3337 3338
    }
  }
H
Haojun Liao 已提交
3339 3340
#endif

3341 3342
}

L
Liu Jicong 已提交
3343
static int32_t compressQueryColData(SColumnInfoData* pColRes, int32_t numOfRows, char* data, int8_t compressed) {
3344 3345
  int32_t colSize = pColRes->info.bytes * numOfRows;
  return (*(tDataTypes[pColRes->info.type].compFunc))(pColRes->pData, colSize, numOfRows, data,
L
Liu Jicong 已提交
3346
                                                      colSize + COMP_OVERFLOW_BYTES, compressed, NULL, 0);
3347 3348
}

L
Liu Jicong 已提交
3349 3350 3351 3352 3353
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);
  //  }
3354 3355 3356 3357 3358 3359 3360 3361 3362 3363

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

L
Liu Jicong 已提交
3364 3365
  event.eventType = eventType;
  event.eventTime = taosGetTimestampUs();
3366 3367 3368
  event.operatorType = operatorInfo->operatorType;

  if (operatorInfo->pRuntimeEnv) {
L
Liu Jicong 已提交
3369 3370 3371 3372
    //    SQInfo* pQInfo = operatorInfo->pRuntimeEnv->qinfo;
    //    if (pQInfo->summary.queryProfEvents) {
    //      taosArrayPush(pQInfo->summary.queryProfEvents, &event);
    //    }
3373 3374 3375
  }
}

L
Liu Jicong 已提交
3376
void publishQueryAbortEvent(SExecTaskInfo* pTaskInfo, int32_t code) {
3377 3378 3379 3380 3381
  SQueryProfEvent event;
  event.eventType = QUERY_PROF_QUERY_ABORT;
  event.eventTime = taosGetTimestampUs();
  event.abortCode = code;

3382 3383
  if (pTaskInfo->cost.queryProfEvents) {
    taosArrayPush(pTaskInfo->cost.queryProfEvents, &event);
3384 3385 3386
  }
}

L
Liu Jicong 已提交
3387
typedef struct {
3388 3389 3390 3391 3392 3393 3394
  uint8_t operatorType;
  int64_t beginTime;
  int64_t endTime;
  int64_t selfTime;
  int64_t descendantsTime;
} SOperatorStackItem;

L
Liu Jicong 已提交
3395 3396
static void doOperatorExecProfOnce(SOperatorStackItem* item, SQueryProfEvent* event, SArray* opStack,
                                   SHashObj* profResults) {
3397 3398 3399 3400 3401 3402 3403 3404
  item->endTime = event->eventTime;
  item->selfTime = (item->endTime - item->beginTime) - (item->descendantsTime);

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

L
Liu Jicong 已提交
3405
  uint8_t              operatorType = item->operatorType;
3406 3407 3408 3409 3410 3411 3412 3413 3414
  SOperatorProfResult* result = taosHashGet(profResults, &operatorType, sizeof(operatorType));
  if (result != NULL) {
    result->sumRunTimes++;
    result->sumSelfTime += item->selfTime;
  } else {
    SOperatorProfResult opResult;
    opResult.operatorType = operatorType;
    opResult.sumSelfTime = item->selfTime;
    opResult.sumRunTimes = 1;
L
Liu Jicong 已提交
3415
    taosHashPut(profResults, &(operatorType), sizeof(operatorType), &opResult, sizeof(opResult));
3416 3417 3418
  }
}

3419 3420 3421 3422 3423 3424 3425 3426 3427 3428
void calculateOperatorProfResults(void) {
//  if (pQInfo->summary.queryProfEvents == NULL) {
//    // qDebug("QInfo:0x%"PRIx64" query prof events array is null", pQInfo->qId);
//    return;
//  }
//
//  if (pQInfo->summary.operatorProfResults == NULL) {
//    // qDebug("QInfo:0x%"PRIx64" operator prof results hash is null", pQInfo->qId);
//    return;
//  }
3429 3430 3431 3432 3433

  SArray* opStack = taosArrayInit(32, sizeof(SOperatorStackItem));
  if (opStack == NULL) {
    return;
  }
3434
#if 0
L
Liu Jicong 已提交
3435
  size_t    size = taosArrayGetSize(pQInfo->summary.queryProfEvents);
3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456
  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);
      }
    }
  }
3457
#endif
3458 3459 3460
  taosArrayDestroy(opStack);
}

L
Liu Jicong 已提交
3461 3462
void queryCostStatis(SExecTaskInfo* pTaskInfo) {
  STaskCostInfo* pSummary = &pTaskInfo->cost;
3463

L
Liu Jicong 已提交
3464 3465 3466
  //  uint64_t hashSize = taosHashGetMemSize(pQInfo->runtimeEnv.pResultRowHashTable);
  //  hashSize += taosHashGetMemSize(pRuntimeEnv->tableqinfoGroupInfo.map);
  //  pSummary->hashSize = hashSize;
3467 3468 3469 3470

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

L
Liu Jicong 已提交
3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490
  //  SResultRowPool* p = pTaskInfo->pool;
  //  if (p != NULL) {
  //    pSummary->winInfoSize = getResultRowPoolMemSize(p);
  //    pSummary->numOfTimeWindows = getNumOfAllocatedResultRows(p);
  //  } else {
  //    pSummary->winInfoSize = 0;
  //    pSummary->numOfTimeWindows = 0;
  //  }
  //
  //  calculateOperatorProfResults(pQInfo);

  qDebug("%s :cost summary: elapsed time:%" PRId64 " us, first merge:%" PRId64
         " us, total blocks:%d, "
         "load block statis:%d, load data block:%d, total rows:%" PRId64 ", check rows:%" PRId64,
         GET_TASKID(pTaskInfo), pSummary->elapsedTime, pSummary->firstStageMergeTime, pSummary->totalBlocks,
         pSummary->loadBlockStatis, pSummary->loadBlocks, pSummary->totalRows, pSummary->totalCheckedRows);
  //
  // qDebug("QInfo:0x%"PRIx64" :cost summary: winResPool size:%.2f Kb, numOfWin:%"PRId64", tableInfoSize:%.2f Kb,
  // hashTable:%.2f Kb", pQInfo->qId, pSummary->winInfoSize/1024.0,
  //      pSummary->numOfTimeWindows, pSummary->tableInfoSize/1024.0, pSummary->hashSize/1024.0);
3491 3492 3493 3494

  if (pSummary->operatorProfResults) {
    SOperatorProfResult* opRes = taosHashIterate(pSummary->operatorProfResults, NULL);
    while (opRes != NULL) {
L
Liu Jicong 已提交
3495 3496
      // qDebug("QInfo:0x%" PRIx64 " :cost summary: operator : %d, exec times: %" PRId64 ", self time: %" PRId64,
      //             pQInfo->qId, opRes->operatorType, opRes->sumRunTimes, opRes->sumSelfTime);
3497 3498 3499 3500 3501
      opRes = taosHashIterate(pSummary->operatorProfResults, opRes);
    }
  }
}

L
Liu Jicong 已提交
3502 3503 3504
// static void updateOffsetVal(STaskRuntimeEnv *pRuntimeEnv, SDataBlockInfo *pBlockInfo) {
//   STaskAttr *pQueryAttr = pRuntimeEnv->pQueryAttr;
//   STableQueryInfo* pTableQueryInfo = pRuntimeEnv->current;
3505
//
L
Liu Jicong 已提交
3506
//   int32_t step = GET_FORWARD_DIRECTION_FACTOR(pQueryAttr->order.order);
3507
//
L
Liu Jicong 已提交
3508 3509 3510 3511
//   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;
//   }
3512
//
L
Liu Jicong 已提交
3513 3514 3515 3516 3517
//   if (QUERY_IS_ASC_QUERY(pQueryAttr)) {
//     pQueryAttr->pos = (int32_t)pQueryAttr->limit.offset;
//   } else {
//     pQueryAttr->pos = pBlockInfo->rows - (int32_t)pQueryAttr->limit.offset - 1;
//   }
3518
//
L
Liu Jicong 已提交
3519
//   assert(pQueryAttr->pos >= 0 && pQueryAttr->pos <= pBlockInfo->rows - 1);
3520
//
L
Liu Jicong 已提交
3521 3522
//   SArray *         pDataBlock = tsdbRetrieveDataBlock(pRuntimeEnv->pTsdbReadHandle, NULL);
//   SColumnInfoData *pColInfoData = taosArrayGet(pDataBlock, 0);
3523
//
L
Liu Jicong 已提交
3524 3525
//   // update the pQueryAttr->limit.offset value, and pQueryAttr->pos value
//   TSKEY *keys = (TSKEY *) pColInfoData->pData;
3526
//
L
Liu Jicong 已提交
3527 3528 3529
//   // update the offset value
//   pTableQueryInfo->lastKey = keys[pQueryAttr->pos];
//   pQueryAttr->limit.offset = 0;
3530
//
L
Liu Jicong 已提交
3531
//   int32_t numOfRes = tableApplyFunctionsOnBlock(pRuntimeEnv, pBlockInfo, NULL, binarySearchForKey, pDataBlock);
3532
//
L
Liu Jicong 已提交
3533 3534 3535 3536
//   //qDebug("QInfo:0x%"PRIx64" check data block, brange:%" PRId64 "-%" PRId64 ", numBlocksOfStep:%d, numOfRes:%d,
//   lastKey:%"PRId64, GET_TASKID(pRuntimeEnv),
//          pBlockInfo->window.skey, pBlockInfo->window.ekey, pBlockInfo->rows, numOfRes, pQuery->current->lastKey);
// }
3537

L
Liu Jicong 已提交
3538 3539
// void skipBlocks(STaskRuntimeEnv *pRuntimeEnv) {
//   STaskAttr *pQueryAttr = pRuntimeEnv->pQueryAttr;
3540
//
L
Liu Jicong 已提交
3541 3542 3543
//   if (pQueryAttr->limit.offset <= 0 || pQueryAttr->numOfFilterCols > 0) {
//     return;
//   }
3544
//
L
Liu Jicong 已提交
3545 3546
//   pQueryAttr->pos = 0;
//   int32_t step = GET_FORWARD_DIRECTION_FACTOR(pQueryAttr->order.order);
3547
//
L
Liu Jicong 已提交
3548 3549
//   STableQueryInfo* pTableQueryInfo = pRuntimeEnv->current;
//   TsdbQueryHandleT pTsdbReadHandle = pRuntimeEnv->pTsdbReadHandle;
3550
//
L
Liu Jicong 已提交
3551 3552 3553 3554 3555
//   SDataBlockInfo blockInfo = SDATA_BLOCK_INITIALIZER;
//   while (tsdbNextDataBlock(pTsdbReadHandle)) {
//     if (isTaskKilled(pRuntimeEnv->qinfo)) {
//       longjmp(pRuntimeEnv->env, TSDB_CODE_TSC_QUERY_CANCELLED);
//     }
3556
//
L
Liu Jicong 已提交
3557
//     tsdbRetrieveDataBlockInfo(pTsdbReadHandle, &blockInfo);
3558
//
L
Liu Jicong 已提交
3559 3560 3561 3562
//     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;
3563
//
L
Liu Jicong 已提交
3564 3565 3566 3567 3568 3569 3570
//       //qDebug("QInfo:0x%"PRIx64" skip rows:%d, offset:%" PRId64, GET_TASKID(pRuntimeEnv), blockInfo.rows,
//              pQuery->limit.offset);
//     } else {  // find the appropriated start position in current block
//       updateOffsetVal(pRuntimeEnv, &blockInfo);
//       break;
//     }
//   }
3571
//
L
Liu Jicong 已提交
3572 3573 3574 3575 3576 3577 3578 3579 3580
//   if (terrno != TSDB_CODE_SUCCESS) {
//     longjmp(pRuntimeEnv->env, terrno);
//   }
// }

// static TSKEY doSkipIntervalProcess(STaskRuntimeEnv* pRuntimeEnv, STimeWindow* win, SDataBlockInfo* pBlockInfo,
// STableQueryInfo* pTableQueryInfo) {
//   STaskAttr *pQueryAttr = pRuntimeEnv->pQueryAttr;
//   SResultRowInfo *pWindowResInfo = &pRuntimeEnv->resultRowInfo;
3581
//
L
Liu Jicong 已提交
3582 3583 3584
//   assert(pQueryAttr->limit.offset == 0);
//   STimeWindow tw = *win;
//   getNextTimeWindow(pQueryAttr, &tw);
3585
//
L
Liu Jicong 已提交
3586 3587
//   if ((tw.skey <= pBlockInfo->window.ekey && QUERY_IS_ASC_QUERY(pQueryAttr)) ||
//       (tw.ekey >= pBlockInfo->window.skey && !QUERY_IS_ASC_QUERY(pQueryAttr))) {
3588
//
L
Liu Jicong 已提交
3589 3590 3591 3592
//     // load the data block and check data remaining in current data block
//     // TODO optimize performance
//     SArray *         pDataBlock = tsdbRetrieveDataBlock(pRuntimeEnv->pTsdbReadHandle, NULL);
//     SColumnInfoData *pColInfoData = taosArrayGet(pDataBlock, 0);
3593
//
L
Liu Jicong 已提交
3594 3595 3596 3597
//     tw = *win;
//     int32_t startPos =
//         getNextQualifiedWindow(pQueryAttr, &tw, pBlockInfo, pColInfoData->pData, binarySearchForKey, -1);
//     assert(startPos >= 0);
3598
//
L
Liu Jicong 已提交
3599 3600
//     // set the abort info
//     pQueryAttr->pos = startPos;
3601
//
L
Liu Jicong 已提交
3602 3603 3604 3605
//     // reset the query start timestamp
//     pTableQueryInfo->win.skey = ((TSKEY *)pColInfoData->pData)[startPos];
//     pQueryAttr->window.skey = pTableQueryInfo->win.skey;
//     TSKEY key = pTableQueryInfo->win.skey;
3606
//
L
Liu Jicong 已提交
3607 3608
//     pWindowResInfo->prevSKey = tw.skey;
//     int32_t index = pRuntimeEnv->resultRowInfo.curIndex;
3609
//
L
Liu Jicong 已提交
3610 3611
//     int32_t numOfRes = tableApplyFunctionsOnBlock(pRuntimeEnv, pBlockInfo, NULL, binarySearchForKey, pDataBlock);
//     pRuntimeEnv->resultRowInfo.curIndex = index;  // restore the window index
3612
//
L
Liu Jicong 已提交
3613 3614 3615 3616
//     //qDebug("QInfo:0x%"PRIx64" check data block, brange:%" PRId64 "-%" PRId64 ", numOfRows:%d, numOfRes:%d,
//     lastKey:%" PRId64,
//            GET_TASKID(pRuntimeEnv), pBlockInfo->window.skey, pBlockInfo->window.ekey, pBlockInfo->rows, numOfRes,
//            pQueryAttr->current->lastKey);
3617
//
L
Liu Jicong 已提交
3618 3619 3620 3621 3622
//     return key;
//   } else {  // do nothing
//     pQueryAttr->window.skey      = tw.skey;
//     pWindowResInfo->prevSKey = tw.skey;
//     pTableQueryInfo->lastKey = tw.skey;
3623
//
L
Liu Jicong 已提交
3624 3625
//     return tw.skey;
//   }
3626
//
L
Liu Jicong 已提交
3627 3628 3629 3630 3631 3632 3633 3634 3635 3636
//   return true;
// }

// static bool skipTimeInterval(STaskRuntimeEnv *pRuntimeEnv, TSKEY* start) {
//   STaskAttr *pQueryAttr = pRuntimeEnv->pQueryAttr;
//   if (QUERY_IS_ASC_QUERY(pQueryAttr)) {
//     assert(*start <= pRuntimeEnv->current->lastKey);
//   } else {
//     assert(*start >= pRuntimeEnv->current->lastKey);
//   }
3637
//
L
Liu Jicong 已提交
3638 3639 3640 3641 3642
//   // 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;
//   }
3643
//
L
Liu Jicong 已提交
3644 3645 3646 3647 3648 3649 3650
//   /*
//    * 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);
3651
//
L
Liu Jicong 已提交
3652 3653
//   STimeWindow w = TSWINDOW_INITIALIZER;
//   bool ascQuery = QUERY_IS_ASC_QUERY(pQueryAttr);
3654
//
L
Liu Jicong 已提交
3655 3656
//   SResultRowInfo *pWindowResInfo = &pRuntimeEnv->resultRowInfo;
//   STableQueryInfo *pTableQueryInfo = pRuntimeEnv->current;
3657
//
L
Liu Jicong 已提交
3658 3659 3660
//   SDataBlockInfo blockInfo = SDATA_BLOCK_INITIALIZER;
//   while (tsdbNextDataBlock(pRuntimeEnv->pTsdbReadHandle)) {
//     tsdbRetrieveDataBlockInfo(pRuntimeEnv->pTsdbReadHandle, &blockInfo);
3661
//
L
Liu Jicong 已提交
3662 3663 3664 3665 3666 3667 3668 3669 3670
//     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;
//     }
3671
//
L
Liu Jicong 已提交
3672 3673
//     // the first time window
//     STimeWindow win = getActiveTimeWindow(pWindowResInfo, pWindowResInfo->prevSKey, pQueryAttr);
3674
//
L
Liu Jicong 已提交
3675 3676
//     while (pQueryAttr->limit.offset > 0) {
//       STimeWindow tw = win;
3677
//
L
Liu Jicong 已提交
3678 3679 3680
//       if ((win.ekey <= blockInfo.window.ekey && ascQuery) || (win.ekey >= blockInfo.window.skey && !ascQuery)) {
//         pQueryAttr->limit.offset -= 1;
//         pWindowResInfo->prevSKey = win.skey;
3681
//
L
Liu Jicong 已提交
3682 3683 3684 3685 3686 3687
//         // 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;
//         }
//       }
3688
//
L
Liu Jicong 已提交
3689 3690 3691 3692
//       if (pQueryAttr->limit.offset == 0) {
//         *start = doSkipIntervalProcess(pRuntimeEnv, &win, &blockInfo, pTableQueryInfo);
//         return true;
//       }
3693
//
L
Liu Jicong 已提交
3694 3695
//       // current window does not ended in current data block, try next data block
//       getNextTimeWindow(pQueryAttr, &tw);
3696
//
L
Liu Jicong 已提交
3697 3698 3699 3700 3701 3702 3703 3704 3705
//       /*
//        * 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)) {
3706
//
L
Liu Jicong 已提交
3707 3708
//         SArray *pDataBlock = tsdbRetrieveDataBlock(pRuntimeEnv->pTsdbReadHandle, NULL);
//         SColumnInfoData *pColInfoData = taosArrayGet(pDataBlock, 0);
3709
//
L
Liu Jicong 已提交
3710 3711 3712
//         if ((win.ekey > blockInfo.window.ekey && ascQuery) || (win.ekey < blockInfo.window.skey && !ascQuery)) {
//           pQueryAttr->limit.offset -= 1;
//         }
3713
//
L
Liu Jicong 已提交
3714 3715 3716 3717 3718 3719 3720 3721
//         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);
3722
//
L
Liu Jicong 已提交
3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733
//           // 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.
//       }
//     }
//   }
3734
//
L
Liu Jicong 已提交
3735 3736 3737 3738
//   // check for error
//   if (terrno != TSDB_CODE_SUCCESS) {
//     longjmp(pRuntimeEnv->env, terrno);
//   }
3739
//
L
Liu Jicong 已提交
3740 3741
//   return true;
// }
3742

3743
int32_t appendDownstream(SOperatorInfo* p, SOperatorInfo** pDownstream, int32_t num) {
H
Haojun Liao 已提交
3744
  if (p->pDownstream == NULL) {
H
Haojun Liao 已提交
3745
    assert(p->numOfDownstream == 0);
3746 3747
  }

wafwerar's avatar
wafwerar 已提交
3748
  p->pDownstream = taosMemoryCalloc(1, num * POINTER_BYTES);
3749 3750 3751 3752 3753 3754 3755
  if (p->pDownstream == NULL) {
    return TSDB_CODE_OUT_OF_MEMORY;
  }

  memcpy(p->pDownstream, pDownstream, num * POINTER_BYTES);
  p->numOfDownstream = num;
  return TSDB_CODE_SUCCESS;
3756 3757 3758 3759
}

static void doDestroyTableQueryInfo(STableGroupInfo* pTableqinfoGroupInfo);

3760
static void doTableQueryInfoTimeWindowCheck(SExecTaskInfo* pTaskInfo, STableQueryInfo* pTableQueryInfo, int32_t order) {
H
Haojun Liao 已提交
3761 3762
#if 0
    if (order == TSDB_ORDER_ASC) {
3763 3764
    assert(
        (pTableQueryInfo->win.skey <= pTableQueryInfo->win.ekey) &&
H
Haojun Liao 已提交
3765 3766
        (pTableQueryInfo->lastKey >= pTaskInfo->window.skey) &&
        (pTableQueryInfo->win.skey >= pTaskInfo->window.skey && pTableQueryInfo->win.ekey <= pTaskInfo->window.ekey));
3767 3768 3769
  } else {
    assert(
        (pTableQueryInfo->win.skey >= pTableQueryInfo->win.ekey) &&
H
Haojun Liao 已提交
3770 3771
        (pTableQueryInfo->lastKey <= pTaskInfo->window.skey) &&
        (pTableQueryInfo->win.skey <= pTaskInfo->window.skey && pTableQueryInfo->win.ekey >= pTaskInfo->window.ekey));
3772
  }
H
Haojun Liao 已提交
3773
#endif
3774 3775
}

L
Liu Jicong 已提交
3776 3777 3778 3779 3780 3781 3782 3783
// STsdbQueryCond createTsdbQueryCond(STaskAttr* pQueryAttr, STimeWindow* win) {
//   STsdbQueryCond cond = {
//       .colList   = pQueryAttr->tableCols,
//       .order     = pQueryAttr->order.order,
//       .numOfCols = pQueryAttr->numOfCols,
//       .type      = BLOCK_LOAD_OFFSET_SEQ_ORDER,
//       .loadExternalRows = false,
//   };
3784
//
L
Liu Jicong 已提交
3785 3786 3787
//   TIME_WINDOW_COPY(cond.twindow, *win);
//   return cond;
// }
3788 3789 3790

static STableIdInfo createTableIdInfo(STableQueryInfo* pTableQueryInfo) {
  STableIdInfo tidInfo;
L
Liu Jicong 已提交
3791 3792 3793 3794 3795
  //  STableId* id = TSDB_TABLEID(pTableQueryInfo->pTable);
  //
  //  tidInfo.uid = id->uid;
  //  tidInfo.tid = id->tid;
  //  tidInfo.key = pTableQueryInfo->lastKey;
3796 3797 3798 3799

  return tidInfo;
}

L
Liu Jicong 已提交
3800 3801 3802 3803
// 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;
3804
//
L
Liu Jicong 已提交
3805 3806 3807
//   if (pTableQueryInfo->pTable == NULL) {
//     return;
//   }
3808
//
L
Liu Jicong 已提交
3809 3810 3811 3812 3813 3814 3815 3816 3817
//   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));
//   }
// }
3818

H
Haojun Liao 已提交
3819
static void doCloseAllTimeWindow(STaskRuntimeEnv* pRuntimeEnv) {
3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831
  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);
    }
  }
}

3832
int32_t loadRemoteDataCallback(void* param, const SDataBuf* pMsg, int32_t code) {
L
Liu Jicong 已提交
3833
  SSourceDataInfo* pSourceDataInfo = (SSourceDataInfo*)param;
H
Haojun Liao 已提交
3834 3835
  if (code == TSDB_CODE_SUCCESS) {
    pSourceDataInfo->pRsp = pMsg->pData;
3836

H
Haojun Liao 已提交
3837 3838 3839 3840 3841 3842 3843
    SRetrieveTableRsp* pRsp = pSourceDataInfo->pRsp;
    pRsp->numOfRows = htonl(pRsp->numOfRows);
    pRsp->compLen   = htonl(pRsp->compLen);
    pRsp->useconds  = htobe64(pRsp->useconds);
  } else {
    pSourceDataInfo->code = code;
  }
H
Haojun Liao 已提交
3844

H
Haojun Liao 已提交
3845
  pSourceDataInfo->status = EX_SOURCE_DATA_READY;
3846
  tsem_post(&pSourceDataInfo->pEx->ready);
wmmhello's avatar
wmmhello 已提交
3847
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
3848 3849 3850 3851
}

static void destroySendMsgInfo(SMsgSendInfo* pMsgBody) {
  assert(pMsgBody != NULL);
wafwerar's avatar
wafwerar 已提交
3852 3853
  taosMemoryFreeClear(pMsgBody->msgInfo.pData);
  taosMemoryFreeClear(pMsgBody);
H
Haojun Liao 已提交
3854 3855
}

S
Shengliang Guan 已提交
3856
void qProcessFetchRsp(void* parent, SRpcMsg* pMsg, SEpSet* pEpSet) {
L
Liu Jicong 已提交
3857
  SMsgSendInfo* pSendInfo = (SMsgSendInfo*)pMsg->ahandle;
H
Haojun Liao 已提交
3858 3859 3860 3861 3862
  assert(pMsg->ahandle != NULL);

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

  if (pMsg->contLen > 0) {
wafwerar's avatar
wafwerar 已提交
3863
    buf.pData = taosMemoryCalloc(1, pMsg->contLen);
H
Haojun Liao 已提交
3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874
    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);
3875 3876
}

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

wafwerar's avatar
wafwerar 已提交
3880
  SResFetchReq* pMsg = taosMemoryCalloc(1, sizeof(SResFetchReq));
3881 3882 3883 3884
  if (NULL == pMsg) {
    pTaskInfo->code = TSDB_CODE_QRY_OUT_OF_MEMORY;
    return pTaskInfo->code;
  }
3885

L
Liu Jicong 已提交
3886 3887
  SDownstreamSourceNode* pSource = taosArrayGet(pExchangeInfo->pSources, sourceIndex);
  SSourceDataInfo*       pDataInfo = taosArrayGet(pExchangeInfo->pSourceDataInfo, sourceIndex);
3888

L
Liu Jicong 已提交
3889 3890
  qDebug("%s build fetch msg and send to vgId:%d, ep:%s, taskId:0x%" PRIx64 ", %d/%" PRIzu, GET_TASKID(pTaskInfo),
         pSource->addr.nodeId, pSource->addr.epSet.eps[0].fqdn, pSource->taskId, sourceIndex, totalSources);
3891 3892 3893 3894 3895 3896 3897

  pMsg->header.vgId = htonl(pSource->addr.nodeId);
  pMsg->sId = htobe64(pSource->schedId);
  pMsg->taskId = htobe64(pSource->taskId);
  pMsg->queryId = htobe64(pTaskInfo->id.queryId);

  // send the fetch remote task result reques
wafwerar's avatar
wafwerar 已提交
3898
  SMsgSendInfo* pMsgSendInfo = taosMemoryCalloc(1, sizeof(SMsgSendInfo));
3899
  if (NULL == pMsgSendInfo) {
wafwerar's avatar
wafwerar 已提交
3900
    taosMemoryFreeClear(pMsg);
3901 3902 3903
    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 已提交
3904 3905
  }

3906 3907 3908 3909 3910
  pMsgSendInfo->param = pDataInfo;
  pMsgSendInfo->msgInfo.pData = pMsg;
  pMsgSendInfo->msgInfo.len = sizeof(SResFetchReq);
  pMsgSendInfo->msgType = TDMT_VND_FETCH;
  pMsgSendInfo->fp = loadRemoteDataCallback;
3911

3912
  int64_t transporterId = 0;
L
Liu Jicong 已提交
3913
  int32_t code = asyncSendMsgToServer(pExchangeInfo->pTransporter, &pSource->addr.epSet, &transporterId, pMsgSendInfo);
3914 3915 3916
  return TSDB_CODE_SUCCESS;
}

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

H
Haojun Liao 已提交
3922 3923
  if (pColList == NULL) {  // data from other sources
    int32_t* colLen = (int32_t*)pData;
L
Liu Jicong 已提交
3924
    char*    pStart = pData + sizeof(int32_t) * numOfOutput;
H
Haojun Liao 已提交
3925

3926
    for (int32_t i = 0; i < numOfOutput; ++i) {
H
Haojun Liao 已提交
3927 3928 3929
      colLen[i] = htonl(colLen[i]);
      ASSERT(colLen[i] > 0);

3930
      SColumnInfoData* pColInfoData = taosArrayGet(pRes->pDataBlock, i);
H
Haojun Liao 已提交
3931 3932 3933
      if (IS_VAR_DATA_TYPE(pColInfoData->info.type)) {
        pColInfoData->varmeta.length = colLen[i];
        pColInfoData->varmeta.allocLen = colLen[i];
3934

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

wafwerar's avatar
wafwerar 已提交
3938
        pColInfoData->pData = taosMemoryMalloc(colLen[i]);
H
Haojun Liao 已提交
3939 3940 3941
      } else {
        memcpy(pColInfoData->nullbitmap, pStart, BitmapLen(numOfRows));
        pStart += BitmapLen(numOfRows);
3942
      }
H
Haojun Liao 已提交
3943 3944 3945

      memcpy(pColInfoData->pData, pStart, colLen[i]);
      pStart += colLen[i];
3946
    }
H
Haojun Liao 已提交
3947
  } else {  // extract data according to pColList
3948
    ASSERT(numOfOutput == taosArrayGetSize(pColList));
3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982
    char* pStart = pData;

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

    SSysTableSchema* pSchema = (SSysTableSchema*)pStart;
    for(int32_t i = 0; i < numOfCols; ++i) {
      SSysTableSchema* p = (SSysTableSchema*)pStart;

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

    SSDataBlock block = {.pDataBlock = taosArrayInit(numOfCols, sizeof(SColumnInfoData)), .info.numOfCols = numOfCols};
    for(int32_t i = 0; i < numOfCols; ++i) {
      SColumnInfoData idata = {0};
      idata.info.type = pSchema[i].type;
      idata.info.bytes = pSchema[i].bytes;
      idata.info.colId = pSchema[i].colId;

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

    blockDataEnsureCapacity(&block, numOfRows);

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

    for (int32_t i = 0; i < numOfCols; ++i) {
      colLen[i] = htonl(colLen[i]);
3983
      ASSERT(colLen[i] >= 0);
3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001

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

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

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

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

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

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

4010 4011
        if (colIndex - 1 == i) {
          SColumnInfoData* pColInfoData = taosArrayGet(pRes->pDataBlock, j);
4012
          colDataAssign(pColInfoData, pSrc, numOfRows);
4013 4014 4015
          break;
        }
      }
4016
    }
4017
  }
4018

H
Haojun Liao 已提交
4019
  pRes->info.rows = numOfRows;
4020

4021
  int64_t el = taosGetTimestampUs() - startTs;
4022

H
Haojun Liao 已提交
4023 4024
  pLoadInfo->totalRows += numOfRows;
  pLoadInfo->totalSize += compLen;
4025

H
Haojun Liao 已提交
4026 4027 4028
  if (total != NULL) {
    *total += numOfRows;
  }
4029

H
Haojun Liao 已提交
4030
  pLoadInfo->totalElapsed += el;
4031 4032
  return TSDB_CODE_SUCCESS;
}
4033

L
Liu Jicong 已提交
4034 4035
static void* setAllSourcesCompleted(SOperatorInfo* pOperator, int64_t startTs) {
  SExchangeInfo* pExchangeInfo = pOperator->info;
4036
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
H
Haojun Liao 已提交
4037

L
Liu Jicong 已提交
4038
  int64_t              el = taosGetTimestampUs() - startTs;
H
Haojun Liao 已提交
4039 4040
  SLoadRemoteDataInfo* pLoadInfo = &pExchangeInfo->loadInfo;
  pLoadInfo->totalElapsed += el;
H
Haojun Liao 已提交
4041

4042
  size_t totalSources = taosArrayGetSize(pExchangeInfo->pSources);
L
Liu Jicong 已提交
4043 4044 4045
  qDebug("%s all %" PRIzu " sources are exhausted, total rows: %" PRIu64 " bytes:%" PRIu64 ", elapsed:%.2f ms",
         GET_TASKID(pTaskInfo), totalSources, pLoadInfo->totalRows, pLoadInfo->totalSize,
         pLoadInfo->totalElapsed / 1000.0);
4046 4047 4048 4049 4050

  doSetOperatorCompleted(pOperator);
  return NULL;
}

L
Liu Jicong 已提交
4051 4052
static SSDataBlock* concurrentlyLoadRemoteDataImpl(SOperatorInfo* pOperator, SExchangeInfo* pExchangeInfo,
                                                   SExecTaskInfo* pTaskInfo) {
4053 4054 4055 4056 4057 4058 4059 4060 4061
  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);

4062
      if (pDataInfo->status == EX_SOURCE_DATA_EXHAUSTED) {
4063
        completed += 1;
H
Haojun Liao 已提交
4064 4065
        continue;
      }
4066

4067
      if (pDataInfo->status != EX_SOURCE_DATA_READY) {
4068 4069 4070
        continue;
      }

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

L
Liu Jicong 已提交
4074
      SSDataBlock*         pRes = pExchangeInfo->pResult;
H
Haojun Liao 已提交
4075
      SLoadRemoteDataInfo* pLoadInfo = &pExchangeInfo->loadInfo;
4076
      if (pRsp->numOfRows == 0) {
L
Liu Jicong 已提交
4077 4078
        qDebug("%s vgId:%d, taskID:0x%" PRIx64 " index:%d completed, rowsOfSource:%" PRIu64 ", totalRows:%" PRIu64
               " try next",
4079
               GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->taskId, i + 1, pDataInfo->totalRows,
H
Haojun Liao 已提交
4080
               pExchangeInfo->loadInfo.totalRows);
4081
        pDataInfo->status = EX_SOURCE_DATA_EXHAUSTED;
4082 4083 4084
        completed += 1;
        continue;
      }
H
Haojun Liao 已提交
4085

H
Haojun Liao 已提交
4086
      SRetrieveTableRsp* pTableRsp = pDataInfo->pRsp;
L
Liu Jicong 已提交
4087 4088 4089
      code =
          setSDataBlockFromFetchRsp(pExchangeInfo->pResult, pLoadInfo, pTableRsp->numOfRows, pTableRsp->data,
                                    pTableRsp->compLen, pOperator->numOfOutput, startTs, &pDataInfo->totalRows, NULL);
4090
      if (code != 0) {
4091 4092 4093
        goto _error;
      }

4094 4095 4096
      if (pRsp->completed == 1) {
        qDebug("%s fetch msg rsp from vgId:%d, taskId:0x%" PRIx64 " numOfRows:%d, rowsOfSource:%" PRIu64
               ", totalRows:%" PRIu64 ", totalBytes:%" PRIu64 " try next %d/%" PRIzu,
L
Liu Jicong 已提交
4097 4098
               GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->taskId, pRes->info.rows, pDataInfo->totalRows,
               pLoadInfo->totalRows, pLoadInfo->totalSize, i + 1, totalSources);
4099
        pDataInfo->status = EX_SOURCE_DATA_EXHAUSTED;
4100
      } else {
4101
        qDebug("%s fetch msg rsp from vgId:%d, taskId:0x%" PRIx64 " numOfRows:%d, totalRows:%" PRIu64 ", totalBytes:%" PRIu64,
H
Haojun Liao 已提交
4102 4103
               GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->taskId, pRes->info.rows, pLoadInfo->totalRows,
               pLoadInfo->totalSize);
4104 4105
      }

4106 4107
      if (pDataInfo->status != EX_SOURCE_DATA_EXHAUSTED) {
        pDataInfo->status = EX_SOURCE_DATA_NOT_READY;
4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126
        code = doSendFetchDataRequest(pExchangeInfo, pTaskInfo, i);
        if (code != TSDB_CODE_SUCCESS) {
          goto _error;
        }
      }

      return pExchangeInfo->pResult;
    }

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

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

L
Liu Jicong 已提交
4127 4128 4129
static SSDataBlock* concurrentlyLoadRemoteData(SOperatorInfo* pOperator) {
  SExchangeInfo* pExchangeInfo = pOperator->info;
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
H
Haojun Liao 已提交
4130

H
Haojun Liao 已提交
4131 4132 4133
  if (pOperator->status == OP_RES_TO_RETURN) {
    return concurrentlyLoadRemoteDataImpl(pOperator, pExchangeInfo, pTaskInfo);
  }
4134

L
Liu Jicong 已提交
4135
  size_t  totalSources = taosArrayGetSize(pExchangeInfo->pSources);
4136 4137 4138
  int64_t startTs = taosGetTimestampUs();

  // Asynchronously send all fetch requests to all sources.
L
Liu Jicong 已提交
4139
  for (int32_t i = 0; i < totalSources; ++i) {
4140 4141
    int32_t code = doSendFetchDataRequest(pExchangeInfo, pTaskInfo, i);
    if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
4142
      return NULL;
4143 4144 4145 4146
    }
  }

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

  tsem_wait(&pExchangeInfo->ready);
H
Haojun Liao 已提交
4151 4152
  pOperator->status = OP_RES_TO_RETURN;
  return concurrentlyLoadRemoteDataImpl(pOperator, pExchangeInfo, pTaskInfo);
4153 4154
}

L
Liu Jicong 已提交
4155 4156 4157
static int32_t prepareConcurrentlyLoad(SOperatorInfo* pOperator) {
  SExchangeInfo* pExchangeInfo = pOperator->info;
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
4158

L
Liu Jicong 已提交
4159
  size_t  totalSources = taosArrayGetSize(pExchangeInfo->pSources);
4160 4161 4162
  int64_t startTs = taosGetTimestampUs();

  // Asynchronously send all fetch requests to all sources.
L
Liu Jicong 已提交
4163
  for (int32_t i = 0; i < totalSources; ++i) {
4164 4165
    int32_t code = doSendFetchDataRequest(pExchangeInfo, pTaskInfo, i);
    if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
4166 4167
      pTaskInfo->code = code;
      return code;
4168 4169 4170 4171
    }
  }

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

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

H
Haojun Liao 已提交
4178
  return TSDB_CODE_SUCCESS;
4179 4180
}

L
Liu Jicong 已提交
4181 4182 4183
static SSDataBlock* seqLoadRemoteData(SOperatorInfo* pOperator) {
  SExchangeInfo* pExchangeInfo = pOperator->info;
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
4184

L
Liu Jicong 已提交
4185
  size_t  totalSources = taosArrayGetSize(pExchangeInfo->pSources);
4186
  int64_t startTs = taosGetTimestampUs();
4187

L
Liu Jicong 已提交
4188
  while (1) {
4189 4190
    if (pExchangeInfo->current >= totalSources) {
      return setAllSourcesCompleted(pOperator, startTs);
4191
    }
4192

4193 4194 4195
    doSendFetchDataRequest(pExchangeInfo, pTaskInfo, pExchangeInfo->current);
    tsem_wait(&pExchangeInfo->ready);

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

H
Haojun Liao 已提交
4199 4200 4201 4202 4203 4204 4205
    if (pDataInfo->code != TSDB_CODE_SUCCESS) {
      qError("%s vgId:%d, taskID:0x%" PRIx64 " error happens, code:%s",
             GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->taskId, tstrerror(pDataInfo->code));
      pOperator->pTaskInfo->code = pDataInfo->code;
      return NULL;
    }

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

4213
      pDataInfo->status = EX_SOURCE_DATA_EXHAUSTED;
4214 4215 4216
      pExchangeInfo->current += 1;
      continue;
    }
H
Haojun Liao 已提交
4217

L
Liu Jicong 已提交
4218
    SSDataBlock*       pRes = pExchangeInfo->pResult;
H
Haojun Liao 已提交
4219
    SRetrieveTableRsp* pTableRsp = pDataInfo->pRsp;
L
Liu Jicong 已提交
4220 4221 4222
    int32_t            code =
        setSDataBlockFromFetchRsp(pExchangeInfo->pResult, pLoadInfo, pTableRsp->numOfRows, pTableRsp->data,
                                  pTableRsp->compLen, pOperator->numOfOutput, startTs, &pDataInfo->totalRows, NULL);
4223 4224

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

4230
      pDataInfo->status = EX_SOURCE_DATA_EXHAUSTED;
4231 4232
      pExchangeInfo->current += 1;
    } else {
L
Liu Jicong 已提交
4233 4234 4235 4236
      qDebug("%s fetch msg rsp from vgId:%d, taskId:0x%" PRIx64 " numOfRows:%d, totalRows:%" PRIu64
             ", totalBytes:%" PRIu64,
             GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->taskId, pRes->info.rows, pLoadInfo->totalRows,
             pLoadInfo->totalSize);
4237 4238 4239 4240
    }

    return pExchangeInfo->pResult;
  }
4241 4242
}

L
Liu Jicong 已提交
4243
static int32_t prepareLoadRemoteData(SOperatorInfo* pOperator) {
4244
  if (OPTR_IS_OPENED(pOperator)) {
H
Haojun Liao 已提交
4245 4246 4247
    return TSDB_CODE_SUCCESS;
  }

L
Liu Jicong 已提交
4248
  SExchangeInfo* pExchangeInfo = pOperator->info;
H
Haojun Liao 已提交
4249 4250 4251 4252 4253 4254 4255 4256 4257
  if (pExchangeInfo->seqLoadData) {
    // do nothing for sequentially load data
  } else {
    int32_t code = prepareConcurrentlyLoad(pOperator);
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }
  }

4258
  OPTR_SET_OPENED(pOperator);
H
Haojun Liao 已提交
4259 4260 4261
  return TSDB_CODE_SUCCESS;
}

L
Liu Jicong 已提交
4262 4263 4264
static SSDataBlock* doLoadRemoteData(SOperatorInfo* pOperator, bool* newgroup) {
  SExchangeInfo* pExchangeInfo = pOperator->info;
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
4265

4266 4267
  pTaskInfo->code = pOperator->_openFn(pOperator);
  if (pTaskInfo->code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
4268 4269
    return NULL;
  }
4270

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

4274
  if (pOperator->status == OP_EXEC_DONE) {
L
Liu Jicong 已提交
4275 4276 4277
    qDebug("%s all %" PRIzu " source(s) are exhausted, total rows:%" PRIu64 " bytes:%" PRIu64 ", elapsed:%.2f ms",
           GET_TASKID(pTaskInfo), totalSources, pLoadInfo->totalRows, pLoadInfo->totalSize,
           pLoadInfo->totalElapsed / 1000.0);
4278 4279 4280 4281
    return NULL;
  }

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

4283 4284 4285
  if (pExchangeInfo->seqLoadData) {
    return seqLoadRemoteData(pOperator);
  } else {
H
Haojun Liao 已提交
4286
    return concurrentlyLoadRemoteData(pOperator);
4287
  }
H
Haojun Liao 已提交
4288

4289
#if 0
H
Haojun Liao 已提交
4290
  _error:
wafwerar's avatar
wafwerar 已提交
4291 4292
  taosMemoryFreeClear(pMsg);
  taosMemoryFreeClear(pMsgSendInfo);
H
Haojun Liao 已提交
4293 4294 4295

  terrno = pTaskInfo->code;
  return NULL;
4296
#endif
H
Haojun Liao 已提交
4297
}
4298

H
Haojun Liao 已提交
4299
static int32_t initDataSource(int32_t numOfSources, SExchangeInfo* pInfo) {
4300
  pInfo->pSourceDataInfo = taosArrayInit(numOfSources, sizeof(SSourceDataInfo));
H
Haojun Liao 已提交
4301 4302
  if (pInfo->pSourceDataInfo == NULL) {
    return TSDB_CODE_OUT_OF_MEMORY;
4303 4304
  }

L
Liu Jicong 已提交
4305
  for (int32_t i = 0; i < numOfSources; ++i) {
4306
    SSourceDataInfo dataInfo = {0};
H
Haojun Liao 已提交
4307
    dataInfo.status = EX_SOURCE_DATA_NOT_READY;
L
Liu Jicong 已提交
4308 4309
    dataInfo.pEx = pInfo;
    dataInfo.index = i;
4310

H
Haojun Liao 已提交
4311 4312 4313 4314 4315 4316 4317 4318 4319 4320
    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 已提交
4321
SOperatorInfo* createExchangeOperatorInfo(const SNodeList* pSources, SSDataBlock* pBlock, SExecTaskInfo* pTaskInfo) {
L
Liu Jicong 已提交
4322
  SExchangeInfo* pInfo = taosMemoryCalloc(1, sizeof(SExchangeInfo));
wafwerar's avatar
wafwerar 已提交
4323
  SOperatorInfo* pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
4324 4325

  if (pInfo == NULL || pOperator == NULL) {
wafwerar's avatar
wafwerar 已提交
4326 4327
    taosMemoryFreeClear(pInfo);
    taosMemoryFreeClear(pOperator);
H
Haojun Liao 已提交
4328 4329
    terrno = TSDB_CODE_QRY_OUT_OF_MEMORY;
    return NULL;
H
Haojun Liao 已提交
4330 4331
  }

H
Haojun Liao 已提交
4332
  size_t numOfSources = LIST_LENGTH(pSources);
H
Haojun Liao 已提交
4333
  pInfo->pSources = taosArrayInit(numOfSources, sizeof(SDownstreamSourceNode));
H
Haojun Liao 已提交
4334 4335 4336
  pInfo->pSourceDataInfo = taosArrayInit(numOfSources, sizeof(SSourceDataInfo));
  if (pInfo->pSourceDataInfo == NULL || pInfo->pSources == NULL) {
    goto _error;
H
Haojun Liao 已提交
4337 4338
  }

L
Liu Jicong 已提交
4339 4340
  for (int32_t i = 0; i < numOfSources; ++i) {
    SNodeListNode* pNode = nodesListGetNode((SNodeList*)pSources, i);
H
Haojun Liao 已提交
4341 4342
    taosArrayPush(pInfo->pSources, pNode);
  }
4343

H
Haojun Liao 已提交
4344 4345 4346
  int32_t code = initDataSource(numOfSources, pInfo);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
4347
  }
H
Haojun Liao 已提交
4348

4349
  pInfo->pResult     = pBlock;
4350 4351 4352
  pInfo->seqLoadData = true;

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

4354
  pOperator->name         = "ExchangeOperator";
X
Xiaoyu Wang 已提交
4355
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_EXCHANGE;
4356
  pOperator->blockingOptr = false;
4357 4358 4359 4360 4361 4362 4363
  pOperator->status       = OP_NOT_OPENED;
  pOperator->info         = pInfo;
  pOperator->numOfOutput  = pBlock->info.numOfCols;
  pOperator->pTaskInfo    = pTaskInfo;
  pOperator->_openFn      = prepareLoadRemoteData;  // assign a dummy function.
  pOperator->getNextFn    = doLoadRemoteData;
  pOperator->closeFn      = destroyExchangeOperatorInfo;
4364

S
Shengliang Guan 已提交
4365
#if 1
L
Liu Jicong 已提交
4366
  {  // todo refactor
H
Haojun Liao 已提交
4367 4368 4369
    SRpcInit rpcInit;
    memset(&rpcInit, 0, sizeof(rpcInit));
    rpcInit.localPort = 0;
H
Haojun Liao 已提交
4370
    rpcInit.label = "EX";
H
Haojun Liao 已提交
4371
    rpcInit.numOfThreads = 1;
S
Shengliang Guan 已提交
4372
    rpcInit.cfp = qProcessFetchRsp;
S
Shengliang Guan 已提交
4373
    rpcInit.sessions = tsMaxConnections;
H
Haojun Liao 已提交
4374
    rpcInit.connType = TAOS_CONN_CLIENT;
L
Liu Jicong 已提交
4375
    rpcInit.user = (char*)"root";
S
Shengliang Guan 已提交
4376
    rpcInit.idleTime = tsShellActivityTimer * 1000;
H
Haojun Liao 已提交
4377
    rpcInit.ckey = "key";
S
Shengliang Guan 已提交
4378
    rpcInit.spi = 1;
L
Liu Jicong 已提交
4379
    rpcInit.secret = (char*)"dcc5bed04851fec854c035b2e40263b6";
H
Haojun Liao 已提交
4380 4381 4382

    pInfo->pTransporter = rpcOpen(&rpcInit);
    if (pInfo->pTransporter == NULL) {
L
Liu Jicong 已提交
4383
      return NULL;  // todo
H
Haojun Liao 已提交
4384 4385
    }
  }
S
Shengliang 已提交
4386
#endif
4387

4388
  return pOperator;
H
Haojun Liao 已提交
4389

L
Liu Jicong 已提交
4390
_error:
H
Haojun Liao 已提交
4391
  if (pInfo != NULL) {
H
Haojun Liao 已提交
4392
    destroyExchangeOperatorInfo(pInfo, numOfSources);
H
Haojun Liao 已提交
4393 4394
  }

wafwerar's avatar
wafwerar 已提交
4395 4396
  taosMemoryFreeClear(pInfo);
  taosMemoryFreeClear(pOperator);
H
Haojun Liao 已提交
4397
  pTaskInfo->code = TSDB_CODE_OUT_OF_MEMORY;
H
Haojun Liao 已提交
4398
  return NULL;
4399 4400
}

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

4404
static void destroySortedMergeOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
4405
  SSortedMergeOperatorInfo* pInfo = (SSortedMergeOperatorInfo*)param;
H
Haojun Liao 已提交
4406
  taosArrayDestroy(pInfo->pSortInfo);
4407 4408 4409
  taosArrayDestroy(pInfo->groupInfo);

  if (pInfo->pSortHandle != NULL) {
H
Haojun Liao 已提交
4410
    tsortDestroySortHandle(pInfo->pSortHandle);
4411 4412
  }

H
Haojun Liao 已提交
4413
  blockDataDestroy(pInfo->binfo.pRes);
H
Haojun Liao 已提交
4414
  cleanupAggSup(&pInfo->aggSup);
4415
}
H
Haojun Liao 已提交
4416

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

X
Xiaoyu Wang 已提交
4420
  *dst = *src;
4421

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

L
Liu Jicong 已提交
4426 4427 4428 4429
  //  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 已提交
4430
}
4431

4432 4433
static SExprInfo* exprArrayDup(SArray* pExprList) {
  size_t numOfOutput = taosArrayGetSize(pExprList);
4434

wafwerar's avatar
wafwerar 已提交
4435
  SExprInfo* p = taosMemoryCalloc(numOfOutput, sizeof(SExprInfo));
4436 4437
  for (int32_t i = 0; i < numOfOutput; ++i) {
    SExprInfo* pExpr = taosArrayGetP(pExprList, i);
H
Haojun Liao 已提交
4438
    assignExprInfo(&p[i], pExpr);
4439 4440
  }

H
Haojun Liao 已提交
4441 4442
  return p;
}
4443

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

H
Haojun Liao 已提交
4449
    bool isNull = tsortIsNullVal(pTupleHandle, i);
H
Haojun Liao 已提交
4450 4451 4452
    if (isNull) {
      colDataAppend(pColInfo, pBlock->info.rows, NULL, true);
    } else {
H
Haojun Liao 已提交
4453
      char* pData = tsortGetValue(pTupleHandle, i);
H
Haojun Liao 已提交
4454 4455
      colDataAppend(pColInfo, pBlock->info.rows, pData, false);
    }
4456 4457
  }

4458 4459
  pBlock->info.rows += 1;
}
4460

H
Haojun Liao 已提交
4461
SSDataBlock* getSortedBlockData(SSortHandle* pHandle, SSDataBlock* pDataBlock, int32_t capacity) {
4462
  blockDataCleanup(pDataBlock);
D
dapan1121 已提交
4463
  blockDataEnsureCapacity(pDataBlock, capacity);
4464

wmmhello's avatar
wmmhello 已提交
4465 4466
  blockDataEnsureCapacity(pDataBlock, capacity);

L
Liu Jicong 已提交
4467
  while (1) {
H
Haojun Liao 已提交
4468
    STupleHandle* pTupleHandle = tsortNextTuple(pHandle);
4469 4470 4471
    if (pTupleHandle == NULL) {
      break;
    }
4472

4473 4474 4475
    appendOneRowToDataBlock(pDataBlock, pTupleHandle);
    if (pDataBlock->info.rows >= capacity) {
      return pDataBlock;
H
Haojun Liao 已提交
4476 4477
    }
  }
4478

L
Liu Jicong 已提交
4479
  return (pDataBlock->info.rows > 0) ? pDataBlock : NULL;
4480
}
4481

4482
SSDataBlock* loadNextDataBlock(void* param) {
L
Liu Jicong 已提交
4483 4484
  SOperatorInfo* pOperator = (SOperatorInfo*)param;
  bool           newgroup = false;
H
Haojun Liao 已提交
4485
  return pOperator->getNextFn(pOperator, &newgroup);
4486 4487
}

L
Liu Jicong 已提交
4488
static bool needToMerge(SSDataBlock* pBlock, SArray* groupInfo, char** buf, int32_t rowIndex) {
4489 4490 4491 4492
  size_t size = taosArrayGetSize(groupInfo);
  if (size == 0) {
    return true;
  }
4493

4494 4495
  for (int32_t i = 0; i < size; ++i) {
    int32_t* index = taosArrayGet(groupInfo, i);
4496

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

4500 4501 4502
    if ((isNull && buf[i] != NULL) || (!isNull && buf[i] == NULL)) {
      return false;
    }
4503

4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516
    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;
      }
4517 4518 4519
    }
  }

4520
  return 0;
4521 4522
}

L
Liu Jicong 已提交
4523 4524 4525
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
4526
    pCtx[j].startRow = rowIndex;
4527 4528
  }

4529 4530
  for (int32_t j = 0; j < numOfExpr; ++j) {
    int32_t functionId = pCtx[j].functionId;
L
Liu Jicong 已提交
4531 4532 4533 4534 4535 4536 4537 4538 4539
    //    pCtx[j].fpSet->addInput(&pCtx[j]);

    //    if (functionId < 0) {
    //      SUdfInfo* pUdfInfo = taosArrayGet(pInfo->udfInfo, -1 * functionId - 1);
    //      doInvokeUdf(pUdfInfo, &pCtx[j], 0, TSDB_UDF_FUNC_MERGE);
    //    } else {
    //      assert(!TSDB_FUNC_IS_SCALAR(functionId));
    //      aAggs[functionId].mergeFunc(&pCtx[j]);
    //    }
4540
  }
4541
}
4542

L
Liu Jicong 已提交
4543 4544
static void doFinalizeResultImpl(SqlFunctionCtx* pCtx, int32_t numOfExpr) {
  for (int32_t j = 0; j < numOfExpr; ++j) {
4545 4546 4547 4548
    int32_t functionId = pCtx[j].functionId;
    //    if (functionId == FUNC_TAG_DUMMY || functionId == FUNC_TS_DUMMY) {
    //      continue;
    //    }
4549

4550 4551 4552 4553
    //    if (functionId < 0) {
    //      SUdfInfo* pUdfInfo = taosArrayGet(pInfo->udfInfo, -1 * functionId - 1);
    //      doInvokeUdf(pUdfInfo, &pCtx[j], 0, TSDB_UDF_FUNC_FINALIZE);
    //    } else {
H
Haojun Liao 已提交
4554
    pCtx[j].fpSet.finalize(&pCtx[j]);
4555 4556
  }
}
4557

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

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

4565 4566 4567
    char* data = colDataGetData(pColInfo, rowIndex);
    memcpy(rowColData[i], data, colDataGetLength(pColInfo, rowIndex));
  }
4568

4569 4570
  return true;
}
4571

4572 4573
static void doMergeImpl(SOperatorInfo* pOperator, int32_t numOfExpr, SSDataBlock* pBlock) {
  SSortedMergeOperatorInfo* pInfo = pOperator->info;
4574

4575
  SqlFunctionCtx* pCtx = pInfo->binfo.pCtx;
L
Liu Jicong 已提交
4576
  for (int32_t i = 0; i < pBlock->info.numOfCols; ++i) {
4577 4578
    pCtx[i].size = 1;
  }
4579

L
Liu Jicong 已提交
4580
  for (int32_t i = 0; i < pBlock->info.rows; ++i) {
4581 4582 4583 4584 4585 4586 4587 4588 4589
    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 已提交
4590
        int32_t numOfRows = getNumOfResult(pInfo->binfo.pCtx, pOperator->numOfOutput, NULL);
4591
        //        setTagValueForMultipleRows(pCtx, pOperator->numOfOutput, numOfRows);
4592

4593
        // TODO check for available buffer;
H
Haojun Liao 已提交
4594

4595 4596 4597 4598 4599
        // next group info data
        pInfo->binfo.pRes->info.rows += numOfRows;
        for (int32_t j = 0; j < numOfExpr; ++j) {
          if (pCtx[j].functionId < 0) {
            continue;
4600
          }
4601

H
Haojun Liao 已提交
4602
          pCtx[j].fpSet.process(&pCtx[j]);
4603
        }
4604 4605 4606

        doMergeResultImpl(pInfo, pCtx, numOfExpr, i);
        pInfo->hasGroupVal = saveCurrentTuple(pInfo->groupVal, pInfo->groupInfo, pBlock, i);
H
Haojun Liao 已提交
4607
      }
4608 4609 4610 4611
    }
  }
}

4612 4613
static SSDataBlock* doMerge(SOperatorInfo* pOperator) {
  SSortedMergeOperatorInfo* pInfo = pOperator->info;
L
Liu Jicong 已提交
4614
  SSortHandle*              pHandle = pInfo->pSortHandle;
4615

4616
  SSDataBlock* pDataBlock = createOneDataBlock(pInfo->binfo.pRes, false);
4617 4618
  blockDataEnsureCapacity(pDataBlock, pInfo->binfo.capacity);

L
Liu Jicong 已提交
4619
  while (1) {
4620
    blockDataCleanup(pDataBlock);
4621
    while (1) {
H
Haojun Liao 已提交
4622
      STupleHandle* pTupleHandle = tsortNextTuple(pHandle);
4623 4624
      if (pTupleHandle == NULL) {
        break;
4625
      }
4626

4627 4628 4629 4630 4631
      // build datablock for merge for one group
      appendOneRowToDataBlock(pDataBlock, pTupleHandle);
      if (pDataBlock->info.rows >= pInfo->binfo.capacity) {
        break;
      }
4632
    }
4633

4634 4635 4636
    if (pDataBlock->info.rows == 0) {
      break;
    }
4637

4638
    setInputDataBlock(pOperator, pInfo->binfo.pCtx, pDataBlock, TSDB_ORDER_ASC);
L
Liu Jicong 已提交
4639 4640
    //  updateOutputBuf(&pInfo->binfo, &pAggInfo->bufCapacity, pBlock->info.rows * pAggInfo->resultRowFactor,
    //  pOperator->pRuntimeEnv, true);
4641 4642 4643
    doMergeImpl(pOperator, pOperator->numOfOutput, pDataBlock);
    // flush to tuple store, and after all data have been handled, return to upstream node or sink node
  }
4644

4645
  doFinalizeResultImpl(pInfo->binfo.pCtx, pOperator->numOfOutput);
H
Haojun Liao 已提交
4646
  int32_t numOfRows = getNumOfResult(pInfo->binfo.pCtx, pOperator->numOfOutput, NULL);
4647
  //        setTagValueForMultipleRows(pCtx, pOperator->numOfOutput, numOfRows);
4648

4649
  // TODO check for available buffer;
4650

4651 4652
  // next group info data
  pInfo->binfo.pRes->info.rows += numOfRows;
L
Liu Jicong 已提交
4653
  return (pInfo->binfo.pRes->info.rows > 0) ? pInfo->binfo.pRes : NULL;
4654
}
4655

L
Liu Jicong 已提交
4656
static SSDataBlock* doSortedMerge(SOperatorInfo* pOperator, bool* newgroup) {
4657 4658
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
4659 4660
  }

L
Liu Jicong 已提交
4661
  SExecTaskInfo*            pTaskInfo = pOperator->pTaskInfo;
4662
  SSortedMergeOperatorInfo* pInfo = pOperator->info;
H
Haojun Liao 已提交
4663
  if (pOperator->status == OP_RES_TO_RETURN) {
H
Haojun Liao 已提交
4664
    return getSortedBlockData(pInfo->pSortHandle, pInfo->binfo.pRes, pInfo->binfo.capacity);
4665 4666
  }

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

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

L
Liu Jicong 已提交
4673
  for (int32_t i = 0; i < pOperator->numOfDownstream; ++i) {
wmmhello's avatar
wmmhello 已提交
4674
    SSortSource* ps = taosMemoryCalloc(1, sizeof(SSortSource));
H
Haojun Liao 已提交
4675
    ps->param = pOperator->pDownstream[i];
H
Haojun Liao 已提交
4676
    tsortAddSource(pInfo->pSortHandle, ps);
4677 4678
  }

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

H
Haojun Liao 已提交
4684
  pOperator->status = OP_RES_TO_RETURN;
4685
  return doMerge(pOperator);
4686
}
4687

L
Liu Jicong 已提交
4688 4689
static int32_t initGroupCol(SExprInfo* pExprInfo, int32_t numOfCols, SArray* pGroupInfo,
                            SSortedMergeOperatorInfo* pInfo) {
4690 4691
  if (pGroupInfo == NULL || taosArrayGetSize(pGroupInfo) == 0) {
    return 0;
H
Haojun Liao 已提交
4692 4693
  }

4694 4695 4696 4697 4698 4699 4700 4701
  int32_t len = 0;
  SArray* plist = taosArrayInit(3, sizeof(SColumn));
  pInfo->groupInfo = taosArrayInit(3, sizeof(int32_t));

  if (plist == NULL || pInfo->groupInfo == NULL) {
    return TSDB_CODE_OUT_OF_MEMORY;
  }

L
Liu Jicong 已提交
4702 4703
  size_t numOfGroupCol = taosArrayGetSize(pInfo->groupInfo);
  for (int32_t i = 0; i < numOfGroupCol; ++i) {
4704
    SColumn* pCol = taosArrayGet(pGroupInfo, i);
L
Liu Jicong 已提交
4705
    for (int32_t j = 0; j < numOfCols; ++j) {
H
Haojun Liao 已提交
4706
      SExprInfo* pe = &pExprInfo[j];
4707
      if (pe->base.resSchema.slotId == pCol->colId) {
4708 4709
        taosArrayPush(plist, pCol);
        taosArrayPush(pInfo->groupInfo, &j);
H
Haojun Liao 已提交
4710
        len += pCol->bytes;
4711 4712
        break;
      }
H
Haojun Liao 已提交
4713 4714 4715
    }
  }

4716
  ASSERT(taosArrayGetSize(pGroupInfo) == taosArrayGetSize(plist));
H
Haojun Liao 已提交
4717

wafwerar's avatar
wafwerar 已提交
4718
  pInfo->groupVal = taosMemoryCalloc(1, (POINTER_BYTES * numOfGroupCol + len));
4719 4720 4721 4722
  if (pInfo->groupVal == NULL) {
    taosArrayDestroy(plist);
    return TSDB_CODE_OUT_OF_MEMORY;
  }
H
Haojun Liao 已提交
4723

4724
  int32_t offset = 0;
L
Liu Jicong 已提交
4725 4726
  char*   start = (char*)(pInfo->groupVal + (POINTER_BYTES * numOfGroupCol));
  for (int32_t i = 0; i < numOfGroupCol; ++i) {
4727 4728
    pInfo->groupVal[i] = start + offset;
    SColumn* pCol = taosArrayGet(plist, i);
H
Haojun Liao 已提交
4729
    offset += pCol->bytes;
4730
  }
H
Haojun Liao 已提交
4731

4732
  taosArrayDestroy(plist);
H
Haojun Liao 已提交
4733

4734 4735
  return TSDB_CODE_SUCCESS;
}
H
Haojun Liao 已提交
4736

L
Liu Jicong 已提交
4737 4738 4739
SOperatorInfo* createSortedMergeOperatorInfo(SOperatorInfo** downstream, int32_t numOfDownstream, SExprInfo* pExprInfo,
                                             int32_t num, SArray* pSortInfo, SArray* pGroupInfo,
                                             SExecTaskInfo* pTaskInfo) {
wafwerar's avatar
wafwerar 已提交
4740
  SSortedMergeOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SSortedMergeOperatorInfo));
L
Liu Jicong 已提交
4741
  SOperatorInfo*            pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
4742
  if (pInfo == NULL || pOperator == NULL) {
4743
    goto _error;
4744
  }
H
Haojun Liao 已提交
4745

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

4749 4750 4751
  if (pInfo->binfo.pCtx == NULL || pInfo->binfo.pRes == NULL) {
    goto _error;
  }
H
Haojun Liao 已提交
4752

4753 4754
  size_t keyBufSize = sizeof(int64_t) + sizeof(int64_t) + POINTER_BYTES;
  int32_t code = doInitAggInfoSup(&pInfo->aggSup, pInfo->binfo.pCtx, num, keyBufSize, pTaskInfo->id.str);
4755 4756 4757
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
H
Haojun Liao 已提交
4758

H
Haojun Liao 已提交
4759
  setFunctionResultOutput(&pInfo->binfo, &pInfo->aggSup, MAIN_SCAN, pTaskInfo);
H
Haojun Liao 已提交
4760
  code = initGroupCol(pExprInfo, num, pGroupInfo, pInfo);
4761 4762 4763
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
H
Haojun Liao 已提交
4764

L
Liu Jicong 已提交
4765 4766 4767 4768 4769
  //  pInfo->resultRowFactor = (int32_t)(getRowNumForMultioutput(pRuntimeEnv->pQueryAttr,
  //      pRuntimeEnv->pQueryAttr->topBotQuery, false));
  pInfo->sortBufSize = 1024 * 16;  // 1MB
  pInfo->bufPageSize = 1024;
  pInfo->pSortInfo = pSortInfo;
H
Haojun Liao 已提交
4770

4771
  pInfo->binfo.capacity = blockDataGetCapacityInRow(pInfo->binfo.pRes, pInfo->bufPageSize);
H
Haojun Liao 已提交
4772

L
Liu Jicong 已提交
4773
  pOperator->name = "SortedMerge";
X
Xiaoyu Wang 已提交
4774
  // pOperator->operatorType = OP_SortedMerge;
4775
  pOperator->blockingOptr = true;
L
Liu Jicong 已提交
4776 4777 4778 4779
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
  pOperator->numOfOutput = num;
  pOperator->pExpr = pExprInfo;
H
Haojun Liao 已提交
4780

L
Liu Jicong 已提交
4781 4782 4783
  pOperator->pTaskInfo = pTaskInfo;
  pOperator->getNextFn = doSortedMerge;
  pOperator->closeFn = destroySortedMergeOperatorInfo;
H
Haojun Liao 已提交
4784

4785 4786 4787
  code = appendDownstream(pOperator, downstream, numOfDownstream);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
4788
  }
H
Haojun Liao 已提交
4789

4790
  return pOperator;
H
Haojun Liao 已提交
4791

L
Liu Jicong 已提交
4792
_error:
4793
  if (pInfo != NULL) {
H
Haojun Liao 已提交
4794
    destroySortedMergeOperatorInfo(pInfo, num);
H
Haojun Liao 已提交
4795 4796
  }

wafwerar's avatar
wafwerar 已提交
4797 4798
  taosMemoryFreeClear(pInfo);
  taosMemoryFreeClear(pOperator);
4799 4800
  terrno = TSDB_CODE_QRY_OUT_OF_MEMORY;
  return NULL;
H
Haojun Liao 已提交
4801 4802
}

L
Liu Jicong 已提交
4803
static SSDataBlock* doSort(SOperatorInfo* pOperator, bool* newgroup) {
4804 4805 4806 4807
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

L
Liu Jicong 已提交
4808
  SExecTaskInfo*     pTaskInfo = pOperator->pTaskInfo;
H
Haojun Liao 已提交
4809 4810
  SSortOperatorInfo* pInfo = pOperator->info;

H
Haojun Liao 已提交
4811
  if (pOperator->status == OP_RES_TO_RETURN) {
H
Haojun Liao 已提交
4812
    return getSortedBlockData(pInfo->pSortHandle, pInfo->pDataBlock, pInfo->numOfRowsInRes);
H
Haojun Liao 已提交
4813 4814
  }

4815
  int32_t numOfBufPage = pInfo->sortBufSize / pInfo->bufPageSize;
4816
  pInfo->pSortHandle = tsortCreateSortHandle(pInfo->pSortInfo, pInfo->inputSlotMap, SORT_SINGLESOURCE_SORT, pInfo->bufPageSize, numOfBufPage,
H
Haojun Liao 已提交
4817
                                             pInfo->pDataBlock, pTaskInfo->id.str);
4818

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

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

H
Haojun Liao 已提交
4825
  int32_t code = tsortOpen(pInfo->pSortHandle);
4826
  taosMemoryFreeClear(ps);
4827
  if (code != TSDB_CODE_SUCCESS) {
4828
    longjmp(pTaskInfo->env, terrno);
4829
  }
4830

H
Haojun Liao 已提交
4831
  pOperator->status = OP_RES_TO_RETURN;
H
Haojun Liao 已提交
4832
  return getSortedBlockData(pInfo->pSortHandle, pInfo->pDataBlock, pInfo->numOfRowsInRes);
4833 4834
}

4835
SOperatorInfo* createSortOperatorInfo(SOperatorInfo* downstream, SSDataBlock* pResBlock, SArray* pSortInfo, SArray* pIndexMap, SExecTaskInfo* pTaskInfo) {
H
Haojun Liao 已提交
4836
  SSortOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SSortOperatorInfo));
L
Liu Jicong 已提交
4837
  SOperatorInfo*     pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
4838 4839 4840
  int32_t rowSize = pResBlock->info.rowSize;

  if (pInfo == NULL || pOperator == NULL || rowSize > 100 * 1024 * 1024) {
wafwerar's avatar
wafwerar 已提交
4841 4842
    taosMemoryFreeClear(pInfo);
    taosMemoryFreeClear(pOperator);
H
Haojun Liao 已提交
4843 4844 4845
    terrno = TSDB_CODE_QRY_OUT_OF_MEMORY;
    return NULL;
  }
4846

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

wmmhello's avatar
wmmhello 已提交
4849
  pInfo->sortBufSize = pInfo->bufPageSize * 16;  // TODO dynamic set the available sort buffer
L
Liu Jicong 已提交
4850 4851 4852
  pInfo->numOfRowsInRes = 1024;
  pInfo->pDataBlock = pResBlock;
  pInfo->pSortInfo = pSortInfo;
4853
  pInfo->inputSlotMap = pIndexMap;
H
Haojun Liao 已提交
4854

H
Haojun Liao 已提交
4855
  pOperator->name         = "SortOperator";
L
Liu Jicong 已提交
4856 4857
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_SORT;
  pOperator->blockingOptr = true;
H
Haojun Liao 已提交
4858 4859
  pOperator->status       = OP_NOT_OPENED;
  pOperator->info         = pInfo;
4860

H
Haojun Liao 已提交
4861 4862 4863
  pOperator->pTaskInfo    = pTaskInfo;
  pOperator->getNextFn    = doSort;
  pOperator->closeFn      = destroyOrderOperatorInfo;
4864

4865
  int32_t code = appendDownstream(pOperator, &downstream, 1);
4866
  return pOperator;
H
Haojun Liao 已提交
4867 4868 4869 4870 4871 4872

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

L
Liu Jicong 已提交
4875
static int32_t getTableScanOrder(STableScanInfo* pTableScanInfo) { return pTableScanInfo->order; }
4876 4877

// this is a blocking operator
L
Liu Jicong 已提交
4878
static int32_t doOpenAggregateOptr(SOperatorInfo* pOperator) {
H
Haojun Liao 已提交
4879 4880
  if (OPTR_IS_OPENED(pOperator)) {
    return TSDB_CODE_SUCCESS;
4881 4882 4883
  }

  SAggOperatorInfo* pAggInfo = pOperator->info;
H
Haojun Liao 已提交
4884
  SOptrBasicInfo*   pInfo = &pAggInfo->binfo;
4885

H
Haojun Liao 已提交
4886
  int32_t        order = TSDB_ORDER_ASC;
H
Haojun Liao 已提交
4887
  SOperatorInfo* downstream = pOperator->pDownstream[0];
4888

H
Haojun Liao 已提交
4889 4890
  bool newgroup = true;
  while (1) {
H
Haojun Liao 已提交
4891
    publishOperatorProfEvent(downstream, QUERY_PROF_BEFORE_OPERATOR_EXEC);
H
Haojun Liao 已提交
4892
    SSDataBlock* pBlock = downstream->getNextFn(downstream, &newgroup);
H
Haojun Liao 已提交
4893
    publishOperatorProfEvent(downstream, QUERY_PROF_AFTER_OPERATOR_EXEC);
4894 4895 4896 4897

    if (pBlock == NULL) {
      break;
    }
H
Haojun Liao 已提交
4898 4899 4900
    //    if (pAggInfo->current != NULL) {
    //      setTagValue(pOperator, pAggInfo->current->pTable, pInfo->pCtx, pOperator->numOfOutput);
    //    }
4901 4902 4903

    // the pDataBlock are always the same one, no need to call this again
    setInputDataBlock(pOperator, pInfo->pCtx, pBlock, order);
H
Haojun Liao 已提交
4904
    doAggregateImpl(pOperator, 0, pInfo->pCtx);
4905

4906
#if 0   // test for encode/decode result info
4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917
    if(pOperator->encodeResultRow){
      char *result = NULL;
      int32_t length = 0;
      SAggSupporter   *pSup = &pAggInfo->aggSup;
      pOperator->encodeResultRow(pOperator, pSup, pInfo, &result, &length);
      taosHashClear(pSup->pResultRowHashTable);
      pInfo->resultRowInfo.size = 0;
      pOperator->decodeResultRow(pOperator, pSup, pInfo, result, length);
      if(result){
        taosMemoryFree(result);
      }
4918
    }
4919
#endif
4920 4921
  }

4922
  finalizeQueryResult(pInfo->pCtx, pOperator->numOfOutput);
H
Haojun Liao 已提交
4923 4924 4925 4926 4927

  OPTR_SET_OPENED(pOperator);
  return TSDB_CODE_SUCCESS;
}

L
Liu Jicong 已提交
4928 4929
static SSDataBlock* getAggregateResult(SOperatorInfo* pOperator, bool* newgroup) {
  SAggOperatorInfo* pAggInfo = pOperator->info;
H
Haojun Liao 已提交
4930 4931 4932 4933 4934 4935
  SOptrBasicInfo*   pInfo = &pAggInfo->binfo;

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

L
Liu Jicong 已提交
4936
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
H
Haojun Liao 已提交
4937 4938 4939 4940 4941
  pTaskInfo->code = pOperator->_openFn(pOperator);
  if (pTaskInfo->code != TSDB_CODE_SUCCESS) {
    return NULL;
  }

H
Haojun Liao 已提交
4942
  getNumOfResult(pInfo->pCtx, pOperator->numOfOutput, pInfo->pRes);
H
Haojun Liao 已提交
4943
  doSetOperatorCompleted(pOperator);
4944

L
Liu Jicong 已提交
4945
  return (blockDataGetNumOfRows(pInfo->pRes) != 0) ? pInfo->pRes : NULL;
4946 4947
}

4948
void aggEncodeResultRow(SOperatorInfo* pOperator, SAggSupporter *pSup, SOptrBasicInfo *pInfo, char **result, int32_t *length) {
wmmhello's avatar
wmmhello 已提交
4949
  int32_t size = taosHashGetSize(pSup->pResultRowHashTable);
4950
  size_t  keyLen = sizeof(uint64_t) * 2;  // estimate the key length
wmmhello's avatar
wmmhello 已提交
4951
  int32_t totalSize = sizeof(int32_t) + size * (sizeof(int32_t) + keyLen + sizeof(int32_t) + pSup->resultRowSize);
wafwerar's avatar
wafwerar 已提交
4952
  *result = taosMemoryCalloc(1, totalSize);
L
Liu Jicong 已提交
4953
  if (*result == NULL) {
4954
    longjmp(pOperator->pTaskInfo->env, TSDB_CODE_OUT_OF_MEMORY);
wmmhello's avatar
wmmhello 已提交
4955 4956 4957
  }
  *(int32_t*)(*result) = size;
  int32_t offset = sizeof(int32_t);
4958 4959 4960 4961 4962 4963 4964 4965

  // prepare memory
  SResultRowPosition* pos = &pInfo->resultRowInfo.pPosition[pInfo->resultRowInfo.curPos];
  void* pPage = getBufPage(pSup->pResultBuf, pos->pageId);
  SResultRow* pRow = (SResultRow*)((char*)pPage + pos->offset);
  setBufPageDirty(pPage, true);
  releaseBufPage(pSup->pResultBuf, pPage);

L
Liu Jicong 已提交
4966
  void*   pIter = taosHashIterate(pSup->pResultRowHashTable, NULL);
wmmhello's avatar
wmmhello 已提交
4967
  while (pIter) {
L
Liu Jicong 已提交
4968
    void*        key = taosHashGetKey(pIter, &keyLen);
4969
    SResultRowPosition* p1 = (SResultRowPosition*)pIter;
4970

4971 4972
    pPage = (SFilePage*) getBufPage(pSup->pResultBuf, p1->pageId);
    pRow = (SResultRow*)((char*)pPage + p1->offset);
4973 4974
    setBufPageDirty(pPage, true);
    releaseBufPage(pSup->pResultBuf, pPage);
wmmhello's avatar
wmmhello 已提交
4975 4976 4977

    // recalculate the result size
    int32_t realTotalSize = offset + sizeof(int32_t) + keyLen + sizeof(int32_t) + pSup->resultRowSize;
L
Liu Jicong 已提交
4978 4979 4980
    if (realTotalSize > totalSize) {
      char* tmp = taosMemoryRealloc(*result, realTotalSize);
      if (tmp == NULL) {
wmmhello's avatar
wmmhello 已提交
4981
        terrno = TSDB_CODE_OUT_OF_MEMORY;
wafwerar's avatar
wafwerar 已提交
4982
        taosMemoryFree(*result);
wmmhello's avatar
wmmhello 已提交
4983
        *result = NULL;
4984
        longjmp(pOperator->pTaskInfo->env, TSDB_CODE_OUT_OF_MEMORY);
L
Liu Jicong 已提交
4985
      } else {
wmmhello's avatar
wmmhello 已提交
4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997
        *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);
4998
    memcpy(*result + offset, pRow, pSup->resultRowSize);
wmmhello's avatar
wmmhello 已提交
4999 5000 5001 5002 5003
    offset += pSup->resultRowSize;

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

L
Liu Jicong 已提交
5004
  if (length) {
wmmhello's avatar
wmmhello 已提交
5005 5006 5007 5008 5009
    *length = offset;
  }
  return;
}

5010
bool aggDecodeResultRow(SOperatorInfo* pOperator, SAggSupporter *pSup, SOptrBasicInfo *pInfo, char* result, int32_t length) {
L
Liu Jicong 已提交
5011
  if (!result || length <= 0) {
wmmhello's avatar
wmmhello 已提交
5012 5013 5014 5015 5016 5017 5018
    return false;
  }

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

  int32_t offset = sizeof(int32_t);
L
Liu Jicong 已提交
5019
  while (count-- > 0 && length > offset) {
wmmhello's avatar
wmmhello 已提交
5020 5021 5022
    int32_t keyLen = *(int32_t*)(result + offset);
    offset += sizeof(int32_t);

L
Liu Jicong 已提交
5023 5024 5025
    uint64_t    tableGroupId = *(uint64_t*)(result + offset);
    SResultRow* resultRow = getNewResultRow_rv(pSup->pResultBuf, tableGroupId, pSup->resultRowSize);
    if (!resultRow) {
5026
      longjmp(pOperator->pTaskInfo->env, TSDB_CODE_TSC_INVALID_INPUT);
wmmhello's avatar
wmmhello 已提交
5027 5028
    }
    // add a new result set for a new group
5029 5030
    SResultRowPosition pos = {.pageId = resultRow->pageId, .offset = resultRow->offset};
    taosHashPut(pSup->pResultRowHashTable, result + offset, keyLen, &pos, sizeof(SResultRowPosition));
wmmhello's avatar
wmmhello 已提交
5031 5032 5033

    offset += keyLen;
    int32_t valueLen = *(int32_t*)(result + offset);
L
Liu Jicong 已提交
5034
    if (valueLen != pSup->resultRowSize) {
5035
      longjmp(pOperator->pTaskInfo->env, TSDB_CODE_TSC_INVALID_INPUT);
wmmhello's avatar
wmmhello 已提交
5036 5037 5038 5039 5040 5041 5042 5043 5044 5045
    }
    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);
5046 5047 5048
    prepareResultListBuffer(&pInfo->resultRowInfo, pOperator->pTaskInfo->env);
    pInfo->resultRowInfo.curPos = pInfo->resultRowInfo.size;
    pInfo->resultRowInfo.pPosition[pInfo->resultRowInfo.size++] = (SResultRowPosition) {.pageId = resultRow->pageId, .offset = resultRow->offset};
wmmhello's avatar
wmmhello 已提交
5049 5050
  }

L
Liu Jicong 已提交
5051
  if (offset != length) {
5052
    longjmp(pOperator->pTaskInfo->env, TSDB_CODE_TSC_INVALID_INPUT);
wmmhello's avatar
wmmhello 已提交
5053 5054 5055 5056
  }
  return true;
}

L
Liu Jicong 已提交
5057
static SSDataBlock* doMultiTableAggregate(SOperatorInfo* pOperator, bool* newgroup) {
5058 5059 5060 5061 5062
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

  SAggOperatorInfo* pAggInfo = pOperator->info;
L
Liu Jicong 已提交
5063 5064
  SOptrBasicInfo*   pInfo = &pAggInfo->binfo;
  SExecTaskInfo*    pTaskInfo = pOperator->pTaskInfo;
5065 5066

  if (pOperator->status == OP_RES_TO_RETURN) {
5067
    toSDatablock(pInfo->pRes, pAggInfo->binfo.capacity, &pAggInfo->groupResInfo, pOperator->pExpr, pAggInfo->pResultBuf, pAggInfo->binfo.rowCellInfoOffset);
H
Haojun Liao 已提交
5068
    if (pInfo->pRes->info.rows == 0 || !hasRemainDataInCurrentGroup(&pAggInfo->groupResInfo)) {
5069 5070 5071 5072 5073 5074
      pOperator->status = OP_EXEC_DONE;
    }

    return pInfo->pRes;
  }

5075
  // table scan order
L
Liu Jicong 已提交
5076
  int32_t        order = TSDB_ORDER_ASC;
H
Haojun Liao 已提交
5077
  SOperatorInfo* downstream = pOperator->pDownstream[0];
5078

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

    if (pBlock == NULL) {
      break;
    }

L
Liu Jicong 已提交
5088 5089 5090 5091 5092
    //    setTagValue(pOperator, pRuntimeEnv->current->pTable, pInfo->pCtx, pOperator->numOfOutput);
    //    if (downstream->operatorType == OP_TableScan) {
    //      STableScanInfo* pScanInfo = downstream->info;
    //      order = getTableScanOrder(pScanInfo);
    //    }
5093 5094 5095 5096 5097

    // the pDataBlock are always the same one, no need to call this again
    setInputDataBlock(pOperator, pInfo->pCtx, pBlock, order);

    TSKEY key = 0;
5098
    if (order == TSDB_ORDER_ASC) {
5099 5100 5101 5102 5103 5104
      key = pBlock->info.window.ekey;
      TSKEY_MAX_ADD(key, 1);
    } else {
      key = pBlock->info.window.skey;
      TSKEY_MIN_SUB(key, -1);
    }
L
Liu Jicong 已提交
5105 5106 5107

    setExecutionContext(pOperator->numOfOutput, pAggInfo->current->groupIndex, key, pTaskInfo, pAggInfo->current,
                        pAggInfo);
H
Haojun Liao 已提交
5108
    doAggregateImpl(pOperator, 0, pInfo->pCtx);
5109 5110 5111 5112
  }

  pOperator->status = OP_RES_TO_RETURN;
  closeAllResultRows(&pInfo->resultRowInfo);
5113
  updateNumOfRowsInResultRows(pInfo->pCtx, pOperator->numOfOutput, &pInfo->resultRowInfo, pInfo->rowCellInfoOffset);
5114

H
Haojun Liao 已提交
5115
  initGroupResInfo(&pAggInfo->groupResInfo, &pInfo->resultRowInfo);
5116
  toSDatablock(pInfo->pRes, pAggInfo->binfo.capacity, &pAggInfo->groupResInfo, pOperator->pExpr, pAggInfo->pResultBuf, pAggInfo->binfo.rowCellInfoOffset);
5117

H
Haojun Liao 已提交
5118
  if (pInfo->pRes->info.rows == 0 || !hasRemainDataInCurrentGroup(&pAggInfo->groupResInfo)) {
5119 5120 5121 5122 5123 5124
    doSetOperatorCompleted(pOperator);
  }

  return pInfo->pRes;
}

L
Liu Jicong 已提交
5125
static SSDataBlock* doProjectOperation(SOperatorInfo* pOperator, bool* newgroup) {
5126
  SProjectOperatorInfo* pProjectInfo = pOperator->info;
L
Liu Jicong 已提交
5127
  SOptrBasicInfo*       pInfo = &pProjectInfo->binfo;
5128 5129

  SSDataBlock* pRes = pInfo->pRes;
5130
  blockDataCleanup(pRes);
5131
  
H
Haojun Liao 已提交
5132
#if 0
5133 5134 5135 5136 5137 5138
  if (pProjectInfo->existDataBlock) {  // TODO refactor
    SSDataBlock* pBlock = pProjectInfo->existDataBlock;
    pProjectInfo->existDataBlock = NULL;
    *newgroup = true;

    // todo dynamic set tags
L
Liu Jicong 已提交
5139 5140 5141
    //    if (pTableQueryInfo != NULL) {
    //      setTagValue(pOperator, pTableQueryInfo->pTable, pInfo->pCtx, pOperator->numOfOutput);
    //    }
5142 5143

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

H
Haojun Liao 已提交
5146
    blockDataEnsureCapacity(pInfo->pRes, pBlock->info.rows);
5147
    projectApplyFunctions(pOperator->pExpr, pInfo->pRes, pBlock, pInfo->pCtx, pOperator->numOfOutput);
L
Liu Jicong 已提交
5148
    if (pRes->info.rows >= pProjectInfo->binfo.capacity * 0.8) {
5149 5150 5151 5152 5153
      copyTsColoum(pRes, pInfo->pCtx, pOperator->numOfOutput);
      resetResultRowEntryResult(pInfo->pCtx, pOperator->numOfOutput);
      return pRes;
    }
  }
H
Haojun Liao 已提交
5154
#endif
5155

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

L
Liu Jicong 已提交
5158
  while (1) {
5159 5160
    bool prevVal = *newgroup;

H
Haojun Liao 已提交
5161
    // The downstream exec may change the value of the newgroup, so use a local variable instead.
H
Haojun Liao 已提交
5162 5163 5164
    publishOperatorProfEvent(downstream, QUERY_PROF_BEFORE_OPERATOR_EXEC);
    SSDataBlock* pBlock = downstream->getNextFn(downstream, newgroup);
    publishOperatorProfEvent(downstream, QUERY_PROF_AFTER_OPERATOR_EXEC);
5165 5166 5167

    if (pBlock == NULL) {
      *newgroup = prevVal;
5168
      setTaskStatus(pOperator->pTaskInfo, TASK_COMPLETED);
5169 5170 5171 5172 5173 5174 5175 5176
      break;
    }

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

    // todo dynamic set tags
H
Haojun Liao 已提交
5183 5184 5185 5186
    //    STableQueryInfo* pTableQueryInfo = pRuntimeEnv->current;
    //    if (pTableQueryInfo != NULL) {
    //      setTagValue(pOperator, pTableQueryInfo->pTable, pInfo->pCtx, pOperator->numOfOutput);
    //    }
5187 5188

    // the pDataBlock are always the same one, no need to call this again
H
Haojun Liao 已提交
5189
    setInputDataBlock(pOperator, pInfo->pCtx, pBlock, TSDB_ORDER_ASC);
5190 5191
    blockDataEnsureCapacity(pInfo->pRes, pInfo->pRes->info.rows + pBlock->info.rows);

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

H
Haojun Liao 已提交
5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225
    if (pProjectInfo->curSOffset > 0) {
      if (pProjectInfo->groupId == 0) {  // it is the first group
        pProjectInfo->groupId = pBlock->info.groupId;
        blockDataCleanup(pInfo->pRes);
        continue;
      } else if (pProjectInfo->groupId != pBlock->info.groupId) {
        pProjectInfo->curSOffset -= 1;

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

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

    if (pProjectInfo->groupId != 0 && pProjectInfo->groupId != pBlock->info.groupId) {
      pProjectInfo->curGroupOutput += 1;
      if ((pProjectInfo->slimit.limit > 0) && (pProjectInfo->slimit.limit <= pProjectInfo->curGroupOutput)) {
        pOperator->status = OP_EXEC_DONE;
        return NULL;
      }

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

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

H
Haojun Liao 已提交
5226
    // todo extract method
H
Haojun Liao 已提交
5227 5228 5229 5230 5231 5232 5233 5234 5235
    if (pProjectInfo->curOffset < pInfo->pRes->info.rows && pProjectInfo->curOffset > 0) {
      blockDataTrimFirstNRows(pInfo->pRes, pProjectInfo->curOffset);
      pProjectInfo->curOffset = 0;
    } else if (pProjectInfo->curOffset >= pInfo->pRes->info.rows) {
      pProjectInfo->curOffset -= pInfo->pRes->info.rows;
      blockDataCleanup(pInfo->pRes);
      continue;
    }

5236
    if (pRes->info.rows >= pOperator->resultInfo.threshold) {
5237 5238 5239
      break;
    }
  }
H
Haojun Liao 已提交
5240
  
H
Haojun Liao 已提交
5241
  if (pProjectInfo->limit.limit > 0 && pProjectInfo->curOutput + pInfo->pRes->info.rows >= pProjectInfo->limit.limit) {
H
Haojun Liao 已提交
5242 5243 5244 5245
    pInfo->pRes->info.rows = (int32_t)(pProjectInfo->limit.limit - pProjectInfo->curOutput);
  }

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

L
Liu Jicong 已提交
5247 5248
  //  copyTsColoum(pRes, pInfo->pCtx, pOperator->numOfOutput);
  return (pInfo->pRes->info.rows > 0) ? pInfo->pRes : NULL;
5249 5250
}

L
Liu Jicong 已提交
5251
static int32_t doOpenIntervalAgg(SOperatorInfo* pOperator) {
5252 5253
  if (OPTR_IS_OPENED(pOperator)) {
    return TSDB_CODE_SUCCESS;
5254 5255
  }

H
Haojun Liao 已提交
5256
  STableIntervalOperatorInfo* pInfo = pOperator->info;
5257

5258
  int32_t order = TSDB_ORDER_ASC;
5259 5260
  //  STimeWindow win = {0};
  bool newgroup = false;
H
Haojun Liao 已提交
5261
  SOperatorInfo* downstream = pOperator->pDownstream[0];
5262

5263
  while (1) {
H
Haojun Liao 已提交
5264
    publishOperatorProfEvent(downstream, QUERY_PROF_BEFORE_OPERATOR_EXEC);
5265
    SSDataBlock* pBlock = downstream->getNextFn(downstream, &newgroup);
H
Haojun Liao 已提交
5266
    publishOperatorProfEvent(downstream, QUERY_PROF_AFTER_OPERATOR_EXEC);
5267 5268 5269 5270 5271

    if (pBlock == NULL) {
      break;
    }

5272
    //    setTagValue(pOperator, pRuntimeEnv->current->pTable, pInfo->pCtx, pOperator->numOfOutput);
5273
    // the pDataBlock are always the same one, no need to call this again
5274
    setInputDataBlock(pOperator, pInfo->binfo.pCtx, pBlock, order);
H
Haojun Liao 已提交
5275
    hashIntervalAgg(pOperator, &pInfo->binfo.resultRowInfo, pBlock, 0);
5276

5277
#if 0   // test for encode/decode result info
5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288
    if(pOperator->encodeResultRow){
      char *result = NULL;
      int32_t length = 0;
      SAggSupporter   *pSup = &pInfo->aggSup;
      pOperator->encodeResultRow(pOperator, pSup, &pInfo->binfo, &result, &length);
      taosHashClear(pSup->pResultRowHashTable);
      pInfo->binfo.resultRowInfo.size = 0;
      pOperator->decodeResultRow(pOperator, pSup, &pInfo->binfo, result, length);
      if(result){
        taosMemoryFree(result);
      }
5289
    }
5290
#endif
5291 5292
  }

H
Haojun Liao 已提交
5293
  closeAllResultRows(&pInfo->binfo.resultRowInfo);
L
Liu Jicong 已提交
5294 5295
  finalizeMultiTupleQueryResult(pInfo->binfo.pCtx, pOperator->numOfOutput, pInfo->aggSup.pResultBuf,
                                &pInfo->binfo.resultRowInfo, pInfo->binfo.rowCellInfoOffset);
5296

H
Haojun Liao 已提交
5297
  initGroupResInfo(&pInfo->groupResInfo, &pInfo->binfo.resultRowInfo);
5298 5299 5300 5301
  OPTR_SET_OPENED(pOperator);
  return TSDB_CODE_SUCCESS;
}

L
Liu Jicong 已提交
5302
static SSDataBlock* doBuildIntervalResult(SOperatorInfo* pOperator, bool* newgroup) {
5303
  STableIntervalOperatorInfo* pInfo = pOperator->info;
L
Liu Jicong 已提交
5304
  SExecTaskInfo*              pTaskInfo = pOperator->pTaskInfo;
5305 5306 5307 5308 5309

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

5310 5311 5312 5313
  if (pInfo->execModel == OPTR_EXEC_MODEL_STREAM) {
    return pOperator->getStreamResFn(pOperator, newgroup);
  }

5314 5315 5316 5317 5318 5319
  pTaskInfo->code = pOperator->_openFn(pOperator);
  if (pTaskInfo->code != TSDB_CODE_SUCCESS) {
    return NULL;
  }

  blockDataEnsureCapacity(pInfo->binfo.pRes, pInfo->binfo.capacity);
5320
  toSDatablock(pInfo->binfo.pRes, pInfo->binfo.capacity, &pInfo->groupResInfo, pOperator->pExpr, pInfo->aggSup.pResultBuf, pInfo->binfo.rowCellInfoOffset);
5321

H
Haojun Liao 已提交
5322
  if (pInfo->binfo.pRes->info.rows == 0 || !hasRemainDataInCurrentGroup(&pInfo->groupResInfo)) {
5323 5324 5325
    doSetOperatorCompleted(pOperator);
  }

L
Liu Jicong 已提交
5326
  return pInfo->binfo.pRes->info.rows == 0 ? NULL : pInfo->binfo.pRes;
5327 5328
}

5329
static SSDataBlock* doStreamIntervalAgg(SOperatorInfo *pOperator, bool* newgroup) {
5330 5331 5332 5333 5334 5335 5336 5337
  STableIntervalOperatorInfo* pInfo = pOperator->info;
  int32_t order = TSDB_ORDER_ASC;

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

  if (pOperator->status == OP_RES_TO_RETURN) {
5338
    toSDatablock(pInfo->binfo.pRes, pInfo->binfo.capacity, &pInfo->groupResInfo, pOperator->pExpr, pInfo->aggSup.pResultBuf, pInfo->binfo.rowCellInfoOffset);
5339 5340 5341
    if (pInfo->binfo.pRes->info.rows == 0 || !hasRemainDataInCurrentGroup(&pInfo->groupResInfo)) {
      pOperator->status = OP_EXEC_DONE;
    }
5342
    return pInfo->binfo.pRes->info.rows == 0 ? NULL : pInfo->binfo.pRes;
5343 5344 5345
  }

  //  STimeWindow win = {0};
5346
  *newgroup = false;
5347 5348 5349 5350 5351 5352
  SOperatorInfo* downstream = pOperator->pDownstream[0];

  SArray* pUpdated = NULL;

  while (1) {
    publishOperatorProfEvent(downstream, QUERY_PROF_BEFORE_OPERATOR_EXEC);
5353
    SSDataBlock* pBlock = downstream->getNextFn(downstream, newgroup);
5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370
    publishOperatorProfEvent(downstream, QUERY_PROF_AFTER_OPERATOR_EXEC);

    if (pBlock == NULL) {
      break;
    }

    // The timewindows that overlaps the timestamps of the input pBlock need to be recalculated and return to the caller.
    // Note that all the time window are not close till now.

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

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

H
Haojun Liao 已提交
5371
  initMultiResInfoFromArrayList(&pInfo->groupResInfo, pUpdated);
5372
  blockDataEnsureCapacity(pInfo->binfo.pRes, pInfo->binfo.capacity);
5373
  toSDatablock(pInfo->binfo.pRes, pInfo->binfo.capacity, &pInfo->groupResInfo, pOperator->pExpr, pInfo->aggSup.pResultBuf, pInfo->binfo.rowCellInfoOffset);
5374 5375 5376 5377 5378 5379 5380 5381

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

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

static SSDataBlock* doAllIntervalAgg(SOperatorInfo *pOperator, bool* newgroup) {
5382 5383 5384 5385
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

5386
  STimeSliceOperatorInfo* pSliceInfo = pOperator->info;
5387
  if (pOperator->status == OP_RES_TO_RETURN) {
L
Liu Jicong 已提交
5388
    //    toSDatablock(&pRuntimeEnv->groupResInfo, pRuntimeEnv, pIntervalInfo->pRes);
5389
    if (pSliceInfo->binfo.pRes->info.rows == 0 || !hasRemainDataInCurrentGroup(&pSliceInfo->groupResInfo)) {
5390 5391 5392
      doSetOperatorCompleted(pOperator);
    }

5393
    return pSliceInfo->binfo.pRes;
5394 5395
  }

5396 5397
  int32_t     order = TSDB_ORDER_ASC;
//  STimeWindow win = pQueryAttr->window;
H
Haojun Liao 已提交
5398
  SOperatorInfo* downstream = pOperator->pDownstream[0];
5399

L
Liu Jicong 已提交
5400
  while (1) {
H
Haojun Liao 已提交
5401
    publishOperatorProfEvent(downstream, QUERY_PROF_BEFORE_OPERATOR_EXEC);
H
Haojun Liao 已提交
5402
    SSDataBlock* pBlock = downstream->getNextFn(downstream, newgroup);
H
Haojun Liao 已提交
5403
    publishOperatorProfEvent(downstream, QUERY_PROF_AFTER_OPERATOR_EXEC);
5404 5405 5406 5407
    if (pBlock == NULL) {
      break;
    }

L
Liu Jicong 已提交
5408
    //    setTagValue(pOperator, pRuntimeEnv->current->pTable, pIntervalInfo->pCtx, pOperator->numOfOutput);
5409
    // the pDataBlock are always the same one, no need to call this again
5410 5411
    setInputDataBlock(pOperator, pSliceInfo->binfo.pCtx, pBlock, order);
    hashAllIntervalAgg(pOperator, &pSliceInfo->binfo.resultRowInfo, pBlock, 0);
5412 5413 5414 5415
  }

  // restore the value
  pOperator->status = OP_RES_TO_RETURN;
5416
  closeAllResultRows(&pSliceInfo->binfo.resultRowInfo);
5417
  setTaskStatus(pOperator->pTaskInfo, TASK_COMPLETED);
5418
  finalizeQueryResult(pSliceInfo->binfo.pCtx, pOperator->numOfOutput);
5419

5420 5421
  initGroupResInfo(&pSliceInfo->groupResInfo, &pSliceInfo->binfo.resultRowInfo);
  //  toSDatablock(&pRuntimeEnv->groupResInfo, pRuntimeEnv, pSliceInfo->pRes);
5422

5423
  if (pSliceInfo->binfo.pRes->info.rows == 0 || !hasRemainDataInCurrentGroup(&pSliceInfo->groupResInfo)) {
5424 5425 5426
    pOperator->status = OP_EXEC_DONE;
  }

5427
  return pSliceInfo->binfo.pRes->info.rows == 0 ? NULL : pSliceInfo->binfo.pRes;
5428 5429
}

L
Liu Jicong 已提交
5430
static SSDataBlock* doSTableIntervalAgg(SOperatorInfo* pOperator, bool* newgroup) {
5431 5432 5433 5434 5435
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

  STableIntervalOperatorInfo* pIntervalInfo = pOperator->info;
L
Liu Jicong 已提交
5436
  STaskRuntimeEnv*            pRuntimeEnv = pOperator->pRuntimeEnv;
5437 5438 5439 5440

  if (pOperator->status == OP_RES_TO_RETURN) {
    int64_t st = taosGetTimestampUs();

L
Liu Jicong 已提交
5441
    //    copyToSDataBlock(NULL, 3000, pIntervalInfo->pRes, pIntervalInfo->rowCellInfoOffset);
H
Haojun Liao 已提交
5442
    if (pIntervalInfo->binfo.pRes->info.rows == 0 || !hasRemainData(&pRuntimeEnv->groupResInfo)) {
5443 5444
      doSetOperatorCompleted(pOperator);
    }
H
Haojun Liao 已提交
5445
    return pIntervalInfo->binfo.pRes;
5446 5447
  }

H
Haojun Liao 已提交
5448
  STaskAttr* pQueryAttr = pRuntimeEnv->pQueryAttr;
H
Haojun Liao 已提交
5449
  SOperatorInfo* downstream = pOperator->pDownstream[0];
5450

L
Liu Jicong 已提交
5451
  while (1) {
H
Haojun Liao 已提交
5452
    publishOperatorProfEvent(downstream, QUERY_PROF_BEFORE_OPERATOR_EXEC);
H
Haojun Liao 已提交
5453
    SSDataBlock* pBlock = downstream->getNextFn(downstream, newgroup);
H
Haojun Liao 已提交
5454
    publishOperatorProfEvent(downstream, QUERY_PROF_AFTER_OPERATOR_EXEC);
5455 5456 5457 5458 5459 5460 5461 5462

    if (pBlock == NULL) {
      break;
    }

    // the pDataBlock are always the same one, no need to call this again
    STableQueryInfo* pTableQueryInfo = pRuntimeEnv->current;

L
Liu Jicong 已提交
5463
    //    setTagValue(pOperator, pTableQueryInfo->pTable, pIntervalInfo->pCtx, pOperator->numOfOutput);
5464
    setInputDataBlock(pOperator, pIntervalInfo->binfo.pCtx, pBlock, TSDB_ORDER_ASC);
5465 5466 5467 5468 5469 5470 5471
    setIntervalQueryRange(pRuntimeEnv, pBlock->info.window.skey);

    hashIntervalAgg(pOperator, &pTableQueryInfo->resInfo, pBlock, pTableQueryInfo->groupIndex);
  }

  pOperator->status = OP_RES_TO_RETURN;
  doCloseAllTimeWindow(pRuntimeEnv);
5472
  setTaskStatus(pOperator->pTaskInfo, TASK_COMPLETED);
5473

L
Liu Jicong 已提交
5474
  //  copyToSDataBlock(pRuntimeEnv, 3000, pIntervalInfo->pRes, pIntervalInfo->rowCellInfoOffset);
H
Haojun Liao 已提交
5475
  if (pIntervalInfo->binfo.pRes->info.rows == 0 || !hasRemainData(&pRuntimeEnv->groupResInfo)) {
5476 5477 5478
    pOperator->status = OP_EXEC_DONE;
  }

H
Haojun Liao 已提交
5479
  return pIntervalInfo->binfo.pRes;
5480 5481
}

L
Liu Jicong 已提交
5482
static SSDataBlock* doAllSTableIntervalAgg(SOperatorInfo* pOperator, bool* newgroup) {
5483 5484 5485 5486 5487
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

  STableIntervalOperatorInfo* pIntervalInfo = pOperator->info;
L
Liu Jicong 已提交
5488
  STaskRuntimeEnv*            pRuntimeEnv = pOperator->pRuntimeEnv;
5489 5490

  if (pOperator->status == OP_RES_TO_RETURN) {
L
Liu Jicong 已提交
5491
    //    copyToSDataBlock(pRuntimeEnv, 3000, pIntervalInfo->pRes, pIntervalInfo->rowCellInfoOffset);
H
Haojun Liao 已提交
5492
    if (pIntervalInfo->binfo.pRes->info.rows == 0 || !hasRemainData(&pRuntimeEnv->groupResInfo)) {
5493 5494 5495
      pOperator->status = OP_EXEC_DONE;
    }

H
Haojun Liao 已提交
5496
    return pIntervalInfo->binfo.pRes;
5497 5498
  }

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

L
Liu Jicong 已提交
5501
  while (1) {
H
Haojun Liao 已提交
5502
    publishOperatorProfEvent(downstream, QUERY_PROF_BEFORE_OPERATOR_EXEC);
H
Haojun Liao 已提交
5503
    SSDataBlock* pBlock = downstream->getNextFn(downstream, newgroup);
H
Haojun Liao 已提交
5504
    publishOperatorProfEvent(downstream, QUERY_PROF_AFTER_OPERATOR_EXEC);
5505 5506 5507 5508 5509 5510 5511 5512

    if (pBlock == NULL) {
      break;
    }

    // the pDataBlock are always the same one, no need to call this again
    STableQueryInfo* pTableQueryInfo = pRuntimeEnv->current;

L
Liu Jicong 已提交
5513
    //    setTagValue(pOperator, pTableQueryInfo->pTable, pIntervalInfo->pCtx, pOperator->numOfOutput);
H
Haojun Liao 已提交
5514
//    setInputDataBlock(pOperator, pIntervalInfo->binfo.pCtx, pBlock, pQueryAttr->order.order);
5515 5516 5517 5518 5519 5520
    setIntervalQueryRange(pRuntimeEnv, pBlock->info.window.skey);

    hashAllIntervalAgg(pOperator, &pTableQueryInfo->resInfo, pBlock, pTableQueryInfo->groupIndex);
  }

  pOperator->status = OP_RES_TO_RETURN;
H
Haojun Liao 已提交
5521
//  pQueryAttr->order.order = order;  // TODO : restore the order
5522
  doCloseAllTimeWindow(pRuntimeEnv);
5523
  setTaskStatus(pOperator->pTaskInfo, TASK_COMPLETED);
5524 5525

  int64_t st = taosGetTimestampUs();
L
Liu Jicong 已提交
5526
  //  copyToSDataBlock(pRuntimeEnv, 3000, pIntervalInfo->pRes, pIntervalInfo->rowCellInfoOffset);
H
Haojun Liao 已提交
5527
  if (pIntervalInfo->binfo.pRes->info.rows == 0 || !hasRemainData(&pRuntimeEnv->groupResInfo)) {
5528 5529 5530
    pOperator->status = OP_EXEC_DONE;
  }

H
Haojun Liao 已提交
5531
  return pIntervalInfo->binfo.pRes;
5532 5533
}

5534 5535
static void doStateWindowAggImpl(SOperatorInfo* pOperator, SStateWindowOperatorInfo* pInfo, SSDataBlock* pBlock) {
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
5536 5537
  SOptrBasicInfo* pBInfo = &pInfo->binfo;

5538 5539
  SColumnInfoData* pStateColInfoData = taosArrayGet(pBlock->pDataBlock, pInfo->colIndex);
  int64_t gid = pBlock->info.groupId;
5540

5541 5542 5543 5544 5545 5546 5547 5548
  bool    masterScan = true;
  int32_t numOfOutput = pOperator->numOfOutput;

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

  SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, 0);
  TSKEY*           tsList = (TSKEY*)pColInfoData->pData;
5549

5550 5551 5552 5553 5554
  SWindowRowsSup* pRowSup = &pInfo->winSup;
  pRowSup->numOfRows = 0;
  
  for (int32_t j = 0; j < pBlock->info.rows; ++j) {
    if (colDataIsNull(pStateColInfoData, pBlock->info.rows, j, pBlock->pBlockAgg)) {
5555 5556
      continue;
    }
5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569

    char* val = colDataGetData(pStateColInfoData, j);

    if (!pInfo->hasKey) {
      memcpy(pInfo->stateKey.pData, val, bytes);
      pInfo->hasKey = true;

      doKeepNewWindowStartInfo(pRowSup, tsList, j);
      doKeepTuple(pRowSup, tsList[j]);
    } else if (memcmp(pInfo->stateKey.pData, val, bytes) == 0) {
      doKeepTuple(pRowSup, tsList[j]);
      if (j == 0 && pRowSup->startRowIndex != 0) {
        pRowSup->startRowIndex = 0;
5570
      }
5571
    } else {  // a new state window started
5572
      SResultRow* pResult = NULL;
5573 5574 5575 5576 5577 5578 5579

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

      pRowSup->win.ekey = pRowSup->win.skey;
      int32_t ret = setResultOutputBufByKey_rv(&pInfo->binfo.resultRowInfo, pBlock->info.uid, &window, masterScan,
                                               &pResult, gid, pInfo->binfo.pCtx, numOfOutput, pInfo->binfo.rowCellInfoOffset, &pInfo->aggSup, pTaskInfo);
5580
      if (ret != TSDB_CODE_SUCCESS) {  // null data, too many state code
5581
        longjmp(pTaskInfo->env, TSDB_CODE_QRY_APP_ERROR);
5582 5583
      }

5584 5585 5586 5587 5588 5589
      updateTimeWindowInfo(&pInfo->timeWindowData, &window, false);
      doApplyFunctions(pInfo->binfo.pCtx, &window, &pInfo->timeWindowData, pRowSup->startRowIndex, pRowSup->numOfRows, NULL, pBlock->info.rows, numOfOutput, TSDB_ORDER_ASC);

      // here we start a new session window
      doKeepNewWindowStartInfo(pRowSup, tsList, j);
      doKeepTuple(pRowSup, tsList[j]);
5590 5591 5592 5593
    }
  }

  SResultRow* pResult = NULL;
5594 5595 5596
  pRowSup->win.ekey = tsList[pBlock->info.rows - 1];
  int32_t ret = setResultOutputBufByKey_rv(&pInfo->binfo.resultRowInfo, pBlock->info.uid, &pRowSup->win, masterScan, &pResult,
                                           gid, pInfo->binfo.pCtx, numOfOutput, pInfo->binfo.rowCellInfoOffset, &pInfo->aggSup, pTaskInfo);
5597
  if (ret != TSDB_CODE_SUCCESS) {  // null data, too many state code
5598
    longjmp(pTaskInfo->env, TSDB_CODE_QRY_APP_ERROR);
5599 5600
  }

5601 5602
  updateTimeWindowInfo(&pInfo->timeWindowData, &pRowSup->win, false);
  doApplyFunctions(pInfo->binfo.pCtx, &pRowSup->win, &pInfo->timeWindowData, pRowSup->startRowIndex, pRowSup->numOfRows, NULL, pBlock->info.rows, numOfOutput, TSDB_ORDER_ASC);
5603 5604
}

L
Liu Jicong 已提交
5605
static SSDataBlock* doStateWindowAgg(SOperatorInfo* pOperator, bool* newgroup) {
5606 5607 5608 5609
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

5610
  SStateWindowOperatorInfo* pInfo = pOperator->info;
H
Haojun Liao 已提交
5611
  SExecTaskInfo*  pTaskInfo = pOperator->pTaskInfo;
5612
  SOptrBasicInfo* pBInfo    = &pInfo->binfo;
5613 5614

  if (pOperator->status == OP_RES_TO_RETURN) {
5615
    toSDatablock(pBInfo->pRes, pBInfo->capacity, &pInfo->groupResInfo, pOperator->pExpr, pInfo->aggSup.pResultBuf, pBInfo->rowCellInfoOffset);
5616 5617 5618 5619
    if (pBInfo->pRes->info.rows == 0 || !hasRemainDataInCurrentGroup(&pInfo->groupResInfo)) {
      doSetOperatorCompleted(pOperator);
      return NULL;
    }
5620 5621 5622 5623

    return pBInfo->pRes;
  }

H
Haojun Liao 已提交
5624 5625 5626
  int32_t        order = TSDB_ORDER_ASC;
  STimeWindow    win = pTaskInfo->window;

H
Haojun Liao 已提交
5627
  SOperatorInfo* downstream = pOperator->pDownstream[0];
5628
  while (1) {
H
Haojun Liao 已提交
5629
    publishOperatorProfEvent(downstream, QUERY_PROF_BEFORE_OPERATOR_EXEC);
H
Haojun Liao 已提交
5630
    SSDataBlock* pBlock = downstream->getNextFn(downstream, newgroup);
H
Haojun Liao 已提交
5631
    publishOperatorProfEvent(downstream, QUERY_PROF_AFTER_OPERATOR_EXEC);
5632 5633 5634 5635

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

5637 5638
    setInputDataBlock(pOperator, pBInfo->pCtx, pBlock, order);
    doStateWindowAggImpl(pOperator, pInfo, pBlock);
5639 5640 5641 5642
  }

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

5645 5646
  initGroupResInfo(&pInfo->groupResInfo, &pBInfo->resultRowInfo);
  blockDataEnsureCapacity(pBInfo->pRes, pBInfo->capacity);
5647
  toSDatablock(pBInfo->pRes, pBInfo->capacity, &pInfo->groupResInfo, pOperator->pExpr, pInfo->aggSup.pResultBuf, pBInfo->rowCellInfoOffset);
5648 5649 5650
  if (pBInfo->pRes->info.rows == 0 || !hasRemainDataInCurrentGroup(&pInfo->groupResInfo)) {
    doSetOperatorCompleted(pOperator);
  }
5651

L
Liu Jicong 已提交
5652
  return pBInfo->pRes->info.rows == 0 ? NULL : pBInfo->pRes;
5653 5654
}

L
Liu Jicong 已提交
5655
static SSDataBlock* doSessionWindowAgg(SOperatorInfo* pOperator, bool* newgroup) {
5656 5657 5658 5659
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

5660
  SSessionAggOperatorInfo* pInfo = pOperator->info;
L
Liu Jicong 已提交
5661
  SOptrBasicInfo*          pBInfo = &pInfo->binfo;
5662 5663

  if (pOperator->status == OP_RES_TO_RETURN) {
5664
    toSDatablock(pBInfo->pRes, pBInfo->capacity, &pInfo->groupResInfo, pOperator->pExpr, pInfo->aggSup.pResultBuf, pBInfo->rowCellInfoOffset);
5665 5666 5667
    if (pBInfo->pRes->info.rows == 0 || !hasRemainDataInCurrentGroup(&pInfo->groupResInfo)) {
      doSetOperatorCompleted(pOperator);
      return NULL;
5668 5669 5670 5671 5672
    }

    return pBInfo->pRes;
  }

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

L
Liu Jicong 已提交
5676
  while (1) {
H
Haojun Liao 已提交
5677
    publishOperatorProfEvent(downstream, QUERY_PROF_BEFORE_OPERATOR_EXEC);
H
Haojun Liao 已提交
5678
    SSDataBlock* pBlock = downstream->getNextFn(downstream, newgroup);
H
Haojun Liao 已提交
5679
    publishOperatorProfEvent(downstream, QUERY_PROF_AFTER_OPERATOR_EXEC);
5680 5681 5682 5683 5684
    if (pBlock == NULL) {
      break;
    }

    // the pDataBlock are always the same one, no need to call this again
H
Haojun Liao 已提交
5685
    setInputDataBlock(pOperator, pBInfo->pCtx, pBlock, order);
5686
    doSessionWindowAggImpl(pOperator, pInfo, pBlock);
5687 5688 5689 5690 5691
  }

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

5694 5695
  initGroupResInfo(&pInfo->groupResInfo, &pBInfo->resultRowInfo);
  blockDataEnsureCapacity(pBInfo->pRes, pBInfo->capacity);
5696
  toSDatablock(pBInfo->pRes, pBInfo->capacity, &pInfo->groupResInfo, pOperator->pExpr, pInfo->aggSup.pResultBuf, pBInfo->rowCellInfoOffset);
5697 5698
  if (pBInfo->pRes->info.rows == 0 || !hasRemainDataInCurrentGroup(&pInfo->groupResInfo)) {
    doSetOperatorCompleted(pOperator);
5699 5700
  }

L
Liu Jicong 已提交
5701
  return pBInfo->pRes->info.rows == 0 ? NULL : pBInfo->pRes;
5702 5703
}

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

L
Liu Jicong 已提交
5708 5709
  int64_t ekey = Q_STATUS_EQUAL(pTaskInfo->status, TASK_COMPLETED) ? pTaskInfo->window.ekey
                                                                   : pInfo->existNewGroupBlock->info.window.ekey;
5710 5711
  taosResetFillInfo(pInfo->pFillInfo, getFillInfoStart(pInfo->pFillInfo));

5712
  taosFillSetStartInfo(pInfo->pFillInfo, pInfo->existNewGroupBlock->info.rows, ekey);
5713 5714
  taosFillSetInputDataBlock(pInfo->pFillInfo, pInfo->existNewGroupBlock);

H
Haojun Liao 已提交
5715
  doFillTimeIntervalGapsInResults(pInfo->pFillInfo, pInfo->pRes, pResultInfo->capacity, pInfo->p);
5716 5717 5718 5719
  pInfo->existNewGroupBlock = NULL;
  *newgroup = true;
}

L
Liu Jicong 已提交
5720 5721
static void doHandleRemainBlockFromNewGroup(SFillOperatorInfo* pInfo, SResultInfo* pResultInfo, bool* newgroup,
                                            SExecTaskInfo* pTaskInfo) {
5722 5723
  if (taosFillHasMoreResults(pInfo->pFillInfo)) {
    *newgroup = false;
H
Haojun Liao 已提交
5724 5725
    doFillTimeIntervalGapsInResults(pInfo->pFillInfo, pInfo->pRes, (int32_t)pResultInfo->capacity, pInfo->p);
    if (pInfo->pRes->info.rows > pResultInfo->threshold || (!pInfo->multigroupResult)) {
5726 5727 5728 5729 5730 5731
      return;
    }
  }

  // handle the cached new group data block
  if (pInfo->existNewGroupBlock) {
5732
    doHandleRemainBlockForNewGroupImpl(pInfo, pResultInfo, newgroup, pTaskInfo);
5733 5734 5735
  }
}

L
Liu Jicong 已提交
5736 5737 5738
static SSDataBlock* doFill(SOperatorInfo* pOperator, bool* newgroup) {
  SFillOperatorInfo* pInfo = pOperator->info;
  SExecTaskInfo*     pTaskInfo = pOperator->pTaskInfo;
5739

H
Haojun Liao 已提交
5740 5741
  SResultInfo* pResultInfo = &pOperator->resultInfo;
  blockDataCleanup(pInfo->pRes);
5742 5743 5744 5745
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

5746
  doHandleRemainBlockFromNewGroup(pInfo, pResultInfo, newgroup, pTaskInfo);
H
Haojun Liao 已提交
5747 5748 5749
  if (pInfo->pRes->info.rows > pResultInfo->threshold || (!pInfo->multigroupResult && pInfo->pRes->info.rows > 0)) {
    return pInfo->pRes;
  }
5750

H
Haojun Liao 已提交
5751
  SOperatorInfo* pDownstream = pOperator->pDownstream[0];
L
Liu Jicong 已提交
5752
  while (1) {
H
Haojun Liao 已提交
5753 5754 5755
    publishOperatorProfEvent(pDownstream, QUERY_PROF_BEFORE_OPERATOR_EXEC);
    SSDataBlock* pBlock = pDownstream->getNextFn(pDownstream, newgroup);
    publishOperatorProfEvent(pDownstream, QUERY_PROF_AFTER_OPERATOR_EXEC);
5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766

    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
5767
      taosFillSetStartInfo(pInfo->pFillInfo, 0, pTaskInfo->window.ekey);
5768 5769 5770 5771 5772 5773 5774
    } else {
      if (pBlock == NULL) {
        if (pInfo->totalInputRows == 0) {
          pOperator->status = OP_EXEC_DONE;
          return NULL;
        }

5775
        taosFillSetStartInfo(pInfo->pFillInfo, 0, pTaskInfo->window.ekey);
5776 5777 5778 5779 5780 5781 5782
      } else {
        pInfo->totalInputRows += pBlock->info.rows;
        taosFillSetStartInfo(pInfo->pFillInfo, pBlock->info.rows, pBlock->info.window.ekey);
        taosFillSetInputDataBlock(pInfo->pFillInfo, pBlock);
      }
    }

H
Haojun Liao 已提交
5783
    doFillTimeIntervalGapsInResults(pInfo->pFillInfo, pInfo->pRes, pInfo->capacity, pInfo->p);
5784 5785 5786 5787 5788

    // 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 已提交
5789
      if (pInfo->pRes->info.rows > pResultInfo->threshold || pBlock == NULL || (!pInfo->multigroupResult)) {
5790 5791 5792
        return pInfo->pRes;
      }

5793
      doHandleRemainBlockFromNewGroup(pInfo, pResultInfo, newgroup, pTaskInfo);
H
Haojun Liao 已提交
5794
      if (pInfo->pRes->info.rows > pOperator->resultInfo.threshold || pBlock == NULL) {
5795 5796 5797 5798
        return pInfo->pRes;
      }
    } else if (pInfo->existNewGroupBlock) {  // try next group
      assert(pBlock != NULL);
5799
      doHandleRemainBlockForNewGroupImpl(pInfo, pResultInfo, newgroup, pTaskInfo);
H
Haojun Liao 已提交
5800
      if (pInfo->pRes->info.rows > pResultInfo->threshold) {
5801 5802 5803 5804 5805 5806 5807 5808 5809
        return pInfo->pRes;
      }
    } else {
      return NULL;
    }
  }
}

// todo set the attribute of query scan count
H
Haojun Liao 已提交
5810
static int32_t getNumOfScanTimes(STaskAttr* pQueryAttr) {
L
Liu Jicong 已提交
5811
  for (int32_t i = 0; i < pQueryAttr->numOfOutput; ++i) {
5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825
    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 已提交
5826 5827
  if (pOperator->closeFn != NULL) {
    pOperator->closeFn(pOperator->info, pOperator->numOfOutput);
5828 5829
  }

H
Haojun Liao 已提交
5830
  if (pOperator->pDownstream != NULL) {
L
Liu Jicong 已提交
5831
    for (int32_t i = 0; i < pOperator->numOfDownstream; ++i) {
H
Haojun Liao 已提交
5832
      destroyOperatorInfo(pOperator->pDownstream[i]);
5833 5834
    }

wafwerar's avatar
wafwerar 已提交
5835
    taosMemoryFreeClear(pOperator->pDownstream);
H
Haojun Liao 已提交
5836
    pOperator->numOfDownstream = 0;
5837 5838
  }

wafwerar's avatar
wafwerar 已提交
5839 5840
  taosMemoryFreeClear(pOperator->info);
  taosMemoryFreeClear(pOperator);
5841 5842
}

5843
int32_t doInitAggInfoSup(SAggSupporter* pAggSup, SqlFunctionCtx* pCtx, int32_t numOfOutput, size_t keyBufSize, const char* pKey) {
5844 5845
  _hash_fn_t hashFn = taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY);

H
Haojun Liao 已提交
5846
  pAggSup->resultRowSize       = getResultRowSize(pCtx, numOfOutput);
5847
  pAggSup->keyBuf              = taosMemoryCalloc(1, keyBufSize);
5848
  pAggSup->pResultRowHashTable = taosHashInit(10, hashFn, true, HASH_NO_LOCK);
H
Haojun Liao 已提交
5849
  pAggSup->pResultRowListSet   = taosHashInit(100, hashFn, false, HASH_NO_LOCK);
5850 5851 5852
  pAggSup->pResultRowArrayList = taosArrayInit(10, sizeof(SResultRowCell));

  if (pAggSup->keyBuf == NULL || pAggSup->pResultRowArrayList == NULL || pAggSup->pResultRowListSet == NULL ||
5853
      pAggSup->pResultRowHashTable == NULL) {
5854 5855 5856
    return TSDB_CODE_OUT_OF_MEMORY;
  }

H
Haojun Liao 已提交
5857 5858 5859 5860 5861
  int32_t code = createDiskbasedBuf(&pAggSup->pResultBuf, 4096, 4096 * 256, pKey, "/tmp/");
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

5862 5863 5864
  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
5865
static void cleanupAggSup(SAggSupporter* pAggSup) {
wafwerar's avatar
wafwerar 已提交
5866
  taosMemoryFreeClear(pAggSup->keyBuf);
5867 5868 5869
  taosHashCleanup(pAggSup->pResultRowHashTable);
  taosHashCleanup(pAggSup->pResultRowListSet);
  taosArrayDestroy(pAggSup->pResultRowArrayList);
H
Haojun Liao 已提交
5870
  destroyDiskbasedBuf(pAggSup->pResultBuf);
5871 5872
}

H
Haojun Liao 已提交
5873
int32_t initAggInfo(SOptrBasicInfo* pBasicInfo, SAggSupporter* pAggSup, SExprInfo* pExprInfo, int32_t numOfCols,
5874
                           int32_t numOfRows, SSDataBlock* pResultBlock, size_t keyBufSize, const char* pkey) {
5875
  pBasicInfo->pCtx = createSqlFunctionCtx(pExprInfo, numOfCols, &pBasicInfo->rowCellInfoOffset);
H
Haojun Liao 已提交
5876 5877 5878
  pBasicInfo->pRes = pResultBlock;
  pBasicInfo->capacity = numOfRows;

5879
  doInitAggInfoSup(pAggSup, pBasicInfo->pCtx, numOfCols, keyBufSize, pkey);
5880
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
5881 5882 5883
}

static STableQueryInfo* initTableQueryInfo(const STableGroupInfo* pTableGroupInfo) {
wafwerar's avatar
wafwerar 已提交
5884
  STableQueryInfo* pTableQueryInfo = taosMemoryCalloc(pTableGroupInfo->numOfTables, sizeof(STableQueryInfo));
H
Haojun Liao 已提交
5885 5886
  if (pTableQueryInfo == NULL) {
    return NULL;
H
Haojun Liao 已提交
5887
  }
H
Haojun Liao 已提交
5888 5889

  int32_t index = 0;
L
Liu Jicong 已提交
5890
  for (int32_t i = 0; i < taosArrayGetSize(pTableGroupInfo->pGroupList); ++i) {
H
Haojun Liao 已提交
5891
    SArray* pa = taosArrayGetP(pTableGroupInfo->pGroupList, i);
L
Liu Jicong 已提交
5892
    for (int32_t j = 0; j < taosArrayGetSize(pa); ++j) {
H
Haojun Liao 已提交
5893 5894
      STableKeyInfo* pk = taosArrayGet(pa, j);

H
Haojun Liao 已提交
5895
      STableQueryInfo* pTQueryInfo = &pTableQueryInfo[index++];
L
Liu Jicong 已提交
5896 5897
      pTQueryInfo->uid = pk->uid;
      pTQueryInfo->lastKey = pk->lastKey;
H
Haojun Liao 已提交
5898 5899 5900
      pTQueryInfo->groupIndex = i;
    }
  }
H
Haojun Liao 已提交
5901 5902

  STimeWindow win = {0, INT64_MAX};
H
Haojun Liao 已提交
5903 5904
  createTableQueryInfo(pTableQueryInfo, false, win);
  return pTableQueryInfo;
H
Haojun Liao 已提交
5905 5906
}

L
Liu Jicong 已提交
5907 5908 5909
SOperatorInfo* createAggregateOperatorInfo(SOperatorInfo* downstream, SExprInfo* pExprInfo, int32_t numOfCols,
                                           SSDataBlock* pResultBlock, SExecTaskInfo* pTaskInfo,
                                           const STableGroupInfo* pTableGroupInfo) {
wafwerar's avatar
wafwerar 已提交
5910
  SAggOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SAggOperatorInfo));
L
Liu Jicong 已提交
5911
  SOperatorInfo*    pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
5912 5913 5914
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }
H
Haojun Liao 已提交
5915 5916

  //(int32_t)(getRowNumForMultioutput(pQueryAttr, pQueryAttr->topBotQuery, pQueryAttr->stableQuery));
H
Haojun Liao 已提交
5917
  int32_t numOfRows = 1;
5918 5919
  size_t keyBufSize = sizeof(int64_t) + sizeof(int64_t) + POINTER_BYTES;
  int32_t code = initAggInfo(&pInfo->binfo, &pInfo->aggSup, pExprInfo, numOfCols, numOfRows, pResultBlock, keyBufSize, pTaskInfo->id.str);
H
Haojun Liao 已提交
5920 5921
  pInfo->pTableQueryInfo = initTableQueryInfo(pTableGroupInfo);
  if (code != TSDB_CODE_SUCCESS || pInfo->pTableQueryInfo == NULL) {
H
Haojun Liao 已提交
5922 5923
    goto _error;
  }
H
Haojun Liao 已提交
5924

H
Haojun Liao 已提交
5925
  setFunctionResultOutput(&pInfo->binfo, &pInfo->aggSup, MAIN_SCAN, pTaskInfo);
5926

H
Haojun Liao 已提交
5927
  pOperator->name         = "TableAggregate";
X
Xiaoyu Wang 已提交
5928
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_AGG;
5929
  pOperator->blockingOptr = true;
H
Haojun Liao 已提交
5930 5931 5932 5933 5934 5935 5936 5937 5938
  pOperator->status       = OP_NOT_OPENED;
  pOperator->info         = pInfo;
  pOperator->pExpr        = pExprInfo;
  pOperator->numOfOutput  = numOfCols;

  pOperator->pTaskInfo    = pTaskInfo;
  pOperator->_openFn      = doOpenAggregateOptr;
  pOperator->getNextFn    = getAggregateResult;
  pOperator->closeFn      = destroyAggOperatorInfo;
wmmhello's avatar
wmmhello 已提交
5939 5940
  pOperator->encodeResultRow = aggEncodeResultRow;
  pOperator->decodeResultRow = aggDecodeResultRow;
H
Haojun Liao 已提交
5941 5942 5943 5944 5945

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

  return pOperator;
L
Liu Jicong 已提交
5948
_error:
H
Haojun Liao 已提交
5949
  destroyAggOperatorInfo(pInfo, numOfCols);
wafwerar's avatar
wafwerar 已提交
5950 5951
  taosMemoryFreeClear(pInfo);
  taosMemoryFreeClear(pOperator);
H
Haojun Liao 已提交
5952 5953
  pTaskInfo->code = TSDB_CODE_OUT_OF_MEMORY;
  return NULL;
5954 5955
}

H
Haojun Liao 已提交
5956
void doDestroyBasicInfo(SOptrBasicInfo* pInfo, int32_t numOfOutput) {
5957 5958
  assert(pInfo != NULL);

5959
  destroySqlFunctionCtx(pInfo->pCtx, numOfOutput);
wafwerar's avatar
wafwerar 已提交
5960
  taosMemoryFreeClear(pInfo->rowCellInfoOffset);
5961 5962

  cleanupResultRowInfo(&pInfo->resultRowInfo);
H
Haojun Liao 已提交
5963
  pInfo->pRes = blockDataDestroy(pInfo->pRes);
5964 5965
}

H
Haojun Liao 已提交
5966
void destroyBasicOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
5967
  SOptrBasicInfo* pInfo = (SOptrBasicInfo*)param;
5968 5969
  doDestroyBasicInfo(pInfo, numOfOutput);
}
H
Haojun Liao 已提交
5970 5971

void destroyStateWindowOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
5972
  SStateWindowOperatorInfo* pInfo = (SStateWindowOperatorInfo*)param;
5973
  doDestroyBasicInfo(&pInfo->binfo, numOfOutput);
5974
  taosMemoryFreeClear(pInfo->stateKey.pData);
5975
}
H
Haojun Liao 已提交
5976 5977

void destroyAggOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
5978
  SAggOperatorInfo* pInfo = (SAggOperatorInfo*)param;
5979 5980
  doDestroyBasicInfo(&pInfo->binfo, numOfOutput);
}
5981

H
Haojun Liao 已提交
5982
void destroyIntervalOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
5983
  STableIntervalOperatorInfo* pInfo = (STableIntervalOperatorInfo*)param;
H
Haojun Liao 已提交
5984 5985 5986 5987 5988
  doDestroyBasicInfo(&pInfo->binfo, numOfOutput);
  cleanupAggSup(&pInfo->aggSup);
}

void destroySWindowOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
5989
  SSessionAggOperatorInfo* pInfo = (SSessionAggOperatorInfo*)param;
5990 5991 5992
  doDestroyBasicInfo(&pInfo->binfo, numOfOutput);
}

H
Haojun Liao 已提交
5993
void destroySFillOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
5994
  SFillOperatorInfo* pInfo = (SFillOperatorInfo*)param;
5995
  pInfo->pFillInfo = taosDestroyFillInfo(pInfo->pFillInfo);
H
Haojun Liao 已提交
5996
  pInfo->pRes = blockDataDestroy(pInfo->pRes);
wafwerar's avatar
wafwerar 已提交
5997
  taosMemoryFreeClear(pInfo->p);
5998 5999
}

H
Haojun Liao 已提交
6000
static void destroyProjectOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
6001
  SProjectOperatorInfo* pInfo = (SProjectOperatorInfo*)param;
6002 6003 6004
  doDestroyBasicInfo(&pInfo->binfo, numOfOutput);
}

H
Haojun Liao 已提交
6005
static void destroyTagScanOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
6006
  STagScanInfo* pInfo = (STagScanInfo*)param;
H
Haojun Liao 已提交
6007
  pInfo->pRes = blockDataDestroy(pInfo->pRes);
6008 6009
}

H
Haojun Liao 已提交
6010
static void destroyOrderOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
6011
  SSortOperatorInfo* pInfo = (SSortOperatorInfo*)param;
H
Haojun Liao 已提交
6012 6013
  pInfo->pDataBlock = blockDataDestroy(pInfo->pDataBlock);

H
Haojun Liao 已提交
6014
  taosArrayDestroy(pInfo->pSortInfo);
6015
  taosArrayDestroy(pInfo->inputSlotMap);
6016 6017
}

H
Haojun Liao 已提交
6018
void destroyExchangeOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
6019
  SExchangeInfo* pExInfo = (SExchangeInfo*)param;
H
Haojun Liao 已提交
6020 6021 6022 6023 6024 6025 6026 6027 6028
  taosArrayDestroy(pExInfo->pSources);
  taosArrayDestroy(pExInfo->pSourceDataInfo);
  if (pExInfo->pResult != NULL) {
    blockDataDestroy(pExInfo->pResult);
  }

  tsem_destroy(&pExInfo->ready);
}

L
Liu Jicong 已提交
6029 6030 6031
SOperatorInfo* createMultiTableAggOperatorInfo(SOperatorInfo* downstream, SExprInfo* pExprInfo, int32_t numOfCols,
                                               SSDataBlock* pResBlock, SExecTaskInfo* pTaskInfo,
                                               const STableGroupInfo* pTableGroupInfo) {
wafwerar's avatar
wafwerar 已提交
6032
  SAggOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SAggOperatorInfo));
6033

H
Haojun Liao 已提交
6034
  int32_t numOfRows = 1;
6035
  size_t keyBufSize = sizeof(int64_t) + sizeof(int64_t) + POINTER_BYTES;
L
Liu Jicong 已提交
6036
  int32_t code =
6037
      initAggInfo(&pInfo->binfo, &pInfo->aggSup, pExprInfo, numOfCols, numOfRows, pResBlock, keyBufSize, pTaskInfo->id.str);
H
Haojun Liao 已提交
6038 6039 6040 6041
  pInfo->pTableQueryInfo = initTableQueryInfo(pTableGroupInfo);
  if (code != TSDB_CODE_SUCCESS || pInfo->pTableQueryInfo == NULL) {
    goto _error;
  }
H
Haojun Liao 已提交
6042

L
Liu Jicong 已提交
6043
  size_t tableGroup = taosArrayGetSize(pTableGroupInfo->pGroupList);
6044
  initResultRowInfo(&pInfo->binfo.resultRowInfo, (int32_t)tableGroup);
6045

wafwerar's avatar
wafwerar 已提交
6046
  SOperatorInfo* pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
L
Liu Jicong 已提交
6047
  pOperator->name = "MultiTableAggregate";
X
Xiaoyu Wang 已提交
6048
  // pOperator->operatorType = OP_MultiTableAggregate;
6049
  pOperator->blockingOptr = true;
L
Liu Jicong 已提交
6050 6051 6052 6053 6054
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
  pOperator->pExpr = pExprInfo;
  pOperator->numOfOutput = numOfCols;
  pOperator->pTaskInfo = pTaskInfo;
6055

H
Haojun Liao 已提交
6056
  pOperator->getNextFn = doMultiTableAggregate;
H
Haojun Liao 已提交
6057
  pOperator->closeFn = destroyAggOperatorInfo;
H
Haojun Liao 已提交
6058 6059 6060 6061
  code = appendDownstream(pOperator, &downstream, 1);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
6062 6063

  return pOperator;
H
Haojun Liao 已提交
6064 6065 6066

_error:
  return NULL;
6067 6068
}

H
Haojun Liao 已提交
6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079
static SArray* setRowTsColumnOutputInfo(SqlFunctionCtx* pCtx, int32_t numOfCols) {
  SArray* pList = taosArrayInit(4, sizeof(int32_t));
  for(int32_t i = 0; i < numOfCols; ++i) {
    if (fmIsPseudoColumnFunc(pCtx[i].functionId)) {
      taosArrayPush(pList, &i);
    }
  }

  return pList;
}

L
Liu Jicong 已提交
6080
SOperatorInfo* createProjectOperatorInfo(SOperatorInfo* downstream, SExprInfo* pExprInfo, int32_t num,
H
Haojun Liao 已提交
6081
                                         SSDataBlock* pResBlock, SLimit* pLimit, SLimit* pSlimit, SExecTaskInfo* pTaskInfo) {
wafwerar's avatar
wafwerar 已提交
6082
  SProjectOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SProjectOperatorInfo));
L
Liu Jicong 已提交
6083
  SOperatorInfo*        pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
6084 6085 6086
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }
6087

H
Haojun Liao 已提交
6088
  pInfo->limit      = *pLimit;
H
Haojun Liao 已提交
6089
  pInfo->slimit     = *pSlimit;
H
Haojun Liao 已提交
6090
  pInfo->curOffset  = pLimit->offset;
H
Haojun Liao 已提交
6091 6092
  pInfo->curSOffset = pSlimit->offset;

H
Haojun Liao 已提交
6093
  pInfo->binfo.pRes = pResBlock;
H
Haojun Liao 已提交
6094 6095 6096

  int32_t numOfCols = num;
  int32_t numOfRows = 4096;
6097 6098
  size_t keyBufSize = sizeof(int64_t) + sizeof(int64_t) + POINTER_BYTES;
  initAggInfo(&pInfo->binfo, &pInfo->aggSup, pExprInfo, numOfCols, numOfRows, pResBlock, keyBufSize, pTaskInfo->id.str);
H
Haojun Liao 已提交
6099
  setFunctionResultOutput(&pInfo->binfo, &pInfo->aggSup, MAIN_SCAN, pTaskInfo);
H
Haojun Liao 已提交
6100
  pInfo->pPseudoColInfo = setRowTsColumnOutputInfo(pInfo->binfo.pCtx, numOfCols);
6101

H
Haojun Liao 已提交
6102
  pOperator->name         = "ProjectOperator";
H
Haojun Liao 已提交
6103
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_PROJECT;
6104
  pOperator->blockingOptr = false;
H
Haojun Liao 已提交
6105 6106 6107 6108 6109 6110 6111
  pOperator->status       = OP_NOT_OPENED;
  pOperator->info         = pInfo;
  pOperator->pExpr        = pExprInfo;
  pOperator->numOfOutput  = num;
  pOperator->_openFn      = operatorDummyOpenFn;
  pOperator->getNextFn    = doProjectOperation;
  pOperator->closeFn      = destroyProjectOperatorInfo;
L
Liu Jicong 已提交
6112 6113

  pOperator->pTaskInfo = pTaskInfo;
6114
  int32_t code = appendDownstream(pOperator, &downstream, 1);
H
Haojun Liao 已提交
6115
  if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
6116 6117
    goto _error;
  }
6118 6119

  return pOperator;
H
Haojun Liao 已提交
6120

L
Liu Jicong 已提交
6121
_error:
H
Haojun Liao 已提交
6122 6123
  pTaskInfo->code = TSDB_CODE_OUT_OF_MEMORY;
  return NULL;
6124 6125
}

L
Liu Jicong 已提交
6126
SOperatorInfo* createIntervalOperatorInfo(SOperatorInfo* downstream, SExprInfo* pExprInfo, int32_t numOfCols,
6127
                                          SSDataBlock* pResBlock, SInterval* pInterval, int32_t primaryTsSlot,
6128
                                          const STableGroupInfo* pTableGroupInfo, SExecTaskInfo* pTaskInfo) {
wafwerar's avatar
wafwerar 已提交
6129
  STableIntervalOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(STableIntervalOperatorInfo));
L
Liu Jicong 已提交
6130
  SOperatorInfo*              pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
6131 6132 6133
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }
H
Haojun Liao 已提交
6134

H
Haojun Liao 已提交
6135 6136
  pInfo->order     = TSDB_ORDER_ASC;
  pInfo->interval  = *pInterval;
6137 6138 6139
  pInfo->execModel = pTaskInfo->execModel;

  pInfo->win       = pTaskInfo->window;
6140 6141
  pInfo->win.skey  = 0;
  pInfo->win.ekey  = INT64_MAX;
6142

6143 6144
  pInfo->primaryTsIndex = primaryTsSlot;

6145
  int32_t numOfRows = 4096;
6146 6147
  size_t keyBufSize = sizeof(int64_t) + sizeof(int64_t) + POINTER_BYTES;
  int32_t code = initAggInfo(&pInfo->binfo, &pInfo->aggSup, pExprInfo, numOfCols, numOfRows, pResBlock, keyBufSize, pTaskInfo->id.str);
6148 6149
  initExecTimeWindowInfo(&pInfo->timeWindowData, &pInfo->win);

L
Liu Jicong 已提交
6150 6151
  //  pInfo->pTableQueryInfo = initTableQueryInfo(pTableGroupInfo);
  if (code != TSDB_CODE_SUCCESS /* || pInfo->pTableQueryInfo == NULL*/) {
H
Haojun Liao 已提交
6152 6153
    goto _error;
  }
H
Haojun Liao 已提交
6154 6155

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

6157
  pOperator->name         = "TimeIntervalAggOperator";
H
Haojun Liao 已提交
6158
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_INTERVAL;
6159
  pOperator->blockingOptr = true;
H
Haojun Liao 已提交
6160 6161 6162 6163 6164 6165 6166
  pOperator->status       = OP_NOT_OPENED;
  pOperator->pExpr        = pExprInfo;
  pOperator->pTaskInfo    = pTaskInfo;
  pOperator->numOfOutput  = numOfCols;
  pOperator->info         = pInfo;
  pOperator->_openFn      = doOpenIntervalAgg;
  pOperator->getNextFn    = doBuildIntervalResult;
6167
  pOperator->getStreamResFn= doStreamIntervalAgg;
H
Haojun Liao 已提交
6168
  pOperator->closeFn      = destroyIntervalOperatorInfo;
6169 6170
  pOperator->encodeResultRow = aggEncodeResultRow;
  pOperator->decodeResultRow = aggDecodeResultRow;
6171

H
Haojun Liao 已提交
6172
  code = appendDownstream(pOperator, &downstream, 1);
H
Haojun Liao 已提交
6173 6174 6175 6176
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }

6177
  return pOperator;
H
Haojun Liao 已提交
6178

L
Liu Jicong 已提交
6179
_error:
H
Haojun Liao 已提交
6180
  destroyIntervalOperatorInfo(pInfo, numOfCols);
wafwerar's avatar
wafwerar 已提交
6181 6182
  taosMemoryFreeClear(pInfo);
  taosMemoryFreeClear(pOperator);
H
Haojun Liao 已提交
6183 6184
  pTaskInfo->code = code;
  return NULL;
6185 6186
}

6187 6188 6189 6190 6191 6192
SOperatorInfo* createTimeSliceOperatorInfo(SOperatorInfo* downstream, SExprInfo* pExprInfo, int32_t numOfCols, SSDataBlock* pResultBlock, SExecTaskInfo* pTaskInfo) {
  STimeSliceOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(STimeSliceOperatorInfo));
  SOperatorInfo* pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
  if (pOperator == NULL || pInfo == NULL) {
    goto _error;
  }
6193

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

6196
  pOperator->name         = "TimeSliceOperator";
L
Liu Jicong 已提交
6197
  //  pOperator->operatorType = OP_AllTimeWindow;
6198
  pOperator->blockingOptr = true;
6199 6200 6201 6202 6203 6204 6205
  pOperator->status       = OP_NOT_OPENED;
  pOperator->pExpr        = pExprInfo;
  pOperator->numOfOutput  = numOfCols;
  pOperator->info         = pInfo;
  pOperator->pTaskInfo    = pTaskInfo;
  pOperator->getNextFn    = doAllIntervalAgg;
  pOperator->closeFn      = destroyBasicOperatorInfo;
6206

L
Liu Jicong 已提交
6207
  int32_t code = appendDownstream(pOperator, &downstream, 1);
6208
  return pOperator;
6209 6210 6211 6212 6213 6214

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

H
Haojun Liao 已提交
6217
SOperatorInfo* createStatewindowOperatorInfo(SOperatorInfo* downstream, SExprInfo* pExpr, int32_t numOfCols, SSDataBlock* pResBlock, SExecTaskInfo* pTaskInfo) {
wafwerar's avatar
wafwerar 已提交
6218
  SStateWindowOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SStateWindowOperatorInfo));
6219 6220 6221 6222
  SOperatorInfo* pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }
H
Haojun Liao 已提交
6223

L
Liu Jicong 已提交
6224
  pInfo->colIndex = -1;
6225 6226
  size_t keyBufSize = sizeof(int64_t) + sizeof(int64_t) + POINTER_BYTES;
  initAggInfo(&pInfo->binfo, &pInfo->aggSup, pExpr, numOfCols, 4096, pResBlock, keyBufSize, pTaskInfo->id.str);
6227
  initResultRowInfo(&pInfo->binfo.resultRowInfo, 8);
6228

6229 6230
  pOperator->name         = "StateWindowOperator";
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_STATE_WINDOW;
6231
  pOperator->blockingOptr = true;
H
Haojun Liao 已提交
6232 6233 6234 6235 6236 6237 6238 6239
  pOperator->status       = OP_NOT_OPENED;
  pOperator->pExpr        = pExpr;
  pOperator->numOfOutput  = numOfCols;

  pOperator->pTaskInfo    = pTaskInfo;
  pOperator->info         = pInfo;
  pOperator->getNextFn    = doStateWindowAgg;
  pOperator->closeFn      = destroyStateWindowOperatorInfo;
6240 6241
  pOperator->encodeResultRow = aggEncodeResultRow;
  pOperator->decodeResultRow = aggDecodeResultRow;
6242

H
Haojun Liao 已提交
6243
  int32_t code = appendDownstream(pOperator, &downstream, 1);
6244
  return pOperator;
6245 6246 6247 6248

  _error:
  pTaskInfo->code = TSDB_CODE_SUCCESS;
  return NULL;
6249 6250
}

L
Liu Jicong 已提交
6251 6252
SOperatorInfo* createSessionAggOperatorInfo(SOperatorInfo* downstream, SExprInfo* pExprInfo, int32_t numOfCols,
                                            SSDataBlock* pResBlock, int64_t gap, SExecTaskInfo* pTaskInfo) {
wafwerar's avatar
wafwerar 已提交
6253
  SSessionAggOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SSessionAggOperatorInfo));
L
Liu Jicong 已提交
6254
  SOperatorInfo*           pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
6255 6256 6257
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }
H
Haojun Liao 已提交
6258

H
Haojun Liao 已提交
6259
  int32_t numOfRows = 4096;
6260 6261
  size_t keyBufSize = sizeof(int64_t) + sizeof(int64_t) + POINTER_BYTES;
  int32_t code = initAggInfo(&pInfo->binfo, &pInfo->aggSup, pExprInfo, numOfCols, numOfRows, pResBlock, keyBufSize, pTaskInfo->id.str);
H
Haojun Liao 已提交
6262 6263 6264
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
6265

H
Haojun Liao 已提交
6266
  initResultRowInfo(&pInfo->binfo.resultRowInfo, 8);
6267
  initExecTimeWindowInfo(&pInfo->timeWindowData, &pTaskInfo->window);
6268

6269 6270
  pInfo->gap              = gap;
  pInfo->binfo.pRes       = pResBlock;
6271
  pInfo->winSup.prevTs    = INT64_MIN;
6272 6273
  pInfo->reptScan         = false;
  pOperator->name         = "SessionWindowAggOperator";
H
Haojun Liao 已提交
6274
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_SESSION_WINDOW;
6275
  pOperator->blockingOptr = true;
6276 6277 6278 6279 6280 6281
  pOperator->status       = OP_NOT_OPENED;
  pOperator->pExpr        = pExprInfo;
  pOperator->numOfOutput  = numOfCols;
  pOperator->info         = pInfo;
  pOperator->getNextFn    = doSessionWindowAgg;
  pOperator->closeFn      = destroySWindowOperatorInfo;
6282 6283
  pOperator->encodeResultRow = aggEncodeResultRow;
  pOperator->decodeResultRow = aggDecodeResultRow;
6284
  pOperator->pTaskInfo    = pTaskInfo;
6285

H
Haojun Liao 已提交
6286
  code = appendDownstream(pOperator, &downstream, 1);
6287
  return pOperator;
H
Haojun Liao 已提交
6288

L
Liu Jicong 已提交
6289
_error:
H
Haojun Liao 已提交
6290 6291 6292 6293
  if (pInfo != NULL) {
    destroySWindowOperatorInfo(pInfo, numOfCols);
  }

wafwerar's avatar
wafwerar 已提交
6294 6295
  taosMemoryFreeClear(pInfo);
  taosMemoryFreeClear(pOperator);
H
Haojun Liao 已提交
6296 6297
  pTaskInfo->code = code;
  return NULL;
6298 6299
}

L
Liu Jicong 已提交
6300 6301
SOperatorInfo* createMultiTableTimeIntervalOperatorInfo(STaskRuntimeEnv* pRuntimeEnv, SOperatorInfo* downstream,
                                                        SExprInfo* pExpr, int32_t numOfOutput) {
wafwerar's avatar
wafwerar 已提交
6302
  STableIntervalOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(STableIntervalOperatorInfo));
6303

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

wafwerar's avatar
wafwerar 已提交
6306
  SOperatorInfo* pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
L
Liu Jicong 已提交
6307 6308
  pOperator->name = "MultiTableTimeIntervalOperator";
  //  pOperator->operatorType = OP_MultiTableTimeInterval;
6309
  pOperator->blockingOptr = true;
L
Liu Jicong 已提交
6310 6311 6312 6313
  pOperator->status = OP_NOT_OPENED;
  pOperator->pExpr = pExpr;
  pOperator->numOfOutput = numOfOutput;
  pOperator->info = pInfo;
6314

H
Haojun Liao 已提交
6315
  pOperator->getNextFn = doSTableIntervalAgg;
H
Haojun Liao 已提交
6316
  pOperator->closeFn = destroyBasicOperatorInfo;
6317

L
Liu Jicong 已提交
6318
  int32_t code = appendDownstream(pOperator, &downstream, 1);
6319 6320 6321
  return pOperator;
}

L
Liu Jicong 已提交
6322 6323
SOperatorInfo* createAllMultiTableTimeIntervalOperatorInfo(STaskRuntimeEnv* pRuntimeEnv, SOperatorInfo* downstream,
                                                           SExprInfo* pExpr, int32_t numOfOutput) {
wafwerar's avatar
wafwerar 已提交
6324
  STableIntervalOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(STableIntervalOperatorInfo));
6325

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

wafwerar's avatar
wafwerar 已提交
6328
  SOperatorInfo* pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
L
Liu Jicong 已提交
6329 6330
  pOperator->name = "AllMultiTableTimeIntervalOperator";
  //  pOperator->operatorType = OP_AllMultiTableTimeInterval;
6331
  pOperator->blockingOptr = true;
wmmhello's avatar
wmmhello 已提交
6332

L
Liu Jicong 已提交
6333 6334 6335 6336
  pOperator->status = OP_NOT_OPENED;
  pOperator->pExpr = pExpr;
  pOperator->numOfOutput = numOfOutput;
  pOperator->info = pInfo;
6337

H
Haojun Liao 已提交
6338
  pOperator->getNextFn = doAllSTableIntervalAgg;
H
Haojun Liao 已提交
6339
  pOperator->closeFn = destroyBasicOperatorInfo;
6340

L
Liu Jicong 已提交
6341
  int32_t code = appendDownstream(pOperator, &downstream, 1);
6342 6343 6344 6345

  return pOperator;
}

H
Haojun Liao 已提交
6346
static int32_t initFillInfo(SFillOperatorInfo* pInfo, SExprInfo* pExpr, int32_t numOfCols, int64_t* fillVal,
L
Liu Jicong 已提交
6347
                            STimeWindow win, int32_t capacity, const char* id, SInterval* pInterval, int32_t fillType) {
H
Haojun Liao 已提交
6348 6349 6350 6351 6352 6353 6354 6355 6356 6357
  struct SFillColInfo* pColInfo = createFillColInfo(pExpr, numOfCols, (int64_t*)fillVal);

  TSKEY sk = TMIN(win.skey, win.ekey);
  TSKEY ek = TMAX(win.skey, win.ekey);

  // TODO set correct time precision
  STimeWindow w = TSWINDOW_INITIALIZER;
  getAlignQueryTimeWindow(pInterval, TSDB_TIME_PRECISION_MILLI, win.skey, sk, ek, &w);

  int32_t order = TSDB_ORDER_ASC;
L
Liu Jicong 已提交
6358 6359
  pInfo->pFillInfo = taosCreateFillInfo(order, w.skey, 0, capacity, numOfCols, pInterval->sliding,
                                        pInterval->slidingUnit, (int8_t)pInterval->precision, fillType, pColInfo, id);
H
Haojun Liao 已提交
6360

wafwerar's avatar
wafwerar 已提交
6361
  pInfo->p = taosMemoryCalloc(numOfCols, POINTER_BYTES);
H
Haojun Liao 已提交
6362 6363 6364 6365 6366 6367 6368 6369

  if (pInfo->pFillInfo == NULL || pInfo->p == NULL) {
    return TSDB_CODE_OUT_OF_MEMORY;
  } else {
    return TSDB_CODE_SUCCESS;
  }
}

L
Liu Jicong 已提交
6370 6371 6372
SOperatorInfo* createFillOperatorInfo(SOperatorInfo* downstream, SExprInfo* pExpr, int32_t numOfCols,
                                      SInterval* pInterval, SSDataBlock* pResBlock, int32_t fillType, char* fillVal,
                                      bool multigroupResult, SExecTaskInfo* pTaskInfo) {
wafwerar's avatar
wafwerar 已提交
6373
  SFillOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SFillOperatorInfo));
L
Liu Jicong 已提交
6374
  SOperatorInfo*     pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
6375

L
Liu Jicong 已提交
6376
  pInfo->pRes = pResBlock;
6377
  pInfo->multigroupResult = multigroupResult;
L
Liu Jicong 已提交
6378
  pInfo->intervalInfo = *pInterval;
6379

H
Haojun Liao 已提交
6380
  SResultInfo* pResultInfo = &pOperator->resultInfo;
L
Liu Jicong 已提交
6381 6382
  int32_t      code = initFillInfo(pInfo, pExpr, numOfCols, (int64_t*)fillVal, pTaskInfo->window, pResultInfo->capacity,
                                   pTaskInfo->id.str, pInterval, fillType);
6383 6384 6385
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
6386

L
Liu Jicong 已提交
6387
  pOperator->name = "FillOperator";
6388
  pOperator->blockingOptr = false;
L
Liu Jicong 已提交
6389 6390 6391 6392 6393 6394 6395 6396
  pOperator->status = OP_NOT_OPENED;
  //  pOperator->operatorType = OP_Fill;
  pOperator->pExpr = pExpr;
  pOperator->numOfOutput = numOfCols;
  pOperator->info = pInfo;
  pOperator->_openFn = operatorDummyOpenFn;
  pOperator->getNextFn = doFill;
  pOperator->pTaskInfo = pTaskInfo;
6397

L
Liu Jicong 已提交
6398
  pOperator->closeFn = destroySFillOperatorInfo;
H
Haojun Liao 已提交
6399

6400
  code = appendDownstream(pOperator, &downstream, 1);
6401
  return pOperator;
H
Haojun Liao 已提交
6402

L
Liu Jicong 已提交
6403
_error:
wafwerar's avatar
wafwerar 已提交
6404 6405
  taosMemoryFreeClear(pOperator);
  taosMemoryFreeClear(pInfo);
H
Haojun Liao 已提交
6406
  return NULL;
6407 6408
}

L
Liu Jicong 已提交
6409
static SSDataBlock* doTagScan(SOperatorInfo* pOperator, bool* newgroup) {
6410 6411 6412 6413 6414 6415
#if 0
  SOperatorInfo* pOperator = (SOperatorInfo*) param;
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

H
Haojun Liao 已提交
6416
  int32_t maxNumOfTables = (int32_t)pResultInfo->capacity;
6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437

  STagScanInfo *pInfo = pOperator->info;
  SSDataBlock  *pRes = pInfo->pRes;
  *newgroup = false;

  int32_t count = 0;
  SArray* pa = GET_TABLEGROUP(pRuntimeEnv, 0);

  int32_t functionId = getExprFunctionId(&pOperator->pExpr[0]);
  if (functionId == FUNCTION_TID_TAG) { // return the tags & table Id
    assert(pQueryAttr->numOfOutput == 1);

    SExprInfo* pExprInfo = &pOperator->pExpr[0];
    int32_t rsize = pExprInfo->base.resSchema.bytes;

    count = 0;

    int16_t bytes = pExprInfo->base.resSchema.bytes;
    int16_t type  = pExprInfo->base.resSchema.type;

    for(int32_t i = 0; i < pQueryAttr->numOfTags; ++i) {
6438
      if (pQueryAttr->tagColList[i].colId == pExprInfo->base.pColumns->info.colId) {
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
        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;
6470
      if (pExprInfo->base.pColumns->info.colId == TSDB_TBNAME_COLUMN_INDEX) {
6471 6472
        data = tsdbGetTableName(item->pTable);
      } else {
6473
        data = tsdbGetTableTagVal(item->pTable, pExprInfo->base.pColumns->info.colId, type, bytes);
6474 6475 6476 6477 6478 6479
      }

      doSetTagValueToResultBuf(output, data, type, bytes);
      count += 1;
    }

6480
    //qDebug("QInfo:0x%"PRIx64" create (tableId, tag) info completed, rows:%d", GET_TASKID(pRuntimeEnv), count);
6481 6482 6483 6484 6485 6486
  } 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;
6487
    //qDebug("QInfo:0x%"PRIx64" create count(tbname) query, res:%d rows:1", GET_TASKID(pRuntimeEnv), count);
6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500
  } 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
6501
        if (TSDB_COL_IS_UD_COL(pExprInfo[j].base.pColumns->flag)) {
6502 6503 6504 6505 6506 6507 6508
          continue;
        }

        SColumnInfoData* pColInfo = taosArrayGet(pRes->pDataBlock, j);
        type  = pExprInfo[j].base.resSchema.type;
        bytes = pExprInfo[j].base.resSchema.bytes;

6509
        if (pExprInfo[j].base.pColumns->info.colId == TSDB_TBNAME_COLUMN_INDEX) {
6510 6511
          data = tsdbGetTableName(item->pTable);
        } else {
6512
          data = tsdbGetTableTagVal(item->pTable, pExprInfo[j].base.pColumns->info.colId, type, bytes);
6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525
        }

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

6526
    //qDebug("QInfo:0x%"PRIx64" create tag values results completed, rows:%d", GET_TASKID(pRuntimeEnv), count);
6527 6528 6529
  }

  if (pOperator->status == OP_EXEC_DONE) {
6530
    setTaskStatus(pOperator->pRuntimeEnv, TASK_COMPLETED);
6531 6532 6533 6534 6535 6536
  }

  pRes->info.rows = count;
  return (pRes->info.rows == 0)? NULL:pInfo->pRes;

#endif
6537
  return TSDB_CODE_SUCCESS;
6538 6539
}

H
Haojun Liao 已提交
6540
SOperatorInfo* createTagScanOperatorInfo(STaskRuntimeEnv* pRuntimeEnv, SExprInfo* pExpr, int32_t numOfOutput) {
wafwerar's avatar
wafwerar 已提交
6541
  STagScanInfo* pInfo = taosMemoryCalloc(1, sizeof(STagScanInfo));
L
Liu Jicong 已提交
6542
  //  pInfo->pRes = createOutputBuf(pExpr, numOfOutput, pResultInfo->capacity);
6543 6544 6545 6546 6547 6548

  size_t numOfGroup = GET_NUM_OF_TABLEGROUP(pRuntimeEnv);
  assert(numOfGroup == 0 || numOfGroup == 1);

  pInfo->curPos = 0;

wafwerar's avatar
wafwerar 已提交
6549
  SOperatorInfo* pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
L
Liu Jicong 已提交
6550
  pOperator->name = "SeqTableTagScan";
X
Xiaoyu Wang 已提交
6551
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_TAG_SCAN;
6552
  pOperator->blockingOptr = false;
L
Liu Jicong 已提交
6553 6554
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
H
Haojun Liao 已提交
6555
  pOperator->getNextFn = doTagScan;
L
Liu Jicong 已提交
6556 6557
  pOperator->pExpr = pExpr;
  pOperator->numOfOutput = numOfOutput;
H
Haojun Liao 已提交
6558
  pOperator->closeFn = destroyTagScanOperatorInfo;
6559 6560 6561

  return pOperator;
}
H
Haojun Liao 已提交
6562

6563

L
Liu Jicong 已提交
6564
static int32_t getColumnIndexInSource(SQueriedTableInfo* pTableInfo, SExprBasicInfo* pExpr, SColumnInfo* pTagCols) {
6565 6566
  int32_t j = 0;

H
Haojun Liao 已提交
6567 6568
  if (TSDB_COL_IS_TAG(pExpr->pParam[0].pCol->type)) {
    if (pExpr->pParam[0].pCol->colId == TSDB_TBNAME_COLUMN_INDEX) {
6569 6570 6571
      return TSDB_TBNAME_COLUMN_INDEX;
    }

L
Liu Jicong 已提交
6572
    while (j < pTableInfo->numOfTags) {
H
Haojun Liao 已提交
6573
      if (pExpr->pParam[0].pCol->colId == pTagCols[j].colId) {
6574 6575 6576 6577 6578 6579
        return j;
      }

      j += 1;
    }

6580
  } /*else if (TSDB_COL_IS_UD_COL(pExpr->colInfo.flag)) {  // user specified column data
6581 6582 6583 6584 6585 6586 6587 6588 6589
    return TSDB_UD_COLUMN_INDEX;
  } else {
    while (j < pTableInfo->numOfCols) {
      if (pExpr->colInfo.colId == pTableInfo->colList[j].colId) {
        return j;
      }

      j += 1;
    }
6590
  }*/
6591 6592 6593 6594

  return INT32_MIN;  // return a less than TSDB_TBNAME_COLUMN_INDEX value
}

L
Liu Jicong 已提交
6595
bool validateExprColumnInfo(SQueriedTableInfo* pTableInfo, SExprBasicInfo* pExpr, SColumnInfo* pTagCols) {
6596 6597 6598 6599
  int32_t j = getColumnIndexInSource(pTableInfo, pExpr, pTagCols);
  return j != INT32_MIN;
}

L
Liu Jicong 已提交
6600 6601
static SResSchema createResSchema(int32_t type, int32_t bytes, int32_t slotId, int32_t scale, int32_t precision,
                                  const char* name) {
H
Haojun Liao 已提交
6602
  SResSchema s = {0};
6603 6604 6605 6606
  s.scale  = scale;
  s.type   = type;
  s.bytes  = bytes;
  s.slotId = slotId;
H
Haojun Liao 已提交
6607
  s.precision = precision;
H
Haojun Liao 已提交
6608 6609 6610 6611
  strncpy(s.name, name, tListLen(s.name));

  return s;
}
H
Haojun Liao 已提交
6612

H
Haojun Liao 已提交
6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629
static SColumn* createColumn(int32_t blockId, int32_t slotId, SDataType* pType) {
  SColumn* pCol = taosMemoryCalloc(1, sizeof(SColumn));
  if (pCol == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

  pCol->slotId      = slotId;
  pCol->bytes       = pType->bytes;
  pCol->type        = pType->type;
  pCol->scale       = pType->scale;
  pCol->precision   = pType->precision;
  pCol->dataBlockId = blockId;

  return pCol;
}

H
Haojun Liao 已提交
6630
SExprInfo* createExprInfo(SNodeList* pNodeList, SNodeList* pGroupKeys, int32_t* numOfExprs) {
H
Haojun Liao 已提交
6631
  int32_t numOfFuncs = LIST_LENGTH(pNodeList);
H
Haojun Liao 已提交
6632 6633 6634 6635
  int32_t numOfGroupKeys = 0;
  if (pGroupKeys != NULL) {
    numOfGroupKeys = LIST_LENGTH(pGroupKeys);
  }
H
Haojun Liao 已提交
6636

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

L
Liu Jicong 已提交
6640
  for (int32_t i = 0; i < (*numOfExprs); ++i) {
H
Haojun Liao 已提交
6641 6642 6643 6644 6645 6646
    STargetNode* pTargetNode = NULL;
    if (i < numOfFuncs) {
      pTargetNode = (STargetNode*)nodesListGetNode(pNodeList, i);
    } else {
      pTargetNode = (STargetNode*)nodesListGetNode(pGroupKeys, i - numOfFuncs);
    }
H
Haojun Liao 已提交
6647

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

wafwerar's avatar
wafwerar 已提交
6650
    pExp->pExpr = taosMemoryCalloc(1, sizeof(tExprNode));
H
Haojun Liao 已提交
6651
    pExp->pExpr->_function.num = 1;
H
Haojun Liao 已提交
6652
    pExp->pExpr->_function.functionId = -1;
H
Haojun Liao 已提交
6653

H
Haojun Liao 已提交
6654
    // it is a project query, or group by column
H
Haojun Liao 已提交
6655
    if (nodeType(pTargetNode->pExpr) == QUERY_NODE_COLUMN) {
H
Haojun Liao 已提交
6656
      pExp->pExpr->nodeType = QUERY_NODE_COLUMN;
L
Liu Jicong 已提交
6657
      SColumnNode* pColNode = (SColumnNode*)pTargetNode->pExpr;
H
Haojun Liao 已提交
6658

G
Ganlin Zhao 已提交
6659 6660 6661
      pExp->base.pParam = taosMemoryCalloc(1, sizeof(SFunctParam));
      pExp->base.numOfParams = 1;

H
Haojun Liao 已提交
6662 6663
      SDataType* pType = &pColNode->node.resType;
      pExp->base.resSchema = createResSchema(pType->type, pType->bytes, pTargetNode->slotId, pType->scale, pType->precision, pColNode->colName);
H
Haojun Liao 已提交
6664 6665
      pExp->base.pParam[0].pCol = createColumn(pColNode->dataBlockId, pColNode->slotId, pType);
      pExp->base.pParam[0].type = FUNC_PARAM_TYPE_COLUMN;
6666
    } else if (nodeType(pTargetNode->pExpr) == QUERY_NODE_VALUE) {
6667 6668 6669 6670 6671 6672 6673 6674 6675 6676
      pExp->pExpr->nodeType = QUERY_NODE_VALUE;
      SValueNode* pValNode = (SValueNode*)pTargetNode->pExpr;

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

      SDataType* pType = &pValNode->node.resType;
      pExp->base.resSchema = createResSchema(pType->type, pType->bytes, pTargetNode->slotId, pType->scale, pType->precision, pValNode->node.aliasName);
      pExp->base.pParam[0].type = FUNC_PARAM_TYPE_VALUE;
      valueNodeToVariant(pValNode, &pExp->base.pParam[0].param);
6677
    } else if (nodeType(pTargetNode->pExpr) == QUERY_NODE_FUNCTION) {
H
Haojun Liao 已提交
6678
      pExp->pExpr->nodeType = QUERY_NODE_FUNCTION;
H
Haojun Liao 已提交
6679 6680 6681
      SFunctionNode* pFuncNode = (SFunctionNode*)pTargetNode->pExpr;

      SDataType* pType = &pFuncNode->node.resType;
L
Liu Jicong 已提交
6682 6683
      pExp->base.resSchema = createResSchema(pType->type, pType->bytes, pTargetNode->slotId, pType->scale,
                                             pType->precision, pFuncNode->node.aliasName);
H
Haojun Liao 已提交
6684

H
Haojun Liao 已提交
6685
      pExp->pExpr->_function.functionId = pFuncNode->funcId;
H
Haojun Liao 已提交
6686
      pExp->pExpr->_function.pFunctNode = pFuncNode;
H
Haojun Liao 已提交
6687
      strncpy(pExp->pExpr->_function.functionName, pFuncNode->functionName, tListLen(pExp->pExpr->_function.functionName));
H
Haojun Liao 已提交
6688 6689 6690

      // TODO: value parameter needs to be handled
      int32_t numOfParam = LIST_LENGTH(pFuncNode->pParameterList);
G
Ganlin Zhao 已提交
6691 6692 6693 6694

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

H
Haojun Liao 已提交
6695 6696
      for (int32_t j = 0; j < numOfParam; ++j) {
        SNode*       p1 = nodesListGetNode(pFuncNode->pParameterList, j);
G
Ganlin Zhao 已提交
6697
        if (p1->type == QUERY_NODE_COLUMN) {
H
Haojun Liao 已提交
6698
          SColumnNode* pcn = (SColumnNode*) p1;
G
Ganlin Zhao 已提交
6699 6700

          pExp->base.pParam[j].type = FUNC_PARAM_TYPE_COLUMN;
H
Haojun Liao 已提交
6701
          pExp->base.pParam[j].pCol = createColumn(pcn->dataBlockId, pcn->slotId, &pcn->node.resType);
G
Ganlin Zhao 已提交
6702 6703 6704 6705
        } else if (p1->type == QUERY_NODE_VALUE) {
          SValueNode* pvn = (SValueNode*)p1;
          pExp->base.pParam[j].type = FUNC_PARAM_TYPE_VALUE;
        }
H
Haojun Liao 已提交
6706
      }
6707
    } else if (nodeType(pTargetNode->pExpr) == QUERY_NODE_OPERATOR) {
H
Haojun Liao 已提交
6708
      pExp->pExpr->nodeType = QUERY_NODE_OPERATOR;
L
Liu Jicong 已提交
6709
      SOperatorNode* pNode = (SOperatorNode*)pTargetNode->pExpr;
6710

G
Ganlin Zhao 已提交
6711 6712 6713
      pExp->base.pParam = taosMemoryCalloc(1, sizeof(SFunctParam));
      pExp->base.numOfParams = 1;

6714
      SDataType* pType = &pNode->node.resType;
H
Haojun Liao 已提交
6715
      pExp->base.resSchema = createResSchema(pType->type, pType->bytes, pTargetNode->slotId, pType->scale, pType->precision, pNode->node.aliasName);
6716 6717 6718

      pExp->pExpr->_optrRoot.pRootNode = pTargetNode->pExpr;

H
Haojun Liao 已提交
6719 6720
//      pExp->base.pParam[0].type = FUNC_PARAM_TYPE_COLUMN;
//      pExp->base.pParam[0].pCol = createColumn(pTargetNode->dataBlockId, pTargetNode->slotId, pType);
6721 6722
    } else {
      ASSERT(0);
H
Haojun Liao 已提交
6723 6724 6725
    }
  }

H
Haojun Liao 已提交
6726
  return pExprs;
H
Haojun Liao 已提交
6727 6728
}

6729
static SExecTaskInfo* createExecTaskInfo(uint64_t queryId, uint64_t taskId, EOPTR_EXEC_MODEL model) {
wafwerar's avatar
wafwerar 已提交
6730
  SExecTaskInfo* pTaskInfo = taosMemoryCalloc(1, sizeof(SExecTaskInfo));
6731
  setTaskStatus(pTaskInfo, TASK_NOT_COMPLETED);
H
Haojun Liao 已提交
6732

6733
  pTaskInfo->cost.created = taosGetTimestampMs();
H
Haojun Liao 已提交
6734
  pTaskInfo->id.queryId = queryId;
6735
  pTaskInfo->execModel  = model;
H
Haojun Liao 已提交
6736

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

6741 6742
  return pTaskInfo;
}
H
Haojun Liao 已提交
6743

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

L
Liu Jicong 已提交
6747 6748
static int32_t doCreateTableGroup(void* metaHandle, int32_t tableType, uint64_t tableUid, STableGroupInfo* pGroupInfo,
                                  uint64_t queryId, uint64_t taskId);
6749 6750
static SArray* extractTableIdList(const STableGroupInfo* pTableGroupInfo);
static SArray* extractScanColumnId(SNodeList* pNodeList);
H
Haojun Liao 已提交
6751
static SArray* extractColumnInfo(SNodeList* pNodeList);
H
Haojun Liao 已提交
6752
static SArray* extractColMatchInfo(SNodeList* pNodeList, SDataBlockDescNode* pOutputNodeList, int32_t* numOfOutputCols);
6753

6754
static SArray* createSortInfo(SNodeList* pNodeList, SNodeList* pNodeListTarget);
6755
static SArray* createIndexMap(SNodeList* pNodeList);
6756
static SArray* extractPartitionColInfo(SNodeList* pNodeList);
H
Haojun Liao 已提交
6757

H
Haojun Liao 已提交
6758
SOperatorInfo* createOperatorTree(SPhysiNode* pPhyNode, SExecTaskInfo* pTaskInfo, SReadHandle* pHandle,
L
Liu Jicong 已提交
6759
                                        uint64_t queryId, uint64_t taskId, STableGroupInfo* pTableGroupInfo) {
X
Xiaoyu Wang 已提交
6760
  if (pPhyNode->pChildren == NULL || LIST_LENGTH(pPhyNode->pChildren) == 0) {
H
Haojun Liao 已提交
6761 6762
    int32_t type = nodeType(pPhyNode);
    if (QUERY_NODE_PHYSICAL_PLAN_TABLE_SCAN == type) {
X
Xiaoyu Wang 已提交
6763
      SScanPhysiNode* pScanPhyNode = (SScanPhysiNode*)pPhyNode;
H
Haojun Liao 已提交
6764

H
Haojun Liao 已提交
6765
      int32_t     numOfCols = 0;
H
Haojun Liao 已提交
6766 6767
      tsdbReaderT pDataReader = doCreateDataReader((STableScanPhysiNode*)pPhyNode, pHandle, pTableGroupInfo, (uint64_t)queryId, taskId);
      SArray* pColList = extractColMatchInfo(pScanPhyNode->pScanCols, pScanPhyNode->node.pOutputDataBlockDesc, &numOfCols);
6768 6769
      SSDataBlock* pResBlock = createOutputBuf_rv1(pScanPhyNode->node.pOutputDataBlockDesc);

L
Liu Jicong 已提交
6770
      return createTableScanOperatorInfo(pDataReader, pScanPhyNode->order, numOfCols, pScanPhyNode->count,
6771
                                         pScanPhyNode->reverse, pColList, pResBlock, pScanPhyNode->node.pConditions, pTaskInfo);
H
Haojun Liao 已提交
6772
    } else if (QUERY_NODE_PHYSICAL_PLAN_EXCHANGE == type) {
H
Haojun Liao 已提交
6773
      SExchangePhysiNode* pExchange = (SExchangePhysiNode*)pPhyNode;
L
Liu Jicong 已提交
6774
      SSDataBlock*        pResBlock = createOutputBuf_rv1(pExchange->node.pOutputDataBlockDesc);
H
Haojun Liao 已提交
6775
      return createExchangeOperatorInfo(pExchange->pSrcEndPoints, pResBlock, pTaskInfo);
H
Haojun Liao 已提交
6776
    } else if (QUERY_NODE_PHYSICAL_PLAN_STREAM_SCAN == type) {
H
Haojun Liao 已提交
6777
      SScanPhysiNode* pScanPhyNode = (SScanPhysiNode*)pPhyNode;  // simple child table.
6778

6779
      int32_t code = doCreateTableGroup(pHandle->meta, pScanPhyNode->tableType, pScanPhyNode->uid, pTableGroupInfo, queryId, taskId);
H
Haojun Liao 已提交
6780
      SArray* tableIdList = extractTableIdList(pTableGroupInfo);
H
Haojun Liao 已提交
6781

6782
      SSDataBlock* pResBlock = createOutputBuf_rv1(pScanPhyNode->node.pOutputDataBlockDesc);
6783 6784 6785 6786

      int32_t numOfCols = 0;
      SArray* pColList = extractColMatchInfo(pScanPhyNode->pScanCols, pScanPhyNode->node.pOutputDataBlockDesc, &numOfCols);
      SOperatorInfo* pOperator = createStreamScanOperatorInfo(pHandle->reader, pResBlock, pColList, tableIdList, pTaskInfo);
6787
      taosArrayDestroy(tableIdList);
H
Haojun Liao 已提交
6788
      return pOperator;
H
Haojun Liao 已提交
6789
    } else if (QUERY_NODE_PHYSICAL_PLAN_SYSTABLE_SCAN == type) {
L
Liu Jicong 已提交
6790 6791
      SSystemTableScanPhysiNode* pSysScanPhyNode = (SSystemTableScanPhysiNode*)pPhyNode;
      SSDataBlock*               pResBlock = createOutputBuf_rv1(pSysScanPhyNode->scan.node.pOutputDataBlockDesc);
H
Haojun Liao 已提交
6792

6793
      struct SScanPhysiNode* pScanNode = &pSysScanPhyNode->scan;
L
Liu Jicong 已提交
6794
      SArray*                colList = extractScanColumnId(pScanNode->pScanCols);
6795

L
Liu Jicong 已提交
6796 6797 6798
      SOperatorInfo* pOperator = createSysTableScanOperatorInfo(
          pHandle->meta, pResBlock, &pScanNode->tableName, pScanNode->node.pConditions, pSysScanPhyNode->mgmtEpSet,
          colList, pTaskInfo, pSysScanPhyNode->showRewrite, pSysScanPhyNode->accountId);
H
Haojun Liao 已提交
6799 6800 6801
      return pOperator;
    } else {
      ASSERT(0);
H
Haojun Liao 已提交
6802 6803 6804
    }
  }

H
Haojun Liao 已提交
6805 6806 6807
  int32_t type = nodeType(pPhyNode);
  size_t size = LIST_LENGTH(pPhyNode->pChildren);
  ASSERT(size == 1);
H
Haojun Liao 已提交
6808

H
Haojun Liao 已提交
6809 6810
  SPhysiNode*    pChildNode = (SPhysiNode*)nodesListGetNode(pPhyNode->pChildren, 0);
  SOperatorInfo* op = createOperatorTree(pChildNode, pTaskInfo, pHandle, queryId, taskId, pTableGroupInfo);
6811
  int32_t        num = 0;
H
Haojun Liao 已提交
6812

H
Haojun Liao 已提交
6813
  if (QUERY_NODE_PHYSICAL_PLAN_PROJECT == type) {
H
Haojun Liao 已提交
6814 6815 6816
    SProjectPhysiNode* pProjPhyNode = (SProjectPhysiNode*) pPhyNode;
    SExprInfo*   pExprInfo = createExprInfo(pProjPhyNode->pProjections, NULL, &num);

H
Haojun Liao 已提交
6817
    SSDataBlock* pResBlock = createOutputBuf_rv1(pPhyNode->pOutputDataBlockDesc);
H
Haojun Liao 已提交
6818
    SLimit limit = {.limit = pProjPhyNode->limit, .offset = pProjPhyNode->offset};
H
Haojun Liao 已提交
6819 6820
    SLimit slimit = {.limit = pProjPhyNode->slimit, .offset = pProjPhyNode->soffset};
    return createProjectOperatorInfo(op, pExprInfo, num, pResBlock, &limit, &slimit, pTaskInfo);
H
Haojun Liao 已提交
6821 6822 6823 6824
  } else if (QUERY_NODE_PHYSICAL_PLAN_AGG == type) {
    SAggPhysiNode* pAggNode = (SAggPhysiNode*)pPhyNode;
    SExprInfo*     pExprInfo = createExprInfo(pAggNode->pAggFuncs, pAggNode->pGroupKeys, &num);
    SSDataBlock*   pResBlock = createOutputBuf_rv1(pPhyNode->pOutputDataBlockDesc);
H
Haojun Liao 已提交
6825

6826 6827
    SExprInfo* pScalarExprInfo = NULL;
    int32_t numOfScalarExpr = 0;
H
Haojun Liao 已提交
6828 6829
    if (pAggNode->pGroupKeys != NULL) {
      SArray* pColList = extractColumnInfo(pAggNode->pGroupKeys);
6830 6831 6832 6833 6834
      if (pAggNode->pExprs != NULL) {
        pScalarExprInfo = createExprInfo(pAggNode->pExprs, NULL, &numOfScalarExpr);
      }

      return createGroupOperatorInfo(op, pExprInfo, num, pResBlock, pColList, pAggNode->node.pConditions, pScalarExprInfo, numOfScalarExpr, pTaskInfo, NULL);
H
Haojun Liao 已提交
6835 6836
    } else {
      return createAggregateOperatorInfo(op, pExprInfo, num, pResBlock, pTaskInfo, pTableGroupInfo);
H
Haojun Liao 已提交
6837
    }
H
Haojun Liao 已提交
6838 6839
  } else if (QUERY_NODE_PHYSICAL_PLAN_INTERVAL == type) {
    SIntervalPhysiNode* pIntervalPhyNode = (SIntervalPhysiNode*)pPhyNode;
H
Haojun Liao 已提交
6840

H
Haojun Liao 已提交
6841 6842
    SExprInfo*   pExprInfo = createExprInfo(pIntervalPhyNode->window.pFuncs, NULL, &num);
    SSDataBlock* pResBlock = createOutputBuf_rv1(pPhyNode->pOutputDataBlockDesc);
H
Haojun Liao 已提交
6843

H
Haojun Liao 已提交
6844 6845 6846 6847 6848 6849 6850 6851 6852
    SInterval interval = {
        .interval     = pIntervalPhyNode->interval,
        .sliding      = pIntervalPhyNode->sliding,
        .intervalUnit = pIntervalPhyNode->intervalUnit,
        .slidingUnit  = pIntervalPhyNode->slidingUnit,
        .offset       = pIntervalPhyNode->offset,
        .precision    = pIntervalPhyNode->precision
    };

6853
    int32_t primaryTsSlotId = ((SColumnNode*) pIntervalPhyNode->window.pTspk)->slotId;
H
Haojun Liao 已提交
6854 6855
    return createIntervalOperatorInfo(op, pExprInfo, num, pResBlock, &interval, primaryTsSlotId, pTableGroupInfo, pTaskInfo);
  } else if (QUERY_NODE_PHYSICAL_PLAN_SORT == type) {
H
Haojun Liao 已提交
6856
    SSortPhysiNode* pSortPhyNode = (SSortPhysiNode*)pPhyNode;
H
Haojun Liao 已提交
6857

H
Haojun Liao 已提交
6858
    SSDataBlock* pResBlock = createOutputBuf_rv1(pPhyNode->pOutputDataBlockDesc);
6859
    SArray*      info = createSortInfo(pSortPhyNode->pSortKeys, pSortPhyNode->pTargets);
6860 6861
    SArray*      slotMap = createIndexMap(pSortPhyNode->pTargets);
    return createSortOperatorInfo(op, pResBlock, info, slotMap, pTaskInfo);
H
Haojun Liao 已提交
6862
  } else if (QUERY_NODE_PHYSICAL_PLAN_SESSION_WINDOW == type) {
H
Haojun Liao 已提交
6863 6864 6865 6866 6867
    SSessionWinodwPhysiNode* pSessionNode = (SSessionWinodwPhysiNode*)pPhyNode;

    SExprInfo*   pExprInfo = createExprInfo(pSessionNode->window.pFuncs, NULL, &num);
    SSDataBlock* pResBlock = createOutputBuf_rv1(pPhyNode->pOutputDataBlockDesc);
    return createSessionAggOperatorInfo(op, pExprInfo, num, pResBlock, pSessionNode->gap, pTaskInfo);
H
Haojun Liao 已提交
6868 6869
  } else if (QUERY_NODE_PHYSICAL_PLAN_PARTITION == type) {
    SPartitionPhysiNode* pPartNode = (SPartitionPhysiNode*) pPhyNode;
6870
    SArray* pColList = extractPartitionColInfo(pPartNode->pPartitionKeys);
H
Haojun Liao 已提交
6871
    SSDataBlock* pResBlock = createOutputBuf_rv1(pPhyNode->pOutputDataBlockDesc);
6872 6873 6874

    SExprInfo* pExprInfo = createExprInfo(pPartNode->pTargets, NULL, &num);
    return createPartitionOperatorInfo(op, pExprInfo, num, pResBlock, pColList, pTaskInfo, NULL);
6875 6876 6877 6878 6879 6880
  } else if (QUERY_NODE_STATE_WINDOW == type) {
    SStateWinodwPhysiNode* pStateNode = (SStateWinodwPhysiNode*) pPhyNode;

    SExprInfo* pExprInfo = createExprInfo(pStateNode->window.pFuncs, NULL, &num);
    SSDataBlock* pResBlock = createOutputBuf_rv1(pPhyNode->pOutputDataBlockDesc);
    return createStatewindowOperatorInfo(op, pExprInfo, num, pResBlock, pTaskInfo);
H
Haojun Liao 已提交
6881 6882
  } else {
    ASSERT(0);
L
Liu Jicong 已提交
6883 6884 6885 6886 6887 6888
  } /*else if (pPhyNode->info.type == OP_MultiTableAggregate) {
     size_t size = taosArrayGetSize(pPhyNode->pChildren);
     assert(size == 1);

     for (int32_t i = 0; i < size; ++i) {
       SPhysiNode*      pChildNode = taosArrayGetP(pPhyNode->pChildren, i);
H
Haojun Liao 已提交
6889
       SOperatorInfo* op = createOperatorTree(pChildNode, pTaskInfo, pHandle, queryId, taskId, pTableGroupInfo);
L
Liu Jicong 已提交
6890 6891 6892
       return createMultiTableAggOperatorInfo(op, pPhyNode->pTargets, pTaskInfo, pTableGroupInfo);
     }
   }*/
6893
  return NULL;
6894
}
H
Haojun Liao 已提交
6895

L
Liu Jicong 已提交
6896 6897
static tsdbReaderT createDataReaderImpl(STableScanPhysiNode* pTableScanNode, STableGroupInfo* pGroupInfo,
                                        void* readHandle, uint64_t queryId, uint64_t taskId) {
H
Haojun Liao 已提交
6898
  STsdbQueryCond cond = {.loadExternalRows = false};
H
Haojun Liao 已提交
6899

L
Liu Jicong 已提交
6900
  cond.order = pTableScanNode->scan.order;
X
Xiaoyu Wang 已提交
6901
  cond.numOfCols = LIST_LENGTH(pTableScanNode->scan.pScanCols);
L
Liu Jicong 已提交
6902
  cond.colList = taosMemoryCalloc(cond.numOfCols, sizeof(SColumnInfo));
H
Haojun Liao 已提交
6903 6904 6905 6906 6907
  if (cond.colList == NULL) {
    terrno = TSDB_CODE_QRY_OUT_OF_MEMORY;
    return NULL;
  }

X
Xiaoyu Wang 已提交
6908
  cond.twindow = pTableScanNode->scanRange;
H
Haojun Liao 已提交
6909
  cond.type = BLOCK_LOAD_OFFSET_SEQ_ORDER;
L
Liu Jicong 已提交
6910
  //  cond.type = pTableScanNode->scanFlag;
H
Haojun Liao 已提交
6911

H
Haojun Liao 已提交
6912
  int32_t j = 0;
H
Haojun Liao 已提交
6913
  for (int32_t i = 0; i < cond.numOfCols; ++i) {
H
Haojun Liao 已提交
6914 6915
    STargetNode* pNode = (STargetNode*)nodesListGetNode(pTableScanNode->scan.pScanCols, i);
    SColumnNode* pColNode = (SColumnNode*)pNode->pExpr;
H
Haojun Liao 已提交
6916 6917 6918
    if (pColNode->colType == COLUMN_TYPE_TAG) {
      continue;
    }
H
Haojun Liao 已提交
6919

6920
    cond.colList[j].type  = pColNode->node.resType.type;
H
Haojun Liao 已提交
6921 6922 6923
    cond.colList[j].bytes = pColNode->node.resType.bytes;
    cond.colList[j].colId = pColNode->colId;
    j += 1;
H
Haojun Liao 已提交
6924 6925
  }

H
Haojun Liao 已提交
6926
  cond.numOfCols = j;
H
Haojun Liao 已提交
6927
  return tsdbQueryTables(readHandle, &cond, pGroupInfo, queryId, taskId);
H
Haojun Liao 已提交
6928
}
H
Haojun Liao 已提交
6929

6930
SArray* extractScanColumnId(SNodeList* pNodeList) {
L
Liu Jicong 已提交
6931
  size_t  numOfCols = LIST_LENGTH(pNodeList);
6932 6933 6934 6935 6936 6937
  SArray* pList = taosArrayInit(numOfCols, sizeof(int16_t));
  if (pList == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

L
Liu Jicong 已提交
6938
  for (int32_t i = 0; i < numOfCols; ++i) {
X
Xiaoyu Wang 已提交
6939
    for (int32_t j = 0; j < numOfCols; ++j) {
L
Liu Jicong 已提交
6940
      STargetNode* pNode = (STargetNode*)nodesListGetNode(pNodeList, j);
X
Xiaoyu Wang 已提交
6941
      if (pNode->slotId == i) {
L
Liu Jicong 已提交
6942
        SColumnNode* pColNode = (SColumnNode*)pNode->pExpr;
X
Xiaoyu Wang 已提交
6943 6944 6945 6946
        taosArrayPush(pList, &pColNode->colId);
        break;
      }
    }
6947 6948 6949 6950 6951
  }

  return pList;
}

H
Haojun Liao 已提交
6952
SArray* extractColumnInfo(SNodeList* pNodeList) {
L
Liu Jicong 已提交
6953
  size_t  numOfCols = LIST_LENGTH(pNodeList);
H
Haojun Liao 已提交
6954 6955 6956 6957 6958 6959
  SArray* pList = taosArrayInit(numOfCols, sizeof(SColumn));
  if (pList == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

L
Liu Jicong 已提交
6960 6961 6962
  for (int32_t i = 0; i < numOfCols; ++i) {
    STargetNode* pNode = (STargetNode*)nodesListGetNode(pNodeList, i);
    SColumnNode* pColNode = (SColumnNode*)pNode->pExpr;
H
Haojun Liao 已提交
6963

H
Haojun Liao 已提交
6964
    // todo extract method
H
Haojun Liao 已提交
6965 6966
    SColumn c = {0};
    c.slotId = pColNode->slotId;
H
Haojun Liao 已提交
6967 6968 6969
    c.colId  = pColNode->colId;
    c.type   = pColNode->node.resType.type;
    c.bytes  = pColNode->node.resType.bytes;
L
Liu Jicong 已提交
6970 6971
    c.precision = pColNode->node.resType.precision;
    c.scale = pColNode->node.resType.scale;
H
Haojun Liao 已提交
6972 6973 6974 6975 6976 6977 6978

    taosArrayPush(pList, &c);
  }

  return pList;
}

6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004
SArray* extractPartitionColInfo(SNodeList* pNodeList) {
  size_t  numOfCols = LIST_LENGTH(pNodeList);
  SArray* pList = taosArrayInit(numOfCols, sizeof(SColumn));
  if (pList == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

  for (int32_t i = 0; i < numOfCols; ++i) {
    SColumnNode* pColNode = (SColumnNode*)nodesListGetNode(pNodeList, i);

    // todo extract method
    SColumn c = {0};
    c.slotId = pColNode->slotId;
    c.colId  = pColNode->colId;
    c.type   = pColNode->node.resType.type;
    c.bytes  = pColNode->node.resType.bytes;
    c.precision = pColNode->node.resType.precision;
    c.scale = pColNode->node.resType.scale;

    taosArrayPush(pList, &c);
  }

  return pList;
}

7005
SArray* createSortInfo(SNodeList* pNodeList, SNodeList* pNodeListTarget) {
L
Liu Jicong 已提交
7006
  size_t  numOfCols = LIST_LENGTH(pNodeList);
H
Haojun Liao 已提交
7007 7008 7009 7010 7011 7012
  SArray* pList = taosArrayInit(numOfCols, sizeof(SBlockOrderInfo));
  if (pList == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return pList;
  }

L
Liu Jicong 已提交
7013
  for (int32_t i = 0; i < numOfCols; ++i) {
7014
    
7015
    SOrderByExprNode* pSortKey = (SOrderByExprNode*)nodesListGetNode(pNodeList, i);
L
Liu Jicong 已提交
7016 7017
    SBlockOrderInfo   bi = {0};
    bi.order = (pSortKey->order == ORDER_ASC) ? TSDB_ORDER_ASC : TSDB_ORDER_DESC;
H
Haojun Liao 已提交
7018 7019 7020 7021
    bi.nullFirst = (pSortKey->nullOrder == NULL_ORDER_FIRST);

    SColumnNode* pColNode = (SColumnNode*)pSortKey->pExpr;

7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036
    bool found = false;
    for (int32_t j = 0; j < LIST_LENGTH(pNodeListTarget); ++j) {
      STargetNode* pTarget = (STargetNode*)nodesListGetNode(pNodeListTarget, j);

      SColumnNode* pColNodeT = (SColumnNode*)pTarget->pExpr;
      if(pColNode->slotId == pColNodeT->slotId){    // to find slotId in PhysiSort OutputDataBlockDesc
        bi.slotId = pTarget->slotId;
        found = true;
        break;
      }
    }

    if(!found){
      qError("sort slot id does not found");
    }
H
Haojun Liao 已提交
7037 7038 7039 7040 7041 7042
    taosArrayPush(pList, &bi);
  }

  return pList;
}

7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060
SArray* createIndexMap(SNodeList* pNodeList) {
  size_t  numOfCols = LIST_LENGTH(pNodeList);
  SArray* pList = taosArrayInit(numOfCols, sizeof(int32_t));
  if (pList == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return pList;
  }

  for (int32_t i = 0; i < numOfCols; ++i) {
    STargetNode* pTarget = (STargetNode*)nodesListGetNode(pNodeList, i);

    SColumnNode* pColNode = (SColumnNode*)pTarget->pExpr;
    taosArrayPush(pList, &pColNode->slotId);
  }

  return pList;
}

H
Haojun Liao 已提交
7061
SArray* extractColMatchInfo(SNodeList* pNodeList, SDataBlockDescNode* pOutputNodeList, int32_t* numOfOutputCols) {
L
Liu Jicong 已提交
7062
  size_t  numOfCols = LIST_LENGTH(pNodeList);
H
Haojun Liao 已提交
7063 7064 7065 7066 7067 7068
  SArray* pList = taosArrayInit(numOfCols, sizeof(SColMatchInfo));
  if (pList == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

L
Liu Jicong 已提交
7069 7070 7071
  for (int32_t i = 0; i < numOfCols; ++i) {
    STargetNode* pNode = (STargetNode*)nodesListGetNode(pNodeList, i);
    SColumnNode* pColNode = (SColumnNode*)pNode->pExpr;
H
Haojun Liao 已提交
7072 7073

    SColMatchInfo c = {0};
L
Liu Jicong 已提交
7074
    c.colId = pColNode->colId;
H
Haojun Liao 已提交
7075
    c.targetSlotId = pNode->slotId;
L
Liu Jicong 已提交
7076
    c.output = true;
H
Haojun Liao 已提交
7077 7078 7079
    taosArrayPush(pList, &c);
  }

H
Haojun Liao 已提交
7080 7081
  *numOfOutputCols = 0;
  int32_t num = LIST_LENGTH(pOutputNodeList->pSlots);
L
Liu Jicong 已提交
7082 7083
  for (int32_t i = 0; i < num; ++i) {
    SSlotDescNode* pNode = (SSlotDescNode*)nodesListGetNode(pOutputNodeList->pSlots, i);
7084 7085 7086 7087 7088 7089
    // todo: add reserve flag check
    if (pNode->slotId >= numOfCols) { // it is a column reserved for the arithmetic expression calculation
      (*numOfOutputCols) += 1;
      continue;
    }

H
Haojun Liao 已提交
7090
    SColMatchInfo* info = taosArrayGet(pList, pNode->slotId);
H
Haojun Liao 已提交
7091 7092 7093 7094 7095
    if (pNode->output) {
      (*numOfOutputCols) += 1;
    } else {
      info->output = false;
    }
H
Haojun Liao 已提交
7096 7097
  }

H
Haojun Liao 已提交
7098 7099 7100
  return pList;
}

H
Haojun Liao 已提交
7101
int32_t doCreateTableGroup(void* metaHandle, int32_t tableType, uint64_t tableUid, STableGroupInfo* pGroupInfo, uint64_t queryId, uint64_t taskId) {
7102
  int32_t code = 0;
H
Haojun Liao 已提交
7103
  if (tableType == TSDB_SUPER_TABLE) {
H
Haojun Liao 已提交
7104
    code = tsdbQuerySTableByTagCond(metaHandle, tableUid, 0, NULL, 0, 0, NULL, pGroupInfo, NULL, 0, queryId, taskId);
H
Haojun Liao 已提交
7105
  } else {  // Create one table group.
H
Haojun Liao 已提交
7106
    code = tsdbGetOneTableGroup(metaHandle, tableUid, 0, pGroupInfo);
7107 7108 7109 7110
  }

  return code;
}
H
Haojun Liao 已提交
7111

7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129
SArray* extractTableIdList(const STableGroupInfo* pTableGroupInfo) {
  SArray* tableIdList = taosArrayInit(4, sizeof(uint64_t));

  if (pTableGroupInfo->numOfTables > 0) {
    SArray* pa = taosArrayGetP(pTableGroupInfo->pGroupList, 0);
    ASSERT(taosArrayGetSize(pTableGroupInfo->pGroupList) == 1);

    // Transfer the Array of STableKeyInfo into uid list.
    size_t numOfTables = taosArrayGetSize(pa);
    for (int32_t i = 0; i < numOfTables; ++i) {
      STableKeyInfo* pkeyInfo = taosArrayGet(pa, i);
      taosArrayPush(tableIdList, &pkeyInfo->uid);
    }
  }

  return tableIdList;
}

L
Liu Jicong 已提交
7130 7131
tsdbReaderT doCreateDataReader(STableScanPhysiNode* pTableScanNode, SReadHandle* pHandle,
                               STableGroupInfo* pTableGroupInfo, uint64_t queryId, uint64_t taskId) {
7132
  uint64_t uid = pTableScanNode->scan.uid;
L
Liu Jicong 已提交
7133 7134
  int32_t  code =
      doCreateTableGroup(pHandle->meta, pTableScanNode->scan.tableType, uid, pTableGroupInfo, queryId, taskId);
7135 7136
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
H
Haojun Liao 已提交
7137
  }
H
Haojun Liao 已提交
7138

H
Haojun Liao 已提交
7139
  if (pTableGroupInfo->numOfTables == 0) {
H
Haojun Liao 已提交
7140
    code = 0;
L
Liu Jicong 已提交
7141
    qDebug("no table qualified for query, TID:0x%" PRIx64 ", QID:0x%" PRIx64, taskId, queryId);
H
Haojun Liao 已提交
7142 7143
    goto _error;
  }
H
Haojun Liao 已提交
7144

H
Haojun Liao 已提交
7145
  return createDataReaderImpl(pTableScanNode, pTableGroupInfo, pHandle->reader, queryId, taskId);
H
Haojun Liao 已提交
7146

L
Liu Jicong 已提交
7147
_error:
H
Haojun Liao 已提交
7148 7149 7150 7151
  terrno = code;
  return NULL;
}

7152
int32_t createExecTaskInfoImpl(SSubplan* pPlan, SExecTaskInfo** pTaskInfo, SReadHandle* pHandle, uint64_t taskId, EOPTR_EXEC_MODEL model) {
H
Haojun Liao 已提交
7153 7154
  uint64_t queryId = pPlan->id.queryId;

H
Haojun Liao 已提交
7155
  int32_t code = TSDB_CODE_SUCCESS;
7156
  *pTaskInfo = createExecTaskInfo(queryId, taskId, model);
H
Haojun Liao 已提交
7157 7158 7159 7160
  if (*pTaskInfo == NULL) {
    code = TSDB_CODE_QRY_OUT_OF_MEMORY;
    goto _complete;
  }
H
Haojun Liao 已提交
7161

H
Haojun Liao 已提交
7162
  STableGroupInfo group = {0};
H
Haojun Liao 已提交
7163
  (*pTaskInfo)->pRoot = createOperatorTree(pPlan->pNode, *pTaskInfo, pHandle, queryId, taskId, &group);
D
dapan1121 已提交
7164
  if (NULL == (*pTaskInfo)->pRoot) {
L
Liu Jicong 已提交
7165
    code = terrno;
D
dapan1121 已提交
7166 7167
    goto _complete;
  }
H
Haojun Liao 已提交
7168

7169
  if ((*pTaskInfo)->pRoot == NULL) {
H
Haojun Liao 已提交
7170
    code = TSDB_CODE_QRY_OUT_OF_MEMORY;
H
Haojun Liao 已提交
7171
    goto _complete;
7172 7173
  }

H
Haojun Liao 已提交
7174 7175
  return code;

H
Haojun Liao 已提交
7176
_complete:
wafwerar's avatar
wafwerar 已提交
7177
  taosMemoryFreeClear(*pTaskInfo);
H
Haojun Liao 已提交
7178 7179 7180

  terrno = code;
  return code;
H
Haojun Liao 已提交
7181 7182
}

L
Liu Jicong 已提交
7183 7184
static int32_t updateOutputBufForTopBotQuery(SQueriedTableInfo* pTableInfo, SColumnInfo* pTagCols, SExprInfo* pExprs,
                                             int32_t numOfOutput, int32_t tagLen, bool superTable) {
7185 7186 7187 7188 7189 7190 7191 7192 7193
  for (int32_t i = 0; i < numOfOutput; ++i) {
    int16_t functId = getExprFunctionId(&pExprs[i]);

    if (functId == FUNCTION_TOP || functId == FUNCTION_BOTTOM) {
      int32_t j = getColumnIndexInSource(pTableInfo, &pExprs[i].base, pTagCols);
      if (j < 0 || j >= pTableInfo->numOfCols) {
        return TSDB_CODE_QRY_INVALID_MSG;
      } else {
        SColumnInfo* pCol = &pTableInfo->colList[j];
L
Liu Jicong 已提交
7194 7195 7196 7197
        //        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);
7198 7199 7200 7201 7202 7203 7204
      }
    }
  }

  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
7205
void setResultBufSize(STaskAttr* pQueryAttr, SResultInfo* pResultInfo) {
7206 7207 7208 7209 7210 7211 7212 7213
  const int32_t DEFAULT_RESULT_MSG_SIZE = 1024 * (1024 + 512);

  // the minimum number of rows for projection query
  const int32_t MIN_ROWS_FOR_PRJ_QUERY = 8192;
  const int32_t DEFAULT_MIN_ROWS = 4096;

  const float THRESHOLD_RATIO = 0.85f;

H
Haojun Liao 已提交
7214 7215 7216 7217 7218 7219 7220 7221 7222 7223
//  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;
//  }
7224 7225

  pResultInfo->threshold = (int32_t)(pResultInfo->capacity * THRESHOLD_RATIO);
H
Haojun Liao 已提交
7226
  pResultInfo->totalRows = 0;
7227 7228
}

L
Liu Jicong 已提交
7229
// TODO refactor
7230
void freeColumnFilterInfo(SColumnFilterInfo* pFilter, int32_t numOfFilters) {
L
Liu Jicong 已提交
7231 7232 7233
  if (pFilter == NULL || numOfFilters == 0) {
    return;
  }
7234

L
Liu Jicong 已提交
7235 7236 7237
  for (int32_t i = 0; i < numOfFilters; i++) {
    if (pFilter[i].filterstr && pFilter[i].pz) {
      taosMemoryFree((void*)(pFilter[i].pz));
7238
    }
L
Liu Jicong 已提交
7239
  }
7240

L
Liu Jicong 已提交
7241
  taosMemoryFree(pFilter);
7242 7243 7244 7245
}

static void doDestroyTableQueryInfo(STableGroupInfo* pTableqinfoGroupInfo) {
  if (pTableqinfoGroupInfo->pGroupList != NULL) {
L
Liu Jicong 已提交
7246
    int32_t numOfGroups = (int32_t)taosArrayGetSize(pTableqinfoGroupInfo->pGroupList);
7247
    for (int32_t i = 0; i < numOfGroups; ++i) {
L
Liu Jicong 已提交
7248
      SArray* p = taosArrayGetP(pTableqinfoGroupInfo->pGroupList, i);
7249 7250

      size_t num = taosArrayGetSize(p);
L
Liu Jicong 已提交
7251
      for (int32_t j = 0; j < num; ++j) {
7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267
        STableQueryInfo* item = taosArrayGetP(p, j);
        destroyTableQueryInfoImpl(item);
      }

      taosArrayDestroy(p);
    }
  }

  taosArrayDestroy(pTableqinfoGroupInfo->pGroupList);
  taosHashCleanup(pTableqinfoGroupInfo->map);

  pTableqinfoGroupInfo->pGroupList = NULL;
  pTableqinfoGroupInfo->map = NULL;
  pTableqinfoGroupInfo->numOfTables = 0;
}

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

H
Haojun Liao 已提交
7271
  doDestroyTableQueryInfo(&pTaskInfo->tableqinfoGroupInfo);
L
Liu Jicong 已提交
7272 7273
  //  taosArrayDestroy(pTaskInfo->summary.queryProfEvents);
  //  taosHashCleanup(pTaskInfo->summary.operatorProfResults);
7274

wafwerar's avatar
wafwerar 已提交
7275 7276 7277
  taosMemoryFreeClear(pTaskInfo->sql);
  taosMemoryFreeClear(pTaskInfo->id.str);
  taosMemoryFreeClear(pTaskInfo);
7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289
}

static void doSetTagValueToResultBuf(char* output, const char* val, int16_t type, int16_t bytes) {
  if (val == NULL) {
    setNull(output, type, bytes);
    return;
  }

  if (IS_VAR_DATA_TYPE(type)) {
    // Binary data overflows for sort of unknown reasons. Let trim the overflow data
    if (varDataTLen(val) > bytes) {
      int32_t maxLen = bytes - VARSTR_HEADER_SIZE;
L
Liu Jicong 已提交
7290
      int32_t len = (varDataLen(val) > maxLen) ? maxLen : varDataLen(val);
7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302
      memcpy(varDataVal(output), varDataVal(val), len);
      varDataSetLen(output, len);
    } else {
      varDataCopy(output, val);
    }
  } else {
    memcpy(output, val, bytes);
  }
}

static int64_t getQuerySupportBufSize(size_t numOfTables) {
  size_t s1 = sizeof(STableQueryInfo);
L
Liu Jicong 已提交
7303 7304
  //  size_t s3 = sizeof(STableCheckInfo);  buffer consumption in tsdb
  return (int64_t)(s1 * 1.5 * numOfTables);
7305 7306 7307 7308 7309 7310 7311
}

int32_t checkForQueryBuf(size_t numOfTables) {
  int64_t t = getQuerySupportBufSize(numOfTables);
  if (tsQueryBufferSizeBytes < 0) {
    return TSDB_CODE_SUCCESS;
  } else if (tsQueryBufferSizeBytes > 0) {
L
Liu Jicong 已提交
7312
    while (1) {
7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338
      int64_t s = tsQueryBufferSizeBytes;
      int64_t remain = s - t;
      if (remain >= 0) {
        if (atomic_val_compare_exchange_64(&tsQueryBufferSizeBytes, s, remain) == s) {
          return TSDB_CODE_SUCCESS;
        }
      } else {
        return TSDB_CODE_QRY_NOT_ENOUGH_BUFFER;
      }
    }
  }

  // disable query processing if the value of tsQueryBufferSize is zero.
  return TSDB_CODE_QRY_NOT_ENOUGH_BUFFER;
}

void releaseQueryBuf(size_t numOfTables) {
  if (tsQueryBufferSizeBytes < 0) {
    return;
  }

  int64_t t = getQuerySupportBufSize(numOfTables);

  // restore value is not enough buffer available
  atomic_add_fetch_64(&tsQueryBufferSizeBytes, t);
}
D
dapan1121 已提交
7339

D
dapan1121 已提交
7340
int32_t getOperatorExplainExecInfo(SOperatorInfo *operatorInfo, SExplainExecInfo **pRes, int32_t *capacity, int32_t *resNum) {
D
dapan1121 已提交
7341 7342 7343 7344 7345
  if (*resNum >= *capacity) {
    *capacity += 10;
    
    *pRes = taosMemoryRealloc(*pRes, (*capacity) * sizeof(SExplainExecInfo));
    if (NULL == *pRes) {
D
dapan1121 已提交
7346
      qError("malloc %d failed", (*capacity) * (int32_t)sizeof(SExplainExecInfo));
D
dapan1121 已提交
7347 7348 7349 7350
      return TSDB_CODE_QRY_OUT_OF_MEMORY;
    }
  }

D
dapan1121 已提交
7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361
  (*pRes)[*resNum].numOfRows = operatorInfo->resultInfo.totalRows;
  (*pRes)[*resNum].startupCost = operatorInfo->cost.openCost;
  (*pRes)[*resNum].totalCost = operatorInfo->cost.totalCost;

  if (operatorInfo->getExplainFn) {
    int32_t code = (*operatorInfo->getExplainFn)(operatorInfo, &(*pRes)->verboseInfo);
    if (code) {
      qError("operator getExplainFn failed, error:%s", tstrerror(code));
      return code;
    }
  }
D
dapan1121 已提交
7362 7363 7364 7365
  
  ++(*resNum);
  
  int32_t code = 0;
D
dapan1121 已提交
7366 7367
  for (int32_t i = 0; i < operatorInfo->numOfDownstream; ++i) {
    code = getOperatorExplainExecInfo(operatorInfo->pDownstream[i], pRes, capacity, resNum);
D
dapan1121 已提交
7368 7369 7370 7371 7372 7373 7374
    if (code) {
      taosMemoryFreeClear(*pRes);
      return TSDB_CODE_QRY_OUT_OF_MEMORY;
    }
  }

  return TSDB_CODE_SUCCESS;
D
dapan1121 已提交
7375 7376 7377
}