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

H
Haojun Liao 已提交
16 17 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"
37
#include "tsdb.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

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

L
Liu Jicong 已提交
54
#define MULTI_KEY_DELIM "-"
55 56

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

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

H
Haojun Liao 已提交
67

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

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

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

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

#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 已提交
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 149 150
#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) {
151
  assert(pExprInfo != NULL && pExprInfo->pExpr != NULL && pExprInfo->pExpr->nodeType == TEXPR_UNARYEXPR_NODE);
152
  return 0;
153 154
}

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

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

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

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

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

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

  tw->ekey -= 1;
}

static void doSetTagValueToResultBuf(char* output, const char* val, int16_t type, int16_t bytes);
L
Liu Jicong 已提交
189 190 191
void        setResultRowOutputBufInitCtx(STaskRuntimeEnv* pRuntimeEnv, SResultRow* pResult, SqlFunctionCtx* pCtx,
                                         int32_t numOfOutput, int32_t* rowCellInfoOffset);
static bool functionNeedToExecute(SqlFunctionCtx* pCtx);
192

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

L
Liu Jicong 已提交
195 196
static void destroyTableQueryInfoImpl(STableQueryInfo* pTableQueryInfo);
static bool hasMainOutput(STaskAttr* pQueryAttr);
197 198 199

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

L
Liu Jicong 已提交
200 201 202 203
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);
204 205
static STableIdInfo createTableIdInfo(STableQueryInfo* pTableQueryInfo);

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

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 已提交
216

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

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

static void doSetOperatorCompleted(SOperatorInfo* pOperator) {
  pOperator->status = OP_EXEC_DONE;
H
Haojun Liao 已提交
226
  if (pOperator->pTaskInfo != NULL) {
227
    setTaskStatus(pOperator->pTaskInfo, TASK_COMPLETED);
228 229
  }
}
230 231 232
#define OPTR_IS_OPENED(_optr)  (((_optr)->status & OP_OPENED) == OP_OPENED)
#define OPTR_SET_OPENED(_optr) ((_optr)->status |= OP_OPENED)

H
Haojun Liao 已提交
233
int32_t operatorDummyOpenFn(SOperatorInfo* pOperator) {
234
  OPTR_SET_OPENED(pOperator);
H
Haojun Liao 已提交
235
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
236 237
}

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

L
Liu Jicong 已提交
240 241
static int32_t doCopyToSDataBlock(SDiskbasedBuf* pBuf, SGroupResInfo* pGroupResInfo, int32_t orderType,
                                  SSDataBlock* pBlock, int32_t rowCapacity, int32_t* rowCellOffset);
242

L
Liu Jicong 已提交
243 244 245
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 已提交
246

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

H
Haojun Liao 已提交
252
SArray* getOrderCheckColumns(STaskAttr* pQuery);
253 254

typedef struct SRowCompSupporter {
L
Liu Jicong 已提交
255 256 257
  STaskRuntimeEnv* pRuntimeEnv;
  int16_t          dataOffset;
  __compar_fn_t    comFunc;
258 259
} SRowCompSupporter;

L
Liu Jicong 已提交
260 261 262
static int compareRowData(const void* a, const void* b, const void* userData) {
  const SResultRow* pRow1 = (const SResultRow*)a;
  const SResultRow* pRow2 = (const SResultRow*)b;
263

L
Liu Jicong 已提交
264 265
  SRowCompSupporter* supporter = (SRowCompSupporter*)userData;
  STaskRuntimeEnv*   pRuntimeEnv = supporter->pRuntimeEnv;
266

L
Liu Jicong 已提交
267 268
  SFilePage* page1 = getBufPage(pRuntimeEnv->pResultBuf, pRow1->pageId);
  SFilePage* page2 = getBufPage(pRuntimeEnv->pResultBuf, pRow2->pageId);
269 270

  int16_t offset = supporter->dataOffset;
L
Liu Jicong 已提交
271 272
  char*   in1 = getPosInResultPage(pRuntimeEnv->pQueryAttr, page1, pRow1->offset, offset);
  char*   in2 = getPosInResultPage(pRuntimeEnv->pQueryAttr, page2, pRow2->offset, offset);
273 274 275 276

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

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

wafwerar's avatar
wafwerar 已提交
281
  SSDataBlock* pBlock = taosMemoryCalloc(1, sizeof(SSDataBlock));
H
Haojun Liao 已提交
282 283 284
  pBlock->info.numOfCols = numOfCols;
  pBlock->pDataBlock = taosArrayInit(numOfCols, sizeof(SColumnInfoData));

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

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

295
    idata.info.type  = pDescNode->dataType.type;
L
Liu Jicong 已提交
296 297
    idata.info.bytes = pDescNode->dataType.bytes;
    idata.info.scale = pDescNode->dataType.scale;
H
Haojun Liao 已提交
298
    idata.info.slotId = pDescNode->slotId;
H
Haojun Liao 已提交
299 300 301
    idata.info.precision = pDescNode->dataType.precision;

    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;
361
  memset(&pResultRowInfo->pPosition[pResultRowInfo->capacity], 0, sizeof(SResultRowPosition));
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;
}

H
Haojun Liao 已提交
402
#if 0
H
Haojun Liao 已提交
403
static SResultRow* doSetResultOutBufByKey(STaskRuntimeEnv* pRuntimeEnv, SResultRowInfo* pResultRowInfo, int64_t tid,
404 405 406 407
                                          char* pData, int16_t bytes, bool masterscan, uint64_t tableGroupId) {
  bool existed = false;
  SET_RES_WINDOW_KEY(pRuntimeEnv->keyBuf, pData, bytes, tableGroupId);

L
Liu Jicong 已提交
408 409
  SResultRow** p1 =
      (SResultRow**)taosHashGet(pRuntimeEnv->pResultRowHashTable, pRuntimeEnv->keyBuf, GET_RES_WINDOW_KEY_LEN(bytes));
410 411 412 413

  // 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.
L
Liu Jicong 已提交
414
      return (p1 != NULL) ? *p1 : NULL;
415 416 417 418 419
    }

    if (p1 != NULL) {
      if (pResultRowInfo->size == 0) {
        existed = false;
H
Haojun Liao 已提交
420
//        assert(pResultRowInfo->curPos == -1);
421
      } else if (pResultRowInfo->size == 1) {
H
Haojun Liao 已提交
422 423
//        existed = (pResultRowInfo->pResult[0] == (*p1));
//        pResultRowInfo->curPos = 0;
424 425
      } else {  // check if current pResultRowInfo contains the existed pResultRow
        SET_RES_EXT_WINDOW_KEY(pRuntimeEnv->keyBuf, pData, bytes, tid, pResultRowInfo);
L
Liu Jicong 已提交
426 427
        int64_t* index =
            taosHashGet(pRuntimeEnv->pResultRowListSet, pRuntimeEnv->keyBuf, GET_RES_EXT_WINDOW_KEY_LEN(bytes));
428
        if (index != NULL) {
H
Haojun Liao 已提交
429
//          pResultRowInfo->curPos = (int32_t)*index;
430 431 432 433 434 435 436 437 438 439 440 441 442 443
          existed = true;
        } else {
          existed = false;
        }
      }
    }
  } else {
    // In case of group by column query, the required SResultRow object must be existed in the pResultRowInfo object.
    if (p1 != NULL) {
      return *p1;
    }
  }

  if (!existed) {
L
Liu Jicong 已提交
444
    //    prepareResultListBuffer(pResultRowInfo, pRuntimeEnv);
445

L
Liu Jicong 已提交
446
    SResultRow* pResult = NULL;
447 448 449 450 451 452 453 454
    if (p1 == NULL) {
      pResult = getNewResultRow(pRuntimeEnv->pool);
      int32_t ret = initResultRow(pResult);
      if (ret != TSDB_CODE_SUCCESS) {
        longjmp(pRuntimeEnv->env, TSDB_CODE_QRY_OUT_OF_MEMORY);
      }

      // add a new result set for a new group
L
Liu Jicong 已提交
455 456
      taosHashPut(pRuntimeEnv->pResultRowHashTable, pRuntimeEnv->keyBuf, GET_RES_WINDOW_KEY_LEN(bytes), &pResult,
                  POINTER_BYTES);
457 458 459 460 461 462 463 464 465 466 467
      SResultRowCell cell = {.groupId = tableGroupId, .pRow = pResult};
      taosArrayPush(pRuntimeEnv->pResultRowArrayList, &cell);
    } else {
      pResult = *p1;
    }

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

    int64_t index = pResultRowInfo->curPos;
    SET_RES_EXT_WINDOW_KEY(pRuntimeEnv->keyBuf, pData, bytes, tid, pResultRowInfo);
L
Liu Jicong 已提交
468 469
    taosHashPut(pRuntimeEnv->pResultRowListSet, pRuntimeEnv->keyBuf, GET_RES_EXT_WINDOW_KEY_LEN(bytes), &index,
                POINTER_BYTES);
470 471 472 473 474 475 476 477 478
  }

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

  return pResultRowInfo->pResult[pResultRowInfo->curPos];
}
H
Haojun Liao 已提交
479
#endif
480

481
SResultRow* getNewResultRow_rv(SDiskbasedBuf* pResultBuf, int64_t tableGroupId, int32_t interBufSize) {
L
Liu Jicong 已提交
482
  SFilePage* pData = NULL;
483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520

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

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

    if (pData->num + interBufSize + sizeof(SResultRow) > getBufPageSize(pResultBuf)) {
      // release current page first, and prepare the next one
      releaseBufPageInfo(pResultBuf, pi);

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

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

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

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

  return pResultRow;
}

L
Liu Jicong 已提交
521 522 523
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 已提交
524
  bool existInCurrentResusltRowInfo = false;
525
  SET_RES_WINDOW_KEY(pSup->keyBuf, pData, bytes, tableGroupId);
H
Haojun Liao 已提交
526

H
Haojun Liao 已提交
527
  SResultRowPosition* p1 = (SResultRowPosition*)taosHashGet(pSup->pResultRowHashTable, pSup->keyBuf, GET_RES_WINDOW_KEY_LEN(bytes));
H
Haojun Liao 已提交
528 529 530 531

  // 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 已提交
532 533 534 535 536
      if (p1 != NULL) {
        return getResultRowByPos(pResultBuf, p1);
      } else {
        return NULL;
      }
H
Haojun Liao 已提交
537 538 539 540
    }

    if (p1 != NULL) {
      if (pResultRowInfo->size == 0) {
H
Haojun Liao 已提交
541
        existInCurrentResusltRowInfo = false;  // this time window created by other timestamp that does not belongs to current table.
H
Haojun Liao 已提交
542 543
        assert(pResultRowInfo->curPos == -1);
      } else if (pResultRowInfo->size == 1) {
H
Haojun Liao 已提交
544 545 546
        ASSERT(0);
//        existInCurrentResusltRowInfo = (pResultRowInfo->pResult[0] == (*p1));
      } else {  // check if current pResultRowInfo contains the existInCurrentResusltRowInfo pResultRow
547 548
        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 已提交
549
        if (index != NULL) {
H
Haojun Liao 已提交
550 551 552
          // TODO check the scan order for current opened time window
//          pResultRowInfo->curPos = (int32_t)*index;
          existInCurrentResusltRowInfo = true;
H
Haojun Liao 已提交
553
        } else {
H
Haojun Liao 已提交
554
          existInCurrentResusltRowInfo = false;
H
Haojun Liao 已提交
555 556 557 558
        }
      }
    }
  } else {
H
Haojun Liao 已提交
559
    // In case of group by column query, the required SResultRow object must be existInCurrentResusltRowInfo in the pResultRowInfo object.
H
Haojun Liao 已提交
560
    if (p1 != NULL) {
H
Haojun Liao 已提交
561
      return getResultRowByPos(pResultBuf, p1);
H
Haojun Liao 已提交
562 563 564
    }
  }

H
Haojun Liao 已提交
565 566 567 568 569 570 571 572 573 574
  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 已提交
575

H
Haojun Liao 已提交
576
    prepareResultListBuffer(pResultRowInfo, pTaskInfo->env);
H
Haojun Liao 已提交
577
    if (p1 == NULL) {
578
      pResult = getNewResultRow_rv(pResultBuf, tableGroupId, pSup->resultRowSize);
H
Haojun Liao 已提交
579
      initResultRow(pResult);
H
Haojun Liao 已提交
580 581

      // add a new result set for a new group
H
Haojun Liao 已提交
582 583 584
      SResultRowPosition pos = {.pageId = pResult->pageId, .offset = pResult->offset};
      taosHashPut(pSup->pResultRowHashTable, pSup->keyBuf, GET_RES_WINDOW_KEY_LEN(bytes), &pos, POINTER_BYTES);
      SResultRowCell cell = {.groupId = tableGroupId, .pos = pos};
585
      taosArrayPush(pSup->pResultRowArrayList, &cell);
H
Haojun Liao 已提交
586
    } else {
H
Haojun Liao 已提交
587
      pResult = getResultRowByPos(pResultBuf, p1);
H
Haojun Liao 已提交
588 589
    }

H
Haojun Liao 已提交
590
    // 2. set the new time window to be the new active time window
H
Haojun Liao 已提交
591
    pResultRowInfo->curPos = pResultRowInfo->size;
H
Haojun Liao 已提交
592
    pResultRowInfo->pPosition[pResultRowInfo->size++] = (SResultRowPosition){.pageId = pResult->pageId, .offset = pResult->offset};
H
Haojun Liao 已提交
593 594

    int64_t index = pResultRowInfo->curPos;
595 596
    SET_RES_EXT_WINDOW_KEY(pSup->keyBuf, pData, bytes, tid, pResultRowInfo);
    taosHashPut(pSup->pResultRowListSet, pSup->keyBuf, GET_RES_EXT_WINDOW_KEY_LEN(bytes), &index, POINTER_BYTES);
H
Haojun Liao 已提交
597 598 599 600 601 602 603
  }

  // 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 已提交
604
  return pResult;
H
Haojun Liao 已提交
605 606
}

L
Liu Jicong 已提交
607 608
static void getInitialStartTimeWindow(SInterval* pInterval, int32_t precision, TSKEY ts, STimeWindow* w, TSKEY ekey,
                                      bool ascQuery) {
H
Haojun Liao 已提交
609 610
  if (ascQuery) {
    getAlignQueryTimeWindow(pInterval, precision, ts, ts, ekey, w);
611 612
  } else {
    // the start position of the first time window in the endpoint that spreads beyond the queried last timestamp
H
Haojun Liao 已提交
613
    getAlignQueryTimeWindow(pInterval, precision, ts, ekey, ts, w);
614 615

    int64_t key = w->skey;
L
Liu Jicong 已提交
616
    while (key < ts) {  // moving towards end
617
      key = taosTimeAdd(key, pInterval->sliding, pInterval->slidingUnit, precision);
618 619 620 621 622 623 624 625 626 627
      if (key >= ts) {
        break;
      }

      w->skey = key;
    }
  }
}

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

L
Liu Jicong 已提交
632
  if (pResultRowInfo->curPos == -1) {  // the first window, from the previous stored value
H
Haojun Liao 已提交
633
    getInitialStartTimeWindow(pInterval, precision, ts, &w, win->ekey, true);
634
    w.ekey = taosTimeAdd(w.skey, pInterval->interval, pInterval->intervalUnit, precision) - 1;
635
  } else {
H
Haojun Liao 已提交
636
    w = getResultRow(pBuf, pResultRowInfo, pResultRowInfo->curPos)->win;
637 638 639
  }

  if (w.skey > ts || w.ekey < ts) {
H
Haojun Liao 已提交
640 641 642
    if (pInterval->intervalUnit == 'n' || pInterval->intervalUnit == 'y') {
      w.skey = taosTimeTruncate(ts, pInterval, precision);
      w.ekey = taosTimeAdd(w.skey, pInterval->interval, pInterval->intervalUnit, precision) - 1;
643 644 645 646
    } else {
      int64_t st = w.skey;

      if (st > ts) {
H
Haojun Liao 已提交
647
        st -= ((st - ts + pInterval->sliding - 1) / pInterval->sliding) * pInterval->sliding;
648 649
      }

H
Haojun Liao 已提交
650
      int64_t et = st + pInterval->interval - 1;
651
      if (et < ts) {
H
Haojun Liao 已提交
652
        st += ((ts - et + pInterval->sliding - 1) / pInterval->sliding) * pInterval->sliding;
653 654 655
      }

      w.skey = st;
656
      w.ekey = taosTimeAdd(w.skey, pInterval->interval, pInterval->intervalUnit, precision) - 1;
657 658 659 660 661 662
    }
  }
  return w;
}

// get the correct time window according to the handled timestamp
L
Liu Jicong 已提交
663
static STimeWindow getCurrentActiveTimeWindow(SResultRowInfo* pResultRowInfo, int64_t ts, STaskAttr* pQueryAttr) {
664
  STimeWindow w = {0};
H
Haojun Liao 已提交
665
#if 0
L
Liu Jicong 已提交
666 667
  if (pResultRowInfo->curPos == -1) {  // the first window, from the previous stored value
                                       //    getInitialStartTimeWindow(pQueryAttr, ts, &w);
668 669

    if (pQueryAttr->interval.intervalUnit == 'n' || pQueryAttr->interval.intervalUnit == 'y') {
L
Liu Jicong 已提交
670 671 672
      w.ekey =
          taosTimeAdd(w.skey, pQueryAttr->interval.interval, pQueryAttr->interval.intervalUnit, pQueryAttr->precision) -
          1;
673 674 675 676
    } else {
      w.ekey = w.skey + pQueryAttr->interval.interval - 1;
    }
  } else {
H
Haojun Liao 已提交
677
    w = pRow->win;
678 679 680 681 682 683 684 685 686
  }

  /*
   * 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 已提交
687
#endif
688 689 690 691 692

  return w;
}

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

L
Liu Jicong 已提交
698
  SFilePage* pData = NULL;
699 700 701 702 703 704

  // 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 已提交
705
    pData = getNewBufPage(pResultBuf, tid, &pageId);
706
    pData->num = sizeof(SFilePage);
707 708
  } else {
    SPageInfo* pi = getLastPageInfo(list);
709
    pData = getBufPage(pResultBuf, getPageId(pi));
710
    pageId = getPageId(pi);
711

712
    if (pData->num + size > getBufPageSize(pResultBuf)) {
713
      // release current page first, and prepare the next one
714
      releaseBufPageInfo(pResultBuf, pi);
715

H
Haojun Liao 已提交
716
      pData = getNewBufPage(pResultBuf, tid, &pageId);
717
      if (pData != NULL) {
718
        pData->num = sizeof(SFilePage);
719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738
      }
    }
  }

  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 已提交
739 740 741
static bool chkWindowOutputBufByKey(STaskRuntimeEnv* pRuntimeEnv, SResultRowInfo* pResultRowInfo, STimeWindow* win,
                                    bool masterscan, SResultRow** pResult, int64_t groupId, SqlFunctionCtx* pCtx,
                                    int32_t numOfOutput, int32_t* rowCellInfoOffset) {
742
  assert(win->skey <= win->ekey);
L
Liu Jicong 已提交
743
  return chkResultRowFromKey(pRuntimeEnv, pResultRowInfo, (char*)&win->skey, TSDB_KEYSIZE, masterscan, groupId);
744 745
}

L
Liu Jicong 已提交
746 747 748
static int32_t setResultOutputBufByKey(STaskRuntimeEnv* pRuntimeEnv, SResultRowInfo* pResultRowInfo, int64_t tid,
                                       STimeWindow* win, bool masterscan, SResultRow** pResult, int64_t tableGroupId,
                                       SqlFunctionCtx* pCtx, int32_t numOfOutput, int32_t* rowCellInfoOffset) {
749
  assert(win->skey <= win->ekey);
L
Liu Jicong 已提交
750
  SDiskbasedBuf* pResultBuf = pRuntimeEnv->pResultBuf;
751

H
Haojun Liao 已提交
752 753
  SResultRow* pResultRow = NULL;//doSetResultOutBufByKey(pRuntimeEnv, pResultRowInfo, tid, (char*)&win->skey, TSDB_KEYSIZE,
//                                                  masterscan, tableGroupId);
754 755 756 757 758 759 760
  if (pResultRow == NULL) {
    *pResult = NULL;
    return TSDB_CODE_SUCCESS;
  }

  // not assign result buffer yet, add new result buffer
  if (pResultRow->pageId == -1) {
L
Liu Jicong 已提交
761 762
    int32_t ret = addNewWindowResultBuf(pResultRow, pResultBuf, (int32_t)tableGroupId,
                                        pRuntimeEnv->pQueryAttr->intermediateResultRowSize);
763 764 765 766 767 768 769 770 771 772 773 774 775
    if (ret != TSDB_CODE_SUCCESS) {
      return -1;
    }
  }

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

  return TSDB_CODE_SUCCESS;
}

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

L
Liu Jicong 已提交
778 779 780 781
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 已提交
782
  assert(win->skey <= win->ekey);
L
Liu Jicong 已提交
783 784
  SResultRow* pResultRow = doSetResultOutBufByKey_rv(pAggSup->pResultBuf, pResultRowInfo, id, (char*)&win->skey,
                                                     TSDB_KEYSIZE, masterscan, tableGroupId, pTaskInfo, true, pAggSup);
H
Haojun Liao 已提交
785 786 787 788 789 790 791 792 793

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

  // set time window for current result
  pResultRow->win = (*win);
  *pResult = pResultRow;
H
Haojun Liao 已提交
794
  setResultRowOutputBufInitCtx_rv(pResultRow, pCtx, numOfOutput, rowCellInfoOffset);
H
Haojun Liao 已提交
795 796 797
  return TSDB_CODE_SUCCESS;
}

798 799 800 801 802
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 已提交
803
    pResult->endInterp = true;
804 805 806 807 808 809 810 811
  }
}

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 已提交
812
    return pResult->endInterp == true;
813 814 815
  }
}

L
Liu Jicong 已提交
816 817
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) {
818 819 820
  int32_t forwardStep = 0;

  if (order == TSDB_ORDER_ASC) {
L
Liu Jicong 已提交
821
    int32_t end = searchFn((char*)&pData[pos], numOfRows - pos, ekey, order);
822 823 824 825 826 827 828 829
    if (end >= 0) {
      forwardStep = end;

      if (pData[end + pos] == ekey) {
        forwardStep += 1;
      }
    }
  } else {
L
Liu Jicong 已提交
830
    int32_t end = searchFn((char*)pData, pos + 1, ekey, order);
831 832 833 834 835 836 837 838 839 840 841 842 843
    if (end >= 0) {
      forwardStep = pos - end;

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

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

H
Haojun Liao 已提交
844
static void doUpdateResultRowIndex(SResultRowInfo* pResultRowInfo, TSKEY lastKey, bool ascQuery, bool timeWindowInterpo) {
845
  int64_t skey = TSKEY_INITIAL_VAL;
H
Haojun Liao 已提交
846
#if 0
847 848
  int32_t i = 0;
  for (i = pResultRowInfo->size - 1; i >= 0; --i) {
L
Liu Jicong 已提交
849
    SResultRow* pResult = pResultRowInfo->pResult[i];
850 851 852 853 854 855
    if (pResult->closed) {
      break;
    }

    // new closed result rows
    if (timeWindowInterpo) {
L
Liu Jicong 已提交
856 857 858
      if (pResult->endInterp &&
          ((pResult->win.skey <= lastKey && ascQuery) || (pResult->win.skey >= lastKey && !ascQuery))) {
        if (i > 0) {  // the first time window, the startInterp is false.
859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877
          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 已提交
878
      //      assert(pResultRowInfo->current == NULL);
879 880 881 882 883 884 885
      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 已提交
886
      SResultRow* pResult = pResultRowInfo->pResult[i];
887 888 889 890 891 892 893 894 895 896 897
      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 已提交
898
#endif
899 900
}

L
Liu Jicong 已提交
901 902
static void updateResultRowInfoActiveIndex(SResultRowInfo* pResultRowInfo, const STimeWindow* pWin, TSKEY lastKey,
                                           bool ascQuery, bool interp) {
H
Haojun Liao 已提交
903
  if ((lastKey > pWin->ekey && ascQuery) || (lastKey < pWin->ekey && (!ascQuery))) {
904 905 906 907
    closeAllResultRows(pResultRowInfo);
    pResultRowInfo->curPos = pResultRowInfo->size - 1;
  } else {
    int32_t step = ascQuery ? 1 : -1;
H
Haojun Liao 已提交
908
    doUpdateResultRowIndex(pResultRowInfo, lastKey - step, ascQuery, interp);
909 910 911
  }
}

L
Liu Jicong 已提交
912 913 914
static int32_t getNumOfRowsInTimeWindow(SDataBlockInfo* pDataBlockInfo, TSKEY* pPrimaryColumn, int32_t startPos,
                                        TSKEY ekey, __block_search_fn_t searchFn, STableQueryInfo* item,
                                        int32_t order) {
915 916
  assert(startPos >= 0 && startPos < pDataBlockInfo->rows);

L
Liu Jicong 已提交
917 918
  int32_t num = -1;
  int32_t step = GET_FORWARD_DIRECTION_FACTOR(order);
919

H
Haojun Liao 已提交
920
  if (order == TSDB_ORDER_ASC) {
921 922
    if (ekey < pDataBlockInfo->window.ekey && pPrimaryColumn) {
      num = getForwardStepsInBlock(pDataBlockInfo->rows, searchFn, ekey, startPos, order, pPrimaryColumn);
H
Haojun Liao 已提交
923
      if (item != NULL) {
924 925 926 927
        item->lastKey = pPrimaryColumn[startPos + (num - 1)] + step;
      }
    } else {
      num = pDataBlockInfo->rows - startPos;
H
Haojun Liao 已提交
928
      if (item != NULL) {
929 930 931 932 933 934
        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 已提交
935
      if (item != NULL) {
936 937 938 939
        item->lastKey = pPrimaryColumn[startPos - (num - 1)] + step;
      }
    } else {
      num = startPos + 1;
H
Haojun Liao 已提交
940
      if (item != NULL) {
941 942 943 944 945 946 947 948 949
        item->lastKey = pDataBlockInfo->window.skey + step;
      }
    }
  }

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

950 951 952 953 954
//  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 已提交
955
  colInfoDataEnsureCapacity(pColData, 5);
956 957 958 959 960 961 962 963 964
  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);
}

965
static void updateTimeWindowInfo(SColumnInfoData* pColData, STimeWindow* pWin, bool includeEndpoint) {
966
  int64_t* ts = (int64_t*)pColData->pData;
967
  int32_t delta = includeEndpoint? 1:0;
968

969
  int64_t duration = pWin->ekey - pWin->skey + delta;
970 971
  ts[2] = duration;       // set the duration
  ts[3] = pWin->skey;     // window start key
972
  ts[4] = pWin->ekey + delta; // window end key
973 974
}

H
Haojun Liao 已提交
975
void doApplyFunctions(SqlFunctionCtx* pCtx, STimeWindow* pWin, SColumnInfoData* pTimeWindowData, int32_t offset, int32_t forwardStep, TSKEY* tsCol,
976
                             int32_t numOfTotal, int32_t numOfOutput, int32_t order) {
977 978 979 980
  for (int32_t k = 0; k < numOfOutput; ++k) {
    pCtx[k].startTs = pWin->skey;

    // keep it temporarialy
981 982
    bool    hasAgg      = pCtx[k].input.colDataAggIsSet;
    int32_t numOfRows   = pCtx[k].input.numOfRows;
H
Haojun Liao 已提交
983
    int32_t startOffset = pCtx[k].input.startRowIndex;
984

H
Haojun Liao 已提交
985
    int32_t pos = (order == TSDB_ORDER_ASC) ? offset : offset - (forwardStep - 1);
986 987
    pCtx[k].input.startRowIndex = pos;
    pCtx[k].input.numOfRows = forwardStep;
988 989

    if (tsCol != NULL) {
H
Haojun Liao 已提交
990
      pCtx[k].ptsList = tsCol;
991 992 993 994 995 996 997 998
    }

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

999 1000 1001 1002
    if (fmIsWindowPseudoColumnFunc(pCtx[k].functionId)) {
      SResultRowEntryInfo* pEntryInfo = GET_RES_INFO(&pCtx[k]);
      char* p = GET_ROWCELL_INTERBUF(pEntryInfo);

1003 1004 1005 1006 1007 1008 1009 1010
      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);
1011 1012 1013 1014 1015
      pEntryInfo->numOfRes = 1;
      pEntryInfo->hasResult = ',';
      continue;
    }

H
Haojun Liao 已提交
1016
    if (functionNeedToExecute(&pCtx[k])) {
1017
      pCtx[k].fpSet.process(&pCtx[k]);
1018 1019 1020
    }

    // restore it
1021 1022 1023
    pCtx[k].input.colDataAggIsSet = hasAgg;
    pCtx[k].input.startRowIndex = startOffset;
    pCtx[k].input.numOfRows = numOfRows;
1024 1025 1026
  }
}

H
Haojun Liao 已提交
1027 1028 1029
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 已提交
1030
  bool    ascQuery = (order == TSDB_ORDER_ASC);
H
Haojun Liao 已提交
1031

1032
  int32_t precision = pInterval->precision;
H
Haojun Liao 已提交
1033
  getNextTimeWindow(pInterval, precision, order, pNext);
1034 1035

  // next time window is not in current block
H
Haojun Liao 已提交
1036 1037
  if ((pNext->skey > pDataBlockInfo->window.ekey && order == TSDB_ORDER_ASC) ||
      (pNext->ekey < pDataBlockInfo->window.skey && order == TSDB_ORDER_DESC)) {
1038 1039 1040
    return -1;
  }

L
Liu Jicong 已提交
1041
  TSKEY   startKey = ascQuery ? pNext->skey : pNext->ekey;
1042 1043 1044
  int32_t startPos = 0;

  // tumbling time window query, a special case of sliding time window query
H
Haojun Liao 已提交
1045 1046
  if (pInterval->sliding == pInterval->interval && prevPosition != -1) {
    int32_t factor = GET_FORWARD_DIRECTION_FACTOR(order);
1047 1048
    startPos = prevPosition + factor;
  } else {
H
Haojun Liao 已提交
1049
    if (startKey <= pDataBlockInfo->window.skey && ascQuery) {
1050
      startPos = 0;
H
Haojun Liao 已提交
1051
    } else if (startKey >= pDataBlockInfo->window.ekey && !ascQuery) {
1052 1053
      startPos = pDataBlockInfo->rows - 1;
    } else {
L
Liu Jicong 已提交
1054
      startPos = binarySearchForKey((char*)primaryKeys, pDataBlockInfo->rows, startKey, order);
1055 1056 1057 1058
    }
  }

  /* interp query with fill should not skip time window */
L
Liu Jicong 已提交
1059 1060 1061
  //  if (pQueryAttr->pointInterpQuery && pQueryAttr->fillType != TSDB_FILL_NONE) {
  //    return startPos;
  //  }
1062 1063 1064 1065 1066 1067

  /*
   * 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 已提交
1068
    if (ascQuery) {
1069 1070 1071 1072 1073
      assert(pDataBlockInfo->window.skey <= pNext->ekey);
    } else {
      assert(pDataBlockInfo->window.ekey >= pNext->skey);
    }
  } else {
H
Haojun Liao 已提交
1074
    if (ascQuery && primaryKeys[startPos] > pNext->ekey) {
1075
      TSKEY next = primaryKeys[startPos];
H
Haojun Liao 已提交
1076 1077 1078
      if (pInterval->intervalUnit == 'n' || pInterval->intervalUnit == 'y') {
        pNext->skey = taosTimeTruncate(next, pInterval, precision);
        pNext->ekey = taosTimeAdd(pNext->skey, pInterval->interval, pInterval->intervalUnit, precision) - 1;
1079
      } else {
L
Liu Jicong 已提交
1080
        pNext->ekey += ((next - pNext->ekey + pInterval->sliding - 1) / pInterval->sliding) * pInterval->sliding;
H
Haojun Liao 已提交
1081
        pNext->skey = pNext->ekey - pInterval->interval + 1;
1082
      }
H
Haojun Liao 已提交
1083
    } else if ((!ascQuery) && primaryKeys[startPos] < pNext->skey) {
1084
      TSKEY next = primaryKeys[startPos];
H
Haojun Liao 已提交
1085 1086 1087
      if (pInterval->intervalUnit == 'n' || pInterval->intervalUnit == 'y') {
        pNext->skey = taosTimeTruncate(next, pInterval, precision);
        pNext->ekey = taosTimeAdd(pNext->skey, pInterval->interval, pInterval->intervalUnit, precision) - 1;
1088
      } else {
H
Haojun Liao 已提交
1089 1090
        pNext->skey -= ((pNext->skey - next + pInterval->sliding - 1) / pInterval->sliding) * pInterval->sliding;
        pNext->ekey = pNext->skey + pInterval->interval - 1;
1091 1092 1093 1094 1095 1096 1097
      }
    }
  }

  return startPos;
}

L
Liu Jicong 已提交
1098
static FORCE_INLINE TSKEY reviseWindowEkey(STaskAttr* pQueryAttr, STimeWindow* pWindow) {
1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114
  TSKEY ekey = -1;
  if (QUERY_IS_ASC_QUERY(pQueryAttr)) {
    ekey = pWindow->ekey;
    if (ekey > pQueryAttr->window.ekey) {
      ekey = pQueryAttr->window.ekey;
    }
  } else {
    ekey = pWindow->skey;
    if (ekey < pQueryAttr->window.ekey) {
      ekey = pQueryAttr->window.ekey;
    }
  }

  return ekey;
}

H
Haojun Liao 已提交
1115
static void setNotInterpoWindowKey(SqlFunctionCtx* pCtx, int32_t numOfOutput, int32_t type) {
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126
  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 已提交
1127
static void saveDataBlockLastRow(char** pRow, SArray* pDataBlock, int32_t rowIndex, int32_t numOfCols) {
1128 1129 1130 1131
  if (pDataBlock == NULL) {
    return;
  }

H
Haojun Liao 已提交
1132
  for (int32_t k = 0; k < numOfCols; ++k) {
L
Liu Jicong 已提交
1133
    SColumnInfoData* pColInfo = taosArrayGet(pDataBlock, k);
H
Haojun Liao 已提交
1134
    memcpy(pRow[k], ((char*)pColInfo->pData) + (pColInfo->info.bytes * rowIndex), pColInfo->info.bytes);
1135 1136 1137
  }
}

H
Haojun Liao 已提交
1138
static TSKEY getStartTsKey(STimeWindow* win, const TSKEY* tsCols, int32_t rows, bool ascQuery) {
1139 1140
  TSKEY ts = TSKEY_INITIAL_VAL;
  if (tsCols == NULL) {
L
Liu Jicong 已提交
1141
    ts = ascQuery ? win->skey : win->ekey;
1142
  } else {
L
Liu Jicong 已提交
1143
    int32_t offset = ascQuery ? 0 : rows - 1;
1144 1145 1146 1147 1148 1149
    ts = tsCols[offset];
  }

  return ts;
}

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

L
Liu Jicong 已提交
1152 1153
static void doSetInputDataBlockInfo(SOperatorInfo* pOperator, SqlFunctionCtx* pCtx, SSDataBlock* pBlock,
                                    int32_t order) {
1154 1155
  for (int32_t i = 0; i < pOperator->numOfOutput; ++i) {
    pCtx[i].order = order;
L
Liu Jicong 已提交
1156
    pCtx[i].size = pBlock->info.rows;
1157 1158
    pCtx[i].currentStage = (uint8_t)pOperator->pRuntimeEnv->scanFlag;

L
Liu Jicong 已提交
1159
    setBlockStatisInfo(&pCtx[i], pBlock, NULL /*&pOperator->pExpr[i].base.colInfo*/);
1160 1161 1162
  }
}

H
Haojun Liao 已提交
1163
void setInputDataBlock(SOperatorInfo* pOperator, SqlFunctionCtx* pCtx, SSDataBlock* pBlock, int32_t order) {
H
Haojun Liao 已提交
1164 1165 1166 1167 1168
  if (pBlock->pDataBlock != NULL) {
    doSetInputDataBlock(pOperator, pCtx, pBlock, order);
  } else {
    doSetInputDataBlockInfo(pOperator, pCtx, pBlock, order);
  }
1169 1170
}

H
Haojun Liao 已提交
1171
static void doSetInputDataBlock(SOperatorInfo* pOperator, SqlFunctionCtx* pCtx, SSDataBlock* pBlock, int32_t order) {
1172 1173
  for (int32_t i = 0; i < pOperator->numOfOutput; ++i) {
    pCtx[i].order = order;
L
Liu Jicong 已提交
1174
    pCtx[i].size = pBlock->info.rows;
H
Haojun Liao 已提交
1175 1176
    pCtx[i].currentStage = MAIN_SCAN;

G
Ganlin Zhao 已提交
1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188
    SExprInfo expr = pOperator->pExpr[i];
    for (int32_t j = 0; j < expr.base.numOfParams; ++j) {
      SFunctParam *pFuncParam = &expr.base.pParam[j];
      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 已提交
1189

H
Haojun Liao 已提交
1190
    //    setBlockStatisInfo(&pCtx[i], pBlock, pOperator->pExpr[i].base.pColumns);
H
Haojun Liao 已提交
1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206
    //      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 已提交
1207 1208 1209 1210
    //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 已提交
1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238


    //        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) {
1239
  for (int32_t k = 0; k < pOperator->numOfOutput; ++k) {
H
Haojun Liao 已提交
1240
    if (functionNeedToExecute(&pCtx[k])) {
L
Liu Jicong 已提交
1241
      pCtx[k].startTs = startTs;  // this can be set during create the struct
H
Haojun Liao 已提交
1242
      pCtx[k].fpSet.process(&pCtx[k]);
1243 1244 1245 1246
    }
  }
}

H
Haojun Liao 已提交
1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257
static void setPseudoOutputColInfo(SSDataBlock* pResult, SqlFunctionCtx* pCtx, SArray* pPseudoList) {
  size_t num = 0;
  if (pPseudoList != NULL) {
    num = taosArrayGetSize(pPseudoList);
  }

  for (int32_t i = 0; i < num; ++i) {
    pCtx[i].pOutput = taosArrayGet(pResult->pDataBlock, i);
  }
}

L
Liu Jicong 已提交
1258
static void projectApplyFunctions(SExprInfo* pExpr, SSDataBlock* pResult, SSDataBlock* pSrcBlock, SqlFunctionCtx* pCtx,
H
Haojun Liao 已提交
1259 1260 1261
                                  int32_t numOfOutput, SArray* pPseudoList) {
  setPseudoOutputColInfo(pResult, pCtx, pPseudoList);

1262
  for (int32_t k = 0; k < numOfOutput; ++k) {
L
Liu Jicong 已提交
1263
    if (pExpr[k].pExpr->nodeType == QUERY_NODE_COLUMN) {  // it is a project query
H
Haojun Liao 已提交
1264
      SColumnInfoData* pColInfoData = taosArrayGet(pResult->pDataBlock, k);
1265
      colDataAssign(pColInfoData, pCtx[k].input.pData[0], pCtx[k].input.numOfRows);
1266 1267

      pResult->info.rows = pCtx[0].input.numOfRows;
H
Haojun Liao 已提交
1268
    } else if (pExpr[k].pExpr->nodeType == QUERY_NODE_OPERATOR) {
1269 1270 1271
      SArray* pBlockList = taosArrayInit(4, POINTER_BYTES);
      taosArrayPush(pBlockList, &pSrcBlock);

1272 1273 1274 1275 1276 1277 1278 1279
      SScalarParam dest = {0};
      dest.columnData = taosArrayGet(pResult->pDataBlock, k);

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

      taosArrayDestroy(pBlockList);
    } else if (pExpr[k].pExpr->nodeType == QUERY_NODE_FUNCTION) {
H
Haojun Liao 已提交
1280
      ASSERT(!fmIsAggFunc(pCtx[k].functionId));
1281

H
Haojun Liao 已提交
1282
      if (fmIsPseudoColumnFunc(pCtx[k].functionId)) {
H
Haojun Liao 已提交
1283
        // do nothing
H
Haojun Liao 已提交
1284
      } else if (fmIsNonstandardSQLFunc(pCtx[k].functionId)) {
H
Haojun Liao 已提交
1285 1286
        // todo set the correct timestamp column
        pCtx[k].input.pPTS = taosArrayGet(pSrcBlock->pDataBlock, 1);
1287

H
Haojun Liao 已提交
1288 1289
        SResultRowEntryInfo *pResInfo = GET_RES_INFO(&pCtx[k]);
        pCtx[k].fpSet.init(&pCtx[k], pResInfo);
1290

H
Haojun Liao 已提交
1291 1292 1293 1294 1295 1296
        pCtx[k].pOutput = taosArrayGet(pResult->pDataBlock, k);
        pCtx[k].offset  = pResult->info.rows;  // set the start offset

        int32_t* outputColIndex = taosArrayGet(pPseudoList, 0);
        pCtx[k].pTsOutput = (SColumnInfoData*)pCtx[*outputColIndex].pOutput;

H
Haojun Liao 已提交
1297
        int32_t numOfRows = pCtx[k].fpSet.process(&pCtx[k]);
H
Haojun Liao 已提交
1298
        pResult->info.rows += numOfRows;
H
Haojun Liao 已提交
1299 1300 1301
      } else {
        SArray* pBlockList = taosArrayInit(4, POINTER_BYTES);
        taosArrayPush(pBlockList, &pSrcBlock);
G
Ganlin Zhao 已提交
1302

H
Haojun Liao 已提交
1303 1304 1305 1306 1307 1308 1309
        SScalarParam dest = {0};
        dest.columnData = taosArrayGet(pResult->pDataBlock, k);

        scalarCalculate((SNode*)pExpr[k].pExpr->_function.pFunctNode, pBlockList, &dest);
        pResult->info.rows = dest.numOfRows;
        taosArrayDestroy(pBlockList);
      }
1310
    } else {
1311
      ASSERT(0);
1312 1313 1314 1315 1316 1317
    }
  }
}

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 已提交
1318 1319
  STaskRuntimeEnv* pRuntimeEnv = pOperator->pRuntimeEnv;
  SExprInfo*       pExpr = pOperator->pExpr;
1320

H
Haojun Liao 已提交
1321
  SqlFunctionCtx* pCtx = pInfo->pCtx;
1322 1323 1324 1325 1326 1327 1328 1329

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

L
Liu Jicong 已提交
1334
    //    assert(pColInfo->info.colId == pColIndex->info.colId && curTs != windowKey);
1335 1336 1337
    double v1 = 0, v2 = 0, v = 0;

    if (prevRowIndex == -1) {
L
Liu Jicong 已提交
1338
      GET_TYPED_DATA(v1, double, pColInfo->info.type, (char*)pRuntimeEnv->prevRow[index]);
1339
    } else {
L
Liu Jicong 已提交
1340
      GET_TYPED_DATA(v1, double, pColInfo->info.type, (char*)pColInfo->pData + prevRowIndex * pColInfo->info.bytes);
1341 1342
    }

L
Liu Jicong 已提交
1343
    GET_TYPED_DATA(v2, double, pColInfo->info.type, (char*)pColInfo->pData + curRowIndex * pColInfo->info.bytes);
1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354

    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 已提交
1355
            pCtx[k].start.ptr = (char*)pRuntimeEnv->prevRow[index];
1356
          } else {
L
Liu Jicong 已提交
1357
            pCtx[k].start.ptr = (char*)pColInfo->pData + prevRowIndex * pColInfo->info.bytes;
1358 1359
          }

L
Liu Jicong 已提交
1360
          pCtx[k].end.ptr = (char*)pColInfo->pData + curRowIndex * pColInfo->info.bytes;
1361 1362 1363
        }
      }
    } else if (functionId == FUNCTION_TWA) {
L
Liu Jicong 已提交
1364 1365 1366
      SPoint point1 = (SPoint){.key = prevTs, .val = &v1};
      SPoint point2 = (SPoint){.key = curTs, .val = &v2};
      SPoint point = (SPoint){.key = windowKey, .val = &v};
1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380

      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 已提交
1381
static bool setTimeWindowInterpolationStartTs(SOperatorInfo* pOperatorInfo, SqlFunctionCtx* pCtx, int32_t pos,
H
Haojun Liao 已提交
1382 1383
                                              int32_t numOfRows, SArray* pDataBlock, const TSKEY* tsCols, STimeWindow* win) {
  bool  ascQuery = true;
L
Liu Jicong 已提交
1384
  TSKEY curTs = tsCols[pos];
H
Haojun Liao 已提交
1385
  TSKEY lastTs = 0;//*(TSKEY*)pRuntimeEnv->prevRow[0];
1386 1387 1388

  // 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 已提交
1389
  TSKEY key = ascQuery ? win->skey : win->ekey;
1390 1391 1392 1393 1394 1395 1396 1397 1398 1399
  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 已提交
1400
  int32_t step = 1;//GET_FORWARD_DIRECTION_FACTOR(pQueryAttr->order.order);
L
Liu Jicong 已提交
1401
  TSKEY   prevTs = ((pos == 0 && ascQuery) || (pos == (numOfRows - 1) && !ascQuery)) ? lastTs : tsCols[pos - step];
1402

H
Haojun Liao 已提交
1403
  doTimeWindowInterpolation(pOperatorInfo, pOperatorInfo->info, pDataBlock, prevTs, pos - step, curTs, pos, key, RESULT_ROW_START_INTERP);
1404 1405 1406
  return true;
}

L
Liu Jicong 已提交
1407 1408 1409
static bool setTimeWindowInterpolationEndTs(SOperatorInfo* pOperatorInfo, SqlFunctionCtx* pCtx, int32_t endRowIndex,
                                            SArray* pDataBlock, const TSKEY* tsCols, TSKEY blockEkey,
                                            STimeWindow* win) {
H
Haojun Liao 已提交
1410 1411
  int32_t order = TSDB_ORDER_ASC;
  int32_t numOfOutput = pOperatorInfo->numOfOutput;
1412

L
Liu Jicong 已提交
1413
  TSKEY actualEndKey = tsCols[endRowIndex];
H
Haojun Liao 已提交
1414
  TSKEY key = order ? win->ekey : win->skey;
1415 1416

  // not ended in current data block, do not invoke interpolation
H
Haojun Liao 已提交
1417
  if ((key > blockEkey /*&& QUERY_IS_ASC_QUERY(pQueryAttr)*/) || (key < blockEkey /*&& !QUERY_IS_ASC_QUERY(pQueryAttr)*/)) {
1418 1419 1420 1421 1422 1423 1424 1425 1426 1427
    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 已提交
1428
  int32_t step = GET_FORWARD_DIRECTION_FACTOR(order);
1429 1430 1431 1432 1433
  int32_t nextRowIndex = endRowIndex + step;
  assert(nextRowIndex >= 0);

  TSKEY nextKey = tsCols[nextRowIndex];
  doTimeWindowInterpolation(pOperatorInfo, pOperatorInfo->info, pDataBlock, actualEndKey, endRowIndex, nextKey,
L
Liu Jicong 已提交
1434
                            nextRowIndex, key, RESULT_ROW_END_INTERP);
1435 1436 1437
  return true;
}

H
Haojun Liao 已提交
1438
static void doWindowBorderInterpolation(SOperatorInfo* pOperatorInfo, SSDataBlock* pBlock, SqlFunctionCtx* pCtx,
L
Liu Jicong 已提交
1439 1440
                                        SResultRow* pResult, STimeWindow* win, int32_t startPos, int32_t forwardStep,
                                        int32_t order, bool timeWindowInterpo) {
H
Haojun Liao 已提交
1441
  if (!timeWindowInterpo) {
1442 1443 1444 1445
    return;
  }

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

L
Liu Jicong 已提交
1448 1449
  if (pBlock->pDataBlock == NULL) {
    //    tscError("pBlock->pDataBlock == NULL");
1450 1451
    return;
  }
H
Haojun Liao 已提交
1452

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

L
Liu Jicong 已提交
1455 1456 1457
  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
1458
    int32_t startRowIndex = startPos;
L
Liu Jicong 已提交
1459 1460
    bool    interp = setTimeWindowInterpolationStartTs(pOperatorInfo, pCtx, startRowIndex, pBlock->info.rows,
                                                       pBlock->pDataBlock, tsCols, win);
1461 1462 1463 1464
    if (interp) {
      setResultRowInterpo(pResult, RESULT_ROW_START_INTERP);
    }
  } else {
H
Haojun Liao 已提交
1465
    setNotInterpoWindowKey(pCtx, pOperatorInfo->numOfOutput, RESULT_ROW_START_INTERP);
1466 1467 1468
  }

  // point interpolation does not require the end key time window interpolation.
L
Liu Jicong 已提交
1469 1470 1471
  //  if (pointInterpQuery) {
  //    return;
  //  }
1472 1473 1474 1475 1476 1477

  // 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 已提交
1478 1479 1480
    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);
1481 1482 1483 1484
    if (interp) {
      setResultRowInterpo(pResult, RESULT_ROW_END_INTERP);
    }
  } else {
H
Haojun Liao 已提交
1485
    setNotInterpoWindowKey(pCtx, pOperatorInfo->numOfOutput, RESULT_ROW_END_INTERP);
1486 1487 1488
  }
}

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

H
Haojun Liao 已提交
1492
  SExecTaskInfo* pTaskInfo = pOperatorInfo->pTaskInfo;
L
Liu Jicong 已提交
1493
  int32_t        numOfOutput = pOperatorInfo->numOfOutput;
1494

1495 1496 1497 1498 1499
  SArray* pUpdated = NULL;
  if (pInfo->execModel == OPTR_EXEC_MODEL_STREAM) {
    pUpdated = taosArrayInit(4, sizeof(SResultRowPosition));
  }

H
Haojun Liao 已提交
1500
  int32_t step = 1;
1501
  bool    ascScan = true;
1502 1503 1504 1505 1506 1507

  int32_t prevIndex = pResultRowInfo->curPos;

  TSKEY* tsCols = NULL;
  if (pSDataBlock->pDataBlock != NULL) {
    SColumnInfoData* pColDataInfo = taosArrayGet(pSDataBlock->pDataBlock, 0);
L
Liu Jicong 已提交
1508
    tsCols = (int64_t*)pColDataInfo->pData;
H
Haojun Liao 已提交
1509 1510
//    assert(tsCols[0] == pSDataBlock->info.window.skey && tsCols[pSDataBlock->info.rows - 1] ==
//           pSDataBlock->info.window.ekey);
1511 1512
  }

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

H
Haojun Liao 已提交
1516
  STimeWindow win = getActiveTimeWindow(pInfo->aggSup.pResultBuf, pResultRowInfo, ts, &pInfo->interval, pInfo->interval.precision, &pInfo->win);
L
Liu Jicong 已提交
1517
  bool        masterScan = true;
1518 1519

  SResultRow* pResult = NULL;
L
Liu Jicong 已提交
1520 1521 1522
  int32_t     ret = setResultOutputBufByKey_rv(pResultRowInfo, pSDataBlock->info.uid, &win, masterScan, &pResult,
                                               tableGroupId, pInfo->binfo.pCtx, numOfOutput, pInfo->binfo.rowCellInfoOffset,
                                               &pInfo->aggSup, pTaskInfo);
1523
  if (ret != TSDB_CODE_SUCCESS || pResult == NULL) {
H
Haojun Liao 已提交
1524
    longjmp(pTaskInfo->env, TSDB_CODE_QRY_OUT_OF_MEMORY);
1525 1526
  }

1527 1528 1529 1530 1531
  if (pInfo->execModel == OPTR_EXEC_MODEL_STREAM) {
    SResultRowPosition pos = {.pageId = pResult->pageId, .offset = pResult->offset};
    taosArrayPush(pUpdated, &pos);
  }

1532
  int32_t forwardStep = 0;
H
Haojun Liao 已提交
1533
  TSKEY   ekey = win.ekey;
1534
  forwardStep =
H
Haojun Liao 已提交
1535
      getNumOfRowsInTimeWindow(&pSDataBlock->info, tsCols, startPos, ekey, binarySearchForKey, NULL, TSDB_ORDER_ASC);
1536 1537 1538

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

#if 0
H
Haojun Liao 已提交
1541
  if (prevIndex != -1 && prevIndex < curIndex && pInfo->timeWindowInterpo) {
1542 1543 1544
    for (int32_t j = prevIndex; j < curIndex; ++j) {  // previous time window may be all closed already.
      SResultRow* pRes = getResultRow(pResultRowInfo, j);
      if (pRes->closed) {
1545
        assert(resultRowInterpolated(pRes, RESULT_ROW_START_INTERP) && resultRowInterpolated(pRes, RESULT_ROW_END_INTERP));
1546 1547 1548
        continue;
      }

L
Liu Jicong 已提交
1549 1550 1551 1552 1553 1554 1555
      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);
      }
1556

L
Liu Jicong 已提交
1557 1558 1559
      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);
1560

L
Liu Jicong 已提交
1561 1562
      setResultRowInterpo(pResult, RESULT_ROW_END_INTERP);
      setNotInterpoWindowKey(pInfo->binfo.pCtx, pOperatorInfo->numOfOutput, RESULT_ROW_START_INTERP);
1563

1564
      doApplyFunctions(pInfo->binfo.pCtx, &w, &pInfo->timeWindowData, startPos, 0, tsCols, pSDataBlock->info.rows, numOfOutput, TSDB_ORDER_ASC);
L
Liu Jicong 已提交
1565
    }
1566 1567

    // restore current time window
L
Liu Jicong 已提交
1568 1569 1570
    ret = setResultOutputBufByKey_rv(pResultRowInfo, pSDataBlock->info.uid, &win, masterScan, &pResult, tableGroupId,
                                     pInfo->binfo.pCtx, numOfOutput, pInfo->binfo.rowCellInfoOffset, &pInfo->aggSup,
                                     pTaskInfo);
1571
    if (ret != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
1572
      longjmp(pTaskInfo->env, TSDB_CODE_QRY_OUT_OF_MEMORY);
1573 1574
    }
  }
H
Haojun Liao 已提交
1575
#endif
1576 1577

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

  updateTimeWindowInfo(&pInfo->timeWindowData, &win, true);
1581
  doApplyFunctions(pInfo->binfo.pCtx, &win, &pInfo->timeWindowData, startPos, forwardStep, tsCols, pSDataBlock->info.rows, numOfOutput, TSDB_ORDER_ASC);
1582 1583 1584 1585

  STimeWindow nextWin = win;
  while (1) {
    int32_t prevEndPos = (forwardStep - 1) * step + startPos;
H
Haojun Liao 已提交
1586
    startPos = getNextQualifiedWindow(&pInfo->interval, &nextWin, &pSDataBlock->info, tsCols, prevEndPos, pInfo);
1587 1588 1589 1590 1591
    if (startPos < 0) {
      break;
    }

    // null data, failed to allocate more memory buffer
L
Liu Jicong 已提交
1592 1593 1594
    int32_t code = setResultOutputBufByKey_rv(pResultRowInfo, pSDataBlock->info.uid, &nextWin, masterScan, &pResult,
                                              tableGroupId, pInfo->binfo.pCtx, numOfOutput,
                                              pInfo->binfo.rowCellInfoOffset, &pInfo->aggSup, pTaskInfo);
1595
    if (code != TSDB_CODE_SUCCESS || pResult == NULL) {
H
Haojun Liao 已提交
1596
      longjmp(pTaskInfo->env, TSDB_CODE_QRY_OUT_OF_MEMORY);
1597 1598
    }

1599 1600 1601 1602 1603
    if (pInfo->execModel == OPTR_EXEC_MODEL_STREAM) {
      SResultRowPosition pos = {.pageId = pResult->pageId, .offset = pResult->offset};
      taosArrayPush(pUpdated, &pos);
    }

L
Liu Jicong 已提交
1604 1605 1606
    ekey = nextWin.ekey;  // reviseWindowEkey(pQueryAttr, &nextWin);
    forwardStep =
        getNumOfRowsInTimeWindow(&pSDataBlock->info, tsCols, startPos, ekey, binarySearchForKey, NULL, TSDB_ORDER_ASC);
1607 1608

    // window start(end) key interpolation
1609 1610 1611
    doWindowBorderInterpolation(pOperatorInfo, pSDataBlock, pInfo->binfo.pCtx, pResult, &nextWin, startPos, forwardStep, pInfo->order, false);

    updateTimeWindowInfo(&pInfo->timeWindowData, &win, true);
1612
    doApplyFunctions(pInfo->binfo.pCtx, &nextWin, &pInfo->timeWindowData, startPos, forwardStep, tsCols, pSDataBlock->info.rows, numOfOutput, TSDB_ORDER_ASC);
1613 1614
  }

H
Haojun Liao 已提交
1615
  if (pInfo->timeWindowInterpo) {
1616
    int32_t rowIndex = ascScan ? (pSDataBlock->info.rows - 1) : 0;
H
Haojun Liao 已提交
1617
    saveDataBlockLastRow(pInfo->pRow, pSDataBlock->pDataBlock, rowIndex, pSDataBlock->info.numOfCols);
1618 1619
  }

1620
  return pUpdated;
L
Liu Jicong 已提交
1621
  //  updateResultRowInfoActiveIndex(pResultRowInfo, &pInfo->win, pRuntimeEnv->current->lastKey, true, false);
1622 1623
}

L
Liu Jicong 已提交
1624 1625 1626
static void hashAllIntervalAgg(SOperatorInfo* pOperatorInfo, SResultRowInfo* pResultRowInfo, SSDataBlock* pSDataBlock,
                               int32_t tableGroupId) {
  STableIntervalOperatorInfo* pInfo = (STableIntervalOperatorInfo*)pOperatorInfo->info;
1627

H
Haojun Liao 已提交
1628
  STaskRuntimeEnv* pRuntimeEnv = pOperatorInfo->pRuntimeEnv;
L
Liu Jicong 已提交
1629
  int32_t          numOfOutput = pOperatorInfo->numOfOutput;
1630

H
Haojun Liao 已提交
1631 1632
  int32_t step = 1;//GET_FORWARD_DIRECTION_FACTOR(pQueryAttr->order.order);
  bool    ascQuery = true;
1633 1634 1635 1636

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

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

H
Haojun Liao 已提交
1645
  STimeWindow win = {0};//getCurrentActiveTimeWindow(pResultRowInfo, ts, pQueryAttr);
L
Liu Jicong 已提交
1646
  bool        masterScan = IS_MAIN_SCAN(pRuntimeEnv);
1647 1648

  SResultRow* pResult = NULL;
L
Liu Jicong 已提交
1649 1650
  int32_t     forwardStep = 0;
  int32_t     ret = 0;
1651 1652 1653 1654 1655
  STimeWindow preWin = win;

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

H
Haojun Liao 已提交
1661
    TSKEY ekey = 0;//reviseWindowEkey(pQueryAttr, &win);
L
Liu Jicong 已提交
1662 1663
    //    forwardStep = getNumOfRowsInTimeWindow(pRuntimeEnv, &pSDataBlock->info, tsCols, startPos, ekey,
    //    binarySearchForKey, true);
1664 1665

    // window start(end) key interpolation
L
Liu Jicong 已提交
1666 1667 1668
    //    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);
1669 1670 1671
    preWin = win;

    int32_t prevEndPos = (forwardStep - 1) * step + startPos;
L
Liu Jicong 已提交
1672 1673
    //    startPos = getNextQualifiedWindow(pQueryAttr, &win, &pSDataBlock->info, tsCols, binarySearchForKey,
    //    prevEndPos);
1674
    if (startPos < 0) {
H
Haojun Liao 已提交
1675 1676 1677 1678 1679 1680 1681 1682 1683
//      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;
1684 1685

        // window start(end) key interpolation
L
Liu Jicong 已提交
1686 1687 1688
        //        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 已提交
1689
//      }
1690 1691 1692 1693 1694 1695

      break;
    }
    setResultRowInterpo(pResult, RESULT_ROW_END_INTERP);
  }

H
Haojun Liao 已提交
1696 1697
//  if (pQueryAttr->timeWindowInterpo) {
//    int32_t rowIndex = ascQuery ? (pSDataBlock->info.rows - 1) : 0;
L
Liu Jicong 已提交
1698
    //    saveDataBlockLastRow(pRuntimeEnv, &pSDataBlock->info, pSDataBlock->pDataBlock, rowIndex);
H
Haojun Liao 已提交
1699
//  }
1700

L
Liu Jicong 已提交
1701
  //  updateResultRowInfoActiveIndex(pResultRowInfo, pQueryAttr, pRuntimeEnv->current->lastKey);
1702 1703
}

1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715
static void doKeepTuple(SSessionAggOperatorInfo* pInfo, int64_t ts) {
  pInfo->curWindow.ekey = ts;
  pInfo->prevTs         = ts;
  pInfo->numOfRows     += 1;
}

static void doKeepSessionStartInfo(SSessionAggOperatorInfo* pInfo, const int64_t* tsList, int32_t rowIndex) {
  pInfo->start          = rowIndex;
  pInfo->numOfRows      = 0;
  pInfo->curWindow.skey = tsList[rowIndex];
}

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

1720
  SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, 0);
1721

1722 1723 1724
  bool    masterScan = true;
  int32_t numOfOutput = pOperator->numOfOutput;
  int64_t gid = pBlock->info.groupId;
1725

H
Haojun Liao 已提交
1726
  int64_t gap = pInfo->gap;
1727
  pInfo->numOfRows = 0;
1728
  if (!pInfo->reptScan) {
1729
    pInfo->reptScan = true;
1730
    pInfo->prevTs   = INT64_MIN;
1731 1732
  }

1733
  // In case of ascending or descending order scan data, only one time window needs to be kepted for each table.
1734
  TSKEY* tsList = (TSKEY*)pColInfoData->pData;
1735
  for (int32_t j = 0; j < pBlock->info.rows; ++j) {
1736
    if (pInfo->prevTs == INT64_MIN) {
1737 1738
      doKeepSessionStartInfo(pInfo, tsList, j);
      doKeepTuple(pInfo, tsList[j]);
1739
    } else if (tsList[j] - pInfo->prevTs <= gap && (tsList[j] - pInfo->prevTs) >= 0) {
1740 1741
      // The gap is less than the threshold, so it belongs to current session window that has been opened already.
      doKeepTuple(pInfo, tsList[j]);
1742 1743 1744 1745 1746
      if (j == 0 && pInfo->start != 0) {
        pInfo->start = 0;
      }
    } else {  // start a new session window
      SResultRow* pResult = NULL;
1747 1748 1749 1750

      // keep the time window for the closed time window.
      STimeWindow window = pInfo->curWindow;

1751
      pInfo->curWindow.ekey = pInfo->curWindow.skey;
L
Liu Jicong 已提交
1752
      int32_t ret = setResultOutputBufByKey_rv(&pInfo->binfo.resultRowInfo, pBlock->info.uid, &window, masterScan,
1753
                                               &pResult, gid, pInfo->binfo.pCtx, numOfOutput, pInfo->binfo.rowCellInfoOffset, &pInfo->aggSup, pTaskInfo);
1754
      if (ret != TSDB_CODE_SUCCESS) {  // null data, too many state code
1755
        longjmp(pTaskInfo->env, TSDB_CODE_QRY_APP_ERROR);
1756 1757
      }

1758
      // pInfo->numOfRows data belong to the current session window
1759 1760
      updateTimeWindowInfo(&pInfo->timeWindowData, &window, false);
      doApplyFunctions(pInfo->binfo.pCtx, &window, &pInfo->timeWindowData, pInfo->start, pInfo->numOfRows, NULL, pBlock->info.rows, numOfOutput, TSDB_ORDER_ASC);
1761

1762 1763 1764
      // here we start a new session window
      doKeepSessionStartInfo(pInfo, tsList, j);
      doKeepTuple(pInfo, tsList[j]);
1765 1766 1767 1768
    }
  }

  SResultRow* pResult = NULL;
1769 1770 1771
  pInfo->curWindow.ekey = tsList[pBlock->info.rows - 1];
  int32_t ret = setResultOutputBufByKey_rv(&pInfo->binfo.resultRowInfo, pBlock->info.uid, &pInfo->curWindow, masterScan, &pResult,
                                           gid, pInfo->binfo.pCtx, numOfOutput, pInfo->binfo.rowCellInfoOffset, &pInfo->aggSup, pTaskInfo);
1772
  if (ret != TSDB_CODE_SUCCESS) {  // null data, too many state code
1773
    longjmp(pTaskInfo->env, TSDB_CODE_QRY_APP_ERROR);
1774 1775
  }

1776 1777
  updateTimeWindowInfo(&pInfo->timeWindowData, &pInfo->curWindow, false);
  doApplyFunctions(pInfo->binfo.pCtx, &pInfo->curWindow, &pInfo->timeWindowData, pInfo->start, pInfo->numOfRows, NULL, pBlock->info.rows, numOfOutput, TSDB_ORDER_ASC);
1778 1779 1780 1781 1782
}

static void setResultRowKey(SResultRow* pResultRow, char* pData, int16_t type) {
  if (IS_VAR_DATA_TYPE(type)) {
    if (pResultRow->key == NULL) {
wafwerar's avatar
wafwerar 已提交
1783
      pResultRow->key = taosMemoryMalloc(varDataTLen(pData));
1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796
      varDataCopy(pResultRow->key, pData);
    } else {
      assert(memcmp(pResultRow->key, pData, varDataTLen(pData)) == 0);
    }
  } else {
    int64_t v = -1;
    GET_TYPED_DATA(v, int64_t, type, pData);

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

H
Haojun Liao 已提交
1797
int32_t setGroupResultOutputBuf_rv(SOptrBasicInfo* binfo, int32_t numOfCols, char* pData, int16_t type,
L
Liu Jicong 已提交
1798 1799 1800 1801
                                          int16_t bytes, int32_t groupId, SDiskbasedBuf* pBuf, SExecTaskInfo* pTaskInfo,
                                          SAggSupporter* pAggSup) {
  SResultRowInfo* pResultRowInfo = &binfo->resultRowInfo;
  SqlFunctionCtx* pCtx = binfo->pCtx;
1802

L
Liu Jicong 已提交
1803
  SResultRow* pResultRow = doSetResultOutBufByKey_rv(pBuf, pResultRowInfo, groupId, (char*)pData, bytes, true, groupId,
H
Haojun Liao 已提交
1804
                                                     pTaskInfo, false, pAggSup);
L
Liu Jicong 已提交
1805
  assert(pResultRow != NULL);
1806 1807

  setResultRowKey(pResultRow, pData, type);
H
Haojun Liao 已提交
1808
  setResultRowOutputBufInitCtx_rv(pResultRow, pCtx, numOfCols, binfo->rowCellInfoOffset);
1809 1810 1811
  return TSDB_CODE_SUCCESS;
}

L
Liu Jicong 已提交
1812 1813
static bool functionNeedToExecute(SqlFunctionCtx* pCtx) {
  struct SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
1814 1815 1816

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

1821
  if (isRowEntryCompleted(pResInfo)) {
1822 1823 1824 1825
    return false;
  }

  if (functionId == FUNCTION_FIRST_DST || functionId == FUNCTION_FIRST) {
L
Liu Jicong 已提交
1826
    //    return QUERY_IS_ASC_QUERY(pQueryAttr);
1827 1828 1829 1830
  }

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

  // in the reverse table scan, only the following functions need to be executed
L
Liu Jicong 已提交
1835 1836 1837 1838
  //  if (IS_REVERSE_SCAN(pRuntimeEnv) ||
  //      (pRuntimeEnv->scanFlag == REPEAT_SCAN && functionId != FUNCTION_STDDEV && functionId != FUNCTION_PERCT)) {
  //    return false;
  //  }
1839 1840 1841 1842

  return true;
}

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

H
Haojun Liao 已提交
1846 1847
  if (pSDataBlock->pBlockAgg != NULL && TSDB_COL_IS_NORMAL_COL(pColumn->flag)) {
    pAgg = &pSDataBlock->pBlockAgg[pCtx->columnIndex];
1848 1849

    pCtx->agg = *pAgg;
L
Liu Jicong 已提交
1850
    pCtx->isAggSet = true;
1851 1852 1853 1854 1855
    assert(pCtx->agg.numOfNull <= pSDataBlock->info.rows);
  } else {
    pCtx->isAggSet = false;
  }

H
Haojun Liao 已提交
1856
  pCtx->hasNull = hasNull(pColumn, pAgg);
1857 1858

  // set the statistics data for primary time stamp column
H
Haojun Liao 已提交
1859
  if (pCtx->functionId == FUNCTION_SPREAD && pColumn->colId == PRIMARYKEY_TIMESTAMP_COL_ID) {
L
Liu Jicong 已提交
1860
    pCtx->isAggSet = true;
1861 1862 1863 1864 1865 1866
    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 已提交
1867
static int32_t setCtxTagColumnInfo(SqlFunctionCtx* pCtx, int32_t numOfOutput) {
1868 1869 1870 1871 1872 1873 1874
  if (!isSelectivityWithTagsQuery(pCtx, numOfOutput)) {
    return TSDB_CODE_SUCCESS;
  }

  int32_t num = 0;
  int16_t tagLen = 0;

H
Haojun Liao 已提交
1875
  SqlFunctionCtx*  p = NULL;
wafwerar's avatar
wafwerar 已提交
1876
  SqlFunctionCtx** pTagCtx = taosMemoryCalloc(numOfOutput, POINTER_BYTES);
1877 1878 1879 1880 1881 1882 1883 1884
  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 已提交
1885
      tagLen += pCtx[i].resDataInfo.bytes;
1886
      pTagCtx[num++] = &pCtx[i];
L
Liu Jicong 已提交
1887
    } else if (1 /*(aAggs[functionId].status & FUNCSTATE_SELECTIVITY) != 0*/) {
1888 1889 1890 1891 1892 1893 1894 1895 1896 1897
      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) {
1898 1899 1900
    p->subsidiaryRes.pCtx = pTagCtx;
    p->subsidiaryRes.numOfCols = num;
    p->subsidiaryRes.bufLen = tagLen;
1901
  } else {
wafwerar's avatar
wafwerar 已提交
1902
    taosMemoryFreeClear(pTagCtx);
1903 1904 1905 1906 1907
  }

  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
1908
static SqlFunctionCtx* createSqlFunctionCtx_rv(SExprInfo* pExprInfo, int32_t numOfOutput, int32_t** rowCellInfoOffset) {
L
Liu Jicong 已提交
1909
  SqlFunctionCtx* pFuncCtx = (SqlFunctionCtx*)taosMemoryCalloc(numOfOutput, sizeof(SqlFunctionCtx));
H
Haojun Liao 已提交
1910 1911 1912 1913
  if (pFuncCtx == NULL) {
    return NULL;
  }

wafwerar's avatar
wafwerar 已提交
1914
  *rowCellInfoOffset = taosMemoryCalloc(numOfOutput, sizeof(int32_t));
H
Haojun Liao 已提交
1915
  if (*rowCellInfoOffset == 0) {
wafwerar's avatar
wafwerar 已提交
1916
    taosMemoryFreeClear(pFuncCtx);
H
Haojun Liao 已提交
1917 1918 1919 1920
    return NULL;
  }

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

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

1926
    pCtx->functionId = -1;
H
Haojun Liao 已提交
1927
    if (pExpr->pExpr->nodeType == QUERY_NODE_FUNCTION) {
H
Haojun Liao 已提交
1928
      SFuncExecEnv env = {0};
H
Haojun Liao 已提交
1929 1930
      pCtx->functionId = pExpr->pExpr->_function.pFunctNode->funcId;

H
Haojun Liao 已提交
1931
      if (fmIsAggFunc(pCtx->functionId) || fmIsNonstandardSQLFunc(pCtx->functionId)) {
1932 1933 1934 1935
        fmGetFuncExecFuncs(pCtx->functionId, &pCtx->fpSet);
        pCtx->fpSet.getEnv(pExpr->pExpr->_function.pFunctNode, &env);
      } else {
        fmGetScalarFuncExecFuncs(pCtx->functionId, &pCtx->sfp);
1936 1937 1938
        if (pCtx->sfp.getEnv != NULL) {
          pCtx->sfp.getEnv(pExpr->pExpr->_function.pFunctNode, &env);
        }
1939
      }
H
Haojun Liao 已提交
1940
      pCtx->resDataInfo.interBufSize = env.calcMemSize;
H
Haojun Liao 已提交
1941 1942
    } else if (pExpr->pExpr->nodeType == QUERY_NODE_COLUMN || pExpr->pExpr->nodeType == QUERY_NODE_OPERATOR) {
      pCtx->resDataInfo.interBufSize = pFunct->resSchema.bytes; // for simple column, the intermediate buffer needs to hold one element.
H
Haojun Liao 已提交
1943
    }
H
Haojun Liao 已提交
1944

H
Haojun Liao 已提交
1945
    pCtx->input.numOfInputCols = pFunct->numOfParams;
wafwerar's avatar
wafwerar 已提交
1946 1947
    pCtx->input.pData = taosMemoryCalloc(pFunct->numOfParams, POINTER_BYTES);
    pCtx->input.pColumnDataAgg = taosMemoryCalloc(pFunct->numOfParams, POINTER_BYTES);
H
Haojun Liao 已提交
1948

H
Haojun Liao 已提交
1949
    pCtx->pTsOutput         = NULL;//taosArrayInit(4, POINTER_BYTES);
L
Liu Jicong 已提交
1950
    pCtx->resDataInfo.bytes = pFunct->resSchema.bytes;
H
Haojun Liao 已提交
1951 1952
    pCtx->resDataInfo.type  = pFunct->resSchema.type;
    pCtx->order             = TSDB_ORDER_ASC;
L
Liu Jicong 已提交
1953
    pCtx->start.key = INT64_MIN;
H
Haojun Liao 已提交
1954
    pCtx->end.key   = INT64_MIN;
H
Haojun Liao 已提交
1955
#if 0
H
Haojun Liao 已提交
1956
    for (int32_t j = 0; j < pCtx->numOfParams; ++j) {
H
Haojun Liao 已提交
1957 1958
//      int16_t type = pFunct->param[j].nType;
//      int16_t bytes = pFunct->param[j].nLen;
H
Haojun Liao 已提交
1959

H
Haojun Liao 已提交
1960 1961 1962 1963 1964
//      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 已提交
1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000
    }

    // 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 已提交
2001
#endif
H
Haojun Liao 已提交
2002 2003
  }

L
Liu Jicong 已提交
2004 2005 2006
  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 已提交
2007
  }
H
Haojun Liao 已提交
2008 2009 2010 2011 2012

  setCtxTagColumnInfo(pFuncCtx, numOfOutput);
  return pFuncCtx;
}

2013
static void* destroySqlFunctionCtx(SqlFunctionCtx* pCtx, int32_t numOfOutput) {
2014 2015 2016 2017 2018 2019 2020 2021 2022 2023
  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 已提交
2024
    taosMemoryFreeClear(pCtx[i].subsidiaryRes.pCtx);
2025 2026
  }

wafwerar's avatar
wafwerar 已提交
2027
  taosMemoryFreeClear(pCtx);
2028 2029 2030
  return NULL;
}

H
Haojun Liao 已提交
2031 2032
static void doFreeQueryHandle(STaskRuntimeEnv* pRuntimeEnv) {
  STaskAttr* pQueryAttr = pRuntimeEnv->pQueryAttr;
2033

L
Liu Jicong 已提交
2034
  //  tsdbCleanupReadHandle(pRuntimeEnv->pTsdbReadHandle);
2035
  pRuntimeEnv->pTsdbReadHandle = NULL;
2036

L
Liu Jicong 已提交
2037 2038
  //  SMemRef* pMemRef = &pQueryAttr->memRef;
  //  assert(pMemRef->ref == 0 && pMemRef->snapshot.imem == NULL && pMemRef->snapshot.mem == NULL);
2039 2040
}

L
Liu Jicong 已提交
2041 2042 2043
static void destroyTsComp(STaskRuntimeEnv* pRuntimeEnv, STaskAttr* pQueryAttr) {
  if (pQueryAttr->tsCompQuery && pRuntimeEnv->outputBuf && pRuntimeEnv->outputBuf->pDataBlock &&
      taosArrayGetSize(pRuntimeEnv->outputBuf->pDataBlock) > 0) {
2044 2045
    SColumnInfoData* pColInfoData = taosArrayGet(pRuntimeEnv->outputBuf->pDataBlock, 0);
    if (pColInfoData) {
L
Liu Jicong 已提交
2046
      TdFilePtr pFile = *(TdFilePtr*)pColInfoData->pData;  // TODO refactor
2047 2048
      if (pFile != NULL) {
        taosCloseFile(&pFile);
L
Liu Jicong 已提交
2049
        *(TdFilePtr*)pColInfoData->pData = NULL;
2050 2051 2052 2053 2054
      }
    }
  }
}

L
Liu Jicong 已提交
2055
bool isTaskKilled(SExecTaskInfo* pTaskInfo) {
2056 2057
  // query has been executed more than tsShellActivityTimer, and the retrieve has not arrived
  // abort current query execution.
L
Liu Jicong 已提交
2058 2059
  if (pTaskInfo->owner != 0 &&
      ((taosGetTimestampSec() - pTaskInfo->cost.start / 1000) > 10 * getMaximumIdleDurationSec())
2060 2061
      /*(!needBuildResAfterQueryComplete(pTaskInfo))*/) {
    assert(pTaskInfo->cost.start != 0);
L
Liu Jicong 已提交
2062 2063 2064
    //    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;
2065 2066 2067 2068 2069
  }

  return false;
}

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

L
Liu Jicong 已提交
2072
static bool isCachedLastQuery(STaskAttr* pQueryAttr) {
2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101
  for (int32_t i = 0; i < pQueryAttr->numOfOutput; ++i) {
    int32_t functionId = getExprFunctionId(&pQueryAttr->pExpr1[i]);
    if (functionId == FUNCTION_LAST || functionId == FUNCTION_LAST_DST) {
      continue;
    }

    return false;
  }

  if (pQueryAttr->order.order != TSDB_ORDER_DESC || !TSWINDOW_IS_EQUAL(pQueryAttr->window, TSWINDOW_DESC_INITIALIZER)) {
    return false;
  }

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

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

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

  return true;
}

/////////////////////////////////////////////////////////////////////////////////////////////
L
Liu Jicong 已提交
2102 2103 2104
// todo refactor : return window
void getAlignQueryTimeWindow(SInterval* pInterval, int32_t precision, int64_t key, int64_t keyFirst, int64_t keyLast,
                             STimeWindow* win) {
2105
  ASSERT(key >= keyFirst && key <= keyLast);
H
Haojun Liao 已提交
2106
  win->skey = taosTimeTruncate(key, pInterval, precision);
2107 2108

  /*
H
Haojun Liao 已提交
2109
   * if the realSkey > INT64_MAX - pInterval->interval, the query duration between
2110 2111
   * realSkey and realEkey must be less than one interval.Therefore, no need to adjust the query ranges.
   */
H
Haojun Liao 已提交
2112 2113
  if (keyFirst > (INT64_MAX - pInterval->interval)) {
    assert(keyLast - keyFirst < pInterval->interval);
2114 2115
    win->ekey = INT64_MAX;
  } else {
2116
    win->ekey = taosTimeAdd(win->skey, pInterval->interval, pInterval->intervalUnit, precision) - 1;
2117 2118 2119
  }
}

L
Liu Jicong 已提交
2120
static int32_t updateBlockLoadStatus(STaskAttr* pQuery, int32_t status) {
2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143
  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 已提交
2144
    if (!hasOtherFunc) {
2145 2146 2147 2148 2149 2150 2151 2152 2153
      return BLK_DATA_DISCARD;
    } else {
      return BLK_DATA_ALL_NEEDED;
    }
  }

  return status;
}

H
Haojun Liao 已提交
2154
static void doUpdateLastKey(STaskAttr* pQueryAttr) {
2155 2156 2157
  STimeWindow* win = &pQueryAttr->window;

  size_t num = taosArrayGetSize(pQueryAttr->tableGroupInfo.pGroupList);
L
Liu Jicong 已提交
2158
  for (int32_t i = 0; i < num; ++i) {
2159 2160 2161
    SArray* p1 = taosArrayGetP(pQueryAttr->tableGroupInfo.pGroupList, i);

    size_t len = taosArrayGetSize(p1);
L
Liu Jicong 已提交
2162 2163 2164 2165 2166 2167 2168
    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;
      //      }
2169 2170 2171 2172
    }
  }
}

L
Liu Jicong 已提交
2173 2174
// static void updateDataCheckOrder(SQInfo *pQInfo, SQueryTableReq* pQueryMsg, bool stableQuery) {
//   STaskAttr* pQueryAttr = pQInfo->runtimeEnv.pQueryAttr;
H
Haojun Liao 已提交
2175
//
L
Liu Jicong 已提交
2176 2177 2178 2179
//   // 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 已提交
2180
//
L
Liu Jicong 已提交
2181 2182 2183 2184 2185
//   // 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 已提交
2186
//
L
Liu Jicong 已提交
2187 2188 2189 2190
//     pQueryAttr->order.order = TSDB_ORDER_ASC;
//     if (pQueryAttr->window.skey > pQueryAttr->window.ekey) {
//       TSWAP(pQueryAttr->window.skey, pQueryAttr->window.ekey, TSKEY);
//     }
H
Haojun Liao 已提交
2191
//
L
Liu Jicong 已提交
2192 2193 2194
//     pQueryAttr->needReverseScan = false;
//     return;
//   }
H
Haojun Liao 已提交
2195
//
L
Liu Jicong 已提交
2196 2197 2198 2199 2200
//   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 已提交
2201
//
L
Liu Jicong 已提交
2202 2203 2204 2205
//     pQueryAttr->needReverseScan = false;
//     doUpdateLastKey(pQueryAttr);
//     return;
//   }
H
Haojun Liao 已提交
2206
//
L
Liu Jicong 已提交
2207 2208 2209 2210 2211 2212
//   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 已提交
2213
//
L
Liu Jicong 已提交
2214 2215 2216
//     pQueryAttr->order.order = TSDB_ORDER_ASC;
//     return;
//   }
H
Haojun Liao 已提交
2217
//
L
Liu Jicong 已提交
2218 2219 2220 2221
//   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 已提交
2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247
////               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 已提交
2248 2249
////                 pQueryAttr->window.skey, pQueryAttr->window.ekey, pQueryAttr->window.ekey,
/// pQueryAttr->window.skey);
H
Haojun Liao 已提交
2250 2251 2252 2253 2254 2255 2256 2257 2258 2259
//
//          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 已提交
2260 2261
////                 pQueryAttr->window.skey, pQueryAttr->window.ekey, pQueryAttr->window.ekey,
/// pQueryAttr->window.skey);
H
Haojun Liao 已提交
2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272
//
//          TSWAP(pQueryAttr->window.skey, pQueryAttr->window.ekey, TSKEY);
//          doUpdateLastKey(pQueryAttr);
//        }
//
//        pQueryAttr->order.order = TSDB_ORDER_DESC;
//        pQueryAttr->needReverseScan = false;
//      }
//    }
//  }
//}
2273

H
Haojun Liao 已提交
2274 2275
static void getIntermediateBufInfo(STaskRuntimeEnv* pRuntimeEnv, int32_t* ps, int32_t* rowsize) {
  STaskAttr* pQueryAttr = pRuntimeEnv->pQueryAttr;
L
Liu Jicong 已提交
2276
  int32_t    MIN_ROWS_PER_PAGE = 4;
2277

L
Liu Jicong 已提交
2278 2279
  *rowsize = (int32_t)(pQueryAttr->resultRowSize *
                       getRowNumForMultioutput(pQueryAttr, pQueryAttr->topBotQuery, pQueryAttr->stableQuery));
2280 2281 2282 2283
  int32_t overhead = sizeof(SFilePage);

  // one page contains at least two rows
  *ps = DEFAULT_INTERN_BUF_PAGE_SIZE;
L
Liu Jicong 已提交
2284
  while (((*rowsize) * MIN_ROWS_PER_PAGE) > (*ps) - overhead) {
2285 2286 2287 2288 2289 2290
    *ps = ((*ps) << 1u);
  }
}

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

L
Liu Jicong 已提交
2291 2292 2293
// static FORCE_INLINE bool doFilterByBlockStatistics(STaskRuntimeEnv* pRuntimeEnv, SDataStatis *pDataStatis,
// SqlFunctionCtx *pCtx, int32_t numOfRows) {
//   STaskAttr* pQueryAttr = pRuntimeEnv->pQueryAttr;
2294
//
L
Liu Jicong 已提交
2295 2296 2297
//   if (pDataStatis == NULL || pQueryAttr->pFilters == NULL) {
//     return true;
//   }
2298
//
L
Liu Jicong 已提交
2299 2300
//   return filterRangeExecute(pQueryAttr->pFilters, pDataStatis, pQueryAttr->numOfCols, numOfRows);
// }
2301

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

dengyihao's avatar
dengyihao 已提交
2305 2306
  TSKEY sk = TMIN(pQueryAttr->window.skey, pQueryAttr->window.ekey);
  TSKEY ek = TMAX(pQueryAttr->window.skey, pQueryAttr->window.ekey);
2307 2308

  if (QUERY_IS_ASC_QUERY(pQueryAttr)) {
L
Liu Jicong 已提交
2309
    //    getAlignQueryTimeWindow(pQueryAttr, pBlockInfo->window.skey, sk, ek, &w);
2310 2311 2312 2313 2314 2315
    assert(w.ekey >= pBlockInfo->window.skey);

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

L
Liu Jicong 已提交
2316 2317
    while (1) {
      //      getNextTimeWindow(pQueryAttr, &w);
2318 2319 2320 2321 2322 2323 2324 2325 2326 2327
      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 已提交
2328
    //    getAlignQueryTimeWindow(pQueryAttr, pBlockInfo->window.ekey, sk, ek, &w);
2329 2330 2331 2332 2333 2334
    assert(w.skey <= pBlockInfo->window.ekey);

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

L
Liu Jicong 已提交
2335 2336
    while (1) {
      //      getNextTimeWindow(pQueryAttr, &w);
2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350
      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 已提交
2351
static int32_t doTSJoinFilter(STaskRuntimeEnv* pRuntimeEnv, TSKEY key, bool ascQuery) {
2352 2353 2354
  STSElem elem = tsBufGetElem(pRuntimeEnv->pTsBuf);

#if defined(_DEBUG_VIEW)
L
Liu Jicong 已提交
2355 2356
  printf("elem in comp ts file:%" PRId64 ", key:%" PRId64 ", tag:%" PRIu64
         ", query order:%d, ts order:%d, traverse:%d, index:%d\n",
2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389
         elem.ts, key, elem.tag.i, pQueryAttr->order.order, pRuntimeEnv->pTsBuf->tsOrder,
         pRuntimeEnv->pTsBuf->cur.order, pRuntimeEnv->pTsBuf->cur.tsIndex);
#endif

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

  return TS_JOIN_TS_EQUAL;
}

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

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

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

      qualified = false;
      for (int32_t j = 0; j < pFilterInfo[k].numOfFilters; ++j) {
        SColumnFilterElem* pFilterElem = NULL;
L
Liu Jicong 已提交
2390
        //        SColumnFilterElem* pFilterElem = &pFilterInfo[k].pFilters[j];
2391 2392 2393

        bool isnull = isNull(pElem, pFilterInfo[k].info.type);
        if (isnull) {
L
Liu Jicong 已提交
2394 2395 2396 2397 2398 2399
          //          if (pFilterElem->fp == isNullOperator) {
          //            qualified = true;
          //            break;
          //          } else {
          //            continue;
          //          }
2400
        } else {
L
Liu Jicong 已提交
2401 2402 2403 2404 2405 2406
          //          if (pFilterElem->fp == notNullOperator) {
          //            qualified = true;
          //            break;
          //          } else if (pFilterElem->fp == isNullOperator) {
          //            continue;
          //          }
2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 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 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477
        }

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

      if (!qualified) {
        break;
      }
    }

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

  return all;
}

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

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

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

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

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

    start += len;
    len = 0;
  }

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

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

H
Haojun Liao 已提交
2478
void filterRowsInDataBlock(STaskRuntimeEnv* pRuntimeEnv, SSingleColumnFilterInfo* pFilterInfo, int32_t numOfFilterCols,
2479 2480 2481
                           SSDataBlock* pBlock, bool ascQuery) {
  int32_t numOfRows = pBlock->info.rows;

L
Liu Jicong 已提交
2482
  int8_t* p = taosMemoryCalloc(numOfRows, sizeof(int8_t));
2483
  bool    all = true;
H
Haojun Liao 已提交
2484
#if 0
2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511
  if (pRuntimeEnv->pTsBuf != NULL) {
    SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, 0);

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

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

    // save the cursor status
    pRuntimeEnv->current->cur = tsBufGetCursor(pRuntimeEnv->pTsBuf);
  } else {
    all = doFilterDataBlock(pFilterInfo, numOfFilterCols, numOfRows, p);
  }
H
Haojun Liao 已提交
2512
#endif
2513 2514 2515 2516 2517

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

wafwerar's avatar
wafwerar 已提交
2518
  taosMemoryFreeClear(p);
2519 2520
}

H
Haojun Liao 已提交
2521
void filterColRowsInDataBlock(STaskRuntimeEnv* pRuntimeEnv, SSDataBlock* pBlock, bool ascQuery) {
L
Liu Jicong 已提交
2522
  int32_t numOfRows = pBlock->info.rows;
2523

L
Liu Jicong 已提交
2524 2525
  int8_t* p = NULL;
  bool    all = true;
2526

L
Liu Jicong 已提交
2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548
  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;
      }
    }
2549

L
Liu Jicong 已提交
2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564
    // 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
    }
  }
2565

L
Liu Jicong 已提交
2566
  taosMemoryFreeClear(p);
2567 2568 2569
}

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

static uint32_t doFilterByBlockTimeWindow(STableScanInfo* pTableScanInfo, SSDataBlock* pBlock) {
H
Haojun Liao 已提交
2573
  SqlFunctionCtx* pCtx = pTableScanInfo->pCtx;
L
Liu Jicong 已提交
2574
  uint32_t        status = BLK_DATA_NO_NEEDED;
2575 2576 2577 2578

  int32_t numOfOutput = pTableScanInfo->numOfOutput;
  for (int32_t i = 0; i < numOfOutput; ++i) {
    int32_t functionId = pCtx[i].functionId;
H
Haojun Liao 已提交
2579
    int32_t colId = pTableScanInfo->pExpr[i].base.pParam[0].pCol->colId;
2580 2581 2582 2583 2584 2585

    // 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 已提交
2586 2587 2588 2589
      //      status |= aAggs[functionId].dataReqFunc(&pTableScanInfo->pCtx[i], &pBlock->info.window, colId);
      //      if ((status & BLK_DATA_ALL_NEEDED) == BLK_DATA_ALL_NEEDED) {
      //        return status;
      //      }
2590 2591 2592 2593 2594 2595
    }
  }

  return status;
}

L
Liu Jicong 已提交
2596 2597
int32_t loadDataBlockOnDemand(SExecTaskInfo* pTaskInfo, STableScanInfo* pTableScanInfo, SSDataBlock* pBlock,
                              uint32_t* status) {
2598 2599
  *status = BLK_DATA_NO_NEEDED;

H
Haojun Liao 已提交
2600
  pBlock->pDataBlock = NULL;
L
Liu Jicong 已提交
2601
  pBlock->pBlockAgg = NULL;
H
Haojun Liao 已提交
2602

L
Liu Jicong 已提交
2603 2604
  //  int64_t groupId = pRuntimeEnv->current->groupIndex;
  //  bool    ascQuery = QUERY_IS_ASC_QUERY(pQueryAttr);
2605

H
Haojun Liao 已提交
2606
  STaskCostInfo* pCost = &pTaskInfo->cost;
2607 2608 2609

  pCost->totalBlocks += 1;
  pCost->totalRows += pBlock->info.rows;
H
Haojun Liao 已提交
2610
#if 0
2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634
  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 已提交
2635
      (QUERY_IS_INTERVAL_QUERY(pQueryAttr) && overlapWithTimeWindow(pTaskInfo, &pBlock->info))) {
2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647
    (*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 已提交
2648
      bool  masterScan = IS_MAIN_SCAN(pRuntimeEnv);
2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676
      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 已提交
2677
//  *status = updateBlockLoadStatus(pRuntimeEnv->pQueryAttr, *status);
2678 2679 2680 2681 2682 2683 2684 2685

  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;
2686
//    tsdbRetrieveDataBlockStatisInfo(pTableScanInfo->pTsdbReadHandle, &pBlock->pBlockAgg);
2687 2688

    if (pBlock->pBlockAgg == NULL) {  // data block statistics does not exist, load data block
2689
//      pBlock->pDataBlock = tsdbRetrieveDataBlock(pTableScanInfo->pTsdbReadHandle, NULL);
2690 2691 2692 2693 2694 2695 2696
      pCost->totalCheckedRows += pBlock->info.rows;
    }
  } else {
    assert((*status) == BLK_DATA_ALL_NEEDED);

    // load the data block statistics to perform further filter
    pCost->loadBlockStatis += 1;
2697
//    tsdbRetrieveDataBlockStatisInfo(pTableScanInfo->pTsdbReadHandle, &pBlock->pBlockAgg);
2698 2699 2700 2701 2702 2703

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

H
Haojun Liao 已提交
2704
          bool  masterScan = IS_MAIN_SCAN(pRuntimeEnv);
2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742
          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;
2743
//    pBlock->pDataBlock = tsdbRetrieveDataBlock(pTableScanInfo->pTsdbReadHandle, NULL);
2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755
//    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 已提交
2756
#endif
2757 2758 2759
  return TSDB_CODE_SUCCESS;
}

L
Liu Jicong 已提交
2760
int32_t binarySearchForKey(char* pValue, int num, TSKEY key, int order) {
2761 2762 2763 2764 2765 2766 2767 2768 2769
  int32_t midPos = -1;
  int32_t numOfRows;

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

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

L
Liu Jicong 已提交
2770
  TSKEY*  keyList = (TSKEY*)pValue;
2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823
  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 已提交
2824
 * set tag value in SqlFunctionCtx
2825 2826
 * e.g.,tag information into input buffer
 */
L
Liu Jicong 已提交
2827
static void doSetTagValueInParam(void* pTable, int32_t tagColId, SVariant* tag, int16_t type, int16_t bytes) {
2828 2829 2830
  taosVariantDestroy(tag);

  char* val = NULL;
L
Liu Jicong 已提交
2831 2832 2833 2834 2835 2836
  //  if (tagColId == TSDB_TBNAME_COLUMN_INDEX) {
  //    val = tsdbGetTableName(pTable);
  //    assert(val != NULL);
  //  } else {
  //    val = tsdbGetTableTagVal(pTable, tagColId, type, bytes);
  //  }
2837 2838 2839 2840 2841 2842 2843 2844

  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 已提交
2845
    int32_t len = (varDataLen(val) > maxLen) ? maxLen : varDataLen(val);
2846
    taosVariantCreateFromBinary(tag, varDataVal(val), len, type);
L
Liu Jicong 已提交
2847
    // taosVariantCreateFromBinary(tag, varDataVal(val), varDataLen(val), type);
2848 2849 2850 2851 2852 2853 2854 2855
  } 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 已提交
2856
  for (int32_t i = 0; i < numOfTags; ++i) {
2857 2858 2859 2860 2861 2862 2863 2864
    if (pTagColList[i].colId == colId) {
      return &pTagColList[i];
    }
  }

  return NULL;
}

L
Liu Jicong 已提交
2865
void setTagValue(SOperatorInfo* pOperatorInfo, void* pTable, SqlFunctionCtx* pCtx, int32_t numOfOutput) {
H
Haojun Liao 已提交
2866
  STaskRuntimeEnv* pRuntimeEnv = pOperatorInfo->pRuntimeEnv;
2867

L
Liu Jicong 已提交
2868 2869
  SExprInfo* pExpr = pOperatorInfo->pExpr;
  STaskAttr* pQueryAttr = pRuntimeEnv->pQueryAttr;
2870 2871

  SExprInfo* pExprInfo = &pExpr[0];
L
Liu Jicong 已提交
2872
  int32_t    functionId = getExprFunctionId(pExprInfo);
2873 2874 2875 2876

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

L
Liu Jicong 已提交
2877
    //    int16_t      tagColId = (int16_t)pExprInfo->base.param[0].i;
H
Haojun Liao 已提交
2878
    int16_t      tagColId = -1;
2879 2880 2881
    SColumnInfo* pColInfo = doGetTagColumnInfoById(pQueryAttr->tagColList, pQueryAttr->numOfTags, tagColId);

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

2883 2884 2885 2886 2887 2888 2889 2890 2891
  } 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 已提交
2892
      if (!TSDB_COL_IS_TAG(pLocalExprInfo->base.pParam[0].pCol->flag)) {
2893 2894 2895 2896
        continue;
      }

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

L
Liu Jicong 已提交
2900 2901 2902
      if (IS_NUMERIC_TYPE(pLocalExprInfo->base.resSchema.type) ||
          pLocalExprInfo->base.resSchema.type == TSDB_DATA_TYPE_BOOL ||
          pLocalExprInfo->base.resSchema.type == TSDB_DATA_TYPE_TIMESTAMP) {
2903 2904 2905 2906
        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 已提交
2907
        }
2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919
      }

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

H
Haojun Liao 已提交
2920
void copyToSDataBlock(SSDataBlock* pBlock, int32_t* offset, SGroupResInfo* pGroupResInfo, SDiskbasedBuf* pResBuf) {
2921 2922 2923 2924 2925 2926 2927
  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 已提交
2928 2929 2930
      //      if ((code = mergeIntoGroupResult(&pGroupResInfo, pRuntimeEnv, offset)) != TSDB_CODE_SUCCESS) {
      return;
      //      }
2931 2932
    }

L
Liu Jicong 已提交
2933
    //    doCopyToSDataBlock(pResBuf, pGroupResInfo, TSDB_ORDER_ASC, pBlock, );
2934 2935 2936 2937 2938 2939 2940 2941 2942 2943

    // 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 已提交
2944 2945 2946
    //    if (pBlock->info.rows >= threshold) {
    //      break;
    //    }
2947 2948 2949
  }
}

L
Liu Jicong 已提交
2950
static void updateTableQueryInfoForReverseScan(STableQueryInfo* pTableQueryInfo) {
2951 2952 2953 2954
  if (pTableQueryInfo == NULL) {
    return;
  }

L
Liu Jicong 已提交
2955 2956
  //  TSWAP(pTableQueryInfo->win.skey, pTableQueryInfo->win.ekey, TSKEY);
  //  pTableQueryInfo->lastKey = pTableQueryInfo->win.skey;
2957

L
Liu Jicong 已提交
2958 2959
  //  SWITCH_ORDER(pTableQueryInfo->cur.order);
  //  pTableQueryInfo->cur.vgroupIndex = -1;
2960 2961 2962 2963 2964 2965 2966 2967 2968 2969

  // 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 已提交
2970
void initResultRow(SResultRow* pResultRow) {
2971 2972 2973 2974 2975 2976
  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 已提交
2977 2978 2979
 * +------------+-----------------result column 1------------+------------------result column 2-----------+
 * | SResultRow | SResultRowEntryInfo | intermediate buffer1 | SResultRowEntryInfo | intermediate buffer 2|
 * +------------+--------------------------------------------+--------------------------------------------+
2980 2981
 *           offset[0]                                  offset[1]                                   offset[2]
 */
2982
// TODO refactor: some function move away
H
Haojun Liao 已提交
2983
void setFunctionResultOutput(SOptrBasicInfo* pInfo, SAggSupporter* pSup, int32_t stage, SExecTaskInfo* pTaskInfo) {
L
Liu Jicong 已提交
2984 2985 2986
  SqlFunctionCtx* pCtx = pInfo->pCtx;
  SSDataBlock*    pDataBlock = pInfo->pRes;
  int32_t*        rowCellInfoOffset = pInfo->rowCellInfoOffset;
H
Haojun Liao 已提交
2987

H
Haojun Liao 已提交
2988
  SResultRowInfo* pResultRowInfo = &pInfo->resultRowInfo;
H
Haojun Liao 已提交
2989
  initResultRowInfo(pResultRowInfo, 16);
H
Haojun Liao 已提交
2990

L
Liu Jicong 已提交
2991 2992 2993 2994
  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 已提交
2995 2996 2997 2998 2999

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

L
Liu Jicong 已提交
3000
    pCtx[i].resultInfo = pEntry;
H
Haojun Liao 已提交
3001 3002 3003
    pCtx[i].currentStage = stage;

    // set the timestamp output buffer for top/bottom/diff query
L
Liu Jicong 已提交
3004 3005
    //    int32_t fid = pCtx[i].functionId;
    //    if (fid == FUNCTION_TOP || fid == FUNCTION_BOTTOM || fid == FUNCTION_DIFF || fid == FUNCTION_DERIVATIVE) {
H
Haojun Liao 已提交
3006
    //      if (i > 0) pCtx[i].pTsOutput = pCtx[i-1].pOutput;
L
Liu Jicong 已提交
3007
    //    }
H
Haojun Liao 已提交
3008 3009 3010 3011 3012
  }

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

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

L
Liu Jicong 已提交
3016
  int32_t newSize = pDataBlock->info.rows + numOfInputRows + 5;  // extra output buffer
3017
  if ((*bufCapacity) < newSize) {
L
Liu Jicong 已提交
3018 3019
    for (int32_t i = 0; i < pDataBlock->info.numOfCols; ++i) {
      SColumnInfoData* pColInfo = taosArrayGet(pDataBlock->pDataBlock, i);
3020

wafwerar's avatar
wafwerar 已提交
3021
      char* p = taosMemoryRealloc(pColInfo->pData, newSize * pColInfo->info.bytes);
3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034
      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 已提交
3035
    SColumnInfoData* pColInfo = taosArrayGet(pDataBlock->pDataBlock, i);
3036 3037 3038 3039 3040
    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 已提交
3041 3042
    if (functionId == FUNCTION_TOP || functionId == FUNCTION_BOTTOM || functionId == FUNCTION_DIFF ||
        functionId == FUNCTION_DERIVATIVE) {
H
Haojun Liao 已提交
3043
//      if (i > 0) pBInfo->pCtx[i].pTsOutput = pBInfo->pCtx[i - 1].pOutput;
3044 3045 3046 3047
    }
  }
}

H
Haojun Liao 已提交
3048
void copyTsColoum(SSDataBlock* pRes, SqlFunctionCtx* pCtx, int32_t numOfOutput) {
3049 3050
  bool    needCopyTs = false;
  int32_t tsNum = 0;
L
Liu Jicong 已提交
3051
  char*   src = NULL;
3052 3053 3054 3055
  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 已提交
3056 3057
      if (i > 0 && pCtx[i - 1].functionId == FUNCTION_TS_DUMMY) {
        SColumnInfoData* pColRes = taosArrayGet(pRes->pDataBlock, i - 1);  // find ts data
3058 3059
        src = pColRes->pData;
      }
L
Liu Jicong 已提交
3060
    } else if (functionId == FUNCTION_TS_DUMMY) {
3061 3062 3063 3064 3065 3066 3067 3068 3069 3070
      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 已提交
3071
    if (functionId == FUNCTION_TS_DUMMY) {
3072 3073 3074 3075 3076 3077
      SColumnInfoData* pColRes = taosArrayGet(pRes->pDataBlock, i);
      memcpy(pColRes->pData, src, pColRes->info.bytes * pRes->info.rows);
    }
  }
}

H
Haojun Liao 已提交
3078
void initCtxOutputBuffer(SqlFunctionCtx* pCtx, int32_t size) {
3079 3080
  for (int32_t j = 0; j < size; ++j) {
    struct SResultRowEntryInfo* pResInfo = GET_RES_INFO(&pCtx[j]);
H
Haojun Liao 已提交
3081
    if (isRowEntryInitialized(pResInfo) || fmIsPseudoColumnFunc(pCtx[j].functionId) || pCtx[j].functionId == -1 || fmIsScalarFunc(pCtx[j].functionId)) {
3082 3083 3084
      continue;
    }

H
Haojun Liao 已提交
3085
    pCtx[j].fpSet.init(&pCtx[j], pCtx[j].resultInfo);
3086 3087 3088
  }
}

L
Liu Jicong 已提交
3089
void setTaskStatus(SExecTaskInfo* pTaskInfo, int8_t status) {
3090
  if (status == TASK_NOT_COMPLETED) {
H
Haojun Liao 已提交
3091
    pTaskInfo->status = status;
3092 3093
  } else {
    // QUERY_NOT_COMPLETED is not compatible with any other status, so clear its position first
3094
    CLEAR_QUERY_STATUS(pTaskInfo, TASK_NOT_COMPLETED);
H
Haojun Liao 已提交
3095
    pTaskInfo->status |= status;
3096 3097 3098
  }
}

3099 3100
void finalizeQueryResult(SqlFunctionCtx* pCtx, int32_t numOfOutput) {
  for (int32_t j = 0; j < numOfOutput; ++j) {
H
Haojun Liao 已提交
3101 3102 3103 3104
    if (pCtx[j].functionId == -1) {
      continue;
    }

3105 3106 3107 3108
    pCtx[j].fpSet.finalize(&pCtx[j]);
  }
}

L
Liu Jicong 已提交
3109 3110
void finalizeMultiTupleQueryResult(SqlFunctionCtx* pCtx, int32_t numOfOutput, SDiskbasedBuf* pBuf,
                                   SResultRowInfo* pResultRowInfo, int32_t* rowCellInfoOffset) {
3111 3112 3113
  for (int32_t i = 0; i < pResultRowInfo->size; ++i) {
    SResultRowPosition* pPos = &pResultRowInfo->pPosition[i];

L
Liu Jicong 已提交
3114
    SFilePage*  bufPage = getBufPage(pBuf, pPos->pageId);
3115
    SResultRow* pRow = (SResultRow*)((char*)bufPage + pPos->offset);
H
Haojun Liao 已提交
3116 3117 3118 3119 3120

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

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

H
Haojun Liao 已提交
3125
      struct SResultRowEntryInfo* pResInfo = pCtx[j].resultInfo;
3126 3127 3128 3129
      if (isRowEntryCompleted(pResInfo) && isRowEntryInitialized(pResInfo)) {
        continue;
      }

H
Haojun Liao 已提交
3130
      if (pCtx[j].fpSet.process) {  // TODO set the dummy function, to avoid the check for null ptr.
H
Haojun Liao 已提交
3131 3132
        pCtx[j].fpSet.finalize(&pCtx[j]);
      }
3133 3134 3135 3136

      if (pRow->numOfRows < pResInfo->numOfRes) {
        pRow->numOfRows = pResInfo->numOfRes;
      }
3137
    }
3138 3139 3140 3141 3142 3143

    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
     */
L
Liu Jicong 已提交
3144
    //    buf->numOfRows = (uint16_t)getNumOfResult(pCtx, numOfOutput);
3145
  }
3146 3147
}

3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167
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]);
3168
        pResInfo->initialized = true;
3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184
      }

      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 已提交
3185
static bool hasMainOutput(STaskAttr* pQueryAttr) {
3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196
  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 已提交
3197 3198
STableQueryInfo* createTableQueryInfo(void* buf, bool groupbyColumn, STimeWindow win) {
  STableQueryInfo* pTableQueryInfo = buf;
3199 3200 3201
  pTableQueryInfo->lastKey = win.skey;

  // set more initial size of interval/groupby query
L
Liu Jicong 已提交
3202 3203 3204 3205 3206 3207 3208 3209
  //  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
  //  }
3210 3211 3212 3213

  return pTableQueryInfo;
}

L
Liu Jicong 已提交
3214
void destroyTableQueryInfoImpl(STableQueryInfo* pTableQueryInfo) {
3215 3216 3217 3218
  if (pTableQueryInfo == NULL) {
    return;
  }

L
Liu Jicong 已提交
3219
  //  taosVariantDestroy(&pTableQueryInfo->tag);
3220 3221 3222
  cleanupResultRowInfo(&pTableQueryInfo->resInfo);
}

L
Liu Jicong 已提交
3223 3224
void setResultRowOutputBufInitCtx(STaskRuntimeEnv* pRuntimeEnv, SResultRow* pResult, SqlFunctionCtx* pCtx,
                                  int32_t numOfOutput, int32_t* rowCellInfoOffset) {
3225
  // Note: pResult->pos[i]->num == 0, there is only fixed number of results for each group
3226
  SFilePage* bufPage = getBufPage(pRuntimeEnv->pResultBuf, pResult->pageId);
3227 3228 3229 3230 3231 3232 3233

  int32_t offset = 0;
  for (int32_t i = 0; i < numOfOutput; ++i) {
    pCtx[i].resultInfo = getResultCell(pResult, i, rowCellInfoOffset);

    struct SResultRowEntryInfo* pResInfo = pCtx[i].resultInfo;
    if (isRowEntryCompleted(pResInfo) && isRowEntryInitialized(pResInfo)) {
H
Haojun Liao 已提交
3234
      offset += pCtx[i].resDataInfo.bytes;
3235 3236 3237 3238
      continue;
    }

    pCtx[i].pOutput = getPosInResultPage(pRuntimeEnv->pQueryAttr, bufPage, pResult->offset, offset);
H
Haojun Liao 已提交
3239
    offset += pCtx[i].resDataInfo.bytes;
3240 3241 3242 3243 3244 3245 3246

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

    if (functionId == FUNCTION_TOP || functionId == FUNCTION_BOTTOM || functionId == FUNCTION_DIFF) {
H
Haojun Liao 已提交
3247
//      if (i > 0) pCtx[i].pTsOutput = pCtx[i - 1].pOutput;
3248 3249
    }

L
Liu Jicong 已提交
3250 3251 3252
    //    if (!pResInfo->initialized) {
    //      aAggs[functionId].init(&pCtx[i], pResInfo);
    //    }
3253 3254 3255
  }
}

H
Haojun Liao 已提交
3256
void setResultRowOutputBufInitCtx_rv(SResultRow* pResult, SqlFunctionCtx* pCtx, int32_t numOfOutput, int32_t* rowCellInfoOffset) {
3257 3258 3259 3260 3261 3262 3263
  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;
    }
3264 3265 3266 3267 3268

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

H
Haojun Liao 已提交
3269
    if (!pResInfo->initialized && pCtx[i].functionId != -1) {
3270
      pCtx[i].fpSet.init(&pCtx[i], pResInfo);
3271 3272 3273 3274
    }
  }
}

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

3280 3281
  SResultRowInfo* pResultRowInfo = &pAggInfo->binfo.resultRowInfo;
  SqlFunctionCtx* pCtx = pAggInfo->binfo.pCtx;
L
Liu Jicong 已提交
3282
  int32_t*        rowCellInfoOffset = pAggInfo->binfo.rowCellInfoOffset;
3283

3284
  SResultRow* pResultRow =
L
Liu Jicong 已提交
3285 3286 3287
      doSetResultOutBufByKey_rv(pAggInfo->pResultBuf, pResultRowInfo, tid, (char*)&tableGroupId, sizeof(tableGroupId),
                                true, uid, pTaskInfo, false, &pAggInfo->aggSup);
  assert(pResultRow != NULL);
3288 3289 3290 3291 3292 3293

  /*
   * 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 已提交
3294
    int32_t ret = addNewWindowResultBuf(pResultRow, pAggInfo->pResultBuf, tableGroupId, pAggInfo->binfo.pRes->info.rowSize);
3295 3296 3297 3298 3299
    if (ret != TSDB_CODE_SUCCESS) {
      return;
    }
  }

H
Haojun Liao 已提交
3300
  setResultRowOutputBufInitCtx_rv(pResultRow, pCtx, numOfOutput, rowCellInfoOffset);
3301 3302
}

L
Liu Jicong 已提交
3303 3304
void setExecutionContext(int32_t numOfOutput, int32_t tableGroupId, TSKEY nextKey, SExecTaskInfo* pTaskInfo,
                         STableQueryInfo* pTableQueryInfo, SAggOperatorInfo* pAggInfo) {
3305 3306
  // lastKey needs to be updated
  pTableQueryInfo->lastKey = nextKey;
3307
  if (pAggInfo->groupId != INT32_MIN && pAggInfo->groupId == tableGroupId) {
3308 3309 3310
    return;
  }

3311
  doSetTableGroupOutputBuf(pAggInfo, numOfOutput, tableGroupId, pTaskInfo);
3312 3313

  // record the current active group id
3314
  pAggInfo->groupId = tableGroupId;
3315 3316
}

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

H
Haojun Liao 已提交
3320
  SExprBasicInfo* pExpr = &pExprInfo->base;
L
Liu Jicong 已提交
3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344
  //  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 已提交
3345
  STaskAttr* pQueryAttr = pRuntimeEnv->pQueryAttr;
3346 3347

  assert(pRuntimeEnv->pTsBuf != NULL);
H
Haojun Liao 已提交
3348
#if 0
3349 3350 3351 3352 3353 3354 3355 3356 3357
  // 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) {
3358
        //qError("QInfo:0x%"PRIx64" failed to find tag:%s in ts_comp", GET_TASKID(pRuntimeEnv), pTag->pz);
3359
      } else {
3360
        //qError("QInfo:0x%"PRIx64" failed to find tag:%" PRId64 " in ts_comp", GET_TASKID(pRuntimeEnv), pTag->i);
3361 3362 3363 3364 3365 3366 3367 3368
      }

      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) {
3369
      //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);
3370
    } else {
3371
      //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);
3372 3373 3374 3375 3376
    }

  } else {
    tsBufSetCursor(pRuntimeEnv->pTsBuf, &pTableQueryInfo->cur);
    if (pTag->nType == TSDB_DATA_TYPE_BINARY || pTag->nType == TSDB_DATA_TYPE_NCHAR) {
3377
      //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);
3378
    } else {
3379
      //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);
3380 3381
    }
  }
H
Haojun Liao 已提交
3382
#endif
3383 3384 3385 3386 3387 3388
  return 0;
}

/*
 * There are two cases to handle:
 *
L
Liu Jicong 已提交
3389 3390
 * 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.
3391 3392 3393 3394
 * 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 已提交
3395 3396 3397 3398
void setIntervalQueryRange(STaskRuntimeEnv* pRuntimeEnv, TSKEY key) {
  STaskAttr*       pQueryAttr = pRuntimeEnv->pQueryAttr;
  STableQueryInfo* pTableQueryInfo = pRuntimeEnv->current;
  SResultRowInfo*  pResultRowInfo = &pTableQueryInfo->resInfo;
3399 3400 3401 3402 3403

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

L
Liu Jicong 已提交
3404
  //  pTableQueryInfo->win.skey = key;
3405 3406 3407 3408 3409 3410 3411 3412 3413 3414
  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 已提交
3415 3416
  TSKEY sk = TMIN(win.skey, win.ekey);
  TSKEY ek = TMAX(win.skey, win.ekey);
L
Liu Jicong 已提交
3417
  //  getAlignQueryTimeWindow(pQueryAttr, win.skey, sk, ek, &w);
3418

L
Liu Jicong 已提交
3419 3420 3421 3422 3423 3424 3425
  //  if (pResultRowInfo->prevSKey == TSKEY_INITIAL_VAL) {
  //    if (!QUERY_IS_ASC_QUERY(pQueryAttr)) {
  //      assert(win.ekey == pQueryAttr->window.ekey);
  //    }
  //
  //    pResultRowInfo->prevSKey = w.skey;
  //  }
3426

L
Liu Jicong 已提交
3427
  //  pTableQueryInfo->lastKey = pTableQueryInfo->win.skey;
3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438
}

/**
 * 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
 */
L
Liu Jicong 已提交
3439 3440
static int32_t doCopyToSDataBlock(SDiskbasedBuf* pBuf, SGroupResInfo* pGroupResInfo, int32_t orderType,
                                  SSDataBlock* pBlock, int32_t rowCapacity, int32_t* rowCellOffset) {
3441
  int32_t numOfRows = getNumOfTotalRes(pGroupResInfo);
L
Liu Jicong 已提交
3442
  int32_t numOfResult = pBlock->info.rows;  // there are already exists result rows
3443 3444 3445 3446

  int32_t start = 0;
  int32_t step = -1;

L
Liu Jicong 已提交
3447
  // qDebug("QInfo:0x%"PRIx64" start to copy data from windowResInfo to output buf", GET_TASKID(pRuntimeEnv));
3448 3449 3450 3451 3452 3453 3454 3455 3456 3457
  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;
  }

3458 3459
  int32_t nrows = pBlock->info.rows;

3460
  for (int32_t i = start; (i < numOfRows) && (i >= 0); i += step) {
3461
    SResultRowPosition* pPos = taosArrayGet(pGroupResInfo->pRows, i);
L
Liu Jicong 已提交
3462
    SFilePage*          page = getBufPage(pBuf, pPos->pageId);
3463 3464

    SResultRow* pRow = (SResultRow*)((char*)page + pPos->offset);
3465 3466 3467 3468 3469
    if (pRow->numOfRows == 0) {
      pGroupResInfo->index += 1;
      continue;
    }

3470
    // TODO copy multiple rows?
3471
    int32_t numOfRowsToCopy = pRow->numOfRows;
L
Liu Jicong 已提交
3472
    if (numOfResult + numOfRowsToCopy >= rowCapacity) {
3473 3474 3475 3476 3477 3478
      break;
    }

    pGroupResInfo->index += 1;

    for (int32_t j = 0; j < pBlock->info.numOfCols; ++j) {
L
Liu Jicong 已提交
3479
      SColumnInfoData*     pColInfoData = taosArrayGet(pBlock->pDataBlock, j);
3480
      SResultRowEntryInfo* pEntryInfo = getResultCell(pRow, j, rowCellOffset);
3481

3482 3483
      char* in = GET_ROWCELL_INTERBUF(pEntryInfo);
      colDataAppend(pColInfoData, nrows, in, pEntryInfo->numOfRes == 0);
3484 3485
    }

3486 3487 3488
    releaseBufPage(pBuf, page);
    nrows += 1;

3489
    numOfResult += numOfRowsToCopy;
H
Haojun Liao 已提交
3490
    if (numOfResult == rowCapacity) {  // output buffer is full
3491 3492 3493 3494
      break;
    }
  }

L
Liu Jicong 已提交
3495
  // qDebug("QInfo:0x%"PRIx64" copy data to query buf completed", GET_TASKID(pRuntimeEnv));
3496 3497 3498 3499
  pBlock->info.rows = numOfResult;
  return 0;
}

H
Haojun Liao 已提交
3500
void toSDatablock(SGroupResInfo* pGroupResInfo, SDiskbasedBuf* pBuf, SSDataBlock* pBlock, int32_t rowCapacity,
L
Liu Jicong 已提交
3501
                         int32_t* rowCellOffset) {
3502 3503
  assert(pGroupResInfo->currentGroup <= pGroupResInfo->totalGroup);

3504
  blockDataCleanup(pBlock);
3505 3506 3507 3508
  if (!hasRemainDataInCurrentGroup(pGroupResInfo)) {
    return;
  }

3509
  int32_t orderType = TSDB_ORDER_ASC;
3510
  doCopyToSDataBlock(pBuf, pGroupResInfo, orderType, pBlock, rowCapacity, rowCellOffset);
3511

H
Haojun Liao 已提交
3512 3513
  // add condition (pBlock->info.rows >= 1) just to runtime happy
  blockDataUpdateTsWindow(pBlock);
3514 3515
}

L
Liu Jicong 已提交
3516 3517
static void updateNumOfRowsInResultRows(SqlFunctionCtx* pCtx, int32_t numOfOutput, SResultRowInfo* pResultRowInfo,
                                        int32_t* rowCellInfoOffset) {
3518
  // update the number of result for each, only update the number of rows for the corresponding window result.
L
Liu Jicong 已提交
3519 3520 3521
  //  if (QUERY_IS_INTERVAL_QUERY(pQueryAttr)) {
  //    return;
  //  }
H
Haojun Liao 已提交
3522
#if 0
3523
  for (int32_t i = 0; i < pResultRowInfo->size; ++i) {
L
Liu Jicong 已提交
3524
    SResultRow* pResult = pResultRowInfo->pResult[i];
3525 3526 3527 3528 3529 3530 3531

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

3532 3533
      SResultRowEntryInfo* pCell = getResultCell(pResult, j, rowCellInfoOffset);
      pResult->numOfRows = (uint16_t)(TMAX(pResult->numOfRows, pCell->numOfRes));
3534 3535
    }
  }
H
Haojun Liao 已提交
3536 3537
#endif

3538 3539
}

L
Liu Jicong 已提交
3540
static int32_t compressQueryColData(SColumnInfoData* pColRes, int32_t numOfRows, char* data, int8_t compressed) {
3541 3542
  int32_t colSize = pColRes->info.bytes * numOfRows;
  return (*(tDataTypes[pColRes->info.type].compFunc))(pColRes->pData, colSize, numOfRows, data,
L
Liu Jicong 已提交
3543
                                                      colSize + COMP_OVERFLOW_BYTES, compressed, NULL, 0);
3544 3545
}

L
Liu Jicong 已提交
3546 3547 3548 3549 3550
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);
  //  }
3551 3552 3553 3554 3555 3556 3557 3558 3559 3560

  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 已提交
3561 3562
  event.eventType = eventType;
  event.eventTime = taosGetTimestampUs();
3563 3564 3565
  event.operatorType = operatorInfo->operatorType;

  if (operatorInfo->pRuntimeEnv) {
L
Liu Jicong 已提交
3566 3567 3568 3569
    //    SQInfo* pQInfo = operatorInfo->pRuntimeEnv->qinfo;
    //    if (pQInfo->summary.queryProfEvents) {
    //      taosArrayPush(pQInfo->summary.queryProfEvents, &event);
    //    }
3570 3571 3572
  }
}

L
Liu Jicong 已提交
3573
void publishQueryAbortEvent(SExecTaskInfo* pTaskInfo, int32_t code) {
3574 3575 3576 3577 3578
  SQueryProfEvent event;
  event.eventType = QUERY_PROF_QUERY_ABORT;
  event.eventTime = taosGetTimestampUs();
  event.abortCode = code;

3579 3580
  if (pTaskInfo->cost.queryProfEvents) {
    taosArrayPush(pTaskInfo->cost.queryProfEvents, &event);
3581 3582 3583
  }
}

L
Liu Jicong 已提交
3584
typedef struct {
3585 3586 3587 3588 3589 3590 3591
  uint8_t operatorType;
  int64_t beginTime;
  int64_t endTime;
  int64_t selfTime;
  int64_t descendantsTime;
} SOperatorStackItem;

L
Liu Jicong 已提交
3592 3593
static void doOperatorExecProfOnce(SOperatorStackItem* item, SQueryProfEvent* event, SArray* opStack,
                                   SHashObj* profResults) {
3594 3595 3596 3597 3598 3599 3600 3601
  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 已提交
3602
  uint8_t              operatorType = item->operatorType;
3603 3604 3605 3606 3607 3608 3609 3610 3611
  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 已提交
3612
    taosHashPut(profResults, &(operatorType), sizeof(operatorType), &opResult, sizeof(opResult));
3613 3614 3615 3616 3617
  }
}

void calculateOperatorProfResults(SQInfo* pQInfo) {
  if (pQInfo->summary.queryProfEvents == NULL) {
L
Liu Jicong 已提交
3618
    // qDebug("QInfo:0x%"PRIx64" query prof events array is null", pQInfo->qId);
3619 3620 3621 3622
    return;
  }

  if (pQInfo->summary.operatorProfResults == NULL) {
L
Liu Jicong 已提交
3623
    // qDebug("QInfo:0x%"PRIx64" operator prof results hash is null", pQInfo->qId);
3624 3625 3626 3627 3628 3629 3630 3631
    return;
  }

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

L
Liu Jicong 已提交
3632
  size_t    size = taosArrayGetSize(pQInfo->summary.queryProfEvents);
3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657
  SHashObj* profResults = pQInfo->summary.operatorProfResults;

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

  taosArrayDestroy(opStack);
}

L
Liu Jicong 已提交
3658 3659
void queryCostStatis(SExecTaskInfo* pTaskInfo) {
  STaskCostInfo* pSummary = &pTaskInfo->cost;
3660

L
Liu Jicong 已提交
3661 3662 3663
  //  uint64_t hashSize = taosHashGetMemSize(pQInfo->runtimeEnv.pResultRowHashTable);
  //  hashSize += taosHashGetMemSize(pRuntimeEnv->tableqinfoGroupInfo.map);
  //  pSummary->hashSize = hashSize;
3664 3665 3666 3667

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

L
Liu Jicong 已提交
3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687
  //  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);
3688 3689 3690 3691

  if (pSummary->operatorProfResults) {
    SOperatorProfResult* opRes = taosHashIterate(pSummary->operatorProfResults, NULL);
    while (opRes != NULL) {
L
Liu Jicong 已提交
3692 3693
      // qDebug("QInfo:0x%" PRIx64 " :cost summary: operator : %d, exec times: %" PRId64 ", self time: %" PRId64,
      //             pQInfo->qId, opRes->operatorType, opRes->sumRunTimes, opRes->sumSelfTime);
3694 3695 3696 3697 3698
      opRes = taosHashIterate(pSummary->operatorProfResults, opRes);
    }
  }
}

L
Liu Jicong 已提交
3699 3700 3701
// static void updateOffsetVal(STaskRuntimeEnv *pRuntimeEnv, SDataBlockInfo *pBlockInfo) {
//   STaskAttr *pQueryAttr = pRuntimeEnv->pQueryAttr;
//   STableQueryInfo* pTableQueryInfo = pRuntimeEnv->current;
3702
//
L
Liu Jicong 已提交
3703
//   int32_t step = GET_FORWARD_DIRECTION_FACTOR(pQueryAttr->order.order);
3704
//
L
Liu Jicong 已提交
3705 3706 3707 3708
//   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;
//   }
3709
//
L
Liu Jicong 已提交
3710 3711 3712 3713 3714
//   if (QUERY_IS_ASC_QUERY(pQueryAttr)) {
//     pQueryAttr->pos = (int32_t)pQueryAttr->limit.offset;
//   } else {
//     pQueryAttr->pos = pBlockInfo->rows - (int32_t)pQueryAttr->limit.offset - 1;
//   }
3715
//
L
Liu Jicong 已提交
3716
//   assert(pQueryAttr->pos >= 0 && pQueryAttr->pos <= pBlockInfo->rows - 1);
3717
//
L
Liu Jicong 已提交
3718 3719
//   SArray *         pDataBlock = tsdbRetrieveDataBlock(pRuntimeEnv->pTsdbReadHandle, NULL);
//   SColumnInfoData *pColInfoData = taosArrayGet(pDataBlock, 0);
3720
//
L
Liu Jicong 已提交
3721 3722
//   // update the pQueryAttr->limit.offset value, and pQueryAttr->pos value
//   TSKEY *keys = (TSKEY *) pColInfoData->pData;
3723
//
L
Liu Jicong 已提交
3724 3725 3726
//   // update the offset value
//   pTableQueryInfo->lastKey = keys[pQueryAttr->pos];
//   pQueryAttr->limit.offset = 0;
3727
//
L
Liu Jicong 已提交
3728
//   int32_t numOfRes = tableApplyFunctionsOnBlock(pRuntimeEnv, pBlockInfo, NULL, binarySearchForKey, pDataBlock);
3729
//
L
Liu Jicong 已提交
3730 3731 3732 3733
//   //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);
// }
3734

L
Liu Jicong 已提交
3735 3736
// void skipBlocks(STaskRuntimeEnv *pRuntimeEnv) {
//   STaskAttr *pQueryAttr = pRuntimeEnv->pQueryAttr;
3737
//
L
Liu Jicong 已提交
3738 3739 3740
//   if (pQueryAttr->limit.offset <= 0 || pQueryAttr->numOfFilterCols > 0) {
//     return;
//   }
3741
//
L
Liu Jicong 已提交
3742 3743
//   pQueryAttr->pos = 0;
//   int32_t step = GET_FORWARD_DIRECTION_FACTOR(pQueryAttr->order.order);
3744
//
L
Liu Jicong 已提交
3745 3746
//   STableQueryInfo* pTableQueryInfo = pRuntimeEnv->current;
//   TsdbQueryHandleT pTsdbReadHandle = pRuntimeEnv->pTsdbReadHandle;
3747
//
L
Liu Jicong 已提交
3748 3749 3750 3751 3752
//   SDataBlockInfo blockInfo = SDATA_BLOCK_INITIALIZER;
//   while (tsdbNextDataBlock(pTsdbReadHandle)) {
//     if (isTaskKilled(pRuntimeEnv->qinfo)) {
//       longjmp(pRuntimeEnv->env, TSDB_CODE_TSC_QUERY_CANCELLED);
//     }
3753
//
L
Liu Jicong 已提交
3754
//     tsdbRetrieveDataBlockInfo(pTsdbReadHandle, &blockInfo);
3755
//
L
Liu Jicong 已提交
3756 3757 3758 3759
//     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;
3760
//
L
Liu Jicong 已提交
3761 3762 3763 3764 3765 3766 3767
//       //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;
//     }
//   }
3768
//
L
Liu Jicong 已提交
3769 3770 3771 3772 3773 3774 3775 3776 3777
//   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;
3778
//
L
Liu Jicong 已提交
3779 3780 3781
//   assert(pQueryAttr->limit.offset == 0);
//   STimeWindow tw = *win;
//   getNextTimeWindow(pQueryAttr, &tw);
3782
//
L
Liu Jicong 已提交
3783 3784
//   if ((tw.skey <= pBlockInfo->window.ekey && QUERY_IS_ASC_QUERY(pQueryAttr)) ||
//       (tw.ekey >= pBlockInfo->window.skey && !QUERY_IS_ASC_QUERY(pQueryAttr))) {
3785
//
L
Liu Jicong 已提交
3786 3787 3788 3789
//     // 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);
3790
//
L
Liu Jicong 已提交
3791 3792 3793 3794
//     tw = *win;
//     int32_t startPos =
//         getNextQualifiedWindow(pQueryAttr, &tw, pBlockInfo, pColInfoData->pData, binarySearchForKey, -1);
//     assert(startPos >= 0);
3795
//
L
Liu Jicong 已提交
3796 3797
//     // set the abort info
//     pQueryAttr->pos = startPos;
3798
//
L
Liu Jicong 已提交
3799 3800 3801 3802
//     // reset the query start timestamp
//     pTableQueryInfo->win.skey = ((TSKEY *)pColInfoData->pData)[startPos];
//     pQueryAttr->window.skey = pTableQueryInfo->win.skey;
//     TSKEY key = pTableQueryInfo->win.skey;
3803
//
L
Liu Jicong 已提交
3804 3805
//     pWindowResInfo->prevSKey = tw.skey;
//     int32_t index = pRuntimeEnv->resultRowInfo.curIndex;
3806
//
L
Liu Jicong 已提交
3807 3808
//     int32_t numOfRes = tableApplyFunctionsOnBlock(pRuntimeEnv, pBlockInfo, NULL, binarySearchForKey, pDataBlock);
//     pRuntimeEnv->resultRowInfo.curIndex = index;  // restore the window index
3809
//
L
Liu Jicong 已提交
3810 3811 3812 3813
//     //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);
3814
//
L
Liu Jicong 已提交
3815 3816 3817 3818 3819
//     return key;
//   } else {  // do nothing
//     pQueryAttr->window.skey      = tw.skey;
//     pWindowResInfo->prevSKey = tw.skey;
//     pTableQueryInfo->lastKey = tw.skey;
3820
//
L
Liu Jicong 已提交
3821 3822
//     return tw.skey;
//   }
3823
//
L
Liu Jicong 已提交
3824 3825 3826 3827 3828 3829 3830 3831 3832 3833
//   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);
//   }
3834
//
L
Liu Jicong 已提交
3835 3836 3837 3838 3839
//   // 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;
//   }
3840
//
L
Liu Jicong 已提交
3841 3842 3843 3844 3845 3846 3847
//   /*
//    * 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);
3848
//
L
Liu Jicong 已提交
3849 3850
//   STimeWindow w = TSWINDOW_INITIALIZER;
//   bool ascQuery = QUERY_IS_ASC_QUERY(pQueryAttr);
3851
//
L
Liu Jicong 已提交
3852 3853
//   SResultRowInfo *pWindowResInfo = &pRuntimeEnv->resultRowInfo;
//   STableQueryInfo *pTableQueryInfo = pRuntimeEnv->current;
3854
//
L
Liu Jicong 已提交
3855 3856 3857
//   SDataBlockInfo blockInfo = SDATA_BLOCK_INITIALIZER;
//   while (tsdbNextDataBlock(pRuntimeEnv->pTsdbReadHandle)) {
//     tsdbRetrieveDataBlockInfo(pRuntimeEnv->pTsdbReadHandle, &blockInfo);
3858
//
L
Liu Jicong 已提交
3859 3860 3861 3862 3863 3864 3865 3866 3867
//     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;
//     }
3868
//
L
Liu Jicong 已提交
3869 3870
//     // the first time window
//     STimeWindow win = getActiveTimeWindow(pWindowResInfo, pWindowResInfo->prevSKey, pQueryAttr);
3871
//
L
Liu Jicong 已提交
3872 3873
//     while (pQueryAttr->limit.offset > 0) {
//       STimeWindow tw = win;
3874
//
L
Liu Jicong 已提交
3875 3876 3877
//       if ((win.ekey <= blockInfo.window.ekey && ascQuery) || (win.ekey >= blockInfo.window.skey && !ascQuery)) {
//         pQueryAttr->limit.offset -= 1;
//         pWindowResInfo->prevSKey = win.skey;
3878
//
L
Liu Jicong 已提交
3879 3880 3881 3882 3883 3884
//         // 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;
//         }
//       }
3885
//
L
Liu Jicong 已提交
3886 3887 3888 3889
//       if (pQueryAttr->limit.offset == 0) {
//         *start = doSkipIntervalProcess(pRuntimeEnv, &win, &blockInfo, pTableQueryInfo);
//         return true;
//       }
3890
//
L
Liu Jicong 已提交
3891 3892
//       // current window does not ended in current data block, try next data block
//       getNextTimeWindow(pQueryAttr, &tw);
3893
//
L
Liu Jicong 已提交
3894 3895 3896 3897 3898 3899 3900 3901 3902
//       /*
//        * 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)) {
3903
//
L
Liu Jicong 已提交
3904 3905
//         SArray *pDataBlock = tsdbRetrieveDataBlock(pRuntimeEnv->pTsdbReadHandle, NULL);
//         SColumnInfoData *pColInfoData = taosArrayGet(pDataBlock, 0);
3906
//
L
Liu Jicong 已提交
3907 3908 3909
//         if ((win.ekey > blockInfo.window.ekey && ascQuery) || (win.ekey < blockInfo.window.skey && !ascQuery)) {
//           pQueryAttr->limit.offset -= 1;
//         }
3910
//
L
Liu Jicong 已提交
3911 3912 3913 3914 3915 3916 3917 3918
//         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);
3919
//
L
Liu Jicong 已提交
3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930
//           // 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.
//       }
//     }
//   }
3931
//
L
Liu Jicong 已提交
3932 3933 3934 3935
//   // check for error
//   if (terrno != TSDB_CODE_SUCCESS) {
//     longjmp(pRuntimeEnv->env, terrno);
//   }
3936
//
L
Liu Jicong 已提交
3937 3938
//   return true;
// }
3939

3940
int32_t appendDownstream(SOperatorInfo* p, SOperatorInfo** pDownstream, int32_t num) {
H
Haojun Liao 已提交
3941
  if (p->pDownstream == NULL) {
H
Haojun Liao 已提交
3942
    assert(p->numOfDownstream == 0);
3943 3944
  }

wafwerar's avatar
wafwerar 已提交
3945
  p->pDownstream = taosMemoryCalloc(1, num * POINTER_BYTES);
3946 3947 3948 3949 3950 3951 3952
  if (p->pDownstream == NULL) {
    return TSDB_CODE_OUT_OF_MEMORY;
  }

  memcpy(p->pDownstream, pDownstream, num * POINTER_BYTES);
  p->numOfDownstream = num;
  return TSDB_CODE_SUCCESS;
3953 3954 3955 3956
}

static void doDestroyTableQueryInfo(STableGroupInfo* pTableqinfoGroupInfo);

H
Haojun Liao 已提交
3957
static int32_t setupQueryHandle(void* tsdb, STaskRuntimeEnv* pRuntimeEnv, int64_t qId, bool isSTableQuery) {
L
Liu Jicong 已提交
3958
  STaskAttr* pQueryAttr = pRuntimeEnv->pQueryAttr;
3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983
#if 0
  // TODO set the tags scan handle
  if (onlyQueryTags(pQueryAttr)) {
    return TSDB_CODE_SUCCESS;
  }

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

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

  terrno = TSDB_CODE_SUCCESS;
  if (isFirstLastRowQuery(pQueryAttr)) {
3984
    pRuntimeEnv->pTsdbReadHandle = tsdbQueryLastRow(tsdb, &cond, &pQueryAttr->tableGroupInfo, qId, &pQueryAttr->memRef);
3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004

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

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

          pCheckInfo->win = pQueryAttr->window;
          pCheckInfo->lastKey = pCheckInfo->win.skey;
        }
      }
    }
  } else if (isCachedLastQuery(pQueryAttr)) {
4005
    pRuntimeEnv->pTsdbReadHandle = tsdbQueryCacheLast(tsdb, &cond, &pQueryAttr->tableGroupInfo, qId, &pQueryAttr->memRef);
4006
  } else if (pQueryAttr->pointInterpQuery) {
4007
    pRuntimeEnv->pTsdbReadHandle = tsdbQueryRowsInExternalWindow(tsdb, &cond, &pQueryAttr->tableGroupInfo, qId, &pQueryAttr->memRef);
4008
  } else {
4009
    pRuntimeEnv->pTsdbReadHandle = tsdbQueryTables(tsdb, &cond, &pQueryAttr->tableGroupInfo, qId, &pQueryAttr->memRef);
4010 4011 4012 4013 4014
  }
#endif
  return terrno;
}

4015
static void doTableQueryInfoTimeWindowCheck(SExecTaskInfo* pTaskInfo, STableQueryInfo* pTableQueryInfo, int32_t order) {
H
Haojun Liao 已提交
4016 4017
#if 0
    if (order == TSDB_ORDER_ASC) {
4018 4019
    assert(
        (pTableQueryInfo->win.skey <= pTableQueryInfo->win.ekey) &&
H
Haojun Liao 已提交
4020 4021
        (pTableQueryInfo->lastKey >= pTaskInfo->window.skey) &&
        (pTableQueryInfo->win.skey >= pTaskInfo->window.skey && pTableQueryInfo->win.ekey <= pTaskInfo->window.ekey));
4022 4023 4024
  } else {
    assert(
        (pTableQueryInfo->win.skey >= pTableQueryInfo->win.ekey) &&
H
Haojun Liao 已提交
4025 4026
        (pTableQueryInfo->lastKey <= pTaskInfo->window.skey) &&
        (pTableQueryInfo->win.skey <= pTaskInfo->window.skey && pTableQueryInfo->win.ekey >= pTaskInfo->window.ekey));
4027
  }
H
Haojun Liao 已提交
4028
#endif
4029 4030
}

L
Liu Jicong 已提交
4031 4032 4033 4034 4035 4036 4037 4038
// 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,
//   };
4039
//
L
Liu Jicong 已提交
4040 4041 4042
//   TIME_WINDOW_COPY(cond.twindow, *win);
//   return cond;
// }
4043 4044 4045

static STableIdInfo createTableIdInfo(STableQueryInfo* pTableQueryInfo) {
  STableIdInfo tidInfo;
L
Liu Jicong 已提交
4046 4047 4048 4049 4050
  //  STableId* id = TSDB_TABLEID(pTableQueryInfo->pTable);
  //
  //  tidInfo.uid = id->uid;
  //  tidInfo.tid = id->tid;
  //  tidInfo.key = pTableQueryInfo->lastKey;
4051 4052 4053 4054

  return tidInfo;
}

L
Liu Jicong 已提交
4055 4056 4057 4058
// 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;
4059
//
L
Liu Jicong 已提交
4060 4061 4062
//   if (pTableQueryInfo->pTable == NULL) {
//     return;
//   }
4063
//
L
Liu Jicong 已提交
4064 4065 4066 4067 4068 4069 4070 4071 4072
//   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));
//   }
// }
4073

H
Haojun Liao 已提交
4074
static void doCloseAllTimeWindow(STaskRuntimeEnv* pRuntimeEnv) {
4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086
  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);
    }
  }
}

4087
int32_t loadRemoteDataCallback(void* param, const SDataBuf* pMsg, int32_t code) {
L
Liu Jicong 已提交
4088
  SSourceDataInfo* pSourceDataInfo = (SSourceDataInfo*)param;
H
Haojun Liao 已提交
4089 4090
  if (code == TSDB_CODE_SUCCESS) {
    pSourceDataInfo->pRsp = pMsg->pData;
4091

H
Haojun Liao 已提交
4092 4093 4094 4095 4096 4097 4098
    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 已提交
4099

H
Haojun Liao 已提交
4100
  pSourceDataInfo->status = EX_SOURCE_DATA_READY;
4101
  tsem_post(&pSourceDataInfo->pEx->ready);
H
Haojun Liao 已提交
4102 4103 4104 4105
}

static void destroySendMsgInfo(SMsgSendInfo* pMsgBody) {
  assert(pMsgBody != NULL);
wafwerar's avatar
wafwerar 已提交
4106 4107
  taosMemoryFreeClear(pMsgBody->msgInfo.pData);
  taosMemoryFreeClear(pMsgBody);
H
Haojun Liao 已提交
4108 4109
}

S
Shengliang Guan 已提交
4110
void qProcessFetchRsp(void* parent, SRpcMsg* pMsg, SEpSet* pEpSet) {
L
Liu Jicong 已提交
4111
  SMsgSendInfo* pSendInfo = (SMsgSendInfo*)pMsg->ahandle;
H
Haojun Liao 已提交
4112 4113 4114 4115 4116
  assert(pMsg->ahandle != NULL);

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

  if (pMsg->contLen > 0) {
wafwerar's avatar
wafwerar 已提交
4117
    buf.pData = taosMemoryCalloc(1, pMsg->contLen);
H
Haojun Liao 已提交
4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128
    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);
4129 4130
}

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

wafwerar's avatar
wafwerar 已提交
4134
  SResFetchReq* pMsg = taosMemoryCalloc(1, sizeof(SResFetchReq));
4135 4136 4137 4138
  if (NULL == pMsg) {
    pTaskInfo->code = TSDB_CODE_QRY_OUT_OF_MEMORY;
    return pTaskInfo->code;
  }
4139

L
Liu Jicong 已提交
4140 4141
  SDownstreamSourceNode* pSource = taosArrayGet(pExchangeInfo->pSources, sourceIndex);
  SSourceDataInfo*       pDataInfo = taosArrayGet(pExchangeInfo->pSourceDataInfo, sourceIndex);
4142

L
Liu Jicong 已提交
4143 4144
  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);
4145 4146 4147 4148 4149 4150 4151

  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 已提交
4152
  SMsgSendInfo* pMsgSendInfo = taosMemoryCalloc(1, sizeof(SMsgSendInfo));
4153
  if (NULL == pMsgSendInfo) {
wafwerar's avatar
wafwerar 已提交
4154
    taosMemoryFreeClear(pMsg);
4155 4156 4157
    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 已提交
4158 4159
  }

4160 4161 4162 4163 4164
  pMsgSendInfo->param = pDataInfo;
  pMsgSendInfo->msgInfo.pData = pMsg;
  pMsgSendInfo->msgInfo.len = sizeof(SResFetchReq);
  pMsgSendInfo->msgType = TDMT_VND_FETCH;
  pMsgSendInfo->fp = loadRemoteDataCallback;
4165

4166
  int64_t transporterId = 0;
L
Liu Jicong 已提交
4167
  int32_t code = asyncSendMsgToServer(pExchangeInfo->pTransporter, &pSource->addr.epSet, &transporterId, pMsgSendInfo);
4168 4169 4170
  return TSDB_CODE_SUCCESS;
}

4171
// TODO if only one or two columnss required, how to extract data?
H
Haojun Liao 已提交
4172
int32_t setSDataBlockFromFetchRsp(SSDataBlock* pRes, SLoadRemoteDataInfo* pLoadInfo, int32_t numOfRows,
L
Liu Jicong 已提交
4173 4174
                                         char* pData, int32_t compLen, int32_t numOfOutput, int64_t startTs,
                                         uint64_t* total, SArray* pColList) {
H
Haojun Liao 已提交
4175
  blockDataEnsureCapacity(pRes, numOfRows);
4176

H
Haojun Liao 已提交
4177 4178
  if (pColList == NULL) {  // data from other sources
    int32_t* colLen = (int32_t*)pData;
L
Liu Jicong 已提交
4179
    char*    pStart = pData + sizeof(int32_t) * numOfOutput;
H
Haojun Liao 已提交
4180

4181
    for (int32_t i = 0; i < numOfOutput; ++i) {
H
Haojun Liao 已提交
4182 4183 4184
      colLen[i] = htonl(colLen[i]);
      ASSERT(colLen[i] > 0);

4185
      SColumnInfoData* pColInfoData = taosArrayGet(pRes->pDataBlock, i);
H
Haojun Liao 已提交
4186 4187 4188
      if (IS_VAR_DATA_TYPE(pColInfoData->info.type)) {
        pColInfoData->varmeta.length = colLen[i];
        pColInfoData->varmeta.allocLen = colLen[i];
4189

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

wafwerar's avatar
wafwerar 已提交
4193
        pColInfoData->pData = taosMemoryMalloc(colLen[i]);
H
Haojun Liao 已提交
4194 4195 4196
      } else {
        memcpy(pColInfoData->nullbitmap, pStart, BitmapLen(numOfRows));
        pStart += BitmapLen(numOfRows);
4197
      }
H
Haojun Liao 已提交
4198 4199 4200

      memcpy(pColInfoData->pData, pStart, colLen[i]);
      pStart += colLen[i];
4201
    }
H
Haojun Liao 已提交
4202
  } else {  // extract data according to pColList
4203
    ASSERT(numOfOutput == taosArrayGetSize(pColList));
H
Haojun Liao 已提交
4204 4205

    // data from mnode
L
Liu Jicong 已提交
4206 4207 4208
    for (int32_t i = 0; i < numOfOutput; ++i) {
      for (int32_t j = 0; j < numOfOutput; ++j) {
        int16_t colIndex = *(int16_t*)taosArrayGet(pColList, j);
4209 4210
        if (colIndex - 1 == i) {
          SColumnInfoData* pColInfoData = taosArrayGet(pRes->pDataBlock, j);
4211

4212 4213 4214 4215 4216 4217 4218
          for (int32_t k = 0; k < numOfRows; ++k) {
            colDataAppend(pColInfoData, k, pData, false);
            pData += pColInfoData->info.bytes;
          }
          break;
        }
      }
4219
    }
4220
  }
4221

H
Haojun Liao 已提交
4222
  pRes->info.rows = numOfRows;
4223

4224
  int64_t el = taosGetTimestampUs() - startTs;
4225

H
Haojun Liao 已提交
4226 4227
  pLoadInfo->totalRows += numOfRows;
  pLoadInfo->totalSize += compLen;
4228

H
Haojun Liao 已提交
4229 4230 4231
  if (total != NULL) {
    *total += numOfRows;
  }
4232

H
Haojun Liao 已提交
4233
  pLoadInfo->totalElapsed += el;
4234 4235
  return TSDB_CODE_SUCCESS;
}
4236

L
Liu Jicong 已提交
4237 4238
static void* setAllSourcesCompleted(SOperatorInfo* pOperator, int64_t startTs) {
  SExchangeInfo* pExchangeInfo = pOperator->info;
4239
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
H
Haojun Liao 已提交
4240

L
Liu Jicong 已提交
4241
  int64_t              el = taosGetTimestampUs() - startTs;
H
Haojun Liao 已提交
4242 4243
  SLoadRemoteDataInfo* pLoadInfo = &pExchangeInfo->loadInfo;
  pLoadInfo->totalElapsed += el;
H
Haojun Liao 已提交
4244

4245
  size_t totalSources = taosArrayGetSize(pExchangeInfo->pSources);
L
Liu Jicong 已提交
4246 4247 4248
  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);
4249 4250 4251 4252 4253

  doSetOperatorCompleted(pOperator);
  return NULL;
}

L
Liu Jicong 已提交
4254 4255
static SSDataBlock* concurrentlyLoadRemoteDataImpl(SOperatorInfo* pOperator, SExchangeInfo* pExchangeInfo,
                                                   SExecTaskInfo* pTaskInfo) {
4256 4257 4258 4259 4260 4261 4262 4263 4264
  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);

4265
      if (pDataInfo->status == EX_SOURCE_DATA_EXHAUSTED) {
4266
        completed += 1;
H
Haojun Liao 已提交
4267 4268
        continue;
      }
4269

4270
      if (pDataInfo->status != EX_SOURCE_DATA_READY) {
4271 4272 4273
        continue;
      }

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

L
Liu Jicong 已提交
4277
      SSDataBlock*         pRes = pExchangeInfo->pResult;
H
Haojun Liao 已提交
4278
      SLoadRemoteDataInfo* pLoadInfo = &pExchangeInfo->loadInfo;
4279
      if (pRsp->numOfRows == 0) {
L
Liu Jicong 已提交
4280 4281
        qDebug("%s vgId:%d, taskID:0x%" PRIx64 " index:%d completed, rowsOfSource:%" PRIu64 ", totalRows:%" PRIu64
               " try next",
4282
               GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->taskId, i + 1, pDataInfo->totalRows,
H
Haojun Liao 已提交
4283
               pExchangeInfo->loadInfo.totalRows);
4284
        pDataInfo->status = EX_SOURCE_DATA_EXHAUSTED;
4285 4286 4287
        completed += 1;
        continue;
      }
H
Haojun Liao 已提交
4288

H
Haojun Liao 已提交
4289
      SRetrieveTableRsp* pTableRsp = pDataInfo->pRsp;
L
Liu Jicong 已提交
4290 4291 4292
      code =
          setSDataBlockFromFetchRsp(pExchangeInfo->pResult, pLoadInfo, pTableRsp->numOfRows, pTableRsp->data,
                                    pTableRsp->compLen, pOperator->numOfOutput, startTs, &pDataInfo->totalRows, NULL);
4293
      if (code != 0) {
4294 4295 4296
        goto _error;
      }

4297 4298 4299
      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 已提交
4300 4301
               GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->taskId, pRes->info.rows, pDataInfo->totalRows,
               pLoadInfo->totalRows, pLoadInfo->totalSize, i + 1, totalSources);
4302
        pDataInfo->status = EX_SOURCE_DATA_EXHAUSTED;
4303
      } else {
4304
        qDebug("%s fetch msg rsp from vgId:%d, taskId:0x%" PRIx64 " numOfRows:%d, totalRows:%" PRIu64 ", totalBytes:%" PRIu64,
H
Haojun Liao 已提交
4305 4306
               GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->taskId, pRes->info.rows, pLoadInfo->totalRows,
               pLoadInfo->totalSize);
4307 4308
      }

4309 4310
      if (pDataInfo->status != EX_SOURCE_DATA_EXHAUSTED) {
        pDataInfo->status = EX_SOURCE_DATA_NOT_READY;
4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329
        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 已提交
4330 4331 4332
static SSDataBlock* concurrentlyLoadRemoteData(SOperatorInfo* pOperator) {
  SExchangeInfo* pExchangeInfo = pOperator->info;
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
H
Haojun Liao 已提交
4333

H
Haojun Liao 已提交
4334 4335 4336
  if (pOperator->status == OP_RES_TO_RETURN) {
    return concurrentlyLoadRemoteDataImpl(pOperator, pExchangeInfo, pTaskInfo);
  }
4337

L
Liu Jicong 已提交
4338
  size_t  totalSources = taosArrayGetSize(pExchangeInfo->pSources);
4339 4340 4341
  int64_t startTs = taosGetTimestampUs();

  // Asynchronously send all fetch requests to all sources.
L
Liu Jicong 已提交
4342
  for (int32_t i = 0; i < totalSources; ++i) {
4343 4344
    int32_t code = doSendFetchDataRequest(pExchangeInfo, pTaskInfo, i);
    if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
4345
      return NULL;
4346 4347 4348 4349
    }
  }

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

  tsem_wait(&pExchangeInfo->ready);
H
Haojun Liao 已提交
4354 4355
  pOperator->status = OP_RES_TO_RETURN;
  return concurrentlyLoadRemoteDataImpl(pOperator, pExchangeInfo, pTaskInfo);
4356 4357
}

L
Liu Jicong 已提交
4358 4359 4360
static int32_t prepareConcurrentlyLoad(SOperatorInfo* pOperator) {
  SExchangeInfo* pExchangeInfo = pOperator->info;
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
4361

L
Liu Jicong 已提交
4362
  size_t  totalSources = taosArrayGetSize(pExchangeInfo->pSources);
4363 4364 4365
  int64_t startTs = taosGetTimestampUs();

  // Asynchronously send all fetch requests to all sources.
L
Liu Jicong 已提交
4366
  for (int32_t i = 0; i < totalSources; ++i) {
4367 4368
    int32_t code = doSendFetchDataRequest(pExchangeInfo, pTaskInfo, i);
    if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
4369 4370
      pTaskInfo->code = code;
      return code;
4371 4372 4373 4374
    }
  }

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

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

H
Haojun Liao 已提交
4381
  return TSDB_CODE_SUCCESS;
4382 4383
}

L
Liu Jicong 已提交
4384 4385 4386
static SSDataBlock* seqLoadRemoteData(SOperatorInfo* pOperator) {
  SExchangeInfo* pExchangeInfo = pOperator->info;
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
4387

L
Liu Jicong 已提交
4388
  size_t  totalSources = taosArrayGetSize(pExchangeInfo->pSources);
4389
  int64_t startTs = taosGetTimestampUs();
4390

L
Liu Jicong 已提交
4391
  while (1) {
4392 4393
    if (pExchangeInfo->current >= totalSources) {
      return setAllSourcesCompleted(pOperator, startTs);
4394
    }
4395

4396 4397 4398
    doSendFetchDataRequest(pExchangeInfo, pTaskInfo, pExchangeInfo->current);
    tsem_wait(&pExchangeInfo->ready);

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

H
Haojun Liao 已提交
4402 4403 4404 4405 4406 4407 4408
    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 已提交
4409
    SRetrieveTableRsp*   pRsp = pDataInfo->pRsp;
H
Haojun Liao 已提交
4410
    SLoadRemoteDataInfo* pLoadInfo = &pExchangeInfo->loadInfo;
4411
    if (pRsp->numOfRows == 0) {
H
Haojun Liao 已提交
4412
      qDebug("%s vgId:%d, taskID:0x%" PRIx64 " %d of total completed, rowsOfSource:%" PRIu64 ", totalRows:%" PRIu64 " try next",
4413
             GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->taskId, pExchangeInfo->current + 1,
H
Haojun Liao 已提交
4414
             pDataInfo->totalRows, pLoadInfo->totalRows);
H
Haojun Liao 已提交
4415

4416
      pDataInfo->status = EX_SOURCE_DATA_EXHAUSTED;
4417 4418 4419
      pExchangeInfo->current += 1;
      continue;
    }
H
Haojun Liao 已提交
4420

L
Liu Jicong 已提交
4421
    SSDataBlock*       pRes = pExchangeInfo->pResult;
H
Haojun Liao 已提交
4422
    SRetrieveTableRsp* pTableRsp = pDataInfo->pRsp;
L
Liu Jicong 已提交
4423 4424 4425
    int32_t            code =
        setSDataBlockFromFetchRsp(pExchangeInfo->pResult, pLoadInfo, pTableRsp->numOfRows, pTableRsp->data,
                                  pTableRsp->compLen, pOperator->numOfOutput, startTs, &pDataInfo->totalRows, NULL);
4426 4427

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

4433
      pDataInfo->status = EX_SOURCE_DATA_EXHAUSTED;
4434 4435
      pExchangeInfo->current += 1;
    } else {
L
Liu Jicong 已提交
4436 4437 4438 4439
      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);
4440 4441 4442 4443
    }

    return pExchangeInfo->pResult;
  }
4444 4445
}

L
Liu Jicong 已提交
4446
static int32_t prepareLoadRemoteData(SOperatorInfo* pOperator) {
4447
  if (OPTR_IS_OPENED(pOperator)) {
H
Haojun Liao 已提交
4448 4449 4450
    return TSDB_CODE_SUCCESS;
  }

L
Liu Jicong 已提交
4451
  SExchangeInfo* pExchangeInfo = pOperator->info;
H
Haojun Liao 已提交
4452 4453 4454 4455 4456 4457 4458 4459 4460
  if (pExchangeInfo->seqLoadData) {
    // do nothing for sequentially load data
  } else {
    int32_t code = prepareConcurrentlyLoad(pOperator);
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }
  }

4461
  OPTR_SET_OPENED(pOperator);
H
Haojun Liao 已提交
4462 4463 4464
  return TSDB_CODE_SUCCESS;
}

L
Liu Jicong 已提交
4465 4466 4467
static SSDataBlock* doLoadRemoteData(SOperatorInfo* pOperator, bool* newgroup) {
  SExchangeInfo* pExchangeInfo = pOperator->info;
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
4468

4469 4470
  pTaskInfo->code = pOperator->_openFn(pOperator);
  if (pTaskInfo->code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
4471 4472
    return NULL;
  }
4473

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

4477
  if (pOperator->status == OP_EXEC_DONE) {
L
Liu Jicong 已提交
4478 4479 4480
    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);
4481 4482 4483 4484
    return NULL;
  }

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

4486 4487 4488
  if (pExchangeInfo->seqLoadData) {
    return seqLoadRemoteData(pOperator);
  } else {
H
Haojun Liao 已提交
4489
    return concurrentlyLoadRemoteData(pOperator);
4490
  }
H
Haojun Liao 已提交
4491

4492
#if 0
H
Haojun Liao 已提交
4493
  _error:
wafwerar's avatar
wafwerar 已提交
4494 4495
  taosMemoryFreeClear(pMsg);
  taosMemoryFreeClear(pMsgSendInfo);
H
Haojun Liao 已提交
4496 4497 4498

  terrno = pTaskInfo->code;
  return NULL;
4499
#endif
H
Haojun Liao 已提交
4500
}
4501

H
Haojun Liao 已提交
4502
static int32_t initDataSource(int32_t numOfSources, SExchangeInfo* pInfo) {
4503
  pInfo->pSourceDataInfo = taosArrayInit(numOfSources, sizeof(SSourceDataInfo));
H
Haojun Liao 已提交
4504 4505
  if (pInfo->pSourceDataInfo == NULL) {
    return TSDB_CODE_OUT_OF_MEMORY;
4506 4507
  }

L
Liu Jicong 已提交
4508
  for (int32_t i = 0; i < numOfSources; ++i) {
4509
    SSourceDataInfo dataInfo = {0};
H
Haojun Liao 已提交
4510
    dataInfo.status = EX_SOURCE_DATA_NOT_READY;
L
Liu Jicong 已提交
4511 4512
    dataInfo.pEx = pInfo;
    dataInfo.index = i;
4513

H
Haojun Liao 已提交
4514 4515 4516 4517 4518 4519 4520 4521 4522 4523
    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 已提交
4524
SOperatorInfo* createExchangeOperatorInfo(const SNodeList* pSources, SSDataBlock* pBlock, SExecTaskInfo* pTaskInfo) {
L
Liu Jicong 已提交
4525
  SExchangeInfo* pInfo = taosMemoryCalloc(1, sizeof(SExchangeInfo));
wafwerar's avatar
wafwerar 已提交
4526
  SOperatorInfo* pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
4527 4528

  if (pInfo == NULL || pOperator == NULL) {
wafwerar's avatar
wafwerar 已提交
4529 4530
    taosMemoryFreeClear(pInfo);
    taosMemoryFreeClear(pOperator);
H
Haojun Liao 已提交
4531 4532
    terrno = TSDB_CODE_QRY_OUT_OF_MEMORY;
    return NULL;
H
Haojun Liao 已提交
4533 4534
  }

H
Haojun Liao 已提交
4535
  size_t numOfSources = LIST_LENGTH(pSources);
H
Haojun Liao 已提交
4536
  pInfo->pSources = taosArrayInit(numOfSources, sizeof(SDownstreamSourceNode));
H
Haojun Liao 已提交
4537 4538 4539
  pInfo->pSourceDataInfo = taosArrayInit(numOfSources, sizeof(SSourceDataInfo));
  if (pInfo->pSourceDataInfo == NULL || pInfo->pSources == NULL) {
    goto _error;
H
Haojun Liao 已提交
4540 4541
  }

L
Liu Jicong 已提交
4542 4543
  for (int32_t i = 0; i < numOfSources; ++i) {
    SNodeListNode* pNode = nodesListGetNode((SNodeList*)pSources, i);
H
Haojun Liao 已提交
4544 4545
    taosArrayPush(pInfo->pSources, pNode);
  }
4546

H
Haojun Liao 已提交
4547 4548 4549
  int32_t code = initDataSource(numOfSources, pInfo);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
4550
  }
H
Haojun Liao 已提交
4551

L
Liu Jicong 已提交
4552 4553
  size_t size = pBlock->info.numOfCols;
  pInfo->pResult = pBlock;
4554 4555 4556
  pInfo->seqLoadData = true;

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

L
Liu Jicong 已提交
4558
  pOperator->name = "ExchangeOperator";
X
Xiaoyu Wang 已提交
4559
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_EXCHANGE;
4560
  pOperator->blockingOptr = false;
L
Liu Jicong 已提交
4561 4562 4563 4564 4565 4566 4567
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
  pOperator->numOfOutput = size;
  pOperator->pTaskInfo = pTaskInfo;
  pOperator->_openFn = prepareLoadRemoteData;  // assign a dummy function.
  pOperator->getNextFn = doLoadRemoteData;
  pOperator->closeFn = destroyExchangeOperatorInfo;
4568

S
Shengliang Guan 已提交
4569
#if 1
L
Liu Jicong 已提交
4570
  {  // todo refactor
H
Haojun Liao 已提交
4571 4572 4573
    SRpcInit rpcInit;
    memset(&rpcInit, 0, sizeof(rpcInit));
    rpcInit.localPort = 0;
H
Haojun Liao 已提交
4574
    rpcInit.label = "EX";
H
Haojun Liao 已提交
4575
    rpcInit.numOfThreads = 1;
S
Shengliang Guan 已提交
4576
    rpcInit.cfp = qProcessFetchRsp;
S
Shengliang Guan 已提交
4577
    rpcInit.sessions = tsMaxConnections;
H
Haojun Liao 已提交
4578
    rpcInit.connType = TAOS_CONN_CLIENT;
L
Liu Jicong 已提交
4579
    rpcInit.user = (char*)"root";
S
Shengliang Guan 已提交
4580
    rpcInit.idleTime = tsShellActivityTimer * 1000;
H
Haojun Liao 已提交
4581
    rpcInit.ckey = "key";
S
Shengliang Guan 已提交
4582
    rpcInit.spi = 1;
L
Liu Jicong 已提交
4583
    rpcInit.secret = (char*)"dcc5bed04851fec854c035b2e40263b6";
H
Haojun Liao 已提交
4584 4585 4586

    pInfo->pTransporter = rpcOpen(&rpcInit);
    if (pInfo->pTransporter == NULL) {
L
Liu Jicong 已提交
4587
      return NULL;  // todo
H
Haojun Liao 已提交
4588 4589
    }
  }
S
Shengliang 已提交
4590
#endif
4591

4592
  return pOperator;
H
Haojun Liao 已提交
4593

L
Liu Jicong 已提交
4594
_error:
H
Haojun Liao 已提交
4595
  if (pInfo != NULL) {
H
Haojun Liao 已提交
4596
    destroyExchangeOperatorInfo(pInfo, numOfSources);
H
Haojun Liao 已提交
4597 4598
  }

wafwerar's avatar
wafwerar 已提交
4599 4600
  taosMemoryFreeClear(pInfo);
  taosMemoryFreeClear(pOperator);
H
Haojun Liao 已提交
4601
  pTaskInfo->code = TSDB_CODE_OUT_OF_MEMORY;
H
Haojun Liao 已提交
4602
  return NULL;
4603 4604
}

H
Haojun Liao 已提交
4605
SSDataBlock* createResultDataBlock(const SArray* pExprInfo) {
wafwerar's avatar
wafwerar 已提交
4606
  SSDataBlock* pResBlock = taosMemoryCalloc(1, sizeof(SSDataBlock));
H
Haojun Liao 已提交
4607 4608 4609 4610 4611 4612 4613 4614
  if (pResBlock == NULL) {
    return NULL;
  }

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

  SArray* pResult = pResBlock->pDataBlock;
L
Liu Jicong 已提交
4615
  for (int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
4616
    SColumnInfoData colInfoData = {0};
L
Liu Jicong 已提交
4617
    SExprInfo*      p = taosArrayGetP(pExprInfo, i);
H
Haojun Liao 已提交
4618

H
Haojun Liao 已提交
4619
    SResSchema* pSchema = &p->base.resSchema;
L
Liu Jicong 已提交
4620
    colInfoData.info.type = pSchema->type;
H
Haojun Liao 已提交
4621 4622
    colInfoData.info.colId = pSchema->colId;
    colInfoData.info.bytes = pSchema->bytes;
H
Haojun Liao 已提交
4623 4624
    colInfoData.info.scale = pSchema->scale;
    colInfoData.info.precision = pSchema->precision;
H
Haojun Liao 已提交
4625 4626 4627 4628 4629 4630
    taosArrayPush(pResult, &colInfoData);
  }

  return pResBlock;
}

H
Haojun Liao 已提交
4631 4632
static int32_t doInitAggInfoSup(SAggSupporter* pAggSup, SqlFunctionCtx* pCtx, int32_t numOfOutput, const char* pKey);
static void    cleanupAggSup(SAggSupporter* pAggSup);
4633

4634
static void destroySortedMergeOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
4635
  SSortedMergeOperatorInfo* pInfo = (SSortedMergeOperatorInfo*)param;
H
Haojun Liao 已提交
4636
  taosArrayDestroy(pInfo->pSortInfo);
4637 4638 4639
  taosArrayDestroy(pInfo->groupInfo);

  if (pInfo->pSortHandle != NULL) {
H
Haojun Liao 已提交
4640
    tsortDestroySortHandle(pInfo->pSortHandle);
4641 4642
  }

H
Haojun Liao 已提交
4643
  blockDataDestroy(pInfo->binfo.pRes);
H
Haojun Liao 已提交
4644
  cleanupAggSup(&pInfo->aggSup);
4645
}
H
Haojun Liao 已提交
4646

4647
static void destroySlimitOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
4648
  SSLimitOperatorInfo* pInfo = (SSLimitOperatorInfo*)param;
4649
  taosArrayDestroy(pInfo->orderColumnList);
H
Haojun Liao 已提交
4650
  pInfo->pRes = blockDataDestroy(pInfo->pRes);
wafwerar's avatar
wafwerar 已提交
4651
  taosMemoryFreeClear(pInfo->prevRow);
4652 4653
}

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

X
Xiaoyu Wang 已提交
4657
  *dst = *src;
4658

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

L
Liu Jicong 已提交
4663 4664 4665 4666
  //  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 已提交
4667
}
4668

4669 4670
static SExprInfo* exprArrayDup(SArray* pExprList) {
  size_t numOfOutput = taosArrayGetSize(pExprList);
4671

wafwerar's avatar
wafwerar 已提交
4672
  SExprInfo* p = taosMemoryCalloc(numOfOutput, sizeof(SExprInfo));
4673 4674
  for (int32_t i = 0; i < numOfOutput; ++i) {
    SExprInfo* pExpr = taosArrayGetP(pExprList, i);
H
Haojun Liao 已提交
4675
    assignExprInfo(&p[i], pExpr);
4676 4677
  }

H
Haojun Liao 已提交
4678 4679
  return p;
}
4680

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

H
Haojun Liao 已提交
4686
    bool isNull = tsortIsNullVal(pTupleHandle, i);
H
Haojun Liao 已提交
4687 4688 4689
    if (isNull) {
      colDataAppend(pColInfo, pBlock->info.rows, NULL, true);
    } else {
H
Haojun Liao 已提交
4690
      char* pData = tsortGetValue(pTupleHandle, i);
H
Haojun Liao 已提交
4691 4692
      colDataAppend(pColInfo, pBlock->info.rows, pData, false);
    }
4693 4694
  }

4695 4696
  pBlock->info.rows += 1;
}
4697

L
Liu Jicong 已提交
4698 4699
static SSDataBlock* getSortedBlockData(SSortHandle* pHandle, SSDataBlock* pDataBlock, bool hasVarCol,
                                       int32_t capacity) {
4700
  blockDataCleanup(pDataBlock);
4701

L
Liu Jicong 已提交
4702
  while (1) {
H
Haojun Liao 已提交
4703
    STupleHandle* pTupleHandle = tsortNextTuple(pHandle);
4704 4705 4706
    if (pTupleHandle == NULL) {
      break;
    }
4707

4708 4709 4710
    appendOneRowToDataBlock(pDataBlock, pTupleHandle);
    if (pDataBlock->info.rows >= capacity) {
      return pDataBlock;
H
Haojun Liao 已提交
4711 4712
    }
  }
4713

L
Liu Jicong 已提交
4714
  return (pDataBlock->info.rows > 0) ? pDataBlock : NULL;
4715
}
4716

4717
SSDataBlock* loadNextDataBlock(void* param) {
L
Liu Jicong 已提交
4718 4719
  SOperatorInfo* pOperator = (SOperatorInfo*)param;
  bool           newgroup = false;
4720

H
Haojun Liao 已提交
4721
  return pOperator->getNextFn(pOperator, &newgroup);
4722 4723
}

L
Liu Jicong 已提交
4724
static bool needToMerge(SSDataBlock* pBlock, SArray* groupInfo, char** buf, int32_t rowIndex) {
4725 4726 4727 4728
  size_t size = taosArrayGetSize(groupInfo);
  if (size == 0) {
    return true;
  }
4729

4730 4731
  for (int32_t i = 0; i < size; ++i) {
    int32_t* index = taosArrayGet(groupInfo, i);
4732

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

4736 4737 4738
    if ((isNull && buf[i] != NULL) || (!isNull && buf[i] == NULL)) {
      return false;
    }
4739

4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752
    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;
      }
4753 4754 4755
    }
  }

4756
  return 0;
4757 4758
}

L
Liu Jicong 已提交
4759 4760 4761
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
4762
    pCtx[j].startRow = rowIndex;
4763 4764
  }

4765 4766
  for (int32_t j = 0; j < numOfExpr; ++j) {
    int32_t functionId = pCtx[j].functionId;
L
Liu Jicong 已提交
4767 4768 4769 4770 4771 4772 4773 4774 4775
    //    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]);
    //    }
4776
  }
4777
}
4778

L
Liu Jicong 已提交
4779 4780
static void doFinalizeResultImpl(SqlFunctionCtx* pCtx, int32_t numOfExpr) {
  for (int32_t j = 0; j < numOfExpr; ++j) {
4781 4782 4783 4784
    int32_t functionId = pCtx[j].functionId;
    //    if (functionId == FUNC_TAG_DUMMY || functionId == FUNC_TS_DUMMY) {
    //      continue;
    //    }
4785

4786 4787 4788 4789
    //    if (functionId < 0) {
    //      SUdfInfo* pUdfInfo = taosArrayGet(pInfo->udfInfo, -1 * functionId - 1);
    //      doInvokeUdf(pUdfInfo, &pCtx[j], 0, TSDB_UDF_FUNC_FINALIZE);
    //    } else {
H
Haojun Liao 已提交
4790
    pCtx[j].fpSet.finalize(&pCtx[j]);
4791 4792
  }
}
4793

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

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

4801 4802 4803
    char* data = colDataGetData(pColInfo, rowIndex);
    memcpy(rowColData[i], data, colDataGetLength(pColInfo, rowIndex));
  }
4804

4805 4806
  return true;
}
4807

4808 4809
static void doMergeImpl(SOperatorInfo* pOperator, int32_t numOfExpr, SSDataBlock* pBlock) {
  SSortedMergeOperatorInfo* pInfo = pOperator->info;
4810

4811
  SqlFunctionCtx* pCtx = pInfo->binfo.pCtx;
L
Liu Jicong 已提交
4812
  for (int32_t i = 0; i < pBlock->info.numOfCols; ++i) {
4813 4814
    pCtx[i].size = 1;
  }
4815

L
Liu Jicong 已提交
4816
  for (int32_t i = 0; i < pBlock->info.rows; ++i) {
4817 4818 4819 4820 4821 4822 4823 4824 4825
    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 已提交
4826
        int32_t numOfRows = getNumOfResult(pInfo->binfo.pCtx, pOperator->numOfOutput, NULL);
4827
        //        setTagValueForMultipleRows(pCtx, pOperator->numOfOutput, numOfRows);
4828

4829
        // TODO check for available buffer;
H
Haojun Liao 已提交
4830

4831 4832 4833 4834 4835
        // next group info data
        pInfo->binfo.pRes->info.rows += numOfRows;
        for (int32_t j = 0; j < numOfExpr; ++j) {
          if (pCtx[j].functionId < 0) {
            continue;
4836
          }
4837

H
Haojun Liao 已提交
4838
          pCtx[j].fpSet.process(&pCtx[j]);
4839
        }
4840 4841 4842

        doMergeResultImpl(pInfo, pCtx, numOfExpr, i);
        pInfo->hasGroupVal = saveCurrentTuple(pInfo->groupVal, pInfo->groupInfo, pBlock, i);
H
Haojun Liao 已提交
4843
      }
4844 4845 4846 4847
    }
  }
}

4848 4849
static SSDataBlock* doMerge(SOperatorInfo* pOperator) {
  SSortedMergeOperatorInfo* pInfo = pOperator->info;
L
Liu Jicong 已提交
4850
  SSortHandle*              pHandle = pInfo->pSortHandle;
4851

4852 4853 4854
  SSDataBlock* pDataBlock = createOneDataBlock(pInfo->binfo.pRes);
  blockDataEnsureCapacity(pDataBlock, pInfo->binfo.capacity);

L
Liu Jicong 已提交
4855
  while (1) {
4856
    blockDataCleanup(pDataBlock);
4857
    while (1) {
H
Haojun Liao 已提交
4858
      STupleHandle* pTupleHandle = tsortNextTuple(pHandle);
4859 4860
      if (pTupleHandle == NULL) {
        break;
4861
      }
4862

4863 4864 4865 4866 4867
      // build datablock for merge for one group
      appendOneRowToDataBlock(pDataBlock, pTupleHandle);
      if (pDataBlock->info.rows >= pInfo->binfo.capacity) {
        break;
      }
4868
    }
4869

4870 4871 4872
    if (pDataBlock->info.rows == 0) {
      break;
    }
4873

4874
    setInputDataBlock(pOperator, pInfo->binfo.pCtx, pDataBlock, TSDB_ORDER_ASC);
L
Liu Jicong 已提交
4875 4876
    //  updateOutputBuf(&pInfo->binfo, &pAggInfo->bufCapacity, pBlock->info.rows * pAggInfo->resultRowFactor,
    //  pOperator->pRuntimeEnv, true);
4877 4878 4879
    doMergeImpl(pOperator, pOperator->numOfOutput, pDataBlock);
    // flush to tuple store, and after all data have been handled, return to upstream node or sink node
  }
4880

4881
  doFinalizeResultImpl(pInfo->binfo.pCtx, pOperator->numOfOutput);
H
Haojun Liao 已提交
4882
  int32_t numOfRows = getNumOfResult(pInfo->binfo.pCtx, pOperator->numOfOutput, NULL);
4883
  //        setTagValueForMultipleRows(pCtx, pOperator->numOfOutput, numOfRows);
4884

4885
  // TODO check for available buffer;
4886

4887 4888
  // next group info data
  pInfo->binfo.pRes->info.rows += numOfRows;
L
Liu Jicong 已提交
4889
  return (pInfo->binfo.pRes->info.rows > 0) ? pInfo->binfo.pRes : NULL;
4890
}
4891

L
Liu Jicong 已提交
4892
static SSDataBlock* doSortedMerge(SOperatorInfo* pOperator, bool* newgroup) {
4893 4894
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
4895 4896
  }

L
Liu Jicong 已提交
4897
  SExecTaskInfo*            pTaskInfo = pOperator->pTaskInfo;
4898
  SSortedMergeOperatorInfo* pInfo = pOperator->info;
H
Haojun Liao 已提交
4899
  if (pOperator->status == OP_RES_TO_RETURN) {
4900
    return getSortedBlockData(pInfo->pSortHandle, pInfo->binfo.pRes, pInfo->hasVarCol, pInfo->binfo.capacity);
4901 4902
  }

4903
  int32_t numOfBufPage = pInfo->sortBufSize / pInfo->bufPageSize;
L
Liu Jicong 已提交
4904 4905
  pInfo->pSortHandle = tsortCreateSortHandle(pInfo->pSortInfo, SORT_MULTISOURCE_MERGE, pInfo->bufPageSize, numOfBufPage,
                                             pInfo->binfo.pRes, "GET_TASKID(pTaskInfo)");
H
Haojun Liao 已提交
4906

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

L
Liu Jicong 已提交
4909
  for (int32_t i = 0; i < pOperator->numOfDownstream; ++i) {
wafwerar's avatar
wafwerar 已提交
4910
    SGenericSource* ps = taosMemoryCalloc(1, sizeof(SGenericSource));
H
Haojun Liao 已提交
4911
    ps->param = pOperator->pDownstream[i];
H
Haojun Liao 已提交
4912
    tsortAddSource(pInfo->pSortHandle, ps);
4913 4914
  }

H
Haojun Liao 已提交
4915
  int32_t code = tsortOpen(pInfo->pSortHandle);
4916
  if (code != TSDB_CODE_SUCCESS) {
4917
    longjmp(pTaskInfo->env, terrno);
4918 4919
  }

H
Haojun Liao 已提交
4920
  pOperator->status = OP_RES_TO_RETURN;
4921
  return doMerge(pOperator);
4922
}
4923

L
Liu Jicong 已提交
4924 4925
static int32_t initGroupCol(SExprInfo* pExprInfo, int32_t numOfCols, SArray* pGroupInfo,
                            SSortedMergeOperatorInfo* pInfo) {
4926 4927
  if (pGroupInfo == NULL || taosArrayGetSize(pGroupInfo) == 0) {
    return 0;
H
Haojun Liao 已提交
4928 4929
  }

4930 4931 4932 4933 4934 4935 4936 4937
  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 已提交
4938 4939
  size_t numOfGroupCol = taosArrayGetSize(pInfo->groupInfo);
  for (int32_t i = 0; i < numOfGroupCol; ++i) {
4940
    SColumn* pCol = taosArrayGet(pGroupInfo, i);
L
Liu Jicong 已提交
4941
    for (int32_t j = 0; j < numOfCols; ++j) {
H
Haojun Liao 已提交
4942
      SExprInfo* pe = &pExprInfo[j];
H
Haojun Liao 已提交
4943
      if (pe->base.resSchema.colId == pCol->colId) {
4944 4945
        taosArrayPush(plist, pCol);
        taosArrayPush(pInfo->groupInfo, &j);
H
Haojun Liao 已提交
4946
        len += pCol->bytes;
4947 4948
        break;
      }
H
Haojun Liao 已提交
4949 4950 4951
    }
  }

4952
  ASSERT(taosArrayGetSize(pGroupInfo) == taosArrayGetSize(plist));
H
Haojun Liao 已提交
4953

wafwerar's avatar
wafwerar 已提交
4954
  pInfo->groupVal = taosMemoryCalloc(1, (POINTER_BYTES * numOfGroupCol + len));
4955 4956 4957 4958
  if (pInfo->groupVal == NULL) {
    taosArrayDestroy(plist);
    return TSDB_CODE_OUT_OF_MEMORY;
  }
H
Haojun Liao 已提交
4959

4960
  int32_t offset = 0;
L
Liu Jicong 已提交
4961 4962
  char*   start = (char*)(pInfo->groupVal + (POINTER_BYTES * numOfGroupCol));
  for (int32_t i = 0; i < numOfGroupCol; ++i) {
4963 4964
    pInfo->groupVal[i] = start + offset;
    SColumn* pCol = taosArrayGet(plist, i);
H
Haojun Liao 已提交
4965
    offset += pCol->bytes;
4966
  }
H
Haojun Liao 已提交
4967

4968
  taosArrayDestroy(plist);
H
Haojun Liao 已提交
4969

4970 4971
  return TSDB_CODE_SUCCESS;
}
H
Haojun Liao 已提交
4972

L
Liu Jicong 已提交
4973 4974 4975
SOperatorInfo* createSortedMergeOperatorInfo(SOperatorInfo** downstream, int32_t numOfDownstream, SExprInfo* pExprInfo,
                                             int32_t num, SArray* pSortInfo, SArray* pGroupInfo,
                                             SExecTaskInfo* pTaskInfo) {
wafwerar's avatar
wafwerar 已提交
4976
  SSortedMergeOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SSortedMergeOperatorInfo));
L
Liu Jicong 已提交
4977
  SOperatorInfo*            pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
4978
  if (pInfo == NULL || pOperator == NULL) {
4979
    goto _error;
4980
  }
H
Haojun Liao 已提交
4981

L
Liu Jicong 已提交
4982
  pInfo->binfo.pCtx = createSqlFunctionCtx_rv(pExprInfo, num, &pInfo->binfo.rowCellInfoOffset);
4983
  initResultRowInfo(&pInfo->binfo.resultRowInfo, (int32_t)1);
H
Haojun Liao 已提交
4984

4985 4986 4987
  if (pInfo->binfo.pCtx == NULL || pInfo->binfo.pRes == NULL) {
    goto _error;
  }
H
Haojun Liao 已提交
4988

H
Haojun Liao 已提交
4989
  int32_t code = doInitAggInfoSup(&pInfo->aggSup, pInfo->binfo.pCtx, num, pTaskInfo->id.str);
4990 4991 4992
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
H
Haojun Liao 已提交
4993

H
Haojun Liao 已提交
4994
  setFunctionResultOutput(&pInfo->binfo, &pInfo->aggSup, MAIN_SCAN, pTaskInfo);
H
Haojun Liao 已提交
4995
  code = initGroupCol(pExprInfo, num, pGroupInfo, pInfo);
4996 4997 4998
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
H
Haojun Liao 已提交
4999

L
Liu Jicong 已提交
5000 5001 5002 5003 5004
  //  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 已提交
5005

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

L
Liu Jicong 已提交
5008
  pOperator->name = "SortedMerge";
X
Xiaoyu Wang 已提交
5009
  // pOperator->operatorType = OP_SortedMerge;
5010
  pOperator->blockingOptr = true;
L
Liu Jicong 已提交
5011 5012 5013 5014
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
  pOperator->numOfOutput = num;
  pOperator->pExpr = pExprInfo;
H
Haojun Liao 已提交
5015

L
Liu Jicong 已提交
5016 5017 5018
  pOperator->pTaskInfo = pTaskInfo;
  pOperator->getNextFn = doSortedMerge;
  pOperator->closeFn = destroySortedMergeOperatorInfo;
H
Haojun Liao 已提交
5019

5020 5021 5022
  code = appendDownstream(pOperator, downstream, numOfDownstream);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
5023
  }
H
Haojun Liao 已提交
5024

5025
  return pOperator;
H
Haojun Liao 已提交
5026

L
Liu Jicong 已提交
5027
_error:
5028
  if (pInfo != NULL) {
H
Haojun Liao 已提交
5029
    destroySortedMergeOperatorInfo(pInfo, num);
H
Haojun Liao 已提交
5030 5031
  }

wafwerar's avatar
wafwerar 已提交
5032 5033
  taosMemoryFreeClear(pInfo);
  taosMemoryFreeClear(pOperator);
5034 5035
  terrno = TSDB_CODE_QRY_OUT_OF_MEMORY;
  return NULL;
H
Haojun Liao 已提交
5036 5037
}

L
Liu Jicong 已提交
5038
static SSDataBlock* doSort(SOperatorInfo* pOperator, bool* newgroup) {
5039 5040 5041 5042
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

L
Liu Jicong 已提交
5043
  SExecTaskInfo*     pTaskInfo = pOperator->pTaskInfo;
H
Haojun Liao 已提交
5044
  SSortOperatorInfo* pInfo = pOperator->info;
L
Liu Jicong 已提交
5045
  bool               hasVarCol = pInfo->pDataBlock->info.hasVarCol;
H
Haojun Liao 已提交
5046

H
Haojun Liao 已提交
5047
  if (pOperator->status == OP_RES_TO_RETURN) {
H
Haojun Liao 已提交
5048
    return getSortedBlockData(pInfo->pSortHandle, pInfo->pDataBlock, hasVarCol, pInfo->numOfRowsInRes);
H
Haojun Liao 已提交
5049 5050
  }

5051
  int32_t numOfBufPage = pInfo->sortBufSize / pInfo->bufPageSize;
L
Liu Jicong 已提交
5052 5053
  pInfo->pSortHandle = tsortCreateSortHandle(pInfo->pSortInfo, SORT_SINGLESOURCE_SORT, pInfo->bufPageSize, numOfBufPage,
                                             pInfo->pDataBlock, "GET_TASKID(pTaskInfo)");
5054

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

wafwerar's avatar
wafwerar 已提交
5057
  SGenericSource* ps = taosMemoryCalloc(1, sizeof(SGenericSource));
H
Haojun Liao 已提交
5058
  ps->param = pOperator->pDownstream[0];
H
Haojun Liao 已提交
5059
  tsortAddSource(pInfo->pSortHandle, ps);
5060

H
Haojun Liao 已提交
5061
  int32_t code = tsortOpen(pInfo->pSortHandle);
5062
  if (code != TSDB_CODE_SUCCESS) {
5063
    longjmp(pTaskInfo->env, terrno);
5064
  }
5065

H
Haojun Liao 已提交
5066
  pOperator->status = OP_RES_TO_RETURN;
H
Haojun Liao 已提交
5067
  return getSortedBlockData(pInfo->pSortHandle, pInfo->pDataBlock, hasVarCol, pInfo->numOfRowsInRes);
5068 5069
}

L
Liu Jicong 已提交
5070 5071
SOperatorInfo* createSortOperatorInfo(SOperatorInfo* downstream, SSDataBlock* pResBlock, SArray* pSortInfo,
                                      SExecTaskInfo* pTaskInfo) {
H
Haojun Liao 已提交
5072
  SSortOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SSortOperatorInfo));
L
Liu Jicong 已提交
5073
  SOperatorInfo*     pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
5074
  if (pInfo == NULL || pOperator == NULL) {
wafwerar's avatar
wafwerar 已提交
5075 5076
    taosMemoryFreeClear(pInfo);
    taosMemoryFreeClear(pOperator);
H
Haojun Liao 已提交
5077 5078 5079
    terrno = TSDB_CODE_QRY_OUT_OF_MEMORY;
    return NULL;
  }
5080

L
Liu Jicong 已提交
5081 5082 5083 5084 5085
  pInfo->sortBufSize = 1024 * 16;  // 1MB, TODO dynamic set the available sort buffer
  pInfo->bufPageSize = 1024;
  pInfo->numOfRowsInRes = 1024;
  pInfo->pDataBlock = pResBlock;
  pInfo->pSortInfo = pSortInfo;
H
Haojun Liao 已提交
5086

L
Liu Jicong 已提交
5087 5088 5089 5090 5091
  pOperator->name = "Sort";
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_SORT;
  pOperator->blockingOptr = true;
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
5092

L
Liu Jicong 已提交
5093 5094 5095
  pOperator->pTaskInfo = pTaskInfo;
  pOperator->getNextFn = doSort;
  pOperator->closeFn = destroyOrderOperatorInfo;
5096

5097
  int32_t code = appendDownstream(pOperator, &downstream, 1);
5098 5099 5100
  return pOperator;
}

L
Liu Jicong 已提交
5101
static int32_t getTableScanOrder(STableScanInfo* pTableScanInfo) { return pTableScanInfo->order; }
5102 5103

// this is a blocking operator
L
Liu Jicong 已提交
5104
static int32_t doOpenAggregateOptr(SOperatorInfo* pOperator) {
H
Haojun Liao 已提交
5105 5106
  if (OPTR_IS_OPENED(pOperator)) {
    return TSDB_CODE_SUCCESS;
5107 5108 5109
  }

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

H
Haojun Liao 已提交
5112
  int32_t        order = TSDB_ORDER_ASC;
H
Haojun Liao 已提交
5113
  SOperatorInfo* downstream = pOperator->pDownstream[0];
5114

H
Haojun Liao 已提交
5115 5116
  bool newgroup = true;
  while (1) {
H
Haojun Liao 已提交
5117
    publishOperatorProfEvent(downstream, QUERY_PROF_BEFORE_OPERATOR_EXEC);
H
Haojun Liao 已提交
5118
    SSDataBlock* pBlock = downstream->getNextFn(downstream, &newgroup);
H
Haojun Liao 已提交
5119
    publishOperatorProfEvent(downstream, QUERY_PROF_AFTER_OPERATOR_EXEC);
5120 5121 5122 5123

    if (pBlock == NULL) {
      break;
    }
H
Haojun Liao 已提交
5124 5125 5126
    //    if (pAggInfo->current != NULL) {
    //      setTagValue(pOperator, pAggInfo->current->pTable, pInfo->pCtx, pOperator->numOfOutput);
    //    }
5127 5128 5129

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

5133
  finalizeQueryResult(pInfo->pCtx, pOperator->numOfOutput);
H
Haojun Liao 已提交
5134 5135 5136 5137 5138

  OPTR_SET_OPENED(pOperator);
  return TSDB_CODE_SUCCESS;
}

L
Liu Jicong 已提交
5139 5140
static SSDataBlock* getAggregateResult(SOperatorInfo* pOperator, bool* newgroup) {
  SAggOperatorInfo* pAggInfo = pOperator->info;
H
Haojun Liao 已提交
5141 5142 5143 5144 5145 5146
  SOptrBasicInfo*   pInfo = &pAggInfo->binfo;

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

L
Liu Jicong 已提交
5147
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
H
Haojun Liao 已提交
5148 5149 5150 5151 5152
  pTaskInfo->code = pOperator->_openFn(pOperator);
  if (pTaskInfo->code != TSDB_CODE_SUCCESS) {
    return NULL;
  }

H
Haojun Liao 已提交
5153
  getNumOfResult(pInfo->pCtx, pOperator->numOfOutput, pInfo->pRes);
H
Haojun Liao 已提交
5154
  doSetOperatorCompleted(pOperator);
5155

L
Liu Jicong 已提交
5156
  return (blockDataGetNumOfRows(pInfo->pRes) != 0) ? pInfo->pRes : NULL;
5157 5158
}

L
Liu Jicong 已提交
5159 5160 5161
static void aggEncodeResultRow(SOperatorInfo* pOperator, char** result, int32_t* length) {
  SAggOperatorInfo* pAggInfo = pOperator->info;
  SAggSupporter*    pSup = &pAggInfo->aggSup;
wmmhello's avatar
wmmhello 已提交
5162 5163

  int32_t size = taosHashGetSize(pSup->pResultRowHashTable);
L
Liu Jicong 已提交
5164
  size_t  keyLen = POINTER_BYTES;  // estimate the key length
wmmhello's avatar
wmmhello 已提交
5165
  int32_t totalSize = sizeof(int32_t) + size * (sizeof(int32_t) + keyLen + sizeof(int32_t) + pSup->resultRowSize);
wafwerar's avatar
wafwerar 已提交
5166
  *result = taosMemoryCalloc(1, totalSize);
L
Liu Jicong 已提交
5167
  if (*result == NULL) {
wmmhello's avatar
wmmhello 已提交
5168 5169 5170 5171 5172
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return;
  }
  *(int32_t*)(*result) = size;
  int32_t offset = sizeof(int32_t);
L
Liu Jicong 已提交
5173
  void*   pIter = taosHashIterate(pSup->pResultRowHashTable, NULL);
wmmhello's avatar
wmmhello 已提交
5174
  while (pIter) {
L
Liu Jicong 已提交
5175 5176
    void*        key = taosHashGetKey(pIter, &keyLen);
    SResultRow** p1 = (SResultRow**)pIter;
wmmhello's avatar
wmmhello 已提交
5177 5178 5179

    // recalculate the result size
    int32_t realTotalSize = offset + sizeof(int32_t) + keyLen + sizeof(int32_t) + pSup->resultRowSize;
L
Liu Jicong 已提交
5180 5181 5182
    if (realTotalSize > totalSize) {
      char* tmp = taosMemoryRealloc(*result, realTotalSize);
      if (tmp == NULL) {
wmmhello's avatar
wmmhello 已提交
5183
        terrno = TSDB_CODE_OUT_OF_MEMORY;
wafwerar's avatar
wafwerar 已提交
5184
        taosMemoryFree(*result);
wmmhello's avatar
wmmhello 已提交
5185 5186
        *result = NULL;
        return;
L
Liu Jicong 已提交
5187
      } else {
wmmhello's avatar
wmmhello 已提交
5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205
        *result = tmp;
      }
    }
    // save key
    *(int32_t*)(*result + offset) = keyLen;
    offset += sizeof(int32_t);
    memcpy(*result + offset, key, keyLen);
    offset += keyLen;

    // save value
    *(int32_t*)(*result + offset) = pSup->resultRowSize;
    offset += sizeof(int32_t);
    memcpy(*result + offset, *p1, pSup->resultRowSize);
    offset += pSup->resultRowSize;

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

L
Liu Jicong 已提交
5206
  if (length) {
wmmhello's avatar
wmmhello 已提交
5207 5208 5209 5210 5211
    *length = offset;
  }
  return;
}

L
Liu Jicong 已提交
5212 5213
static bool aggDecodeResultRow(SOperatorInfo* pOperator, char* result, int32_t length) {
  if (!result || length <= 0) {
wmmhello's avatar
wmmhello 已提交
5214 5215 5216
    return false;
  }

L
Liu Jicong 已提交
5217 5218 5219
  SAggOperatorInfo* pAggInfo = pOperator->info;
  SAggSupporter*    pSup = &pAggInfo->aggSup;
  SOptrBasicInfo*   pInfo = &pAggInfo->binfo;
wmmhello's avatar
wmmhello 已提交
5220 5221 5222 5223 5224

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

  int32_t offset = sizeof(int32_t);
L
Liu Jicong 已提交
5225
  while (count-- > 0 && length > offset) {
wmmhello's avatar
wmmhello 已提交
5226 5227 5228
    int32_t keyLen = *(int32_t*)(result + offset);
    offset += sizeof(int32_t);

L
Liu Jicong 已提交
5229 5230 5231
    uint64_t    tableGroupId = *(uint64_t*)(result + offset);
    SResultRow* resultRow = getNewResultRow_rv(pSup->pResultBuf, tableGroupId, pSup->resultRowSize);
    if (!resultRow) {
wmmhello's avatar
wmmhello 已提交
5232 5233 5234 5235 5236 5237 5238 5239
      terrno = TSDB_CODE_TSC_INVALID_INPUT;
      return false;
    }
    // add a new result set for a new group
    taosHashPut(pSup->pResultRowHashTable, result + offset, keyLen, &resultRow, POINTER_BYTES);

    offset += keyLen;
    int32_t valueLen = *(int32_t*)(result + offset);
L
Liu Jicong 已提交
5240
    if (valueLen != pSup->resultRowSize) {
wmmhello's avatar
wmmhello 已提交
5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252
      terrno = TSDB_CODE_TSC_INVALID_INPUT;
      return false;
    }
    offset += sizeof(int32_t);
    int32_t pageId = resultRow->pageId;
    int32_t pOffset = resultRow->offset;
    memcpy(resultRow, result + offset, valueLen);
    resultRow->pageId = pageId;
    resultRow->offset = pOffset;
    offset += valueLen;

    initResultRow(resultRow);
L
Liu Jicong 已提交
5253 5254
    pInfo->resultRowInfo.pPosition[pInfo->resultRowInfo.size++] =
        (SResultRowPosition){.pageId = resultRow->pageId, .offset = resultRow->offset};
wmmhello's avatar
wmmhello 已提交
5255 5256
  }

L
Liu Jicong 已提交
5257
  if (offset != length) {
wmmhello's avatar
wmmhello 已提交
5258 5259 5260 5261 5262 5263
    terrno = TSDB_CODE_TSC_INVALID_INPUT;
    return false;
  }
  return true;
}

L
Liu Jicong 已提交
5264
static SSDataBlock* doMultiTableAggregate(SOperatorInfo* pOperator, bool* newgroup) {
5265 5266 5267 5268 5269
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

  SAggOperatorInfo* pAggInfo = pOperator->info;
L
Liu Jicong 已提交
5270 5271
  SOptrBasicInfo*   pInfo = &pAggInfo->binfo;
  SExecTaskInfo*    pTaskInfo = pOperator->pTaskInfo;
5272 5273

  if (pOperator->status == OP_RES_TO_RETURN) {
L
Liu Jicong 已提交
5274 5275
    toSDatablock(&pAggInfo->groupResInfo, pAggInfo->pResultBuf, pInfo->pRes, pAggInfo->binfo.capacity,
                 pAggInfo->binfo.rowCellInfoOffset);
5276

H
Haojun Liao 已提交
5277
    if (pInfo->pRes->info.rows == 0 || !hasRemainDataInCurrentGroup(&pAggInfo->groupResInfo)) {
5278 5279 5280 5281 5282 5283
      pOperator->status = OP_EXEC_DONE;
    }

    return pInfo->pRes;
  }

5284
  // table scan order
L
Liu Jicong 已提交
5285
  int32_t        order = TSDB_ORDER_ASC;
H
Haojun Liao 已提交
5286
  SOperatorInfo* downstream = pOperator->pDownstream[0];
5287

L
Liu Jicong 已提交
5288
  while (1) {
H
Haojun Liao 已提交
5289
    publishOperatorProfEvent(downstream, QUERY_PROF_BEFORE_OPERATOR_EXEC);
H
Haojun Liao 已提交
5290
    SSDataBlock* pBlock = downstream->getNextFn(downstream, newgroup);
H
Haojun Liao 已提交
5291
    publishOperatorProfEvent(downstream, QUERY_PROF_AFTER_OPERATOR_EXEC);
5292 5293 5294 5295 5296

    if (pBlock == NULL) {
      break;
    }

L
Liu Jicong 已提交
5297 5298 5299 5300 5301
    //    setTagValue(pOperator, pRuntimeEnv->current->pTable, pInfo->pCtx, pOperator->numOfOutput);
    //    if (downstream->operatorType == OP_TableScan) {
    //      STableScanInfo* pScanInfo = downstream->info;
    //      order = getTableScanOrder(pScanInfo);
    //    }
5302 5303 5304 5305 5306

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

    TSKEY key = 0;
5307
    if (order == TSDB_ORDER_ASC) {
5308 5309 5310 5311 5312 5313
      key = pBlock->info.window.ekey;
      TSKEY_MAX_ADD(key, 1);
    } else {
      key = pBlock->info.window.skey;
      TSKEY_MIN_SUB(key, -1);
    }
L
Liu Jicong 已提交
5314 5315 5316

    setExecutionContext(pOperator->numOfOutput, pAggInfo->current->groupIndex, key, pTaskInfo, pAggInfo->current,
                        pAggInfo);
H
Haojun Liao 已提交
5317
    doAggregateImpl(pOperator, 0, pInfo->pCtx);
5318 5319 5320 5321
  }

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

H
Haojun Liao 已提交
5324
  initGroupResInfo(&pAggInfo->groupResInfo, &pInfo->resultRowInfo);
L
Liu Jicong 已提交
5325 5326
  toSDatablock(&pAggInfo->groupResInfo, pAggInfo->pResultBuf, pInfo->pRes, pAggInfo->binfo.capacity,
               pAggInfo->binfo.rowCellInfoOffset);
5327

H
Haojun Liao 已提交
5328
  if (pInfo->pRes->info.rows == 0 || !hasRemainDataInCurrentGroup(&pAggInfo->groupResInfo)) {
5329 5330 5331 5332 5333 5334
    doSetOperatorCompleted(pOperator);
  }

  return pInfo->pRes;
}

L
Liu Jicong 已提交
5335
static SSDataBlock* doProjectOperation(SOperatorInfo* pOperator, bool* newgroup) {
5336
  SProjectOperatorInfo* pProjectInfo = pOperator->info;
L
Liu Jicong 已提交
5337
  SOptrBasicInfo*       pInfo = &pProjectInfo->binfo;
5338 5339

  SSDataBlock* pRes = pInfo->pRes;
5340
  blockDataCleanup(pRes);
H
Haojun Liao 已提交
5341
#if 0
5342 5343 5344 5345 5346 5347
  if (pProjectInfo->existDataBlock) {  // TODO refactor
    SSDataBlock* pBlock = pProjectInfo->existDataBlock;
    pProjectInfo->existDataBlock = NULL;
    *newgroup = true;

    // todo dynamic set tags
L
Liu Jicong 已提交
5348 5349 5350
    //    if (pTableQueryInfo != NULL) {
    //      setTagValue(pOperator, pTableQueryInfo->pTable, pInfo->pCtx, pOperator->numOfOutput);
    //    }
5351 5352

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

H
Haojun Liao 已提交
5355
    blockDataEnsureCapacity(pInfo->pRes, pBlock->info.rows);
5356
    projectApplyFunctions(pOperator->pExpr, pInfo->pRes, pBlock, pInfo->pCtx, pOperator->numOfOutput);
L
Liu Jicong 已提交
5357
    if (pRes->info.rows >= pProjectInfo->binfo.capacity * 0.8) {
5358 5359 5360 5361 5362
      copyTsColoum(pRes, pInfo->pCtx, pOperator->numOfOutput);
      resetResultRowEntryResult(pInfo->pCtx, pOperator->numOfOutput);
      return pRes;
    }
  }
H
Haojun Liao 已提交
5363
#endif
5364

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

L
Liu Jicong 已提交
5367
  while (1) {
5368 5369
    bool prevVal = *newgroup;

H
Haojun Liao 已提交
5370
    // The downstream exec may change the value of the newgroup, so use a local variable instead.
H
Haojun Liao 已提交
5371 5372 5373
    publishOperatorProfEvent(downstream, QUERY_PROF_BEFORE_OPERATOR_EXEC);
    SSDataBlock* pBlock = downstream->getNextFn(downstream, newgroup);
    publishOperatorProfEvent(downstream, QUERY_PROF_AFTER_OPERATOR_EXEC);
5374 5375 5376 5377

    if (pBlock == NULL) {
      assert(*newgroup == false);
      *newgroup = prevVal;
5378
      setTaskStatus(pOperator->pTaskInfo, TASK_COMPLETED);
5379 5380 5381 5382 5383 5384 5385 5386
      break;
    }

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

    // todo dynamic set tags
H
Haojun Liao 已提交
5393 5394 5395 5396
    //    STableQueryInfo* pTableQueryInfo = pRuntimeEnv->current;
    //    if (pTableQueryInfo != NULL) {
    //      setTagValue(pOperator, pTableQueryInfo->pTable, pInfo->pCtx, pOperator->numOfOutput);
    //    }
5397 5398

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

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

H
Haojun Liao 已提交
5404
    // todo extract method
H
Haojun Liao 已提交
5405 5406 5407 5408 5409 5410 5411 5412 5413
    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;
    }

5414
    if (pRes->info.rows >= pOperator->resultInfo.threshold) {
5415 5416 5417
      break;
    }
  }
H
Haojun Liao 已提交
5418
  
H
Haojun Liao 已提交
5419
  if (pProjectInfo->limit.limit > 0 && pProjectInfo->curOutput + pInfo->pRes->info.rows >= pProjectInfo->limit.limit) {
H
Haojun Liao 已提交
5420 5421 5422 5423
    pInfo->pRes->info.rows = (int32_t)(pProjectInfo->limit.limit - pProjectInfo->curOutput);
  }

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

L
Liu Jicong 已提交
5425 5426
  //  copyTsColoum(pRes, pInfo->pCtx, pOperator->numOfOutput);
  return (pInfo->pRes->info.rows > 0) ? pInfo->pRes : NULL;
5427 5428
}

L
Liu Jicong 已提交
5429
static int32_t doOpenIntervalAgg(SOperatorInfo* pOperator) {
5430 5431
  if (OPTR_IS_OPENED(pOperator)) {
    return TSDB_CODE_SUCCESS;
5432 5433
  }

H
Haojun Liao 已提交
5434
  STableIntervalOperatorInfo* pInfo = pOperator->info;
5435

5436
  int32_t order = TSDB_ORDER_ASC;
5437 5438
  //  STimeWindow win = {0};
  bool newgroup = false;
H
Haojun Liao 已提交
5439
  SOperatorInfo* downstream = pOperator->pDownstream[0];
5440

5441
  while (1) {
H
Haojun Liao 已提交
5442
    publishOperatorProfEvent(downstream, QUERY_PROF_BEFORE_OPERATOR_EXEC);
5443
    SSDataBlock* pBlock = downstream->getNextFn(downstream, &newgroup);
H
Haojun Liao 已提交
5444
    publishOperatorProfEvent(downstream, QUERY_PROF_AFTER_OPERATOR_EXEC);
5445 5446 5447 5448 5449

    if (pBlock == NULL) {
      break;
    }

5450
    //    setTagValue(pOperator, pRuntimeEnv->current->pTable, pInfo->pCtx, pOperator->numOfOutput);
5451
    // the pDataBlock are always the same one, no need to call this again
5452
    setInputDataBlock(pOperator, pInfo->binfo.pCtx, pBlock, order);
H
Haojun Liao 已提交
5453
    hashIntervalAgg(pOperator, &pInfo->binfo.resultRowInfo, pBlock, 0);
5454 5455
  }

H
Haojun Liao 已提交
5456
  closeAllResultRows(&pInfo->binfo.resultRowInfo);
L
Liu Jicong 已提交
5457 5458
  finalizeMultiTupleQueryResult(pInfo->binfo.pCtx, pOperator->numOfOutput, pInfo->aggSup.pResultBuf,
                                &pInfo->binfo.resultRowInfo, pInfo->binfo.rowCellInfoOffset);
5459

H
Haojun Liao 已提交
5460
  initGroupResInfo(&pInfo->groupResInfo, &pInfo->binfo.resultRowInfo);
5461 5462 5463 5464
  OPTR_SET_OPENED(pOperator);
  return TSDB_CODE_SUCCESS;
}

L
Liu Jicong 已提交
5465
static SSDataBlock* doBuildIntervalResult(SOperatorInfo* pOperator, bool* newgroup) {
5466
  STableIntervalOperatorInfo* pInfo = pOperator->info;
L
Liu Jicong 已提交
5467
  SExecTaskInfo*              pTaskInfo = pOperator->pTaskInfo;
5468 5469 5470 5471 5472

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

5473 5474 5475 5476
  if (pInfo->execModel == OPTR_EXEC_MODEL_STREAM) {
    return pOperator->getStreamResFn(pOperator, newgroup);
  }

5477 5478 5479 5480 5481 5482
  pTaskInfo->code = pOperator->_openFn(pOperator);
  if (pTaskInfo->code != TSDB_CODE_SUCCESS) {
    return NULL;
  }

  blockDataEnsureCapacity(pInfo->binfo.pRes, pInfo->binfo.capacity);
L
Liu Jicong 已提交
5483 5484
  toSDatablock(&pInfo->groupResInfo, pInfo->aggSup.pResultBuf, pInfo->binfo.pRes, pInfo->binfo.capacity,
               pInfo->binfo.rowCellInfoOffset);
5485

H
Haojun Liao 已提交
5486
  if (pInfo->binfo.pRes->info.rows == 0 || !hasRemainDataInCurrentGroup(&pInfo->groupResInfo)) {
5487 5488 5489
    doSetOperatorCompleted(pOperator);
  }

L
Liu Jicong 已提交
5490
  return pInfo->binfo.pRes->info.rows == 0 ? NULL : pInfo->binfo.pRes;
5491 5492
}

5493
static SSDataBlock* doStreamIntervalAgg(SOperatorInfo *pOperator, bool* newgroup) {
5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506
  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) {
    toSDatablock(&pInfo->groupResInfo, pInfo->aggSup.pResultBuf, pInfo->binfo.pRes, pInfo->binfo.capacity,
                 pInfo->binfo.rowCellInfoOffset);
    if (pInfo->binfo.pRes->info.rows == 0 || !hasRemainDataInCurrentGroup(&pInfo->groupResInfo)) {
      pOperator->status = OP_EXEC_DONE;
    }
5507
    return pInfo->binfo.pRes->info.rows == 0 ? NULL : pInfo->binfo.pRes;
5508 5509 5510
  }

  //  STimeWindow win = {0};
5511
  *newgroup = false;
5512 5513 5514 5515 5516 5517
  SOperatorInfo* downstream = pOperator->pDownstream[0];

  SArray* pUpdated = NULL;

  while (1) {
    publishOperatorProfEvent(downstream, QUERY_PROF_BEFORE_OPERATOR_EXEC);
5518
    SSDataBlock* pBlock = downstream->getNextFn(downstream, newgroup);
5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535
    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 已提交
5536
  initMultiResInfoFromArrayList(&pInfo->groupResInfo, pUpdated);
5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547
  blockDataEnsureCapacity(pInfo->binfo.pRes, pInfo->binfo.capacity);
  toSDatablock(&pInfo->groupResInfo, pInfo->aggSup.pResultBuf, pInfo->binfo.pRes, pInfo->binfo.capacity,
               pInfo->binfo.rowCellInfoOffset);

  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) {
5548 5549 5550 5551 5552 5553
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

  STableIntervalOperatorInfo* pIntervalInfo = pOperator->info;

H
Haojun Liao 已提交
5554
  STaskRuntimeEnv* pRuntimeEnv = pOperator->pRuntimeEnv;
5555
  if (pOperator->status == OP_RES_TO_RETURN) {
L
Liu Jicong 已提交
5556
    //    toSDatablock(&pRuntimeEnv->groupResInfo, pRuntimeEnv, pIntervalInfo->pRes);
5557

H
Haojun Liao 已提交
5558
    if (pIntervalInfo->binfo.pRes->info.rows == 0 || !hasRemainDataInCurrentGroup(&pRuntimeEnv->groupResInfo)) {
5559 5560 5561
      doSetOperatorCompleted(pOperator);
    }

H
Haojun Liao 已提交
5562
    return pIntervalInfo->binfo.pRes;
5563 5564
  }

L
Liu Jicong 已提交
5565 5566
  STaskAttr*  pQueryAttr = pRuntimeEnv->pQueryAttr;
  int32_t     order = pQueryAttr->order.order;
5567 5568
  STimeWindow win = pQueryAttr->window;

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

L
Liu Jicong 已提交
5571
  while (1) {
H
Haojun Liao 已提交
5572
    publishOperatorProfEvent(downstream, QUERY_PROF_BEFORE_OPERATOR_EXEC);
H
Haojun Liao 已提交
5573
    SSDataBlock* pBlock = downstream->getNextFn(downstream, newgroup);
H
Haojun Liao 已提交
5574
    publishOperatorProfEvent(downstream, QUERY_PROF_AFTER_OPERATOR_EXEC);
5575 5576 5577 5578 5579

    if (pBlock == NULL) {
      break;
    }

L
Liu Jicong 已提交
5580
    //    setTagValue(pOperator, pRuntimeEnv->current->pTable, pIntervalInfo->pCtx, pOperator->numOfOutput);
5581 5582

    // the pDataBlock are always the same one, no need to call this again
H
Haojun Liao 已提交
5583 5584
    setInputDataBlock(pOperator, pIntervalInfo->binfo.pCtx, pBlock, pQueryAttr->order.order);
    hashAllIntervalAgg(pOperator, &pIntervalInfo->binfo.resultRowInfo, pBlock, 0);
5585 5586 5587 5588 5589 5590 5591
  }

  // restore the value
  pQueryAttr->order.order = order;
  pQueryAttr->window = win;

  pOperator->status = OP_RES_TO_RETURN;
H
Haojun Liao 已提交
5592
  closeAllResultRows(&pIntervalInfo->binfo.resultRowInfo);
5593
  setTaskStatus(pOperator->pTaskInfo, TASK_COMPLETED);
5594
  finalizeQueryResult(pIntervalInfo->binfo.pCtx, pOperator->numOfOutput);
5595

H
Haojun Liao 已提交
5596
  initGroupResInfo(&pRuntimeEnv->groupResInfo, &pIntervalInfo->binfo.resultRowInfo);
L
Liu Jicong 已提交
5597
  //  toSDatablock(&pRuntimeEnv->groupResInfo, pRuntimeEnv, pIntervalInfo->pRes);
5598

H
Haojun Liao 已提交
5599
  if (pIntervalInfo->binfo.pRes->info.rows == 0 || !hasRemainDataInCurrentGroup(&pRuntimeEnv->groupResInfo)) {
5600 5601 5602
    pOperator->status = OP_EXEC_DONE;
  }

L
Liu Jicong 已提交
5603
  return pIntervalInfo->binfo.pRes->info.rows == 0 ? NULL : pIntervalInfo->binfo.pRes;
5604 5605
}

L
Liu Jicong 已提交
5606
static SSDataBlock* doSTableIntervalAgg(SOperatorInfo* pOperator, bool* newgroup) {
5607 5608 5609 5610 5611
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

  STableIntervalOperatorInfo* pIntervalInfo = pOperator->info;
L
Liu Jicong 已提交
5612
  STaskRuntimeEnv*            pRuntimeEnv = pOperator->pRuntimeEnv;
5613 5614 5615 5616

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

L
Liu Jicong 已提交
5617
    //    copyToSDataBlock(NULL, 3000, pIntervalInfo->pRes, pIntervalInfo->rowCellInfoOffset);
H
Haojun Liao 已提交
5618
    if (pIntervalInfo->binfo.pRes->info.rows == 0 || !hasRemainData(&pRuntimeEnv->groupResInfo)) {
5619 5620
      doSetOperatorCompleted(pOperator);
    }
H
Haojun Liao 已提交
5621
    return pIntervalInfo->binfo.pRes;
5622 5623
  }

H
Haojun Liao 已提交
5624
  STaskAttr* pQueryAttr = pRuntimeEnv->pQueryAttr;
L
Liu Jicong 已提交
5625
  int32_t    order = pQueryAttr->order.order;
5626

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

L
Liu Jicong 已提交
5629
  while (1) {
H
Haojun Liao 已提交
5630
    publishOperatorProfEvent(downstream, QUERY_PROF_BEFORE_OPERATOR_EXEC);
H
Haojun Liao 已提交
5631
    SSDataBlock* pBlock = downstream->getNextFn(downstream, newgroup);
H
Haojun Liao 已提交
5632
    publishOperatorProfEvent(downstream, QUERY_PROF_AFTER_OPERATOR_EXEC);
5633 5634 5635 5636 5637 5638 5639 5640

    if (pBlock == NULL) {
      break;
    }

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

L
Liu Jicong 已提交
5641
    //    setTagValue(pOperator, pTableQueryInfo->pTable, pIntervalInfo->pCtx, pOperator->numOfOutput);
H
Haojun Liao 已提交
5642
    setInputDataBlock(pOperator, pIntervalInfo->binfo.pCtx, pBlock, pQueryAttr->order.order);
5643 5644 5645 5646 5647 5648
    setIntervalQueryRange(pRuntimeEnv, pBlock->info.window.skey);

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

  pOperator->status = OP_RES_TO_RETURN;
L
Liu Jicong 已提交
5649
  pQueryAttr->order.order = order;  // TODO : restore the order
5650
  doCloseAllTimeWindow(pRuntimeEnv);
5651
  setTaskStatus(pOperator->pTaskInfo, TASK_COMPLETED);
5652

L
Liu Jicong 已提交
5653
  //  copyToSDataBlock(pRuntimeEnv, 3000, pIntervalInfo->pRes, pIntervalInfo->rowCellInfoOffset);
H
Haojun Liao 已提交
5654
  if (pIntervalInfo->binfo.pRes->info.rows == 0 || !hasRemainData(&pRuntimeEnv->groupResInfo)) {
5655 5656 5657
    pOperator->status = OP_EXEC_DONE;
  }

H
Haojun Liao 已提交
5658
  return pIntervalInfo->binfo.pRes;
5659 5660
}

L
Liu Jicong 已提交
5661
static SSDataBlock* doAllSTableIntervalAgg(SOperatorInfo* pOperator, bool* newgroup) {
5662 5663 5664 5665 5666
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

  STableIntervalOperatorInfo* pIntervalInfo = pOperator->info;
L
Liu Jicong 已提交
5667
  STaskRuntimeEnv*            pRuntimeEnv = pOperator->pRuntimeEnv;
5668 5669

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

H
Haojun Liao 已提交
5675
    return pIntervalInfo->binfo.pRes;
5676 5677
  }

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

L
Liu Jicong 已提交
5680
  while (1) {
H
Haojun Liao 已提交
5681
    publishOperatorProfEvent(downstream, QUERY_PROF_BEFORE_OPERATOR_EXEC);
H
Haojun Liao 已提交
5682
    SSDataBlock* pBlock = downstream->getNextFn(downstream, newgroup);
H
Haojun Liao 已提交
5683
    publishOperatorProfEvent(downstream, QUERY_PROF_AFTER_OPERATOR_EXEC);
5684 5685 5686 5687 5688 5689 5690 5691

    if (pBlock == NULL) {
      break;
    }

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

L
Liu Jicong 已提交
5692
    //    setTagValue(pOperator, pTableQueryInfo->pTable, pIntervalInfo->pCtx, pOperator->numOfOutput);
H
Haojun Liao 已提交
5693
//    setInputDataBlock(pOperator, pIntervalInfo->binfo.pCtx, pBlock, pQueryAttr->order.order);
5694 5695 5696 5697 5698 5699
    setIntervalQueryRange(pRuntimeEnv, pBlock->info.window.skey);

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

  pOperator->status = OP_RES_TO_RETURN;
H
Haojun Liao 已提交
5700
//  pQueryAttr->order.order = order;  // TODO : restore the order
5701
  doCloseAllTimeWindow(pRuntimeEnv);
5702
  setTaskStatus(pOperator->pTaskInfo, TASK_COMPLETED);
5703 5704

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

L
Liu Jicong 已提交
5710 5711
  //  SQInfo* pQInfo = pRuntimeEnv->qinfo;
  //  pQInfo->summary.firstStageMergeTime += (taosGetTimestampUs() - st);
5712

H
Haojun Liao 已提交
5713
  return pIntervalInfo->binfo.pRes;
5714 5715
}

L
Liu Jicong 已提交
5716
static void doStateWindowAggImpl(SOperatorInfo* pOperator, SStateWindowOperatorInfo* pInfo, SSDataBlock* pSDataBlock) {
H
Haojun Liao 已提交
5717
  STaskRuntimeEnv* pRuntimeEnv = pOperator->pRuntimeEnv;
L
Liu Jicong 已提交
5718
  STableQueryInfo* item = pRuntimeEnv->current;
5719 5720 5721 5722
  SColumnInfoData* pColInfoData = taosArrayGet(pSDataBlock->pDataBlock, pInfo->colIndex);

  SOptrBasicInfo* pBInfo = &pInfo->binfo;

H
Haojun Liao 已提交
5723
  bool    masterScan = IS_MAIN_SCAN(pRuntimeEnv);
L
Liu Jicong 已提交
5724 5725
  int16_t bytes = pColInfoData->info.bytes;
  int16_t type = pColInfoData->info.type;
5726 5727

  SColumnInfoData* pTsColInfoData = taosArrayGet(pSDataBlock->pDataBlock, 0);
L
Liu Jicong 已提交
5728
  TSKEY*           tsList = (TSKEY*)pTsColInfoData->pData;
5729 5730
  if (IS_REPEAT_SCAN(pRuntimeEnv) && !pInfo->reptScan) {
    pInfo->reptScan = true;
wafwerar's avatar
wafwerar 已提交
5731
    taosMemoryFreeClear(pInfo->prevData);
5732 5733 5734 5735 5736 5737 5738 5739 5740
  }

  pInfo->numOfRows = 0;
  for (int32_t j = 0; j < pSDataBlock->info.rows; ++j) {
    char* val = ((char*)pColInfoData->pData) + bytes * j;
    if (isNull(val, type)) {
      continue;
    }
    if (pInfo->prevData == NULL) {
wafwerar's avatar
wafwerar 已提交
5741
      pInfo->prevData = taosMemoryMalloc(bytes);
5742 5743 5744 5745 5746 5747 5748 5749 5750
      memcpy(pInfo->prevData, val, bytes);
      pInfo->numOfRows = 1;
      pInfo->curWindow.skey = tsList[j];
      pInfo->curWindow.ekey = tsList[j];
      pInfo->start = j;

    } else if (memcmp(pInfo->prevData, val, bytes) == 0) {
      pInfo->curWindow.ekey = tsList[j];
      pInfo->numOfRows += 1;
L
Liu Jicong 已提交
5751
      // pInfo->start = j;
5752 5753 5754 5755 5756 5757 5758
      if (j == 0 && pInfo->start != 0) {
        pInfo->numOfRows = 1;
        pInfo->start = 0;
      }
    } else {
      SResultRow* pResult = NULL;
      pInfo->curWindow.ekey = pInfo->curWindow.skey;
L
Liu Jicong 已提交
5759 5760 5761
      int32_t ret = setResultOutputBufByKey(pRuntimeEnv, &pBInfo->resultRowInfo, pSDataBlock->info.uid,
                                            &pInfo->curWindow, masterScan, &pResult, item->groupIndex, pBInfo->pCtx,
                                            pOperator->numOfOutput, pBInfo->rowCellInfoOffset);
5762 5763 5764
      if (ret != TSDB_CODE_SUCCESS) {  // null data, too many state code
        longjmp(pRuntimeEnv->env, TSDB_CODE_QRY_APP_ERROR);
      }
L
Liu Jicong 已提交
5765 5766
      //      doApplyFunctions(pRuntimeEnv, pBInfo->pCtx, &pInfo->curWindow, pInfo->start, pInfo->numOfRows, tsList,
      //                       pSDataBlock->info.rows, pOperator->numOfOutput);
5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778

      pInfo->curWindow.skey = tsList[j];
      pInfo->curWindow.ekey = tsList[j];
      memcpy(pInfo->prevData, val, bytes);
      pInfo->numOfRows = 1;
      pInfo->start = j;
    }
  }

  SResultRow* pResult = NULL;

  pInfo->curWindow.ekey = pInfo->curWindow.skey;
L
Liu Jicong 已提交
5779 5780
  int32_t ret = setResultOutputBufByKey(pRuntimeEnv, &pBInfo->resultRowInfo, pSDataBlock->info.uid, &pInfo->curWindow,
                                        masterScan, &pResult, item->groupIndex, pBInfo->pCtx, pOperator->numOfOutput,
5781 5782 5783 5784 5785
                                        pBInfo->rowCellInfoOffset);
  if (ret != TSDB_CODE_SUCCESS) {  // null data, too many state code
    longjmp(pRuntimeEnv->env, TSDB_CODE_QRY_APP_ERROR);
  }

L
Liu Jicong 已提交
5786 5787
  //  doApplyFunctions(pRuntimeEnv, pBInfo->pCtx, &pInfo->curWindow, pInfo->start, pInfo->numOfRows, tsList,
  //                   pSDataBlock->info.rows, pOperator->numOfOutput);
5788 5789
}

L
Liu Jicong 已提交
5790
static SSDataBlock* doStateWindowAgg(SOperatorInfo* pOperator, bool* newgroup) {
5791 5792 5793 5794 5795
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

  SStateWindowOperatorInfo* pWindowInfo = pOperator->info;
H
Haojun Liao 已提交
5796 5797
  SExecTaskInfo*  pTaskInfo = pOperator->pTaskInfo;
  SOptrBasicInfo* pBInfo    = &pWindowInfo->binfo;
5798 5799

  if (pOperator->status == OP_RES_TO_RETURN) {
L
Liu Jicong 已提交
5800
    //    toSDatablock(&pRuntimeEnv->groupResInfo, pRuntimeEnv, pBInfo->pRes);
5801

H
Haojun Liao 已提交
5802 5803 5804
//    if (pBInfo->pRes->info.rows == 0 || !hasRemainDataInCurrentGroup(&pRuntimeEnv->groupResInfo)) {
//      pOperator->status = OP_EXEC_DONE;
//    }
5805 5806 5807 5808

    return pBInfo->pRes;
  }

H
Haojun Liao 已提交
5809 5810 5811
  int32_t        order = TSDB_ORDER_ASC;
  STimeWindow    win = pTaskInfo->window;

H
Haojun Liao 已提交
5812
  SOperatorInfo* downstream = pOperator->pDownstream[0];
5813
  while (1) {
H
Haojun Liao 已提交
5814
    publishOperatorProfEvent(downstream, QUERY_PROF_BEFORE_OPERATOR_EXEC);
H
Haojun Liao 已提交
5815
    SSDataBlock* pBlock = downstream->getNextFn(downstream, newgroup);
H
Haojun Liao 已提交
5816
    publishOperatorProfEvent(downstream, QUERY_PROF_AFTER_OPERATOR_EXEC);
5817 5818 5819 5820

    if (pBlock == NULL) {
      break;
    }
H
Haojun Liao 已提交
5821 5822 5823 5824 5825

//    setInputDataBlock(pOperator, pBInfo->pCtx, pDataBlock, TSDB_ORDER_ASC);
//    if (pWindowInfo->colIndex == -1) {
//      pWindowInfo->colIndex = getGroupbyColumnIndex(pRuntimeEnv->pQueryAttr->pGroupbyExpr, pBlock);
//    }
L
Liu Jicong 已提交
5826
    doStateWindowAggImpl(pOperator, pWindowInfo, pBlock);
5827 5828 5829
  }

  // restore the value
H
Haojun Liao 已提交
5830 5831
//  pQueryAttr->order.order = order;
//  pQueryAttr->window = win;
5832 5833 5834

  pOperator->status = OP_RES_TO_RETURN;
  closeAllResultRows(&pBInfo->resultRowInfo);
5835
  setTaskStatus(pOperator->pTaskInfo, TASK_COMPLETED);
5836
  finalizeQueryResult(pBInfo->pCtx, pOperator->numOfOutput);
5837

H
Haojun Liao 已提交
5838
//  initGroupResInfo(&pRuntimeEnv->groupResInfo, &pBInfo->resultRowInfo);
L
Liu Jicong 已提交
5839
  //  toSDatablock(&pRuntimeEnv->groupResInfo, pRuntimeEnv, pBInfo->pRes);
5840

H
Haojun Liao 已提交
5841 5842 5843
//  if (pBInfo->pRes->info.rows == 0 || !hasRemainDataInCurrentGroup(&pRuntimeEnv->groupResInfo)) {
//    pOperator->status = OP_EXEC_DONE;
//  }
5844

L
Liu Jicong 已提交
5845
  return pBInfo->pRes->info.rows == 0 ? NULL : pBInfo->pRes;
5846 5847
}

L
Liu Jicong 已提交
5848
static SSDataBlock* doSessionWindowAgg(SOperatorInfo* pOperator, bool* newgroup) {
5849 5850 5851 5852
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

5853
  SSessionAggOperatorInfo* pInfo = pOperator->info;
L
Liu Jicong 已提交
5854
  SOptrBasicInfo*          pBInfo = &pInfo->binfo;
5855 5856

  if (pOperator->status == OP_RES_TO_RETURN) {
5857
    toSDatablock(&pInfo->groupResInfo, pInfo->aggSup.pResultBuf, pBInfo->pRes, pBInfo->capacity, pBInfo->rowCellInfoOffset);
5858 5859 5860
    if (pBInfo->pRes->info.rows == 0 || !hasRemainDataInCurrentGroup(&pInfo->groupResInfo)) {
      doSetOperatorCompleted(pOperator);
      return NULL;
5861 5862 5863 5864 5865
    }

    return pBInfo->pRes;
  }

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

L
Liu Jicong 已提交
5869
  while (1) {
H
Haojun Liao 已提交
5870
    publishOperatorProfEvent(downstream, QUERY_PROF_BEFORE_OPERATOR_EXEC);
H
Haojun Liao 已提交
5871
    SSDataBlock* pBlock = downstream->getNextFn(downstream, newgroup);
H
Haojun Liao 已提交
5872
    publishOperatorProfEvent(downstream, QUERY_PROF_AFTER_OPERATOR_EXEC);
5873 5874 5875 5876 5877
    if (pBlock == NULL) {
      break;
    }

    // the pDataBlock are always the same one, no need to call this again
H
Haojun Liao 已提交
5878
    setInputDataBlock(pOperator, pBInfo->pCtx, pBlock, order);
5879
    doSessionWindowAggImpl(pOperator, pInfo, pBlock);
5880 5881 5882 5883 5884
  }

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

5887 5888
  initGroupResInfo(&pInfo->groupResInfo, &pBInfo->resultRowInfo);
  blockDataEnsureCapacity(pBInfo->pRes, pBInfo->capacity);
5889
  toSDatablock(&pInfo->groupResInfo, pInfo->aggSup.pResultBuf, pBInfo->pRes, pBInfo->capacity, pBInfo->rowCellInfoOffset);
5890 5891
  if (pBInfo->pRes->info.rows == 0 || !hasRemainDataInCurrentGroup(&pInfo->groupResInfo)) {
    doSetOperatorCompleted(pOperator);
5892 5893
  }

L
Liu Jicong 已提交
5894
  return pBInfo->pRes->info.rows == 0 ? NULL : pBInfo->pRes;
5895 5896 5897
}


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

L
Liu Jicong 已提交
5902 5903
  int64_t ekey = Q_STATUS_EQUAL(pTaskInfo->status, TASK_COMPLETED) ? pTaskInfo->window.ekey
                                                                   : pInfo->existNewGroupBlock->info.window.ekey;
5904 5905
  taosResetFillInfo(pInfo->pFillInfo, getFillInfoStart(pInfo->pFillInfo));

5906
  taosFillSetStartInfo(pInfo->pFillInfo, pInfo->existNewGroupBlock->info.rows, ekey);
5907 5908
  taosFillSetInputDataBlock(pInfo->pFillInfo, pInfo->existNewGroupBlock);

H
Haojun Liao 已提交
5909
  doFillTimeIntervalGapsInResults(pInfo->pFillInfo, pInfo->pRes, pResultInfo->capacity, pInfo->p);
5910 5911 5912 5913
  pInfo->existNewGroupBlock = NULL;
  *newgroup = true;
}

L
Liu Jicong 已提交
5914 5915
static void doHandleRemainBlockFromNewGroup(SFillOperatorInfo* pInfo, SResultInfo* pResultInfo, bool* newgroup,
                                            SExecTaskInfo* pTaskInfo) {
5916 5917
  if (taosFillHasMoreResults(pInfo->pFillInfo)) {
    *newgroup = false;
H
Haojun Liao 已提交
5918 5919
    doFillTimeIntervalGapsInResults(pInfo->pFillInfo, pInfo->pRes, (int32_t)pResultInfo->capacity, pInfo->p);
    if (pInfo->pRes->info.rows > pResultInfo->threshold || (!pInfo->multigroupResult)) {
5920 5921 5922 5923 5924 5925
      return;
    }
  }

  // handle the cached new group data block
  if (pInfo->existNewGroupBlock) {
5926
    doHandleRemainBlockForNewGroupImpl(pInfo, pResultInfo, newgroup, pTaskInfo);
5927 5928 5929
  }
}

L
Liu Jicong 已提交
5930 5931 5932
static SSDataBlock* doFill(SOperatorInfo* pOperator, bool* newgroup) {
  SFillOperatorInfo* pInfo = pOperator->info;
  SExecTaskInfo*     pTaskInfo = pOperator->pTaskInfo;
5933

H
Haojun Liao 已提交
5934 5935
  SResultInfo* pResultInfo = &pOperator->resultInfo;
  blockDataCleanup(pInfo->pRes);
5936 5937 5938 5939
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

5940
  doHandleRemainBlockFromNewGroup(pInfo, pResultInfo, newgroup, pTaskInfo);
H
Haojun Liao 已提交
5941 5942 5943
  if (pInfo->pRes->info.rows > pResultInfo->threshold || (!pInfo->multigroupResult && pInfo->pRes->info.rows > 0)) {
    return pInfo->pRes;
  }
5944

H
Haojun Liao 已提交
5945
  SOperatorInfo* pDownstream = pOperator->pDownstream[0];
L
Liu Jicong 已提交
5946
  while (1) {
H
Haojun Liao 已提交
5947 5948 5949
    publishOperatorProfEvent(pDownstream, QUERY_PROF_BEFORE_OPERATOR_EXEC);
    SSDataBlock* pBlock = pDownstream->getNextFn(pDownstream, newgroup);
    publishOperatorProfEvent(pDownstream, QUERY_PROF_AFTER_OPERATOR_EXEC);
5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960

    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
5961
      taosFillSetStartInfo(pInfo->pFillInfo, 0, pTaskInfo->window.ekey);
5962 5963 5964 5965 5966 5967 5968
    } else {
      if (pBlock == NULL) {
        if (pInfo->totalInputRows == 0) {
          pOperator->status = OP_EXEC_DONE;
          return NULL;
        }

5969
        taosFillSetStartInfo(pInfo->pFillInfo, 0, pTaskInfo->window.ekey);
5970 5971 5972 5973 5974 5975 5976
      } else {
        pInfo->totalInputRows += pBlock->info.rows;
        taosFillSetStartInfo(pInfo->pFillInfo, pBlock->info.rows, pBlock->info.window.ekey);
        taosFillSetInputDataBlock(pInfo->pFillInfo, pBlock);
      }
    }

H
Haojun Liao 已提交
5977
    doFillTimeIntervalGapsInResults(pInfo->pFillInfo, pInfo->pRes, pInfo->capacity, pInfo->p);
5978 5979 5980 5981 5982

    // 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 已提交
5983
      if (pInfo->pRes->info.rows > pResultInfo->threshold || pBlock == NULL || (!pInfo->multigroupResult)) {
5984 5985 5986
        return pInfo->pRes;
      }

5987
      doHandleRemainBlockFromNewGroup(pInfo, pResultInfo, newgroup, pTaskInfo);
H
Haojun Liao 已提交
5988
      if (pInfo->pRes->info.rows > pOperator->resultInfo.threshold || pBlock == NULL) {
5989 5990 5991 5992
        return pInfo->pRes;
      }
    } else if (pInfo->existNewGroupBlock) {  // try next group
      assert(pBlock != NULL);
5993
      doHandleRemainBlockForNewGroupImpl(pInfo, pResultInfo, newgroup, pTaskInfo);
H
Haojun Liao 已提交
5994
      if (pInfo->pRes->info.rows > pResultInfo->threshold) {
5995 5996 5997 5998 5999 6000 6001 6002 6003
        return pInfo->pRes;
      }
    } else {
      return NULL;
    }
  }
}

// todo set the attribute of query scan count
H
Haojun Liao 已提交
6004
static int32_t getNumOfScanTimes(STaskAttr* pQueryAttr) {
L
Liu Jicong 已提交
6005
  for (int32_t i = 0; i < pQueryAttr->numOfOutput; ++i) {
6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019
    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 已提交
6020 6021
  if (pOperator->closeFn != NULL) {
    pOperator->closeFn(pOperator->info, pOperator->numOfOutput);
6022 6023
  }

H
Haojun Liao 已提交
6024
  if (pOperator->pDownstream != NULL) {
L
Liu Jicong 已提交
6025
    for (int32_t i = 0; i < pOperator->numOfDownstream; ++i) {
H
Haojun Liao 已提交
6026
      destroyOperatorInfo(pOperator->pDownstream[i]);
6027 6028
    }

wafwerar's avatar
wafwerar 已提交
6029
    taosMemoryFreeClear(pOperator->pDownstream);
H
Haojun Liao 已提交
6030
    pOperator->numOfDownstream = 0;
6031 6032
  }

wafwerar's avatar
wafwerar 已提交
6033 6034
  taosMemoryFreeClear(pOperator->info);
  taosMemoryFreeClear(pOperator);
6035 6036
}

L
Liu Jicong 已提交
6037
int32_t doInitAggInfoSup(SAggSupporter* pAggSup, SqlFunctionCtx* pCtx, int32_t numOfOutput, const char* pKey) {
6038 6039
  _hash_fn_t hashFn = taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY);

H
Haojun Liao 已提交
6040 6041
  pAggSup->resultRowSize       = getResultRowSize(pCtx, numOfOutput);
  pAggSup->keyBuf              = taosMemoryCalloc(1, sizeof(int64_t) + sizeof(int64_t) + POINTER_BYTES);
6042
  pAggSup->pResultRowHashTable = taosHashInit(10, hashFn, true, HASH_NO_LOCK);
H
Haojun Liao 已提交
6043
  pAggSup->pResultRowListSet   = taosHashInit(100, hashFn, false, HASH_NO_LOCK);
6044 6045 6046
  pAggSup->pResultRowArrayList = taosArrayInit(10, sizeof(SResultRowCell));

  if (pAggSup->keyBuf == NULL || pAggSup->pResultRowArrayList == NULL || pAggSup->pResultRowListSet == NULL ||
6047
      pAggSup->pResultRowHashTable == NULL) {
6048 6049 6050
    return TSDB_CODE_OUT_OF_MEMORY;
  }

H
Haojun Liao 已提交
6051 6052 6053 6054 6055
  int32_t code = createDiskbasedBuf(&pAggSup->pResultBuf, 4096, 4096 * 256, pKey, "/tmp/");
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

6056 6057 6058
  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
6059
static void cleanupAggSup(SAggSupporter* pAggSup) {
wafwerar's avatar
wafwerar 已提交
6060
  taosMemoryFreeClear(pAggSup->keyBuf);
6061 6062 6063
  taosHashCleanup(pAggSup->pResultRowHashTable);
  taosHashCleanup(pAggSup->pResultRowListSet);
  taosArrayDestroy(pAggSup->pResultRowArrayList);
H
Haojun Liao 已提交
6064
  destroyDiskbasedBuf(pAggSup->pResultBuf);
6065 6066
}

H
Haojun Liao 已提交
6067
int32_t initAggInfo(SOptrBasicInfo* pBasicInfo, SAggSupporter* pAggSup, SExprInfo* pExprInfo, int32_t numOfCols,
H
Haojun Liao 已提交
6068
                           int32_t numOfRows, SSDataBlock* pResultBlock, const char* pkey) {
H
Haojun Liao 已提交
6069 6070 6071 6072
  pBasicInfo->pCtx = createSqlFunctionCtx_rv(pExprInfo, numOfCols, &pBasicInfo->rowCellInfoOffset);
  pBasicInfo->pRes = pResultBlock;
  pBasicInfo->capacity = numOfRows;

H
Haojun Liao 已提交
6073
  doInitAggInfoSup(pAggSup, pBasicInfo->pCtx, numOfCols, pkey);
H
Haojun Liao 已提交
6074 6075 6076
}

static STableQueryInfo* initTableQueryInfo(const STableGroupInfo* pTableGroupInfo) {
wafwerar's avatar
wafwerar 已提交
6077
  STableQueryInfo* pTableQueryInfo = taosMemoryCalloc(pTableGroupInfo->numOfTables, sizeof(STableQueryInfo));
H
Haojun Liao 已提交
6078 6079
  if (pTableQueryInfo == NULL) {
    return NULL;
H
Haojun Liao 已提交
6080
  }
H
Haojun Liao 已提交
6081 6082

  int32_t index = 0;
L
Liu Jicong 已提交
6083
  for (int32_t i = 0; i < taosArrayGetSize(pTableGroupInfo->pGroupList); ++i) {
H
Haojun Liao 已提交
6084
    SArray* pa = taosArrayGetP(pTableGroupInfo->pGroupList, i);
L
Liu Jicong 已提交
6085
    for (int32_t j = 0; j < taosArrayGetSize(pa); ++j) {
H
Haojun Liao 已提交
6086 6087
      STableKeyInfo* pk = taosArrayGet(pa, j);

H
Haojun Liao 已提交
6088
      STableQueryInfo* pTQueryInfo = &pTableQueryInfo[index++];
L
Liu Jicong 已提交
6089 6090
      pTQueryInfo->uid = pk->uid;
      pTQueryInfo->lastKey = pk->lastKey;
H
Haojun Liao 已提交
6091 6092 6093
      pTQueryInfo->groupIndex = i;
    }
  }
H
Haojun Liao 已提交
6094 6095

  STimeWindow win = {0, INT64_MAX};
H
Haojun Liao 已提交
6096 6097
  createTableQueryInfo(pTableQueryInfo, false, win);
  return pTableQueryInfo;
H
Haojun Liao 已提交
6098 6099
}

L
Liu Jicong 已提交
6100 6101 6102
SOperatorInfo* createAggregateOperatorInfo(SOperatorInfo* downstream, SExprInfo* pExprInfo, int32_t numOfCols,
                                           SSDataBlock* pResultBlock, SExecTaskInfo* pTaskInfo,
                                           const STableGroupInfo* pTableGroupInfo) {
wafwerar's avatar
wafwerar 已提交
6103
  SAggOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SAggOperatorInfo));
L
Liu Jicong 已提交
6104
  SOperatorInfo*    pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
6105 6106 6107
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }
H
Haojun Liao 已提交
6108 6109

  //(int32_t)(getRowNumForMultioutput(pQueryAttr, pQueryAttr->topBotQuery, pQueryAttr->stableQuery));
H
Haojun Liao 已提交
6110
  int32_t numOfRows = 1;
H
Haojun Liao 已提交
6111
  int32_t code = initAggInfo(&pInfo->binfo, &pInfo->aggSup, pExprInfo, numOfCols, numOfRows, pResultBlock, pTaskInfo->id.str);
H
Haojun Liao 已提交
6112 6113
  pInfo->pTableQueryInfo = initTableQueryInfo(pTableGroupInfo);
  if (code != TSDB_CODE_SUCCESS || pInfo->pTableQueryInfo == NULL) {
H
Haojun Liao 已提交
6114 6115
    goto _error;
  }
H
Haojun Liao 已提交
6116

H
Haojun Liao 已提交
6117
  setFunctionResultOutput(&pInfo->binfo, &pInfo->aggSup, MAIN_SCAN, pTaskInfo);
6118

H
Haojun Liao 已提交
6119
  pOperator->name         = "TableAggregate";
X
Xiaoyu Wang 已提交
6120
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_AGG;
6121
  pOperator->blockingOptr = true;
H
Haojun Liao 已提交
6122 6123 6124 6125 6126 6127 6128 6129 6130
  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 已提交
6131 6132
  pOperator->encodeResultRow = aggEncodeResultRow;
  pOperator->decodeResultRow = aggDecodeResultRow;
H
Haojun Liao 已提交
6133 6134 6135 6136 6137

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

  return pOperator;
L
Liu Jicong 已提交
6140
_error:
H
Haojun Liao 已提交
6141
  destroyAggOperatorInfo(pInfo, numOfCols);
wafwerar's avatar
wafwerar 已提交
6142 6143
  taosMemoryFreeClear(pInfo);
  taosMemoryFreeClear(pOperator);
H
Haojun Liao 已提交
6144 6145
  pTaskInfo->code = TSDB_CODE_OUT_OF_MEMORY;
  return NULL;
6146 6147
}

H
Haojun Liao 已提交
6148
void doDestroyBasicInfo(SOptrBasicInfo* pInfo, int32_t numOfOutput) {
6149 6150
  assert(pInfo != NULL);

6151
  destroySqlFunctionCtx(pInfo->pCtx, numOfOutput);
wafwerar's avatar
wafwerar 已提交
6152
  taosMemoryFreeClear(pInfo->rowCellInfoOffset);
6153 6154

  cleanupResultRowInfo(&pInfo->resultRowInfo);
H
Haojun Liao 已提交
6155
  pInfo->pRes = blockDataDestroy(pInfo->pRes);
6156 6157
}

H
Haojun Liao 已提交
6158
void destroyBasicOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
6159
  SOptrBasicInfo* pInfo = (SOptrBasicInfo*)param;
6160 6161
  doDestroyBasicInfo(pInfo, numOfOutput);
}
H
Haojun Liao 已提交
6162 6163

void destroyStateWindowOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
6164
  SStateWindowOperatorInfo* pInfo = (SStateWindowOperatorInfo*)param;
6165
  doDestroyBasicInfo(&pInfo->binfo, numOfOutput);
wafwerar's avatar
wafwerar 已提交
6166
  taosMemoryFreeClear(pInfo->prevData);
6167
}
H
Haojun Liao 已提交
6168 6169

void destroyAggOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
6170
  SAggOperatorInfo* pInfo = (SAggOperatorInfo*)param;
6171 6172
  doDestroyBasicInfo(&pInfo->binfo, numOfOutput);
}
6173

H
Haojun Liao 已提交
6174
void destroyIntervalOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
6175
  STableIntervalOperatorInfo* pInfo = (STableIntervalOperatorInfo*)param;
H
Haojun Liao 已提交
6176 6177 6178 6179 6180
  doDestroyBasicInfo(&pInfo->binfo, numOfOutput);
  cleanupAggSup(&pInfo->aggSup);
}

void destroySWindowOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
6181
  SSessionAggOperatorInfo* pInfo = (SSessionAggOperatorInfo*)param;
6182 6183 6184
  doDestroyBasicInfo(&pInfo->binfo, numOfOutput);
}

H
Haojun Liao 已提交
6185
void destroySFillOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
6186
  SFillOperatorInfo* pInfo = (SFillOperatorInfo*)param;
6187
  pInfo->pFillInfo = taosDestroyFillInfo(pInfo->pFillInfo);
H
Haojun Liao 已提交
6188
  pInfo->pRes = blockDataDestroy(pInfo->pRes);
wafwerar's avatar
wafwerar 已提交
6189
  taosMemoryFreeClear(pInfo->p);
6190 6191
}

H
Haojun Liao 已提交
6192
static void destroyProjectOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
6193
  SProjectOperatorInfo* pInfo = (SProjectOperatorInfo*)param;
6194 6195 6196
  doDestroyBasicInfo(&pInfo->binfo, numOfOutput);
}

H
Haojun Liao 已提交
6197
static void destroyTagScanOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
6198
  STagScanInfo* pInfo = (STagScanInfo*)param;
H
Haojun Liao 已提交
6199
  pInfo->pRes = blockDataDestroy(pInfo->pRes);
6200 6201
}

H
Haojun Liao 已提交
6202
static void destroyOrderOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
6203
  SSortOperatorInfo* pInfo = (SSortOperatorInfo*)param;
H
Haojun Liao 已提交
6204 6205
  pInfo->pDataBlock = blockDataDestroy(pInfo->pDataBlock);

H
Haojun Liao 已提交
6206
  taosArrayDestroy(pInfo->pSortInfo);
6207 6208 6209
}

static void destroyDistinctOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
6210
  SDistinctOperatorInfo* pInfo = (SDistinctOperatorInfo*)param;
6211
  taosHashCleanup(pInfo->pSet);
wafwerar's avatar
wafwerar 已提交
6212
  taosMemoryFreeClear(pInfo->buf);
6213
  taosArrayDestroy(pInfo->pDistinctDataInfo);
H
Haojun Liao 已提交
6214
  pInfo->pRes = blockDataDestroy(pInfo->pRes);
6215 6216
}

H
Haojun Liao 已提交
6217
void destroyExchangeOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
6218
  SExchangeInfo* pExInfo = (SExchangeInfo*)param;
H
Haojun Liao 已提交
6219 6220 6221 6222 6223 6224 6225 6226 6227
  taosArrayDestroy(pExInfo->pSources);
  taosArrayDestroy(pExInfo->pSourceDataInfo);
  if (pExInfo->pResult != NULL) {
    blockDataDestroy(pExInfo->pResult);
  }

  tsem_destroy(&pExInfo->ready);
}

L
Liu Jicong 已提交
6228 6229 6230
SOperatorInfo* createMultiTableAggOperatorInfo(SOperatorInfo* downstream, SExprInfo* pExprInfo, int32_t numOfCols,
                                               SSDataBlock* pResBlock, SExecTaskInfo* pTaskInfo,
                                               const STableGroupInfo* pTableGroupInfo) {
wafwerar's avatar
wafwerar 已提交
6231
  SAggOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SAggOperatorInfo));
6232

H
Haojun Liao 已提交
6233
  int32_t numOfRows = 1;
L
Liu Jicong 已提交
6234 6235
  int32_t code =
      initAggInfo(&pInfo->binfo, &pInfo->aggSup, pExprInfo, numOfCols, numOfRows, pResBlock, pTaskInfo->id.str);
H
Haojun Liao 已提交
6236 6237 6238 6239
  pInfo->pTableQueryInfo = initTableQueryInfo(pTableGroupInfo);
  if (code != TSDB_CODE_SUCCESS || pInfo->pTableQueryInfo == NULL) {
    goto _error;
  }
H
Haojun Liao 已提交
6240

L
Liu Jicong 已提交
6241
  size_t tableGroup = taosArrayGetSize(pTableGroupInfo->pGroupList);
6242
  initResultRowInfo(&pInfo->binfo.resultRowInfo, (int32_t)tableGroup);
6243

wafwerar's avatar
wafwerar 已提交
6244
  SOperatorInfo* pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
L
Liu Jicong 已提交
6245
  pOperator->name = "MultiTableAggregate";
X
Xiaoyu Wang 已提交
6246
  // pOperator->operatorType = OP_MultiTableAggregate;
6247
  pOperator->blockingOptr = true;
L
Liu Jicong 已提交
6248 6249 6250 6251 6252
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
  pOperator->pExpr = pExprInfo;
  pOperator->numOfOutput = numOfCols;
  pOperator->pTaskInfo = pTaskInfo;
6253

H
Haojun Liao 已提交
6254
  pOperator->getNextFn = doMultiTableAggregate;
H
Haojun Liao 已提交
6255
  pOperator->closeFn = destroyAggOperatorInfo;
H
Haojun Liao 已提交
6256 6257 6258 6259
  code = appendDownstream(pOperator, &downstream, 1);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
6260 6261

  return pOperator;
H
Haojun Liao 已提交
6262 6263 6264

_error:
  return NULL;
6265 6266
}

H
Haojun Liao 已提交
6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277
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 已提交
6278
SOperatorInfo* createProjectOperatorInfo(SOperatorInfo* downstream, SExprInfo* pExprInfo, int32_t num,
H
Haojun Liao 已提交
6279
                                         SSDataBlock* pResBlock, SLimit* pLimit, SExecTaskInfo* pTaskInfo) {
wafwerar's avatar
wafwerar 已提交
6280
  SProjectOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SProjectOperatorInfo));
L
Liu Jicong 已提交
6281
  SOperatorInfo*        pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
6282 6283 6284
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }
6285

H
Haojun Liao 已提交
6286 6287
  pInfo->limit      = *pLimit;
  pInfo->curOffset  = pLimit->offset;
H
Haojun Liao 已提交
6288
  pInfo->binfo.pRes = pResBlock;
H
Haojun Liao 已提交
6289 6290 6291 6292 6293

  int32_t numOfCols = num;
  int32_t numOfRows = 4096;
  initAggInfo(&pInfo->binfo, &pInfo->aggSup, pExprInfo, numOfCols, numOfRows, pResBlock, pTaskInfo->id.str);
  setFunctionResultOutput(&pInfo->binfo, &pInfo->aggSup, MAIN_SCAN, pTaskInfo);
H
Haojun Liao 已提交
6294
  pInfo->pPseudoColInfo = setRowTsColumnOutputInfo(pInfo->binfo.pCtx, numOfCols);
6295

H
Haojun Liao 已提交
6296
  pOperator->name         = "ProjectOperator";
H
Haojun Liao 已提交
6297
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_PROJECT;
6298
  pOperator->blockingOptr = false;
H
Haojun Liao 已提交
6299 6300 6301 6302 6303 6304 6305
  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 已提交
6306 6307

  pOperator->pTaskInfo = pTaskInfo;
6308
  int32_t code = appendDownstream(pOperator, &downstream, 1);
H
Haojun Liao 已提交
6309
  if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
6310 6311
    goto _error;
  }
6312 6313

  return pOperator;
H
Haojun Liao 已提交
6314

L
Liu Jicong 已提交
6315
_error:
H
Haojun Liao 已提交
6316 6317
  pTaskInfo->code = TSDB_CODE_OUT_OF_MEMORY;
  return NULL;
6318 6319
}

L
Liu Jicong 已提交
6320 6321
SOperatorInfo* createIntervalOperatorInfo(SOperatorInfo* downstream, SExprInfo* pExprInfo, int32_t numOfCols,
                                          SSDataBlock* pResBlock, SInterval* pInterval,
6322
                                          const STableGroupInfo* pTableGroupInfo, SExecTaskInfo* pTaskInfo) {
wafwerar's avatar
wafwerar 已提交
6323
  STableIntervalOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(STableIntervalOperatorInfo));
L
Liu Jicong 已提交
6324
  SOperatorInfo*              pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
6325 6326 6327
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }
H
Haojun Liao 已提交
6328

H
Haojun Liao 已提交
6329 6330
  pInfo->order     = TSDB_ORDER_ASC;
  pInfo->interval  = *pInterval;
6331 6332 6333
  pInfo->execModel = pTaskInfo->execModel;

  pInfo->win       = pTaskInfo->window;
6334 6335
  pInfo->win.skey  = 0;
  pInfo->win.ekey  = INT64_MAX;
6336 6337

  int32_t numOfRows = 4096;
H
Haojun Liao 已提交
6338
  int32_t code = initAggInfo(&pInfo->binfo, &pInfo->aggSup, pExprInfo, numOfCols, numOfRows, pResBlock, pTaskInfo->id.str);
6339 6340
  initExecTimeWindowInfo(&pInfo->timeWindowData, &pInfo->win);

L
Liu Jicong 已提交
6341 6342
  //  pInfo->pTableQueryInfo = initTableQueryInfo(pTableGroupInfo);
  if (code != TSDB_CODE_SUCCESS /* || pInfo->pTableQueryInfo == NULL*/) {
H
Haojun Liao 已提交
6343 6344
    goto _error;
  }
H
Haojun Liao 已提交
6345 6346

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

6348
  pOperator->name         = "TimeIntervalAggOperator";
H
Haojun Liao 已提交
6349
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_INTERVAL;
6350
  pOperator->blockingOptr = true;
H
Haojun Liao 已提交
6351 6352 6353 6354 6355 6356 6357
  pOperator->status       = OP_NOT_OPENED;
  pOperator->pExpr        = pExprInfo;
  pOperator->pTaskInfo    = pTaskInfo;
  pOperator->numOfOutput  = numOfCols;
  pOperator->info         = pInfo;
  pOperator->_openFn      = doOpenIntervalAgg;
  pOperator->getNextFn    = doBuildIntervalResult;
6358
  pOperator->getStreamResFn= doStreamIntervalAgg;
H
Haojun Liao 已提交
6359
  pOperator->closeFn      = destroyIntervalOperatorInfo;
6360

H
Haojun Liao 已提交
6361
  code = appendDownstream(pOperator, &downstream, 1);
H
Haojun Liao 已提交
6362 6363 6364 6365
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }

6366
  return pOperator;
H
Haojun Liao 已提交
6367

L
Liu Jicong 已提交
6368
_error:
H
Haojun Liao 已提交
6369
  destroyIntervalOperatorInfo(pInfo, numOfCols);
wafwerar's avatar
wafwerar 已提交
6370 6371
  taosMemoryFreeClear(pInfo);
  taosMemoryFreeClear(pOperator);
H
Haojun Liao 已提交
6372 6373
  pTaskInfo->code = code;
  return NULL;
6374 6375
}

L
Liu Jicong 已提交
6376 6377
SOperatorInfo* createAllTimeIntervalOperatorInfo(STaskRuntimeEnv* pRuntimeEnv, SOperatorInfo* downstream,
                                                 SExprInfo* pExpr, int32_t numOfOutput) {
wafwerar's avatar
wafwerar 已提交
6378
  STableIntervalOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(STableIntervalOperatorInfo));
6379

L
Liu Jicong 已提交
6380 6381
  //  pInfo->binfo.pCtx = createSqlFunctionCtx(pRuntimeEnv, pExpr, numOfOutput, &pInfo->binfo.rowCellInfoOffset);
  //  pInfo->binfo.pRes = createOutputBuf(pExpr, numOfOutput, pResultInfo->capacity);
H
Haojun Liao 已提交
6382
  initResultRowInfo(&pInfo->binfo.resultRowInfo, 8);
6383

wafwerar's avatar
wafwerar 已提交
6384
  SOperatorInfo* pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
6385

L
Liu Jicong 已提交
6386 6387
  pOperator->name = "AllTimeIntervalAggOperator";
  //  pOperator->operatorType = OP_AllTimeWindow;
6388
  pOperator->blockingOptr = true;
L
Liu Jicong 已提交
6389 6390 6391 6392 6393
  pOperator->status = OP_NOT_OPENED;
  pOperator->pExpr = pExpr;
  pOperator->numOfOutput = numOfOutput;
  pOperator->info = pInfo;
  pOperator->pRuntimeEnv = pRuntimeEnv;
H
Haojun Liao 已提交
6394
  pOperator->getNextFn = doAllIntervalAgg;
H
Haojun Liao 已提交
6395
  pOperator->closeFn = destroyBasicOperatorInfo;
6396

L
Liu Jicong 已提交
6397
  int32_t code = appendDownstream(pOperator, &downstream, 1);
6398 6399 6400
  return pOperator;
}

H
Haojun Liao 已提交
6401
SOperatorInfo* createStatewindowOperatorInfo(SOperatorInfo* downstream, SExprInfo* pExpr, int32_t numOfCols, SSDataBlock* pResBlock, SExecTaskInfo* pTaskInfo) {
wafwerar's avatar
wafwerar 已提交
6402
  SStateWindowOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SStateWindowOperatorInfo));
H
Haojun Liao 已提交
6403

L
Liu Jicong 已提交
6404 6405 6406 6407
  pInfo->colIndex = -1;
  pInfo->reptScan = false;
  //  pInfo->binfo.pCtx = createSqlFunctionCtx(pRuntimeEnv, pExpr, numOfOutput, &pInfo->binfo.rowCellInfoOffset);
  //  pInfo->binfo.pRes = createOutputBuf(pExpr, numOfOutput, pResultInfo->capacity);
6408
  initResultRowInfo(&pInfo->binfo.resultRowInfo, 8);
6409

wafwerar's avatar
wafwerar 已提交
6410
  SOperatorInfo* pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
L
Liu Jicong 已提交
6411 6412
  pOperator->name = "StateWindowOperator";
  //  pOperator->operatorType = OP_StateWindow;
6413
  pOperator->blockingOptr = true;
H
Haojun Liao 已提交
6414 6415 6416 6417 6418 6419 6420 6421
  pOperator->status       = OP_NOT_OPENED;
  pOperator->pExpr        = pExpr;
  pOperator->numOfOutput  = numOfCols;

  pOperator->pTaskInfo    = pTaskInfo;
  pOperator->info         = pInfo;
  pOperator->getNextFn    = doStateWindowAgg;
  pOperator->closeFn      = destroyStateWindowOperatorInfo;
6422

H
Haojun Liao 已提交
6423
  int32_t code = appendDownstream(pOperator, &downstream, 1);
6424 6425 6426
  return pOperator;
}

L
Liu Jicong 已提交
6427 6428
SOperatorInfo* createSessionAggOperatorInfo(SOperatorInfo* downstream, SExprInfo* pExprInfo, int32_t numOfCols,
                                            SSDataBlock* pResBlock, int64_t gap, SExecTaskInfo* pTaskInfo) {
wafwerar's avatar
wafwerar 已提交
6429
  SSessionAggOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SSessionAggOperatorInfo));
L
Liu Jicong 已提交
6430
  SOperatorInfo*           pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
6431 6432 6433
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }
H
Haojun Liao 已提交
6434

H
Haojun Liao 已提交
6435
  int32_t numOfRows = 4096;
6436
  int32_t code = initAggInfo(&pInfo->binfo, &pInfo->aggSup, pExprInfo, numOfCols, numOfRows, pResBlock, pTaskInfo->id.str);
H
Haojun Liao 已提交
6437 6438 6439
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
6440

H
Haojun Liao 已提交
6441
  initResultRowInfo(&pInfo->binfo.resultRowInfo, 8);
6442
  initExecTimeWindowInfo(&pInfo->timeWindowData, &pTaskInfo->window);
6443

6444 6445 6446 6447 6448
  pInfo->gap              = gap;
  pInfo->binfo.pRes       = pResBlock;
  pInfo->prevTs           = INT64_MIN;
  pInfo->reptScan         = false;
  pOperator->name         = "SessionWindowAggOperator";
H
Haojun Liao 已提交
6449
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_SESSION_WINDOW;
6450
  pOperator->blockingOptr = true;
6451 6452 6453 6454 6455 6456 6457
  pOperator->status       = OP_NOT_OPENED;
  pOperator->pExpr        = pExprInfo;
  pOperator->numOfOutput  = numOfCols;
  pOperator->info         = pInfo;
  pOperator->getNextFn    = doSessionWindowAgg;
  pOperator->closeFn      = destroySWindowOperatorInfo;
  pOperator->pTaskInfo    = pTaskInfo;
6458

H
Haojun Liao 已提交
6459
  code = appendDownstream(pOperator, &downstream, 1);
6460
  return pOperator;
H
Haojun Liao 已提交
6461

L
Liu Jicong 已提交
6462
_error:
H
Haojun Liao 已提交
6463 6464 6465 6466
  if (pInfo != NULL) {
    destroySWindowOperatorInfo(pInfo, numOfCols);
  }

wafwerar's avatar
wafwerar 已提交
6467 6468
  taosMemoryFreeClear(pInfo);
  taosMemoryFreeClear(pOperator);
H
Haojun Liao 已提交
6469 6470
  pTaskInfo->code = code;
  return NULL;
6471 6472
}

L
Liu Jicong 已提交
6473 6474
SOperatorInfo* createMultiTableTimeIntervalOperatorInfo(STaskRuntimeEnv* pRuntimeEnv, SOperatorInfo* downstream,
                                                        SExprInfo* pExpr, int32_t numOfOutput) {
wafwerar's avatar
wafwerar 已提交
6475
  STableIntervalOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(STableIntervalOperatorInfo));
6476

L
Liu Jicong 已提交
6477 6478
  //  pInfo->binfo.pCtx = createSqlFunctionCtx(pRuntimeEnv, pExpr, numOfOutput, &pInfo->binfo.rowCellInfoOffset);
  //  pInfo->binfo.pRes = createOutputBuf(pExpr, numOfOutput, pResultInfo->capacity);
H
Haojun Liao 已提交
6479
  initResultRowInfo(&pInfo->binfo.resultRowInfo, 8);
6480

wafwerar's avatar
wafwerar 已提交
6481
  SOperatorInfo* pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
L
Liu Jicong 已提交
6482 6483
  pOperator->name = "MultiTableTimeIntervalOperator";
  //  pOperator->operatorType = OP_MultiTableTimeInterval;
6484
  pOperator->blockingOptr = true;
L
Liu Jicong 已提交
6485 6486 6487 6488 6489
  pOperator->status = OP_NOT_OPENED;
  pOperator->pExpr = pExpr;
  pOperator->numOfOutput = numOfOutput;
  pOperator->info = pInfo;
  pOperator->pRuntimeEnv = pRuntimeEnv;
6490

H
Haojun Liao 已提交
6491
  pOperator->getNextFn = doSTableIntervalAgg;
H
Haojun Liao 已提交
6492
  pOperator->closeFn = destroyBasicOperatorInfo;
6493

L
Liu Jicong 已提交
6494
  int32_t code = appendDownstream(pOperator, &downstream, 1);
6495 6496 6497
  return pOperator;
}

L
Liu Jicong 已提交
6498 6499
SOperatorInfo* createAllMultiTableTimeIntervalOperatorInfo(STaskRuntimeEnv* pRuntimeEnv, SOperatorInfo* downstream,
                                                           SExprInfo* pExpr, int32_t numOfOutput) {
wafwerar's avatar
wafwerar 已提交
6500
  STableIntervalOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(STableIntervalOperatorInfo));
6501

L
Liu Jicong 已提交
6502 6503
  //  pInfo->binfo.pCtx = createSqlFunctionCtx(pRuntimeEnv, pExpr, numOfOutput, &pInfo->binfo.rowCellInfoOffset);
  //  pInfo->binfo.pRes = createOutputBuf(pExpr, numOfOutput, pResultInfo->capacity);
H
Haojun Liao 已提交
6504
  initResultRowInfo(&pInfo->binfo.resultRowInfo, 8);
6505

wafwerar's avatar
wafwerar 已提交
6506
  SOperatorInfo* pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
L
Liu Jicong 已提交
6507 6508
  pOperator->name = "AllMultiTableTimeIntervalOperator";
  //  pOperator->operatorType = OP_AllMultiTableTimeInterval;
6509
  pOperator->blockingOptr = true;
L
Liu Jicong 已提交
6510 6511 6512 6513 6514
  pOperator->status = OP_NOT_OPENED;
  pOperator->pExpr = pExpr;
  pOperator->numOfOutput = numOfOutput;
  pOperator->info = pInfo;
  pOperator->pRuntimeEnv = pRuntimeEnv;
6515

H
Haojun Liao 已提交
6516
  pOperator->getNextFn = doAllSTableIntervalAgg;
H
Haojun Liao 已提交
6517
  pOperator->closeFn = destroyBasicOperatorInfo;
6518

L
Liu Jicong 已提交
6519
  int32_t code = appendDownstream(pOperator, &downstream, 1);
6520 6521 6522 6523

  return pOperator;
}

H
Haojun Liao 已提交
6524
static int32_t initFillInfo(SFillOperatorInfo* pInfo, SExprInfo* pExpr, int32_t numOfCols, int64_t* fillVal,
L
Liu Jicong 已提交
6525
                            STimeWindow win, int32_t capacity, const char* id, SInterval* pInterval, int32_t fillType) {
H
Haojun Liao 已提交
6526 6527 6528 6529 6530 6531 6532 6533 6534 6535
  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 已提交
6536 6537
  pInfo->pFillInfo = taosCreateFillInfo(order, w.skey, 0, capacity, numOfCols, pInterval->sliding,
                                        pInterval->slidingUnit, (int8_t)pInterval->precision, fillType, pColInfo, id);
H
Haojun Liao 已提交
6538

wafwerar's avatar
wafwerar 已提交
6539
  pInfo->p = taosMemoryCalloc(numOfCols, POINTER_BYTES);
H
Haojun Liao 已提交
6540 6541 6542 6543 6544 6545 6546 6547

  if (pInfo->pFillInfo == NULL || pInfo->p == NULL) {
    return TSDB_CODE_OUT_OF_MEMORY;
  } else {
    return TSDB_CODE_SUCCESS;
  }
}

L
Liu Jicong 已提交
6548 6549 6550
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 已提交
6551
  SFillOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SFillOperatorInfo));
L
Liu Jicong 已提交
6552
  SOperatorInfo*     pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
6553

L
Liu Jicong 已提交
6554
  pInfo->pRes = pResBlock;
6555
  pInfo->multigroupResult = multigroupResult;
L
Liu Jicong 已提交
6556
  pInfo->intervalInfo = *pInterval;
6557

H
Haojun Liao 已提交
6558
  SResultInfo* pResultInfo = &pOperator->resultInfo;
L
Liu Jicong 已提交
6559 6560
  int32_t      code = initFillInfo(pInfo, pExpr, numOfCols, (int64_t*)fillVal, pTaskInfo->window, pResultInfo->capacity,
                                   pTaskInfo->id.str, pInterval, fillType);
6561 6562 6563
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
6564

L
Liu Jicong 已提交
6565
  pOperator->name = "FillOperator";
6566
  pOperator->blockingOptr = false;
L
Liu Jicong 已提交
6567 6568 6569 6570 6571 6572 6573 6574
  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;
6575

L
Liu Jicong 已提交
6576
  pOperator->closeFn = destroySFillOperatorInfo;
H
Haojun Liao 已提交
6577

6578
  code = appendDownstream(pOperator, &downstream, 1);
6579
  return pOperator;
H
Haojun Liao 已提交
6580

L
Liu Jicong 已提交
6581
_error:
wafwerar's avatar
wafwerar 已提交
6582 6583
  taosMemoryFreeClear(pOperator);
  taosMemoryFreeClear(pInfo);
H
Haojun Liao 已提交
6584
  return NULL;
6585 6586
}

L
Liu Jicong 已提交
6587 6588
SOperatorInfo* createSLimitOperatorInfo(STaskRuntimeEnv* pRuntimeEnv, SOperatorInfo* downstream, SExprInfo* pExpr,
                                        int32_t numOfOutput, void* pMerger, bool multigroupResult) {
wafwerar's avatar
wafwerar 已提交
6589
  SSLimitOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SSLimitOperatorInfo));
L
Liu Jicong 已提交
6590 6591 6592 6593 6594 6595 6596 6597 6598 6599
  SOperatorInfo*       pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));

  //  pInfo->orderColumnList = getResultGroupCheckColumns(pQueryAttr);
  //  pInfo->slimit          = pQueryAttr->slimit;
  //  pInfo->limit           = pQueryAttr->limit;
  //  pInfo->capacity        = pResultInfo->capacity;
  //  pInfo->threshold       = (int64_t)(pInfo->capacity * 0.8);
  //  pInfo->currentOffset   = pQueryAttr->limit.offset;
  //  pInfo->currentGroupOffset = pQueryAttr->slimit.offset;
  pInfo->multigroupResult = multigroupResult;
6600 6601 6602

  // TODO refactor
  int32_t len = 0;
L
Liu Jicong 已提交
6603
  for (int32_t i = 0; i < numOfOutput; ++i) {
6604 6605 6606
    len += pExpr[i].base.resSchema.bytes;
  }

L
Liu Jicong 已提交
6607
  int32_t numOfCols = (pInfo->orderColumnList != NULL) ? (int32_t)taosArrayGetSize(pInfo->orderColumnList) : 0;
wafwerar's avatar
wafwerar 已提交
6608
  pInfo->prevRow = taosMemoryCalloc(1, (POINTER_BYTES * numOfCols + len));
6609 6610

  int32_t offset = POINTER_BYTES * numOfCols;
L
Liu Jicong 已提交
6611
  for (int32_t i = 0; i < numOfCols; ++i) {
6612 6613 6614 6615 6616 6617
    pInfo->prevRow[i] = (char*)pInfo->prevRow + offset;

    SColIndex* index = taosArrayGet(pInfo->orderColumnList, i);
    offset += pExpr[index->colIndex].base.resSchema.bytes;
  }

L
Liu Jicong 已提交
6618
  //  pInfo->pRes = createOutputBuf(pExpr, numOfOutput, pOperator->resultInfo.capacity);
6619

L
Liu Jicong 已提交
6620
  pOperator->name = "SLimitOperator";
X
Xiaoyu Wang 已提交
6621
  // pOperator->operatorType = OP_SLimit;
6622
  pOperator->blockingOptr = false;
L
Liu Jicong 已提交
6623 6624 6625 6626
  pOperator->status = OP_NOT_OPENED;
  //  pOperator->exec         = doSLimit;
  pOperator->info = pInfo;
  pOperator->pRuntimeEnv = pRuntimeEnv;
H
Haojun Liao 已提交
6627
  pOperator->closeFn = destroySlimitOperatorInfo;
6628

L
Liu Jicong 已提交
6629
  int32_t code = appendDownstream(pOperator, &downstream, 1);
6630 6631 6632
  return pOperator;
}

L
Liu Jicong 已提交
6633
static SSDataBlock* doTagScan(SOperatorInfo* pOperator, bool* newgroup) {
6634 6635 6636 6637 6638 6639
#if 0
  SOperatorInfo* pOperator = (SOperatorInfo*) param;
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

H
Haojun Liao 已提交
6640
  STaskRuntimeEnv* pRuntimeEnv = pOperator->pRuntimeEnv;
H
Haojun Liao 已提交
6641
  int32_t maxNumOfTables = (int32_t)pResultInfo->capacity;
6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662

  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) {
6663
      if (pQueryAttr->tagColList[i].colId == pExprInfo->base.pColumns->info.colId) {
6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694
        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;
6695
      if (pExprInfo->base.pColumns->info.colId == TSDB_TBNAME_COLUMN_INDEX) {
6696 6697
        data = tsdbGetTableName(item->pTable);
      } else {
6698
        data = tsdbGetTableTagVal(item->pTable, pExprInfo->base.pColumns->info.colId, type, bytes);
6699 6700 6701 6702 6703 6704
      }

      doSetTagValueToResultBuf(output, data, type, bytes);
      count += 1;
    }

6705
    //qDebug("QInfo:0x%"PRIx64" create (tableId, tag) info completed, rows:%d", GET_TASKID(pRuntimeEnv), count);
6706 6707 6708 6709 6710 6711
  } 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;
6712
    //qDebug("QInfo:0x%"PRIx64" create count(tbname) query, res:%d rows:1", GET_TASKID(pRuntimeEnv), count);
6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725
  } 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
6726
        if (TSDB_COL_IS_UD_COL(pExprInfo[j].base.pColumns->flag)) {
6727 6728 6729 6730 6731 6732 6733
          continue;
        }

        SColumnInfoData* pColInfo = taosArrayGet(pRes->pDataBlock, j);
        type  = pExprInfo[j].base.resSchema.type;
        bytes = pExprInfo[j].base.resSchema.bytes;

6734
        if (pExprInfo[j].base.pColumns->info.colId == TSDB_TBNAME_COLUMN_INDEX) {
6735 6736
          data = tsdbGetTableName(item->pTable);
        } else {
6737
          data = tsdbGetTableTagVal(item->pTable, pExprInfo[j].base.pColumns->info.colId, type, bytes);
6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750
        }

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

6751
    //qDebug("QInfo:0x%"PRIx64" create tag values results completed, rows:%d", GET_TASKID(pRuntimeEnv), count);
6752 6753 6754
  }

  if (pOperator->status == OP_EXEC_DONE) {
6755
    setTaskStatus(pOperator->pRuntimeEnv, TASK_COMPLETED);
6756 6757 6758 6759 6760 6761 6762 6763
  }

  pRes->info.rows = count;
  return (pRes->info.rows == 0)? NULL:pInfo->pRes;

#endif
}

H
Haojun Liao 已提交
6764
SOperatorInfo* createTagScanOperatorInfo(STaskRuntimeEnv* pRuntimeEnv, SExprInfo* pExpr, int32_t numOfOutput) {
wafwerar's avatar
wafwerar 已提交
6765
  STagScanInfo* pInfo = taosMemoryCalloc(1, sizeof(STagScanInfo));
L
Liu Jicong 已提交
6766
  //  pInfo->pRes = createOutputBuf(pExpr, numOfOutput, pResultInfo->capacity);
6767 6768 6769 6770 6771 6772 6773

  size_t numOfGroup = GET_NUM_OF_TABLEGROUP(pRuntimeEnv);
  assert(numOfGroup == 0 || numOfGroup == 1);

  pInfo->totalTables = pRuntimeEnv->tableqinfoGroupInfo.numOfTables;
  pInfo->curPos = 0;

wafwerar's avatar
wafwerar 已提交
6774
  SOperatorInfo* pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
L
Liu Jicong 已提交
6775
  pOperator->name = "SeqTableTagScan";
X
Xiaoyu Wang 已提交
6776
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_TAG_SCAN;
6777
  pOperator->blockingOptr = false;
L
Liu Jicong 已提交
6778 6779
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
H
Haojun Liao 已提交
6780
  pOperator->getNextFn = doTagScan;
L
Liu Jicong 已提交
6781 6782 6783
  pOperator->pExpr = pExpr;
  pOperator->numOfOutput = numOfOutput;
  pOperator->pRuntimeEnv = pRuntimeEnv;
H
Haojun Liao 已提交
6784
  pOperator->closeFn = destroyTagScanOperatorInfo;
6785 6786 6787

  return pOperator;
}
L
Liu Jicong 已提交
6788
static bool initMultiDistinctInfo(SDistinctOperatorInfo* pInfo, SOperatorInfo* pOperator, SSDataBlock* pBlock) {
6789
  if (taosArrayGetSize(pInfo->pDistinctDataInfo) == pOperator->numOfOutput) {
L
Liu Jicong 已提交
6790
    // distinct info already inited
6791 6792 6793
    return true;
  }
  for (int i = 0; i < pOperator->numOfOutput; i++) {
L
Liu Jicong 已提交
6794
    //    pInfo->totalBytes += pOperator->pExpr[i].base.colBytes;
6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807
  }
  for (int i = 0; i < pOperator->numOfOutput; i++) {
    int numOfBlock = (int)(taosArrayGetSize(pBlock->pDataBlock));
    assert(i < numOfBlock);
    for (int j = 0; j < numOfBlock; j++) {
      SColumnInfoData* pColDataInfo = taosArrayGet(pBlock->pDataBlock, j);
      if (pColDataInfo->info.colId == pOperator->pExpr[i].base.resSchema.colId) {
        SDistinctDataInfo item = {.index = j, .type = pColDataInfo->info.type, .bytes = pColDataInfo->info.bytes};
        taosArrayInsert(pInfo->pDistinctDataInfo, i, &item);
      }
    }
  }
  pInfo->totalBytes += (int32_t)strlen(MULTI_KEY_DELIM) * (pOperator->numOfOutput);
L
Liu Jicong 已提交
6808 6809
  pInfo->buf = taosMemoryCalloc(1, pInfo->totalBytes);
  return taosArrayGetSize(pInfo->pDistinctDataInfo) == pOperator->numOfOutput ? true : false;
6810 6811
}

L
Liu Jicong 已提交
6812 6813 6814
static void buildMultiDistinctKey(SDistinctOperatorInfo* pInfo, SSDataBlock* pBlock, int32_t rowId) {
  char* p = pInfo->buf;
  memset(p, 0, pInfo->totalBytes);
6815 6816

  for (int i = 0; i < taosArrayGetSize(pInfo->pDistinctDataInfo); i++) {
L
Liu Jicong 已提交
6817
    SDistinctDataInfo* pDistDataInfo = (SDistinctDataInfo*)taosArrayGet(pInfo->pDistinctDataInfo, i);
6818
    SColumnInfoData*   pColDataInfo = taosArrayGet(pBlock->pDataBlock, pDistDataInfo->index);
L
Liu Jicong 已提交
6819 6820 6821
    char*              val = ((char*)pColDataInfo->pData) + pColDataInfo->info.bytes * rowId;
    if (isNull(val, pDistDataInfo->type)) {
      p += pDistDataInfo->bytes;
6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835
      continue;
    }
    if (IS_VAR_DATA_TYPE(pDistDataInfo->type)) {
      memcpy(p, varDataVal(val), varDataLen(val));
      p += varDataLen(val);
    } else {
      memcpy(p, val, pDistDataInfo->bytes);
      p += pDistDataInfo->bytes;
    }
    memcpy(p, MULTI_KEY_DELIM, strlen(MULTI_KEY_DELIM));
    p += strlen(MULTI_KEY_DELIM);
  }
}

L
Liu Jicong 已提交
6836
static SSDataBlock* hashDistinct(SOperatorInfo* pOperator, bool* newgroup) {
6837 6838 6839 6840 6841
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

  SDistinctOperatorInfo* pInfo = pOperator->info;
L
Liu Jicong 已提交
6842
  SSDataBlock*           pRes = pInfo->pRes;
6843 6844 6845

  pRes->info.rows = 0;
  SSDataBlock* pBlock = NULL;
L
Liu Jicong 已提交
6846

H
Haojun Liao 已提交
6847
  SOperatorInfo* pDownstream = pOperator->pDownstream[0];
L
Liu Jicong 已提交
6848
  while (1) {
H
Haojun Liao 已提交
6849 6850 6851
    publishOperatorProfEvent(pDownstream, QUERY_PROF_BEFORE_OPERATOR_EXEC);
    pBlock = pDownstream->getNextFn(pDownstream, newgroup);
    publishOperatorProfEvent(pDownstream, QUERY_PROF_AFTER_OPERATOR_EXEC);
6852 6853 6854 6855 6856 6857 6858 6859 6860

    if (pBlock == NULL) {
      doSetOperatorCompleted(pOperator);
      break;
    }
    if (!initMultiDistinctInfo(pInfo, pOperator, pBlock)) {
      doSetOperatorCompleted(pOperator);
      break;
    }
H
Haojun Liao 已提交
6861

L
Liu Jicong 已提交
6862
    // ensure result output buf
6863 6864 6865 6866
    if (pRes->info.rows + pBlock->info.rows > pInfo->outputCapacity) {
      int32_t newSize = pRes->info.rows + pBlock->info.rows;
      for (int i = 0; i < taosArrayGetSize(pRes->pDataBlock); i++) {
        SColumnInfoData*   pResultColInfoData = taosArrayGet(pRes->pDataBlock, i);
L
Liu Jicong 已提交
6867 6868
        SDistinctDataInfo* pDistDataInfo = taosArrayGet(pInfo->pDistinctDataInfo, i);
        char*              tmp = taosMemoryRealloc(pResultColInfoData->pData, newSize * pDistDataInfo->bytes);
6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884
        if (tmp == NULL) {
          return NULL;
        } else {
          pResultColInfoData->pData = tmp;
        }
      }
      pInfo->outputCapacity = newSize;
    }

    for (int32_t i = 0; i < pBlock->info.rows; i++) {
      buildMultiDistinctKey(pInfo, pBlock, i);
      if (taosHashGet(pInfo->pSet, pInfo->buf, pInfo->totalBytes) == NULL) {
        int32_t dummy;
        taosHashPut(pInfo->pSet, pInfo->buf, pInfo->totalBytes, &dummy, sizeof(dummy));
        for (int j = 0; j < taosArrayGetSize(pRes->pDataBlock); j++) {
          SDistinctDataInfo* pDistDataInfo = taosArrayGet(pInfo->pDistinctDataInfo, j);  // distinct meta info
L
Liu Jicong 已提交
6885 6886
          SColumnInfoData*   pColInfoData = taosArrayGet(pBlock->pDataBlock, pDistDataInfo->index);  // src
          SColumnInfoData*   pResultColInfoData = taosArrayGet(pRes->pDataBlock, j);                 // dist
6887 6888

          char* val = ((char*)pColInfoData->pData) + pDistDataInfo->bytes * i;
L
Liu Jicong 已提交
6889
          char* start = pResultColInfoData->pData + pDistDataInfo->bytes * pInfo->pRes->info.rows;
6890 6891 6892
          memcpy(start, val, pDistDataInfo->bytes);
        }
        pRes->info.rows += 1;
L
Liu Jicong 已提交
6893
      }
6894 6895 6896 6897 6898 6899
    }

    if (pRes->info.rows >= pInfo->threshold) {
      break;
    }
  }
L
Liu Jicong 已提交
6900
  return (pInfo->pRes->info.rows > 0) ? pInfo->pRes : NULL;
6901 6902
}

H
Haojun Liao 已提交
6903
SOperatorInfo* createDistinctOperatorInfo(SOperatorInfo* downstream, SExprInfo* pExpr, int32_t numOfCols, SSDataBlock* pResBlock, SExecTaskInfo* pTaskInfo) {
wafwerar's avatar
wafwerar 已提交
6904
  SDistinctOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SDistinctOperatorInfo));
H
Haojun Liao 已提交
6905 6906 6907 6908 6909 6910 6911 6912
  SOperatorInfo* pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));

  pOperator->resultInfo.capacity = 4096;  // todo extract function.

  pInfo->totalBytes        = 0;
  pInfo->buf               = NULL;

  pInfo->pDistinctDataInfo = taosArrayInit(numOfCols, sizeof(SDistinctDataInfo));
6913 6914
  pInfo->pSet = taosHashInit(64, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), false, HASH_NO_LOCK);

H
Haojun Liao 已提交
6915 6916 6917 6918 6919 6920 6921 6922 6923
  pOperator->name         = "DistinctOperator";
  pOperator->blockingOptr = true;
  pOperator->status       = OP_NOT_OPENED;
//  pOperator->operatorType = DISTINCT;
  pOperator->pExpr        = pExpr;
  pOperator->numOfOutput  = numOfCols;
  pOperator->info         = pInfo;
  pOperator->getNextFn    = hashDistinct;
  pOperator->closeFn      = destroyDistinctOperatorInfo;
6924

L
Liu Jicong 已提交
6925
  int32_t code = appendDownstream(pOperator, &downstream, 1);
6926 6927 6928
  return pOperator;
}

L
Liu Jicong 已提交
6929
static int32_t getColumnIndexInSource(SQueriedTableInfo* pTableInfo, SExprBasicInfo* pExpr, SColumnInfo* pTagCols) {
6930 6931
  int32_t j = 0;

H
Haojun Liao 已提交
6932 6933
  if (TSDB_COL_IS_TAG(pExpr->pParam[0].pCol->type)) {
    if (pExpr->pParam[0].pCol->colId == TSDB_TBNAME_COLUMN_INDEX) {
6934 6935 6936
      return TSDB_TBNAME_COLUMN_INDEX;
    }

L
Liu Jicong 已提交
6937
    while (j < pTableInfo->numOfTags) {
H
Haojun Liao 已提交
6938
      if (pExpr->pParam[0].pCol->colId == pTagCols[j].colId) {
6939 6940 6941 6942 6943 6944
        return j;
      }

      j += 1;
    }

6945
  } /*else if (TSDB_COL_IS_UD_COL(pExpr->colInfo.flag)) {  // user specified column data
6946 6947 6948 6949 6950 6951 6952 6953 6954
    return TSDB_UD_COLUMN_INDEX;
  } else {
    while (j < pTableInfo->numOfCols) {
      if (pExpr->colInfo.colId == pTableInfo->colList[j].colId) {
        return j;
      }

      j += 1;
    }
6955
  }*/
6956 6957 6958 6959

  return INT32_MIN;  // return a less than TSDB_TBNAME_COLUMN_INDEX value
}

L
Liu Jicong 已提交
6960
bool validateExprColumnInfo(SQueriedTableInfo* pTableInfo, SExprBasicInfo* pExpr, SColumnInfo* pTagCols) {
6961 6962 6963 6964 6965 6966
  int32_t j = getColumnIndexInSource(pTableInfo, pExpr, pTagCols);
  return j != INT32_MIN;
}

static int32_t deserializeColFilterInfo(SColumnFilterInfo* pColFilters, int16_t numOfFilters, char** pMsg) {
  for (int32_t f = 0; f < numOfFilters; ++f) {
L
Liu Jicong 已提交
6967
    SColumnFilterInfo* pFilterMsg = (SColumnFilterInfo*)(*pMsg);
6968

L
Liu Jicong 已提交
6969
    SColumnFilterInfo* pColFilter = &pColFilters[f];
6970 6971 6972 6973 6974 6975 6976
    pColFilter->filterstr = htons(pFilterMsg->filterstr);

    (*pMsg) += sizeof(SColumnFilterInfo);

    if (pColFilter->filterstr) {
      pColFilter->len = htobe64(pFilterMsg->len);

L
Liu Jicong 已提交
6977 6978
      pColFilter->pz =
          (int64_t)taosMemoryCalloc(1, (size_t)(pColFilter->len + 1 * TSDB_NCHAR_SIZE));  // note: null-terminator
6979 6980 6981 6982
      if (pColFilter->pz == 0) {
        return TSDB_CODE_QRY_OUT_OF_MEMORY;
      }

L
Liu Jicong 已提交
6983
      memcpy((void*)pColFilter->pz, (*pMsg), (size_t)pColFilter->len);
6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996
      (*pMsg) += (pColFilter->len + 1);
    } else {
      pColFilter->lowerBndi = htobe64(pFilterMsg->lowerBndi);
      pColFilter->upperBndi = htobe64(pFilterMsg->upperBndi);
    }

    pColFilter->lowerRelOptr = htons(pFilterMsg->lowerRelOptr);
    pColFilter->upperRelOptr = htons(pFilterMsg->upperRelOptr);
  }

  return TSDB_CODE_SUCCESS;
}

L
Liu Jicong 已提交
6997 6998
static SResSchema createResSchema(int32_t type, int32_t bytes, int32_t slotId, int32_t scale, int32_t precision,
                                  const char* name) {
H
Haojun Liao 已提交
6999 7000
  SResSchema s = {0};
  s.scale = scale;
L
Liu Jicong 已提交
7001
  s.type = type;
H
Haojun Liao 已提交
7002 7003
  s.bytes = bytes;
  s.colId = slotId;
H
Haojun Liao 已提交
7004
  s.precision = precision;
H
Haojun Liao 已提交
7005 7006 7007 7008
  strncpy(s.name, name, tListLen(s.name));

  return s;
}
H
Haojun Liao 已提交
7009

H
Haojun Liao 已提交
7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026
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 已提交
7027
SExprInfo* createExprInfo(SNodeList* pNodeList, SNodeList* pGroupKeys, int32_t* numOfExprs) {
H
Haojun Liao 已提交
7028
  int32_t numOfFuncs = LIST_LENGTH(pNodeList);
H
Haojun Liao 已提交
7029 7030 7031 7032
  int32_t numOfGroupKeys = 0;
  if (pGroupKeys != NULL) {
    numOfGroupKeys = LIST_LENGTH(pGroupKeys);
  }
H
Haojun Liao 已提交
7033

H
Haojun Liao 已提交
7034
  *numOfExprs = numOfFuncs + numOfGroupKeys;
wafwerar's avatar
wafwerar 已提交
7035
  SExprInfo* pExprs = taosMemoryCalloc(*numOfExprs, sizeof(SExprInfo));
H
Haojun Liao 已提交
7036

L
Liu Jicong 已提交
7037
  for (int32_t i = 0; i < (*numOfExprs); ++i) {
H
Haojun Liao 已提交
7038 7039 7040 7041 7042 7043
    STargetNode* pTargetNode = NULL;
    if (i < numOfFuncs) {
      pTargetNode = (STargetNode*)nodesListGetNode(pNodeList, i);
    } else {
      pTargetNode = (STargetNode*)nodesListGetNode(pGroupKeys, i - numOfFuncs);
    }
H
Haojun Liao 已提交
7044

H
Haojun Liao 已提交
7045
    SExprInfo* pExp = &pExprs[pTargetNode->slotId];
H
Haojun Liao 已提交
7046

wafwerar's avatar
wafwerar 已提交
7047
    pExp->pExpr = taosMemoryCalloc(1, sizeof(tExprNode));
H
Haojun Liao 已提交
7048
    pExp->pExpr->_function.num = 1;
H
Haojun Liao 已提交
7049
    pExp->pExpr->_function.functionId = -1;
H
Haojun Liao 已提交
7050

H
Haojun Liao 已提交
7051
    // it is a project query, or group by column
H
Haojun Liao 已提交
7052
    if (nodeType(pTargetNode->pExpr) == QUERY_NODE_COLUMN) {
H
Haojun Liao 已提交
7053
      pExp->pExpr->nodeType = QUERY_NODE_COLUMN;
L
Liu Jicong 已提交
7054
      SColumnNode* pColNode = (SColumnNode*)pTargetNode->pExpr;
H
Haojun Liao 已提交
7055

G
Ganlin Zhao 已提交
7056 7057 7058
      pExp->base.pParam = taosMemoryCalloc(1, sizeof(SFunctParam));
      pExp->base.numOfParams = 1;

H
Haojun Liao 已提交
7059 7060
      SDataType* pType = &pColNode->node.resType;
      pExp->base.resSchema = createResSchema(pType->type, pType->bytes, pTargetNode->slotId, pType->scale, pType->precision, pColNode->colName);
H
Haojun Liao 已提交
7061 7062
      pExp->base.pParam[0].pCol = createColumn(pColNode->dataBlockId, pColNode->slotId, pType);
      pExp->base.pParam[0].type = FUNC_PARAM_TYPE_COLUMN;
7063
    } else if (nodeType(pTargetNode->pExpr) == QUERY_NODE_FUNCTION) {
H
Haojun Liao 已提交
7064
      pExp->pExpr->nodeType = QUERY_NODE_FUNCTION;
H
Haojun Liao 已提交
7065 7066 7067
      SFunctionNode* pFuncNode = (SFunctionNode*)pTargetNode->pExpr;

      SDataType* pType = &pFuncNode->node.resType;
L
Liu Jicong 已提交
7068 7069
      pExp->base.resSchema = createResSchema(pType->type, pType->bytes, pTargetNode->slotId, pType->scale,
                                             pType->precision, pFuncNode->node.aliasName);
H
Haojun Liao 已提交
7070

H
Haojun Liao 已提交
7071
      pExp->pExpr->_function.functionId = pFuncNode->funcId;
H
Haojun Liao 已提交
7072
      pExp->pExpr->_function.pFunctNode = pFuncNode;
H
Haojun Liao 已提交
7073
      strncpy(pExp->pExpr->_function.functionName, pFuncNode->functionName, tListLen(pExp->pExpr->_function.functionName));
H
Haojun Liao 已提交
7074 7075 7076

      // TODO: value parameter needs to be handled
      int32_t numOfParam = LIST_LENGTH(pFuncNode->pParameterList);
G
Ganlin Zhao 已提交
7077 7078 7079 7080

      pExp->base.pParam = taosMemoryCalloc(numOfParam, sizeof(SFunctParam));
      pExp->base.numOfParams = numOfParam;

H
Haojun Liao 已提交
7081 7082
      for (int32_t j = 0; j < numOfParam; ++j) {
        SNode*       p1 = nodesListGetNode(pFuncNode->pParameterList, j);
G
Ganlin Zhao 已提交
7083
        if (p1->type == QUERY_NODE_COLUMN) {
H
Haojun Liao 已提交
7084
          SColumnNode* pcn = (SColumnNode*) p1;
G
Ganlin Zhao 已提交
7085 7086

          pExp->base.pParam[j].type = FUNC_PARAM_TYPE_COLUMN;
H
Haojun Liao 已提交
7087
          pExp->base.pParam[j].pCol = createColumn(pcn->dataBlockId, pcn->slotId, &pcn->node.resType);
G
Ganlin Zhao 已提交
7088 7089 7090 7091
        } else if (p1->type == QUERY_NODE_VALUE) {
          SValueNode* pvn = (SValueNode*)p1;
          pExp->base.pParam[j].type = FUNC_PARAM_TYPE_VALUE;
        }
H
Haojun Liao 已提交
7092
      }
7093
    } else if (nodeType(pTargetNode->pExpr) == QUERY_NODE_OPERATOR) {
H
Haojun Liao 已提交
7094
      pExp->pExpr->nodeType = QUERY_NODE_OPERATOR;
L
Liu Jicong 已提交
7095
      SOperatorNode* pNode = (SOperatorNode*)pTargetNode->pExpr;
7096

G
Ganlin Zhao 已提交
7097 7098 7099
      pExp->base.pParam = taosMemoryCalloc(1, sizeof(SFunctParam));
      pExp->base.numOfParams = 1;

7100
      SDataType* pType = &pNode->node.resType;
H
Haojun Liao 已提交
7101
      pExp->base.resSchema = createResSchema(pType->type, pType->bytes, pTargetNode->slotId, pType->scale, pType->precision, pNode->node.aliasName);
7102 7103 7104

      pExp->pExpr->_optrRoot.pRootNode = pTargetNode->pExpr;

H
Haojun Liao 已提交
7105 7106
//      pExp->base.pParam[0].type = FUNC_PARAM_TYPE_COLUMN;
//      pExp->base.pParam[0].pCol = createColumn(pTargetNode->dataBlockId, pTargetNode->slotId, pType);
7107 7108
    } else {
      ASSERT(0);
H
Haojun Liao 已提交
7109 7110 7111
    }
  }

H
Haojun Liao 已提交
7112
  return pExprs;
H
Haojun Liao 已提交
7113 7114
}

7115
static SExecTaskInfo* createExecTaskInfo(uint64_t queryId, uint64_t taskId, EOPTR_EXEC_MODEL model) {
wafwerar's avatar
wafwerar 已提交
7116
  SExecTaskInfo* pTaskInfo = taosMemoryCalloc(1, sizeof(SExecTaskInfo));
7117
  setTaskStatus(pTaskInfo, TASK_NOT_COMPLETED);
H
Haojun Liao 已提交
7118

7119
  pTaskInfo->cost.created = taosGetTimestampMs();
H
Haojun Liao 已提交
7120
  pTaskInfo->id.queryId = queryId;
7121
  pTaskInfo->execModel  = model;
H
Haojun Liao 已提交
7122

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

7127 7128
  return pTaskInfo;
}
H
Haojun Liao 已提交
7129

L
Liu Jicong 已提交
7130 7131
static tsdbReaderT doCreateDataReader(STableScanPhysiNode* pTableScanNode, SReadHandle* pHandle,
                                      STableGroupInfo* pTableGroupInfo, uint64_t queryId, uint64_t taskId);
H
Haojun Liao 已提交
7132

L
Liu Jicong 已提交
7133 7134
static int32_t doCreateTableGroup(void* metaHandle, int32_t tableType, uint64_t tableUid, STableGroupInfo* pGroupInfo,
                                  uint64_t queryId, uint64_t taskId);
7135 7136
static SArray* extractTableIdList(const STableGroupInfo* pTableGroupInfo);
static SArray* extractScanColumnId(SNodeList* pNodeList);
H
Haojun Liao 已提交
7137
static SArray* extractColumnInfo(SNodeList* pNodeList);
H
Haojun Liao 已提交
7138
static SArray* extractColMatchInfo(SNodeList* pNodeList, SDataBlockDescNode* pOutputNodeList, int32_t* numOfOutputCols);
H
Haojun Liao 已提交
7139
static SArray* createSortInfo(SNodeList* pNodeList);
H
Haojun Liao 已提交
7140

H
Haojun Liao 已提交
7141
SOperatorInfo* createOperatorTree(SPhysiNode* pPhyNode, SExecTaskInfo* pTaskInfo, SReadHandle* pHandle,
L
Liu Jicong 已提交
7142
                                        uint64_t queryId, uint64_t taskId, STableGroupInfo* pTableGroupInfo) {
X
Xiaoyu Wang 已提交
7143 7144 7145
  if (pPhyNode->pChildren == NULL || LIST_LENGTH(pPhyNode->pChildren) == 0) {
    if (QUERY_NODE_PHYSICAL_PLAN_TABLE_SCAN == nodeType(pPhyNode)) {
      SScanPhysiNode* pScanPhyNode = (SScanPhysiNode*)pPhyNode;
H
Haojun Liao 已提交
7146

H
Haojun Liao 已提交
7147
      int32_t     numOfCols = 0;
H
Haojun Liao 已提交
7148 7149
      tsdbReaderT pDataReader = doCreateDataReader((STableScanPhysiNode*)pPhyNode, pHandle, pTableGroupInfo, (uint64_t)queryId, taskId);
      SArray* pColList = extractColMatchInfo(pScanPhyNode->pScanCols, pScanPhyNode->node.pOutputDataBlockDesc, &numOfCols);
H
Haojun Liao 已提交
7150

L
Liu Jicong 已提交
7151
      return createTableScanOperatorInfo(pDataReader, pScanPhyNode->order, numOfCols, pScanPhyNode->count,
H
Haojun Liao 已提交
7152
                                         pScanPhyNode->reverse, pColList, pScanPhyNode->node.pConditions, pTaskInfo);
X
Xiaoyu Wang 已提交
7153
    } else if (QUERY_NODE_PHYSICAL_PLAN_EXCHANGE == nodeType(pPhyNode)) {
H
Haojun Liao 已提交
7154
      SExchangePhysiNode* pExchange = (SExchangePhysiNode*)pPhyNode;
L
Liu Jicong 已提交
7155
      SSDataBlock*        pResBlock = createOutputBuf_rv1(pExchange->node.pOutputDataBlockDesc);
H
Haojun Liao 已提交
7156
      return createExchangeOperatorInfo(pExchange->pSrcEndPoints, pResBlock, pTaskInfo);
X
Xiaoyu Wang 已提交
7157
    } else if (QUERY_NODE_PHYSICAL_PLAN_STREAM_SCAN == nodeType(pPhyNode)) {
H
Haojun Liao 已提交
7158
      SScanPhysiNode* pScanPhyNode = (SScanPhysiNode*)pPhyNode;  // simple child table.
7159

L
Liu Jicong 已提交
7160 7161
      int32_t code = doCreateTableGroup(pHandle->meta, pScanPhyNode->tableType, pScanPhyNode->uid, pTableGroupInfo,
                                        queryId, taskId);
H
Haojun Liao 已提交
7162
      SArray* tableIdList = extractTableIdList(pTableGroupInfo);
H
Haojun Liao 已提交
7163

7164
      SSDataBlock* pResBlock = createOutputBuf_rv1(pScanPhyNode->node.pOutputDataBlockDesc);
7165 7166 7167 7168

      int32_t numOfCols = 0;
      SArray* pColList = extractColMatchInfo(pScanPhyNode->pScanCols, pScanPhyNode->node.pOutputDataBlockDesc, &numOfCols);
      SOperatorInfo* pOperator = createStreamScanOperatorInfo(pHandle->reader, pResBlock, pColList, tableIdList, pTaskInfo);
7169
      taosArrayDestroy(tableIdList);
H
Haojun Liao 已提交
7170
      return pOperator;
H
Haojun Liao 已提交
7171
    } else if (QUERY_NODE_PHYSICAL_PLAN_SYSTABLE_SCAN == nodeType(pPhyNode)) {
L
Liu Jicong 已提交
7172 7173
      SSystemTableScanPhysiNode* pSysScanPhyNode = (SSystemTableScanPhysiNode*)pPhyNode;
      SSDataBlock*               pResBlock = createOutputBuf_rv1(pSysScanPhyNode->scan.node.pOutputDataBlockDesc);
H
Haojun Liao 已提交
7174

7175
      struct SScanPhysiNode* pScanNode = &pSysScanPhyNode->scan;
L
Liu Jicong 已提交
7176
      SArray*                colList = extractScanColumnId(pScanNode->pScanCols);
7177

L
Liu Jicong 已提交
7178 7179 7180
      SOperatorInfo* pOperator = createSysTableScanOperatorInfo(
          pHandle->meta, pResBlock, &pScanNode->tableName, pScanNode->node.pConditions, pSysScanPhyNode->mgmtEpSet,
          colList, pTaskInfo, pSysScanPhyNode->showRewrite, pSysScanPhyNode->accountId);
H
Haojun Liao 已提交
7181 7182 7183
      return pOperator;
    } else {
      ASSERT(0);
H
Haojun Liao 已提交
7184 7185 7186
    }
  }

H
Haojun Liao 已提交
7187 7188 7189 7190
  if (QUERY_NODE_PHYSICAL_PLAN_PROJECT == nodeType(pPhyNode)) {
    size_t size = LIST_LENGTH(pPhyNode->pChildren);
    assert(size == 1);

H
Haojun Liao 已提交
7191
    SPhysiNode*    pChildNode = (SPhysiNode*)nodesListGetNode(pPhyNode->pChildren, 0);
H
Haojun Liao 已提交
7192
    SOperatorInfo* op = createOperatorTree(pChildNode, pTaskInfo, pHandle, queryId, taskId, pTableGroupInfo);
H
Haojun Liao 已提交
7193

L
Liu Jicong 已提交
7194
    int32_t      num = 0;
H
Haojun Liao 已提交
7195 7196 7197
    SProjectPhysiNode* pProjPhyNode = (SProjectPhysiNode*) pPhyNode;
    SExprInfo*   pExprInfo = createExprInfo(pProjPhyNode->pProjections, NULL, &num);

H
Haojun Liao 已提交
7198
    SSDataBlock* pResBlock = createOutputBuf_rv1(pPhyNode->pOutputDataBlockDesc);
H
Haojun Liao 已提交
7199 7200 7201
    SLimit limit = {.limit = pProjPhyNode->limit, .offset = pProjPhyNode->offset};

    return createProjectOperatorInfo(op, pExprInfo, num, pResBlock, &limit, pTaskInfo);
H
Haojun Liao 已提交
7202
  } else if (QUERY_NODE_PHYSICAL_PLAN_AGG == nodeType(pPhyNode)) {
X
Xiaoyu Wang 已提交
7203
    size_t size = LIST_LENGTH(pPhyNode->pChildren);
H
Haojun Liao 已提交
7204 7205
    assert(size == 1);

H
Haojun Liao 已提交
7206
    for (int32_t i = 0; i < size; ++i) {
H
Haojun Liao 已提交
7207
      SPhysiNode*    pChildNode = (SPhysiNode*)nodesListGetNode(pPhyNode->pChildren, i);
H
Haojun Liao 已提交
7208
      SOperatorInfo* op = createOperatorTree(pChildNode, pTaskInfo, pHandle, queryId, taskId, pTableGroupInfo);
H
Haojun Liao 已提交
7209

H
Haojun Liao 已提交
7210
      int32_t num = 0;
H
Haojun Liao 已提交
7211 7212

      SAggPhysiNode* pAggNode = (SAggPhysiNode*)pPhyNode;
L
Liu Jicong 已提交
7213 7214
      SExprInfo*     pExprInfo = createExprInfo(pAggNode->pAggFuncs, pAggNode->pGroupKeys, &num);
      SSDataBlock*   pResBlock = createOutputBuf_rv1(pPhyNode->pOutputDataBlockDesc);
H
Haojun Liao 已提交
7215 7216 7217 7218 7219 7220 7221

      if (pAggNode->pGroupKeys != NULL) {
        SArray* pColList = extractColumnInfo(pAggNode->pGroupKeys);
        return createGroupOperatorInfo(op, pExprInfo, num, pResBlock, pColList, pTaskInfo, NULL);
      } else {
        return createAggregateOperatorInfo(op, pExprInfo, num, pResBlock, pTaskInfo, pTableGroupInfo);
      }
H
Haojun Liao 已提交
7222
    }
H
Haojun Liao 已提交
7223 7224 7225 7226 7227 7228
  } else if (QUERY_NODE_PHYSICAL_PLAN_INTERVAL == nodeType(pPhyNode)) {
    size_t size = LIST_LENGTH(pPhyNode->pChildren);
    assert(size == 1);

    for (int32_t i = 0; i < size; ++i) {
      SPhysiNode*    pChildNode = (SPhysiNode*)nodesListGetNode(pPhyNode->pChildren, i);
H
Haojun Liao 已提交
7229
      SOperatorInfo* op = createOperatorTree(pChildNode, pTaskInfo, pHandle, queryId, taskId, pTableGroupInfo);
H
Haojun Liao 已提交
7230

7231 7232
      SIntervalPhysiNode* pIntervalPhyNode = (SIntervalPhysiNode*)pPhyNode;

L
Liu Jicong 已提交
7233 7234 7235
      // todo: set the correct primary timestamp key column
      int32_t      num = 0;
      SExprInfo*   pExprInfo = createExprInfo(pIntervalPhyNode->window.pFuncs, NULL, &num);
H
Haojun Liao 已提交
7236
      SSDataBlock* pResBlock = createOutputBuf_rv1(pPhyNode->pOutputDataBlockDesc);
7237

H
Haojun Liao 已提交
7238 7239
      SInterval interval = {.interval     = pIntervalPhyNode->interval,
                            .sliding      = pIntervalPhyNode->sliding,
H
Haojun Liao 已提交
7240
                            .intervalUnit = pIntervalPhyNode->intervalUnit,
H
Haojun Liao 已提交
7241 7242
                            .slidingUnit  = pIntervalPhyNode->slidingUnit,
                            .offset       = pIntervalPhyNode->offset,
7243
                            .precision    = TSDB_TIME_PRECISION_MILLI};
7244
      return createIntervalOperatorInfo(op, pExprInfo, num, pResBlock, &interval, pTableGroupInfo, pTaskInfo);
H
Haojun Liao 已提交
7245
    }
H
Haojun Liao 已提交
7246 7247 7248 7249
  } else if (QUERY_NODE_PHYSICAL_PLAN_SORT == nodeType(pPhyNode)) {
    size_t size = LIST_LENGTH(pPhyNode->pChildren);
    assert(size == 1);

H
Haojun Liao 已提交
7250
    SPhysiNode*    pChildNode = (SPhysiNode*)nodesListGetNode(pPhyNode->pChildren, 0);
H
Haojun Liao 已提交
7251
    SOperatorInfo* op = createOperatorTree(pChildNode, pTaskInfo, pHandle, queryId, taskId, pTableGroupInfo);
H
Haojun Liao 已提交
7252

H
Haojun Liao 已提交
7253
    SSortPhysiNode* pSortPhyNode = (SSortPhysiNode*)pPhyNode;
H
Haojun Liao 已提交
7254

H
Haojun Liao 已提交
7255 7256
    SSDataBlock* pResBlock = createOutputBuf_rv1(pPhyNode->pOutputDataBlockDesc);
    SArray*      info = createSortInfo(pSortPhyNode->pSortKeys);
H
Haojun Liao 已提交
7257
    return createSortOperatorInfo(op, pResBlock, info, pTaskInfo);
H
Haojun Liao 已提交
7258 7259 7260 7261 7262
  } else if (QUERY_NODE_PHYSICAL_PLAN_SESSION_WINDOW == nodeType(pPhyNode)) {
    size_t size = LIST_LENGTH(pPhyNode->pChildren);
    assert(size == 1);

    SPhysiNode*    pChildNode = (SPhysiNode*)nodesListGetNode(pPhyNode->pChildren, 0);
H
Haojun Liao 已提交
7263
    SOperatorInfo* op = createOperatorTree(pChildNode, pTaskInfo, pHandle, queryId, taskId, pTableGroupInfo);
H
Haojun Liao 已提交
7264 7265 7266 7267 7268 7269 7270

    SSessionWinodwPhysiNode* pSessionNode = (SSessionWinodwPhysiNode*)pPhyNode;

    int32_t      num = 0;
    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 已提交
7271 7272
  } else {
    ASSERT(0);
L
Liu Jicong 已提交
7273 7274 7275 7276 7277 7278
  } /*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 已提交
7279
       SOperatorInfo* op = createOperatorTree(pChildNode, pTaskInfo, pHandle, queryId, taskId, pTableGroupInfo);
L
Liu Jicong 已提交
7280 7281 7282
       return createMultiTableAggOperatorInfo(op, pPhyNode->pTargets, pTaskInfo, pTableGroupInfo);
     }
   }*/
7283
}
H
Haojun Liao 已提交
7284

L
Liu Jicong 已提交
7285 7286
static tsdbReaderT createDataReaderImpl(STableScanPhysiNode* pTableScanNode, STableGroupInfo* pGroupInfo,
                                        void* readHandle, uint64_t queryId, uint64_t taskId) {
H
Haojun Liao 已提交
7287
  STsdbQueryCond cond = {.loadExternalRows = false};
H
Haojun Liao 已提交
7288

L
Liu Jicong 已提交
7289
  cond.order = pTableScanNode->scan.order;
X
Xiaoyu Wang 已提交
7290
  cond.numOfCols = LIST_LENGTH(pTableScanNode->scan.pScanCols);
L
Liu Jicong 已提交
7291
  cond.colList = taosMemoryCalloc(cond.numOfCols, sizeof(SColumnInfo));
H
Haojun Liao 已提交
7292 7293 7294 7295 7296
  if (cond.colList == NULL) {
    terrno = TSDB_CODE_QRY_OUT_OF_MEMORY;
    return NULL;
  }

X
Xiaoyu Wang 已提交
7297
  cond.twindow = pTableScanNode->scanRange;
H
Haojun Liao 已提交
7298
  cond.type = BLOCK_LOAD_OFFSET_SEQ_ORDER;
L
Liu Jicong 已提交
7299
  //  cond.type = pTableScanNode->scanFlag;
H
Haojun Liao 已提交
7300

H
Haojun Liao 已提交
7301
  int32_t j = 0;
H
Haojun Liao 已提交
7302
  for (int32_t i = 0; i < cond.numOfCols; ++i) {
H
Haojun Liao 已提交
7303 7304
    STargetNode* pNode = (STargetNode*)nodesListGetNode(pTableScanNode->scan.pScanCols, i);
    SColumnNode* pColNode = (SColumnNode*)pNode->pExpr;
H
Haojun Liao 已提交
7305 7306 7307
    if (pColNode->colType == COLUMN_TYPE_TAG) {
      continue;
    }
H
Haojun Liao 已提交
7308

L
Liu Jicong 已提交
7309
    cond.colList[j].type = pColNode->node.resType.type;
H
Haojun Liao 已提交
7310 7311 7312
    cond.colList[j].bytes = pColNode->node.resType.bytes;
    cond.colList[j].colId = pColNode->colId;
    j += 1;
H
Haojun Liao 已提交
7313 7314
  }

H
Haojun Liao 已提交
7315
  cond.numOfCols = j;
H
Haojun Liao 已提交
7316
  return tsdbQueryTables(readHandle, &cond, pGroupInfo, queryId, taskId);
H
Haojun Liao 已提交
7317
}
H
Haojun Liao 已提交
7318

7319
SArray* extractScanColumnId(SNodeList* pNodeList) {
L
Liu Jicong 已提交
7320
  size_t  numOfCols = LIST_LENGTH(pNodeList);
7321 7322 7323 7324 7325 7326
  SArray* pList = taosArrayInit(numOfCols, sizeof(int16_t));
  if (pList == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

L
Liu Jicong 已提交
7327
  for (int32_t i = 0; i < numOfCols; ++i) {
X
Xiaoyu Wang 已提交
7328
    for (int32_t j = 0; j < numOfCols; ++j) {
L
Liu Jicong 已提交
7329
      STargetNode* pNode = (STargetNode*)nodesListGetNode(pNodeList, j);
X
Xiaoyu Wang 已提交
7330
      if (pNode->slotId == i) {
L
Liu Jicong 已提交
7331
        SColumnNode* pColNode = (SColumnNode*)pNode->pExpr;
X
Xiaoyu Wang 已提交
7332 7333 7334 7335
        taosArrayPush(pList, &pColNode->colId);
        break;
      }
    }
7336 7337 7338 7339 7340
  }

  return pList;
}

H
Haojun Liao 已提交
7341
SArray* extractColumnInfo(SNodeList* pNodeList) {
L
Liu Jicong 已提交
7342
  size_t  numOfCols = LIST_LENGTH(pNodeList);
H
Haojun Liao 已提交
7343 7344 7345 7346 7347 7348
  SArray* pList = taosArrayInit(numOfCols, sizeof(SColumn));
  if (pList == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

L
Liu Jicong 已提交
7349 7350 7351
  for (int32_t i = 0; i < numOfCols; ++i) {
    STargetNode* pNode = (STargetNode*)nodesListGetNode(pNodeList, i);
    SColumnNode* pColNode = (SColumnNode*)pNode->pExpr;
H
Haojun Liao 已提交
7352 7353 7354

    SColumn c = {0};
    c.slotId = pColNode->slotId;
L
Liu Jicong 已提交
7355 7356 7357 7358 7359
    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;
H
Haojun Liao 已提交
7360 7361 7362 7363 7364 7365 7366

    taosArrayPush(pList, &c);
  }

  return pList;
}

H
Haojun Liao 已提交
7367
SArray* createSortInfo(SNodeList* pNodeList) {
L
Liu Jicong 已提交
7368
  size_t  numOfCols = LIST_LENGTH(pNodeList);
H
Haojun Liao 已提交
7369 7370 7371 7372 7373 7374
  SArray* pList = taosArrayInit(numOfCols, sizeof(SBlockOrderInfo));
  if (pList == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return pList;
  }

L
Liu Jicong 已提交
7375 7376 7377 7378 7379
  for (int32_t i = 0; i < numOfCols; ++i) {
    STargetNode*      pNode = (STargetNode*)nodesListGetNode(pNodeList, i);
    SOrderByExprNode* pSortKey = (SOrderByExprNode*)pNode->pExpr;
    SBlockOrderInfo   bi = {0};
    bi.order = (pSortKey->order == ORDER_ASC) ? TSDB_ORDER_ASC : TSDB_ORDER_DESC;
H
Haojun Liao 已提交
7380 7381 7382 7383
    bi.nullFirst = (pSortKey->nullOrder == NULL_ORDER_FIRST);

    SColumnNode* pColNode = (SColumnNode*)pSortKey->pExpr;
    bi.slotId = pColNode->slotId;
L
Liu Jicong 已提交
7384 7385 7386 7387 7388 7389 7390 7391
    //    pColNode->order;
    //    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;
H
Haojun Liao 已提交
7392 7393 7394 7395 7396 7397 7398

    taosArrayPush(pList, &bi);
  }

  return pList;
}

H
Haojun Liao 已提交
7399
SArray* extractColMatchInfo(SNodeList* pNodeList, SDataBlockDescNode* pOutputNodeList, int32_t* numOfOutputCols) {
L
Liu Jicong 已提交
7400
  size_t  numOfCols = LIST_LENGTH(pNodeList);
H
Haojun Liao 已提交
7401 7402 7403 7404 7405 7406
  SArray* pList = taosArrayInit(numOfCols, sizeof(SColMatchInfo));
  if (pList == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

L
Liu Jicong 已提交
7407 7408 7409
  for (int32_t i = 0; i < numOfCols; ++i) {
    STargetNode* pNode = (STargetNode*)nodesListGetNode(pNodeList, i);
    SColumnNode* pColNode = (SColumnNode*)pNode->pExpr;
H
Haojun Liao 已提交
7410 7411

    SColMatchInfo c = {0};
L
Liu Jicong 已提交
7412
    c.colId = pColNode->colId;
H
Haojun Liao 已提交
7413
    c.targetSlotId = pNode->slotId;
L
Liu Jicong 已提交
7414
    c.output = true;
H
Haojun Liao 已提交
7415 7416 7417
    taosArrayPush(pList, &c);
  }

H
Haojun Liao 已提交
7418 7419 7420
  *numOfOutputCols = 0;

  int32_t num = LIST_LENGTH(pOutputNodeList->pSlots);
L
Liu Jicong 已提交
7421 7422
  for (int32_t i = 0; i < num; ++i) {
    SSlotDescNode* pNode = (SSlotDescNode*)nodesListGetNode(pOutputNodeList->pSlots, i);
H
Haojun Liao 已提交
7423
    SColMatchInfo* info = taosArrayGet(pList, pNode->slotId);
H
Haojun Liao 已提交
7424 7425 7426 7427 7428
    if (pNode->output) {
      (*numOfOutputCols) += 1;
    } else {
      info->output = false;
    }
H
Haojun Liao 已提交
7429 7430
  }

H
Haojun Liao 已提交
7431 7432 7433
  return pList;
}

H
Haojun Liao 已提交
7434
int32_t doCreateTableGroup(void* metaHandle, int32_t tableType, uint64_t tableUid, STableGroupInfo* pGroupInfo, uint64_t queryId, uint64_t taskId) {
7435
  int32_t code = 0;
H
Haojun Liao 已提交
7436
  if (tableType == TSDB_SUPER_TABLE) {
H
Haojun Liao 已提交
7437
    code = tsdbQuerySTableByTagCond(metaHandle, tableUid, 0, NULL, 0, 0, NULL, pGroupInfo, NULL, 0, queryId, taskId);
H
Haojun Liao 已提交
7438
  } else {  // Create one table group.
H
Haojun Liao 已提交
7439
    code = tsdbGetOneTableGroup(metaHandle, tableUid, 0, pGroupInfo);
7440 7441 7442 7443
  }

  return code;
}
H
Haojun Liao 已提交
7444

7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462
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 已提交
7463 7464
tsdbReaderT doCreateDataReader(STableScanPhysiNode* pTableScanNode, SReadHandle* pHandle,
                               STableGroupInfo* pTableGroupInfo, uint64_t queryId, uint64_t taskId) {
7465
  uint64_t uid = pTableScanNode->scan.uid;
L
Liu Jicong 已提交
7466 7467
  int32_t  code =
      doCreateTableGroup(pHandle->meta, pTableScanNode->scan.tableType, uid, pTableGroupInfo, queryId, taskId);
7468 7469
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
H
Haojun Liao 已提交
7470
  }
H
Haojun Liao 已提交
7471

H
Haojun Liao 已提交
7472
  if (pTableGroupInfo->numOfTables == 0) {
H
Haojun Liao 已提交
7473
    code = 0;
L
Liu Jicong 已提交
7474
    qDebug("no table qualified for query, TID:0x%" PRIx64 ", QID:0x%" PRIx64, taskId, queryId);
H
Haojun Liao 已提交
7475 7476
    goto _error;
  }
H
Haojun Liao 已提交
7477

H
Haojun Liao 已提交
7478
  return createDataReaderImpl(pTableScanNode, pTableGroupInfo, pHandle->reader, queryId, taskId);
H
Haojun Liao 已提交
7479

L
Liu Jicong 已提交
7480
_error:
H
Haojun Liao 已提交
7481 7482 7483 7484
  terrno = code;
  return NULL;
}

7485
int32_t createExecTaskInfoImpl(SSubplan* pPlan, SExecTaskInfo** pTaskInfo, SReadHandle* pHandle, uint64_t taskId, EOPTR_EXEC_MODEL model) {
H
Haojun Liao 已提交
7486 7487
  uint64_t queryId = pPlan->id.queryId;

H
Haojun Liao 已提交
7488
  int32_t code = TSDB_CODE_SUCCESS;
7489
  *pTaskInfo = createExecTaskInfo(queryId, taskId, model);
H
Haojun Liao 已提交
7490 7491 7492 7493
  if (*pTaskInfo == NULL) {
    code = TSDB_CODE_QRY_OUT_OF_MEMORY;
    goto _complete;
  }
H
Haojun Liao 已提交
7494

H
Haojun Liao 已提交
7495
  STableGroupInfo group = {0};
H
Haojun Liao 已提交
7496
  (*pTaskInfo)->pRoot = createOperatorTree(pPlan->pNode, *pTaskInfo, pHandle, queryId, taskId, &group);
D
dapan1121 已提交
7497
  if (NULL == (*pTaskInfo)->pRoot) {
L
Liu Jicong 已提交
7498
    code = terrno;
D
dapan1121 已提交
7499 7500
    goto _complete;
  }
H
Haojun Liao 已提交
7501

7502
  if ((*pTaskInfo)->pRoot == NULL) {
H
Haojun Liao 已提交
7503
    code = TSDB_CODE_QRY_OUT_OF_MEMORY;
H
Haojun Liao 已提交
7504
    goto _complete;
7505 7506
  }

H
Haojun Liao 已提交
7507 7508
  return code;

H
Haojun Liao 已提交
7509
_complete:
wafwerar's avatar
wafwerar 已提交
7510
  taosMemoryFreeClear(*pTaskInfo);
H
Haojun Liao 已提交
7511 7512 7513

  terrno = code;
  return code;
H
Haojun Liao 已提交
7514 7515
}

L
Liu Jicong 已提交
7516 7517
static int32_t updateOutputBufForTopBotQuery(SQueriedTableInfo* pTableInfo, SColumnInfo* pTagCols, SExprInfo* pExprs,
                                             int32_t numOfOutput, int32_t tagLen, bool superTable) {
7518 7519 7520 7521 7522 7523 7524 7525 7526
  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 已提交
7527 7528 7529 7530
        //        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);
7531 7532 7533 7534 7535 7536 7537
      }
    }
  }

  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
7538
void setResultBufSize(STaskAttr* pQueryAttr, SResultInfo* pResultInfo) {
7539 7540 7541 7542 7543 7544 7545 7546
  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 已提交
7547 7548 7549 7550 7551 7552 7553 7554 7555 7556
//  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;
//  }
7557 7558

  pResultInfo->threshold = (int32_t)(pResultInfo->capacity * THRESHOLD_RATIO);
H
Haojun Liao 已提交
7559
  pResultInfo->totalRows = 0;
7560 7561
}

L
Liu Jicong 已提交
7562
// TODO refactor
7563
void freeColumnFilterInfo(SColumnFilterInfo* pFilter, int32_t numOfFilters) {
L
Liu Jicong 已提交
7564 7565 7566
  if (pFilter == NULL || numOfFilters == 0) {
    return;
  }
7567

L
Liu Jicong 已提交
7568 7569 7570
  for (int32_t i = 0; i < numOfFilters; i++) {
    if (pFilter[i].filterstr && pFilter[i].pz) {
      taosMemoryFree((void*)(pFilter[i].pz));
7571
    }
L
Liu Jicong 已提交
7572
  }
7573

L
Liu Jicong 已提交
7574
  taosMemoryFree(pFilter);
7575 7576 7577 7578
}

static void doDestroyTableQueryInfo(STableGroupInfo* pTableqinfoGroupInfo) {
  if (pTableqinfoGroupInfo->pGroupList != NULL) {
L
Liu Jicong 已提交
7579
    int32_t numOfGroups = (int32_t)taosArrayGetSize(pTableqinfoGroupInfo->pGroupList);
7580
    for (int32_t i = 0; i < numOfGroups; ++i) {
L
Liu Jicong 已提交
7581
      SArray* p = taosArrayGetP(pTableqinfoGroupInfo->pGroupList, i);
7582 7583

      size_t num = taosArrayGetSize(p);
L
Liu Jicong 已提交
7584
      for (int32_t j = 0; j < num; ++j) {
7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600
        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 已提交
7601
void doDestroyTask(SExecTaskInfo* pTaskInfo) {
H
Haojun Liao 已提交
7602 7603
  qDebug("%s execTask is freed", GET_TASKID(pTaskInfo));

H
Haojun Liao 已提交
7604
  doDestroyTableQueryInfo(&pTaskInfo->tableqinfoGroupInfo);
L
Liu Jicong 已提交
7605 7606
  //  taosArrayDestroy(pTaskInfo->summary.queryProfEvents);
  //  taosHashCleanup(pTaskInfo->summary.operatorProfResults);
7607

wafwerar's avatar
wafwerar 已提交
7608 7609 7610
  taosMemoryFreeClear(pTaskInfo->sql);
  taosMemoryFreeClear(pTaskInfo->id.str);
  taosMemoryFreeClear(pTaskInfo);
7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622
}

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 已提交
7623
      int32_t len = (varDataLen(val) > maxLen) ? maxLen : varDataLen(val);
7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635
      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 已提交
7636 7637
  //  size_t s3 = sizeof(STableCheckInfo);  buffer consumption in tsdb
  return (int64_t)(s1 * 1.5 * numOfTables);
7638 7639 7640 7641 7642 7643 7644
}

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 已提交
7645
    while (1) {
7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671
      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);
}