executorimpl.c 277.8 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 54

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

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

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

H
Haojun Liao 已提交
65

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

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

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

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

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

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

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

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

int32_t getMaximumIdleDurationSec() { return tsShellActivityTimer * 2; }

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

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

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

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

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

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

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

  tw->ekey -= 1;
}

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

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

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

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

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

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

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

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

219
static void destroyOperatorInfo(SOperatorInfo* pOperator);
220
static void destroySysTableScannerOperatorInfo(void* param, int32_t numOfOutput);
221

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

229 230 231
#define OPTR_IS_OPENED(_optr)  (((_optr)->status & OP_OPENED) == OP_OPENED)
#define OPTR_SET_OPENED(_optr) ((_optr)->status |= OP_OPENED)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

H
Haojun Liao 已提交
304
    taosArrayPush(pBlock->pDataBlock, &idata);
H
Haojun Liao 已提交
305
  }
H
Haojun Liao 已提交
306 307

  return pBlock;
H
Haojun Liao 已提交
308 309
}

L
Liu Jicong 已提交
310
static bool isSelectivityWithTagsQuery(SqlFunctionCtx* pCtx, int32_t numOfOutput) {
311
  return true;
L
Liu Jicong 已提交
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
  //  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) {
333 334 335 336 337 338 339 340 341 342
    return false;
  }

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

  return true;
}

H
Haojun Liao 已提交
343
static void prepareResultListBuffer(SResultRowInfo* pResultRowInfo, jmp_buf env) {
344 345
  int64_t newCapacity = 0;

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

wafwerar's avatar
wafwerar 已提交
361
  pResultRowInfo->pPosition = taosMemoryRealloc(pResultRowInfo->pPosition, newCapacity * sizeof(SResultRowPosition));
362 363

  int32_t inc = (int32_t)newCapacity - pResultRowInfo->capacity;
364
  memset(&pResultRowInfo->pPosition[pResultRowInfo->capacity], 0, sizeof(SResultRowPosition));
365 366 367
  pResultRowInfo->capacity = (int32_t)newCapacity;
}

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

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

  // 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 已提交
386
//        existed = (pResultRowInfo->pResult[0] == (*p1));
387 388
      } else {  // check if current pResultRowInfo contains the existed pResultRow
        SET_RES_EXT_WINDOW_KEY(pRuntimeEnv->keyBuf, pData, bytes, uid, pResultRowInfo);
L
Liu Jicong 已提交
389 390
        int64_t* index =
            taosHashGet(pRuntimeEnv->pResultRowListSet, pRuntimeEnv->keyBuf, GET_RES_EXT_WINDOW_KEY_LEN(bytes));
391 392 393 394 395 396 397 398 399 400 401 402 403 404
        if (index != NULL) {
          existed = true;
        } else {
          existed = false;
        }
      }
    }

    return existed;
  }

  return p1 != NULL;
}

H
Haojun Liao 已提交
405
#if 0
H
Haojun Liao 已提交
406
static SResultRow* doSetResultOutBufByKey(STaskRuntimeEnv* pRuntimeEnv, SResultRowInfo* pResultRowInfo, int64_t tid,
407 408 409 410
                                          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 已提交
411 412
  SResultRow** p1 =
      (SResultRow**)taosHashGet(pRuntimeEnv->pResultRowHashTable, pRuntimeEnv->keyBuf, GET_RES_WINDOW_KEY_LEN(bytes));
413 414 415 416

  // 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 已提交
417
      return (p1 != NULL) ? *p1 : NULL;
418 419 420 421 422
    }

    if (p1 != NULL) {
      if (pResultRowInfo->size == 0) {
        existed = false;
H
Haojun Liao 已提交
423
//        assert(pResultRowInfo->curPos == -1);
424
      } else if (pResultRowInfo->size == 1) {
H
Haojun Liao 已提交
425 426
//        existed = (pResultRowInfo->pResult[0] == (*p1));
//        pResultRowInfo->curPos = 0;
427 428
      } else {  // check if current pResultRowInfo contains the existed pResultRow
        SET_RES_EXT_WINDOW_KEY(pRuntimeEnv->keyBuf, pData, bytes, tid, pResultRowInfo);
L
Liu Jicong 已提交
429 430
        int64_t* index =
            taosHashGet(pRuntimeEnv->pResultRowListSet, pRuntimeEnv->keyBuf, GET_RES_EXT_WINDOW_KEY_LEN(bytes));
431
        if (index != NULL) {
H
Haojun Liao 已提交
432
//          pResultRowInfo->curPos = (int32_t)*index;
433 434 435 436 437 438 439 440 441 442 443 444 445 446
          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 已提交
447
    //    prepareResultListBuffer(pResultRowInfo, pRuntimeEnv);
448

L
Liu Jicong 已提交
449
    SResultRow* pResult = NULL;
450 451 452 453 454 455 456 457
    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 已提交
458 459
      taosHashPut(pRuntimeEnv->pResultRowHashTable, pRuntimeEnv->keyBuf, GET_RES_WINDOW_KEY_LEN(bytes), &pResult,
                  POINTER_BYTES);
460 461 462 463 464 465 466 467 468 469 470
      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 已提交
471 472
    taosHashPut(pRuntimeEnv->pResultRowListSet, pRuntimeEnv->keyBuf, GET_RES_EXT_WINDOW_KEY_LEN(bytes), &index,
                POINTER_BYTES);
473 474 475 476 477 478 479 480 481
  }

  // 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 已提交
482
#endif
483

484
SResultRow* getNewResultRow_rv(SDiskbasedBuf* pResultBuf, int64_t tableGroupId, int32_t interBufSize) {
L
Liu Jicong 已提交
485
  SFilePage* pData = NULL;
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 521 522 523

  // 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 已提交
524 525 526
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 已提交
527
  bool existInCurrentResusltRowInfo = false;
528
  SET_RES_WINDOW_KEY(pSup->keyBuf, pData, bytes, tableGroupId);
H
Haojun Liao 已提交
529

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

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

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

H
Haojun Liao 已提交
569 570 571 572 573 574 575 576 577 578
  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 已提交
579

H
Haojun Liao 已提交
580
    prepareResultListBuffer(pResultRowInfo, pTaskInfo->env);
H
Haojun Liao 已提交
581
    if (p1 == NULL) {
582
      pResult = getNewResultRow_rv(pResultBuf, tableGroupId, pSup->resultRowSize);
H
Haojun Liao 已提交
583
      initResultRow(pResult);
H
Haojun Liao 已提交
584 585

      // add a new result set for a new group
H
Haojun Liao 已提交
586 587 588
      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};
589
      taosArrayPush(pSup->pResultRowArrayList, &cell);
H
Haojun Liao 已提交
590
    } else {
H
Haojun Liao 已提交
591
      pResult = getResultRowByPos(pResultBuf, p1);
H
Haojun Liao 已提交
592 593
    }

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

    int64_t index = pResultRowInfo->curPos;
599 600
    SET_RES_EXT_WINDOW_KEY(pSup->keyBuf, pData, bytes, tid, pResultRowInfo);
    taosHashPut(pSup->pResultRowListSet, pSup->keyBuf, GET_RES_EXT_WINDOW_KEY_LEN(bytes), &index, POINTER_BYTES);
C
Cary Xu 已提交
601 602
  } else {
    pResult = getResultRowByPos(pResultBuf, p1);
H
Haojun Liao 已提交
603 604 605 606 607 608 609
  }

  // 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 已提交
610
  return pResult;
H
Haojun Liao 已提交
611 612
}

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

    int64_t key = w->skey;
L
Liu Jicong 已提交
622
    while (key < ts) {  // moving towards end
623
      key = taosTimeAdd(key, pInterval->sliding, pInterval->slidingUnit, precision);
624 625 626 627 628 629 630 631 632 633
      if (key >= ts) {
        break;
      }

      w->skey = key;
    }
  }
}

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

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

  if (w.skey > ts || w.ekey < ts) {
H
Haojun Liao 已提交
646 647 648
    if (pInterval->intervalUnit == 'n' || pInterval->intervalUnit == 'y') {
      w.skey = taosTimeTruncate(ts, pInterval, precision);
      w.ekey = taosTimeAdd(w.skey, pInterval->interval, pInterval->intervalUnit, precision) - 1;
649 650 651 652
    } else {
      int64_t st = w.skey;

      if (st > ts) {
H
Haojun Liao 已提交
653
        st -= ((st - ts + pInterval->sliding - 1) / pInterval->sliding) * pInterval->sliding;
654 655
      }

H
Haojun Liao 已提交
656
      int64_t et = st + pInterval->interval - 1;
657
      if (et < ts) {
H
Haojun Liao 已提交
658
        st += ((ts - et + pInterval->sliding - 1) / pInterval->sliding) * pInterval->sliding;
659 660 661
      }

      w.skey = st;
662
      w.ekey = taosTimeAdd(w.skey, pInterval->interval, pInterval->intervalUnit, precision) - 1;
663 664 665 666 667 668
    }
  }
  return w;
}

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

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

  /*
   * 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 已提交
693
#endif
694 695 696 697 698

  return w;
}

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

L
Liu Jicong 已提交
704
  SFilePage* pData = NULL;
705 706 707 708 709 710

  // 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 已提交
711
    pData = getNewBufPage(pResultBuf, tid, &pageId);
712
    pData->num = sizeof(SFilePage);
713 714
  } else {
    SPageInfo* pi = getLastPageInfo(list);
715
    pData = getBufPage(pResultBuf, getPageId(pi));
716
    pageId = getPageId(pi);
717

718
    if (pData->num + size > getBufPageSize(pResultBuf)) {
719
      // release current page first, and prepare the next one
720
      releaseBufPageInfo(pResultBuf, pi);
721

H
Haojun Liao 已提交
722
      pData = getNewBufPage(pResultBuf, tid, &pageId);
723
      if (pData != NULL) {
724
        pData->num = sizeof(SFilePage);
725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744
      }
    }
  }

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

L
Liu Jicong 已提交
752 753 754
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) {
755
  assert(win->skey <= win->ekey);
L
Liu Jicong 已提交
756
  SDiskbasedBuf* pResultBuf = pRuntimeEnv->pResultBuf;
757

H
Haojun Liao 已提交
758 759
  SResultRow* pResultRow = NULL;//doSetResultOutBufByKey(pRuntimeEnv, pResultRowInfo, tid, (char*)&win->skey, TSDB_KEYSIZE,
//                                                  masterscan, tableGroupId);
760 761 762 763 764 765 766
  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 已提交
767 768
    int32_t ret = addNewWindowResultBuf(pResultRow, pResultBuf, (int32_t)tableGroupId,
                                        pRuntimeEnv->pQueryAttr->intermediateResultRowSize);
769 770 771 772 773 774 775 776 777 778 779 780 781
    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 已提交
782
static void setResultRowOutputBufInitCtx_rv(SResultRow* pResult, SqlFunctionCtx* pCtx, int32_t numOfOutput, int32_t* rowCellInfoOffset);
H
Haojun Liao 已提交
783

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

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

  // set time window for current result
  pResultRow->win = (*win);
  *pResult = pResultRow;
H
Haojun Liao 已提交
800
  setResultRowOutputBufInitCtx_rv(pResultRow, pCtx, numOfOutput, rowCellInfoOffset);
H
Haojun Liao 已提交
801 802 803
  return TSDB_CODE_SUCCESS;
}

804 805 806 807 808
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 已提交
809
    pResult->endInterp = true;
810 811 812 813 814 815 816 817
  }
}

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 已提交
818
    return pResult->endInterp == true;
819 820 821
  }
}

L
Liu Jicong 已提交
822 823
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) {
824 825 826
  int32_t forwardStep = 0;

  if (order == TSDB_ORDER_ASC) {
L
Liu Jicong 已提交
827
    int32_t end = searchFn((char*)&pData[pos], numOfRows - pos, ekey, order);
828 829 830 831 832 833 834 835
    if (end >= 0) {
      forwardStep = end;

      if (pData[end + pos] == ekey) {
        forwardStep += 1;
      }
    }
  } else {
L
Liu Jicong 已提交
836
    int32_t end = searchFn((char*)pData, pos + 1, ekey, order);
837 838 839 840 841 842 843 844 845 846 847 848 849
    if (end >= 0) {
      forwardStep = pos - end;

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

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

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

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

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

L
Liu Jicong 已提交
918 919 920
static int32_t getNumOfRowsInTimeWindow(SDataBlockInfo* pDataBlockInfo, TSKEY* pPrimaryColumn, int32_t startPos,
                                        TSKEY ekey, __block_search_fn_t searchFn, STableQueryInfo* item,
                                        int32_t order) {
921 922
  assert(startPos >= 0 && startPos < pDataBlockInfo->rows);

L
Liu Jicong 已提交
923 924
  int32_t num = -1;
  int32_t step = GET_FORWARD_DIRECTION_FACTOR(order);
925

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

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

956 957 958 959 960
//  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 已提交
961
  colInfoDataEnsureCapacity(pColData, 5);
962 963 964 965 966 967 968 969 970
  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);
}

971
static void updateTimeWindowInfo(SColumnInfoData* pColData, STimeWindow* pWin, bool includeEndpoint) {
972
  int64_t* ts = (int64_t*)pColData->pData;
973
  int32_t delta = includeEndpoint? 1:0;
974

975
  int64_t duration = pWin->ekey - pWin->skey + delta;
976 977
  ts[2] = duration;       // set the duration
  ts[3] = pWin->skey;     // window start key
978
  ts[4] = pWin->ekey + delta; // window end key
979 980
}

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

H
Haojun Liao 已提交
986
    // keep it temporarily
987 988
    bool    hasAgg      = pCtx[k].input.colDataAggIsSet;
    int32_t numOfRows   = pCtx[k].input.numOfRows;
H
Haojun Liao 已提交
989
    int32_t startOffset = pCtx[k].input.startRowIndex;
990

H
Haojun Liao 已提交
991
    int32_t pos = (order == TSDB_ORDER_ASC) ? offset : offset - (forwardStep - 1);
992 993
    pCtx[k].input.startRowIndex = pos;
    pCtx[k].input.numOfRows = forwardStep;
994 995

    if (tsCol != NULL) {
H
Haojun Liao 已提交
996
      pCtx[k].ptsList = tsCol;
997 998 999 1000 1001 1002 1003 1004
    }

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

1005 1006 1007 1008
    if (fmIsWindowPseudoColumnFunc(pCtx[k].functionId)) {
      SResultRowEntryInfo* pEntryInfo = GET_RES_INFO(&pCtx[k]);
      char* p = GET_ROWCELL_INTERBUF(pEntryInfo);

1009 1010 1011 1012 1013 1014 1015 1016
      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);
1017 1018 1019 1020
      pEntryInfo->numOfRes = 1;
      continue;
    }

H
Haojun Liao 已提交
1021
    if (functionNeedToExecute(&pCtx[k])) {
1022
      pCtx[k].fpSet.process(&pCtx[k]);
1023 1024 1025
    }

    // restore it
1026 1027 1028
    pCtx[k].input.colDataAggIsSet = hasAgg;
    pCtx[k].input.startRowIndex = startOffset;
    pCtx[k].input.numOfRows = numOfRows;
1029 1030 1031
  }
}

H
Haojun Liao 已提交
1032 1033 1034
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 已提交
1035
  bool    ascQuery = (order == TSDB_ORDER_ASC);
H
Haojun Liao 已提交
1036

1037
  int32_t precision = pInterval->precision;
H
Haojun Liao 已提交
1038
  getNextTimeWindow(pInterval, precision, order, pNext);
1039 1040

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

L
Liu Jicong 已提交
1046
  TSKEY   startKey = ascQuery ? pNext->skey : pNext->ekey;
1047 1048 1049
  int32_t startPos = 0;

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

  /* interp query with fill should not skip time window */
L
Liu Jicong 已提交
1064 1065 1066
  //  if (pQueryAttr->pointInterpQuery && pQueryAttr->fillType != TSDB_FILL_NONE) {
  //    return startPos;
  //  }
1067 1068 1069 1070 1071 1072

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

  return startPos;
}

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

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

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

  return ts;
}

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

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

L
Liu Jicong 已提交
1164
    setBlockStatisInfo(&pCtx[i], pBlock, NULL /*&pOperator->pExpr[i].base.colInfo*/);
1165 1166 1167
  }
}

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

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

G
Ganlin Zhao 已提交
1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193
    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 已提交
1194

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


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

H
Haojun Liao 已提交
1252
static void setPseudoOutputColInfo(SSDataBlock* pResult, SqlFunctionCtx* pCtx, SArray* pPseudoList) {
1253
  size_t num = (pPseudoList != NULL)? taosArrayGetSize(pPseudoList):0;
H
Haojun Liao 已提交
1254 1255 1256 1257 1258
  for (int32_t i = 0; i < num; ++i) {
    pCtx[i].pOutput = taosArrayGet(pResult->pDataBlock, i);
  }
}

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

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

      pResult->info.rows = pCtx[0].input.numOfRows;
1269 1270 1271
    } else if (pExpr[k].pExpr->nodeType == QUERY_NODE_VALUE) {
      SColumnInfoData* pColInfoData = taosArrayGet(pResult->pDataBlock, k);
      for (int32_t i = 0; i < pSrcBlock->info.rows; ++i) {
1272
        colDataAppend(pColInfoData, i, taosVariantGet(&pExpr[k].base.pParam[0].param, pExpr[k].base.pParam[0].param.nType), TSDB_DATA_TYPE_NULL == pExpr[k].base.pParam[0].param.nType);
1273 1274
      }
      pResult->info.rows = pSrcBlock->info.rows;
H
Haojun Liao 已提交
1275
    } else if (pExpr[k].pExpr->nodeType == QUERY_NODE_OPERATOR) {
1276 1277 1278
      SArray* pBlockList = taosArrayInit(4, POINTER_BYTES);
      taosArrayPush(pBlockList, &pSrcBlock);

1279 1280 1281 1282 1283 1284 1285 1286
      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 已提交
1287
      ASSERT(!fmIsAggFunc(pCtx[k].functionId));
1288

H
Haojun Liao 已提交
1289
      if (fmIsPseudoColumnFunc(pCtx[k].functionId)) {
H
Haojun Liao 已提交
1290
        // do nothing
H
Haojun Liao 已提交
1291
      } else if (fmIsNonstandardSQLFunc(pCtx[k].functionId)) {
H
Haojun Liao 已提交
1292 1293
        // todo set the correct timestamp column
        pCtx[k].input.pPTS = taosArrayGet(pSrcBlock->pDataBlock, 1);
1294

H
Haojun Liao 已提交
1295 1296
        SResultRowEntryInfo *pResInfo = GET_RES_INFO(&pCtx[k]);
        pCtx[k].fpSet.init(&pCtx[k], pResInfo);
1297

H
Haojun Liao 已提交
1298 1299
        pCtx[k].pOutput = taosArrayGet(pResult->pDataBlock, k);
        pCtx[k].offset  = pResult->info.rows;  // set the start offset
G
Ganlin Zhao 已提交
1300

1301 1302 1303 1304
        if (taosArrayGetSize(pPseudoList) > 0) {
          int32_t* outputColIndex = taosArrayGet(pPseudoList, 0);
          pCtx[k].pTsOutput = (SColumnInfoData*)pCtx[*outputColIndex].pOutput;
        }
H
Haojun Liao 已提交
1305

H
Haojun Liao 已提交
1306
        int32_t numOfRows = pCtx[k].fpSet.process(&pCtx[k]);
H
Haojun Liao 已提交
1307
        pResult->info.rows += numOfRows;
H
Haojun Liao 已提交
1308 1309 1310
      } else {
        SArray* pBlockList = taosArrayInit(4, POINTER_BYTES);
        taosArrayPush(pBlockList, &pSrcBlock);
G
Ganlin Zhao 已提交
1311

H
Haojun Liao 已提交
1312 1313
        SScalarParam dest = {0};
        dest.columnData = taosArrayGet(pResult->pDataBlock, k);
G
Ganlin Zhao 已提交
1314

H
Haojun Liao 已提交
1315 1316 1317 1318
        scalarCalculate((SNode*)pExpr[k].pExpr->_function.pFunctNode, pBlockList, &dest);
        pResult->info.rows = dest.numOfRows;
        taosArrayDestroy(pBlockList);
      }
1319
    } else {
1320
      ASSERT(0);
1321 1322 1323 1324 1325 1326
    }
  }
}

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 已提交
1327 1328
  STaskRuntimeEnv* pRuntimeEnv = pOperator->pRuntimeEnv;
  SExprInfo*       pExpr = pOperator->pExpr;
1329

H
Haojun Liao 已提交
1330
  SqlFunctionCtx* pCtx = pInfo->pCtx;
1331 1332 1333 1334 1335 1336 1337 1338

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

L
Liu Jicong 已提交
1343
    //    assert(pColInfo->info.colId == pColIndex->info.colId && curTs != windowKey);
1344 1345 1346
    double v1 = 0, v2 = 0, v = 0;

    if (prevRowIndex == -1) {
L
Liu Jicong 已提交
1347
      GET_TYPED_DATA(v1, double, pColInfo->info.type, (char*)pRuntimeEnv->prevRow[index]);
1348
    } else {
L
Liu Jicong 已提交
1349
      GET_TYPED_DATA(v1, double, pColInfo->info.type, (char*)pColInfo->pData + prevRowIndex * pColInfo->info.bytes);
1350 1351
    }

L
Liu Jicong 已提交
1352
    GET_TYPED_DATA(v2, double, pColInfo->info.type, (char*)pColInfo->pData + curRowIndex * pColInfo->info.bytes);
1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363

    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 已提交
1364
            pCtx[k].start.ptr = (char*)pRuntimeEnv->prevRow[index];
1365
          } else {
L
Liu Jicong 已提交
1366
            pCtx[k].start.ptr = (char*)pColInfo->pData + prevRowIndex * pColInfo->info.bytes;
1367 1368
          }

L
Liu Jicong 已提交
1369
          pCtx[k].end.ptr = (char*)pColInfo->pData + curRowIndex * pColInfo->info.bytes;
1370 1371 1372
        }
      }
    } else if (functionId == FUNCTION_TWA) {
L
Liu Jicong 已提交
1373 1374 1375
      SPoint point1 = (SPoint){.key = prevTs, .val = &v1};
      SPoint point2 = (SPoint){.key = curTs, .val = &v2};
      SPoint point = (SPoint){.key = windowKey, .val = &v};
1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389

      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 已提交
1390
static bool setTimeWindowInterpolationStartTs(SOperatorInfo* pOperatorInfo, SqlFunctionCtx* pCtx, int32_t pos,
H
Haojun Liao 已提交
1391 1392
                                              int32_t numOfRows, SArray* pDataBlock, const TSKEY* tsCols, STimeWindow* win) {
  bool  ascQuery = true;
L
Liu Jicong 已提交
1393
  TSKEY curTs = tsCols[pos];
H
Haojun Liao 已提交
1394
  TSKEY lastTs = 0;//*(TSKEY*)pRuntimeEnv->prevRow[0];
1395 1396 1397

  // 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 已提交
1398
  TSKEY key = ascQuery ? win->skey : win->ekey;
1399 1400 1401 1402 1403 1404 1405 1406 1407 1408
  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 已提交
1409
  int32_t step = 1;//GET_FORWARD_DIRECTION_FACTOR(pQueryAttr->order.order);
L
Liu Jicong 已提交
1410
  TSKEY   prevTs = ((pos == 0 && ascQuery) || (pos == (numOfRows - 1) && !ascQuery)) ? lastTs : tsCols[pos - step];
1411

H
Haojun Liao 已提交
1412
  doTimeWindowInterpolation(pOperatorInfo, pOperatorInfo->info, pDataBlock, prevTs, pos - step, curTs, pos, key, RESULT_ROW_START_INTERP);
1413 1414 1415
  return true;
}

L
Liu Jicong 已提交
1416 1417 1418
static bool setTimeWindowInterpolationEndTs(SOperatorInfo* pOperatorInfo, SqlFunctionCtx* pCtx, int32_t endRowIndex,
                                            SArray* pDataBlock, const TSKEY* tsCols, TSKEY blockEkey,
                                            STimeWindow* win) {
H
Haojun Liao 已提交
1419 1420
  int32_t order = TSDB_ORDER_ASC;
  int32_t numOfOutput = pOperatorInfo->numOfOutput;
1421

L
Liu Jicong 已提交
1422
  TSKEY actualEndKey = tsCols[endRowIndex];
H
Haojun Liao 已提交
1423
  TSKEY key = order ? win->ekey : win->skey;
1424 1425

  // not ended in current data block, do not invoke interpolation
H
Haojun Liao 已提交
1426
  if ((key > blockEkey /*&& QUERY_IS_ASC_QUERY(pQueryAttr)*/) || (key < blockEkey /*&& !QUERY_IS_ASC_QUERY(pQueryAttr)*/)) {
1427 1428 1429 1430 1431 1432 1433 1434 1435 1436
    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 已提交
1437
  int32_t step = GET_FORWARD_DIRECTION_FACTOR(order);
1438 1439 1440 1441 1442
  int32_t nextRowIndex = endRowIndex + step;
  assert(nextRowIndex >= 0);

  TSKEY nextKey = tsCols[nextRowIndex];
  doTimeWindowInterpolation(pOperatorInfo, pOperatorInfo->info, pDataBlock, actualEndKey, endRowIndex, nextKey,
L
Liu Jicong 已提交
1443
                            nextRowIndex, key, RESULT_ROW_END_INTERP);
1444 1445 1446
  return true;
}

H
Haojun Liao 已提交
1447
static void doWindowBorderInterpolation(SOperatorInfo* pOperatorInfo, SSDataBlock* pBlock, SqlFunctionCtx* pCtx,
L
Liu Jicong 已提交
1448 1449
                                        SResultRow* pResult, STimeWindow* win, int32_t startPos, int32_t forwardStep,
                                        int32_t order, bool timeWindowInterpo) {
H
Haojun Liao 已提交
1450
  if (!timeWindowInterpo) {
1451 1452 1453 1454
    return;
  }

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

L
Liu Jicong 已提交
1457 1458
  if (pBlock->pDataBlock == NULL) {
    //    tscError("pBlock->pDataBlock == NULL");
1459 1460
    return;
  }
H
Haojun Liao 已提交
1461

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

L
Liu Jicong 已提交
1464 1465 1466
  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
1467
    int32_t startRowIndex = startPos;
L
Liu Jicong 已提交
1468 1469
    bool    interp = setTimeWindowInterpolationStartTs(pOperatorInfo, pCtx, startRowIndex, pBlock->info.rows,
                                                       pBlock->pDataBlock, tsCols, win);
1470 1471 1472 1473
    if (interp) {
      setResultRowInterpo(pResult, RESULT_ROW_START_INTERP);
    }
  } else {
H
Haojun Liao 已提交
1474
    setNotInterpoWindowKey(pCtx, pOperatorInfo->numOfOutput, RESULT_ROW_START_INTERP);
1475 1476 1477
  }

  // point interpolation does not require the end key time window interpolation.
L
Liu Jicong 已提交
1478 1479 1480
  //  if (pointInterpQuery) {
  //    return;
  //  }
1481 1482 1483 1484 1485 1486

  // 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 已提交
1487 1488 1489
    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);
1490 1491 1492 1493
    if (interp) {
      setResultRowInterpo(pResult, RESULT_ROW_END_INTERP);
    }
  } else {
H
Haojun Liao 已提交
1494
    setNotInterpoWindowKey(pCtx, pOperatorInfo->numOfOutput, RESULT_ROW_END_INTERP);
1495 1496 1497
  }
}

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

H
Haojun Liao 已提交
1501
  SExecTaskInfo* pTaskInfo = pOperatorInfo->pTaskInfo;
L
Liu Jicong 已提交
1502
  int32_t        numOfOutput = pOperatorInfo->numOfOutput;
1503

1504 1505 1506 1507 1508
  SArray* pUpdated = NULL;
  if (pInfo->execModel == OPTR_EXEC_MODEL_STREAM) {
    pUpdated = taosArrayInit(4, sizeof(SResultRowPosition));
  }

H
Haojun Liao 已提交
1509
  int32_t step = 1;
1510
  bool    ascScan = true;
1511 1512 1513 1514 1515

  int32_t prevIndex = pResultRowInfo->curPos;

  TSKEY* tsCols = NULL;
  if (pSDataBlock->pDataBlock != NULL) {
1516
    SColumnInfoData* pColDataInfo = taosArrayGet(pSDataBlock->pDataBlock, pInfo->primaryTsIndex);
L
Liu Jicong 已提交
1517
    tsCols = (int64_t*)pColDataInfo->pData;
H
Haojun Liao 已提交
1518 1519
//    assert(tsCols[0] == pSDataBlock->info.window.skey && tsCols[pSDataBlock->info.rows - 1] ==
//           pSDataBlock->info.window.ekey);
1520 1521
  }

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

H
Haojun Liao 已提交
1525
  STimeWindow win = getActiveTimeWindow(pInfo->aggSup.pResultBuf, pResultRowInfo, ts, &pInfo->interval, pInfo->interval.precision, &pInfo->win);
L
Liu Jicong 已提交
1526
  bool        masterScan = true;
1527 1528

  SResultRow* pResult = NULL;
L
Liu Jicong 已提交
1529 1530 1531
  int32_t     ret = setResultOutputBufByKey_rv(pResultRowInfo, pSDataBlock->info.uid, &win, masterScan, &pResult,
                                               tableGroupId, pInfo->binfo.pCtx, numOfOutput, pInfo->binfo.rowCellInfoOffset,
                                               &pInfo->aggSup, pTaskInfo);
1532
  if (ret != TSDB_CODE_SUCCESS || pResult == NULL) {
H
Haojun Liao 已提交
1533
    longjmp(pTaskInfo->env, TSDB_CODE_QRY_OUT_OF_MEMORY);
1534 1535
  }

1536 1537 1538 1539 1540
  if (pInfo->execModel == OPTR_EXEC_MODEL_STREAM) {
    SResultRowPosition pos = {.pageId = pResult->pageId, .offset = pResult->offset};
    taosArrayPush(pUpdated, &pos);
  }

1541
  int32_t forwardStep = 0;
H
Haojun Liao 已提交
1542
  TSKEY   ekey = win.ekey;
1543
  forwardStep =
H
Haojun Liao 已提交
1544
      getNumOfRowsInTimeWindow(&pSDataBlock->info, tsCols, startPos, ekey, binarySearchForKey, NULL, TSDB_ORDER_ASC);
1545 1546 1547

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

#if 0
H
Haojun Liao 已提交
1550
  if (prevIndex != -1 && prevIndex < curIndex && pInfo->timeWindowInterpo) {
1551 1552 1553
    for (int32_t j = prevIndex; j < curIndex; ++j) {  // previous time window may be all closed already.
      SResultRow* pRes = getResultRow(pResultRowInfo, j);
      if (pRes->closed) {
1554
        assert(resultRowInterpolated(pRes, RESULT_ROW_START_INTERP) && resultRowInterpolated(pRes, RESULT_ROW_END_INTERP));
1555 1556 1557
        continue;
      }

L
Liu Jicong 已提交
1558 1559 1560 1561 1562 1563 1564
      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);
      }
1565

L
Liu Jicong 已提交
1566 1567 1568
      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);
1569

L
Liu Jicong 已提交
1570 1571
      setResultRowInterpo(pResult, RESULT_ROW_END_INTERP);
      setNotInterpoWindowKey(pInfo->binfo.pCtx, pOperatorInfo->numOfOutput, RESULT_ROW_START_INTERP);
1572

1573
      doApplyFunctions(pInfo->binfo.pCtx, &w, &pInfo->timeWindowData, startPos, 0, tsCols, pSDataBlock->info.rows, numOfOutput, TSDB_ORDER_ASC);
L
Liu Jicong 已提交
1574
    }
1575 1576

    // restore current time window
L
Liu Jicong 已提交
1577 1578 1579
    ret = setResultOutputBufByKey_rv(pResultRowInfo, pSDataBlock->info.uid, &win, masterScan, &pResult, tableGroupId,
                                     pInfo->binfo.pCtx, numOfOutput, pInfo->binfo.rowCellInfoOffset, &pInfo->aggSup,
                                     pTaskInfo);
1580
    if (ret != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
1581
      longjmp(pTaskInfo->env, TSDB_CODE_QRY_OUT_OF_MEMORY);
1582 1583
    }
  }
H
Haojun Liao 已提交
1584
#endif
1585 1586

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

  updateTimeWindowInfo(&pInfo->timeWindowData, &win, true);
1590
  doApplyFunctions(pInfo->binfo.pCtx, &win, &pInfo->timeWindowData, startPos, forwardStep, tsCols, pSDataBlock->info.rows, numOfOutput, TSDB_ORDER_ASC);
1591 1592 1593 1594

  STimeWindow nextWin = win;
  while (1) {
    int32_t prevEndPos = (forwardStep - 1) * step + startPos;
H
Haojun Liao 已提交
1595
    startPos = getNextQualifiedWindow(&pInfo->interval, &nextWin, &pSDataBlock->info, tsCols, prevEndPos, pInfo);
1596 1597 1598 1599 1600
    if (startPos < 0) {
      break;
    }

    // null data, failed to allocate more memory buffer
L
Liu Jicong 已提交
1601 1602 1603
    int32_t code = setResultOutputBufByKey_rv(pResultRowInfo, pSDataBlock->info.uid, &nextWin, masterScan, &pResult,
                                              tableGroupId, pInfo->binfo.pCtx, numOfOutput,
                                              pInfo->binfo.rowCellInfoOffset, &pInfo->aggSup, pTaskInfo);
1604
    if (code != TSDB_CODE_SUCCESS || pResult == NULL) {
H
Haojun Liao 已提交
1605
      longjmp(pTaskInfo->env, TSDB_CODE_QRY_OUT_OF_MEMORY);
1606 1607
    }

1608 1609 1610 1611 1612
    if (pInfo->execModel == OPTR_EXEC_MODEL_STREAM) {
      SResultRowPosition pos = {.pageId = pResult->pageId, .offset = pResult->offset};
      taosArrayPush(pUpdated, &pos);
    }

L
Liu Jicong 已提交
1613 1614 1615
    ekey = nextWin.ekey;  // reviseWindowEkey(pQueryAttr, &nextWin);
    forwardStep =
        getNumOfRowsInTimeWindow(&pSDataBlock->info, tsCols, startPos, ekey, binarySearchForKey, NULL, TSDB_ORDER_ASC);
1616 1617

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

H
Haojun Liao 已提交
1621
    updateTimeWindowInfo(&pInfo->timeWindowData, &nextWin, true);
1622
    doApplyFunctions(pInfo->binfo.pCtx, &nextWin, &pInfo->timeWindowData, startPos, forwardStep, tsCols, pSDataBlock->info.rows, numOfOutput, TSDB_ORDER_ASC);
1623 1624
  }

H
Haojun Liao 已提交
1625
  if (pInfo->timeWindowInterpo) {
1626
    int32_t rowIndex = ascScan ? (pSDataBlock->info.rows - 1) : 0;
H
Haojun Liao 已提交
1627
    saveDataBlockLastRow(pInfo->pRow, pSDataBlock->pDataBlock, rowIndex, pSDataBlock->info.numOfCols);
1628 1629
  }

1630
  return pUpdated;
L
Liu Jicong 已提交
1631
  //  updateResultRowInfoActiveIndex(pResultRowInfo, &pInfo->win, pRuntimeEnv->current->lastKey, true, false);
1632 1633
}

L
Liu Jicong 已提交
1634 1635 1636
static void hashAllIntervalAgg(SOperatorInfo* pOperatorInfo, SResultRowInfo* pResultRowInfo, SSDataBlock* pSDataBlock,
                               int32_t tableGroupId) {
  STableIntervalOperatorInfo* pInfo = (STableIntervalOperatorInfo*)pOperatorInfo->info;
1637

H
Haojun Liao 已提交
1638
  STaskRuntimeEnv* pRuntimeEnv = pOperatorInfo->pRuntimeEnv;
L
Liu Jicong 已提交
1639
  int32_t          numOfOutput = pOperatorInfo->numOfOutput;
1640

H
Haojun Liao 已提交
1641 1642
  int32_t step = 1;//GET_FORWARD_DIRECTION_FACTOR(pQueryAttr->order.order);
  bool    ascQuery = true;
1643 1644 1645 1646

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

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

H
Haojun Liao 已提交
1655
  STimeWindow win = {0};//getCurrentActiveTimeWindow(pResultRowInfo, ts, pQueryAttr);
L
Liu Jicong 已提交
1656
  bool        masterScan = IS_MAIN_SCAN(pRuntimeEnv);
1657 1658

  SResultRow* pResult = NULL;
L
Liu Jicong 已提交
1659 1660
  int32_t     forwardStep = 0;
  int32_t     ret = 0;
1661 1662 1663 1664 1665
  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 已提交
1666
                                  tableGroupId, pInfo->binfo.pCtx, numOfOutput, pInfo->binfo.rowCellInfoOffset);
1667 1668 1669 1670
    if (ret != TSDB_CODE_SUCCESS) {
      longjmp(pRuntimeEnv->env, TSDB_CODE_QRY_OUT_OF_MEMORY);
    }

H
Haojun Liao 已提交
1671
    TSKEY ekey = 0;//reviseWindowEkey(pQueryAttr, &win);
L
Liu Jicong 已提交
1672 1673
    //    forwardStep = getNumOfRowsInTimeWindow(pRuntimeEnv, &pSDataBlock->info, tsCols, startPos, ekey,
    //    binarySearchForKey, true);
1674 1675

    // window start(end) key interpolation
L
Liu Jicong 已提交
1676 1677 1678
    //    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);
1679 1680 1681
    preWin = win;

    int32_t prevEndPos = (forwardStep - 1) * step + startPos;
L
Liu Jicong 已提交
1682 1683
    //    startPos = getNextQualifiedWindow(pQueryAttr, &win, &pSDataBlock->info, tsCols, binarySearchForKey,
    //    prevEndPos);
1684
    if (startPos < 0) {
H
Haojun Liao 已提交
1685 1686 1687 1688 1689 1690 1691 1692 1693
//      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;
1694 1695

        // window start(end) key interpolation
L
Liu Jicong 已提交
1696 1697 1698
        //        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 已提交
1699
//      }
1700 1701 1702 1703 1704 1705

      break;
    }
    setResultRowInterpo(pResult, RESULT_ROW_END_INTERP);
  }

H
Haojun Liao 已提交
1706 1707
//  if (pQueryAttr->timeWindowInterpo) {
//    int32_t rowIndex = ascQuery ? (pSDataBlock->info.rows - 1) : 0;
L
Liu Jicong 已提交
1708
    //    saveDataBlockLastRow(pRuntimeEnv, &pSDataBlock->info, pSDataBlock->pDataBlock, rowIndex);
H
Haojun Liao 已提交
1709
//  }
1710

L
Liu Jicong 已提交
1711
  //  updateResultRowInfoActiveIndex(pResultRowInfo, pQueryAttr, pRuntimeEnv->current->lastKey);
1712 1713
}

1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725
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];
}

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

1730
  SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, 0);
1731

1732 1733 1734
  bool    masterScan = true;
  int32_t numOfOutput = pOperator->numOfOutput;
  int64_t gid = pBlock->info.groupId;
1735

H
Haojun Liao 已提交
1736
  int64_t gap = pInfo->gap;
1737
  pInfo->numOfRows = 0;
1738
  if (!pInfo->reptScan) {
1739
    pInfo->reptScan = true;
1740
    pInfo->prevTs   = INT64_MIN;
1741 1742
  }

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

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

1761
      pInfo->curWindow.ekey = pInfo->curWindow.skey;
L
Liu Jicong 已提交
1762
      int32_t ret = setResultOutputBufByKey_rv(&pInfo->binfo.resultRowInfo, pBlock->info.uid, &window, masterScan,
1763
                                               &pResult, gid, pInfo->binfo.pCtx, numOfOutput, pInfo->binfo.rowCellInfoOffset, &pInfo->aggSup, pTaskInfo);
1764
      if (ret != TSDB_CODE_SUCCESS) {  // null data, too many state code
1765
        longjmp(pTaskInfo->env, TSDB_CODE_QRY_APP_ERROR);
1766 1767
      }

1768
      // pInfo->numOfRows data belong to the current session window
1769 1770
      updateTimeWindowInfo(&pInfo->timeWindowData, &window, false);
      doApplyFunctions(pInfo->binfo.pCtx, &window, &pInfo->timeWindowData, pInfo->start, pInfo->numOfRows, NULL, pBlock->info.rows, numOfOutput, TSDB_ORDER_ASC);
1771

1772 1773 1774
      // here we start a new session window
      doKeepSessionStartInfo(pInfo, tsList, j);
      doKeepTuple(pInfo, tsList[j]);
1775 1776 1777 1778
    }
  }

  SResultRow* pResult = NULL;
1779 1780 1781
  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);
1782
  if (ret != TSDB_CODE_SUCCESS) {  // null data, too many state code
1783
    longjmp(pTaskInfo->env, TSDB_CODE_QRY_APP_ERROR);
1784 1785
  }

1786 1787
  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);
1788 1789 1790 1791 1792
}

static void setResultRowKey(SResultRow* pResultRow, char* pData, int16_t type) {
  if (IS_VAR_DATA_TYPE(type)) {
    if (pResultRow->key == NULL) {
wafwerar's avatar
wafwerar 已提交
1793
      pResultRow->key = taosMemoryMalloc(varDataTLen(pData));
1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806
      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 已提交
1807
int32_t setGroupResultOutputBuf_rv(SOptrBasicInfo* binfo, int32_t numOfCols, char* pData, int16_t type,
L
Liu Jicong 已提交
1808 1809 1810 1811
                                          int16_t bytes, int32_t groupId, SDiskbasedBuf* pBuf, SExecTaskInfo* pTaskInfo,
                                          SAggSupporter* pAggSup) {
  SResultRowInfo* pResultRowInfo = &binfo->resultRowInfo;
  SqlFunctionCtx* pCtx = binfo->pCtx;
1812

L
Liu Jicong 已提交
1813
  SResultRow* pResultRow = doSetResultOutBufByKey_rv(pBuf, pResultRowInfo, groupId, (char*)pData, bytes, true, groupId,
H
Haojun Liao 已提交
1814
                                                     pTaskInfo, false, pAggSup);
L
Liu Jicong 已提交
1815
  assert(pResultRow != NULL);
1816 1817

  setResultRowKey(pResultRow, pData, type);
H
Haojun Liao 已提交
1818
  setResultRowOutputBufInitCtx_rv(pResultRow, pCtx, numOfCols, binfo->rowCellInfoOffset);
1819 1820 1821
  return TSDB_CODE_SUCCESS;
}

L
Liu Jicong 已提交
1822 1823
static bool functionNeedToExecute(SqlFunctionCtx* pCtx) {
  struct SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
1824 1825 1826

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

1831
  if (isRowEntryCompleted(pResInfo)) {
1832 1833 1834 1835
    return false;
  }

  if (functionId == FUNCTION_FIRST_DST || functionId == FUNCTION_FIRST) {
L
Liu Jicong 已提交
1836
    //    return QUERY_IS_ASC_QUERY(pQueryAttr);
1837 1838 1839 1840
  }

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

  // in the reverse table scan, only the following functions need to be executed
L
Liu Jicong 已提交
1845 1846 1847 1848
  //  if (IS_REVERSE_SCAN(pRuntimeEnv) ||
  //      (pRuntimeEnv->scanFlag == REPEAT_SCAN && functionId != FUNCTION_STDDEV && functionId != FUNCTION_PERCT)) {
  //    return false;
  //  }
1849 1850 1851 1852

  return true;
}

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

H
Haojun Liao 已提交
1856 1857
  if (pSDataBlock->pBlockAgg != NULL && TSDB_COL_IS_NORMAL_COL(pColumn->flag)) {
    pAgg = &pSDataBlock->pBlockAgg[pCtx->columnIndex];
1858 1859

    pCtx->agg = *pAgg;
L
Liu Jicong 已提交
1860
    pCtx->isAggSet = true;
1861 1862 1863 1864 1865
    assert(pCtx->agg.numOfNull <= pSDataBlock->info.rows);
  } else {
    pCtx->isAggSet = false;
  }

H
Haojun Liao 已提交
1866
  pCtx->hasNull = hasNull(pColumn, pAgg);
1867 1868

  // set the statistics data for primary time stamp column
H
Haojun Liao 已提交
1869
  if (pCtx->functionId == FUNCTION_SPREAD && pColumn->colId == PRIMARYKEY_TIMESTAMP_COL_ID) {
L
Liu Jicong 已提交
1870
    pCtx->isAggSet = true;
1871 1872 1873 1874 1875 1876
    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 已提交
1877
static int32_t setCtxTagColumnInfo(SqlFunctionCtx* pCtx, int32_t numOfOutput) {
1878 1879 1880 1881 1882 1883 1884
  if (!isSelectivityWithTagsQuery(pCtx, numOfOutput)) {
    return TSDB_CODE_SUCCESS;
  }

  int32_t num = 0;
  int16_t tagLen = 0;

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

  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
1918
static SqlFunctionCtx* createSqlFunctionCtx_rv(SExprInfo* pExprInfo, int32_t numOfOutput, int32_t** rowCellInfoOffset) {
L
Liu Jicong 已提交
1919
  SqlFunctionCtx* pFuncCtx = (SqlFunctionCtx*)taosMemoryCalloc(numOfOutput, sizeof(SqlFunctionCtx));
H
Haojun Liao 已提交
1920 1921 1922 1923
  if (pFuncCtx == NULL) {
    return NULL;
  }

wafwerar's avatar
wafwerar 已提交
1924
  *rowCellInfoOffset = taosMemoryCalloc(numOfOutput, sizeof(int32_t));
H
Haojun Liao 已提交
1925
  if (*rowCellInfoOffset == 0) {
wafwerar's avatar
wafwerar 已提交
1926
    taosMemoryFreeClear(pFuncCtx);
H
Haojun Liao 已提交
1927 1928 1929 1930
    return NULL;
  }

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

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

1936
    pCtx->functionId = -1;
H
Haojun Liao 已提交
1937
    if (pExpr->pExpr->nodeType == QUERY_NODE_FUNCTION) {
H
Haojun Liao 已提交
1938
      SFuncExecEnv env = {0};
H
Haojun Liao 已提交
1939 1940
      pCtx->functionId = pExpr->pExpr->_function.pFunctNode->funcId;

H
Haojun Liao 已提交
1941
      if (fmIsAggFunc(pCtx->functionId) || fmIsNonstandardSQLFunc(pCtx->functionId)) {
1942 1943 1944 1945
        fmGetFuncExecFuncs(pCtx->functionId, &pCtx->fpSet);
        pCtx->fpSet.getEnv(pExpr->pExpr->_function.pFunctNode, &env);
      } else {
        fmGetScalarFuncExecFuncs(pCtx->functionId, &pCtx->sfp);
1946 1947 1948
        if (pCtx->sfp.getEnv != NULL) {
          pCtx->sfp.getEnv(pExpr->pExpr->_function.pFunctNode, &env);
        }
1949
      }
H
Haojun Liao 已提交
1950
      pCtx->resDataInfo.interBufSize = env.calcMemSize;
D
dapan1121 已提交
1951
    } else if (pExpr->pExpr->nodeType == QUERY_NODE_COLUMN || pExpr->pExpr->nodeType == QUERY_NODE_OPERATOR || pExpr->pExpr->nodeType == QUERY_NODE_VALUE) {
H
Haojun Liao 已提交
1952
      pCtx->resDataInfo.interBufSize = pFunct->resSchema.bytes; // for simple column, the intermediate buffer needs to hold one element.
H
Haojun Liao 已提交
1953
    }
H
Haojun Liao 已提交
1954

H
Haojun Liao 已提交
1955
    pCtx->input.numOfInputCols = pFunct->numOfParams;
wafwerar's avatar
wafwerar 已提交
1956 1957
    pCtx->input.pData = taosMemoryCalloc(pFunct->numOfParams, POINTER_BYTES);
    pCtx->input.pColumnDataAgg = taosMemoryCalloc(pFunct->numOfParams, POINTER_BYTES);
H
Haojun Liao 已提交
1958

H
Haojun Liao 已提交
1959
    pCtx->pTsOutput         = NULL;//taosArrayInit(4, POINTER_BYTES);
L
Liu Jicong 已提交
1960
    pCtx->resDataInfo.bytes = pFunct->resSchema.bytes;
H
Haojun Liao 已提交
1961 1962
    pCtx->resDataInfo.type  = pFunct->resSchema.type;
    pCtx->order             = TSDB_ORDER_ASC;
L
Liu Jicong 已提交
1963
    pCtx->start.key = INT64_MIN;
H
Haojun Liao 已提交
1964
    pCtx->end.key   = INT64_MIN;
H
Haojun Liao 已提交
1965
#if 0
H
Haojun Liao 已提交
1966
    for (int32_t j = 0; j < pCtx->numOfParams; ++j) {
H
Haojun Liao 已提交
1967 1968
//      int16_t type = pFunct->param[j].nType;
//      int16_t bytes = pFunct->param[j].nLen;
H
Haojun Liao 已提交
1969

H
Haojun Liao 已提交
1970 1971 1972 1973 1974
//      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 已提交
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 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010
    }

    // 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 已提交
2011
#endif
H
Haojun Liao 已提交
2012 2013
  }

L
Liu Jicong 已提交
2014 2015 2016
  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 已提交
2017
  }
H
Haojun Liao 已提交
2018 2019 2020 2021 2022

  setCtxTagColumnInfo(pFuncCtx, numOfOutput);
  return pFuncCtx;
}

2023
static void* destroySqlFunctionCtx(SqlFunctionCtx* pCtx, int32_t numOfOutput) {
2024 2025 2026 2027 2028 2029 2030 2031 2032 2033
  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 已提交
2034
    taosMemoryFreeClear(pCtx[i].subsidiaryRes.pCtx);
2035 2036
  }

wafwerar's avatar
wafwerar 已提交
2037
  taosMemoryFreeClear(pCtx);
2038 2039 2040
  return NULL;
}

H
Haojun Liao 已提交
2041 2042
static void doFreeQueryHandle(STaskRuntimeEnv* pRuntimeEnv) {
  STaskAttr* pQueryAttr = pRuntimeEnv->pQueryAttr;
2043

L
Liu Jicong 已提交
2044
  //  tsdbCleanupReadHandle(pRuntimeEnv->pTsdbReadHandle);
2045
  pRuntimeEnv->pTsdbReadHandle = NULL;
2046

L
Liu Jicong 已提交
2047 2048
  //  SMemRef* pMemRef = &pQueryAttr->memRef;
  //  assert(pMemRef->ref == 0 && pMemRef->snapshot.imem == NULL && pMemRef->snapshot.mem == NULL);
2049 2050
}

L
Liu Jicong 已提交
2051 2052 2053
static void destroyTsComp(STaskRuntimeEnv* pRuntimeEnv, STaskAttr* pQueryAttr) {
  if (pQueryAttr->tsCompQuery && pRuntimeEnv->outputBuf && pRuntimeEnv->outputBuf->pDataBlock &&
      taosArrayGetSize(pRuntimeEnv->outputBuf->pDataBlock) > 0) {
2054 2055
    SColumnInfoData* pColInfoData = taosArrayGet(pRuntimeEnv->outputBuf->pDataBlock, 0);
    if (pColInfoData) {
L
Liu Jicong 已提交
2056
      TdFilePtr pFile = *(TdFilePtr*)pColInfoData->pData;  // TODO refactor
2057 2058
      if (pFile != NULL) {
        taosCloseFile(&pFile);
L
Liu Jicong 已提交
2059
        *(TdFilePtr*)pColInfoData->pData = NULL;
2060 2061 2062 2063 2064
      }
    }
  }
}

L
Liu Jicong 已提交
2065
bool isTaskKilled(SExecTaskInfo* pTaskInfo) {
2066 2067
  // query has been executed more than tsShellActivityTimer, and the retrieve has not arrived
  // abort current query execution.
L
Liu Jicong 已提交
2068 2069
  if (pTaskInfo->owner != 0 &&
      ((taosGetTimestampSec() - pTaskInfo->cost.start / 1000) > 10 * getMaximumIdleDurationSec())
2070 2071
      /*(!needBuildResAfterQueryComplete(pTaskInfo))*/) {
    assert(pTaskInfo->cost.start != 0);
L
Liu Jicong 已提交
2072 2073 2074
    //    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;
2075 2076 2077 2078 2079
  }

  return false;
}

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

L
Liu Jicong 已提交
2082
static bool isCachedLastQuery(STaskAttr* pQueryAttr) {
2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111
  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 已提交
2112 2113 2114
// todo refactor : return window
void getAlignQueryTimeWindow(SInterval* pInterval, int32_t precision, int64_t key, int64_t keyFirst, int64_t keyLast,
                             STimeWindow* win) {
2115
  ASSERT(key >= keyFirst && key <= keyLast);
H
Haojun Liao 已提交
2116
  win->skey = taosTimeTruncate(key, pInterval, precision);
2117 2118

  /*
H
Haojun Liao 已提交
2119
   * if the realSkey > INT64_MAX - pInterval->interval, the query duration between
2120 2121
   * realSkey and realEkey must be less than one interval.Therefore, no need to adjust the query ranges.
   */
H
Haojun Liao 已提交
2122 2123
  if (keyFirst > (INT64_MAX - pInterval->interval)) {
    assert(keyLast - keyFirst < pInterval->interval);
2124 2125
    win->ekey = INT64_MAX;
  } else {
2126
    win->ekey = taosTimeAdd(win->skey, pInterval->interval, pInterval->intervalUnit, precision) - 1;
2127 2128 2129
  }
}

L
Liu Jicong 已提交
2130
static int32_t updateBlockLoadStatus(STaskAttr* pQuery, int32_t status) {
2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153
  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 已提交
2154
    if (!hasOtherFunc) {
2155 2156 2157 2158 2159 2160 2161 2162 2163
      return BLK_DATA_DISCARD;
    } else {
      return BLK_DATA_ALL_NEEDED;
    }
  }

  return status;
}

H
Haojun Liao 已提交
2164
static void doUpdateLastKey(STaskAttr* pQueryAttr) {
2165 2166 2167
  STimeWindow* win = &pQueryAttr->window;

  size_t num = taosArrayGetSize(pQueryAttr->tableGroupInfo.pGroupList);
L
Liu Jicong 已提交
2168
  for (int32_t i = 0; i < num; ++i) {
2169 2170 2171
    SArray* p1 = taosArrayGetP(pQueryAttr->tableGroupInfo.pGroupList, i);

    size_t len = taosArrayGetSize(p1);
L
Liu Jicong 已提交
2172 2173 2174 2175 2176 2177 2178
    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;
      //      }
2179 2180 2181 2182
    }
  }
}

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

H
Haojun Liao 已提交
2284 2285
static void getIntermediateBufInfo(STaskRuntimeEnv* pRuntimeEnv, int32_t* ps, int32_t* rowsize) {
  STaskAttr* pQueryAttr = pRuntimeEnv->pQueryAttr;
L
Liu Jicong 已提交
2286
  int32_t    MIN_ROWS_PER_PAGE = 4;
2287

L
Liu Jicong 已提交
2288 2289
  *rowsize = (int32_t)(pQueryAttr->resultRowSize *
                       getRowNumForMultioutput(pQueryAttr, pQueryAttr->topBotQuery, pQueryAttr->stableQuery));
2290 2291 2292 2293
  int32_t overhead = sizeof(SFilePage);

  // one page contains at least two rows
  *ps = DEFAULT_INTERN_BUF_PAGE_SIZE;
L
Liu Jicong 已提交
2294
  while (((*rowsize) * MIN_ROWS_PER_PAGE) > (*ps) - overhead) {
2295 2296 2297 2298 2299 2300
    *ps = ((*ps) << 1u);
  }
}

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

L
Liu Jicong 已提交
2301 2302 2303
// static FORCE_INLINE bool doFilterByBlockStatistics(STaskRuntimeEnv* pRuntimeEnv, SDataStatis *pDataStatis,
// SqlFunctionCtx *pCtx, int32_t numOfRows) {
//   STaskAttr* pQueryAttr = pRuntimeEnv->pQueryAttr;
2304
//
L
Liu Jicong 已提交
2305 2306 2307
//   if (pDataStatis == NULL || pQueryAttr->pFilters == NULL) {
//     return true;
//   }
2308
//
L
Liu Jicong 已提交
2309 2310
//   return filterRangeExecute(pQueryAttr->pFilters, pDataStatis, pQueryAttr->numOfCols, numOfRows);
// }
2311

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

dengyihao's avatar
dengyihao 已提交
2315 2316
  TSKEY sk = TMIN(pQueryAttr->window.skey, pQueryAttr->window.ekey);
  TSKEY ek = TMAX(pQueryAttr->window.skey, pQueryAttr->window.ekey);
2317 2318

  if (QUERY_IS_ASC_QUERY(pQueryAttr)) {
L
Liu Jicong 已提交
2319
    //    getAlignQueryTimeWindow(pQueryAttr, pBlockInfo->window.skey, sk, ek, &w);
2320 2321 2322 2323 2324 2325
    assert(w.ekey >= pBlockInfo->window.skey);

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

L
Liu Jicong 已提交
2326 2327
    while (1) {
      //      getNextTimeWindow(pQueryAttr, &w);
2328 2329 2330 2331 2332 2333 2334 2335 2336 2337
      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 已提交
2338
    //    getAlignQueryTimeWindow(pQueryAttr, pBlockInfo->window.ekey, sk, ek, &w);
2339 2340 2341 2342 2343 2344
    assert(w.skey <= pBlockInfo->window.ekey);

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

L
Liu Jicong 已提交
2345 2346
    while (1) {
      //      getNextTimeWindow(pQueryAttr, &w);
2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360
      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 已提交
2361
static int32_t doTSJoinFilter(STaskRuntimeEnv* pRuntimeEnv, TSKEY key, bool ascQuery) {
2362 2363 2364
  STSElem elem = tsBufGetElem(pRuntimeEnv->pTsBuf);

#if defined(_DEBUG_VIEW)
L
Liu Jicong 已提交
2365 2366
  printf("elem in comp ts file:%" PRId64 ", key:%" PRId64 ", tag:%" PRIu64
         ", query order:%d, ts order:%d, traverse:%d, index:%d\n",
2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399
         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 已提交
2400
        //        SColumnFilterElem* pFilterElem = &pFilterInfo[k].pFilters[j];
2401 2402 2403

        bool isnull = isNull(pElem, pFilterInfo[k].info.type);
        if (isnull) {
L
Liu Jicong 已提交
2404 2405 2406 2407 2408 2409
          //          if (pFilterElem->fp == isNullOperator) {
          //            qualified = true;
          //            break;
          //          } else {
          //            continue;
          //          }
2410
        } else {
L
Liu Jicong 已提交
2411 2412 2413 2414 2415 2416
          //          if (pFilterElem->fp == notNullOperator) {
          //            qualified = true;
          //            break;
          //          } else if (pFilterElem->fp == isNullOperator) {
          //            continue;
          //          }
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 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487
        }

        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 已提交
2488
void filterRowsInDataBlock(STaskRuntimeEnv* pRuntimeEnv, SSingleColumnFilterInfo* pFilterInfo, int32_t numOfFilterCols,
2489 2490 2491
                           SSDataBlock* pBlock, bool ascQuery) {
  int32_t numOfRows = pBlock->info.rows;

L
Liu Jicong 已提交
2492
  int8_t* p = taosMemoryCalloc(numOfRows, sizeof(int8_t));
2493
  bool    all = true;
H
Haojun Liao 已提交
2494
#if 0
2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521
  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 已提交
2522
#endif
2523 2524 2525 2526 2527

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

wafwerar's avatar
wafwerar 已提交
2528
  taosMemoryFreeClear(p);
2529 2530
}

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

L
Liu Jicong 已提交
2534 2535
  int8_t* p = NULL;
  bool    all = true;
2536

L
Liu Jicong 已提交
2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558
  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;
      }
    }
2559

L
Liu Jicong 已提交
2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574
    // 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
    }
  }
2575

L
Liu Jicong 已提交
2576
  taosMemoryFreeClear(p);
2577 2578 2579
}

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

static uint32_t doFilterByBlockTimeWindow(STableScanInfo* pTableScanInfo, SSDataBlock* pBlock) {
H
Haojun Liao 已提交
2583
  SqlFunctionCtx* pCtx = pTableScanInfo->pCtx;
L
Liu Jicong 已提交
2584
  uint32_t        status = BLK_DATA_NO_NEEDED;
2585 2586 2587 2588

  int32_t numOfOutput = pTableScanInfo->numOfOutput;
  for (int32_t i = 0; i < numOfOutput; ++i) {
    int32_t functionId = pCtx[i].functionId;
H
Haojun Liao 已提交
2589
    int32_t colId = pTableScanInfo->pExpr[i].base.pParam[0].pCol->colId;
2590 2591 2592 2593 2594 2595

    // 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 已提交
2596 2597 2598 2599
      //      status |= aAggs[functionId].dataReqFunc(&pTableScanInfo->pCtx[i], &pBlock->info.window, colId);
      //      if ((status & BLK_DATA_ALL_NEEDED) == BLK_DATA_ALL_NEEDED) {
      //        return status;
      //      }
2600 2601 2602 2603 2604 2605
    }
  }

  return status;
}

L
Liu Jicong 已提交
2606 2607
int32_t loadDataBlockOnDemand(SExecTaskInfo* pTaskInfo, STableScanInfo* pTableScanInfo, SSDataBlock* pBlock,
                              uint32_t* status) {
2608 2609
  *status = BLK_DATA_NO_NEEDED;

H
Haojun Liao 已提交
2610
  pBlock->pDataBlock = NULL;
L
Liu Jicong 已提交
2611
  pBlock->pBlockAgg = NULL;
H
Haojun Liao 已提交
2612

L
Liu Jicong 已提交
2613 2614
  //  int64_t groupId = pRuntimeEnv->current->groupIndex;
  //  bool    ascQuery = QUERY_IS_ASC_QUERY(pQueryAttr);
2615

H
Haojun Liao 已提交
2616
  STaskCostInfo* pCost = &pTaskInfo->cost;
2617 2618 2619

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

  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;
2696
//    tsdbRetrieveDataBlockStatisInfo(pTableScanInfo->pTsdbReadHandle, &pBlock->pBlockAgg);
2697 2698

    if (pBlock->pBlockAgg == NULL) {  // data block statistics does not exist, load data block
2699
//      pBlock->pDataBlock = tsdbRetrieveDataBlock(pTableScanInfo->pTsdbReadHandle, NULL);
2700 2701 2702 2703 2704 2705 2706
      pCost->totalCheckedRows += pBlock->info.rows;
    }
  } else {
    assert((*status) == BLK_DATA_ALL_NEEDED);

    // load the data block statistics to perform further filter
    pCost->loadBlockStatis += 1;
2707
//    tsdbRetrieveDataBlockStatisInfo(pTableScanInfo->pTsdbReadHandle, &pBlock->pBlockAgg);
2708 2709 2710 2711 2712 2713

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

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

L
Liu Jicong 已提交
2770
int32_t binarySearchForKey(char* pValue, int num, TSKEY key, int order) {
2771 2772 2773 2774 2775 2776 2777 2778 2779
  int32_t midPos = -1;
  int32_t numOfRows;

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

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

L
Liu Jicong 已提交
2780
  TSKEY*  keyList = (TSKEY*)pValue;
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 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833
  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 已提交
2834
 * set tag value in SqlFunctionCtx
2835 2836
 * e.g.,tag information into input buffer
 */
L
Liu Jicong 已提交
2837
static void doSetTagValueInParam(void* pTable, int32_t tagColId, SVariant* tag, int16_t type, int16_t bytes) {
2838 2839 2840
  taosVariantDestroy(tag);

  char* val = NULL;
L
Liu Jicong 已提交
2841 2842 2843 2844 2845 2846
  //  if (tagColId == TSDB_TBNAME_COLUMN_INDEX) {
  //    val = tsdbGetTableName(pTable);
  //    assert(val != NULL);
  //  } else {
  //    val = tsdbGetTableTagVal(pTable, tagColId, type, bytes);
  //  }
2847 2848 2849 2850 2851 2852 2853 2854

  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 已提交
2855
    int32_t len = (varDataLen(val) > maxLen) ? maxLen : varDataLen(val);
2856
    taosVariantCreateFromBinary(tag, varDataVal(val), len, type);
L
Liu Jicong 已提交
2857
    // taosVariantCreateFromBinary(tag, varDataVal(val), varDataLen(val), type);
2858 2859 2860 2861 2862 2863 2864 2865
  } 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 已提交
2866
  for (int32_t i = 0; i < numOfTags; ++i) {
2867 2868 2869 2870 2871 2872 2873 2874
    if (pTagColList[i].colId == colId) {
      return &pTagColList[i];
    }
  }

  return NULL;
}

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

L
Liu Jicong 已提交
2878 2879
  SExprInfo* pExpr = pOperatorInfo->pExpr;
  STaskAttr* pQueryAttr = pRuntimeEnv->pQueryAttr;
2880 2881

  SExprInfo* pExprInfo = &pExpr[0];
L
Liu Jicong 已提交
2882
  int32_t    functionId = getExprFunctionId(pExprInfo);
2883 2884 2885 2886

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

L
Liu Jicong 已提交
2887
    //    int16_t      tagColId = (int16_t)pExprInfo->base.param[0].i;
H
Haojun Liao 已提交
2888
    int16_t      tagColId = -1;
2889 2890 2891
    SColumnInfo* pColInfo = doGetTagColumnInfoById(pQueryAttr->tagColList, pQueryAttr->numOfTags, tagColId);

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

2893 2894 2895 2896 2897 2898 2899 2900 2901
  } 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 已提交
2902
      if (!TSDB_COL_IS_TAG(pLocalExprInfo->base.pParam[0].pCol->flag)) {
2903 2904 2905 2906
        continue;
      }

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

L
Liu Jicong 已提交
2910 2911 2912
      if (IS_NUMERIC_TYPE(pLocalExprInfo->base.resSchema.type) ||
          pLocalExprInfo->base.resSchema.type == TSDB_DATA_TYPE_BOOL ||
          pLocalExprInfo->base.resSchema.type == TSDB_DATA_TYPE_TIMESTAMP) {
2913 2914 2915 2916
        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 已提交
2917
        }
2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929
      }

      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 已提交
2930
void copyToSDataBlock(SSDataBlock* pBlock, int32_t* offset, SGroupResInfo* pGroupResInfo, SDiskbasedBuf* pResBuf) {
2931 2932 2933 2934 2935 2936 2937
  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 已提交
2938 2939 2940
      //      if ((code = mergeIntoGroupResult(&pGroupResInfo, pRuntimeEnv, offset)) != TSDB_CODE_SUCCESS) {
      return;
      //      }
2941 2942
    }

L
Liu Jicong 已提交
2943
    //    doCopyToSDataBlock(pResBuf, pGroupResInfo, TSDB_ORDER_ASC, pBlock, );
2944 2945 2946 2947 2948 2949 2950 2951 2952 2953

    // 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 已提交
2954 2955 2956
    //    if (pBlock->info.rows >= threshold) {
    //      break;
    //    }
2957 2958 2959
  }
}

L
Liu Jicong 已提交
2960
static void updateTableQueryInfoForReverseScan(STableQueryInfo* pTableQueryInfo) {
2961 2962 2963 2964
  if (pTableQueryInfo == NULL) {
    return;
  }

L
Liu Jicong 已提交
2965 2966
  //  TSWAP(pTableQueryInfo->win.skey, pTableQueryInfo->win.ekey, TSKEY);
  //  pTableQueryInfo->lastKey = pTableQueryInfo->win.skey;
2967

L
Liu Jicong 已提交
2968 2969
  //  SWITCH_ORDER(pTableQueryInfo->cur.order);
  //  pTableQueryInfo->cur.vgroupIndex = -1;
2970 2971 2972 2973 2974 2975 2976 2977 2978 2979

  // 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 已提交
2980
void initResultRow(SResultRow* pResultRow) {
2981 2982 2983 2984 2985 2986
  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 已提交
2987 2988 2989
 * +------------+-----------------result column 1------------+------------------result column 2-----------+
 * | SResultRow | SResultRowEntryInfo | intermediate buffer1 | SResultRowEntryInfo | intermediate buffer 2|
 * +------------+--------------------------------------------+--------------------------------------------+
2990 2991
 *           offset[0]                                  offset[1]                                   offset[2]
 */
2992
// TODO refactor: some function move away
H
Haojun Liao 已提交
2993
void setFunctionResultOutput(SOptrBasicInfo* pInfo, SAggSupporter* pSup, int32_t stage, SExecTaskInfo* pTaskInfo) {
L
Liu Jicong 已提交
2994 2995 2996
  SqlFunctionCtx* pCtx = pInfo->pCtx;
  SSDataBlock*    pDataBlock = pInfo->pRes;
  int32_t*        rowCellInfoOffset = pInfo->rowCellInfoOffset;
H
Haojun Liao 已提交
2997

H
Haojun Liao 已提交
2998
  SResultRowInfo* pResultRowInfo = &pInfo->resultRowInfo;
H
Haojun Liao 已提交
2999
  initResultRowInfo(pResultRowInfo, 16);
H
Haojun Liao 已提交
3000

L
Liu Jicong 已提交
3001 3002 3003 3004
  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 已提交
3005 3006 3007 3008 3009

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

L
Liu Jicong 已提交
3010
    pCtx[i].resultInfo = pEntry;
H
Haojun Liao 已提交
3011 3012 3013
    pCtx[i].currentStage = stage;

    // set the timestamp output buffer for top/bottom/diff query
L
Liu Jicong 已提交
3014 3015
    //    int32_t fid = pCtx[i].functionId;
    //    if (fid == FUNCTION_TOP || fid == FUNCTION_BOTTOM || fid == FUNCTION_DIFF || fid == FUNCTION_DERIVATIVE) {
H
Haojun Liao 已提交
3016
    //      if (i > 0) pCtx[i].pTsOutput = pCtx[i-1].pOutput;
L
Liu Jicong 已提交
3017
    //    }
H
Haojun Liao 已提交
3018 3019 3020 3021 3022
  }

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

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

L
Liu Jicong 已提交
3026
  int32_t newSize = pDataBlock->info.rows + numOfInputRows + 5;  // extra output buffer
3027
  if ((*bufCapacity) < newSize) {
L
Liu Jicong 已提交
3028 3029
    for (int32_t i = 0; i < pDataBlock->info.numOfCols; ++i) {
      SColumnInfoData* pColInfo = taosArrayGet(pDataBlock->pDataBlock, i);
3030

wafwerar's avatar
wafwerar 已提交
3031
      char* p = taosMemoryRealloc(pColInfo->pData, newSize * pColInfo->info.bytes);
3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044
      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 已提交
3045
    SColumnInfoData* pColInfo = taosArrayGet(pDataBlock->pDataBlock, i);
3046 3047 3048 3049 3050
    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 已提交
3051 3052
    if (functionId == FUNCTION_TOP || functionId == FUNCTION_BOTTOM || functionId == FUNCTION_DIFF ||
        functionId == FUNCTION_DERIVATIVE) {
H
Haojun Liao 已提交
3053
//      if (i > 0) pBInfo->pCtx[i].pTsOutput = pBInfo->pCtx[i - 1].pOutput;
3054 3055 3056 3057
    }
  }
}

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

H
Haojun Liao 已提交
3088
void initCtxOutputBuffer(SqlFunctionCtx* pCtx, int32_t size) {
3089 3090
  for (int32_t j = 0; j < size; ++j) {
    struct SResultRowEntryInfo* pResInfo = GET_RES_INFO(&pCtx[j]);
H
Haojun Liao 已提交
3091
    if (isRowEntryInitialized(pResInfo) || fmIsPseudoColumnFunc(pCtx[j].functionId) || pCtx[j].functionId == -1 || fmIsScalarFunc(pCtx[j].functionId)) {
3092 3093 3094
      continue;
    }

H
Haojun Liao 已提交
3095
    pCtx[j].fpSet.init(&pCtx[j], pCtx[j].resultInfo);
3096 3097 3098
  }
}

L
Liu Jicong 已提交
3099
void setTaskStatus(SExecTaskInfo* pTaskInfo, int8_t status) {
3100
  if (status == TASK_NOT_COMPLETED) {
H
Haojun Liao 已提交
3101
    pTaskInfo->status = status;
3102 3103
  } else {
    // QUERY_NOT_COMPLETED is not compatible with any other status, so clear its position first
3104
    CLEAR_QUERY_STATUS(pTaskInfo, TASK_NOT_COMPLETED);
H
Haojun Liao 已提交
3105
    pTaskInfo->status |= status;
3106 3107 3108
  }
}

3109 3110
void finalizeQueryResult(SqlFunctionCtx* pCtx, int32_t numOfOutput) {
  for (int32_t j = 0; j < numOfOutput; ++j) {
H
Haojun Liao 已提交
3111 3112 3113 3114
    if (pCtx[j].functionId == -1) {
      continue;
    }

3115 3116 3117 3118
    pCtx[j].fpSet.finalize(&pCtx[j]);
  }
}

L
Liu Jicong 已提交
3119 3120
void finalizeMultiTupleQueryResult(SqlFunctionCtx* pCtx, int32_t numOfOutput, SDiskbasedBuf* pBuf,
                                   SResultRowInfo* pResultRowInfo, int32_t* rowCellInfoOffset) {
3121 3122 3123
  for (int32_t i = 0; i < pResultRowInfo->size; ++i) {
    SResultRowPosition* pPos = &pResultRowInfo->pPosition[i];

L
Liu Jicong 已提交
3124
    SFilePage*  bufPage = getBufPage(pBuf, pPos->pageId);
3125
    SResultRow* pRow = (SResultRow*)((char*)bufPage + pPos->offset);
H
Haojun Liao 已提交
3126 3127 3128 3129 3130

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

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

H
Haojun Liao 已提交
3135
      struct SResultRowEntryInfo* pResInfo = pCtx[j].resultInfo;
3136 3137 3138 3139
      if (isRowEntryCompleted(pResInfo) && isRowEntryInitialized(pResInfo)) {
        continue;
      }

H
Haojun Liao 已提交
3140
      if (pCtx[j].fpSet.process) {  // TODO set the dummy function, to avoid the check for null ptr.
H
Haojun Liao 已提交
3141 3142
        pCtx[j].fpSet.finalize(&pCtx[j]);
      }
3143 3144 3145 3146

      if (pRow->numOfRows < pResInfo->numOfRes) {
        pRow->numOfRows = pResInfo->numOfRes;
      }
3147
    }
3148 3149 3150

    releaseBufPage(pBuf, bufPage);
  }
3151 3152
}

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

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

  // set more initial size of interval/groupby query
L
Liu Jicong 已提交
3207 3208 3209 3210 3211 3212 3213 3214
  //  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
  //  }
3215 3216 3217 3218

  return pTableQueryInfo;
}

L
Liu Jicong 已提交
3219
void destroyTableQueryInfoImpl(STableQueryInfo* pTableQueryInfo) {
3220 3221 3222 3223
  if (pTableQueryInfo == NULL) {
    return;
  }

L
Liu Jicong 已提交
3224
  //  taosVariantDestroy(&pTableQueryInfo->tag);
3225 3226 3227
  cleanupResultRowInfo(&pTableQueryInfo->resInfo);
}

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

  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 已提交
3239
      offset += pCtx[i].resDataInfo.bytes;
3240 3241 3242 3243
      continue;
    }

    pCtx[i].pOutput = getPosInResultPage(pRuntimeEnv->pQueryAttr, bufPage, pResult->offset, offset);
H
Haojun Liao 已提交
3244
    offset += pCtx[i].resDataInfo.bytes;
3245 3246 3247 3248 3249 3250 3251

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

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

L
Liu Jicong 已提交
3255 3256 3257
    //    if (!pResInfo->initialized) {
    //      aAggs[functionId].init(&pCtx[i], pResInfo);
    //    }
3258 3259 3260
  }
}

H
Haojun Liao 已提交
3261
void setResultRowOutputBufInitCtx_rv(SResultRow* pResult, SqlFunctionCtx* pCtx, int32_t numOfOutput, int32_t* rowCellInfoOffset) {
3262 3263 3264 3265 3266 3267 3268
  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;
    }
3269 3270 3271 3272 3273

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

H
Haojun Liao 已提交
3274
    if (!pResInfo->initialized && pCtx[i].functionId != -1) {
3275
      pCtx[i].fpSet.init(&pCtx[i], pResInfo);
3276 3277 3278 3279
    }
  }
}

3280 3281 3282 3283 3284 3285
void doFilter(const SNode* pFilterNode, SSDataBlock* pBlock) {
  if (pFilterNode == NULL) {
    return;
  }

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

H
Haojun Liao 已提交
3287
  // todo move to the initialization function
H
Haojun Liao 已提交
3288
  int32_t code = filterInitFromNode((SNode*)pFilterNode, &filter, 0);
3289 3290 3291 3292 3293 3294 3295 3296 3297 3298

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

  int8_t* rowRes = NULL;
  bool    keep = filterExecute(filter, pBlock, &rowRes, NULL, param1.numOfCols);

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

H
Haojun Liao 已提交
3299
  // todo extract method
3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310
  int32_t numOfRow = 0;
  for (int32_t i = 0; i < pBlock->info.numOfCols; ++i) {
    SColumnInfoData* pDst = taosArrayGet(px->pDataBlock, i);
    SColumnInfoData* pSrc = taosArrayGet(pBlock->pDataBlock, i);

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

H
Haojun Liao 已提交
3311 3312 3313 3314 3315
      if (colDataIsNull_s(pSrc, j)) {
        colDataAppendNULL(pDst, numOfRow);
      } else {
        colDataAppend(pDst, numOfRow, colDataGetData(pSrc, j), false);
      }
3316 3317 3318 3319 3320 3321 3322 3323 3324
      numOfRow += 1;
    }

    *pSrc = *pDst;
  }

  pBlock->info.rows = numOfRow;
}

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

3330 3331
  SResultRowInfo* pResultRowInfo = &pAggInfo->binfo.resultRowInfo;
  SqlFunctionCtx* pCtx = pAggInfo->binfo.pCtx;
L
Liu Jicong 已提交
3332
  int32_t*        rowCellInfoOffset = pAggInfo->binfo.rowCellInfoOffset;
3333

3334
  SResultRow* pResultRow =
L
Liu Jicong 已提交
3335 3336 3337
      doSetResultOutBufByKey_rv(pAggInfo->pResultBuf, pResultRowInfo, tid, (char*)&tableGroupId, sizeof(tableGroupId),
                                true, uid, pTaskInfo, false, &pAggInfo->aggSup);
  assert(pResultRow != NULL);
3338 3339 3340 3341 3342 3343

  /*
   * 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 已提交
3344
    int32_t ret = addNewWindowResultBuf(pResultRow, pAggInfo->pResultBuf, tableGroupId, pAggInfo->binfo.pRes->info.rowSize);
3345 3346 3347 3348 3349
    if (ret != TSDB_CODE_SUCCESS) {
      return;
    }
  }

H
Haojun Liao 已提交
3350
  setResultRowOutputBufInitCtx_rv(pResultRow, pCtx, numOfOutput, rowCellInfoOffset);
3351 3352
}

L
Liu Jicong 已提交
3353 3354
void setExecutionContext(int32_t numOfOutput, int32_t tableGroupId, TSKEY nextKey, SExecTaskInfo* pTaskInfo,
                         STableQueryInfo* pTableQueryInfo, SAggOperatorInfo* pAggInfo) {
3355 3356
  // lastKey needs to be updated
  pTableQueryInfo->lastKey = nextKey;
3357
  if (pAggInfo->groupId != INT32_MIN && pAggInfo->groupId == tableGroupId) {
3358 3359 3360
    return;
  }

3361
  doSetTableGroupOutputBuf(pAggInfo, numOfOutput, tableGroupId, pTaskInfo);
3362 3363

  // record the current active group id
3364
  pAggInfo->groupId = tableGroupId;
3365 3366
}

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

H
Haojun Liao 已提交
3370
  SExprBasicInfo* pExpr = &pExprInfo->base;
L
Liu Jicong 已提交
3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394
  //  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 已提交
3395
  STaskAttr* pQueryAttr = pRuntimeEnv->pQueryAttr;
3396 3397

  assert(pRuntimeEnv->pTsBuf != NULL);
H
Haojun Liao 已提交
3398
#if 0
3399 3400 3401 3402 3403 3404 3405 3406 3407
  // 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) {
3408
        //qError("QInfo:0x%"PRIx64" failed to find tag:%s in ts_comp", GET_TASKID(pRuntimeEnv), pTag->pz);
3409
      } else {
3410
        //qError("QInfo:0x%"PRIx64" failed to find tag:%" PRId64 " in ts_comp", GET_TASKID(pRuntimeEnv), pTag->i);
3411 3412 3413 3414 3415 3416 3417 3418
      }

      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) {
3419
      //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);
3420
    } else {
3421
      //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);
3422 3423 3424 3425 3426
    }

  } else {
    tsBufSetCursor(pRuntimeEnv->pTsBuf, &pTableQueryInfo->cur);
    if (pTag->nType == TSDB_DATA_TYPE_BINARY || pTag->nType == TSDB_DATA_TYPE_NCHAR) {
3427
      //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);
3428
    } else {
3429
      //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);
3430 3431
    }
  }
H
Haojun Liao 已提交
3432
#endif
3433 3434 3435 3436 3437 3438
  return 0;
}

/*
 * There are two cases to handle:
 *
L
Liu Jicong 已提交
3439 3440
 * 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.
3441 3442 3443 3444
 * 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 已提交
3445 3446 3447 3448
void setIntervalQueryRange(STaskRuntimeEnv* pRuntimeEnv, TSKEY key) {
  STaskAttr*       pQueryAttr = pRuntimeEnv->pQueryAttr;
  STableQueryInfo* pTableQueryInfo = pRuntimeEnv->current;
  SResultRowInfo*  pResultRowInfo = &pTableQueryInfo->resInfo;
3449 3450 3451 3452 3453

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

L
Liu Jicong 已提交
3454
  //  pTableQueryInfo->win.skey = key;
3455 3456 3457 3458 3459 3460 3461 3462 3463 3464
  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 已提交
3465 3466
  TSKEY sk = TMIN(win.skey, win.ekey);
  TSKEY ek = TMAX(win.skey, win.ekey);
L
Liu Jicong 已提交
3467
  //  getAlignQueryTimeWindow(pQueryAttr, win.skey, sk, ek, &w);
3468

L
Liu Jicong 已提交
3469 3470 3471 3472 3473 3474 3475
  //  if (pResultRowInfo->prevSKey == TSKEY_INITIAL_VAL) {
  //    if (!QUERY_IS_ASC_QUERY(pQueryAttr)) {
  //      assert(win.ekey == pQueryAttr->window.ekey);
  //    }
  //
  //    pResultRowInfo->prevSKey = w.skey;
  //  }
3476

L
Liu Jicong 已提交
3477
  //  pTableQueryInfo->lastKey = pTableQueryInfo->win.skey;
3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488
}

/**
 * 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 已提交
3489 3490
static int32_t doCopyToSDataBlock(SDiskbasedBuf* pBuf, SGroupResInfo* pGroupResInfo, int32_t orderType,
                                  SSDataBlock* pBlock, int32_t rowCapacity, int32_t* rowCellOffset) {
3491
  int32_t numOfRows = getNumOfTotalRes(pGroupResInfo);
L
Liu Jicong 已提交
3492
  int32_t numOfResult = pBlock->info.rows;  // there are already exists result rows
3493 3494 3495 3496

  int32_t start = 0;
  int32_t step = -1;

L
Liu Jicong 已提交
3497
  // qDebug("QInfo:0x%"PRIx64" start to copy data from windowResInfo to output buf", GET_TASKID(pRuntimeEnv));
3498 3499 3500 3501 3502 3503 3504 3505 3506 3507
  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;
  }

3508 3509
  int32_t nrows = pBlock->info.rows;

3510
  for (int32_t i = start; (i < numOfRows) && (i >= 0); i += step) {
3511
    SResultRowPosition* pPos = taosArrayGet(pGroupResInfo->pRows, i);
L
Liu Jicong 已提交
3512
    SFilePage*          page = getBufPage(pBuf, pPos->pageId);
3513 3514

    SResultRow* pRow = (SResultRow*)((char*)page + pPos->offset);
3515 3516 3517 3518 3519
    if (pRow->numOfRows == 0) {
      pGroupResInfo->index += 1;
      continue;
    }

3520
    // TODO copy multiple rows?
3521
    int32_t numOfRowsToCopy = pRow->numOfRows;
L
Liu Jicong 已提交
3522
    if (numOfResult + numOfRowsToCopy >= rowCapacity) {
3523 3524 3525 3526 3527 3528
      break;
    }

    pGroupResInfo->index += 1;

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

3532
      char* in = GET_ROWCELL_INTERBUF(pEntryInfo);
H
Haojun Liao 已提交
3533
      colDataAppend(pColInfoData, nrows, in, pEntryInfo->isNullRes);
3534 3535
    }

3536 3537 3538
    releaseBufPage(pBuf, page);
    nrows += 1;

3539
    numOfResult += numOfRowsToCopy;
H
Haojun Liao 已提交
3540
    if (numOfResult == rowCapacity) {  // output buffer is full
3541 3542 3543 3544
      break;
    }
  }

L
Liu Jicong 已提交
3545
  // qDebug("QInfo:0x%"PRIx64" copy data to query buf completed", GET_TASKID(pRuntimeEnv));
3546 3547 3548 3549
  pBlock->info.rows = numOfResult;
  return 0;
}

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

3554
  blockDataCleanup(pBlock);
3555 3556 3557 3558
  if (!hasRemainDataInCurrentGroup(pGroupResInfo)) {
    return;
  }

3559
  int32_t orderType = TSDB_ORDER_ASC;
3560
  doCopyToSDataBlock(pBuf, pGroupResInfo, orderType, pBlock, rowCapacity, rowCellOffset);
3561

H
Haojun Liao 已提交
3562 3563
  // add condition (pBlock->info.rows >= 1) just to runtime happy
  blockDataUpdateTsWindow(pBlock);
3564 3565
}

L
Liu Jicong 已提交
3566 3567
static void updateNumOfRowsInResultRows(SqlFunctionCtx* pCtx, int32_t numOfOutput, SResultRowInfo* pResultRowInfo,
                                        int32_t* rowCellInfoOffset) {
3568
  // update the number of result for each, only update the number of rows for the corresponding window result.
L
Liu Jicong 已提交
3569 3570 3571
  //  if (QUERY_IS_INTERVAL_QUERY(pQueryAttr)) {
  //    return;
  //  }
H
Haojun Liao 已提交
3572
#if 0
3573
  for (int32_t i = 0; i < pResultRowInfo->size; ++i) {
L
Liu Jicong 已提交
3574
    SResultRow* pResult = pResultRowInfo->pResult[i];
3575 3576 3577 3578 3579 3580 3581

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

3582 3583
      SResultRowEntryInfo* pCell = getResultCell(pResult, j, rowCellInfoOffset);
      pResult->numOfRows = (uint16_t)(TMAX(pResult->numOfRows, pCell->numOfRes));
3584 3585
    }
  }
H
Haojun Liao 已提交
3586 3587
#endif

3588 3589
}

L
Liu Jicong 已提交
3590
static int32_t compressQueryColData(SColumnInfoData* pColRes, int32_t numOfRows, char* data, int8_t compressed) {
3591 3592
  int32_t colSize = pColRes->info.bytes * numOfRows;
  return (*(tDataTypes[pColRes->info.type].compFunc))(pColRes->pData, colSize, numOfRows, data,
L
Liu Jicong 已提交
3593
                                                      colSize + COMP_OVERFLOW_BYTES, compressed, NULL, 0);
3594 3595
}

L
Liu Jicong 已提交
3596 3597 3598 3599 3600
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);
  //  }
3601 3602 3603 3604 3605 3606 3607 3608 3609 3610

  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 已提交
3611 3612
  event.eventType = eventType;
  event.eventTime = taosGetTimestampUs();
3613 3614 3615
  event.operatorType = operatorInfo->operatorType;

  if (operatorInfo->pRuntimeEnv) {
L
Liu Jicong 已提交
3616 3617 3618 3619
    //    SQInfo* pQInfo = operatorInfo->pRuntimeEnv->qinfo;
    //    if (pQInfo->summary.queryProfEvents) {
    //      taosArrayPush(pQInfo->summary.queryProfEvents, &event);
    //    }
3620 3621 3622
  }
}

L
Liu Jicong 已提交
3623
void publishQueryAbortEvent(SExecTaskInfo* pTaskInfo, int32_t code) {
3624 3625 3626 3627 3628
  SQueryProfEvent event;
  event.eventType = QUERY_PROF_QUERY_ABORT;
  event.eventTime = taosGetTimestampUs();
  event.abortCode = code;

3629 3630
  if (pTaskInfo->cost.queryProfEvents) {
    taosArrayPush(pTaskInfo->cost.queryProfEvents, &event);
3631 3632 3633
  }
}

L
Liu Jicong 已提交
3634
typedef struct {
3635 3636 3637 3638 3639 3640 3641
  uint8_t operatorType;
  int64_t beginTime;
  int64_t endTime;
  int64_t selfTime;
  int64_t descendantsTime;
} SOperatorStackItem;

L
Liu Jicong 已提交
3642 3643
static void doOperatorExecProfOnce(SOperatorStackItem* item, SQueryProfEvent* event, SArray* opStack,
                                   SHashObj* profResults) {
3644 3645 3646 3647 3648 3649 3650 3651
  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 已提交
3652
  uint8_t              operatorType = item->operatorType;
3653 3654 3655 3656 3657 3658 3659 3660 3661
  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 已提交
3662
    taosHashPut(profResults, &(operatorType), sizeof(operatorType), &opResult, sizeof(opResult));
3663 3664 3665 3666 3667
  }
}

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

  if (pQInfo->summary.operatorProfResults == NULL) {
L
Liu Jicong 已提交
3673
    // qDebug("QInfo:0x%"PRIx64" operator prof results hash is null", pQInfo->qId);
3674 3675 3676 3677 3678 3679 3680 3681
    return;
  }

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

L
Liu Jicong 已提交
3682
  size_t    size = taosArrayGetSize(pQInfo->summary.queryProfEvents);
3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707
  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 已提交
3708 3709
void queryCostStatis(SExecTaskInfo* pTaskInfo) {
  STaskCostInfo* pSummary = &pTaskInfo->cost;
3710

L
Liu Jicong 已提交
3711 3712 3713
  //  uint64_t hashSize = taosHashGetMemSize(pQInfo->runtimeEnv.pResultRowHashTable);
  //  hashSize += taosHashGetMemSize(pRuntimeEnv->tableqinfoGroupInfo.map);
  //  pSummary->hashSize = hashSize;
3714 3715 3716 3717

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

L
Liu Jicong 已提交
3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737
  //  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);
3738 3739 3740 3741

  if (pSummary->operatorProfResults) {
    SOperatorProfResult* opRes = taosHashIterate(pSummary->operatorProfResults, NULL);
    while (opRes != NULL) {
L
Liu Jicong 已提交
3742 3743
      // qDebug("QInfo:0x%" PRIx64 " :cost summary: operator : %d, exec times: %" PRId64 ", self time: %" PRId64,
      //             pQInfo->qId, opRes->operatorType, opRes->sumRunTimes, opRes->sumSelfTime);
3744 3745 3746 3747 3748
      opRes = taosHashIterate(pSummary->operatorProfResults, opRes);
    }
  }
}

L
Liu Jicong 已提交
3749 3750 3751
// static void updateOffsetVal(STaskRuntimeEnv *pRuntimeEnv, SDataBlockInfo *pBlockInfo) {
//   STaskAttr *pQueryAttr = pRuntimeEnv->pQueryAttr;
//   STableQueryInfo* pTableQueryInfo = pRuntimeEnv->current;
3752
//
L
Liu Jicong 已提交
3753
//   int32_t step = GET_FORWARD_DIRECTION_FACTOR(pQueryAttr->order.order);
3754
//
L
Liu Jicong 已提交
3755 3756 3757 3758
//   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;
//   }
3759
//
L
Liu Jicong 已提交
3760 3761 3762 3763 3764
//   if (QUERY_IS_ASC_QUERY(pQueryAttr)) {
//     pQueryAttr->pos = (int32_t)pQueryAttr->limit.offset;
//   } else {
//     pQueryAttr->pos = pBlockInfo->rows - (int32_t)pQueryAttr->limit.offset - 1;
//   }
3765
//
L
Liu Jicong 已提交
3766
//   assert(pQueryAttr->pos >= 0 && pQueryAttr->pos <= pBlockInfo->rows - 1);
3767
//
L
Liu Jicong 已提交
3768 3769
//   SArray *         pDataBlock = tsdbRetrieveDataBlock(pRuntimeEnv->pTsdbReadHandle, NULL);
//   SColumnInfoData *pColInfoData = taosArrayGet(pDataBlock, 0);
3770
//
L
Liu Jicong 已提交
3771 3772
//   // update the pQueryAttr->limit.offset value, and pQueryAttr->pos value
//   TSKEY *keys = (TSKEY *) pColInfoData->pData;
3773
//
L
Liu Jicong 已提交
3774 3775 3776
//   // update the offset value
//   pTableQueryInfo->lastKey = keys[pQueryAttr->pos];
//   pQueryAttr->limit.offset = 0;
3777
//
L
Liu Jicong 已提交
3778
//   int32_t numOfRes = tableApplyFunctionsOnBlock(pRuntimeEnv, pBlockInfo, NULL, binarySearchForKey, pDataBlock);
3779
//
L
Liu Jicong 已提交
3780 3781 3782 3783
//   //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);
// }
3784

L
Liu Jicong 已提交
3785 3786
// void skipBlocks(STaskRuntimeEnv *pRuntimeEnv) {
//   STaskAttr *pQueryAttr = pRuntimeEnv->pQueryAttr;
3787
//
L
Liu Jicong 已提交
3788 3789 3790
//   if (pQueryAttr->limit.offset <= 0 || pQueryAttr->numOfFilterCols > 0) {
//     return;
//   }
3791
//
L
Liu Jicong 已提交
3792 3793
//   pQueryAttr->pos = 0;
//   int32_t step = GET_FORWARD_DIRECTION_FACTOR(pQueryAttr->order.order);
3794
//
L
Liu Jicong 已提交
3795 3796
//   STableQueryInfo* pTableQueryInfo = pRuntimeEnv->current;
//   TsdbQueryHandleT pTsdbReadHandle = pRuntimeEnv->pTsdbReadHandle;
3797
//
L
Liu Jicong 已提交
3798 3799 3800 3801 3802
//   SDataBlockInfo blockInfo = SDATA_BLOCK_INITIALIZER;
//   while (tsdbNextDataBlock(pTsdbReadHandle)) {
//     if (isTaskKilled(pRuntimeEnv->qinfo)) {
//       longjmp(pRuntimeEnv->env, TSDB_CODE_TSC_QUERY_CANCELLED);
//     }
3803
//
L
Liu Jicong 已提交
3804
//     tsdbRetrieveDataBlockInfo(pTsdbReadHandle, &blockInfo);
3805
//
L
Liu Jicong 已提交
3806 3807 3808 3809
//     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;
3810
//
L
Liu Jicong 已提交
3811 3812 3813 3814 3815 3816 3817
//       //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;
//     }
//   }
3818
//
L
Liu Jicong 已提交
3819 3820 3821 3822 3823 3824 3825 3826 3827
//   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;
3828
//
L
Liu Jicong 已提交
3829 3830 3831
//   assert(pQueryAttr->limit.offset == 0);
//   STimeWindow tw = *win;
//   getNextTimeWindow(pQueryAttr, &tw);
3832
//
L
Liu Jicong 已提交
3833 3834
//   if ((tw.skey <= pBlockInfo->window.ekey && QUERY_IS_ASC_QUERY(pQueryAttr)) ||
//       (tw.ekey >= pBlockInfo->window.skey && !QUERY_IS_ASC_QUERY(pQueryAttr))) {
3835
//
L
Liu Jicong 已提交
3836 3837 3838 3839
//     // 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);
3840
//
L
Liu Jicong 已提交
3841 3842 3843 3844
//     tw = *win;
//     int32_t startPos =
//         getNextQualifiedWindow(pQueryAttr, &tw, pBlockInfo, pColInfoData->pData, binarySearchForKey, -1);
//     assert(startPos >= 0);
3845
//
L
Liu Jicong 已提交
3846 3847
//     // set the abort info
//     pQueryAttr->pos = startPos;
3848
//
L
Liu Jicong 已提交
3849 3850 3851 3852
//     // reset the query start timestamp
//     pTableQueryInfo->win.skey = ((TSKEY *)pColInfoData->pData)[startPos];
//     pQueryAttr->window.skey = pTableQueryInfo->win.skey;
//     TSKEY key = pTableQueryInfo->win.skey;
3853
//
L
Liu Jicong 已提交
3854 3855
//     pWindowResInfo->prevSKey = tw.skey;
//     int32_t index = pRuntimeEnv->resultRowInfo.curIndex;
3856
//
L
Liu Jicong 已提交
3857 3858
//     int32_t numOfRes = tableApplyFunctionsOnBlock(pRuntimeEnv, pBlockInfo, NULL, binarySearchForKey, pDataBlock);
//     pRuntimeEnv->resultRowInfo.curIndex = index;  // restore the window index
3859
//
L
Liu Jicong 已提交
3860 3861 3862 3863
//     //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);
3864
//
L
Liu Jicong 已提交
3865 3866 3867 3868 3869
//     return key;
//   } else {  // do nothing
//     pQueryAttr->window.skey      = tw.skey;
//     pWindowResInfo->prevSKey = tw.skey;
//     pTableQueryInfo->lastKey = tw.skey;
3870
//
L
Liu Jicong 已提交
3871 3872
//     return tw.skey;
//   }
3873
//
L
Liu Jicong 已提交
3874 3875 3876 3877 3878 3879 3880 3881 3882 3883
//   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);
//   }
3884
//
L
Liu Jicong 已提交
3885 3886 3887 3888 3889
//   // 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;
//   }
3890
//
L
Liu Jicong 已提交
3891 3892 3893 3894 3895 3896 3897
//   /*
//    * 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);
3898
//
L
Liu Jicong 已提交
3899 3900
//   STimeWindow w = TSWINDOW_INITIALIZER;
//   bool ascQuery = QUERY_IS_ASC_QUERY(pQueryAttr);
3901
//
L
Liu Jicong 已提交
3902 3903
//   SResultRowInfo *pWindowResInfo = &pRuntimeEnv->resultRowInfo;
//   STableQueryInfo *pTableQueryInfo = pRuntimeEnv->current;
3904
//
L
Liu Jicong 已提交
3905 3906 3907
//   SDataBlockInfo blockInfo = SDATA_BLOCK_INITIALIZER;
//   while (tsdbNextDataBlock(pRuntimeEnv->pTsdbReadHandle)) {
//     tsdbRetrieveDataBlockInfo(pRuntimeEnv->pTsdbReadHandle, &blockInfo);
3908
//
L
Liu Jicong 已提交
3909 3910 3911 3912 3913 3914 3915 3916 3917
//     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;
//     }
3918
//
L
Liu Jicong 已提交
3919 3920
//     // the first time window
//     STimeWindow win = getActiveTimeWindow(pWindowResInfo, pWindowResInfo->prevSKey, pQueryAttr);
3921
//
L
Liu Jicong 已提交
3922 3923
//     while (pQueryAttr->limit.offset > 0) {
//       STimeWindow tw = win;
3924
//
L
Liu Jicong 已提交
3925 3926 3927
//       if ((win.ekey <= blockInfo.window.ekey && ascQuery) || (win.ekey >= blockInfo.window.skey && !ascQuery)) {
//         pQueryAttr->limit.offset -= 1;
//         pWindowResInfo->prevSKey = win.skey;
3928
//
L
Liu Jicong 已提交
3929 3930 3931 3932 3933 3934
//         // 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;
//         }
//       }
3935
//
L
Liu Jicong 已提交
3936 3937 3938 3939
//       if (pQueryAttr->limit.offset == 0) {
//         *start = doSkipIntervalProcess(pRuntimeEnv, &win, &blockInfo, pTableQueryInfo);
//         return true;
//       }
3940
//
L
Liu Jicong 已提交
3941 3942
//       // current window does not ended in current data block, try next data block
//       getNextTimeWindow(pQueryAttr, &tw);
3943
//
L
Liu Jicong 已提交
3944 3945 3946 3947 3948 3949 3950 3951 3952
//       /*
//        * 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)) {
3953
//
L
Liu Jicong 已提交
3954 3955
//         SArray *pDataBlock = tsdbRetrieveDataBlock(pRuntimeEnv->pTsdbReadHandle, NULL);
//         SColumnInfoData *pColInfoData = taosArrayGet(pDataBlock, 0);
3956
//
L
Liu Jicong 已提交
3957 3958 3959
//         if ((win.ekey > blockInfo.window.ekey && ascQuery) || (win.ekey < blockInfo.window.skey && !ascQuery)) {
//           pQueryAttr->limit.offset -= 1;
//         }
3960
//
L
Liu Jicong 已提交
3961 3962 3963 3964 3965 3966 3967 3968
//         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);
3969
//
L
Liu Jicong 已提交
3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980
//           // 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.
//       }
//     }
//   }
3981
//
L
Liu Jicong 已提交
3982 3983 3984 3985
//   // check for error
//   if (terrno != TSDB_CODE_SUCCESS) {
//     longjmp(pRuntimeEnv->env, terrno);
//   }
3986
//
L
Liu Jicong 已提交
3987 3988
//   return true;
// }
3989

3990
int32_t appendDownstream(SOperatorInfo* p, SOperatorInfo** pDownstream, int32_t num) {
H
Haojun Liao 已提交
3991
  if (p->pDownstream == NULL) {
H
Haojun Liao 已提交
3992
    assert(p->numOfDownstream == 0);
3993 3994
  }

wafwerar's avatar
wafwerar 已提交
3995
  p->pDownstream = taosMemoryCalloc(1, num * POINTER_BYTES);
3996 3997 3998 3999 4000 4001 4002
  if (p->pDownstream == NULL) {
    return TSDB_CODE_OUT_OF_MEMORY;
  }

  memcpy(p->pDownstream, pDownstream, num * POINTER_BYTES);
  p->numOfDownstream = num;
  return TSDB_CODE_SUCCESS;
4003 4004 4005 4006
}

static void doDestroyTableQueryInfo(STableGroupInfo* pTableqinfoGroupInfo);

H
Haojun Liao 已提交
4007
static int32_t setupQueryHandle(void* tsdb, STaskRuntimeEnv* pRuntimeEnv, int64_t qId, bool isSTableQuery) {
L
Liu Jicong 已提交
4008
  STaskAttr* pQueryAttr = pRuntimeEnv->pQueryAttr;
4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033
#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)) {
4034
    pRuntimeEnv->pTsdbReadHandle = tsdbQueryLastRow(tsdb, &cond, &pQueryAttr->tableGroupInfo, qId, &pQueryAttr->memRef);
4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054

    // 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)) {
4055
    pRuntimeEnv->pTsdbReadHandle = tsdbQueryCacheLast(tsdb, &cond, &pQueryAttr->tableGroupInfo, qId, &pQueryAttr->memRef);
4056
  } else if (pQueryAttr->pointInterpQuery) {
4057
    pRuntimeEnv->pTsdbReadHandle = tsdbQueryRowsInExternalWindow(tsdb, &cond, &pQueryAttr->tableGroupInfo, qId, &pQueryAttr->memRef);
4058
  } else {
4059
    pRuntimeEnv->pTsdbReadHandle = tsdbQueryTables(tsdb, &cond, &pQueryAttr->tableGroupInfo, qId, &pQueryAttr->memRef);
4060 4061 4062 4063 4064
  }
#endif
  return terrno;
}

4065
static void doTableQueryInfoTimeWindowCheck(SExecTaskInfo* pTaskInfo, STableQueryInfo* pTableQueryInfo, int32_t order) {
H
Haojun Liao 已提交
4066 4067
#if 0
    if (order == TSDB_ORDER_ASC) {
4068 4069
    assert(
        (pTableQueryInfo->win.skey <= pTableQueryInfo->win.ekey) &&
H
Haojun Liao 已提交
4070 4071
        (pTableQueryInfo->lastKey >= pTaskInfo->window.skey) &&
        (pTableQueryInfo->win.skey >= pTaskInfo->window.skey && pTableQueryInfo->win.ekey <= pTaskInfo->window.ekey));
4072 4073 4074
  } else {
    assert(
        (pTableQueryInfo->win.skey >= pTableQueryInfo->win.ekey) &&
H
Haojun Liao 已提交
4075 4076
        (pTableQueryInfo->lastKey <= pTaskInfo->window.skey) &&
        (pTableQueryInfo->win.skey <= pTaskInfo->window.skey && pTableQueryInfo->win.ekey >= pTaskInfo->window.ekey));
4077
  }
H
Haojun Liao 已提交
4078
#endif
4079 4080
}

L
Liu Jicong 已提交
4081 4082 4083 4084 4085 4086 4087 4088
// 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,
//   };
4089
//
L
Liu Jicong 已提交
4090 4091 4092
//   TIME_WINDOW_COPY(cond.twindow, *win);
//   return cond;
// }
4093 4094 4095

static STableIdInfo createTableIdInfo(STableQueryInfo* pTableQueryInfo) {
  STableIdInfo tidInfo;
L
Liu Jicong 已提交
4096 4097 4098 4099 4100
  //  STableId* id = TSDB_TABLEID(pTableQueryInfo->pTable);
  //
  //  tidInfo.uid = id->uid;
  //  tidInfo.tid = id->tid;
  //  tidInfo.key = pTableQueryInfo->lastKey;
4101 4102 4103 4104

  return tidInfo;
}

L
Liu Jicong 已提交
4105 4106 4107 4108
// 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;
4109
//
L
Liu Jicong 已提交
4110 4111 4112
//   if (pTableQueryInfo->pTable == NULL) {
//     return;
//   }
4113
//
L
Liu Jicong 已提交
4114 4115 4116 4117 4118 4119 4120 4121 4122
//   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));
//   }
// }
4123

H
Haojun Liao 已提交
4124
static void doCloseAllTimeWindow(STaskRuntimeEnv* pRuntimeEnv) {
4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136
  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);
    }
  }
}

4137
int32_t loadRemoteDataCallback(void* param, const SDataBuf* pMsg, int32_t code) {
L
Liu Jicong 已提交
4138
  SSourceDataInfo* pSourceDataInfo = (SSourceDataInfo*)param;
H
Haojun Liao 已提交
4139 4140
  if (code == TSDB_CODE_SUCCESS) {
    pSourceDataInfo->pRsp = pMsg->pData;
4141

H
Haojun Liao 已提交
4142 4143 4144 4145 4146 4147 4148
    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 已提交
4149

H
Haojun Liao 已提交
4150
  pSourceDataInfo->status = EX_SOURCE_DATA_READY;
4151
  tsem_post(&pSourceDataInfo->pEx->ready);
H
Haojun Liao 已提交
4152
}
4153

H
Haojun Liao 已提交
4154 4155
static void destroySendMsgInfo(SMsgSendInfo* pMsgBody) {
  assert(pMsgBody != NULL);
wafwerar's avatar
wafwerar 已提交
4156 4157
  taosMemoryFreeClear(pMsgBody->msgInfo.pData);
  taosMemoryFreeClear(pMsgBody);
H
Haojun Liao 已提交
4158
}
4159

S
Shengliang Guan 已提交
4160
void qProcessFetchRsp(void* parent, SRpcMsg* pMsg, SEpSet* pEpSet) {
L
Liu Jicong 已提交
4161
  SMsgSendInfo* pSendInfo = (SMsgSendInfo*)pMsg->ahandle;
H
Haojun Liao 已提交
4162
  assert(pMsg->ahandle != NULL);
4163

H
Haojun Liao 已提交
4164
  SDataBuf buf = {.len = pMsg->contLen, .pData = NULL};
4165

H
Haojun Liao 已提交
4166
  if (pMsg->contLen > 0) {
wafwerar's avatar
wafwerar 已提交
4167
    buf.pData = taosMemoryCalloc(1, pMsg->contLen);
H
Haojun Liao 已提交
4168 4169 4170 4171 4172
    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);
4173 4174 4175
    }
  }

H
Haojun Liao 已提交
4176 4177 4178
  pSendInfo->fp(pSendInfo->param, &buf, pMsg->code);
  rpcFreeCont(pMsg->pCont);
  destroySendMsgInfo(pSendInfo);
4179 4180
}

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

wafwerar's avatar
wafwerar 已提交
4184
  SResFetchReq* pMsg = taosMemoryCalloc(1, sizeof(SResFetchReq));
4185 4186 4187
  if (NULL == pMsg) {
    pTaskInfo->code = TSDB_CODE_QRY_OUT_OF_MEMORY;
    return pTaskInfo->code;
H
Haojun Liao 已提交
4188 4189
  }

L
Liu Jicong 已提交
4190 4191
  SDownstreamSourceNode* pSource = taosArrayGet(pExchangeInfo->pSources, sourceIndex);
  SSourceDataInfo*       pDataInfo = taosArrayGet(pExchangeInfo->pSourceDataInfo, sourceIndex);
4192

L
Liu Jicong 已提交
4193 4194
  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);
4195 4196 4197 4198 4199 4200 4201

  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 已提交
4202
  SMsgSendInfo* pMsgSendInfo = taosMemoryCalloc(1, sizeof(SMsgSendInfo));
4203
  if (NULL == pMsgSendInfo) {
wafwerar's avatar
wafwerar 已提交
4204
    taosMemoryFreeClear(pMsg);
4205 4206 4207
    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 已提交
4208 4209
  }

4210 4211 4212 4213 4214
  pMsgSendInfo->param = pDataInfo;
  pMsgSendInfo->msgInfo.pData = pMsg;
  pMsgSendInfo->msgInfo.len = sizeof(SResFetchReq);
  pMsgSendInfo->msgType = TDMT_VND_FETCH;
  pMsgSendInfo->fp = loadRemoteDataCallback;
4215

4216
  int64_t transporterId = 0;
L
Liu Jicong 已提交
4217
  int32_t code = asyncSendMsgToServer(pExchangeInfo->pTransporter, &pSource->addr.epSet, &transporterId, pMsgSendInfo);
4218 4219 4220
  return TSDB_CODE_SUCCESS;
}

4221
// TODO if only one or two columnss required, how to extract data?
H
Haojun Liao 已提交
4222
int32_t setSDataBlockFromFetchRsp(SSDataBlock* pRes, SLoadRemoteDataInfo* pLoadInfo, int32_t numOfRows,
L
Liu Jicong 已提交
4223 4224
                                         char* pData, int32_t compLen, int32_t numOfOutput, int64_t startTs,
                                         uint64_t* total, SArray* pColList) {
H
Haojun Liao 已提交
4225
  blockDataEnsureCapacity(pRes, numOfRows);
4226

H
Haojun Liao 已提交
4227 4228
  if (pColList == NULL) {  // data from other sources
    int32_t* colLen = (int32_t*)pData;
L
Liu Jicong 已提交
4229
    char*    pStart = pData + sizeof(int32_t) * numOfOutput;
H
Haojun Liao 已提交
4230

4231
    for (int32_t i = 0; i < numOfOutput; ++i) {
H
Haojun Liao 已提交
4232 4233 4234
      colLen[i] = htonl(colLen[i]);
      ASSERT(colLen[i] > 0);

4235
      SColumnInfoData* pColInfoData = taosArrayGet(pRes->pDataBlock, i);
H
Haojun Liao 已提交
4236 4237 4238
      if (IS_VAR_DATA_TYPE(pColInfoData->info.type)) {
        pColInfoData->varmeta.length = colLen[i];
        pColInfoData->varmeta.allocLen = colLen[i];
4239

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

wafwerar's avatar
wafwerar 已提交
4243
        pColInfoData->pData = taosMemoryMalloc(colLen[i]);
H
Haojun Liao 已提交
4244 4245 4246
      } else {
        memcpy(pColInfoData->nullbitmap, pStart, BitmapLen(numOfRows));
        pStart += BitmapLen(numOfRows);
4247
      }
H
Haojun Liao 已提交
4248 4249 4250

      memcpy(pColInfoData->pData, pStart, colLen[i]);
      pStart += colLen[i];
4251
    }
H
Haojun Liao 已提交
4252
  } else {  // extract data according to pColList
4253
    ASSERT(numOfOutput == taosArrayGetSize(pColList));
H
Haojun Liao 已提交
4254 4255

    // data from mnode
L
Liu Jicong 已提交
4256 4257 4258
    for (int32_t i = 0; i < numOfOutput; ++i) {
      for (int32_t j = 0; j < numOfOutput; ++j) {
        int16_t colIndex = *(int16_t*)taosArrayGet(pColList, j);
4259 4260
        if (colIndex - 1 == i) {
          SColumnInfoData* pColInfoData = taosArrayGet(pRes->pDataBlock, j);
4261

4262 4263 4264 4265 4266 4267 4268
          for (int32_t k = 0; k < numOfRows; ++k) {
            colDataAppend(pColInfoData, k, pData, false);
            pData += pColInfoData->info.bytes;
          }
          break;
        }
      }
4269
    }
4270
  }
4271

H
Haojun Liao 已提交
4272
  pRes->info.rows = numOfRows;
4273

4274
  int64_t el = taosGetTimestampUs() - startTs;
4275

H
Haojun Liao 已提交
4276 4277
  pLoadInfo->totalRows += numOfRows;
  pLoadInfo->totalSize += compLen;
4278

H
Haojun Liao 已提交
4279 4280 4281
  if (total != NULL) {
    *total += numOfRows;
  }
4282

H
Haojun Liao 已提交
4283
  pLoadInfo->totalElapsed += el;
4284 4285
  return TSDB_CODE_SUCCESS;
}
4286

L
Liu Jicong 已提交
4287 4288
static void* setAllSourcesCompleted(SOperatorInfo* pOperator, int64_t startTs) {
  SExchangeInfo* pExchangeInfo = pOperator->info;
4289
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
H
Haojun Liao 已提交
4290

L
Liu Jicong 已提交
4291
  int64_t              el = taosGetTimestampUs() - startTs;
H
Haojun Liao 已提交
4292 4293
  SLoadRemoteDataInfo* pLoadInfo = &pExchangeInfo->loadInfo;
  pLoadInfo->totalElapsed += el;
H
Haojun Liao 已提交
4294

4295
  size_t totalSources = taosArrayGetSize(pExchangeInfo->pSources);
L
Liu Jicong 已提交
4296 4297 4298
  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);
4299 4300 4301 4302 4303

  doSetOperatorCompleted(pOperator);
  return NULL;
}

L
Liu Jicong 已提交
4304 4305
static SSDataBlock* concurrentlyLoadRemoteDataImpl(SOperatorInfo* pOperator, SExchangeInfo* pExchangeInfo,
                                                   SExecTaskInfo* pTaskInfo) {
4306 4307 4308 4309 4310 4311 4312 4313 4314
  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);

4315
      if (pDataInfo->status == EX_SOURCE_DATA_EXHAUSTED) {
4316
        completed += 1;
H
Haojun Liao 已提交
4317 4318
        continue;
      }
4319

4320
      if (pDataInfo->status != EX_SOURCE_DATA_READY) {
4321 4322 4323
        continue;
      }

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

L
Liu Jicong 已提交
4327
      SSDataBlock*         pRes = pExchangeInfo->pResult;
H
Haojun Liao 已提交
4328
      SLoadRemoteDataInfo* pLoadInfo = &pExchangeInfo->loadInfo;
4329
      if (pRsp->numOfRows == 0) {
L
Liu Jicong 已提交
4330 4331
        qDebug("%s vgId:%d, taskID:0x%" PRIx64 " index:%d completed, rowsOfSource:%" PRIu64 ", totalRows:%" PRIu64
               " try next",
4332
               GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->taskId, i + 1, pDataInfo->totalRows,
H
Haojun Liao 已提交
4333
               pExchangeInfo->loadInfo.totalRows);
4334
        pDataInfo->status = EX_SOURCE_DATA_EXHAUSTED;
4335 4336 4337
        completed += 1;
        continue;
      }
H
Haojun Liao 已提交
4338

H
Haojun Liao 已提交
4339
      SRetrieveTableRsp* pTableRsp = pDataInfo->pRsp;
L
Liu Jicong 已提交
4340 4341 4342
      code =
          setSDataBlockFromFetchRsp(pExchangeInfo->pResult, pLoadInfo, pTableRsp->numOfRows, pTableRsp->data,
                                    pTableRsp->compLen, pOperator->numOfOutput, startTs, &pDataInfo->totalRows, NULL);
4343
      if (code != 0) {
4344 4345 4346
        goto _error;
      }

4347 4348 4349
      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 已提交
4350 4351
               GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->taskId, pRes->info.rows, pDataInfo->totalRows,
               pLoadInfo->totalRows, pLoadInfo->totalSize, i + 1, totalSources);
4352
        pDataInfo->status = EX_SOURCE_DATA_EXHAUSTED;
4353
      } else {
4354
        qDebug("%s fetch msg rsp from vgId:%d, taskId:0x%" PRIx64 " numOfRows:%d, totalRows:%" PRIu64 ", totalBytes:%" PRIu64,
H
Haojun Liao 已提交
4355 4356
               GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->taskId, pRes->info.rows, pLoadInfo->totalRows,
               pLoadInfo->totalSize);
4357 4358
      }

4359 4360
      if (pDataInfo->status != EX_SOURCE_DATA_EXHAUSTED) {
        pDataInfo->status = EX_SOURCE_DATA_NOT_READY;
4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379
        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 已提交
4380 4381 4382
static SSDataBlock* concurrentlyLoadRemoteData(SOperatorInfo* pOperator) {
  SExchangeInfo* pExchangeInfo = pOperator->info;
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
H
Haojun Liao 已提交
4383

H
Haojun Liao 已提交
4384 4385 4386
  if (pOperator->status == OP_RES_TO_RETURN) {
    return concurrentlyLoadRemoteDataImpl(pOperator, pExchangeInfo, pTaskInfo);
  }
4387

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

  // Asynchronously send all fetch requests to all sources.
L
Liu Jicong 已提交
4392
  for (int32_t i = 0; i < totalSources; ++i) {
4393 4394
    int32_t code = doSendFetchDataRequest(pExchangeInfo, pTaskInfo, i);
    if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
4395
      return NULL;
4396 4397 4398 4399
    }
  }

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

  tsem_wait(&pExchangeInfo->ready);
H
Haojun Liao 已提交
4404 4405
  pOperator->status = OP_RES_TO_RETURN;
  return concurrentlyLoadRemoteDataImpl(pOperator, pExchangeInfo, pTaskInfo);
4406 4407
}

L
Liu Jicong 已提交
4408 4409 4410
static int32_t prepareConcurrentlyLoad(SOperatorInfo* pOperator) {
  SExchangeInfo* pExchangeInfo = pOperator->info;
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
4411

L
Liu Jicong 已提交
4412
  size_t  totalSources = taosArrayGetSize(pExchangeInfo->pSources);
4413 4414 4415
  int64_t startTs = taosGetTimestampUs();

  // Asynchronously send all fetch requests to all sources.
L
Liu Jicong 已提交
4416
  for (int32_t i = 0; i < totalSources; ++i) {
4417 4418
    int32_t code = doSendFetchDataRequest(pExchangeInfo, pTaskInfo, i);
    if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
4419 4420
      pTaskInfo->code = code;
      return code;
4421 4422 4423 4424
    }
  }

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

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

H
Haojun Liao 已提交
4431
  return TSDB_CODE_SUCCESS;
4432 4433
}

L
Liu Jicong 已提交
4434 4435 4436
static SSDataBlock* seqLoadRemoteData(SOperatorInfo* pOperator) {
  SExchangeInfo* pExchangeInfo = pOperator->info;
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
4437

L
Liu Jicong 已提交
4438
  size_t  totalSources = taosArrayGetSize(pExchangeInfo->pSources);
4439
  int64_t startTs = taosGetTimestampUs();
4440

L
Liu Jicong 已提交
4441
  while (1) {
4442 4443
    if (pExchangeInfo->current >= totalSources) {
      return setAllSourcesCompleted(pOperator, startTs);
4444
    }
4445

4446 4447 4448
    doSendFetchDataRequest(pExchangeInfo, pTaskInfo, pExchangeInfo->current);
    tsem_wait(&pExchangeInfo->ready);

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

H
Haojun Liao 已提交
4452 4453 4454 4455 4456 4457 4458
    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 已提交
4459
    SRetrieveTableRsp*   pRsp = pDataInfo->pRsp;
H
Haojun Liao 已提交
4460
    SLoadRemoteDataInfo* pLoadInfo = &pExchangeInfo->loadInfo;
4461
    if (pRsp->numOfRows == 0) {
H
Haojun Liao 已提交
4462
      qDebug("%s vgId:%d, taskID:0x%" PRIx64 " %d of total completed, rowsOfSource:%" PRIu64 ", totalRows:%" PRIu64 " try next",
4463
             GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->taskId, pExchangeInfo->current + 1,
H
Haojun Liao 已提交
4464
             pDataInfo->totalRows, pLoadInfo->totalRows);
H
Haojun Liao 已提交
4465

4466
      pDataInfo->status = EX_SOURCE_DATA_EXHAUSTED;
4467 4468 4469
      pExchangeInfo->current += 1;
      continue;
    }
H
Haojun Liao 已提交
4470

L
Liu Jicong 已提交
4471
    SSDataBlock*       pRes = pExchangeInfo->pResult;
H
Haojun Liao 已提交
4472
    SRetrieveTableRsp* pTableRsp = pDataInfo->pRsp;
L
Liu Jicong 已提交
4473 4474 4475
    int32_t            code =
        setSDataBlockFromFetchRsp(pExchangeInfo->pResult, pLoadInfo, pTableRsp->numOfRows, pTableRsp->data,
                                  pTableRsp->compLen, pOperator->numOfOutput, startTs, &pDataInfo->totalRows, NULL);
4476 4477

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

4483
      pDataInfo->status = EX_SOURCE_DATA_EXHAUSTED;
4484 4485
      pExchangeInfo->current += 1;
    } else {
L
Liu Jicong 已提交
4486 4487 4488 4489
      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);
4490 4491 4492 4493
    }

    return pExchangeInfo->pResult;
  }
4494 4495
}

L
Liu Jicong 已提交
4496
static int32_t prepareLoadRemoteData(SOperatorInfo* pOperator) {
4497
  if (OPTR_IS_OPENED(pOperator)) {
H
Haojun Liao 已提交
4498 4499 4500
    return TSDB_CODE_SUCCESS;
  }

L
Liu Jicong 已提交
4501
  SExchangeInfo* pExchangeInfo = pOperator->info;
H
Haojun Liao 已提交
4502 4503 4504 4505 4506 4507 4508 4509 4510
  if (pExchangeInfo->seqLoadData) {
    // do nothing for sequentially load data
  } else {
    int32_t code = prepareConcurrentlyLoad(pOperator);
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }
  }

4511
  OPTR_SET_OPENED(pOperator);
H
Haojun Liao 已提交
4512 4513 4514
  return TSDB_CODE_SUCCESS;
}

L
Liu Jicong 已提交
4515 4516 4517
static SSDataBlock* doLoadRemoteData(SOperatorInfo* pOperator, bool* newgroup) {
  SExchangeInfo* pExchangeInfo = pOperator->info;
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
4518

4519 4520
  pTaskInfo->code = pOperator->_openFn(pOperator);
  if (pTaskInfo->code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
4521 4522
    return NULL;
  }
4523

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

4527
  if (pOperator->status == OP_EXEC_DONE) {
L
Liu Jicong 已提交
4528 4529 4530
    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);
4531 4532 4533 4534
    return NULL;
  }

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

4536 4537 4538
  if (pExchangeInfo->seqLoadData) {
    return seqLoadRemoteData(pOperator);
  } else {
H
Haojun Liao 已提交
4539
    return concurrentlyLoadRemoteData(pOperator);
4540
  }
H
Haojun Liao 已提交
4541

4542
#if 0
H
Haojun Liao 已提交
4543
  _error:
wafwerar's avatar
wafwerar 已提交
4544 4545
  taosMemoryFreeClear(pMsg);
  taosMemoryFreeClear(pMsgSendInfo);
H
Haojun Liao 已提交
4546 4547 4548

  terrno = pTaskInfo->code;
  return NULL;
4549
#endif
H
Haojun Liao 已提交
4550
}
4551

H
Haojun Liao 已提交
4552
static int32_t initDataSource(int32_t numOfSources, SExchangeInfo* pInfo) {
4553
  pInfo->pSourceDataInfo = taosArrayInit(numOfSources, sizeof(SSourceDataInfo));
H
Haojun Liao 已提交
4554 4555
  if (pInfo->pSourceDataInfo == NULL) {
    return TSDB_CODE_OUT_OF_MEMORY;
4556 4557
  }

L
Liu Jicong 已提交
4558
  for (int32_t i = 0; i < numOfSources; ++i) {
4559
    SSourceDataInfo dataInfo = {0};
H
Haojun Liao 已提交
4560
    dataInfo.status = EX_SOURCE_DATA_NOT_READY;
L
Liu Jicong 已提交
4561 4562
    dataInfo.pEx = pInfo;
    dataInfo.index = i;
4563

H
Haojun Liao 已提交
4564 4565 4566 4567 4568 4569 4570 4571 4572 4573
    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 已提交
4574
SOperatorInfo* createExchangeOperatorInfo(const SNodeList* pSources, SSDataBlock* pBlock, SExecTaskInfo* pTaskInfo) {
L
Liu Jicong 已提交
4575
  SExchangeInfo* pInfo = taosMemoryCalloc(1, sizeof(SExchangeInfo));
wafwerar's avatar
wafwerar 已提交
4576
  SOperatorInfo* pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
4577 4578

  if (pInfo == NULL || pOperator == NULL) {
wafwerar's avatar
wafwerar 已提交
4579 4580
    taosMemoryFreeClear(pInfo);
    taosMemoryFreeClear(pOperator);
H
Haojun Liao 已提交
4581 4582
    terrno = TSDB_CODE_QRY_OUT_OF_MEMORY;
    return NULL;
H
Haojun Liao 已提交
4583 4584
  }

H
Haojun Liao 已提交
4585
  size_t numOfSources = LIST_LENGTH(pSources);
H
Haojun Liao 已提交
4586
  pInfo->pSources = taosArrayInit(numOfSources, sizeof(SDownstreamSourceNode));
H
Haojun Liao 已提交
4587 4588 4589
  pInfo->pSourceDataInfo = taosArrayInit(numOfSources, sizeof(SSourceDataInfo));
  if (pInfo->pSourceDataInfo == NULL || pInfo->pSources == NULL) {
    goto _error;
H
Haojun Liao 已提交
4590 4591
  }

L
Liu Jicong 已提交
4592 4593
  for (int32_t i = 0; i < numOfSources; ++i) {
    SNodeListNode* pNode = nodesListGetNode((SNodeList*)pSources, i);
H
Haojun Liao 已提交
4594 4595
    taosArrayPush(pInfo->pSources, pNode);
  }
4596

H
Haojun Liao 已提交
4597 4598 4599
  int32_t code = initDataSource(numOfSources, pInfo);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
4600
  }
H
Haojun Liao 已提交
4601

L
Liu Jicong 已提交
4602 4603
  size_t size = pBlock->info.numOfCols;
  pInfo->pResult = pBlock;
4604 4605 4606
  pInfo->seqLoadData = true;

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

L
Liu Jicong 已提交
4608
  pOperator->name = "ExchangeOperator";
X
Xiaoyu Wang 已提交
4609
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_EXCHANGE;
4610
  pOperator->blockingOptr = false;
L
Liu Jicong 已提交
4611 4612 4613 4614 4615 4616 4617
  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;
4618

S
Shengliang Guan 已提交
4619
#if 1
L
Liu Jicong 已提交
4620
  {  // todo refactor
H
Haojun Liao 已提交
4621 4622 4623
    SRpcInit rpcInit;
    memset(&rpcInit, 0, sizeof(rpcInit));
    rpcInit.localPort = 0;
H
Haojun Liao 已提交
4624
    rpcInit.label = "EX";
H
Haojun Liao 已提交
4625
    rpcInit.numOfThreads = 1;
S
Shengliang Guan 已提交
4626
    rpcInit.cfp = qProcessFetchRsp;
S
Shengliang Guan 已提交
4627
    rpcInit.sessions = tsMaxConnections;
H
Haojun Liao 已提交
4628
    rpcInit.connType = TAOS_CONN_CLIENT;
L
Liu Jicong 已提交
4629
    rpcInit.user = (char*)"root";
S
Shengliang Guan 已提交
4630
    rpcInit.idleTime = tsShellActivityTimer * 1000;
H
Haojun Liao 已提交
4631
    rpcInit.ckey = "key";
S
Shengliang Guan 已提交
4632
    rpcInit.spi = 1;
L
Liu Jicong 已提交
4633
    rpcInit.secret = (char*)"dcc5bed04851fec854c035b2e40263b6";
H
Haojun Liao 已提交
4634 4635 4636

    pInfo->pTransporter = rpcOpen(&rpcInit);
    if (pInfo->pTransporter == NULL) {
L
Liu Jicong 已提交
4637
      return NULL;  // todo
H
Haojun Liao 已提交
4638 4639
    }
  }
S
Shengliang 已提交
4640
#endif
4641

4642
  return pOperator;
H
Haojun Liao 已提交
4643

L
Liu Jicong 已提交
4644
_error:
H
Haojun Liao 已提交
4645
  if (pInfo != NULL) {
H
Haojun Liao 已提交
4646
    destroyExchangeOperatorInfo(pInfo, numOfSources);
H
Haojun Liao 已提交
4647 4648
  }

wafwerar's avatar
wafwerar 已提交
4649 4650
  taosMemoryFreeClear(pInfo);
  taosMemoryFreeClear(pOperator);
H
Haojun Liao 已提交
4651
  pTaskInfo->code = TSDB_CODE_OUT_OF_MEMORY;
H
Haojun Liao 已提交
4652
  return NULL;
4653 4654
}

H
Haojun Liao 已提交
4655
SSDataBlock* createResultDataBlock(const SArray* pExprInfo) {
wafwerar's avatar
wafwerar 已提交
4656
  SSDataBlock* pResBlock = taosMemoryCalloc(1, sizeof(SSDataBlock));
H
Haojun Liao 已提交
4657 4658 4659 4660 4661 4662 4663 4664
  if (pResBlock == NULL) {
    return NULL;
  }

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

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

H
Haojun Liao 已提交
4669
    SResSchema* pSchema = &p->base.resSchema;
L
Liu Jicong 已提交
4670
    colInfoData.info.type = pSchema->type;
H
Haojun Liao 已提交
4671 4672
    colInfoData.info.colId = pSchema->colId;
    colInfoData.info.bytes = pSchema->bytes;
H
Haojun Liao 已提交
4673 4674
    colInfoData.info.scale = pSchema->scale;
    colInfoData.info.precision = pSchema->precision;
H
Haojun Liao 已提交
4675 4676 4677 4678 4679 4680
    taosArrayPush(pResult, &colInfoData);
  }

  return pResBlock;
}

L
Liu Jicong 已提交
4681 4682
static int32_t doInitAggInfoSup(SAggSupporter* pAggSup, SqlFunctionCtx* pCtx, int32_t numOfOutput, const char* pKey);
static void    cleanupAggSup(SAggSupporter* pAggSup);
4683

4684
static void destroySortedMergeOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
4685
  SSortedMergeOperatorInfo* pInfo = (SSortedMergeOperatorInfo*)param;
H
Haojun Liao 已提交
4686
  taosArrayDestroy(pInfo->pSortInfo);
4687 4688 4689
  taosArrayDestroy(pInfo->groupInfo);

  if (pInfo->pSortHandle != NULL) {
H
Haojun Liao 已提交
4690
    tsortDestroySortHandle(pInfo->pSortHandle);
4691 4692
  }

H
Haojun Liao 已提交
4693
  blockDataDestroy(pInfo->binfo.pRes);
H
Haojun Liao 已提交
4694
  cleanupAggSup(&pInfo->aggSup);
4695
}
H
Haojun Liao 已提交
4696

4697
static void destroySlimitOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
4698
  SSLimitOperatorInfo* pInfo = (SSLimitOperatorInfo*)param;
4699
  taosArrayDestroy(pInfo->orderColumnList);
H
Haojun Liao 已提交
4700
  pInfo->pRes = blockDataDestroy(pInfo->pRes);
wafwerar's avatar
wafwerar 已提交
4701
  taosMemoryFreeClear(pInfo->prevRow);
4702 4703
}

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

X
Xiaoyu Wang 已提交
4707
  *dst = *src;
4708

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

L
Liu Jicong 已提交
4713 4714 4715 4716
  //  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 已提交
4717
}
4718

4719 4720
static SExprInfo* exprArrayDup(SArray* pExprList) {
  size_t numOfOutput = taosArrayGetSize(pExprList);
4721

wafwerar's avatar
wafwerar 已提交
4722
  SExprInfo* p = taosMemoryCalloc(numOfOutput, sizeof(SExprInfo));
4723 4724
  for (int32_t i = 0; i < numOfOutput; ++i) {
    SExprInfo* pExpr = taosArrayGetP(pExprList, i);
H
Haojun Liao 已提交
4725
    assignExprInfo(&p[i], pExpr);
4726 4727
  }

H
Haojun Liao 已提交
4728 4729
  return p;
}
4730

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

H
Haojun Liao 已提交
4736
    bool isNull = tsortIsNullVal(pTupleHandle, i);
H
Haojun Liao 已提交
4737 4738 4739
    if (isNull) {
      colDataAppend(pColInfo, pBlock->info.rows, NULL, true);
    } else {
H
Haojun Liao 已提交
4740
      char* pData = tsortGetValue(pTupleHandle, i);
H
Haojun Liao 已提交
4741 4742
      colDataAppend(pColInfo, pBlock->info.rows, pData, false);
    }
4743 4744
  }

4745 4746
  pBlock->info.rows += 1;
}
4747

H
Haojun Liao 已提交
4748
SSDataBlock* getSortedBlockData(SSortHandle* pHandle, SSDataBlock* pDataBlock, int32_t capacity) {
4749
  blockDataCleanup(pDataBlock);
4750

L
Liu Jicong 已提交
4751
  while (1) {
H
Haojun Liao 已提交
4752
    STupleHandle* pTupleHandle = tsortNextTuple(pHandle);
4753 4754 4755
    if (pTupleHandle == NULL) {
      break;
    }
4756

4757 4758 4759
    appendOneRowToDataBlock(pDataBlock, pTupleHandle);
    if (pDataBlock->info.rows >= capacity) {
      return pDataBlock;
H
Haojun Liao 已提交
4760 4761
    }
  }
4762

L
Liu Jicong 已提交
4763
  return (pDataBlock->info.rows > 0) ? pDataBlock : NULL;
4764
}
4765

4766
SSDataBlock* loadNextDataBlock(void* param) {
L
Liu Jicong 已提交
4767 4768
  SOperatorInfo* pOperator = (SOperatorInfo*)param;
  bool           newgroup = false;
H
Haojun Liao 已提交
4769
  return pOperator->getNextFn(pOperator, &newgroup);
4770 4771
}

L
Liu Jicong 已提交
4772
static bool needToMerge(SSDataBlock* pBlock, SArray* groupInfo, char** buf, int32_t rowIndex) {
4773 4774 4775 4776
  size_t size = taosArrayGetSize(groupInfo);
  if (size == 0) {
    return true;
  }
4777

4778 4779
  for (int32_t i = 0; i < size; ++i) {
    int32_t* index = taosArrayGet(groupInfo, i);
4780

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

4784 4785 4786
    if ((isNull && buf[i] != NULL) || (!isNull && buf[i] == NULL)) {
      return false;
    }
4787

4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800
    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;
      }
4801 4802 4803
    }
  }

4804
  return 0;
4805 4806
}

L
Liu Jicong 已提交
4807 4808 4809
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
4810
    pCtx[j].startRow = rowIndex;
4811 4812
  }

4813 4814
  for (int32_t j = 0; j < numOfExpr; ++j) {
    int32_t functionId = pCtx[j].functionId;
L
Liu Jicong 已提交
4815 4816 4817 4818 4819 4820 4821 4822 4823
    //    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]);
    //    }
4824
  }
4825
}
4826

L
Liu Jicong 已提交
4827 4828
static void doFinalizeResultImpl(SqlFunctionCtx* pCtx, int32_t numOfExpr) {
  for (int32_t j = 0; j < numOfExpr; ++j) {
4829 4830 4831 4832
    int32_t functionId = pCtx[j].functionId;
    //    if (functionId == FUNC_TAG_DUMMY || functionId == FUNC_TS_DUMMY) {
    //      continue;
    //    }
4833

4834 4835 4836 4837
    //    if (functionId < 0) {
    //      SUdfInfo* pUdfInfo = taosArrayGet(pInfo->udfInfo, -1 * functionId - 1);
    //      doInvokeUdf(pUdfInfo, &pCtx[j], 0, TSDB_UDF_FUNC_FINALIZE);
    //    } else {
H
Haojun Liao 已提交
4838
    pCtx[j].fpSet.finalize(&pCtx[j]);
4839 4840
  }
}
4841

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

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

4849 4850 4851
    char* data = colDataGetData(pColInfo, rowIndex);
    memcpy(rowColData[i], data, colDataGetLength(pColInfo, rowIndex));
  }
4852

4853 4854
  return true;
}
4855

4856 4857
static void doMergeImpl(SOperatorInfo* pOperator, int32_t numOfExpr, SSDataBlock* pBlock) {
  SSortedMergeOperatorInfo* pInfo = pOperator->info;
4858

4859
  SqlFunctionCtx* pCtx = pInfo->binfo.pCtx;
L
Liu Jicong 已提交
4860
  for (int32_t i = 0; i < pBlock->info.numOfCols; ++i) {
4861 4862
    pCtx[i].size = 1;
  }
4863

L
Liu Jicong 已提交
4864
  for (int32_t i = 0; i < pBlock->info.rows; ++i) {
4865 4866 4867 4868 4869 4870 4871 4872 4873
    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 已提交
4874
        int32_t numOfRows = getNumOfResult(pInfo->binfo.pCtx, pOperator->numOfOutput, NULL);
4875
        //        setTagValueForMultipleRows(pCtx, pOperator->numOfOutput, numOfRows);
4876

4877
        // TODO check for available buffer;
H
Haojun Liao 已提交
4878

4879 4880 4881 4882 4883
        // next group info data
        pInfo->binfo.pRes->info.rows += numOfRows;
        for (int32_t j = 0; j < numOfExpr; ++j) {
          if (pCtx[j].functionId < 0) {
            continue;
4884
          }
4885

H
Haojun Liao 已提交
4886
          pCtx[j].fpSet.process(&pCtx[j]);
4887
        }
4888 4889 4890

        doMergeResultImpl(pInfo, pCtx, numOfExpr, i);
        pInfo->hasGroupVal = saveCurrentTuple(pInfo->groupVal, pInfo->groupInfo, pBlock, i);
H
Haojun Liao 已提交
4891
      }
4892 4893 4894 4895
    }
  }
}

4896 4897
static SSDataBlock* doMerge(SOperatorInfo* pOperator) {
  SSortedMergeOperatorInfo* pInfo = pOperator->info;
L
Liu Jicong 已提交
4898
  SSortHandle*              pHandle = pInfo->pSortHandle;
4899

4900 4901 4902
  SSDataBlock* pDataBlock = createOneDataBlock(pInfo->binfo.pRes);
  blockDataEnsureCapacity(pDataBlock, pInfo->binfo.capacity);

L
Liu Jicong 已提交
4903
  while (1) {
4904
    blockDataCleanup(pDataBlock);
4905
    while (1) {
H
Haojun Liao 已提交
4906
      STupleHandle* pTupleHandle = tsortNextTuple(pHandle);
4907 4908
      if (pTupleHandle == NULL) {
        break;
4909
      }
4910

4911 4912 4913 4914 4915
      // build datablock for merge for one group
      appendOneRowToDataBlock(pDataBlock, pTupleHandle);
      if (pDataBlock->info.rows >= pInfo->binfo.capacity) {
        break;
      }
4916
    }
4917

4918 4919 4920
    if (pDataBlock->info.rows == 0) {
      break;
    }
4921

4922
    setInputDataBlock(pOperator, pInfo->binfo.pCtx, pDataBlock, TSDB_ORDER_ASC);
L
Liu Jicong 已提交
4923 4924
    //  updateOutputBuf(&pInfo->binfo, &pAggInfo->bufCapacity, pBlock->info.rows * pAggInfo->resultRowFactor,
    //  pOperator->pRuntimeEnv, true);
4925 4926 4927
    doMergeImpl(pOperator, pOperator->numOfOutput, pDataBlock);
    // flush to tuple store, and after all data have been handled, return to upstream node or sink node
  }
4928

4929
  doFinalizeResultImpl(pInfo->binfo.pCtx, pOperator->numOfOutput);
H
Haojun Liao 已提交
4930
  int32_t numOfRows = getNumOfResult(pInfo->binfo.pCtx, pOperator->numOfOutput, NULL);
4931
  //        setTagValueForMultipleRows(pCtx, pOperator->numOfOutput, numOfRows);
4932

4933
  // TODO check for available buffer;
4934

4935 4936
  // next group info data
  pInfo->binfo.pRes->info.rows += numOfRows;
L
Liu Jicong 已提交
4937
  return (pInfo->binfo.pRes->info.rows > 0) ? pInfo->binfo.pRes : NULL;
4938
}
4939

L
Liu Jicong 已提交
4940
static SSDataBlock* doSortedMerge(SOperatorInfo* pOperator, bool* newgroup) {
4941 4942
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
4943 4944
  }

L
Liu Jicong 已提交
4945
  SExecTaskInfo*            pTaskInfo = pOperator->pTaskInfo;
4946
  SSortedMergeOperatorInfo* pInfo = pOperator->info;
H
Haojun Liao 已提交
4947
  if (pOperator->status == OP_RES_TO_RETURN) {
H
Haojun Liao 已提交
4948
    return getSortedBlockData(pInfo->pSortHandle, pInfo->binfo.pRes, pInfo->binfo.capacity);
4949 4950
  }

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

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

L
Liu Jicong 已提交
4957
  for (int32_t i = 0; i < pOperator->numOfDownstream; ++i) {
wafwerar's avatar
wafwerar 已提交
4958
    SGenericSource* ps = taosMemoryCalloc(1, sizeof(SGenericSource));
H
Haojun Liao 已提交
4959
    ps->param = pOperator->pDownstream[i];
H
Haojun Liao 已提交
4960
    tsortAddSource(pInfo->pSortHandle, ps);
4961 4962
  }

H
Haojun Liao 已提交
4963
  int32_t code = tsortOpen(pInfo->pSortHandle);
4964
  if (code != TSDB_CODE_SUCCESS) {
4965
    longjmp(pTaskInfo->env, terrno);
4966 4967
  }

H
Haojun Liao 已提交
4968
  pOperator->status = OP_RES_TO_RETURN;
4969
  return doMerge(pOperator);
4970
}
4971

L
Liu Jicong 已提交
4972 4973
static int32_t initGroupCol(SExprInfo* pExprInfo, int32_t numOfCols, SArray* pGroupInfo,
                            SSortedMergeOperatorInfo* pInfo) {
4974 4975
  if (pGroupInfo == NULL || taosArrayGetSize(pGroupInfo) == 0) {
    return 0;
H
Haojun Liao 已提交
4976 4977
  }

4978 4979 4980 4981 4982 4983 4984 4985
  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 已提交
4986 4987
  size_t numOfGroupCol = taosArrayGetSize(pInfo->groupInfo);
  for (int32_t i = 0; i < numOfGroupCol; ++i) {
4988
    SColumn* pCol = taosArrayGet(pGroupInfo, i);
L
Liu Jicong 已提交
4989
    for (int32_t j = 0; j < numOfCols; ++j) {
H
Haojun Liao 已提交
4990
      SExprInfo* pe = &pExprInfo[j];
H
Haojun Liao 已提交
4991
      if (pe->base.resSchema.colId == pCol->colId) {
4992 4993
        taosArrayPush(plist, pCol);
        taosArrayPush(pInfo->groupInfo, &j);
H
Haojun Liao 已提交
4994
        len += pCol->bytes;
4995 4996
        break;
      }
H
Haojun Liao 已提交
4997 4998 4999
    }
  }

5000
  ASSERT(taosArrayGetSize(pGroupInfo) == taosArrayGetSize(plist));
H
Haojun Liao 已提交
5001

wafwerar's avatar
wafwerar 已提交
5002
  pInfo->groupVal = taosMemoryCalloc(1, (POINTER_BYTES * numOfGroupCol + len));
5003 5004 5005 5006
  if (pInfo->groupVal == NULL) {
    taosArrayDestroy(plist);
    return TSDB_CODE_OUT_OF_MEMORY;
  }
H
Haojun Liao 已提交
5007

5008
  int32_t offset = 0;
L
Liu Jicong 已提交
5009 5010
  char*   start = (char*)(pInfo->groupVal + (POINTER_BYTES * numOfGroupCol));
  for (int32_t i = 0; i < numOfGroupCol; ++i) {
5011 5012
    pInfo->groupVal[i] = start + offset;
    SColumn* pCol = taosArrayGet(plist, i);
H
Haojun Liao 已提交
5013
    offset += pCol->bytes;
5014
  }
H
Haojun Liao 已提交
5015

5016
  taosArrayDestroy(plist);
H
Haojun Liao 已提交
5017

5018 5019
  return TSDB_CODE_SUCCESS;
}
H
Haojun Liao 已提交
5020

L
Liu Jicong 已提交
5021 5022 5023
SOperatorInfo* createSortedMergeOperatorInfo(SOperatorInfo** downstream, int32_t numOfDownstream, SExprInfo* pExprInfo,
                                             int32_t num, SArray* pSortInfo, SArray* pGroupInfo,
                                             SExecTaskInfo* pTaskInfo) {
wafwerar's avatar
wafwerar 已提交
5024
  SSortedMergeOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SSortedMergeOperatorInfo));
L
Liu Jicong 已提交
5025
  SOperatorInfo*            pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
5026
  if (pInfo == NULL || pOperator == NULL) {
5027
    goto _error;
5028
  }
H
Haojun Liao 已提交
5029

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

5033 5034 5035
  if (pInfo->binfo.pCtx == NULL || pInfo->binfo.pRes == NULL) {
    goto _error;
  }
H
Haojun Liao 已提交
5036

H
Haojun Liao 已提交
5037
  int32_t code = doInitAggInfoSup(&pInfo->aggSup, pInfo->binfo.pCtx, num, pTaskInfo->id.str);
5038 5039 5040
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
H
Haojun Liao 已提交
5041

H
Haojun Liao 已提交
5042
  setFunctionResultOutput(&pInfo->binfo, &pInfo->aggSup, MAIN_SCAN, pTaskInfo);
H
Haojun Liao 已提交
5043
  code = initGroupCol(pExprInfo, num, pGroupInfo, pInfo);
5044 5045 5046
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
H
Haojun Liao 已提交
5047

L
Liu Jicong 已提交
5048 5049 5050 5051 5052
  //  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 已提交
5053

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

L
Liu Jicong 已提交
5056
  pOperator->name = "SortedMerge";
X
Xiaoyu Wang 已提交
5057
  // pOperator->operatorType = OP_SortedMerge;
5058
  pOperator->blockingOptr = true;
L
Liu Jicong 已提交
5059 5060 5061 5062
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
  pOperator->numOfOutput = num;
  pOperator->pExpr = pExprInfo;
H
Haojun Liao 已提交
5063

L
Liu Jicong 已提交
5064 5065 5066
  pOperator->pTaskInfo = pTaskInfo;
  pOperator->getNextFn = doSortedMerge;
  pOperator->closeFn = destroySortedMergeOperatorInfo;
H
Haojun Liao 已提交
5067

5068 5069 5070
  code = appendDownstream(pOperator, downstream, numOfDownstream);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
5071
  }
H
Haojun Liao 已提交
5072

5073
  return pOperator;
H
Haojun Liao 已提交
5074

L
Liu Jicong 已提交
5075
_error:
5076
  if (pInfo != NULL) {
H
Haojun Liao 已提交
5077
    destroySortedMergeOperatorInfo(pInfo, num);
H
Haojun Liao 已提交
5078 5079
  }

wafwerar's avatar
wafwerar 已提交
5080 5081
  taosMemoryFreeClear(pInfo);
  taosMemoryFreeClear(pOperator);
5082 5083
  terrno = TSDB_CODE_QRY_OUT_OF_MEMORY;
  return NULL;
H
Haojun Liao 已提交
5084 5085
}

L
Liu Jicong 已提交
5086
static SSDataBlock* doSort(SOperatorInfo* pOperator, bool* newgroup) {
5087 5088 5089 5090
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

L
Liu Jicong 已提交
5091
  SExecTaskInfo*     pTaskInfo = pOperator->pTaskInfo;
H
Haojun Liao 已提交
5092 5093
  SSortOperatorInfo* pInfo = pOperator->info;

H
Haojun Liao 已提交
5094
  if (pOperator->status == OP_RES_TO_RETURN) {
H
Haojun Liao 已提交
5095
    return getSortedBlockData(pInfo->pSortHandle, pInfo->pDataBlock, pInfo->numOfRowsInRes);
H
Haojun Liao 已提交
5096 5097
  }

5098
  int32_t numOfBufPage = pInfo->sortBufSize / pInfo->bufPageSize;
L
Liu Jicong 已提交
5099
  pInfo->pSortHandle = tsortCreateSortHandle(pInfo->pSortInfo, SORT_SINGLESOURCE_SORT, pInfo->bufPageSize, numOfBufPage,
H
Haojun Liao 已提交
5100
                                             pInfo->pDataBlock, pTaskInfo->id.str);
5101

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

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

H
Haojun Liao 已提交
5108
  int32_t code = tsortOpen(pInfo->pSortHandle);
5109
  if (code != TSDB_CODE_SUCCESS) {
5110
    longjmp(pTaskInfo->env, terrno);
5111
  }
5112

H
Haojun Liao 已提交
5113
  pOperator->status = OP_RES_TO_RETURN;
H
Haojun Liao 已提交
5114
  return getSortedBlockData(pInfo->pSortHandle, pInfo->pDataBlock, pInfo->numOfRowsInRes);
5115 5116
}

H
Haojun Liao 已提交
5117
SOperatorInfo* createSortOperatorInfo(SOperatorInfo* downstream, SSDataBlock* pResBlock, SArray* pSortInfo, SExecTaskInfo* pTaskInfo) {
H
Haojun Liao 已提交
5118
  SSortOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SSortOperatorInfo));
L
Liu Jicong 已提交
5119
  SOperatorInfo*     pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
5120
  if (pInfo == NULL || pOperator == NULL) {
H
Haojun Liao 已提交
5121
    goto _error;
H
Haojun Liao 已提交
5122
  }
5123

H
Haojun Liao 已提交
5124 5125 5126 5127 5128
  pInfo->sortBufSize      = 1024 * 16;  // TODO dynamic set the available sort buffer
  pInfo->bufPageSize      = 1024;
  pInfo->numOfRowsInRes   = 1024;
  pInfo->pDataBlock       = pResBlock;
  pInfo->pSortInfo        = pSortInfo;
H
Haojun Liao 已提交
5129

H
Haojun Liao 已提交
5130
  pOperator->name         = "SortOperator";
L
Liu Jicong 已提交
5131 5132
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_SORT;
  pOperator->blockingOptr = true;
H
Haojun Liao 已提交
5133 5134
  pOperator->status       = OP_NOT_OPENED;
  pOperator->info         = pInfo;
5135

H
Haojun Liao 已提交
5136 5137 5138
  pOperator->pTaskInfo    = pTaskInfo;
  pOperator->getNextFn    = doSort;
  pOperator->closeFn      = destroyOrderOperatorInfo;
5139

5140
  int32_t code = appendDownstream(pOperator, &downstream, 1);
5141
  return pOperator;
H
Haojun Liao 已提交
5142 5143 5144 5145 5146 5147

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

L
Liu Jicong 已提交
5150
static int32_t getTableScanOrder(STableScanInfo* pTableScanInfo) { return pTableScanInfo->order; }
5151 5152

// this is a blocking operator
L
Liu Jicong 已提交
5153
static int32_t doOpenAggregateOptr(SOperatorInfo* pOperator) {
H
Haojun Liao 已提交
5154 5155
  if (OPTR_IS_OPENED(pOperator)) {
    return TSDB_CODE_SUCCESS;
5156 5157 5158
  }

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

H
Haojun Liao 已提交
5161
  int32_t        order = TSDB_ORDER_ASC;
H
Haojun Liao 已提交
5162
  SOperatorInfo* downstream = pOperator->pDownstream[0];
5163

H
Haojun Liao 已提交
5164 5165
  bool newgroup = true;
  while (1) {
H
Haojun Liao 已提交
5166
    publishOperatorProfEvent(downstream, QUERY_PROF_BEFORE_OPERATOR_EXEC);
H
Haojun Liao 已提交
5167
    SSDataBlock* pBlock = downstream->getNextFn(downstream, &newgroup);
H
Haojun Liao 已提交
5168
    publishOperatorProfEvent(downstream, QUERY_PROF_AFTER_OPERATOR_EXEC);
5169 5170 5171 5172

    if (pBlock == NULL) {
      break;
    }
H
Haojun Liao 已提交
5173 5174 5175
    //    if (pAggInfo->current != NULL) {
    //      setTagValue(pOperator, pAggInfo->current->pTable, pInfo->pCtx, pOperator->numOfOutput);
    //    }
5176 5177 5178

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

5182
  finalizeQueryResult(pInfo->pCtx, pOperator->numOfOutput);
H
Haojun Liao 已提交
5183 5184 5185 5186 5187

  OPTR_SET_OPENED(pOperator);
  return TSDB_CODE_SUCCESS;
}

L
Liu Jicong 已提交
5188 5189
static SSDataBlock* getAggregateResult(SOperatorInfo* pOperator, bool* newgroup) {
  SAggOperatorInfo* pAggInfo = pOperator->info;
H
Haojun Liao 已提交
5190 5191 5192 5193 5194 5195
  SOptrBasicInfo*   pInfo = &pAggInfo->binfo;

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

L
Liu Jicong 已提交
5196
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
H
Haojun Liao 已提交
5197 5198 5199 5200 5201
  pTaskInfo->code = pOperator->_openFn(pOperator);
  if (pTaskInfo->code != TSDB_CODE_SUCCESS) {
    return NULL;
  }

H
Haojun Liao 已提交
5202
  getNumOfResult(pInfo->pCtx, pOperator->numOfOutput, pInfo->pRes);
H
Haojun Liao 已提交
5203
  doSetOperatorCompleted(pOperator);
5204

L
Liu Jicong 已提交
5205
  return (blockDataGetNumOfRows(pInfo->pRes) != 0) ? pInfo->pRes : NULL;
5206 5207
}

L
Liu Jicong 已提交
5208 5209 5210
static void aggEncodeResultRow(SOperatorInfo* pOperator, char** result, int32_t* length) {
  SAggOperatorInfo* pAggInfo = pOperator->info;
  SAggSupporter*    pSup = &pAggInfo->aggSup;
wmmhello's avatar
wmmhello 已提交
5211 5212

  int32_t size = taosHashGetSize(pSup->pResultRowHashTable);
L
Liu Jicong 已提交
5213
  size_t  keyLen = POINTER_BYTES;  // estimate the key length
wmmhello's avatar
wmmhello 已提交
5214
  int32_t totalSize = sizeof(int32_t) + size * (sizeof(int32_t) + keyLen + sizeof(int32_t) + pSup->resultRowSize);
wafwerar's avatar
wafwerar 已提交
5215
  *result = taosMemoryCalloc(1, totalSize);
L
Liu Jicong 已提交
5216
  if (*result == NULL) {
wmmhello's avatar
wmmhello 已提交
5217 5218 5219 5220 5221
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return;
  }
  *(int32_t*)(*result) = size;
  int32_t offset = sizeof(int32_t);
L
Liu Jicong 已提交
5222
  void*   pIter = taosHashIterate(pSup->pResultRowHashTable, NULL);
wmmhello's avatar
wmmhello 已提交
5223
  while (pIter) {
L
Liu Jicong 已提交
5224 5225
    void*        key = taosHashGetKey(pIter, &keyLen);
    SResultRow** p1 = (SResultRow**)pIter;
wmmhello's avatar
wmmhello 已提交
5226 5227 5228

    // recalculate the result size
    int32_t realTotalSize = offset + sizeof(int32_t) + keyLen + sizeof(int32_t) + pSup->resultRowSize;
L
Liu Jicong 已提交
5229 5230 5231
    if (realTotalSize > totalSize) {
      char* tmp = taosMemoryRealloc(*result, realTotalSize);
      if (tmp == NULL) {
wmmhello's avatar
wmmhello 已提交
5232
        terrno = TSDB_CODE_OUT_OF_MEMORY;
wafwerar's avatar
wafwerar 已提交
5233
        taosMemoryFree(*result);
wmmhello's avatar
wmmhello 已提交
5234 5235
        *result = NULL;
        return;
L
Liu Jicong 已提交
5236
      } else {
wmmhello's avatar
wmmhello 已提交
5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254
        *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 已提交
5255
  if (length) {
wmmhello's avatar
wmmhello 已提交
5256 5257 5258 5259 5260
    *length = offset;
  }
  return;
}

L
Liu Jicong 已提交
5261 5262
static bool aggDecodeResultRow(SOperatorInfo* pOperator, char* result, int32_t length) {
  if (!result || length <= 0) {
wmmhello's avatar
wmmhello 已提交
5263 5264 5265
    return false;
  }

L
Liu Jicong 已提交
5266 5267 5268
  SAggOperatorInfo* pAggInfo = pOperator->info;
  SAggSupporter*    pSup = &pAggInfo->aggSup;
  SOptrBasicInfo*   pInfo = &pAggInfo->binfo;
wmmhello's avatar
wmmhello 已提交
5269 5270 5271 5272 5273

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

  int32_t offset = sizeof(int32_t);
L
Liu Jicong 已提交
5274
  while (count-- > 0 && length > offset) {
wmmhello's avatar
wmmhello 已提交
5275 5276 5277
    int32_t keyLen = *(int32_t*)(result + offset);
    offset += sizeof(int32_t);

L
Liu Jicong 已提交
5278 5279 5280
    uint64_t    tableGroupId = *(uint64_t*)(result + offset);
    SResultRow* resultRow = getNewResultRow_rv(pSup->pResultBuf, tableGroupId, pSup->resultRowSize);
    if (!resultRow) {
wmmhello's avatar
wmmhello 已提交
5281 5282 5283 5284 5285 5286 5287 5288
      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 已提交
5289
    if (valueLen != pSup->resultRowSize) {
wmmhello's avatar
wmmhello 已提交
5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301
      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 已提交
5302 5303
    pInfo->resultRowInfo.pPosition[pInfo->resultRowInfo.size++] =
        (SResultRowPosition){.pageId = resultRow->pageId, .offset = resultRow->offset};
wmmhello's avatar
wmmhello 已提交
5304 5305
  }

L
Liu Jicong 已提交
5306
  if (offset != length) {
wmmhello's avatar
wmmhello 已提交
5307 5308 5309 5310 5311 5312
    terrno = TSDB_CODE_TSC_INVALID_INPUT;
    return false;
  }
  return true;
}

L
Liu Jicong 已提交
5313
static SSDataBlock* doMultiTableAggregate(SOperatorInfo* pOperator, bool* newgroup) {
5314 5315 5316 5317 5318
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

  SAggOperatorInfo* pAggInfo = pOperator->info;
L
Liu Jicong 已提交
5319 5320
  SOptrBasicInfo*   pInfo = &pAggInfo->binfo;
  SExecTaskInfo*    pTaskInfo = pOperator->pTaskInfo;
5321 5322

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

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

    return pInfo->pRes;
  }

5333
  // table scan order
L
Liu Jicong 已提交
5334
  int32_t        order = TSDB_ORDER_ASC;
H
Haojun Liao 已提交
5335
  SOperatorInfo* downstream = pOperator->pDownstream[0];
5336

L
Liu Jicong 已提交
5337
  while (1) {
H
Haojun Liao 已提交
5338
    publishOperatorProfEvent(downstream, QUERY_PROF_BEFORE_OPERATOR_EXEC);
H
Haojun Liao 已提交
5339
    SSDataBlock* pBlock = downstream->getNextFn(downstream, newgroup);
H
Haojun Liao 已提交
5340
    publishOperatorProfEvent(downstream, QUERY_PROF_AFTER_OPERATOR_EXEC);
5341 5342 5343 5344 5345

    if (pBlock == NULL) {
      break;
    }

L
Liu Jicong 已提交
5346 5347 5348 5349 5350
    //    setTagValue(pOperator, pRuntimeEnv->current->pTable, pInfo->pCtx, pOperator->numOfOutput);
    //    if (downstream->operatorType == OP_TableScan) {
    //      STableScanInfo* pScanInfo = downstream->info;
    //      order = getTableScanOrder(pScanInfo);
    //    }
5351 5352 5353 5354 5355

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

    TSKEY key = 0;
5356
    if (order == TSDB_ORDER_ASC) {
5357 5358 5359 5360 5361 5362
      key = pBlock->info.window.ekey;
      TSKEY_MAX_ADD(key, 1);
    } else {
      key = pBlock->info.window.skey;
      TSKEY_MIN_SUB(key, -1);
    }
L
Liu Jicong 已提交
5363 5364 5365

    setExecutionContext(pOperator->numOfOutput, pAggInfo->current->groupIndex, key, pTaskInfo, pAggInfo->current,
                        pAggInfo);
H
Haojun Liao 已提交
5366
    doAggregateImpl(pOperator, 0, pInfo->pCtx);
5367 5368 5369 5370
  }

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

H
Haojun Liao 已提交
5373
  initGroupResInfo(&pAggInfo->groupResInfo, &pInfo->resultRowInfo);
L
Liu Jicong 已提交
5374 5375
  toSDatablock(&pAggInfo->groupResInfo, pAggInfo->pResultBuf, pInfo->pRes, pAggInfo->binfo.capacity,
               pAggInfo->binfo.rowCellInfoOffset);
5376

H
Haojun Liao 已提交
5377
  if (pInfo->pRes->info.rows == 0 || !hasRemainDataInCurrentGroup(&pAggInfo->groupResInfo)) {
5378 5379 5380 5381 5382 5383
    doSetOperatorCompleted(pOperator);
  }

  return pInfo->pRes;
}

L
Liu Jicong 已提交
5384
static SSDataBlock* doProjectOperation(SOperatorInfo* pOperator, bool* newgroup) {
5385
  SProjectOperatorInfo* pProjectInfo = pOperator->info;
L
Liu Jicong 已提交
5386
  SOptrBasicInfo*       pInfo = &pProjectInfo->binfo;
5387 5388

  SSDataBlock* pRes = pInfo->pRes;
5389
  blockDataCleanup(pRes);
H
Haojun Liao 已提交
5390
#if 0
5391 5392 5393 5394 5395 5396
  if (pProjectInfo->existDataBlock) {  // TODO refactor
    SSDataBlock* pBlock = pProjectInfo->existDataBlock;
    pProjectInfo->existDataBlock = NULL;
    *newgroup = true;

    // todo dynamic set tags
L
Liu Jicong 已提交
5397 5398 5399
    //    if (pTableQueryInfo != NULL) {
    //      setTagValue(pOperator, pTableQueryInfo->pTable, pInfo->pCtx, pOperator->numOfOutput);
    //    }
5400 5401

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

H
Haojun Liao 已提交
5404
    blockDataEnsureCapacity(pInfo->pRes, pBlock->info.rows);
5405
    projectApplyFunctions(pOperator->pExpr, pInfo->pRes, pBlock, pInfo->pCtx, pOperator->numOfOutput);
L
Liu Jicong 已提交
5406
    if (pRes->info.rows >= pProjectInfo->binfo.capacity * 0.8) {
5407 5408 5409 5410 5411
      copyTsColoum(pRes, pInfo->pCtx, pOperator->numOfOutput);
      resetResultRowEntryResult(pInfo->pCtx, pOperator->numOfOutput);
      return pRes;
    }
  }
H
Haojun Liao 已提交
5412
#endif
5413

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

L
Liu Jicong 已提交
5416
  while (1) {
5417 5418
    bool prevVal = *newgroup;

H
Haojun Liao 已提交
5419
    // The downstream exec may change the value of the newgroup, so use a local variable instead.
H
Haojun Liao 已提交
5420 5421 5422
    publishOperatorProfEvent(downstream, QUERY_PROF_BEFORE_OPERATOR_EXEC);
    SSDataBlock* pBlock = downstream->getNextFn(downstream, newgroup);
    publishOperatorProfEvent(downstream, QUERY_PROF_AFTER_OPERATOR_EXEC);
5423 5424 5425 5426

    if (pBlock == NULL) {
      assert(*newgroup == false);
      *newgroup = prevVal;
5427
      setTaskStatus(pOperator->pTaskInfo, TASK_COMPLETED);
5428 5429 5430 5431 5432 5433 5434 5435
      break;
    }

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

    // todo dynamic set tags
H
Haojun Liao 已提交
5442 5443 5444 5445
    //    STableQueryInfo* pTableQueryInfo = pRuntimeEnv->current;
    //    if (pTableQueryInfo != NULL) {
    //      setTagValue(pOperator, pTableQueryInfo->pTable, pInfo->pCtx, pOperator->numOfOutput);
    //    }
5446 5447

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

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

H
Haojun Liao 已提交
5453
    // todo extract method
H
Haojun Liao 已提交
5454 5455 5456 5457 5458 5459 5460 5461
    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;
    }
5462

5463
    if (pRes->info.rows >= pOperator->resultInfo.threshold) {
5464 5465 5466
      break;
    }
  }
H
Haojun Liao 已提交
5467
  
H
Haojun Liao 已提交
5468
  if (pProjectInfo->limit.limit > 0 && pProjectInfo->curOutput + pInfo->pRes->info.rows >= pProjectInfo->limit.limit) {
H
Haojun Liao 已提交
5469
    pInfo->pRes->info.rows = (int32_t)(pProjectInfo->limit.limit - pProjectInfo->curOutput);
5470 5471
  }

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

L
Liu Jicong 已提交
5474 5475
  //  copyTsColoum(pRes, pInfo->pCtx, pOperator->numOfOutput);
  return (pInfo->pRes->info.rows > 0) ? pInfo->pRes : NULL;
5476 5477
}

L
Liu Jicong 已提交
5478
static int32_t doOpenIntervalAgg(SOperatorInfo* pOperator) {
5479 5480
  if (OPTR_IS_OPENED(pOperator)) {
    return TSDB_CODE_SUCCESS;
5481 5482
  }

H
Haojun Liao 已提交
5483
  STableIntervalOperatorInfo* pInfo = pOperator->info;
5484

5485
  int32_t order = TSDB_ORDER_ASC;
5486 5487
  //  STimeWindow win = {0};
  bool newgroup = false;
H
Haojun Liao 已提交
5488
  SOperatorInfo* downstream = pOperator->pDownstream[0];
5489

5490
  while (1) {
H
Haojun Liao 已提交
5491
    publishOperatorProfEvent(downstream, QUERY_PROF_BEFORE_OPERATOR_EXEC);
5492
    SSDataBlock* pBlock = downstream->getNextFn(downstream, &newgroup);
H
Haojun Liao 已提交
5493
    publishOperatorProfEvent(downstream, QUERY_PROF_AFTER_OPERATOR_EXEC);
5494 5495 5496 5497 5498

    if (pBlock == NULL) {
      break;
    }

5499
    //    setTagValue(pOperator, pRuntimeEnv->current->pTable, pInfo->pCtx, pOperator->numOfOutput);
5500
    // the pDataBlock are always the same one, no need to call this again
5501
    setInputDataBlock(pOperator, pInfo->binfo.pCtx, pBlock, order);
H
Haojun Liao 已提交
5502
    hashIntervalAgg(pOperator, &pInfo->binfo.resultRowInfo, pBlock, 0);
5503 5504
  }

H
Haojun Liao 已提交
5505
  closeAllResultRows(&pInfo->binfo.resultRowInfo);
L
Liu Jicong 已提交
5506 5507
  finalizeMultiTupleQueryResult(pInfo->binfo.pCtx, pOperator->numOfOutput, pInfo->aggSup.pResultBuf,
                                &pInfo->binfo.resultRowInfo, pInfo->binfo.rowCellInfoOffset);
5508

H
Haojun Liao 已提交
5509
  initGroupResInfo(&pInfo->groupResInfo, &pInfo->binfo.resultRowInfo);
5510 5511 5512 5513
  OPTR_SET_OPENED(pOperator);
  return TSDB_CODE_SUCCESS;
}

L
Liu Jicong 已提交
5514
static SSDataBlock* doBuildIntervalResult(SOperatorInfo* pOperator, bool* newgroup) {
5515
  STableIntervalOperatorInfo* pInfo = pOperator->info;
L
Liu Jicong 已提交
5516
  SExecTaskInfo*              pTaskInfo = pOperator->pTaskInfo;
5517 5518 5519 5520 5521

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

5522 5523 5524 5525
  if (pInfo->execModel == OPTR_EXEC_MODEL_STREAM) {
    return pOperator->getStreamResFn(pOperator, newgroup);
  }

5526 5527 5528 5529 5530 5531
  pTaskInfo->code = pOperator->_openFn(pOperator);
  if (pTaskInfo->code != TSDB_CODE_SUCCESS) {
    return NULL;
  }

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

H
Haojun Liao 已提交
5535
  if (pInfo->binfo.pRes->info.rows == 0 || !hasRemainDataInCurrentGroup(&pInfo->groupResInfo)) {
5536 5537 5538
    doSetOperatorCompleted(pOperator);
  }

L
Liu Jicong 已提交
5539
  return pInfo->binfo.pRes->info.rows == 0 ? NULL : pInfo->binfo.pRes;
5540 5541
}

5542
static SSDataBlock* doStreamIntervalAgg(SOperatorInfo *pOperator, bool* newgroup) {
5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555
  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;
    }
5556
    return pInfo->binfo.pRes->info.rows == 0 ? NULL : pInfo->binfo.pRes;
5557 5558 5559
  }

  //  STimeWindow win = {0};
5560
  *newgroup = false;
5561 5562 5563 5564 5565 5566
  SOperatorInfo* downstream = pOperator->pDownstream[0];

  SArray* pUpdated = NULL;

  while (1) {
    publishOperatorProfEvent(downstream, QUERY_PROF_BEFORE_OPERATOR_EXEC);
5567
    SSDataBlock* pBlock = downstream->getNextFn(downstream, newgroup);
5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584
    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 已提交
5585
  initMultiResInfoFromArrayList(&pInfo->groupResInfo, pUpdated);
5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596
  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) {
5597 5598 5599 5600 5601 5602
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

  STableIntervalOperatorInfo* pIntervalInfo = pOperator->info;

H
Haojun Liao 已提交
5603
  STaskRuntimeEnv* pRuntimeEnv = pOperator->pRuntimeEnv;
5604
  if (pOperator->status == OP_RES_TO_RETURN) {
L
Liu Jicong 已提交
5605
    //    toSDatablock(&pRuntimeEnv->groupResInfo, pRuntimeEnv, pIntervalInfo->pRes);
5606

H
Haojun Liao 已提交
5607
    if (pIntervalInfo->binfo.pRes->info.rows == 0 || !hasRemainDataInCurrentGroup(&pRuntimeEnv->groupResInfo)) {
5608 5609 5610
      doSetOperatorCompleted(pOperator);
    }

H
Haojun Liao 已提交
5611
    return pIntervalInfo->binfo.pRes;
5612 5613
  }

L
Liu Jicong 已提交
5614 5615
  STaskAttr*  pQueryAttr = pRuntimeEnv->pQueryAttr;
  int32_t     order = pQueryAttr->order.order;
5616 5617
  STimeWindow win = pQueryAttr->window;

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

L
Liu Jicong 已提交
5620
  while (1) {
H
Haojun Liao 已提交
5621
    publishOperatorProfEvent(downstream, QUERY_PROF_BEFORE_OPERATOR_EXEC);
H
Haojun Liao 已提交
5622
    SSDataBlock* pBlock = downstream->getNextFn(downstream, newgroup);
H
Haojun Liao 已提交
5623
    publishOperatorProfEvent(downstream, QUERY_PROF_AFTER_OPERATOR_EXEC);
5624 5625 5626 5627 5628

    if (pBlock == NULL) {
      break;
    }

L
Liu Jicong 已提交
5629
    //    setTagValue(pOperator, pRuntimeEnv->current->pTable, pIntervalInfo->pCtx, pOperator->numOfOutput);
5630 5631

    // the pDataBlock are always the same one, no need to call this again
H
Haojun Liao 已提交
5632 5633
    setInputDataBlock(pOperator, pIntervalInfo->binfo.pCtx, pBlock, pQueryAttr->order.order);
    hashAllIntervalAgg(pOperator, &pIntervalInfo->binfo.resultRowInfo, pBlock, 0);
5634 5635 5636 5637 5638 5639 5640
  }

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

  pOperator->status = OP_RES_TO_RETURN;
H
Haojun Liao 已提交
5641
  closeAllResultRows(&pIntervalInfo->binfo.resultRowInfo);
5642
  setTaskStatus(pOperator->pTaskInfo, TASK_COMPLETED);
5643
  finalizeQueryResult(pIntervalInfo->binfo.pCtx, pOperator->numOfOutput);
5644

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

H
Haojun Liao 已提交
5648
  if (pIntervalInfo->binfo.pRes->info.rows == 0 || !hasRemainDataInCurrentGroup(&pRuntimeEnv->groupResInfo)) {
5649 5650 5651
    pOperator->status = OP_EXEC_DONE;
  }

L
Liu Jicong 已提交
5652
  return pIntervalInfo->binfo.pRes->info.rows == 0 ? NULL : pIntervalInfo->binfo.pRes;
5653 5654
}

L
Liu Jicong 已提交
5655
static SSDataBlock* doSTableIntervalAgg(SOperatorInfo* pOperator, bool* newgroup) {
5656 5657 5658 5659 5660
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

  STableIntervalOperatorInfo* pIntervalInfo = pOperator->info;
L
Liu Jicong 已提交
5661
  STaskRuntimeEnv*            pRuntimeEnv = pOperator->pRuntimeEnv;
5662 5663 5664 5665

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

L
Liu Jicong 已提交
5666
    //    copyToSDataBlock(NULL, 3000, pIntervalInfo->pRes, pIntervalInfo->rowCellInfoOffset);
H
Haojun Liao 已提交
5667
    if (pIntervalInfo->binfo.pRes->info.rows == 0 || !hasRemainData(&pRuntimeEnv->groupResInfo)) {
5668 5669
      doSetOperatorCompleted(pOperator);
    }
H
Haojun Liao 已提交
5670
    return pIntervalInfo->binfo.pRes;
5671 5672
  }

H
Haojun Liao 已提交
5673
  STaskAttr* pQueryAttr = pRuntimeEnv->pQueryAttr;
L
Liu Jicong 已提交
5674
  int32_t    order = pQueryAttr->order.order;
5675

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

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

    if (pBlock == NULL) {
      break;
    }

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

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

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

  pOperator->status = OP_RES_TO_RETURN;
L
Liu Jicong 已提交
5698
  pQueryAttr->order.order = order;  // TODO : restore the order
5699
  doCloseAllTimeWindow(pRuntimeEnv);
5700
  setTaskStatus(pOperator->pTaskInfo, TASK_COMPLETED);
5701

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

H
Haojun Liao 已提交
5707
  return pIntervalInfo->binfo.pRes;
5708 5709
}

L
Liu Jicong 已提交
5710
static SSDataBlock* doAllSTableIntervalAgg(SOperatorInfo* pOperator, bool* newgroup) {
5711 5712 5713 5714 5715
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

  STableIntervalOperatorInfo* pIntervalInfo = pOperator->info;
L
Liu Jicong 已提交
5716
  STaskRuntimeEnv*            pRuntimeEnv = pOperator->pRuntimeEnv;
5717 5718

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

H
Haojun Liao 已提交
5724
    return pIntervalInfo->binfo.pRes;
5725 5726
  }

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

L
Liu Jicong 已提交
5729
  while (1) {
H
Haojun Liao 已提交
5730
    publishOperatorProfEvent(downstream, QUERY_PROF_BEFORE_OPERATOR_EXEC);
H
Haojun Liao 已提交
5731
    SSDataBlock* pBlock = downstream->getNextFn(downstream, newgroup);
H
Haojun Liao 已提交
5732
    publishOperatorProfEvent(downstream, QUERY_PROF_AFTER_OPERATOR_EXEC);
5733 5734 5735 5736 5737 5738 5739 5740

    if (pBlock == NULL) {
      break;
    }

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

L
Liu Jicong 已提交
5741
    //    setTagValue(pOperator, pTableQueryInfo->pTable, pIntervalInfo->pCtx, pOperator->numOfOutput);
H
Haojun Liao 已提交
5742
//    setInputDataBlock(pOperator, pIntervalInfo->binfo.pCtx, pBlock, pQueryAttr->order.order);
5743 5744 5745 5746 5747 5748
    setIntervalQueryRange(pRuntimeEnv, pBlock->info.window.skey);

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

  pOperator->status = OP_RES_TO_RETURN;
H
Haojun Liao 已提交
5749
//  pQueryAttr->order.order = order;  // TODO : restore the order
5750
  doCloseAllTimeWindow(pRuntimeEnv);
5751
  setTaskStatus(pOperator->pTaskInfo, TASK_COMPLETED);
5752 5753

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

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

H
Haojun Liao 已提交
5762
  return pIntervalInfo->binfo.pRes;
5763 5764
}

L
Liu Jicong 已提交
5765
static void doStateWindowAggImpl(SOperatorInfo* pOperator, SStateWindowOperatorInfo* pInfo, SSDataBlock* pSDataBlock) {
H
Haojun Liao 已提交
5766
  STaskRuntimeEnv* pRuntimeEnv = pOperator->pRuntimeEnv;
L
Liu Jicong 已提交
5767
  STableQueryInfo* item = pRuntimeEnv->current;
5768 5769 5770 5771
  SColumnInfoData* pColInfoData = taosArrayGet(pSDataBlock->pDataBlock, pInfo->colIndex);

  SOptrBasicInfo* pBInfo = &pInfo->binfo;

H
Haojun Liao 已提交
5772
  bool    masterScan = IS_MAIN_SCAN(pRuntimeEnv);
L
Liu Jicong 已提交
5773 5774
  int16_t bytes = pColInfoData->info.bytes;
  int16_t type = pColInfoData->info.type;
5775 5776

  SColumnInfoData* pTsColInfoData = taosArrayGet(pSDataBlock->pDataBlock, 0);
L
Liu Jicong 已提交
5777
  TSKEY*           tsList = (TSKEY*)pTsColInfoData->pData;
5778 5779
  if (IS_REPEAT_SCAN(pRuntimeEnv) && !pInfo->reptScan) {
    pInfo->reptScan = true;
wafwerar's avatar
wafwerar 已提交
5780
    taosMemoryFreeClear(pInfo->prevData);
5781 5782 5783 5784 5785 5786 5787 5788 5789
  }

  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 已提交
5790
      pInfo->prevData = taosMemoryMalloc(bytes);
5791 5792 5793 5794 5795 5796 5797 5798 5799
      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 已提交
5800
      // pInfo->start = j;
5801 5802 5803 5804 5805 5806 5807
      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 已提交
5808 5809 5810
      int32_t ret = setResultOutputBufByKey(pRuntimeEnv, &pBInfo->resultRowInfo, pSDataBlock->info.uid,
                                            &pInfo->curWindow, masterScan, &pResult, item->groupIndex, pBInfo->pCtx,
                                            pOperator->numOfOutput, pBInfo->rowCellInfoOffset);
5811 5812 5813
      if (ret != TSDB_CODE_SUCCESS) {  // null data, too many state code
        longjmp(pRuntimeEnv->env, TSDB_CODE_QRY_APP_ERROR);
      }
L
Liu Jicong 已提交
5814 5815
      //      doApplyFunctions(pRuntimeEnv, pBInfo->pCtx, &pInfo->curWindow, pInfo->start, pInfo->numOfRows, tsList,
      //                       pSDataBlock->info.rows, pOperator->numOfOutput);
5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827

      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 已提交
5828 5829
  int32_t ret = setResultOutputBufByKey(pRuntimeEnv, &pBInfo->resultRowInfo, pSDataBlock->info.uid, &pInfo->curWindow,
                                        masterScan, &pResult, item->groupIndex, pBInfo->pCtx, pOperator->numOfOutput,
5830 5831 5832 5833 5834
                                        pBInfo->rowCellInfoOffset);
  if (ret != TSDB_CODE_SUCCESS) {  // null data, too many state code
    longjmp(pRuntimeEnv->env, TSDB_CODE_QRY_APP_ERROR);
  }

L
Liu Jicong 已提交
5835 5836
  //  doApplyFunctions(pRuntimeEnv, pBInfo->pCtx, &pInfo->curWindow, pInfo->start, pInfo->numOfRows, tsList,
  //                   pSDataBlock->info.rows, pOperator->numOfOutput);
5837 5838
}

L
Liu Jicong 已提交
5839
static SSDataBlock* doStateWindowAgg(SOperatorInfo* pOperator, bool* newgroup) {
5840 5841 5842 5843 5844
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

  SStateWindowOperatorInfo* pWindowInfo = pOperator->info;
H
Haojun Liao 已提交
5845 5846
  SExecTaskInfo*  pTaskInfo = pOperator->pTaskInfo;
  SOptrBasicInfo* pBInfo    = &pWindowInfo->binfo;
5847 5848

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

H
Haojun Liao 已提交
5851 5852 5853
//    if (pBInfo->pRes->info.rows == 0 || !hasRemainDataInCurrentGroup(&pRuntimeEnv->groupResInfo)) {
//      pOperator->status = OP_EXEC_DONE;
//    }
5854 5855 5856 5857

    return pBInfo->pRes;
  }

H
Haojun Liao 已提交
5858 5859 5860
  int32_t        order = TSDB_ORDER_ASC;
  STimeWindow    win = pTaskInfo->window;

H
Haojun Liao 已提交
5861
  SOperatorInfo* downstream = pOperator->pDownstream[0];
5862
  while (1) {
H
Haojun Liao 已提交
5863
    publishOperatorProfEvent(downstream, QUERY_PROF_BEFORE_OPERATOR_EXEC);
H
Haojun Liao 已提交
5864
    SSDataBlock* pBlock = downstream->getNextFn(downstream, newgroup);
H
Haojun Liao 已提交
5865
    publishOperatorProfEvent(downstream, QUERY_PROF_AFTER_OPERATOR_EXEC);
5866 5867 5868 5869

    if (pBlock == NULL) {
      break;
    }
H
Haojun Liao 已提交
5870 5871 5872 5873 5874

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

  // restore the value
H
Haojun Liao 已提交
5879 5880
//  pQueryAttr->order.order = order;
//  pQueryAttr->window = win;
5881 5882 5883

  pOperator->status = OP_RES_TO_RETURN;
  closeAllResultRows(&pBInfo->resultRowInfo);
5884
  setTaskStatus(pOperator->pTaskInfo, TASK_COMPLETED);
5885
  finalizeQueryResult(pBInfo->pCtx, pOperator->numOfOutput);
5886

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

H
Haojun Liao 已提交
5890 5891 5892
//  if (pBInfo->pRes->info.rows == 0 || !hasRemainDataInCurrentGroup(&pRuntimeEnv->groupResInfo)) {
//    pOperator->status = OP_EXEC_DONE;
//  }
5893

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

L
Liu Jicong 已提交
5897
static SSDataBlock* doSessionWindowAgg(SOperatorInfo* pOperator, bool* newgroup) {
5898 5899 5900 5901
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

5902
  SSessionAggOperatorInfo* pInfo = pOperator->info;
L
Liu Jicong 已提交
5903
  SOptrBasicInfo*          pBInfo = &pInfo->binfo;
5904 5905

  if (pOperator->status == OP_RES_TO_RETURN) {
5906
    toSDatablock(&pInfo->groupResInfo, pInfo->aggSup.pResultBuf, pBInfo->pRes, pBInfo->capacity, pBInfo->rowCellInfoOffset);
5907 5908 5909
    if (pBInfo->pRes->info.rows == 0 || !hasRemainDataInCurrentGroup(&pInfo->groupResInfo)) {
      doSetOperatorCompleted(pOperator);
      return NULL;
5910 5911 5912 5913 5914
    }

    return pBInfo->pRes;
  }

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

L
Liu Jicong 已提交
5918
  while (1) {
H
Haojun Liao 已提交
5919
    publishOperatorProfEvent(downstream, QUERY_PROF_BEFORE_OPERATOR_EXEC);
H
Haojun Liao 已提交
5920
    SSDataBlock* pBlock = downstream->getNextFn(downstream, newgroup);
H
Haojun Liao 已提交
5921
    publishOperatorProfEvent(downstream, QUERY_PROF_AFTER_OPERATOR_EXEC);
5922 5923 5924 5925 5926
    if (pBlock == NULL) {
      break;
    }

    // the pDataBlock are always the same one, no need to call this again
H
Haojun Liao 已提交
5927
    setInputDataBlock(pOperator, pBInfo->pCtx, pBlock, order);
5928
    doSessionWindowAggImpl(pOperator, pInfo, pBlock);
5929 5930 5931 5932 5933
  }

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

5936 5937
  initGroupResInfo(&pInfo->groupResInfo, &pBInfo->resultRowInfo);
  blockDataEnsureCapacity(pBInfo->pRes, pBInfo->capacity);
5938
  toSDatablock(&pInfo->groupResInfo, pInfo->aggSup.pResultBuf, pBInfo->pRes, pBInfo->capacity, pBInfo->rowCellInfoOffset);
5939 5940
  if (pBInfo->pRes->info.rows == 0 || !hasRemainDataInCurrentGroup(&pInfo->groupResInfo)) {
    doSetOperatorCompleted(pOperator);
5941 5942
  }

L
Liu Jicong 已提交
5943
  return pBInfo->pRes->info.rows == 0 ? NULL : pBInfo->pRes;
5944 5945 5946
}


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

L
Liu Jicong 已提交
5951 5952
  int64_t ekey = Q_STATUS_EQUAL(pTaskInfo->status, TASK_COMPLETED) ? pTaskInfo->window.ekey
                                                                   : pInfo->existNewGroupBlock->info.window.ekey;
5953 5954
  taosResetFillInfo(pInfo->pFillInfo, getFillInfoStart(pInfo->pFillInfo));

5955
  taosFillSetStartInfo(pInfo->pFillInfo, pInfo->existNewGroupBlock->info.rows, ekey);
5956 5957
  taosFillSetInputDataBlock(pInfo->pFillInfo, pInfo->existNewGroupBlock);

H
Haojun Liao 已提交
5958
  doFillTimeIntervalGapsInResults(pInfo->pFillInfo, pInfo->pRes, pResultInfo->capacity, pInfo->p);
5959 5960 5961 5962
  pInfo->existNewGroupBlock = NULL;
  *newgroup = true;
}

L
Liu Jicong 已提交
5963 5964
static void doHandleRemainBlockFromNewGroup(SFillOperatorInfo* pInfo, SResultInfo* pResultInfo, bool* newgroup,
                                            SExecTaskInfo* pTaskInfo) {
5965 5966
  if (taosFillHasMoreResults(pInfo->pFillInfo)) {
    *newgroup = false;
H
Haojun Liao 已提交
5967 5968
    doFillTimeIntervalGapsInResults(pInfo->pFillInfo, pInfo->pRes, (int32_t)pResultInfo->capacity, pInfo->p);
    if (pInfo->pRes->info.rows > pResultInfo->threshold || (!pInfo->multigroupResult)) {
5969 5970 5971 5972 5973 5974
      return;
    }
  }

  // handle the cached new group data block
  if (pInfo->existNewGroupBlock) {
5975
    doHandleRemainBlockForNewGroupImpl(pInfo, pResultInfo, newgroup, pTaskInfo);
5976 5977 5978
  }
}

L
Liu Jicong 已提交
5979 5980 5981
static SSDataBlock* doFill(SOperatorInfo* pOperator, bool* newgroup) {
  SFillOperatorInfo* pInfo = pOperator->info;
  SExecTaskInfo*     pTaskInfo = pOperator->pTaskInfo;
5982

H
Haojun Liao 已提交
5983 5984
  SResultInfo* pResultInfo = &pOperator->resultInfo;
  blockDataCleanup(pInfo->pRes);
5985 5986 5987 5988
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

5989
  doHandleRemainBlockFromNewGroup(pInfo, pResultInfo, newgroup, pTaskInfo);
H
Haojun Liao 已提交
5990 5991 5992
  if (pInfo->pRes->info.rows > pResultInfo->threshold || (!pInfo->multigroupResult && pInfo->pRes->info.rows > 0)) {
    return pInfo->pRes;
  }
5993

H
Haojun Liao 已提交
5994
  SOperatorInfo* pDownstream = pOperator->pDownstream[0];
L
Liu Jicong 已提交
5995
  while (1) {
H
Haojun Liao 已提交
5996 5997 5998
    publishOperatorProfEvent(pDownstream, QUERY_PROF_BEFORE_OPERATOR_EXEC);
    SSDataBlock* pBlock = pDownstream->getNextFn(pDownstream, newgroup);
    publishOperatorProfEvent(pDownstream, QUERY_PROF_AFTER_OPERATOR_EXEC);
5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009

    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
6010
      taosFillSetStartInfo(pInfo->pFillInfo, 0, pTaskInfo->window.ekey);
6011 6012 6013 6014 6015 6016 6017
    } else {
      if (pBlock == NULL) {
        if (pInfo->totalInputRows == 0) {
          pOperator->status = OP_EXEC_DONE;
          return NULL;
        }

6018
        taosFillSetStartInfo(pInfo->pFillInfo, 0, pTaskInfo->window.ekey);
6019 6020 6021 6022 6023 6024 6025
      } else {
        pInfo->totalInputRows += pBlock->info.rows;
        taosFillSetStartInfo(pInfo->pFillInfo, pBlock->info.rows, pBlock->info.window.ekey);
        taosFillSetInputDataBlock(pInfo->pFillInfo, pBlock);
      }
    }

H
Haojun Liao 已提交
6026
    doFillTimeIntervalGapsInResults(pInfo->pFillInfo, pInfo->pRes, pInfo->capacity, pInfo->p);
6027 6028 6029 6030 6031

    // 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 已提交
6032
      if (pInfo->pRes->info.rows > pResultInfo->threshold || pBlock == NULL || (!pInfo->multigroupResult)) {
6033 6034 6035
        return pInfo->pRes;
      }

6036
      doHandleRemainBlockFromNewGroup(pInfo, pResultInfo, newgroup, pTaskInfo);
H
Haojun Liao 已提交
6037
      if (pInfo->pRes->info.rows > pOperator->resultInfo.threshold || pBlock == NULL) {
6038 6039 6040 6041
        return pInfo->pRes;
      }
    } else if (pInfo->existNewGroupBlock) {  // try next group
      assert(pBlock != NULL);
6042
      doHandleRemainBlockForNewGroupImpl(pInfo, pResultInfo, newgroup, pTaskInfo);
H
Haojun Liao 已提交
6043
      if (pInfo->pRes->info.rows > pResultInfo->threshold) {
6044 6045 6046 6047 6048 6049 6050 6051 6052
        return pInfo->pRes;
      }
    } else {
      return NULL;
    }
  }
}

// todo set the attribute of query scan count
H
Haojun Liao 已提交
6053
static int32_t getNumOfScanTimes(STaskAttr* pQueryAttr) {
L
Liu Jicong 已提交
6054
  for (int32_t i = 0; i < pQueryAttr->numOfOutput; ++i) {
6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068
    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 已提交
6069 6070
  if (pOperator->closeFn != NULL) {
    pOperator->closeFn(pOperator->info, pOperator->numOfOutput);
6071 6072
  }

H
Haojun Liao 已提交
6073
  if (pOperator->pDownstream != NULL) {
L
Liu Jicong 已提交
6074
    for (int32_t i = 0; i < pOperator->numOfDownstream; ++i) {
H
Haojun Liao 已提交
6075
      destroyOperatorInfo(pOperator->pDownstream[i]);
6076 6077
    }

wafwerar's avatar
wafwerar 已提交
6078
    taosMemoryFreeClear(pOperator->pDownstream);
H
Haojun Liao 已提交
6079
    pOperator->numOfDownstream = 0;
6080 6081
  }

wafwerar's avatar
wafwerar 已提交
6082 6083
  taosMemoryFreeClear(pOperator->info);
  taosMemoryFreeClear(pOperator);
6084 6085
}

L
Liu Jicong 已提交
6086
int32_t doInitAggInfoSup(SAggSupporter* pAggSup, SqlFunctionCtx* pCtx, int32_t numOfOutput, const char* pKey) {
6087 6088
  _hash_fn_t hashFn = taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY);

H
Haojun Liao 已提交
6089 6090
  pAggSup->resultRowSize       = getResultRowSize(pCtx, numOfOutput);
  pAggSup->keyBuf              = taosMemoryCalloc(1, sizeof(int64_t) + sizeof(int64_t) + POINTER_BYTES);
6091
  pAggSup->pResultRowHashTable = taosHashInit(10, hashFn, true, HASH_NO_LOCK);
H
Haojun Liao 已提交
6092
  pAggSup->pResultRowListSet   = taosHashInit(100, hashFn, false, HASH_NO_LOCK);
6093 6094 6095
  pAggSup->pResultRowArrayList = taosArrayInit(10, sizeof(SResultRowCell));

  if (pAggSup->keyBuf == NULL || pAggSup->pResultRowArrayList == NULL || pAggSup->pResultRowListSet == NULL ||
6096
      pAggSup->pResultRowHashTable == NULL) {
6097 6098 6099
    return TSDB_CODE_OUT_OF_MEMORY;
  }

H
Haojun Liao 已提交
6100 6101 6102 6103 6104
  int32_t code = createDiskbasedBuf(&pAggSup->pResultBuf, 4096, 4096 * 256, pKey, "/tmp/");
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

6105 6106 6107
  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
6108
static void cleanupAggSup(SAggSupporter* pAggSup) {
wafwerar's avatar
wafwerar 已提交
6109
  taosMemoryFreeClear(pAggSup->keyBuf);
6110 6111 6112
  taosHashCleanup(pAggSup->pResultRowHashTable);
  taosHashCleanup(pAggSup->pResultRowListSet);
  taosArrayDestroy(pAggSup->pResultRowArrayList);
H
Haojun Liao 已提交
6113
  destroyDiskbasedBuf(pAggSup->pResultBuf);
6114 6115
}

H
Haojun Liao 已提交
6116
int32_t initAggInfo(SOptrBasicInfo* pBasicInfo, SAggSupporter* pAggSup, SExprInfo* pExprInfo, int32_t numOfCols,
H
Haojun Liao 已提交
6117
                           int32_t numOfRows, SSDataBlock* pResultBlock, const char* pkey) {
H
Haojun Liao 已提交
6118 6119 6120 6121
  pBasicInfo->pCtx = createSqlFunctionCtx_rv(pExprInfo, numOfCols, &pBasicInfo->rowCellInfoOffset);
  pBasicInfo->pRes = pResultBlock;
  pBasicInfo->capacity = numOfRows;

H
Haojun Liao 已提交
6122
  doInitAggInfoSup(pAggSup, pBasicInfo->pCtx, numOfCols, pkey);
H
Haojun Liao 已提交
6123 6124 6125
}

static STableQueryInfo* initTableQueryInfo(const STableGroupInfo* pTableGroupInfo) {
wafwerar's avatar
wafwerar 已提交
6126
  STableQueryInfo* pTableQueryInfo = taosMemoryCalloc(pTableGroupInfo->numOfTables, sizeof(STableQueryInfo));
H
Haojun Liao 已提交
6127 6128
  if (pTableQueryInfo == NULL) {
    return NULL;
H
Haojun Liao 已提交
6129
  }
H
Haojun Liao 已提交
6130 6131

  int32_t index = 0;
L
Liu Jicong 已提交
6132
  for (int32_t i = 0; i < taosArrayGetSize(pTableGroupInfo->pGroupList); ++i) {
H
Haojun Liao 已提交
6133
    SArray* pa = taosArrayGetP(pTableGroupInfo->pGroupList, i);
L
Liu Jicong 已提交
6134
    for (int32_t j = 0; j < taosArrayGetSize(pa); ++j) {
H
Haojun Liao 已提交
6135 6136
      STableKeyInfo* pk = taosArrayGet(pa, j);

H
Haojun Liao 已提交
6137
      STableQueryInfo* pTQueryInfo = &pTableQueryInfo[index++];
L
Liu Jicong 已提交
6138 6139
      pTQueryInfo->uid = pk->uid;
      pTQueryInfo->lastKey = pk->lastKey;
H
Haojun Liao 已提交
6140 6141 6142
      pTQueryInfo->groupIndex = i;
    }
  }
H
Haojun Liao 已提交
6143 6144

  STimeWindow win = {0, INT64_MAX};
H
Haojun Liao 已提交
6145 6146
  createTableQueryInfo(pTableQueryInfo, false, win);
  return pTableQueryInfo;
H
Haojun Liao 已提交
6147 6148
}

L
Liu Jicong 已提交
6149 6150 6151
SOperatorInfo* createAggregateOperatorInfo(SOperatorInfo* downstream, SExprInfo* pExprInfo, int32_t numOfCols,
                                           SSDataBlock* pResultBlock, SExecTaskInfo* pTaskInfo,
                                           const STableGroupInfo* pTableGroupInfo) {
wafwerar's avatar
wafwerar 已提交
6152
  SAggOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SAggOperatorInfo));
L
Liu Jicong 已提交
6153
  SOperatorInfo*    pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
6154 6155 6156
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }
H
Haojun Liao 已提交
6157 6158

  //(int32_t)(getRowNumForMultioutput(pQueryAttr, pQueryAttr->topBotQuery, pQueryAttr->stableQuery));
H
Haojun Liao 已提交
6159
  int32_t numOfRows = 1;
H
Haojun Liao 已提交
6160
  int32_t code = initAggInfo(&pInfo->binfo, &pInfo->aggSup, pExprInfo, numOfCols, numOfRows, pResultBlock, pTaskInfo->id.str);
H
Haojun Liao 已提交
6161 6162
  pInfo->pTableQueryInfo = initTableQueryInfo(pTableGroupInfo);
  if (code != TSDB_CODE_SUCCESS || pInfo->pTableQueryInfo == NULL) {
H
Haojun Liao 已提交
6163 6164
    goto _error;
  }
H
Haojun Liao 已提交
6165

H
Haojun Liao 已提交
6166
  setFunctionResultOutput(&pInfo->binfo, &pInfo->aggSup, MAIN_SCAN, pTaskInfo);
6167

H
Haojun Liao 已提交
6168
  pOperator->name         = "TableAggregate";
X
Xiaoyu Wang 已提交
6169
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_AGG;
6170
  pOperator->blockingOptr = true;
H
Haojun Liao 已提交
6171 6172 6173 6174 6175 6176 6177 6178 6179
  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 已提交
6180 6181
  pOperator->encodeResultRow = aggEncodeResultRow;
  pOperator->decodeResultRow = aggDecodeResultRow;
H
Haojun Liao 已提交
6182 6183 6184 6185 6186

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

  return pOperator;
L
Liu Jicong 已提交
6189
_error:
H
Haojun Liao 已提交
6190
  destroyAggOperatorInfo(pInfo, numOfCols);
wafwerar's avatar
wafwerar 已提交
6191 6192
  taosMemoryFreeClear(pInfo);
  taosMemoryFreeClear(pOperator);
H
Haojun Liao 已提交
6193 6194
  pTaskInfo->code = TSDB_CODE_OUT_OF_MEMORY;
  return NULL;
6195 6196
}

H
Haojun Liao 已提交
6197
void doDestroyBasicInfo(SOptrBasicInfo* pInfo, int32_t numOfOutput) {
6198 6199
  assert(pInfo != NULL);

6200
  destroySqlFunctionCtx(pInfo->pCtx, numOfOutput);
wafwerar's avatar
wafwerar 已提交
6201
  taosMemoryFreeClear(pInfo->rowCellInfoOffset);
6202 6203

  cleanupResultRowInfo(&pInfo->resultRowInfo);
H
Haojun Liao 已提交
6204
  pInfo->pRes = blockDataDestroy(pInfo->pRes);
6205 6206
}

H
Haojun Liao 已提交
6207
void destroyBasicOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
6208
  SOptrBasicInfo* pInfo = (SOptrBasicInfo*)param;
6209 6210
  doDestroyBasicInfo(pInfo, numOfOutput);
}
H
Haojun Liao 已提交
6211 6212

void destroyStateWindowOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
6213
  SStateWindowOperatorInfo* pInfo = (SStateWindowOperatorInfo*)param;
6214
  doDestroyBasicInfo(&pInfo->binfo, numOfOutput);
wafwerar's avatar
wafwerar 已提交
6215
  taosMemoryFreeClear(pInfo->prevData);
6216
}
H
Haojun Liao 已提交
6217 6218

void destroyAggOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
6219
  SAggOperatorInfo* pInfo = (SAggOperatorInfo*)param;
6220 6221
  doDestroyBasicInfo(&pInfo->binfo, numOfOutput);
}
6222

H
Haojun Liao 已提交
6223
void destroyIntervalOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
6224
  STableIntervalOperatorInfo* pInfo = (STableIntervalOperatorInfo*)param;
H
Haojun Liao 已提交
6225 6226 6227 6228 6229
  doDestroyBasicInfo(&pInfo->binfo, numOfOutput);
  cleanupAggSup(&pInfo->aggSup);
}

void destroySWindowOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
6230
  SSessionAggOperatorInfo* pInfo = (SSessionAggOperatorInfo*)param;
6231 6232 6233
  doDestroyBasicInfo(&pInfo->binfo, numOfOutput);
}

H
Haojun Liao 已提交
6234
void destroySFillOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
6235
  SFillOperatorInfo* pInfo = (SFillOperatorInfo*)param;
6236
  pInfo->pFillInfo = taosDestroyFillInfo(pInfo->pFillInfo);
H
Haojun Liao 已提交
6237
  pInfo->pRes = blockDataDestroy(pInfo->pRes);
wafwerar's avatar
wafwerar 已提交
6238
  taosMemoryFreeClear(pInfo->p);
6239 6240
}

H
Haojun Liao 已提交
6241
static void destroyProjectOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
6242
  SProjectOperatorInfo* pInfo = (SProjectOperatorInfo*)param;
6243 6244 6245
  doDestroyBasicInfo(&pInfo->binfo, numOfOutput);
}

H
Haojun Liao 已提交
6246
static void destroyTagScanOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
6247
  STagScanInfo* pInfo = (STagScanInfo*)param;
H
Haojun Liao 已提交
6248
  pInfo->pRes = blockDataDestroy(pInfo->pRes);
6249 6250
}

H
Haojun Liao 已提交
6251
static void destroyOrderOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
6252
  SSortOperatorInfo* pInfo = (SSortOperatorInfo*)param;
H
Haojun Liao 已提交
6253 6254
  pInfo->pDataBlock = blockDataDestroy(pInfo->pDataBlock);

H
Haojun Liao 已提交
6255
  taosArrayDestroy(pInfo->pSortInfo);
6256 6257
}

H
Haojun Liao 已提交
6258
void destroyExchangeOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
6259
  SExchangeInfo* pExInfo = (SExchangeInfo*)param;
H
Haojun Liao 已提交
6260 6261 6262 6263 6264 6265 6266 6267 6268
  taosArrayDestroy(pExInfo->pSources);
  taosArrayDestroy(pExInfo->pSourceDataInfo);
  if (pExInfo->pResult != NULL) {
    blockDataDestroy(pExInfo->pResult);
  }

  tsem_destroy(&pExInfo->ready);
}

L
Liu Jicong 已提交
6269 6270 6271
SOperatorInfo* createMultiTableAggOperatorInfo(SOperatorInfo* downstream, SExprInfo* pExprInfo, int32_t numOfCols,
                                               SSDataBlock* pResBlock, SExecTaskInfo* pTaskInfo,
                                               const STableGroupInfo* pTableGroupInfo) {
wafwerar's avatar
wafwerar 已提交
6272
  SAggOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SAggOperatorInfo));
6273

H
Haojun Liao 已提交
6274
  int32_t numOfRows = 1;
L
Liu Jicong 已提交
6275 6276
  int32_t code =
      initAggInfo(&pInfo->binfo, &pInfo->aggSup, pExprInfo, numOfCols, numOfRows, pResBlock, pTaskInfo->id.str);
H
Haojun Liao 已提交
6277 6278 6279 6280
  pInfo->pTableQueryInfo = initTableQueryInfo(pTableGroupInfo);
  if (code != TSDB_CODE_SUCCESS || pInfo->pTableQueryInfo == NULL) {
    goto _error;
  }
H
Haojun Liao 已提交
6281

L
Liu Jicong 已提交
6282
  size_t tableGroup = taosArrayGetSize(pTableGroupInfo->pGroupList);
6283
  initResultRowInfo(&pInfo->binfo.resultRowInfo, (int32_t)tableGroup);
6284

wafwerar's avatar
wafwerar 已提交
6285
  SOperatorInfo* pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
L
Liu Jicong 已提交
6286
  pOperator->name = "MultiTableAggregate";
X
Xiaoyu Wang 已提交
6287
  // pOperator->operatorType = OP_MultiTableAggregate;
6288
  pOperator->blockingOptr = true;
L
Liu Jicong 已提交
6289 6290 6291 6292 6293
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
  pOperator->pExpr = pExprInfo;
  pOperator->numOfOutput = numOfCols;
  pOperator->pTaskInfo = pTaskInfo;
6294

H
Haojun Liao 已提交
6295
  pOperator->getNextFn = doMultiTableAggregate;
H
Haojun Liao 已提交
6296
  pOperator->closeFn = destroyAggOperatorInfo;
H
Haojun Liao 已提交
6297 6298 6299 6300
  code = appendDownstream(pOperator, &downstream, 1);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
6301 6302

  return pOperator;
H
Haojun Liao 已提交
6303 6304 6305

_error:
  return NULL;
6306 6307
}

H
Haojun Liao 已提交
6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318
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 已提交
6319
SOperatorInfo* createProjectOperatorInfo(SOperatorInfo* downstream, SExprInfo* pExprInfo, int32_t num,
H
Haojun Liao 已提交
6320
                                         SSDataBlock* pResBlock, SLimit* pLimit, SExecTaskInfo* pTaskInfo) {
wafwerar's avatar
wafwerar 已提交
6321
  SProjectOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SProjectOperatorInfo));
L
Liu Jicong 已提交
6322
  SOperatorInfo*        pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
6323 6324 6325
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }
6326

H
Haojun Liao 已提交
6327 6328
  pInfo->limit      = *pLimit;
  pInfo->curOffset  = pLimit->offset;
H
Haojun Liao 已提交
6329
  pInfo->binfo.pRes = pResBlock;
H
Haojun Liao 已提交
6330 6331 6332 6333 6334

  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 已提交
6335
  pInfo->pPseudoColInfo = setRowTsColumnOutputInfo(pInfo->binfo.pCtx, numOfCols);
6336

H
Haojun Liao 已提交
6337
  pOperator->name         = "ProjectOperator";
H
Haojun Liao 已提交
6338
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_PROJECT;
6339
  pOperator->blockingOptr = false;
H
Haojun Liao 已提交
6340 6341 6342 6343 6344 6345 6346
  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 已提交
6347 6348

  pOperator->pTaskInfo = pTaskInfo;
6349
  int32_t code = appendDownstream(pOperator, &downstream, 1);
H
Haojun Liao 已提交
6350
  if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
6351 6352
    goto _error;
  }
6353 6354

  return pOperator;
H
Haojun Liao 已提交
6355

L
Liu Jicong 已提交
6356
_error:
H
Haojun Liao 已提交
6357 6358
  pTaskInfo->code = TSDB_CODE_OUT_OF_MEMORY;
  return NULL;
6359 6360
}

L
Liu Jicong 已提交
6361
SOperatorInfo* createIntervalOperatorInfo(SOperatorInfo* downstream, SExprInfo* pExprInfo, int32_t numOfCols,
6362
                                          SSDataBlock* pResBlock, SInterval* pInterval, int32_t primaryTsSlot,
6363
                                          const STableGroupInfo* pTableGroupInfo, SExecTaskInfo* pTaskInfo) {
wafwerar's avatar
wafwerar 已提交
6364
  STableIntervalOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(STableIntervalOperatorInfo));
L
Liu Jicong 已提交
6365
  SOperatorInfo*              pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
6366 6367 6368
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }
H
Haojun Liao 已提交
6369

H
Haojun Liao 已提交
6370 6371
  pInfo->order     = TSDB_ORDER_ASC;
  pInfo->interval  = *pInterval;
6372 6373 6374
  pInfo->execModel = pTaskInfo->execModel;

  pInfo->win       = pTaskInfo->window;
6375 6376
  pInfo->win.skey  = 0;
  pInfo->win.ekey  = INT64_MAX;
6377

6378 6379
  pInfo->primaryTsIndex = primaryTsSlot;

6380
  int32_t numOfRows = 4096;
H
Haojun Liao 已提交
6381
  int32_t code = initAggInfo(&pInfo->binfo, &pInfo->aggSup, pExprInfo, numOfCols, numOfRows, pResBlock, pTaskInfo->id.str);
6382 6383
  initExecTimeWindowInfo(&pInfo->timeWindowData, &pInfo->win);

L
Liu Jicong 已提交
6384 6385
  //  pInfo->pTableQueryInfo = initTableQueryInfo(pTableGroupInfo);
  if (code != TSDB_CODE_SUCCESS /* || pInfo->pTableQueryInfo == NULL*/) {
H
Haojun Liao 已提交
6386 6387
    goto _error;
  }
H
Haojun Liao 已提交
6388 6389

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

6391
  pOperator->name         = "TimeIntervalAggOperator";
H
Haojun Liao 已提交
6392
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_INTERVAL;
6393
  pOperator->blockingOptr = true;
H
Haojun Liao 已提交
6394 6395 6396 6397 6398 6399 6400
  pOperator->status       = OP_NOT_OPENED;
  pOperator->pExpr        = pExprInfo;
  pOperator->pTaskInfo    = pTaskInfo;
  pOperator->numOfOutput  = numOfCols;
  pOperator->info         = pInfo;
  pOperator->_openFn      = doOpenIntervalAgg;
  pOperator->getNextFn    = doBuildIntervalResult;
6401
  pOperator->getStreamResFn= doStreamIntervalAgg;
H
Haojun Liao 已提交
6402
  pOperator->closeFn      = destroyIntervalOperatorInfo;
6403

H
Haojun Liao 已提交
6404
  code = appendDownstream(pOperator, &downstream, 1);
H
Haojun Liao 已提交
6405 6406 6407 6408
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }

6409
  return pOperator;
H
Haojun Liao 已提交
6410

L
Liu Jicong 已提交
6411
_error:
H
Haojun Liao 已提交
6412
  destroyIntervalOperatorInfo(pInfo, numOfCols);
wafwerar's avatar
wafwerar 已提交
6413 6414
  taosMemoryFreeClear(pInfo);
  taosMemoryFreeClear(pOperator);
H
Haojun Liao 已提交
6415 6416
  pTaskInfo->code = code;
  return NULL;
6417 6418
}

L
Liu Jicong 已提交
6419 6420
SOperatorInfo* createAllTimeIntervalOperatorInfo(STaskRuntimeEnv* pRuntimeEnv, SOperatorInfo* downstream,
                                                 SExprInfo* pExpr, int32_t numOfOutput) {
wafwerar's avatar
wafwerar 已提交
6421
  STableIntervalOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(STableIntervalOperatorInfo));
6422

L
Liu Jicong 已提交
6423 6424
  //  pInfo->binfo.pCtx = createSqlFunctionCtx(pRuntimeEnv, pExpr, numOfOutput, &pInfo->binfo.rowCellInfoOffset);
  //  pInfo->binfo.pRes = createOutputBuf(pExpr, numOfOutput, pResultInfo->capacity);
H
Haojun Liao 已提交
6425
  initResultRowInfo(&pInfo->binfo.resultRowInfo, 8);
6426

wafwerar's avatar
wafwerar 已提交
6427
  SOperatorInfo* pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
6428

L
Liu Jicong 已提交
6429 6430
  pOperator->name = "AllTimeIntervalAggOperator";
  //  pOperator->operatorType = OP_AllTimeWindow;
6431
  pOperator->blockingOptr = true;
L
Liu Jicong 已提交
6432 6433 6434 6435 6436
  pOperator->status = OP_NOT_OPENED;
  pOperator->pExpr = pExpr;
  pOperator->numOfOutput = numOfOutput;
  pOperator->info = pInfo;
  pOperator->pRuntimeEnv = pRuntimeEnv;
H
Haojun Liao 已提交
6437
  pOperator->getNextFn = doAllIntervalAgg;
H
Haojun Liao 已提交
6438
  pOperator->closeFn = destroyBasicOperatorInfo;
6439

L
Liu Jicong 已提交
6440
  int32_t code = appendDownstream(pOperator, &downstream, 1);
6441 6442 6443
  return pOperator;
}

H
Haojun Liao 已提交
6444
SOperatorInfo* createStatewindowOperatorInfo(SOperatorInfo* downstream, SExprInfo* pExpr, int32_t numOfCols, SSDataBlock* pResBlock, SExecTaskInfo* pTaskInfo) {
wafwerar's avatar
wafwerar 已提交
6445
  SStateWindowOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SStateWindowOperatorInfo));
H
Haojun Liao 已提交
6446

L
Liu Jicong 已提交
6447 6448 6449 6450
  pInfo->colIndex = -1;
  pInfo->reptScan = false;
  //  pInfo->binfo.pCtx = createSqlFunctionCtx(pRuntimeEnv, pExpr, numOfOutput, &pInfo->binfo.rowCellInfoOffset);
  //  pInfo->binfo.pRes = createOutputBuf(pExpr, numOfOutput, pResultInfo->capacity);
6451
  initResultRowInfo(&pInfo->binfo.resultRowInfo, 8);
6452

wafwerar's avatar
wafwerar 已提交
6453
  SOperatorInfo* pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
L
Liu Jicong 已提交
6454 6455
  pOperator->name = "StateWindowOperator";
  //  pOperator->operatorType = OP_StateWindow;
6456
  pOperator->blockingOptr = true;
H
Haojun Liao 已提交
6457 6458 6459 6460 6461 6462 6463 6464
  pOperator->status       = OP_NOT_OPENED;
  pOperator->pExpr        = pExpr;
  pOperator->numOfOutput  = numOfCols;

  pOperator->pTaskInfo    = pTaskInfo;
  pOperator->info         = pInfo;
  pOperator->getNextFn    = doStateWindowAgg;
  pOperator->closeFn      = destroyStateWindowOperatorInfo;
6465

H
Haojun Liao 已提交
6466
  int32_t code = appendDownstream(pOperator, &downstream, 1);
6467 6468 6469
  return pOperator;
}

L
Liu Jicong 已提交
6470 6471
SOperatorInfo* createSessionAggOperatorInfo(SOperatorInfo* downstream, SExprInfo* pExprInfo, int32_t numOfCols,
                                            SSDataBlock* pResBlock, int64_t gap, SExecTaskInfo* pTaskInfo) {
wafwerar's avatar
wafwerar 已提交
6472
  SSessionAggOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SSessionAggOperatorInfo));
L
Liu Jicong 已提交
6473
  SOperatorInfo*           pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
6474 6475 6476
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }
H
Haojun Liao 已提交
6477

H
Haojun Liao 已提交
6478
  int32_t numOfRows = 4096;
6479
  int32_t code = initAggInfo(&pInfo->binfo, &pInfo->aggSup, pExprInfo, numOfCols, numOfRows, pResBlock, pTaskInfo->id.str);
H
Haojun Liao 已提交
6480 6481 6482
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
6483

H
Haojun Liao 已提交
6484
  initResultRowInfo(&pInfo->binfo.resultRowInfo, 8);
6485
  initExecTimeWindowInfo(&pInfo->timeWindowData, &pTaskInfo->window);
6486

6487 6488 6489 6490 6491
  pInfo->gap              = gap;
  pInfo->binfo.pRes       = pResBlock;
  pInfo->prevTs           = INT64_MIN;
  pInfo->reptScan         = false;
  pOperator->name         = "SessionWindowAggOperator";
H
Haojun Liao 已提交
6492
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_SESSION_WINDOW;
6493
  pOperator->blockingOptr = true;
6494 6495 6496 6497 6498 6499 6500
  pOperator->status       = OP_NOT_OPENED;
  pOperator->pExpr        = pExprInfo;
  pOperator->numOfOutput  = numOfCols;
  pOperator->info         = pInfo;
  pOperator->getNextFn    = doSessionWindowAgg;
  pOperator->closeFn      = destroySWindowOperatorInfo;
  pOperator->pTaskInfo    = pTaskInfo;
6501

H
Haojun Liao 已提交
6502
  code = appendDownstream(pOperator, &downstream, 1);
6503
  return pOperator;
H
Haojun Liao 已提交
6504

L
Liu Jicong 已提交
6505
_error:
H
Haojun Liao 已提交
6506 6507 6508 6509
  if (pInfo != NULL) {
    destroySWindowOperatorInfo(pInfo, numOfCols);
  }

wafwerar's avatar
wafwerar 已提交
6510 6511
  taosMemoryFreeClear(pInfo);
  taosMemoryFreeClear(pOperator);
H
Haojun Liao 已提交
6512 6513
  pTaskInfo->code = code;
  return NULL;
6514 6515
}

L
Liu Jicong 已提交
6516 6517
SOperatorInfo* createMultiTableTimeIntervalOperatorInfo(STaskRuntimeEnv* pRuntimeEnv, SOperatorInfo* downstream,
                                                        SExprInfo* pExpr, int32_t numOfOutput) {
wafwerar's avatar
wafwerar 已提交
6518
  STableIntervalOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(STableIntervalOperatorInfo));
6519

L
Liu Jicong 已提交
6520 6521
  //  pInfo->binfo.pCtx = createSqlFunctionCtx(pRuntimeEnv, pExpr, numOfOutput, &pInfo->binfo.rowCellInfoOffset);
  //  pInfo->binfo.pRes = createOutputBuf(pExpr, numOfOutput, pResultInfo->capacity);
H
Haojun Liao 已提交
6522
  initResultRowInfo(&pInfo->binfo.resultRowInfo, 8);
6523

wafwerar's avatar
wafwerar 已提交
6524
  SOperatorInfo* pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
L
Liu Jicong 已提交
6525 6526
  pOperator->name = "MultiTableTimeIntervalOperator";
  //  pOperator->operatorType = OP_MultiTableTimeInterval;
6527
  pOperator->blockingOptr = true;
L
Liu Jicong 已提交
6528 6529 6530 6531 6532
  pOperator->status = OP_NOT_OPENED;
  pOperator->pExpr = pExpr;
  pOperator->numOfOutput = numOfOutput;
  pOperator->info = pInfo;
  pOperator->pRuntimeEnv = pRuntimeEnv;
6533

H
Haojun Liao 已提交
6534
  pOperator->getNextFn = doSTableIntervalAgg;
H
Haojun Liao 已提交
6535
  pOperator->closeFn = destroyBasicOperatorInfo;
6536

L
Liu Jicong 已提交
6537
  int32_t code = appendDownstream(pOperator, &downstream, 1);
6538 6539 6540
  return pOperator;
}

L
Liu Jicong 已提交
6541 6542
SOperatorInfo* createAllMultiTableTimeIntervalOperatorInfo(STaskRuntimeEnv* pRuntimeEnv, SOperatorInfo* downstream,
                                                           SExprInfo* pExpr, int32_t numOfOutput) {
wafwerar's avatar
wafwerar 已提交
6543
  STableIntervalOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(STableIntervalOperatorInfo));
6544

L
Liu Jicong 已提交
6545 6546
  //  pInfo->binfo.pCtx = createSqlFunctionCtx(pRuntimeEnv, pExpr, numOfOutput, &pInfo->binfo.rowCellInfoOffset);
  //  pInfo->binfo.pRes = createOutputBuf(pExpr, numOfOutput, pResultInfo->capacity);
H
Haojun Liao 已提交
6547
  initResultRowInfo(&pInfo->binfo.resultRowInfo, 8);
6548

wafwerar's avatar
wafwerar 已提交
6549
  SOperatorInfo* pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
L
Liu Jicong 已提交
6550 6551
  pOperator->name = "AllMultiTableTimeIntervalOperator";
  //  pOperator->operatorType = OP_AllMultiTableTimeInterval;
6552
  pOperator->blockingOptr = true;
L
Liu Jicong 已提交
6553 6554 6555 6556 6557
  pOperator->status = OP_NOT_OPENED;
  pOperator->pExpr = pExpr;
  pOperator->numOfOutput = numOfOutput;
  pOperator->info = pInfo;
  pOperator->pRuntimeEnv = pRuntimeEnv;
6558

H
Haojun Liao 已提交
6559
  pOperator->getNextFn = doAllSTableIntervalAgg;
H
Haojun Liao 已提交
6560
  pOperator->closeFn = destroyBasicOperatorInfo;
6561

L
Liu Jicong 已提交
6562
  int32_t code = appendDownstream(pOperator, &downstream, 1);
6563 6564 6565 6566

  return pOperator;
}

H
Haojun Liao 已提交
6567
static int32_t initFillInfo(SFillOperatorInfo* pInfo, SExprInfo* pExpr, int32_t numOfCols, int64_t* fillVal,
L
Liu Jicong 已提交
6568
                            STimeWindow win, int32_t capacity, const char* id, SInterval* pInterval, int32_t fillType) {
H
Haojun Liao 已提交
6569 6570 6571 6572 6573 6574 6575 6576 6577 6578
  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 已提交
6579 6580
  pInfo->pFillInfo = taosCreateFillInfo(order, w.skey, 0, capacity, numOfCols, pInterval->sliding,
                                        pInterval->slidingUnit, (int8_t)pInterval->precision, fillType, pColInfo, id);
H
Haojun Liao 已提交
6581

wafwerar's avatar
wafwerar 已提交
6582
  pInfo->p = taosMemoryCalloc(numOfCols, POINTER_BYTES);
H
Haojun Liao 已提交
6583 6584 6585 6586 6587 6588 6589 6590

  if (pInfo->pFillInfo == NULL || pInfo->p == NULL) {
    return TSDB_CODE_OUT_OF_MEMORY;
  } else {
    return TSDB_CODE_SUCCESS;
  }
}

L
Liu Jicong 已提交
6591 6592 6593
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 已提交
6594
  SFillOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SFillOperatorInfo));
L
Liu Jicong 已提交
6595
  SOperatorInfo*     pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
6596

L
Liu Jicong 已提交
6597
  pInfo->pRes = pResBlock;
6598
  pInfo->multigroupResult = multigroupResult;
L
Liu Jicong 已提交
6599
  pInfo->intervalInfo = *pInterval;
6600

H
Haojun Liao 已提交
6601
  SResultInfo* pResultInfo = &pOperator->resultInfo;
L
Liu Jicong 已提交
6602 6603
  int32_t      code = initFillInfo(pInfo, pExpr, numOfCols, (int64_t*)fillVal, pTaskInfo->window, pResultInfo->capacity,
                                   pTaskInfo->id.str, pInterval, fillType);
6604 6605 6606
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
6607

L
Liu Jicong 已提交
6608
  pOperator->name = "FillOperator";
6609
  pOperator->blockingOptr = false;
L
Liu Jicong 已提交
6610 6611 6612 6613 6614 6615 6616 6617
  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;
6618

L
Liu Jicong 已提交
6619
  pOperator->closeFn = destroySFillOperatorInfo;
H
Haojun Liao 已提交
6620

6621
  code = appendDownstream(pOperator, &downstream, 1);
6622
  return pOperator;
H
Haojun Liao 已提交
6623

L
Liu Jicong 已提交
6624
_error:
wafwerar's avatar
wafwerar 已提交
6625 6626
  taosMemoryFreeClear(pOperator);
  taosMemoryFreeClear(pInfo);
H
Haojun Liao 已提交
6627
  return NULL;
6628 6629
}

L
Liu Jicong 已提交
6630 6631
SOperatorInfo* createSLimitOperatorInfo(STaskRuntimeEnv* pRuntimeEnv, SOperatorInfo* downstream, SExprInfo* pExpr,
                                        int32_t numOfOutput, void* pMerger, bool multigroupResult) {
wafwerar's avatar
wafwerar 已提交
6632
  SSLimitOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SSLimitOperatorInfo));
L
Liu Jicong 已提交
6633 6634 6635 6636 6637 6638 6639 6640 6641 6642
  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;
6643 6644 6645

  // TODO refactor
  int32_t len = 0;
L
Liu Jicong 已提交
6646
  for (int32_t i = 0; i < numOfOutput; ++i) {
6647 6648 6649
    len += pExpr[i].base.resSchema.bytes;
  }

L
Liu Jicong 已提交
6650
  int32_t numOfCols = (pInfo->orderColumnList != NULL) ? (int32_t)taosArrayGetSize(pInfo->orderColumnList) : 0;
wafwerar's avatar
wafwerar 已提交
6651
  pInfo->prevRow = taosMemoryCalloc(1, (POINTER_BYTES * numOfCols + len));
6652 6653

  int32_t offset = POINTER_BYTES * numOfCols;
L
Liu Jicong 已提交
6654
  for (int32_t i = 0; i < numOfCols; ++i) {
6655 6656 6657 6658 6659 6660
    pInfo->prevRow[i] = (char*)pInfo->prevRow + offset;

    SColIndex* index = taosArrayGet(pInfo->orderColumnList, i);
    offset += pExpr[index->colIndex].base.resSchema.bytes;
  }

L
Liu Jicong 已提交
6661
  //  pInfo->pRes = createOutputBuf(pExpr, numOfOutput, pOperator->resultInfo.capacity);
6662

L
Liu Jicong 已提交
6663
  pOperator->name = "SLimitOperator";
X
Xiaoyu Wang 已提交
6664
  // pOperator->operatorType = OP_SLimit;
6665
  pOperator->blockingOptr = false;
L
Liu Jicong 已提交
6666 6667 6668 6669
  pOperator->status = OP_NOT_OPENED;
  //  pOperator->exec         = doSLimit;
  pOperator->info = pInfo;
  pOperator->pRuntimeEnv = pRuntimeEnv;
H
Haojun Liao 已提交
6670
  pOperator->closeFn = destroySlimitOperatorInfo;
6671

L
Liu Jicong 已提交
6672
  int32_t code = appendDownstream(pOperator, &downstream, 1);
6673 6674 6675
  return pOperator;
}

L
Liu Jicong 已提交
6676
static SSDataBlock* doTagScan(SOperatorInfo* pOperator, bool* newgroup) {
6677 6678 6679 6680 6681 6682
#if 0
  SOperatorInfo* pOperator = (SOperatorInfo*) param;
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

H
Haojun Liao 已提交
6683
  STaskRuntimeEnv* pRuntimeEnv = pOperator->pRuntimeEnv;
H
Haojun Liao 已提交
6684
  int32_t maxNumOfTables = (int32_t)pResultInfo->capacity;
6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705

  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) {
6706
      if (pQueryAttr->tagColList[i].colId == pExprInfo->base.pColumns->info.colId) {
6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737
        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;
6738
      if (pExprInfo->base.pColumns->info.colId == TSDB_TBNAME_COLUMN_INDEX) {
6739 6740
        data = tsdbGetTableName(item->pTable);
      } else {
6741
        data = tsdbGetTableTagVal(item->pTable, pExprInfo->base.pColumns->info.colId, type, bytes);
6742 6743 6744 6745 6746 6747
      }

      doSetTagValueToResultBuf(output, data, type, bytes);
      count += 1;
    }

6748
    //qDebug("QInfo:0x%"PRIx64" create (tableId, tag) info completed, rows:%d", GET_TASKID(pRuntimeEnv), count);
6749 6750 6751 6752 6753 6754
  } 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;
6755
    //qDebug("QInfo:0x%"PRIx64" create count(tbname) query, res:%d rows:1", GET_TASKID(pRuntimeEnv), count);
6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768
  } 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
6769
        if (TSDB_COL_IS_UD_COL(pExprInfo[j].base.pColumns->flag)) {
6770 6771 6772 6773 6774 6775 6776
          continue;
        }

        SColumnInfoData* pColInfo = taosArrayGet(pRes->pDataBlock, j);
        type  = pExprInfo[j].base.resSchema.type;
        bytes = pExprInfo[j].base.resSchema.bytes;

6777
        if (pExprInfo[j].base.pColumns->info.colId == TSDB_TBNAME_COLUMN_INDEX) {
6778 6779
          data = tsdbGetTableName(item->pTable);
        } else {
6780
          data = tsdbGetTableTagVal(item->pTable, pExprInfo[j].base.pColumns->info.colId, type, bytes);
6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793
        }

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

6794
    //qDebug("QInfo:0x%"PRIx64" create tag values results completed, rows:%d", GET_TASKID(pRuntimeEnv), count);
6795 6796 6797
  }

  if (pOperator->status == OP_EXEC_DONE) {
6798
    setTaskStatus(pOperator->pRuntimeEnv, TASK_COMPLETED);
6799 6800 6801 6802 6803 6804 6805 6806
  }

  pRes->info.rows = count;
  return (pRes->info.rows == 0)? NULL:pInfo->pRes;

#endif
}

H
Haojun Liao 已提交
6807
SOperatorInfo* createTagScanOperatorInfo(STaskRuntimeEnv* pRuntimeEnv, SExprInfo* pExpr, int32_t numOfOutput) {
wafwerar's avatar
wafwerar 已提交
6808
  STagScanInfo* pInfo = taosMemoryCalloc(1, sizeof(STagScanInfo));
L
Liu Jicong 已提交
6809
  //  pInfo->pRes = createOutputBuf(pExpr, numOfOutput, pResultInfo->capacity);
6810 6811 6812 6813 6814 6815 6816

  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 已提交
6817
  SOperatorInfo* pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
L
Liu Jicong 已提交
6818
  pOperator->name = "SeqTableTagScan";
X
Xiaoyu Wang 已提交
6819
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_TAG_SCAN;
6820
  pOperator->blockingOptr = false;
L
Liu Jicong 已提交
6821 6822
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
H
Haojun Liao 已提交
6823
  pOperator->getNextFn = doTagScan;
L
Liu Jicong 已提交
6824 6825 6826
  pOperator->pExpr = pExpr;
  pOperator->numOfOutput = numOfOutput;
  pOperator->pRuntimeEnv = pRuntimeEnv;
H
Haojun Liao 已提交
6827
  pOperator->closeFn = destroyTagScanOperatorInfo;
6828 6829 6830

  return pOperator;
}
H
Haojun Liao 已提交
6831

6832

L
Liu Jicong 已提交
6833
static int32_t getColumnIndexInSource(SQueriedTableInfo* pTableInfo, SExprBasicInfo* pExpr, SColumnInfo* pTagCols) {
6834 6835
  int32_t j = 0;

H
Haojun Liao 已提交
6836 6837
  if (TSDB_COL_IS_TAG(pExpr->pParam[0].pCol->type)) {
    if (pExpr->pParam[0].pCol->colId == TSDB_TBNAME_COLUMN_INDEX) {
6838 6839 6840
      return TSDB_TBNAME_COLUMN_INDEX;
    }

L
Liu Jicong 已提交
6841
    while (j < pTableInfo->numOfTags) {
H
Haojun Liao 已提交
6842
      if (pExpr->pParam[0].pCol->colId == pTagCols[j].colId) {
6843 6844 6845 6846 6847 6848
        return j;
      }

      j += 1;
    }

6849
  } /*else if (TSDB_COL_IS_UD_COL(pExpr->colInfo.flag)) {  // user specified column data
6850 6851 6852 6853 6854 6855 6856 6857 6858
    return TSDB_UD_COLUMN_INDEX;
  } else {
    while (j < pTableInfo->numOfCols) {
      if (pExpr->colInfo.colId == pTableInfo->colList[j].colId) {
        return j;
      }

      j += 1;
    }
6859
  }*/
6860 6861 6862 6863

  return INT32_MIN;  // return a less than TSDB_TBNAME_COLUMN_INDEX value
}

L
Liu Jicong 已提交
6864
bool validateExprColumnInfo(SQueriedTableInfo* pTableInfo, SExprBasicInfo* pExpr, SColumnInfo* pTagCols) {
6865 6866 6867 6868 6869 6870
  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 已提交
6871
    SColumnFilterInfo* pFilterMsg = (SColumnFilterInfo*)(*pMsg);
6872

L
Liu Jicong 已提交
6873
    SColumnFilterInfo* pColFilter = &pColFilters[f];
6874 6875 6876 6877 6878 6879 6880
    pColFilter->filterstr = htons(pFilterMsg->filterstr);

    (*pMsg) += sizeof(SColumnFilterInfo);

    if (pColFilter->filterstr) {
      pColFilter->len = htobe64(pFilterMsg->len);

L
Liu Jicong 已提交
6881 6882
      pColFilter->pz =
          (int64_t)taosMemoryCalloc(1, (size_t)(pColFilter->len + 1 * TSDB_NCHAR_SIZE));  // note: null-terminator
6883 6884 6885 6886
      if (pColFilter->pz == 0) {
        return TSDB_CODE_QRY_OUT_OF_MEMORY;
      }

L
Liu Jicong 已提交
6887
      memcpy((void*)pColFilter->pz, (*pMsg), (size_t)pColFilter->len);
6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900
      (*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 已提交
6901 6902
static SResSchema createResSchema(int32_t type, int32_t bytes, int32_t slotId, int32_t scale, int32_t precision,
                                  const char* name) {
H
Haojun Liao 已提交
6903 6904
  SResSchema s = {0};
  s.scale = scale;
L
Liu Jicong 已提交
6905
  s.type = type;
H
Haojun Liao 已提交
6906 6907
  s.bytes = bytes;
  s.colId = slotId;
H
Haojun Liao 已提交
6908
  s.precision = precision;
H
Haojun Liao 已提交
6909 6910 6911 6912
  strncpy(s.name, name, tListLen(s.name));

  return s;
}
H
Haojun Liao 已提交
6913

H
Haojun Liao 已提交
6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930
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 已提交
6931
SExprInfo* createExprInfo(SNodeList* pNodeList, SNodeList* pGroupKeys, int32_t* numOfExprs) {
H
Haojun Liao 已提交
6932
  int32_t numOfFuncs = LIST_LENGTH(pNodeList);
H
Haojun Liao 已提交
6933 6934 6935 6936
  int32_t numOfGroupKeys = 0;
  if (pGroupKeys != NULL) {
    numOfGroupKeys = LIST_LENGTH(pGroupKeys);
  }
H
Haojun Liao 已提交
6937

H
Haojun Liao 已提交
6938
  *numOfExprs = numOfFuncs + numOfGroupKeys;
wafwerar's avatar
wafwerar 已提交
6939
  SExprInfo* pExprs = taosMemoryCalloc(*numOfExprs, sizeof(SExprInfo));
H
Haojun Liao 已提交
6940

L
Liu Jicong 已提交
6941
  for (int32_t i = 0; i < (*numOfExprs); ++i) {
H
Haojun Liao 已提交
6942 6943 6944 6945 6946 6947
    STargetNode* pTargetNode = NULL;
    if (i < numOfFuncs) {
      pTargetNode = (STargetNode*)nodesListGetNode(pNodeList, i);
    } else {
      pTargetNode = (STargetNode*)nodesListGetNode(pGroupKeys, i - numOfFuncs);
    }
H
Haojun Liao 已提交
6948

H
Haojun Liao 已提交
6949
    SExprInfo* pExp = &pExprs[pTargetNode->slotId];
H
Haojun Liao 已提交
6950

wafwerar's avatar
wafwerar 已提交
6951
    pExp->pExpr = taosMemoryCalloc(1, sizeof(tExprNode));
H
Haojun Liao 已提交
6952
    pExp->pExpr->_function.num = 1;
H
Haojun Liao 已提交
6953
    pExp->pExpr->_function.functionId = -1;
H
Haojun Liao 已提交
6954

H
Haojun Liao 已提交
6955
    // it is a project query, or group by column
H
Haojun Liao 已提交
6956
    if (nodeType(pTargetNode->pExpr) == QUERY_NODE_COLUMN) {
H
Haojun Liao 已提交
6957
      pExp->pExpr->nodeType = QUERY_NODE_COLUMN;
L
Liu Jicong 已提交
6958
      SColumnNode* pColNode = (SColumnNode*)pTargetNode->pExpr;
H
Haojun Liao 已提交
6959

G
Ganlin Zhao 已提交
6960 6961 6962
      pExp->base.pParam = taosMemoryCalloc(1, sizeof(SFunctParam));
      pExp->base.numOfParams = 1;

H
Haojun Liao 已提交
6963 6964
      SDataType* pType = &pColNode->node.resType;
      pExp->base.resSchema = createResSchema(pType->type, pType->bytes, pTargetNode->slotId, pType->scale, pType->precision, pColNode->colName);
H
Haojun Liao 已提交
6965 6966
      pExp->base.pParam[0].pCol = createColumn(pColNode->dataBlockId, pColNode->slotId, pType);
      pExp->base.pParam[0].type = FUNC_PARAM_TYPE_COLUMN;
6967
    } else if (nodeType(pTargetNode->pExpr) == QUERY_NODE_VALUE) {
6968 6969 6970 6971 6972 6973 6974 6975 6976 6977
      pExp->pExpr->nodeType = QUERY_NODE_VALUE;
      SValueNode* pValNode = (SValueNode*)pTargetNode->pExpr;

      pExp->base.pParam = taosMemoryCalloc(1, sizeof(SFunctParam));
      pExp->base.numOfParams = 1;

      SDataType* pType = &pValNode->node.resType;
      pExp->base.resSchema = createResSchema(pType->type, pType->bytes, pTargetNode->slotId, pType->scale, pType->precision, pValNode->node.aliasName);
      pExp->base.pParam[0].type = FUNC_PARAM_TYPE_VALUE;
      valueNodeToVariant(pValNode, &pExp->base.pParam[0].param);
6978
    } else if (nodeType(pTargetNode->pExpr) == QUERY_NODE_FUNCTION) {
H
Haojun Liao 已提交
6979
      pExp->pExpr->nodeType = QUERY_NODE_FUNCTION;
H
Haojun Liao 已提交
6980 6981 6982
      SFunctionNode* pFuncNode = (SFunctionNode*)pTargetNode->pExpr;

      SDataType* pType = &pFuncNode->node.resType;
L
Liu Jicong 已提交
6983 6984
      pExp->base.resSchema = createResSchema(pType->type, pType->bytes, pTargetNode->slotId, pType->scale,
                                             pType->precision, pFuncNode->node.aliasName);
H
Haojun Liao 已提交
6985

H
Haojun Liao 已提交
6986
      pExp->pExpr->_function.functionId = pFuncNode->funcId;
H
Haojun Liao 已提交
6987
      pExp->pExpr->_function.pFunctNode = pFuncNode;
H
Haojun Liao 已提交
6988
      strncpy(pExp->pExpr->_function.functionName, pFuncNode->functionName, tListLen(pExp->pExpr->_function.functionName));
H
Haojun Liao 已提交
6989 6990 6991

      // TODO: value parameter needs to be handled
      int32_t numOfParam = LIST_LENGTH(pFuncNode->pParameterList);
G
Ganlin Zhao 已提交
6992 6993 6994 6995

      pExp->base.pParam = taosMemoryCalloc(numOfParam, sizeof(SFunctParam));
      pExp->base.numOfParams = numOfParam;

H
Haojun Liao 已提交
6996 6997
      for (int32_t j = 0; j < numOfParam; ++j) {
        SNode*       p1 = nodesListGetNode(pFuncNode->pParameterList, j);
G
Ganlin Zhao 已提交
6998
        if (p1->type == QUERY_NODE_COLUMN) {
H
Haojun Liao 已提交
6999
          SColumnNode* pcn = (SColumnNode*) p1;
G
Ganlin Zhao 已提交
7000 7001

          pExp->base.pParam[j].type = FUNC_PARAM_TYPE_COLUMN;
H
Haojun Liao 已提交
7002
          pExp->base.pParam[j].pCol = createColumn(pcn->dataBlockId, pcn->slotId, &pcn->node.resType);
G
Ganlin Zhao 已提交
7003 7004 7005 7006
        } else if (p1->type == QUERY_NODE_VALUE) {
          SValueNode* pvn = (SValueNode*)p1;
          pExp->base.pParam[j].type = FUNC_PARAM_TYPE_VALUE;
        }
H
Haojun Liao 已提交
7007
      }
7008
    } else if (nodeType(pTargetNode->pExpr) == QUERY_NODE_OPERATOR) {
H
Haojun Liao 已提交
7009
      pExp->pExpr->nodeType = QUERY_NODE_OPERATOR;
L
Liu Jicong 已提交
7010
      SOperatorNode* pNode = (SOperatorNode*)pTargetNode->pExpr;
7011

G
Ganlin Zhao 已提交
7012 7013 7014
      pExp->base.pParam = taosMemoryCalloc(1, sizeof(SFunctParam));
      pExp->base.numOfParams = 1;

7015
      SDataType* pType = &pNode->node.resType;
H
Haojun Liao 已提交
7016
      pExp->base.resSchema = createResSchema(pType->type, pType->bytes, pTargetNode->slotId, pType->scale, pType->precision, pNode->node.aliasName);
7017 7018 7019

      pExp->pExpr->_optrRoot.pRootNode = pTargetNode->pExpr;

H
Haojun Liao 已提交
7020 7021
//      pExp->base.pParam[0].type = FUNC_PARAM_TYPE_COLUMN;
//      pExp->base.pParam[0].pCol = createColumn(pTargetNode->dataBlockId, pTargetNode->slotId, pType);
7022 7023
    } else {
      ASSERT(0);
H
Haojun Liao 已提交
7024 7025 7026
    }
  }

H
Haojun Liao 已提交
7027
  return pExprs;
H
Haojun Liao 已提交
7028 7029
}

7030
static SExecTaskInfo* createExecTaskInfo(uint64_t queryId, uint64_t taskId, EOPTR_EXEC_MODEL model) {
wafwerar's avatar
wafwerar 已提交
7031
  SExecTaskInfo* pTaskInfo = taosMemoryCalloc(1, sizeof(SExecTaskInfo));
7032
  setTaskStatus(pTaskInfo, TASK_NOT_COMPLETED);
H
Haojun Liao 已提交
7033

7034
  pTaskInfo->cost.created = taosGetTimestampMs();
H
Haojun Liao 已提交
7035
  pTaskInfo->id.queryId = queryId;
7036
  pTaskInfo->execModel  = model;
H
Haojun Liao 已提交
7037

wafwerar's avatar
wafwerar 已提交
7038
  char* p = taosMemoryCalloc(1, 128);
L
Liu Jicong 已提交
7039
  snprintf(p, 128, "TID:0x%" PRIx64 " QID:0x%" PRIx64, taskId, queryId);
7040
  pTaskInfo->id.str = strdup(p);
H
Haojun Liao 已提交
7041

7042 7043
  return pTaskInfo;
}
H
Haojun Liao 已提交
7044

L
Liu Jicong 已提交
7045 7046
static tsdbReaderT doCreateDataReader(STableScanPhysiNode* pTableScanNode, SReadHandle* pHandle,
                                      STableGroupInfo* pTableGroupInfo, uint64_t queryId, uint64_t taskId);
H
Haojun Liao 已提交
7047

L
Liu Jicong 已提交
7048 7049
static int32_t doCreateTableGroup(void* metaHandle, int32_t tableType, uint64_t tableUid, STableGroupInfo* pGroupInfo,
                                  uint64_t queryId, uint64_t taskId);
7050 7051
static SArray* extractTableIdList(const STableGroupInfo* pTableGroupInfo);
static SArray* extractScanColumnId(SNodeList* pNodeList);
H
Haojun Liao 已提交
7052
static SArray* extractColumnInfo(SNodeList* pNodeList);
H
Haojun Liao 已提交
7053
static SArray* extractColMatchInfo(SNodeList* pNodeList, SDataBlockDescNode* pOutputNodeList, int32_t* numOfOutputCols);
H
Haojun Liao 已提交
7054
static SArray* createSortInfo(SNodeList* pNodeList);
H
Haojun Liao 已提交
7055

H
Haojun Liao 已提交
7056
SOperatorInfo* createOperatorTree(SPhysiNode* pPhyNode, SExecTaskInfo* pTaskInfo, SReadHandle* pHandle,
L
Liu Jicong 已提交
7057
                                        uint64_t queryId, uint64_t taskId, STableGroupInfo* pTableGroupInfo) {
X
Xiaoyu Wang 已提交
7058 7059 7060
  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 已提交
7061

H
Haojun Liao 已提交
7062
      int32_t     numOfCols = 0;
H
Haojun Liao 已提交
7063 7064
      tsdbReaderT pDataReader = doCreateDataReader((STableScanPhysiNode*)pPhyNode, pHandle, pTableGroupInfo, (uint64_t)queryId, taskId);
      SArray* pColList = extractColMatchInfo(pScanPhyNode->pScanCols, pScanPhyNode->node.pOutputDataBlockDesc, &numOfCols);
L
Liu Jicong 已提交
7065
      return createTableScanOperatorInfo(pDataReader, pScanPhyNode->order, numOfCols, pScanPhyNode->count,
H
Haojun Liao 已提交
7066
                                         pScanPhyNode->reverse, pColList, pScanPhyNode->node.pConditions, pTaskInfo);
X
Xiaoyu Wang 已提交
7067
    } else if (QUERY_NODE_PHYSICAL_PLAN_EXCHANGE == nodeType(pPhyNode)) {
H
Haojun Liao 已提交
7068
      SExchangePhysiNode* pExchange = (SExchangePhysiNode*)pPhyNode;
L
Liu Jicong 已提交
7069
      SSDataBlock*        pResBlock = createOutputBuf_rv1(pExchange->node.pOutputDataBlockDesc);
H
Haojun Liao 已提交
7070
      return createExchangeOperatorInfo(pExchange->pSrcEndPoints, pResBlock, pTaskInfo);
X
Xiaoyu Wang 已提交
7071
    } else if (QUERY_NODE_PHYSICAL_PLAN_STREAM_SCAN == nodeType(pPhyNode)) {
H
Haojun Liao 已提交
7072
      SScanPhysiNode* pScanPhyNode = (SScanPhysiNode*)pPhyNode;  // simple child table.
7073

7074
      int32_t code = doCreateTableGroup(pHandle->meta, pScanPhyNode->tableType, pScanPhyNode->uid, pTableGroupInfo, queryId, taskId);
H
Haojun Liao 已提交
7075
      SArray* tableIdList = extractTableIdList(pTableGroupInfo);
H
Haojun Liao 已提交
7076

7077
      SSDataBlock* pResBlock = createOutputBuf_rv1(pScanPhyNode->node.pOutputDataBlockDesc);
7078 7079 7080 7081

      int32_t numOfCols = 0;
      SArray* pColList = extractColMatchInfo(pScanPhyNode->pScanCols, pScanPhyNode->node.pOutputDataBlockDesc, &numOfCols);
      SOperatorInfo* pOperator = createStreamScanOperatorInfo(pHandle->reader, pResBlock, pColList, tableIdList, pTaskInfo);
7082
      taosArrayDestroy(tableIdList);
H
Haojun Liao 已提交
7083
      return pOperator;
H
Haojun Liao 已提交
7084
    } else if (QUERY_NODE_PHYSICAL_PLAN_SYSTABLE_SCAN == nodeType(pPhyNode)) {
L
Liu Jicong 已提交
7085 7086
      SSystemTableScanPhysiNode* pSysScanPhyNode = (SSystemTableScanPhysiNode*)pPhyNode;
      SSDataBlock*               pResBlock = createOutputBuf_rv1(pSysScanPhyNode->scan.node.pOutputDataBlockDesc);
H
Haojun Liao 已提交
7087

7088
      struct SScanPhysiNode* pScanNode = &pSysScanPhyNode->scan;
L
Liu Jicong 已提交
7089
      SArray*                colList = extractScanColumnId(pScanNode->pScanCols);
7090

L
Liu Jicong 已提交
7091 7092 7093
      SOperatorInfo* pOperator = createSysTableScanOperatorInfo(
          pHandle->meta, pResBlock, &pScanNode->tableName, pScanNode->node.pConditions, pSysScanPhyNode->mgmtEpSet,
          colList, pTaskInfo, pSysScanPhyNode->showRewrite, pSysScanPhyNode->accountId);
H
Haojun Liao 已提交
7094 7095 7096
      return pOperator;
    } else {
      ASSERT(0);
H
Haojun Liao 已提交
7097 7098 7099
    }
  }

H
Haojun Liao 已提交
7100 7101 7102 7103
  if (QUERY_NODE_PHYSICAL_PLAN_PROJECT == nodeType(pPhyNode)) {
    size_t size = LIST_LENGTH(pPhyNode->pChildren);
    assert(size == 1);

H
Haojun Liao 已提交
7104
    SPhysiNode*    pChildNode = (SPhysiNode*)nodesListGetNode(pPhyNode->pChildren, 0);
H
Haojun Liao 已提交
7105
    SOperatorInfo* op = createOperatorTree(pChildNode, pTaskInfo, pHandle, queryId, taskId, pTableGroupInfo);
H
Haojun Liao 已提交
7106

L
Liu Jicong 已提交
7107
    int32_t      num = 0;
H
Haojun Liao 已提交
7108 7109 7110
    SProjectPhysiNode* pProjPhyNode = (SProjectPhysiNode*) pPhyNode;
    SExprInfo*   pExprInfo = createExprInfo(pProjPhyNode->pProjections, NULL, &num);

H
Haojun Liao 已提交
7111
    SSDataBlock* pResBlock = createOutputBuf_rv1(pPhyNode->pOutputDataBlockDesc);
H
Haojun Liao 已提交
7112 7113 7114
    SLimit limit = {.limit = pProjPhyNode->limit, .offset = pProjPhyNode->offset};

    return createProjectOperatorInfo(op, pExprInfo, num, pResBlock, &limit, pTaskInfo);
H
Haojun Liao 已提交
7115
  } else if (QUERY_NODE_PHYSICAL_PLAN_AGG == nodeType(pPhyNode)) {
X
Xiaoyu Wang 已提交
7116
    size_t size = LIST_LENGTH(pPhyNode->pChildren);
H
Haojun Liao 已提交
7117 7118
    assert(size == 1);

H
Haojun Liao 已提交
7119
    for (int32_t i = 0; i < size; ++i) {
H
Haojun Liao 已提交
7120
      SPhysiNode*    pChildNode = (SPhysiNode*)nodesListGetNode(pPhyNode->pChildren, i);
H
Haojun Liao 已提交
7121
      SOperatorInfo* op = createOperatorTree(pChildNode, pTaskInfo, pHandle, queryId, taskId, pTableGroupInfo);
H
Haojun Liao 已提交
7122

H
Haojun Liao 已提交
7123
      int32_t num = 0;
H
Haojun Liao 已提交
7124 7125

      SAggPhysiNode* pAggNode = (SAggPhysiNode*)pPhyNode;
L
Liu Jicong 已提交
7126 7127
      SExprInfo*     pExprInfo = createExprInfo(pAggNode->pAggFuncs, pAggNode->pGroupKeys, &num);
      SSDataBlock*   pResBlock = createOutputBuf_rv1(pPhyNode->pOutputDataBlockDesc);
H
Haojun Liao 已提交
7128 7129 7130

      if (pAggNode->pGroupKeys != NULL) {
        SArray* pColList = extractColumnInfo(pAggNode->pGroupKeys);
7131
        return createGroupOperatorInfo(op, pExprInfo, num, pResBlock, pColList, pAggNode->node.pConditions, pTaskInfo, NULL);
H
Haojun Liao 已提交
7132 7133 7134
      } else {
        return createAggregateOperatorInfo(op, pExprInfo, num, pResBlock, pTaskInfo, pTableGroupInfo);
      }
H
Haojun Liao 已提交
7135
    }
H
Haojun Liao 已提交
7136 7137 7138 7139 7140 7141
  } 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 已提交
7142
      SOperatorInfo* op = createOperatorTree(pChildNode, pTaskInfo, pHandle, queryId, taskId, pTableGroupInfo);
H
Haojun Liao 已提交
7143

7144 7145
      SIntervalPhysiNode* pIntervalPhyNode = (SIntervalPhysiNode*)pPhyNode;

L
Liu Jicong 已提交
7146 7147
      int32_t      num = 0;
      SExprInfo*   pExprInfo = createExprInfo(pIntervalPhyNode->window.pFuncs, NULL, &num);
H
Haojun Liao 已提交
7148
      SSDataBlock* pResBlock = createOutputBuf_rv1(pPhyNode->pOutputDataBlockDesc);
7149

H
Haojun Liao 已提交
7150 7151 7152 7153 7154 7155 7156 7157
      SInterval interval = {
          .interval     = pIntervalPhyNode->interval,
          .sliding      = pIntervalPhyNode->sliding,
          .intervalUnit = pIntervalPhyNode->intervalUnit,
          .slidingUnit  = pIntervalPhyNode->slidingUnit,
          .offset       = pIntervalPhyNode->offset,
          .precision    = pIntervalPhyNode->precision
      };
7158 7159 7160

      int32_t primaryTsSlotId = ((SColumnNode*) pIntervalPhyNode->pTspk)->slotId;
      return createIntervalOperatorInfo(op, pExprInfo, num, pResBlock, &interval, primaryTsSlotId, pTableGroupInfo, pTaskInfo);
H
Haojun Liao 已提交
7161
    }
H
Haojun Liao 已提交
7162 7163 7164 7165
  } else if (QUERY_NODE_PHYSICAL_PLAN_SORT == nodeType(pPhyNode)) {
    size_t size = LIST_LENGTH(pPhyNode->pChildren);
    assert(size == 1);

H
Haojun Liao 已提交
7166
    SPhysiNode*    pChildNode = (SPhysiNode*)nodesListGetNode(pPhyNode->pChildren, 0);
H
Haojun Liao 已提交
7167
    SOperatorInfo* op = createOperatorTree(pChildNode, pTaskInfo, pHandle, queryId, taskId, pTableGroupInfo);
H
Haojun Liao 已提交
7168

H
Haojun Liao 已提交
7169
    SSortPhysiNode* pSortPhyNode = (SSortPhysiNode*)pPhyNode;
H
Haojun Liao 已提交
7170

H
Haojun Liao 已提交
7171 7172
    SSDataBlock* pResBlock = createOutputBuf_rv1(pPhyNode->pOutputDataBlockDesc);
    SArray*      info = createSortInfo(pSortPhyNode->pSortKeys);
H
Haojun Liao 已提交
7173
    return createSortOperatorInfo(op, pResBlock, info, pTaskInfo);
H
Haojun Liao 已提交
7174 7175 7176 7177 7178
  } 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 已提交
7179
    SOperatorInfo* op = createOperatorTree(pChildNode, pTaskInfo, pHandle, queryId, taskId, pTableGroupInfo);
H
Haojun Liao 已提交
7180 7181 7182 7183 7184 7185 7186

    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 已提交
7187 7188
  } else {
    ASSERT(0);
L
Liu Jicong 已提交
7189 7190 7191 7192 7193 7194
  } /*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 已提交
7195
       SOperatorInfo* op = createOperatorTree(pChildNode, pTaskInfo, pHandle, queryId, taskId, pTableGroupInfo);
L
Liu Jicong 已提交
7196 7197 7198
       return createMultiTableAggOperatorInfo(op, pPhyNode->pTargets, pTaskInfo, pTableGroupInfo);
     }
   }*/
7199
}
H
Haojun Liao 已提交
7200

L
Liu Jicong 已提交
7201 7202
static tsdbReaderT createDataReaderImpl(STableScanPhysiNode* pTableScanNode, STableGroupInfo* pGroupInfo,
                                        void* readHandle, uint64_t queryId, uint64_t taskId) {
H
Haojun Liao 已提交
7203
  STsdbQueryCond cond = {.loadExternalRows = false};
H
Haojun Liao 已提交
7204

L
Liu Jicong 已提交
7205
  cond.order = pTableScanNode->scan.order;
X
Xiaoyu Wang 已提交
7206
  cond.numOfCols = LIST_LENGTH(pTableScanNode->scan.pScanCols);
L
Liu Jicong 已提交
7207
  cond.colList = taosMemoryCalloc(cond.numOfCols, sizeof(SColumnInfo));
H
Haojun Liao 已提交
7208 7209 7210 7211 7212
  if (cond.colList == NULL) {
    terrno = TSDB_CODE_QRY_OUT_OF_MEMORY;
    return NULL;
  }

X
Xiaoyu Wang 已提交
7213
  cond.twindow = pTableScanNode->scanRange;
H
Haojun Liao 已提交
7214
  cond.type = BLOCK_LOAD_OFFSET_SEQ_ORDER;
L
Liu Jicong 已提交
7215
  //  cond.type = pTableScanNode->scanFlag;
H
Haojun Liao 已提交
7216

H
Haojun Liao 已提交
7217
  int32_t j = 0;
H
Haojun Liao 已提交
7218
  for (int32_t i = 0; i < cond.numOfCols; ++i) {
H
Haojun Liao 已提交
7219 7220
    STargetNode* pNode = (STargetNode*)nodesListGetNode(pTableScanNode->scan.pScanCols, i);
    SColumnNode* pColNode = (SColumnNode*)pNode->pExpr;
H
Haojun Liao 已提交
7221 7222 7223
    if (pColNode->colType == COLUMN_TYPE_TAG) {
      continue;
    }
H
Haojun Liao 已提交
7224

7225
    cond.colList[j].type  = pColNode->node.resType.type;
H
Haojun Liao 已提交
7226 7227 7228
    cond.colList[j].bytes = pColNode->node.resType.bytes;
    cond.colList[j].colId = pColNode->colId;
    j += 1;
H
Haojun Liao 已提交
7229 7230
  }

H
Haojun Liao 已提交
7231
  cond.numOfCols = j;
H
Haojun Liao 已提交
7232
  return tsdbQueryTables(readHandle, &cond, pGroupInfo, queryId, taskId);
H
Haojun Liao 已提交
7233
}
H
Haojun Liao 已提交
7234

7235
SArray* extractScanColumnId(SNodeList* pNodeList) {
L
Liu Jicong 已提交
7236
  size_t  numOfCols = LIST_LENGTH(pNodeList);
7237 7238 7239 7240 7241 7242
  SArray* pList = taosArrayInit(numOfCols, sizeof(int16_t));
  if (pList == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

L
Liu Jicong 已提交
7243
  for (int32_t i = 0; i < numOfCols; ++i) {
X
Xiaoyu Wang 已提交
7244
    for (int32_t j = 0; j < numOfCols; ++j) {
L
Liu Jicong 已提交
7245
      STargetNode* pNode = (STargetNode*)nodesListGetNode(pNodeList, j);
X
Xiaoyu Wang 已提交
7246
      if (pNode->slotId == i) {
L
Liu Jicong 已提交
7247
        SColumnNode* pColNode = (SColumnNode*)pNode->pExpr;
X
Xiaoyu Wang 已提交
7248 7249 7250 7251
        taosArrayPush(pList, &pColNode->colId);
        break;
      }
    }
7252 7253 7254 7255 7256
  }

  return pList;
}

H
Haojun Liao 已提交
7257
SArray* extractColumnInfo(SNodeList* pNodeList) {
L
Liu Jicong 已提交
7258
  size_t  numOfCols = LIST_LENGTH(pNodeList);
H
Haojun Liao 已提交
7259 7260 7261 7262 7263 7264
  SArray* pList = taosArrayInit(numOfCols, sizeof(SColumn));
  if (pList == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

L
Liu Jicong 已提交
7265 7266 7267
  for (int32_t i = 0; i < numOfCols; ++i) {
    STargetNode* pNode = (STargetNode*)nodesListGetNode(pNodeList, i);
    SColumnNode* pColNode = (SColumnNode*)pNode->pExpr;
H
Haojun Liao 已提交
7268 7269 7270

    SColumn c = {0};
    c.slotId = pColNode->slotId;
L
Liu Jicong 已提交
7271 7272 7273 7274 7275
    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 已提交
7276 7277 7278 7279 7280 7281 7282

    taosArrayPush(pList, &c);
  }

  return pList;
}

H
Haojun Liao 已提交
7283
SArray* createSortInfo(SNodeList* pNodeList) {
L
Liu Jicong 已提交
7284
  size_t  numOfCols = LIST_LENGTH(pNodeList);
H
Haojun Liao 已提交
7285 7286 7287 7288 7289 7290
  SArray* pList = taosArrayInit(numOfCols, sizeof(SBlockOrderInfo));
  if (pList == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return pList;
  }

L
Liu Jicong 已提交
7291 7292 7293 7294 7295
  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 已提交
7296 7297 7298 7299
    bi.nullFirst = (pSortKey->nullOrder == NULL_ORDER_FIRST);

    SColumnNode* pColNode = (SColumnNode*)pSortKey->pExpr;
    bi.slotId = pColNode->slotId;
L
Liu Jicong 已提交
7300 7301 7302 7303 7304 7305 7306 7307
    //    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 已提交
7308 7309 7310 7311 7312 7313 7314

    taosArrayPush(pList, &bi);
  }

  return pList;
}

H
Haojun Liao 已提交
7315
SArray* extractColMatchInfo(SNodeList* pNodeList, SDataBlockDescNode* pOutputNodeList, int32_t* numOfOutputCols) {
L
Liu Jicong 已提交
7316
  size_t  numOfCols = LIST_LENGTH(pNodeList);
H
Haojun Liao 已提交
7317 7318 7319 7320 7321 7322
  SArray* pList = taosArrayInit(numOfCols, sizeof(SColMatchInfo));
  if (pList == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

L
Liu Jicong 已提交
7323 7324 7325
  for (int32_t i = 0; i < numOfCols; ++i) {
    STargetNode* pNode = (STargetNode*)nodesListGetNode(pNodeList, i);
    SColumnNode* pColNode = (SColumnNode*)pNode->pExpr;
H
Haojun Liao 已提交
7326 7327

    SColMatchInfo c = {0};
L
Liu Jicong 已提交
7328
    c.colId = pColNode->colId;
H
Haojun Liao 已提交
7329
    c.targetSlotId = pNode->slotId;
L
Liu Jicong 已提交
7330
    c.output = true;
H
Haojun Liao 已提交
7331 7332 7333
    taosArrayPush(pList, &c);
  }

H
Haojun Liao 已提交
7334 7335 7336
  *numOfOutputCols = 0;

  int32_t num = LIST_LENGTH(pOutputNodeList->pSlots);
L
Liu Jicong 已提交
7337 7338
  for (int32_t i = 0; i < num; ++i) {
    SSlotDescNode* pNode = (SSlotDescNode*)nodesListGetNode(pOutputNodeList->pSlots, i);
H
Haojun Liao 已提交
7339
    SColMatchInfo* info = taosArrayGet(pList, pNode->slotId);
H
Haojun Liao 已提交
7340 7341 7342 7343 7344
    if (pNode->output) {
      (*numOfOutputCols) += 1;
    } else {
      info->output = false;
    }
H
Haojun Liao 已提交
7345 7346
  }

H
Haojun Liao 已提交
7347 7348 7349
  return pList;
}

H
Haojun Liao 已提交
7350
int32_t doCreateTableGroup(void* metaHandle, int32_t tableType, uint64_t tableUid, STableGroupInfo* pGroupInfo, uint64_t queryId, uint64_t taskId) {
7351
  int32_t code = 0;
H
Haojun Liao 已提交
7352
  if (tableType == TSDB_SUPER_TABLE) {
H
Haojun Liao 已提交
7353
    code = tsdbQuerySTableByTagCond(metaHandle, tableUid, 0, NULL, 0, 0, NULL, pGroupInfo, NULL, 0, queryId, taskId);
H
Haojun Liao 已提交
7354
  } else {  // Create one table group.
H
Haojun Liao 已提交
7355
    code = tsdbGetOneTableGroup(metaHandle, tableUid, 0, pGroupInfo);
7356 7357 7358 7359
  }

  return code;
}
H
Haojun Liao 已提交
7360

7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378
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 已提交
7379 7380
tsdbReaderT doCreateDataReader(STableScanPhysiNode* pTableScanNode, SReadHandle* pHandle,
                               STableGroupInfo* pTableGroupInfo, uint64_t queryId, uint64_t taskId) {
7381
  uint64_t uid = pTableScanNode->scan.uid;
L
Liu Jicong 已提交
7382 7383
  int32_t  code =
      doCreateTableGroup(pHandle->meta, pTableScanNode->scan.tableType, uid, pTableGroupInfo, queryId, taskId);
7384 7385
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
H
Haojun Liao 已提交
7386
  }
H
Haojun Liao 已提交
7387

H
Haojun Liao 已提交
7388
  if (pTableGroupInfo->numOfTables == 0) {
H
Haojun Liao 已提交
7389
    code = 0;
L
Liu Jicong 已提交
7390
    qDebug("no table qualified for query, TID:0x%" PRIx64 ", QID:0x%" PRIx64, taskId, queryId);
H
Haojun Liao 已提交
7391 7392
    goto _error;
  }
H
Haojun Liao 已提交
7393

H
Haojun Liao 已提交
7394
  return createDataReaderImpl(pTableScanNode, pTableGroupInfo, pHandle->reader, queryId, taskId);
H
Haojun Liao 已提交
7395

L
Liu Jicong 已提交
7396
_error:
H
Haojun Liao 已提交
7397 7398 7399 7400
  terrno = code;
  return NULL;
}

7401
int32_t createExecTaskInfoImpl(SSubplan* pPlan, SExecTaskInfo** pTaskInfo, SReadHandle* pHandle, uint64_t taskId, EOPTR_EXEC_MODEL model) {
H
Haojun Liao 已提交
7402 7403
  uint64_t queryId = pPlan->id.queryId;

H
Haojun Liao 已提交
7404
  int32_t code = TSDB_CODE_SUCCESS;
7405
  *pTaskInfo = createExecTaskInfo(queryId, taskId, model);
H
Haojun Liao 已提交
7406 7407 7408 7409
  if (*pTaskInfo == NULL) {
    code = TSDB_CODE_QRY_OUT_OF_MEMORY;
    goto _complete;
  }
H
Haojun Liao 已提交
7410

H
Haojun Liao 已提交
7411
  STableGroupInfo group = {0};
H
Haojun Liao 已提交
7412
  (*pTaskInfo)->pRoot = createOperatorTree(pPlan->pNode, *pTaskInfo, pHandle, queryId, taskId, &group);
D
dapan1121 已提交
7413
  if (NULL == (*pTaskInfo)->pRoot) {
L
Liu Jicong 已提交
7414
    code = terrno;
D
dapan1121 已提交
7415 7416
    goto _complete;
  }
H
Haojun Liao 已提交
7417

7418
  if ((*pTaskInfo)->pRoot == NULL) {
H
Haojun Liao 已提交
7419
    code = TSDB_CODE_QRY_OUT_OF_MEMORY;
H
Haojun Liao 已提交
7420
    goto _complete;
7421 7422
  }

H
Haojun Liao 已提交
7423 7424
  return code;

H
Haojun Liao 已提交
7425
_complete:
wafwerar's avatar
wafwerar 已提交
7426
  taosMemoryFreeClear(*pTaskInfo);
H
Haojun Liao 已提交
7427 7428 7429

  terrno = code;
  return code;
H
Haojun Liao 已提交
7430 7431
}

L
Liu Jicong 已提交
7432 7433
static int32_t updateOutputBufForTopBotQuery(SQueriedTableInfo* pTableInfo, SColumnInfo* pTagCols, SExprInfo* pExprs,
                                             int32_t numOfOutput, int32_t tagLen, bool superTable) {
7434 7435 7436 7437 7438 7439 7440 7441 7442
  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 已提交
7443 7444 7445 7446
        //        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);
7447 7448 7449 7450 7451 7452 7453
      }
    }
  }

  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
7454
void setResultBufSize(STaskAttr* pQueryAttr, SResultInfo* pResultInfo) {
7455 7456 7457 7458 7459 7460 7461 7462
  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 已提交
7463 7464 7465 7466 7467 7468 7469 7470 7471 7472
//  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;
//  }
7473 7474

  pResultInfo->threshold = (int32_t)(pResultInfo->capacity * THRESHOLD_RATIO);
H
Haojun Liao 已提交
7475
  pResultInfo->totalRows = 0;
7476 7477
}

L
Liu Jicong 已提交
7478
// TODO refactor
7479
void freeColumnFilterInfo(SColumnFilterInfo* pFilter, int32_t numOfFilters) {
L
Liu Jicong 已提交
7480 7481 7482
  if (pFilter == NULL || numOfFilters == 0) {
    return;
  }
7483

L
Liu Jicong 已提交
7484 7485 7486
  for (int32_t i = 0; i < numOfFilters; i++) {
    if (pFilter[i].filterstr && pFilter[i].pz) {
      taosMemoryFree((void*)(pFilter[i].pz));
7487
    }
L
Liu Jicong 已提交
7488
  }
7489

L
Liu Jicong 已提交
7490
  taosMemoryFree(pFilter);
7491 7492 7493 7494
}

static void doDestroyTableQueryInfo(STableGroupInfo* pTableqinfoGroupInfo) {
  if (pTableqinfoGroupInfo->pGroupList != NULL) {
L
Liu Jicong 已提交
7495
    int32_t numOfGroups = (int32_t)taosArrayGetSize(pTableqinfoGroupInfo->pGroupList);
7496
    for (int32_t i = 0; i < numOfGroups; ++i) {
L
Liu Jicong 已提交
7497
      SArray* p = taosArrayGetP(pTableqinfoGroupInfo->pGroupList, i);
7498 7499

      size_t num = taosArrayGetSize(p);
L
Liu Jicong 已提交
7500
      for (int32_t j = 0; j < num; ++j) {
7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516
        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 已提交
7517
void doDestroyTask(SExecTaskInfo* pTaskInfo) {
H
Haojun Liao 已提交
7518 7519
  qDebug("%s execTask is freed", GET_TASKID(pTaskInfo));

H
Haojun Liao 已提交
7520
  doDestroyTableQueryInfo(&pTaskInfo->tableqinfoGroupInfo);
L
Liu Jicong 已提交
7521 7522
  //  taosArrayDestroy(pTaskInfo->summary.queryProfEvents);
  //  taosHashCleanup(pTaskInfo->summary.operatorProfResults);
7523

wafwerar's avatar
wafwerar 已提交
7524 7525 7526
  taosMemoryFreeClear(pTaskInfo->sql);
  taosMemoryFreeClear(pTaskInfo->id.str);
  taosMemoryFreeClear(pTaskInfo);
7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538
}

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 已提交
7539
      int32_t len = (varDataLen(val) > maxLen) ? maxLen : varDataLen(val);
7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551
      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 已提交
7552 7553
  //  size_t s3 = sizeof(STableCheckInfo);  buffer consumption in tsdb
  return (int64_t)(s1 * 1.5 * numOfTables);
7554 7555 7556 7557 7558 7559 7560
}

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 已提交
7561
    while (1) {
7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587
      int64_t s = tsQueryBufferSizeBytes;
      int64_t remain = s - t;
      if (remain >= 0) {
        if (atomic_val_compare_exchange_64(&tsQueryBufferSizeBytes, s, remain) == s) {
          return TSDB_CODE_SUCCESS;
        }
      } else {
        return TSDB_CODE_QRY_NOT_ENOUGH_BUFFER;
      }
    }
  }

  // disable query processing if the value of tsQueryBufferSize is zero.
  return TSDB_CODE_QRY_NOT_ENOUGH_BUFFER;
}

void releaseQueryBuf(size_t numOfTables) {
  if (tsQueryBufferSizeBytes < 0) {
    return;
  }

  int64_t t = getQuerySupportBufSize(numOfTables);

  // restore value is not enough buffer available
  atomic_add_fetch_64(&tsQueryBufferSizeBytes, t);
}
D
dapan1121 已提交
7588

D
dapan1121 已提交
7589
int32_t getOperatorExplainExecInfo(SOperatorInfo *operatorInfo, SExplainExecInfo **pRes, int32_t *capacity, int32_t *resNum) {
D
dapan1121 已提交
7590 7591 7592 7593 7594
  if (*resNum >= *capacity) {
    *capacity += 10;
    
    *pRes = taosMemoryRealloc(*pRes, (*capacity) * sizeof(SExplainExecInfo));
    if (NULL == *pRes) {
D
dapan1121 已提交
7595
      qError("malloc %d failed", (*capacity) * (int32_t)sizeof(SExplainExecInfo));
D
dapan1121 已提交
7596 7597 7598 7599
      return TSDB_CODE_QRY_OUT_OF_MEMORY;
    }
  }

D
dapan1121 已提交
7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610
  (*pRes)[*resNum].numOfRows = operatorInfo->resultInfo.totalRows;
  (*pRes)[*resNum].startupCost = operatorInfo->cost.openCost;
  (*pRes)[*resNum].totalCost = operatorInfo->cost.totalCost;

  if (operatorInfo->getExplainFn) {
    int32_t code = (*operatorInfo->getExplainFn)(operatorInfo, &(*pRes)->verboseInfo);
    if (code) {
      qError("operator getExplainFn failed, error:%s", tstrerror(code));
      return code;
    }
  }
D
dapan1121 已提交
7611 7612 7613 7614
  
  ++(*resNum);
  
  int32_t code = 0;
D
dapan1121 已提交
7615 7616
  for (int32_t i = 0; i < operatorInfo->numOfDownstream; ++i) {
    code = getOperatorExplainExecInfo(operatorInfo->pDownstream[i], pRes, capacity, resNum);
D
dapan1121 已提交
7617 7618 7619 7620 7621 7622 7623
    if (code) {
      taosMemoryFreeClear(*pRes);
      return TSDB_CODE_QRY_OUT_OF_MEMORY;
    }
  }

  return TSDB_CODE_SUCCESS;
D
dapan1121 已提交
7624 7625 7626
}