executorimpl.c 186.7 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
#include "filter.h"
#include "function.h"
18 19
#include "functionMgt.h"
#include "os.h"
H
Haojun Liao 已提交
20
#include "querynodes.h"
21
#include "tfill.h"
dengyihao's avatar
dengyihao 已提交
22
#include "tname.h"
23

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

30
#include "executorimpl.h"
31
#include "query.h"
32 33
#include "tcompare.h"
#include "tcompression.h"
H
Haojun Liao 已提交
34
#include "thash.h"
35
#include "ttypes.h"
dengyihao's avatar
dengyihao 已提交
36
#include "vnode.h"
wmmhello's avatar
wmmhello 已提交
37
#include "index.h"
38

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

L
Liu Jicong 已提交
45 46
#define SDATA_BLOCK_INITIALIZER \
  (SDataBlockInfo) { {0}, 0 }
47 48 49 50

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

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

#if 0
static UNUSED_FUNC void *u_malloc (size_t __size) {
wafwerar's avatar
wafwerar 已提交
58
  uint32_t v = taosRand();
59 60 61 62

  if (v % 1000 <= 0) {
    return NULL;
  } else {
wafwerar's avatar
wafwerar 已提交
63
    return taosMemoryMalloc(__size);
64 65 66 67
  }
}

static UNUSED_FUNC void* u_calloc(size_t num, size_t __size) {
wafwerar's avatar
wafwerar 已提交
68
  uint32_t v = taosRand();
69 70 71
  if (v % 1000 <= 0) {
    return NULL;
  } else {
wafwerar's avatar
wafwerar 已提交
72
    return taosMemoryCalloc(num, __size);
73 74 75 76
  }
}

static UNUSED_FUNC void* u_realloc(void* p, size_t __size) {
wafwerar's avatar
wafwerar 已提交
77
  uint32_t v = taosRand();
78 79 80
  if (v % 5 <= 1) {
    return NULL;
  } else {
wafwerar's avatar
wafwerar 已提交
81
    return taosMemoryRealloc(p, __size);
82 83 84 85 86 87 88 89 90
  }
}

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

#define CLEAR_QUERY_STATUS(q, st)   ((q)->status &= (~(st)))
wmmhello's avatar
wmmhello 已提交
91
//#define GET_NUM_OF_TABLEGROUP(q)    taosArrayGetSize((q)->tableqinfoGroupInfo.pGroupList)
92 93
#define QUERY_IS_INTERVAL_QUERY(_q) ((_q)->interval.interval > 0)

L
Liu Jicong 已提交
94 95 96
int32_t getMaximumIdleDurationSec() { return tsShellActivityTimer * 2; }

static int32_t getExprFunctionId(SExprInfo* pExprInfo) {
97
  assert(pExprInfo != NULL && pExprInfo->pExpr != NULL && pExprInfo->pExpr->nodeType == TEXPR_UNARYEXPR_NODE);
98
  return 0;
99 100 101 102
}

static void doSetTagValueToResultBuf(char* output, const char* val, int16_t type, int16_t bytes);

103
static void setBlockStatisInfo(SqlFunctionCtx* pCtx, SExprInfo* pExpr, SSDataBlock* pSDataBlock);
104

L
Liu Jicong 已提交
105
static void destroyTableQueryInfoImpl(STableQueryInfo* pTableQueryInfo);
106 107 108

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

X
Xiaoyu Wang 已提交
109
static void releaseQueryBuf(size_t numOfTables);
110

H
Haojun Liao 已提交
111
static int32_t getNumOfScanTimes(STaskAttr* pQueryAttr);
112 113 114 115 116 117

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 destroyAggOperatorInfo(void* param, int32_t numOfOutput);
X
Xiaoyu Wang 已提交
118

H
Haojun Liao 已提交
119
static void destroyIntervalOperatorInfo(void* param, int32_t numOfOutput);
H
Haojun Liao 已提交
120 121
static void destroyExchangeOperatorInfo(void* param, int32_t numOfOutput);

122
static void destroyOperatorInfo(SOperatorInfo* pOperator);
123
static void destroySysTableScannerOperatorInfo(void* param, int32_t numOfOutput);
124

125
void doSetOperatorCompleted(SOperatorInfo* pOperator) {
126
  pOperator->status = OP_EXEC_DONE;
127

128
  pOperator->cost.totalCost = (taosGetTimestampUs() - pOperator->pTaskInfo->cost.start * 1000) / 1000.0;
H
Haojun Liao 已提交
129
  if (pOperator->pTaskInfo != NULL) {
130
    setTaskStatus(pOperator->pTaskInfo, TASK_COMPLETED);
131 132
  }
}
133

H
Haojun Liao 已提交
134
int32_t operatorDummyOpenFn(SOperatorInfo* pOperator) {
135
  OPTR_SET_OPENED(pOperator);
136
  pOperator->cost.openCost = 0;
H
Haojun Liao 已提交
137
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
138 139
}

140
SOperatorFpSet createOperatorFpSet(__optr_open_fn_t openFn, __optr_fn_t nextFn, __optr_fn_t streamFn,
L
Liu Jicong 已提交
141
                                   __optr_fn_t cleanup, __optr_close_fn_t closeFn, __optr_encode_fn_t encode,
142
                                   __optr_decode_fn_t decode, __optr_explain_fn_t explain) {
143 144 145 146 147 148 149 150 151 152 153 154 155 156
  SOperatorFpSet fpSet = {
      ._openFn = openFn,
      .getNextFn = nextFn,
      .getStreamResFn = streamFn,
      .cleanupFn = cleanup,
      .closeFn = closeFn,
      .encodeResultRow = encode,
      .decodeResultRow = decode,
      .getExplainFn = explain,
  };

  return fpSet;
}

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

X
Xiaoyu Wang 已提交
159 160 161
static int32_t doCopyToSDataBlock(SExecTaskInfo* taskInfo, SSDataBlock* pBlock, SExprInfo* pExprInfo,
                                  SDiskbasedBuf* pBuf, SGroupResInfo* pGroupResInfo, const int32_t* rowCellOffset,
                                  SqlFunctionCtx* pCtx, int32_t numOfExprs);
H
Haojun Liao 已提交
162

163
static void initCtxOutputBuffer(SqlFunctionCtx* pCtx, int32_t size);
H
Haojun Liao 已提交
164
static void setResultBufSize(STaskAttr* pQueryAttr, SResultInfo* pResultInfo);
dengyihao's avatar
dengyihao 已提交
165 166
static void doSetTableGroupOutputBuf(SAggOperatorInfo* pAggInfo, int32_t numOfOutput, uint64_t groupId,
                                     SExecTaskInfo* pTaskInfo);
167

H
Haojun Liao 已提交
168
SArray* getOrderCheckColumns(STaskAttr* pQuery);
169 170

typedef struct SRowCompSupporter {
L
Liu Jicong 已提交
171 172 173
  STaskRuntimeEnv* pRuntimeEnv;
  int16_t          dataOffset;
  __compar_fn_t    comFunc;
174 175
} SRowCompSupporter;

L
Liu Jicong 已提交
176 177 178
static int compareRowData(const void* a, const void* b, const void* userData) {
  const SResultRow* pRow1 = (const SResultRow*)a;
  const SResultRow* pRow2 = (const SResultRow*)b;
179

L
Liu Jicong 已提交
180 181
  SRowCompSupporter* supporter = (SRowCompSupporter*)userData;
  STaskRuntimeEnv*   pRuntimeEnv = supporter->pRuntimeEnv;
182

L
Liu Jicong 已提交
183 184
  SFilePage* page1 = getBufPage(pRuntimeEnv->pResultBuf, pRow1->pageId);
  SFilePage* page2 = getBufPage(pRuntimeEnv->pResultBuf, pRow2->pageId);
185 186

  int16_t offset = supporter->dataOffset;
187
  return 0;
X
Xiaoyu Wang 已提交
188 189
  //  char*   in1 = getPosInResultPage(pRuntimeEnv->pQueryAttr, page1, pRow1->offset, offset);
  //  char*   in2 = getPosInResultPage(pRuntimeEnv->pQueryAttr, page2, pRow2->offset, offset);
190

X
Xiaoyu Wang 已提交
191
  //  return (in1 != NULL && in2 != NULL) ? supporter->comFunc(in1, in2) : 0;
192 193
}

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

wafwerar's avatar
wafwerar 已提交
198
  SSDataBlock* pBlock = taosMemoryCalloc(1, sizeof(SSDataBlock));
H
Haojun Liao 已提交
199 200
  pBlock->pDataBlock = taosArrayInit(numOfCols, sizeof(SColumnInfoData));

H
Haojun Liao 已提交
201
  pBlock->info.blockId = pNode->dataBlockId;
dengyihao's avatar
dengyihao 已提交
202
  pBlock->info.rowSize = pNode->totalRowSize;  // todo ??
5
54liuyao 已提交
203
  pBlock->info.type = STREAM_INVALID;
H
Haojun Liao 已提交
204

L
Liu Jicong 已提交
205
  for (int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
206
    SColumnInfoData idata = {{0}};
L
Liu Jicong 已提交
207
    SSlotDescNode*  pDescNode = nodesListGetNode(pNode->pSlots, i);
X
Xiaoyu Wang 已提交
208 209 210
    //    if (!pDescNode->output) {  // todo disable it temporarily
    //      continue;
    //    }
H
Haojun Liao 已提交
211

dengyihao's avatar
dengyihao 已提交
212
    idata.info.type = pDescNode->dataType.type;
L
Liu Jicong 已提交
213 214
    idata.info.bytes = pDescNode->dataType.bytes;
    idata.info.scale = pDescNode->dataType.scale;
H
Haojun Liao 已提交
215
    idata.info.slotId = pDescNode->slotId;
H
Haojun Liao 已提交
216 217
    idata.info.precision = pDescNode->dataType.precision;

H
Hongze Cheng 已提交
218 219 220 221
    if (IS_VAR_DATA_TYPE(idata.info.type)) {
      pBlock->info.hasVarCol = true;
    }

H
Haojun Liao 已提交
222
    taosArrayPush(pBlock->pDataBlock, &idata);
H
Haojun Liao 已提交
223
  }
H
Haojun Liao 已提交
224

225
  pBlock->info.numOfCols = taosArrayGetSize(pBlock->pDataBlock);
H
Haojun Liao 已提交
226
  return pBlock;
H
Haojun Liao 已提交
227 228
}

L
Liu Jicong 已提交
229
static bool hasNull(SColumn* pColumn, SColumnDataAgg* pStatis) {
dengyihao's avatar
dengyihao 已提交
230 231
  if (TSDB_COL_IS_TAG(pColumn->flag) || TSDB_COL_IS_UD_COL(pColumn->flag) ||
      pColumn->colId == PRIMARYKEY_TIMESTAMP_COL_ID) {
232 233 234 235 236 237 238 239 240 241
    return false;
  }

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

  return true;
}

H
Haojun Liao 已提交
242
static void prepareResultListBuffer(SResultRowInfo* pResultRowInfo, jmp_buf env) {
243 244
  int64_t newCapacity = 0;

245 246 247 248 249 250 251 252 253 254 255
  // 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);
  }

256
  if (newCapacity <= pResultRowInfo->capacity) {
H
Haojun Liao 已提交
257 258 259
    newCapacity += 4;
  }

260 261 262 263 264 265
  char* p = taosMemoryRealloc(pResultRowInfo->pPosition, newCapacity * sizeof(SResultRowPosition));
  if (p == NULL) {
    longjmp(env, TSDB_CODE_OUT_OF_MEMORY);
  }

  pResultRowInfo->pPosition = (SResultRowPosition*)p;
266 267

  int32_t inc = (int32_t)newCapacity - pResultRowInfo->capacity;
wmmhello's avatar
wmmhello 已提交
268
  memset(&pResultRowInfo->pPosition[pResultRowInfo->capacity], 0, sizeof(SResultRowPosition) * inc);
269 270 271
  pResultRowInfo->capacity = (int32_t)newCapacity;
}

L
Liu Jicong 已提交
272 273
static bool chkResultRowFromKey(STaskRuntimeEnv* pRuntimeEnv, SResultRowInfo* pResultRowInfo, char* pData,
                                int16_t bytes, bool masterscan, uint64_t uid) {
274 275 276
  bool existed = false;
  SET_RES_WINDOW_KEY(pRuntimeEnv->keyBuf, pData, bytes, uid);

L
Liu Jicong 已提交
277 278
  SResultRow** p1 =
      (SResultRow**)taosHashGet(pRuntimeEnv->pResultRowHashTable, pRuntimeEnv->keyBuf, GET_RES_WINDOW_KEY_LEN(bytes));
279 280 281 282 283 284 285 286 287 288 289

  // 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) {
dengyihao's avatar
dengyihao 已提交
290
        //        existed = (pResultRowInfo->pResult[0] == (*p1));
291 292
      } else {  // check if current pResultRowInfo contains the existed pResultRow
        SET_RES_EXT_WINDOW_KEY(pRuntimeEnv->keyBuf, pData, bytes, uid, pResultRowInfo);
L
Liu Jicong 已提交
293 294
        int64_t* index =
            taosHashGet(pRuntimeEnv->pResultRowListSet, pRuntimeEnv->keyBuf, GET_RES_EXT_WINDOW_KEY_LEN(bytes));
295 296 297 298 299 300 301 302 303 304 305 306 307 308
        if (index != NULL) {
          existed = true;
        } else {
          existed = false;
        }
      }
    }

    return existed;
  }

  return p1 != NULL;
}

309
SResultRow* getNewResultRow_rv(SDiskbasedBuf* pResultBuf, int64_t tableGroupId, int32_t interBufSize) {
L
Liu Jicong 已提交
310
  SFilePage* pData = NULL;
311 312 313 314 315 316 317 318 319 320 321 322 323

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

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

wmmhello's avatar
wmmhello 已提交
324
    if (pData->num + interBufSize > getBufPageSize(pResultBuf)) {
325 326 327 328 329 330 331 332 333 334 335 336 337 338
      // 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;
  }

339 340
  setBufPageDirty(pData, true);

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

wmmhello's avatar
wmmhello 已提交
346
  pData->num += interBufSize;
347 348 349 350

  return pResultRow;
}

351 352 353 354 355 356 357
/**
 * the struct of key in hash table
 * +----------+---------------+
 * | group id |   key data    |
 * | 8 bytes  | actual length |
 * +----------+---------------+
 */
358 359 360
SResultRow* doSetResultOutBufByKey(SDiskbasedBuf* pResultBuf, SResultRowInfo* pResultRowInfo, char* pData,
                                   int16_t bytes, bool masterscan, uint64_t groupId, SExecTaskInfo* pTaskInfo,
                                   bool isIntervalQuery, SAggSupporter* pSup) {
361
  SET_RES_WINDOW_KEY(pSup->keyBuf, pData, bytes, groupId);
H
Haojun Liao 已提交
362

dengyihao's avatar
dengyihao 已提交
363 364
  SResultRowPosition* p1 =
      (SResultRowPosition*)taosHashGet(pSup->pResultRowHashTable, pSup->keyBuf, GET_RES_WINDOW_KEY_LEN(bytes));
H
Haojun Liao 已提交
365

366 367
  SResultRow* pResult = NULL;

H
Haojun Liao 已提交
368 369
  // in case of repeat scan/reverse scan, no new time window added.
  if (isIntervalQuery) {
370 371
    if (masterscan && p1 != NULL) {  // the *p1 may be NULL in case of sliding+offset exists.
      pResult = getResultRowByPos(pResultBuf, p1);
372
      ASSERT(pResult->pageId == p1->pageId && pResult->offset == p1->offset);
H
Haojun Liao 已提交
373 374
    }
  } else {
dengyihao's avatar
dengyihao 已提交
375 376
    // In case of group by column query, the required SResultRow object must be existInCurrentResusltRowInfo in the
    // pResultRowInfo object.
H
Haojun Liao 已提交
377
    if (p1 != NULL) {
378
      pResult = getResultRowByPos(pResultBuf, p1);
379
      ASSERT(pResult->pageId == p1->pageId && pResult->offset == p1->offset);
H
Haojun Liao 已提交
380 381 382
    }
  }

L
Liu Jicong 已提交
383
  // 1. close current opened time window
384
  if (pResultRowInfo->cur.pageId != -1 && ((pResult == NULL) || (pResult->pageId != pResultRowInfo->cur.pageId &&
L
Liu Jicong 已提交
385
                                                                 pResult->offset != pResultRowInfo->cur.offset))) {
386 387 388 389 390 391 392 393 394 395 396
    // todo extract function
    SResultRowPosition pos = pResultRowInfo->cur;
    SFilePage*         pPage = getBufPage(pResultBuf, pos.pageId);
    SResultRow*        pRow = (SResultRow*)((char*)pPage + pos.offset);
    closeResultRow(pRow);
    releaseBufPage(pResultBuf, pPage);
  }

  // allocate a new buffer page
  prepareResultListBuffer(pResultRowInfo, pTaskInfo->env);
  if (pResult == NULL) {
H
Haojun Liao 已提交
397
    ASSERT(pSup->resultRowSize > 0);
398 399
    pResult = getNewResultRow_rv(pResultBuf, groupId, pSup->resultRowSize);
    initResultRow(pResult);
H
Haojun Liao 已提交
400

401 402
    // add a new result set for a new group
    SResultRowPosition pos = {.pageId = pResult->pageId, .offset = pResult->offset};
L
Liu Jicong 已提交
403 404
    taosHashPut(pSup->pResultRowHashTable, pSup->keyBuf, GET_RES_WINDOW_KEY_LEN(bytes), &pos,
                sizeof(SResultRowPosition));
H
Haojun Liao 已提交
405 406
  }

407 408 409 410 411
  // 2. set the new time window to be the new active time window
  pResultRowInfo->pPosition[pResultRowInfo->size++] =
      (SResultRowPosition){.pageId = pResult->pageId, .offset = pResult->offset};
  pResultRowInfo->cur = (SResultRowPosition){.pageId = pResult->pageId, .offset = pResult->offset};

H
Haojun Liao 已提交
412 413 414 415 416
  // 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 已提交
417
  return pResult;
H
Haojun Liao 已提交
418 419
}

420
// get the correct time window according to the handled timestamp
L
Liu Jicong 已提交
421
static STimeWindow getCurrentActiveTimeWindow(SResultRowInfo* pResultRowInfo, int64_t ts, STaskAttr* pQueryAttr) {
422
  STimeWindow w = {0};
H
Haojun Liao 已提交
423
#if 0
L
Liu Jicong 已提交
424 425
  if (pResultRowInfo->curPos == -1) {  // the first window, from the previous stored value
                                       //    getInitialStartTimeWindow(pQueryAttr, ts, &w);
426 427

    if (pQueryAttr->interval.intervalUnit == 'n' || pQueryAttr->interval.intervalUnit == 'y') {
L
Liu Jicong 已提交
428 429 430
      w.ekey =
          taosTimeAdd(w.skey, pQueryAttr->interval.interval, pQueryAttr->interval.intervalUnit, pQueryAttr->precision) -
          1;
431 432 433 434
    } else {
      w.ekey = w.skey + pQueryAttr->interval.interval - 1;
    }
  } else {
H
Haojun Liao 已提交
435
    w = pRow->win;
436 437 438 439 440 441 442 443 444
  }

  /*
   * 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 已提交
445
#endif
446 447 448 449 450

  return w;
}

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

L
Liu Jicong 已提交
456
  SFilePage* pData = NULL;
457 458 459 460 461 462

  // 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 已提交
463
    pData = getNewBufPage(pResultBuf, tid, &pageId);
464
    pData->num = sizeof(SFilePage);
465 466
  } else {
    SPageInfo* pi = getLastPageInfo(list);
467
    pData = getBufPage(pResultBuf, getPageId(pi));
468
    pageId = getPageId(pi);
469

470
    if (pData->num + size > getBufPageSize(pResultBuf)) {
471
      // release current page first, and prepare the next one
472
      releaseBufPageInfo(pResultBuf, pi);
473

H
Haojun Liao 已提交
474
      pData = getNewBufPage(pResultBuf, tid, &pageId);
475
      if (pData != NULL) {
476
        pData->num = sizeof(SFilePage);
477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
      }
    }
  }

  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 已提交
497 498 499
static bool chkWindowOutputBufByKey(STaskRuntimeEnv* pRuntimeEnv, SResultRowInfo* pResultRowInfo, STimeWindow* win,
                                    bool masterscan, SResultRow** pResult, int64_t groupId, SqlFunctionCtx* pCtx,
                                    int32_t numOfOutput, int32_t* rowCellInfoOffset) {
500
  assert(win->skey <= win->ekey);
L
Liu Jicong 已提交
501
  return chkResultRowFromKey(pRuntimeEnv, pResultRowInfo, (char*)&win->skey, TSDB_KEYSIZE, masterscan, groupId);
502 503
}

dengyihao's avatar
dengyihao 已提交
504 505
static void doUpdateResultRowIndex(SResultRowInfo* pResultRowInfo, TSKEY lastKey, bool ascQuery,
                                   bool timeWindowInterpo) {
506
  int64_t skey = TSKEY_INITIAL_VAL;
H
Haojun Liao 已提交
507
#if 0
508 509
  int32_t i = 0;
  for (i = pResultRowInfo->size - 1; i >= 0; --i) {
L
Liu Jicong 已提交
510
    SResultRow* pResult = pResultRowInfo->pResult[i];
511 512 513 514 515 516
    if (pResult->closed) {
      break;
    }

    // new closed result rows
    if (timeWindowInterpo) {
L
Liu Jicong 已提交
517 518 519
      if (pResult->endInterp &&
          ((pResult->win.skey <= lastKey && ascQuery) || (pResult->win.skey >= lastKey && !ascQuery))) {
        if (i > 0) {  // the first time window, the startInterp is false.
520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
          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 已提交
539
      //      assert(pResultRowInfo->current == NULL);
540 541 542 543 544 545 546
      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 已提交
547
      SResultRow* pResult = pResultRowInfo->pResult[i];
548 549 550 551 552 553 554 555 556 557 558
      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 已提交
559
#endif
560
}
561
//
dengyihao's avatar
dengyihao 已提交
562
// static void updateResultRowInfoActiveIndex(SResultRowInfo* pResultRowInfo, const STimeWindow* pWin, TSKEY lastKey,
563 564 565 566 567 568 569 570 571
//                                           bool ascQuery, bool interp) {
//  if ((lastKey > pWin->ekey && ascQuery) || (lastKey < pWin->ekey && (!ascQuery))) {
//    closeAllResultRows(pResultRowInfo);
//    pResultRowInfo->curPos = pResultRowInfo->size - 1;
//  } else {
//    int32_t step = ascQuery ? 1 : -1;
//    doUpdateResultRowIndex(pResultRowInfo, lastKey - step, ascQuery, interp);
//  }
//}
572

573
//  query_range_start, query_range_end, window_duration, window_start, window_end
574
void initExecTimeWindowInfo(SColumnInfoData* pColData, STimeWindow* pQueryWindow) {
575 576 577
  pColData->info.type = TSDB_DATA_TYPE_TIMESTAMP;
  pColData->info.bytes = sizeof(int64_t);

578
  colInfoDataEnsureCapacity(pColData, 0, 5);
579 580 581 582 583 584 585 586 587
  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);
}

X
Xiaoyu Wang 已提交
588 589 590
void doApplyFunctions(SExecTaskInfo* taskInfo, SqlFunctionCtx* pCtx, STimeWindow* pWin,
                      SColumnInfoData* pTimeWindowData, int32_t offset, int32_t forwardStep, TSKEY* tsCol,
                      int32_t numOfTotal, int32_t numOfOutput, int32_t order) {
591
  for (int32_t k = 0; k < numOfOutput; ++k) {
H
Haojun Liao 已提交
592
    // keep it temporarily
dengyihao's avatar
dengyihao 已提交
593 594
    bool    hasAgg = pCtx[k].input.colDataAggIsSet;
    int32_t numOfRows = pCtx[k].input.numOfRows;
H
Haojun Liao 已提交
595
    int32_t startOffset = pCtx[k].input.startRowIndex;
596

597
    pCtx[k].input.startRowIndex = offset;
598
    pCtx[k].input.numOfRows = forwardStep;
599 600

    if (tsCol != NULL) {
H
Haojun Liao 已提交
601
      pCtx[k].ptsList = tsCol;
602 603 604 605
    }

    // not a whole block involved in query processing, statistics data can not be used
    // NOTE: the original value of isSet have been changed here
606 607
    if (pCtx[k].input.colDataAggIsSet && forwardStep < numOfTotal) {
      pCtx[k].input.colDataAggIsSet = false;
608 609
    }

610 611
    if (fmIsWindowPseudoColumnFunc(pCtx[k].functionId)) {
      SResultRowEntryInfo* pEntryInfo = GET_RES_INFO(&pCtx[k]);
dengyihao's avatar
dengyihao 已提交
612
      char*                p = GET_ROWCELL_INTERBUF(pEntryInfo);
613

614
      SColumnInfoData idata = {0};
dengyihao's avatar
dengyihao 已提交
615
      idata.info.type = TSDB_DATA_TYPE_BIGINT;
616
      idata.info.bytes = tDataTypes[TSDB_DATA_TYPE_BIGINT].bytes;
dengyihao's avatar
dengyihao 已提交
617
      idata.pData = p;
618 619 620 621

      SScalarParam out = {.columnData = &idata};
      SScalarParam tw = {.numOfRows = 5, .columnData = pTimeWindowData};
      pCtx[k].sfp.process(&tw, 1, &out);
622 623 624
      pEntryInfo->numOfRes = 1;
      continue;
    }
625
    int32_t code = TSDB_CODE_SUCCESS;
626
    if (functionNeedToExecute(&pCtx[k]) && pCtx[k].fpSet.process != NULL) {
627 628 629 630 631 632
      code = pCtx[k].fpSet.process(&pCtx[k]);
      if (code != TSDB_CODE_SUCCESS) {
        qError("%s apply functions error, code: %s", GET_TASKID(taskInfo), tstrerror(code));
        taskInfo->code = code;
        longjmp(taskInfo->env, code);
      }
633 634 635
    }

    // restore it
636 637 638
    pCtx[k].input.colDataAggIsSet = hasAgg;
    pCtx[k].input.startRowIndex = startOffset;
    pCtx[k].input.numOfRows = numOfRows;
639 640 641
  }
}

L
Liu Jicong 已提交
642
static FORCE_INLINE TSKEY reviseWindowEkey(STaskAttr* pQueryAttr, STimeWindow* pWindow) {
dengyihao's avatar
dengyihao 已提交
643
  TSKEY   ekey = -1;
644 645
  int32_t order = TSDB_ORDER_ASC;
  if (order == TSDB_ORDER_ASC) {
646 647 648 649 650 651 652 653 654 655 656 657 658 659
    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;
}

dengyihao's avatar
dengyihao 已提交
660
static int32_t doSetInputDataBlock(SOperatorInfo* pOperator, SqlFunctionCtx* pCtx, SSDataBlock* pBlock, int32_t order,
661
                                   int32_t scanFlag, bool createDummyCol);
662

dengyihao's avatar
dengyihao 已提交
663 664
static void doSetInputDataBlockInfo(SOperatorInfo* pOperator, SqlFunctionCtx* pCtx, SSDataBlock* pBlock,
                                    int32_t order) {
665
  for (int32_t i = 0; i < pOperator->numOfExprs; ++i) {
666
    pCtx[i].order = order;
667
    pCtx[i].input.numOfRows = pBlock->info.rows;
668
    setBlockStatisInfo(&pCtx[i], &pOperator->pExpr[i], pBlock);
669 670 671
  }
}

X
Xiaoyu Wang 已提交
672 673
void setInputDataBlock(SOperatorInfo* pOperator, SqlFunctionCtx* pCtx, SSDataBlock* pBlock, int32_t order,
                       int32_t scanFlag, bool createDummyCol) {
674
  if (pBlock->pBlockAgg != NULL) {
H
Haojun Liao 已提交
675
    doSetInputDataBlockInfo(pOperator, pCtx, pBlock, order);
676
  } else {
677
    doSetInputDataBlock(pOperator, pCtx, pBlock, order, scanFlag, createDummyCol);
H
Haojun Liao 已提交
678
  }
679 680
}

L
Liu Jicong 已提交
681 682
static int32_t doCreateConstantValColumnInfo(SInputColumnInfoData* pInput, SFunctParam* pFuncParam, int32_t paramIndex,
                                             int32_t numOfRows) {
683 684 685 686 687 688 689 690
  SColumnInfoData* pColInfo = NULL;
  if (pInput->pData[paramIndex] == NULL) {
    pColInfo = taosMemoryCalloc(1, sizeof(SColumnInfoData));
    if (pColInfo == NULL) {
      return TSDB_CODE_OUT_OF_MEMORY;
    }

    // Set the correct column info (data type and bytes)
691 692
    pColInfo->info.type = pFuncParam->param.nType;
    pColInfo->info.bytes = pFuncParam->param.nLen;
693 694

    pInput->pData[paramIndex] = pColInfo;
695 696
  } else {
    pColInfo = pInput->pData[paramIndex];
697 698
  }

699
  colInfoDataEnsureCapacity(pColInfo, 0, numOfRows);
700

701
  int8_t type = pFuncParam->param.nType;
702 703
  if (type == TSDB_DATA_TYPE_BIGINT || type == TSDB_DATA_TYPE_UBIGINT) {
    int64_t v = pFuncParam->param.i;
dengyihao's avatar
dengyihao 已提交
704
    for (int32_t i = 0; i < numOfRows; ++i) {
705 706 707 708
      colDataAppendInt64(pColInfo, i, &v);
    }
  } else if (type == TSDB_DATA_TYPE_DOUBLE) {
    double v = pFuncParam->param.d;
dengyihao's avatar
dengyihao 已提交
709
    for (int32_t i = 0; i < numOfRows; ++i) {
710 711
      colDataAppendDouble(pColInfo, i, &v);
    }
712
  } else if (type == TSDB_DATA_TYPE_VARCHAR) {
L
Liu Jicong 已提交
713
    char* tmp = taosMemoryMalloc(pFuncParam->param.nLen + VARSTR_HEADER_SIZE);
714
    STR_WITH_SIZE_TO_VARSTR(tmp, pFuncParam->param.pz, pFuncParam->param.nLen);
L
Liu Jicong 已提交
715
    for (int32_t i = 0; i < numOfRows; ++i) {
716 717
      colDataAppend(pColInfo, i, tmp, false);
    }
718 719 720 721 722
  }

  return TSDB_CODE_SUCCESS;
}

dengyihao's avatar
dengyihao 已提交
723
static int32_t doSetInputDataBlock(SOperatorInfo* pOperator, SqlFunctionCtx* pCtx, SSDataBlock* pBlock, int32_t order,
X
Xiaoyu Wang 已提交
724
                                   int32_t scanFlag, bool createDummyCol) {
725 726
  int32_t code = TSDB_CODE_SUCCESS;

727
  for (int32_t i = 0; i < pOperator->numOfExprs; ++i) {
L
Liu Jicong 已提交
728
    pCtx[i].order = order;
729 730
    pCtx[i].input.numOfRows = pBlock->info.rows;

L
Liu Jicong 已提交
731
    pCtx[i].pSrcBlock = pBlock;
X
Xiaoyu Wang 已提交
732
    pCtx[i].scanFlag = scanFlag;
H
Haojun Liao 已提交
733

734
    SInputColumnInfoData* pInput = &pCtx[i].input;
735
    pInput->uid = pBlock->info.uid;
C
Cary Xu 已提交
736
    pInput->colDataAggIsSet = false;
737

738 739
    SExprInfo* pOneExpr = &pOperator->pExpr[i];
    for (int32_t j = 0; j < pOneExpr->base.numOfParams; ++j) {
dengyihao's avatar
dengyihao 已提交
740
      SFunctParam* pFuncParam = &pOneExpr->base.pParam[j];
G
Ganlin Zhao 已提交
741 742
      if (pFuncParam->type == FUNC_PARAM_TYPE_COLUMN) {
        int32_t slotId = pFuncParam->pCol->slotId;
dengyihao's avatar
dengyihao 已提交
743
        pInput->pData[j] = taosArrayGet(pBlock->pDataBlock, slotId);
744 745 746
        pInput->totalRows = pBlock->info.rows;
        pInput->numOfRows = pBlock->info.rows;
        pInput->startRowIndex = 0;
747

748
        // NOTE: the last parameter is the primary timestamp column
749 750 751
        if (fmIsTimelineFunc(pCtx[i].functionId) && (j == pOneExpr->base.numOfParams - 1)) {
          pInput->pPTS = pInput->pData[j];
        }
752 753
        ASSERT(pInput->pData[j] != NULL);
      } else if (pFuncParam->type == FUNC_PARAM_TYPE_VALUE) {
754 755 756
        // todo avoid case: top(k, 12), 12 is the value parameter.
        // sum(11), 11 is also the value parameter.
        if (createDummyCol && pOneExpr->base.numOfParams == 1) {
757 758 759 760
          pInput->totalRows = pBlock->info.rows;
          pInput->numOfRows = pBlock->info.rows;
          pInput->startRowIndex = 0;

761
          code = doCreateConstantValColumnInfo(pInput, pFuncParam, j, pBlock->info.rows);
762 763 764
          if (code != TSDB_CODE_SUCCESS) {
            return code;
          }
765
        }
G
Ganlin Zhao 已提交
766 767
      }
    }
H
Haojun Liao 已提交
768
  }
769 770

  return code;
H
Haojun Liao 已提交
771 772
}

773
static int32_t doAggregateImpl(SOperatorInfo* pOperator, TSKEY startTs, SqlFunctionCtx* pCtx) {
774
  for (int32_t k = 0; k < pOperator->numOfExprs; ++k) {
H
Haojun Liao 已提交
775
    if (functionNeedToExecute(&pCtx[k])) {
776 777
      // todo add a dummy funtion to avoid process check
      if (pCtx[k].fpSet.process != NULL) {
778 779
        int32_t code = pCtx[k].fpSet.process(&pCtx[k]);
        if (code != TSDB_CODE_SUCCESS) {
780 781
          qError("%s aggregate function error happens, code: %s", GET_TASKID(pOperator->pTaskInfo), tstrerror(code));
          return code;
782
        }
783
      }
784 785
    }
  }
786 787

  return TSDB_CODE_SUCCESS;
788 789
}

H
Haojun Liao 已提交
790
static void setPseudoOutputColInfo(SSDataBlock* pResult, SqlFunctionCtx* pCtx, SArray* pPseudoList) {
dengyihao's avatar
dengyihao 已提交
791
  size_t num = (pPseudoList != NULL) ? taosArrayGetSize(pPseudoList) : 0;
H
Haojun Liao 已提交
792 793 794 795 796
  for (int32_t i = 0; i < num; ++i) {
    pCtx[i].pOutput = taosArrayGet(pResult->pDataBlock, i);
  }
}

797
int32_t projectApplyFunctions(SExprInfo* pExpr, SSDataBlock* pResult, SSDataBlock* pSrcBlock, SqlFunctionCtx* pCtx,
X
Xiaoyu Wang 已提交
798
                              int32_t numOfOutput, SArray* pPseudoList) {
H
Haojun Liao 已提交
799
  setPseudoOutputColInfo(pResult, pCtx, pPseudoList);
H
Haojun Liao 已提交
800
  pResult->info.groupId = pSrcBlock->info.groupId;
H
Haojun Liao 已提交
801

dengyihao's avatar
dengyihao 已提交
802 803
  // if the source equals to the destination, it is to create a new column as the result of scalar function or some
  // operators.
804 805
  bool createNewColModel = (pResult == pSrcBlock);

806 807
  int32_t numOfRows = 0;

808
  for (int32_t k = 0; k < numOfOutput; ++k) {
dengyihao's avatar
dengyihao 已提交
809
    int32_t         outputSlotId = pExpr[k].base.resSchema.slotId;
810 811
    SqlFunctionCtx* pfCtx = &pCtx[k];

L
Liu Jicong 已提交
812
    if (pExpr[k].pExpr->nodeType == QUERY_NODE_COLUMN) {  // it is a project query
813
      SColumnInfoData* pColInfoData = taosArrayGet(pResult->pDataBlock, outputSlotId);
814
      if (pResult->info.rows > 0 && !createNewColModel) {
X
Xiaoyu Wang 已提交
815 816
        colDataMergeCol(pColInfoData, pResult->info.rows, &pResult->info.capacity, pfCtx->input.pData[0],
                        pfCtx->input.numOfRows);
817 818 819
      } else {
        colDataAssign(pColInfoData, pfCtx->input.pData[0], pfCtx->input.numOfRows);
      }
820

821
      numOfRows = pfCtx->input.numOfRows;
822
    } else if (pExpr[k].pExpr->nodeType == QUERY_NODE_VALUE) {
823
      SColumnInfoData* pColInfoData = taosArrayGet(pResult->pDataBlock, outputSlotId);
824

dengyihao's avatar
dengyihao 已提交
825
      int32_t offset = createNewColModel ? 0 : pResult->info.rows;
826
      for (int32_t i = 0; i < pSrcBlock->info.rows; ++i) {
dengyihao's avatar
dengyihao 已提交
827 828 829
        colDataAppend(pColInfoData, i + offset,
                      taosVariantGet(&pExpr[k].base.pParam[0].param, pExpr[k].base.pParam[0].param.nType),
                      TSDB_DATA_TYPE_NULL == pExpr[k].base.pParam[0].param.nType);
830
      }
831 832

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

837
      SColumnInfoData* pResColData = taosArrayGet(pResult->pDataBlock, outputSlotId);
838
      SColumnInfoData  idata = {.info = pResColData->info, .hasNull = true};
839

840
      SScalarParam dest = {.columnData = &idata};
X
Xiaoyu Wang 已提交
841
      int32_t      code = scalarCalculate(pExpr[k].pExpr->_optrRoot.pRootNode, pBlockList, &dest);
842 843 844 845
      if (code != TSDB_CODE_SUCCESS) {
        taosArrayDestroy(pBlockList);
        return code;
      }
846

dengyihao's avatar
dengyihao 已提交
847
      int32_t startOffset = createNewColModel ? 0 : pResult->info.rows;
848
      colInfoDataEnsureCapacity(pResColData, startOffset, pResult->info.capacity);
849
      colDataMergeCol(pResColData, startOffset, &pResult->info.capacity, &idata, dest.numOfRows);
850 851

      numOfRows = dest.numOfRows;
852 853
      taosArrayDestroy(pBlockList);
    } else if (pExpr[k].pExpr->nodeType == QUERY_NODE_FUNCTION) {
854
      ASSERT(!fmIsAggFunc(pfCtx->functionId));
855

856 857
      // _rowts/_c0, not tbname column
      if (fmIsPseudoColumnFunc(pfCtx->functionId) && (!fmIsScanPseudoColumnFunc(pfCtx->functionId))) {
H
Haojun Liao 已提交
858
        // do nothing
X
Xiaoyu Wang 已提交
859
      } else if (fmIsIndefiniteRowsFunc(pfCtx->functionId)) {
dengyihao's avatar
dengyihao 已提交
860
        SResultRowEntryInfo* pResInfo = GET_RES_INFO(&pCtx[k]);
861
        pfCtx->fpSet.init(&pCtx[k], pResInfo);
862

863
        pfCtx->pOutput = taosArrayGet(pResult->pDataBlock, outputSlotId);
dengyihao's avatar
dengyihao 已提交
864
        pfCtx->offset = createNewColModel ? 0 : pResult->info.rows;  // set the start offset
H
Haojun Liao 已提交
865

866
        // set the timestamp(_rowts) output buffer
867 868
        if (taosArrayGetSize(pPseudoList) > 0) {
          int32_t* outputColIndex = taosArrayGet(pPseudoList, 0);
869
          pfCtx->pTsOutput = (SColumnInfoData*)pCtx[*outputColIndex].pOutput;
870
        }
H
Haojun Liao 已提交
871

872
        numOfRows = pfCtx->fpSet.process(pfCtx);
H
Haojun Liao 已提交
873 874 875
      } else {
        SArray* pBlockList = taosArrayInit(4, POINTER_BYTES);
        taosArrayPush(pBlockList, &pSrcBlock);
G
Ganlin Zhao 已提交
876

877
        SColumnInfoData* pResColData = taosArrayGet(pResult->pDataBlock, outputSlotId);
878
        SColumnInfoData  idata = {.info = pResColData->info, .hasNull = true};
H
Haojun Liao 已提交
879

880
        SScalarParam dest = {.columnData = &idata};
X
Xiaoyu Wang 已提交
881
        int32_t      code = scalarCalculate((SNode*)pExpr[k].pExpr->_function.pFunctNode, pBlockList, &dest);
882 883 884 885
        if (code != TSDB_CODE_SUCCESS) {
          taosArrayDestroy(pBlockList);
          return code;
        }
886

dengyihao's avatar
dengyihao 已提交
887
        int32_t startOffset = createNewColModel ? 0 : pResult->info.rows;
888
        colInfoDataEnsureCapacity(pResColData, startOffset, pResult->info.capacity);
889
        colDataMergeCol(pResColData, startOffset, &pResult->info.capacity, &idata, dest.numOfRows);
890 891

        numOfRows = dest.numOfRows;
H
Haojun Liao 已提交
892 893
        taosArrayDestroy(pBlockList);
      }
894
    } else {
895
      ASSERT(0);
896 897
    }
  }
898

899 900 901
  if (!createNewColModel) {
    pResult->info.rows += numOfRows;
  }
902 903

  return TSDB_CODE_SUCCESS;
904 905
}

906 907 908
static void setResultRowKey(SResultRow* pResultRow, char* pData, int16_t type) {
  if (IS_VAR_DATA_TYPE(type)) {
    // todo disable this
909

910 911 912 913 914 915 916 917 918
    //    if (pResultRow->key == NULL) {
    //      pResultRow->key = taosMemoryMalloc(varDataTLen(pData));
    //      varDataCopy(pResultRow->key, pData);
    //    } else {
    //      ASSERT(memcmp(pResultRow->key, pData, varDataTLen(pData)) == 0);
    //    }
  } else {
    int64_t v = -1;
    GET_TYPED_DATA(v, int64_t, type, pData);
919

920 921
    pResultRow->win.skey = v;
    pResultRow->win.ekey = v;
922 923 924
  }
}

925 926 927 928 929
int32_t setGroupResultOutputBuf(SOptrBasicInfo* binfo, int32_t numOfCols, char* pData, int16_t type, int16_t bytes,
                                int32_t groupId, SDiskbasedBuf* pBuf, SExecTaskInfo* pTaskInfo,
                                SAggSupporter* pAggSup) {
  SResultRowInfo* pResultRowInfo = &binfo->resultRowInfo;
  SqlFunctionCtx* pCtx = binfo->pCtx;
930

931 932 933
  SResultRow* pResultRow =
      doSetResultOutBufByKey(pBuf, pResultRowInfo, (char*)pData, bytes, true, groupId, pTaskInfo, false, pAggSup);
  assert(pResultRow != NULL);
934

935
  setResultRowKey(pResultRow, pData, type);
936
  setResultRowInitCtx(pResultRow, pCtx, numOfCols, binfo->rowCellInfoOffset);
937
  return TSDB_CODE_SUCCESS;
938 939
}

5
54liuyao 已提交
940
bool functionNeedToExecute(SqlFunctionCtx* pCtx) {
941
  struct SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
942

943 944 945 946 947
  // in case of timestamp column, always generated results.
  int32_t functionId = pCtx->functionId;
  if (functionId == -1) {
    return false;
  }
948

949 950
  if (pCtx->scanFlag == REPEAT_SCAN) {
    return fmIsRepeatScanFunc(pCtx->functionId);
951 952
  }

953 954
  if (isRowEntryCompleted(pResInfo)) {
    return false;
955 956
  }

X
Xiaoyu Wang 已提交
957 958 959 960 961 962 963 964
  //  if (functionId == FUNCTION_FIRST_DST || functionId == FUNCTION_FIRST) {
  //    //    return QUERY_IS_ASC_QUERY(pQueryAttr);
  //  }
  //
  //  // denote the order type
  //  if ((functionId == FUNCTION_LAST_DST || functionId == FUNCTION_LAST)) {
  //    //    return pCtx->param[0].i == pQueryAttr->order.order;
  //  }
965

966 967 968 969 970
  // in the reverse table scan, only the following functions need to be executed
  //  if (IS_REVERSE_SCAN(pRuntimeEnv) ||
  //      (pRuntimeEnv->scanFlag == REPEAT_SCAN && functionId != FUNCTION_STDDEV && functionId != FUNCTION_PERCT)) {
  //    return false;
  //  }
971 972 973 974

  return true;
}

975 976 977 978 979 980 981
static int32_t doCreateConstantValColumnAggInfo(SInputColumnInfoData* pInput, SFunctParam* pFuncParam, int32_t type,
                                                int32_t paramIndex, int32_t numOfRows) {
  if (pInput->pData[paramIndex] == NULL) {
    pInput->pData[paramIndex] = taosMemoryCalloc(1, sizeof(SColumnInfoData));
    if (pInput->pData[paramIndex] == NULL) {
      return TSDB_CODE_OUT_OF_MEMORY;
    }
982

983 984 985
    // Set the correct column info (data type and bytes)
    pInput->pData[paramIndex]->info.type = type;
    pInput->pData[paramIndex]->info.bytes = tDataTypes[type].bytes;
986
  }
H
Haojun Liao 已提交
987

988 989 990 991 992 993
  SColumnDataAgg* da = NULL;
  if (pInput->pColumnDataAgg[paramIndex] == NULL) {
    da = taosMemoryCalloc(1, sizeof(SColumnDataAgg));
    pInput->pColumnDataAgg[paramIndex] = da;
    if (da == NULL) {
      return TSDB_CODE_OUT_OF_MEMORY;
994 995
    }
  } else {
996
    da = pInput->pColumnDataAgg[paramIndex];
997 998
  }

999
  ASSERT(!IS_VAR_DATA_TYPE(type));
1000

1001 1002 1003 1004 1005 1006
  if (type == TSDB_DATA_TYPE_BIGINT) {
    int64_t v = pFuncParam->param.i;
    *da = (SColumnDataAgg){.numOfNull = 0, .min = v, .max = v, .maxIndex = 0, .minIndex = 0, .sum = v * numOfRows};
  } else if (type == TSDB_DATA_TYPE_DOUBLE) {
    double v = pFuncParam->param.d;
    *da = (SColumnDataAgg){.numOfNull = 0, .maxIndex = 0, .minIndex = 0};
1007

1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
    *(double*)&da->min = v;
    *(double*)&da->max = v;
    *(double*)&da->sum = v * numOfRows;
  } else if (type == TSDB_DATA_TYPE_BOOL) {  // todo validate this data type
    bool v = pFuncParam->param.i;

    *da = (SColumnDataAgg){.numOfNull = 0, .maxIndex = 0, .minIndex = 0};
    *(bool*)&da->min = 0;
    *(bool*)&da->max = v;
    *(bool*)&da->sum = v * numOfRows;
  } else if (type == TSDB_DATA_TYPE_TIMESTAMP) {
    // do nothing
1020
  } else {
1021
    ASSERT(0);
1022 1023
  }

1024 1025
  return TSDB_CODE_SUCCESS;
}
1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036

void setBlockStatisInfo(SqlFunctionCtx* pCtx, SExprInfo* pExprInfo, SSDataBlock* pBlock) {
  int32_t numOfRows = pBlock->info.rows;

  SInputColumnInfoData* pInput = &pCtx->input;
  pInput->numOfRows = numOfRows;
  pInput->totalRows = numOfRows;

  if (pBlock->pBlockAgg != NULL) {
    pInput->colDataAggIsSet = true;

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

1040 1041
      if (pFuncParam->type == FUNC_PARAM_TYPE_COLUMN) {
        int32_t slotId = pFuncParam->pCol->slotId;
1042 1043 1044 1045
        pInput->pColumnDataAgg[j] = pBlock->pBlockAgg[slotId];
        if (pInput->pColumnDataAgg[j] == NULL) {
          pInput->colDataAggIsSet = false;
        }
1046 1047 1048 1049

        // Here we set the column info data since the data type for each column data is required, but
        // the data in the corresponding SColumnInfoData will not be used.
        pInput->pData[j] = taosArrayGet(pBlock->pDataBlock, slotId);
1050 1051
      } else if (pFuncParam->type == FUNC_PARAM_TYPE_VALUE) {
        doCreateConstantValColumnAggInfo(pInput, pFuncParam, pFuncParam->param.nType, j, pBlock->info.rows);
1052 1053
      }
    }
1054
  } else {
1055
    pInput->colDataAggIsSet = false;
1056 1057 1058
  }

  // set the statistics data for primary time stamp column
1059 1060 1061 1062 1063
  //  if (pCtx->functionId == FUNCTION_SPREAD && pColumn->colId == PRIMARYKEY_TIMESTAMP_COL_ID) {
  //    pCtx->isAggSet = true;
  //    pCtx->agg.min = pBlock->info.window.skey;
  //    pCtx->agg.max = pBlock->info.window.ekey;
  //  }
1064 1065 1066
}

// set the output buffer for the selectivity + tag query
1067
static int32_t setSelectValueColumnInfo(SqlFunctionCtx* pCtx, int32_t numOfOutput) {
1068 1069
  int32_t num = 0;

H
Haojun Liao 已提交
1070
  SqlFunctionCtx*  p = NULL;
1071 1072
  SqlFunctionCtx** pValCtx = taosMemoryCalloc(numOfOutput, POINTER_BYTES);
  if (pValCtx == NULL) {
1073 1074 1075 1076
    return TSDB_CODE_QRY_OUT_OF_MEMORY;
  }

  for (int32_t i = 0; i < numOfOutput; ++i) {
1077 1078
    if (strcmp(pCtx[i].pExpr->pExpr->_function.functionName, "_select_value") == 0) {
      pValCtx[num++] = &pCtx[i];
X
Xiaoyu Wang 已提交
1079
    } else if (fmIsSelectFunc(pCtx[i].functionId)) {
1080
      p = &pCtx[i];
1081
    }
X
Xiaoyu Wang 已提交
1082 1083 1084 1085 1086 1087 1088 1089 1090 1091
    //    if (functionId == FUNCTION_TAG_DUMMY || functionId == FUNCTION_TS_DUMMY) {
    //      tagLen += pCtx[i].resDataInfo.bytes;
    //      pTagCtx[num++] = &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
    //    }
1092
  }
1093

1094
  if (p != NULL) {
1095
    p->subsidiaries.pCtx = pValCtx;
1096
    p->subsidiaries.num = num;
1097
  } else {
1098
    taosMemoryFreeClear(pValCtx);
1099 1100 1101 1102 1103
  }

  return TSDB_CODE_SUCCESS;
}

1104
SqlFunctionCtx* createSqlFunctionCtx(SExprInfo* pExprInfo, int32_t numOfOutput, int32_t** rowCellInfoOffset) {
L
Liu Jicong 已提交
1105
  SqlFunctionCtx* pFuncCtx = (SqlFunctionCtx*)taosMemoryCalloc(numOfOutput, sizeof(SqlFunctionCtx));
H
Haojun Liao 已提交
1106 1107 1108 1109
  if (pFuncCtx == NULL) {
    return NULL;
  }

wafwerar's avatar
wafwerar 已提交
1110
  *rowCellInfoOffset = taosMemoryCalloc(numOfOutput, sizeof(int32_t));
H
Haojun Liao 已提交
1111
  if (*rowCellInfoOffset == 0) {
wafwerar's avatar
wafwerar 已提交
1112
    taosMemoryFreeClear(pFuncCtx);
H
Haojun Liao 已提交
1113 1114 1115 1116
    return NULL;
  }

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

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

1122
    pCtx->functionId = -1;
1123
    pCtx->curBufPage = -1;
L
Liu Jicong 已提交
1124
    pCtx->pExpr = pExpr;
1125

H
Haojun Liao 已提交
1126
    if (pExpr->pExpr->nodeType == QUERY_NODE_FUNCTION) {
H
Haojun Liao 已提交
1127
      SFuncExecEnv env = {0};
H
Haojun Liao 已提交
1128 1129
      pCtx->functionId = pExpr->pExpr->_function.pFunctNode->funcId;

X
Xiaoyu Wang 已提交
1130
      if (fmIsAggFunc(pCtx->functionId) || fmIsIndefiniteRowsFunc(pCtx->functionId)) {
1131 1132 1133 1134
        bool isUdaf = fmIsUserDefinedFunc(pCtx->functionId);
        if (!isUdaf) {
          fmGetFuncExecFuncs(pCtx->functionId, &pCtx->fpSet);
        } else {
1135
          char* udfName = pExpr->pExpr->_function.pFunctNode->functionName;
1136 1137 1138
          strncpy(pCtx->udfName, udfName, strlen(udfName));
          fmGetUdafExecFuncs(pCtx->functionId, &pCtx->fpSet);
        }
1139 1140 1141
        pCtx->fpSet.getEnv(pExpr->pExpr->_function.pFunctNode, &env);
      } else {
        fmGetScalarFuncExecFuncs(pCtx->functionId, &pCtx->sfp);
1142 1143 1144
        if (pCtx->sfp.getEnv != NULL) {
          pCtx->sfp.getEnv(pExpr->pExpr->_function.pFunctNode, &env);
        }
1145
      }
H
Haojun Liao 已提交
1146
      pCtx->resDataInfo.interBufSize = env.calcMemSize;
1147 1148
    } else if (pExpr->pExpr->nodeType == QUERY_NODE_COLUMN || pExpr->pExpr->nodeType == QUERY_NODE_OPERATOR ||
               pExpr->pExpr->nodeType == QUERY_NODE_VALUE) {
H
Haojun Liao 已提交
1149
      // for simple column, the result buffer needs to hold at least one element.
1150
      pCtx->resDataInfo.interBufSize = pFunct->resSchema.bytes;
H
Haojun Liao 已提交
1151
    }
H
Haojun Liao 已提交
1152

H
Haojun Liao 已提交
1153
    pCtx->input.numOfInputCols = pFunct->numOfParams;
wafwerar's avatar
wafwerar 已提交
1154 1155
    pCtx->input.pData = taosMemoryCalloc(pFunct->numOfParams, POINTER_BYTES);
    pCtx->input.pColumnDataAgg = taosMemoryCalloc(pFunct->numOfParams, POINTER_BYTES);
H
Haojun Liao 已提交
1156

1157
    pCtx->pTsOutput = NULL;
L
Liu Jicong 已提交
1158
    pCtx->resDataInfo.bytes = pFunct->resSchema.bytes;
1159
    pCtx->resDataInfo.type = pFunct->resSchema.type;
L
Liu Jicong 已提交
1160
    pCtx->order = TSDB_ORDER_ASC;
1161
    pCtx->start.key = INT64_MIN;
L
Liu Jicong 已提交
1162
    pCtx->end.key = INT64_MIN;
1163
    pCtx->numOfParams = pExpr->base.numOfParams;
H
Haojun Liao 已提交
1164

1165
    pCtx->param = pFunct->pParam;
dengyihao's avatar
dengyihao 已提交
1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199
    //    for (int32_t j = 0; j < pCtx->numOfParams; ++j) {
    //      // 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_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 已提交
1200 1201
  }

L
Liu Jicong 已提交
1202 1203 1204
  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 已提交
1205
  }
H
Haojun Liao 已提交
1206

1207
  setSelectValueColumnInfo(pFuncCtx, numOfOutput);
H
Haojun Liao 已提交
1208 1209 1210
  return pFuncCtx;
}

1211
static void* destroySqlFunctionCtx(SqlFunctionCtx* pCtx, int32_t numOfOutput) {
1212 1213 1214 1215 1216 1217
  if (pCtx == NULL) {
    return NULL;
  }

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

    taosVariantDestroy(&pCtx[i].tag);
1222
    taosMemoryFreeClear(pCtx[i].subsidiaries.pCtx);
H
Haojun Liao 已提交
1223 1224
    taosMemoryFree(pCtx[i].input.pData);
    taosMemoryFree(pCtx[i].input.pColumnDataAgg);
1225 1226
  }

wafwerar's avatar
wafwerar 已提交
1227
  taosMemoryFreeClear(pCtx);
1228 1229 1230
  return NULL;
}

L
Liu Jicong 已提交
1231
bool isTaskKilled(SExecTaskInfo* pTaskInfo) {
1232 1233
  // query has been executed more than tsShellActivityTimer, and the retrieve has not arrived
  // abort current query execution.
L
Liu Jicong 已提交
1234 1235
  if (pTaskInfo->owner != 0 &&
      ((taosGetTimestampSec() - pTaskInfo->cost.start / 1000) > 10 * getMaximumIdleDurationSec())
1236 1237
      /*(!needBuildResAfterQueryComplete(pTaskInfo))*/) {
    assert(pTaskInfo->cost.start != 0);
L
Liu Jicong 已提交
1238 1239 1240
    //    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;
1241 1242 1243 1244 1245
  }

  return false;
}

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

L
Liu Jicong 已提交
1248
static bool isCachedLastQuery(STaskAttr* pQueryAttr) {
1249 1250 1251 1252 1253 1254 1255 1256 1257
  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;
  }

1258 1259
  int32_t order = TSDB_ORDER_ASC;
  if (order != TSDB_ORDER_DESC || !TSWINDOW_IS_EQUAL(pQueryAttr->window, TSWINDOW_DESC_INITIALIZER)) {
1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278
    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 已提交
1279
// todo refactor : return window
1280
void getAlignQueryTimeWindow(SInterval* pInterval, int32_t precision, int64_t key, STimeWindow* win) {
H
Haojun Liao 已提交
1281
  win->skey = taosTimeTruncate(key, pInterval, precision);
1282 1283

  /*
H
Haojun Liao 已提交
1284
   * if the realSkey > INT64_MAX - pInterval->interval, the query duration between
1285 1286
   * realSkey and realEkey must be less than one interval.Therefore, no need to adjust the query ranges.
   */
1287 1288
  win->ekey = taosTimeAdd(win->skey, pInterval->interval, pInterval->intervalUnit, precision) - 1;
  if (win->ekey < win->skey) {
1289 1290 1291 1292
    win->ekey = INT64_MAX;
  }
}

L
Liu Jicong 已提交
1293
static int32_t updateBlockLoadStatus(STaskAttr* pQuery, int32_t status) {
1294 1295 1296
  bool hasFirstLastFunc = false;
  bool hasOtherFunc = false;

1297
  if (status == BLK_DATA_DATA_LOAD || status == BLK_DATA_FILTEROUT) {
1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315
    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;
    }
  }

1316
  if (hasFirstLastFunc && status == BLK_DATA_NOT_LOAD) {
L
Liu Jicong 已提交
1317
    if (!hasOtherFunc) {
1318
      return BLK_DATA_FILTEROUT;
1319
    } else {
1320
      return BLK_DATA_DATA_LOAD;
1321 1322 1323 1324 1325 1326
    }
  }

  return status;
}

L
Liu Jicong 已提交
1327 1328
// static void updateDataCheckOrder(SQInfo *pQInfo, SQueryTableReq* pQueryMsg, bool stableQuery) {
//   STaskAttr* pQueryAttr = pQInfo->runtimeEnv.pQueryAttr;
H
Haojun Liao 已提交
1329
//
L
Liu Jicong 已提交
1330 1331 1332 1333
//   // 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 已提交
1334
//
L
Liu Jicong 已提交
1335 1336 1337 1338 1339
//   // 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 已提交
1340
//
L
Liu Jicong 已提交
1341 1342
//     pQueryAttr->order.order = TSDB_ORDER_ASC;
//     if (pQueryAttr->window.skey > pQueryAttr->window.ekey) {
wafwerar's avatar
wafwerar 已提交
1343
//       TSWAP(pQueryAttr->window.skey, pQueryAttr->window.ekey);
L
Liu Jicong 已提交
1344
//     }
H
Haojun Liao 已提交
1345
//
L
Liu Jicong 已提交
1346 1347 1348
//     pQueryAttr->needReverseScan = false;
//     return;
//   }
H
Haojun Liao 已提交
1349
//
L
Liu Jicong 已提交
1350 1351 1352
//   if (pQueryAttr->groupbyColumn && pQueryAttr->order.order == TSDB_ORDER_DESC) {
//     pQueryAttr->order.order = TSDB_ORDER_ASC;
//     if (pQueryAttr->window.skey > pQueryAttr->window.ekey) {
wafwerar's avatar
wafwerar 已提交
1353
//       TSWAP(pQueryAttr->window.skey, pQueryAttr->window.ekey);
L
Liu Jicong 已提交
1354
//     }
H
Haojun Liao 已提交
1355
//
L
Liu Jicong 已提交
1356 1357 1358 1359
//     pQueryAttr->needReverseScan = false;
//     doUpdateLastKey(pQueryAttr);
//     return;
//   }
H
Haojun Liao 已提交
1360
//
L
Liu Jicong 已提交
1361 1362 1363 1364 1365 1366
//   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 已提交
1367
//
L
Liu Jicong 已提交
1368 1369 1370
//     pQueryAttr->order.order = TSDB_ORDER_ASC;
//     return;
//   }
H
Haojun Liao 已提交
1371
//
L
Liu Jicong 已提交
1372 1373 1374 1375
//   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 已提交
1376 1377
////               pQueryAttr->window.ekey, pQueryAttr->window.ekey, pQueryAttr->window.skey);
//
wafwerar's avatar
wafwerar 已提交
1378
//        TSWAP(pQueryAttr->window.skey, pQueryAttr->window.ekey);
H
Haojun Liao 已提交
1379 1380 1381 1382 1383 1384 1385 1386 1387 1388
//        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);
//
wafwerar's avatar
wafwerar 已提交
1389
//        TSWAP(pQueryAttr->window.skey, pQueryAttr->window.ekey);
H
Haojun Liao 已提交
1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401
//        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 已提交
1402 1403
////                 pQueryAttr->window.skey, pQueryAttr->window.ekey, pQueryAttr->window.ekey,
/// pQueryAttr->window.skey);
H
Haojun Liao 已提交
1404
//
wafwerar's avatar
wafwerar 已提交
1405
//          TSWAP(pQueryAttr->window.skey, pQueryAttr->window.ekey);
H
Haojun Liao 已提交
1406 1407 1408 1409 1410 1411 1412 1413
//          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 已提交
1414 1415
////                 pQueryAttr->window.skey, pQueryAttr->window.ekey, pQueryAttr->window.ekey,
/// pQueryAttr->window.skey);
H
Haojun Liao 已提交
1416
//
wafwerar's avatar
wafwerar 已提交
1417
//          TSWAP(pQueryAttr->window.skey, pQueryAttr->window.ekey);
H
Haojun Liao 已提交
1418 1419 1420 1421 1422 1423 1424 1425 1426
//          doUpdateLastKey(pQueryAttr);
//        }
//
//        pQueryAttr->order.order = TSDB_ORDER_DESC;
//        pQueryAttr->needReverseScan = false;
//      }
//    }
//  }
//}
1427

L
Liu Jicong 已提交
1428 1429 1430
// static FORCE_INLINE bool doFilterByBlockStatistics(STaskRuntimeEnv* pRuntimeEnv, SDataStatis *pDataStatis,
// SqlFunctionCtx *pCtx, int32_t numOfRows) {
//   STaskAttr* pQueryAttr = pRuntimeEnv->pQueryAttr;
1431
//
L
Liu Jicong 已提交
1432 1433 1434
//   if (pDataStatis == NULL || pQueryAttr->pFilters == NULL) {
//     return true;
//   }
1435
//
L
Liu Jicong 已提交
1436 1437
//   return filterRangeExecute(pQueryAttr->pFilters, pDataStatis, pQueryAttr->numOfCols, numOfRows);
// }
1438

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

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

1445
  if (true) {
L
Liu Jicong 已提交
1446
    //    getAlignQueryTimeWindow(pQueryAttr, pBlockInfo->window.skey, sk, ek, &w);
1447 1448 1449 1450 1451 1452
    assert(w.ekey >= pBlockInfo->window.skey);

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

L
Liu Jicong 已提交
1453 1454
    while (1) {
      //      getNextTimeWindow(pQueryAttr, &w);
1455 1456 1457 1458 1459 1460 1461 1462 1463 1464
      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 已提交
1465
    //    getAlignQueryTimeWindow(pQueryAttr, pBlockInfo->window.ekey, sk, ek, &w);
1466 1467 1468 1469 1470 1471
    assert(w.skey <= pBlockInfo->window.ekey);

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

L
Liu Jicong 已提交
1472 1473
    while (1) {
      //      getNextTimeWindow(pQueryAttr, &w);
1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537
      if (w.ekey < pBlockInfo->window.skey) {
        break;
      }

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

  return false;
}

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

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

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

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

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

    start += len;
    len = 0;
  }

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

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

static uint32_t doFilterByBlockTimeWindow(STableScanInfo* pTableScanInfo, SSDataBlock* pBlock) {
H
Haojun Liao 已提交
1538
  SqlFunctionCtx* pCtx = pTableScanInfo->pCtx;
1539
  uint32_t        status = BLK_DATA_NOT_LOAD;
1540 1541 1542 1543

  int32_t numOfOutput = pTableScanInfo->numOfOutput;
  for (int32_t i = 0; i < numOfOutput; ++i) {
    int32_t functionId = pCtx[i].functionId;
H
Haojun Liao 已提交
1544
    int32_t colId = pTableScanInfo->pExpr[i].base.pParam[0].pCol->colId;
1545 1546 1547

    // group by + first/last should not apply the first/last block filter
    if (functionId < 0) {
1548
      status |= BLK_DATA_DATA_LOAD;
1549 1550
      return status;
    } else {
L
Liu Jicong 已提交
1551
      //      status |= aAggs[functionId].dataReqFunc(&pTableScanInfo->pCtx[i], &pBlock->info.window, colId);
1552
      //      if ((status & BLK_DATA_DATA_LOAD) == BLK_DATA_DATA_LOAD) {
L
Liu Jicong 已提交
1553 1554
      //        return status;
      //      }
1555 1556 1557 1558 1559 1560
    }
  }

  return status;
}

L
Liu Jicong 已提交
1561 1562
int32_t loadDataBlockOnDemand(SExecTaskInfo* pTaskInfo, STableScanInfo* pTableScanInfo, SSDataBlock* pBlock,
                              uint32_t* status) {
1563
  *status = BLK_DATA_NOT_LOAD;
1564

H
Haojun Liao 已提交
1565
  pBlock->pDataBlock = NULL;
L
Liu Jicong 已提交
1566
  pBlock->pBlockAgg = NULL;
H
Haojun Liao 已提交
1567

L
Liu Jicong 已提交
1568 1569
  //  int64_t groupId = pRuntimeEnv->current->groupIndex;
  //  bool    ascQuery = QUERY_IS_ASC_QUERY(pQueryAttr);
1570

H
Haojun Liao 已提交
1571
  STaskCostInfo* pCost = &pTaskInfo->cost;
1572

1573 1574
//  pCost->totalBlocks += 1;
//  pCost->totalRows += pBlock->info.rows;
H
Haojun Liao 已提交
1575
#if 0
1576 1577 1578
  // 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 已提交
1579
      (QUERY_IS_INTERVAL_QUERY(pQueryAttr) && overlapWithTimeWindow(pTaskInfo, &pBlock->info))) {
1580
    (*status) = BLK_DATA_DATA_LOAD;
1581 1582 1583
  }

  // check if this data block is required to load
1584
  if ((*status) != BLK_DATA_DATA_LOAD) {
1585 1586 1587 1588 1589 1590 1591
    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 已提交
1592
      bool  masterScan = IS_MAIN_SCAN(pRuntimeEnv);
1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615
      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 {
1616
      (*status) = BLK_DATA_DATA_LOAD;
1617 1618 1619 1620
    }
  }

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

1623
  if ((*status) == BLK_DATA_NOT_LOAD || (*status) == BLK_DATA_FILTEROUT) {
1624 1625
    //qDebug("QInfo:0x%"PRIx64" data block discard, brange:%" PRId64 "-%" PRId64 ", rows:%d", pQInfo->qId, pBlockInfo->window.skey,
//           pBlockInfo->window.ekey, pBlockInfo->rows);
1626
    pCost->skipBlocks += 1;
1627
  } else if ((*status) == BLK_DATA_SMA_LOAD) {
1628 1629
    // this function never returns error?
    pCost->loadBlockStatis += 1;
1630
//    tsdbRetrieveDataBlockStatisInfo(pTableScanInfo->pTsdbReadHandle, &pBlock->pBlockAgg);
1631 1632

    if (pBlock->pBlockAgg == NULL) {  // data block statistics does not exist, load data block
1633
//      pBlock->pDataBlock = tsdbRetrieveDataBlock(pTableScanInfo->pTsdbReadHandle, NULL);
1634 1635 1636
      pCost->totalCheckedRows += pBlock->info.rows;
    }
  } else {
1637
    assert((*status) == BLK_DATA_DATA_LOAD);
1638 1639 1640

    // load the data block statistics to perform further filter
    pCost->loadBlockStatis += 1;
1641
//    tsdbRetrieveDataBlockStatisInfo(pTableScanInfo->pTsdbReadHandle, &pBlock->pBlockAgg);
1642 1643 1644 1645 1646 1647

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

H
Haojun Liao 已提交
1648
          bool  masterScan = IS_MAIN_SCAN(pRuntimeEnv);
1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665
          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
1666
            pCost->skipBlocks += 1;
1667 1668
            //qDebug("QInfo:0x%"PRIx64" data block discard, brange:%" PRId64 "-%" PRId64 ", rows:%d", pQInfo->qId,
//                   pBlockInfo->window.skey, pBlockInfo->window.ekey, pBlockInfo->rows);
1669
            (*status) = BLK_DATA_FILTEROUT;
1670 1671 1672 1673 1674 1675 1676 1677
            return TSDB_CODE_SUCCESS;
          }
        }
      }
    }

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

    pCost->totalCheckedRows += pBlockInfo->rows;
    pCost->loadBlocks += 1;
1687
//    pBlock->pDataBlock = tsdbRetrieveDataBlock(pTableScanInfo->pTsdbReadHandle, NULL);
1688 1689 1690 1691 1692 1693 1694
//    if (pBlock->pDataBlock == NULL) {
//      return terrno;
//    }

//    if (pQueryAttr->pFilters != NULL) {
//      filterSetColFieldData(pQueryAttr->pFilters, pBlock->info.numOfCols, pBlock->pDataBlock);
//    }
1695

1696 1697 1698 1699
//    if (pQueryAttr->pFilters != NULL || pRuntimeEnv->pTsBuf != NULL) {
//      filterColRowsInDataBlock(pRuntimeEnv, pBlock, ascQuery);
//    }
  }
H
Haojun Liao 已提交
1700
#endif
1701 1702 1703
  return TSDB_CODE_SUCCESS;
}

L
Liu Jicong 已提交
1704
static void updateTableQueryInfoForReverseScan(STableQueryInfo* pTableQueryInfo) {
1705 1706 1707 1708
  if (pTableQueryInfo == NULL) {
    return;
  }

wafwerar's avatar
wafwerar 已提交
1709
  //  TSWAP(pTableQueryInfo->win.skey, pTableQueryInfo->win.ekey);
L
Liu Jicong 已提交
1710
  //  pTableQueryInfo->lastKey = pTableQueryInfo->win.skey;
1711

L
Liu Jicong 已提交
1712 1713
  //  SWITCH_ORDER(pTableQueryInfo->cur.order);
  //  pTableQueryInfo->cur.vgroupIndex = -1;
1714 1715

  // set the index to be the end slot of result rows array
dengyihao's avatar
dengyihao 已提交
1716 1717 1718 1719 1720 1721
  //  SResultRowInfo* pResultRowInfo = &pTableQueryInfo->resInfo;
  //  if (pResultRowInfo->size > 0) {
  //    pResultRowInfo->curPos = pResultRowInfo->size - 1;
  //  } else {
  //    pResultRowInfo->curPos = -1;
  //  }
1722 1723
}

H
Haojun Liao 已提交
1724
void initResultRow(SResultRow* pResultRow) {
X
Xiaoyu Wang 已提交
1725
  //  pResultRow->pEntryInfo = (struct SResultRowEntryInfo*)((char*)pResultRow + sizeof(SResultRow));
1726 1727 1728 1729 1730
}

/*
 * 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 已提交
1731 1732 1733
 * +------------+-----------------result column 1------------+------------------result column 2-----------+
 * | SResultRow | SResultRowEntryInfo | intermediate buffer1 | SResultRowEntryInfo | intermediate buffer 2|
 * +------------+--------------------------------------------+--------------------------------------------+
1734 1735
 *           offset[0]                                  offset[1]                                   offset[2]
 */
1736
// TODO refactor: some function move away
X
Xiaoyu Wang 已提交
1737 1738
void setFunctionResultOutput(SOptrBasicInfo* pInfo, SAggSupporter* pSup, int32_t stage, int32_t numOfExprs,
                             SExecTaskInfo* pTaskInfo) {
L
Liu Jicong 已提交
1739 1740 1741
  SqlFunctionCtx* pCtx = pInfo->pCtx;
  SSDataBlock*    pDataBlock = pInfo->pRes;
  int32_t*        rowCellInfoOffset = pInfo->rowCellInfoOffset;
H
Haojun Liao 已提交
1742

H
Haojun Liao 已提交
1743
  SResultRowInfo* pResultRowInfo = &pInfo->resultRowInfo;
H
Haojun Liao 已提交
1744
  initResultRowInfo(pResultRowInfo, 16);
H
Haojun Liao 已提交
1745

L
Liu Jicong 已提交
1746 1747
  int64_t     tid = 0;
  int64_t     groupId = 0;
1748 1749
  SResultRow* pRow = doSetResultOutBufByKey(pSup->pResultBuf, pResultRowInfo, (char*)&tid, sizeof(tid), true, groupId,
                                            pTaskInfo, false, pSup);
H
Haojun Liao 已提交
1750

1751
  for (int32_t i = 0; i < numOfExprs; ++i) {
H
Haojun Liao 已提交
1752 1753 1754
    struct SResultRowEntryInfo* pEntry = getResultCell(pRow, i, rowCellInfoOffset);
    cleanupResultRowEntry(pEntry);

L
Liu Jicong 已提交
1755
    pCtx[i].resultInfo = pEntry;
1756
    pCtx[i].scanFlag = stage;
H
Haojun Liao 已提交
1757 1758
  }

1759
  initCtxOutputBuffer(pCtx, numOfExprs);
H
Haojun Liao 已提交
1760 1761
}

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

L
Liu Jicong 已提交
1765
  int32_t newSize = pDataBlock->info.rows + numOfInputRows + 5;  // extra output buffer
1766
  if ((*bufCapacity) < newSize) {
L
Liu Jicong 已提交
1767 1768
    for (int32_t i = 0; i < pDataBlock->info.numOfCols; ++i) {
      SColumnInfoData* pColInfo = taosArrayGet(pDataBlock->pDataBlock, i);
1769

wafwerar's avatar
wafwerar 已提交
1770
      char* p = taosMemoryRealloc(pColInfo->pData, newSize * pColInfo->info.bytes);
1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783
      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 已提交
1784
    SColumnInfoData* pColInfo = taosArrayGet(pDataBlock->pDataBlock, i);
1785 1786 1787 1788 1789
    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 已提交
1790 1791
    if (functionId == FUNCTION_TOP || functionId == FUNCTION_BOTTOM || functionId == FUNCTION_DIFF ||
        functionId == FUNCTION_DERIVATIVE) {
dengyihao's avatar
dengyihao 已提交
1792
      //      if (i > 0) pBInfo->pCtx[i].pTsOutput = pBInfo->pCtx[i - 1].pOutput;
1793 1794 1795 1796
    }
  }
}

H
Haojun Liao 已提交
1797
void copyTsColoum(SSDataBlock* pRes, SqlFunctionCtx* pCtx, int32_t numOfOutput) {
1798 1799
  bool    needCopyTs = false;
  int32_t tsNum = 0;
L
Liu Jicong 已提交
1800
  char*   src = NULL;
1801 1802 1803 1804
  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 已提交
1805 1806
      if (i > 0 && pCtx[i - 1].functionId == FUNCTION_TS_DUMMY) {
        SColumnInfoData* pColRes = taosArrayGet(pRes->pDataBlock, i - 1);  // find ts data
1807 1808
        src = pColRes->pData;
      }
L
Liu Jicong 已提交
1809
    } else if (functionId == FUNCTION_TS_DUMMY) {
1810 1811 1812 1813 1814 1815 1816 1817 1818 1819
      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 已提交
1820
    if (functionId == FUNCTION_TS_DUMMY) {
1821 1822 1823 1824 1825 1826
      SColumnInfoData* pColRes = taosArrayGet(pRes->pDataBlock, i);
      memcpy(pColRes->pData, src, pColRes->info.bytes * pRes->info.rows);
    }
  }
}

H
Haojun Liao 已提交
1827
void initCtxOutputBuffer(SqlFunctionCtx* pCtx, int32_t size) {
1828 1829
  for (int32_t j = 0; j < size; ++j) {
    struct SResultRowEntryInfo* pResInfo = GET_RES_INFO(&pCtx[j]);
dengyihao's avatar
dengyihao 已提交
1830 1831
    if (isRowEntryInitialized(pResInfo) || fmIsPseudoColumnFunc(pCtx[j].functionId) || pCtx[j].functionId == -1 ||
        fmIsScalarFunc(pCtx[j].functionId)) {
1832 1833 1834
      continue;
    }

H
Haojun Liao 已提交
1835
    pCtx[j].fpSet.init(&pCtx[j], pCtx[j].resultInfo);
1836 1837 1838
  }
}

L
Liu Jicong 已提交
1839
void setTaskStatus(SExecTaskInfo* pTaskInfo, int8_t status) {
1840
  if (status == TASK_NOT_COMPLETED) {
H
Haojun Liao 已提交
1841
    pTaskInfo->status = status;
1842 1843
  } else {
    // QUERY_NOT_COMPLETED is not compatible with any other status, so clear its position first
1844
    CLEAR_QUERY_STATUS(pTaskInfo, TASK_NOT_COMPLETED);
H
Haojun Liao 已提交
1845
    pTaskInfo->status |= status;
1846 1847 1848
  }
}

L
Liu Jicong 已提交
1849
void destroyTableQueryInfoImpl(STableQueryInfo* pTableQueryInfo) {
1850 1851 1852 1853
  if (pTableQueryInfo == NULL) {
    return;
  }

L
Liu Jicong 已提交
1854
  //  taosVariantDestroy(&pTableQueryInfo->tag);
dengyihao's avatar
dengyihao 已提交
1855
  //  cleanupResultRowInfo(&pTableQueryInfo->resInfo);
1856 1857
}

1858
void setResultRowInitCtx(SResultRow* pResult, SqlFunctionCtx* pCtx, int32_t numOfOutput, int32_t* rowCellInfoOffset) {
1859 1860 1861 1862 1863 1864 1865
  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;
    }
1866 1867 1868 1869 1870

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

1871 1872 1873 1874 1875 1876
    if (!pResInfo->initialized) {
      if (pCtx[i].functionId != -1) {
        pCtx[i].fpSet.init(&pCtx[i], pResInfo);
      } else {
        pResInfo->initialized = true;
      }
1877 1878 1879 1880
    }
  }
}

1881
static void extractQualifiedTupleByFilterResult(SSDataBlock* pBlock, const int8_t* rowRes, bool keep);
X
Xiaoyu Wang 已提交
1882
void        doFilter(const SNode* pFilterNode, SSDataBlock* pBlock, SArray* pColMatchInfo) {
1883 1884 1885 1886 1887
  if (pFilterNode == NULL) {
    return;
  }

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

H
Haojun Liao 已提交
1889
  // todo move to the initialization function
H
Haojun Liao 已提交
1890
  int32_t code = filterInitFromNode((SNode*)pFilterNode, &filter, 0);
1891 1892 1893 1894 1895

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

  int8_t* rowRes = NULL;
1896

1897
  // todo the keep seems never to be True??
1898
  bool keep = filterExecute(filter, pBlock, &rowRes, NULL, param1.numOfCols);
D
dapan1121 已提交
1899
  filterFreeInfo(filter);
1900

1901
  extractQualifiedTupleByFilterResult(pBlock, rowRes, keep);
1902
  blockDataUpdateTsWindow(pBlock, 0);
1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913
}

void extractQualifiedTupleByFilterResult(SSDataBlock* pBlock, const int8_t* rowRes, bool keep) {
  if (keep) {
    return;
  }

  if (rowRes != NULL) {
    SSDataBlock* px = createOneDataBlock(pBlock, false);
    blockDataEnsureCapacity(px, pBlock->info.rows);

1914 1915
    int32_t totalRows = pBlock->info.rows;

1916 1917 1918 1919
    for (int32_t i = 0; i < pBlock->info.numOfCols; ++i) {
      SColumnInfoData* pDst = taosArrayGet(px->pDataBlock, i);
      SColumnInfoData* pSrc = taosArrayGet(pBlock->pDataBlock, i);

1920 1921 1922 1923 1924
      // it is a reserved column for scalar function, and no data in this column yet.
      if (pSrc->pData == NULL) {
        continue;
      }

1925
      int32_t numOfRows = 0;
1926
      for (int32_t j = 0; j < totalRows; ++j) {
D
dapan1121 已提交
1927 1928 1929
        if (rowRes[j] == 0) {
          continue;
        }
1930

D
dapan1121 已提交
1931
        if (colDataIsNull_s(pSrc, j)) {
1932
          colDataAppendNULL(pDst, numOfRows);
D
dapan1121 已提交
1933
        } else {
1934
          colDataAppend(pDst, numOfRows, colDataGetData(pSrc, j), false);
D
dapan1121 已提交
1935
        }
1936
        numOfRows += 1;
H
Haojun Liao 已提交
1937
      }
1938

1939 1940 1941 1942 1943 1944
      if (pBlock->info.rows == totalRows) {
        pBlock->info.rows = numOfRows;
      } else {
        ASSERT(pBlock->info.rows == numOfRows);
      }

1945 1946 1947 1948 1949
      *pSrc = *pDst;
    }
  } else {
    // do nothing
    pBlock->info.rows = 0;
1950 1951 1952
  }
}

dengyihao's avatar
dengyihao 已提交
1953 1954
void doSetTableGroupOutputBuf(SAggOperatorInfo* pAggInfo, int32_t numOfOutput, uint64_t groupId,
                              SExecTaskInfo* pTaskInfo) {
1955 1956 1957
  // for simple group by query without interval, all the tables belong to one group result.
  int64_t uid = 0;

1958 1959
  SResultRowInfo* pResultRowInfo = &pAggInfo->binfo.resultRowInfo;
  SqlFunctionCtx* pCtx = pAggInfo->binfo.pCtx;
L
Liu Jicong 已提交
1960
  int32_t*        rowCellInfoOffset = pAggInfo->binfo.rowCellInfoOffset;
1961

1962
  SResultRow* pResultRow = doSetResultOutBufByKey(pAggInfo->aggSup.pResultBuf, pResultRowInfo, (char*)&groupId,
L
Liu Jicong 已提交
1963
                                                  sizeof(groupId), true, groupId, pTaskInfo, false, &pAggInfo->aggSup);
L
Liu Jicong 已提交
1964
  assert(pResultRow != NULL);
1965 1966 1967 1968 1969 1970

  /*
   * 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) {
dengyihao's avatar
dengyihao 已提交
1971 1972
    int32_t ret =
        addNewWindowResultBuf(pResultRow, pAggInfo->aggSup.pResultBuf, groupId, pAggInfo->binfo.pRes->info.rowSize);
1973 1974 1975 1976 1977
    if (ret != TSDB_CODE_SUCCESS) {
      return;
    }
  }

1978
  setResultRowInitCtx(pResultRow, pCtx, numOfOutput, rowCellInfoOffset);
1979 1980
}

H
Haojun Liao 已提交
1981 1982
void setExecutionContext(int32_t numOfOutput, uint64_t groupId, SExecTaskInfo* pTaskInfo, SAggOperatorInfo* pAggInfo) {
  if (pAggInfo->groupId != INT32_MIN && pAggInfo->groupId == groupId) {
1983 1984 1985
    return;
  }

H
Haojun Liao 已提交
1986
  doSetTableGroupOutputBuf(pAggInfo, numOfOutput, groupId, pTaskInfo);
1987 1988

  // record the current active group id
H
Haojun Liao 已提交
1989
  pAggInfo->groupId = groupId;
1990 1991
}

1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004
static void doUpdateNumOfRows(SResultRow* pRow, int32_t numOfExprs, const int32_t* rowCellOffset) {
  for (int32_t j = 0; j < numOfExprs; ++j) {
    struct SResultRowEntryInfo* pResInfo = getResultCell(pRow, j, rowCellOffset);
    if (!isRowEntryInitialized(pResInfo)) {
      continue;
    }

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

X
Xiaoyu Wang 已提交
2005 2006 2007
int32_t doCopyToSDataBlock(SExecTaskInfo* pTaskInfo, SSDataBlock* pBlock, SExprInfo* pExprInfo, SDiskbasedBuf* pBuf,
                           SGroupResInfo* pGroupResInfo, const int32_t* rowCellOffset, SqlFunctionCtx* pCtx,
                           int32_t numOfExprs) {
2008
  int32_t numOfRows = getNumOfTotalRes(pGroupResInfo);
2009
  int32_t start = pGroupResInfo->index;
2010

2011
  for (int32_t i = start; i < numOfRows; i += 1) {
L
Liu Jicong 已提交
2012 2013
    SResKeyPos* pPos = taosArrayGetP(pGroupResInfo->pRows, i);
    SFilePage*  page = getBufPage(pBuf, pPos->pos.pageId);
2014

2015
    SResultRow* pRow = (SResultRow*)((char*)page + pPos->pos.offset);
2016 2017

    doUpdateNumOfRows(pRow, numOfExprs, rowCellOffset);
2018 2019
    if (pRow->numOfRows == 0) {
      pGroupResInfo->index += 1;
2020
      releaseBufPage(pBuf, page);
2021 2022 2023
      continue;
    }

2024 2025 2026 2027 2028
    if (pBlock->info.groupId == 0) {
      pBlock->info.groupId = pPos->groupId;
    } else {
      // current value belongs to different group, it can't be packed into one datablock
      if (pBlock->info.groupId != pPos->groupId) {
2029
        releaseBufPage(pBuf, page);
2030 2031 2032 2033
        break;
      }
    }

2034
    if (pBlock->info.rows + pRow->numOfRows > pBlock->info.capacity) {
2035
      releaseBufPage(pBuf, page);
2036 2037 2038 2039 2040
      break;
    }

    pGroupResInfo->index += 1;

2041
    for (int32_t j = 0; j < numOfExprs; ++j) {
2042 2043
      int32_t slotId = pExprInfo[j].base.resSchema.slotId;

2044
      pCtx[j].resultInfo = getResultCell(pRow, j, rowCellOffset);
2045
      if (pCtx[j].fpSet.finalize) {
2046
        int32_t code = pCtx[j].fpSet.finalize(&pCtx[j], pBlock);
2047
        if (TAOS_FAILED(code)) {
2048 2049
          qError("%s build result data block error, code %s", GET_TASKID(pTaskInfo), tstrerror(code));
          longjmp(pTaskInfo->env, code);
2050
        }
2051 2052
      } else if (strcmp(pCtx[j].pExpr->pExpr->_function.functionName, "_select_value") == 0) {
        // do nothing, todo refactor
2053
      } else {
2054 2055
        // expand the result into multiple rows. E.g., _wstartts, top(k, 20)
        // the _wstartts needs to copy to 20 following rows, since the results of top-k expands to 20 different rows.
X
Xiaoyu Wang 已提交
2056 2057 2058 2059 2060
        SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, slotId);
        char*            in = GET_ROWCELL_INTERBUF(pCtx[j].resultInfo);
        for (int32_t k = 0; k < pRow->numOfRows; ++k) {
          colDataAppend(pColInfoData, pBlock->info.rows + k, in, pCtx[j].resultInfo->isNullRes);
        }
2061
      }
2062 2063
    }

2064
    releaseBufPage(pBuf, page);
2065 2066
    pBlock->info.rows += pRow->numOfRows;
    if (pBlock->info.rows >= pBlock->info.capacity) {  // output buffer is full
2067 2068 2069 2070
      break;
    }
  }

X
Xiaoyu Wang 已提交
2071 2072
  qDebug("%s result generated, rows:%d, groupId:%" PRIu64, GET_TASKID(pTaskInfo), pBlock->info.rows,
         pBlock->info.groupId);
2073
  blockDataUpdateTsWindow(pBlock, 0);
2074 2075 2076
  return 0;
}

X
Xiaoyu Wang 已提交
2077 2078 2079 2080
void doBuildResultDatablock(SOperatorInfo* pOperator, SOptrBasicInfo* pbInfo, SGroupResInfo* pGroupResInfo,
                            SDiskbasedBuf* pBuf) {
  SExprInfo*     pExprInfo = pOperator->pExpr;
  int32_t        numOfExprs = pOperator->numOfExprs;
2081 2082
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;

X
Xiaoyu Wang 已提交
2083 2084 2085
  int32_t*        rowCellOffset = pbInfo->rowCellInfoOffset;
  SSDataBlock*    pBlock = pbInfo->pRes;
  SqlFunctionCtx* pCtx = pbInfo->pCtx;
2086

2087
  blockDataCleanup(pBlock);
2088
  if (!hashRemainDataInGroupInfo(pGroupResInfo)) {
2089 2090 2091
    return;
  }

2092 2093
  // clear the existed group id
  pBlock->info.groupId = 0;
2094
  doCopyToSDataBlock(pTaskInfo, pBlock, pExprInfo, pBuf, pGroupResInfo, rowCellOffset, pCtx, numOfExprs);
2095 2096
}

L
Liu Jicong 已提交
2097 2098
static void updateNumOfRowsInResultRows(SqlFunctionCtx* pCtx, int32_t numOfOutput, SResultRowInfo* pResultRowInfo,
                                        int32_t* rowCellInfoOffset) {
2099
  // update the number of result for each, only update the number of rows for the corresponding window result.
L
Liu Jicong 已提交
2100 2101 2102
  //  if (QUERY_IS_INTERVAL_QUERY(pQueryAttr)) {
  //    return;
  //  }
H
Haojun Liao 已提交
2103
#if 0
2104
  for (int32_t i = 0; i < pResultRowInfo->size; ++i) {
L
Liu Jicong 已提交
2105
    SResultRow* pResult = pResultRowInfo->pResult[i];
2106 2107 2108 2109 2110 2111 2112

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

2113 2114
      SResultRowEntryInfo* pCell = getResultCell(pResult, j, rowCellInfoOffset);
      pResult->numOfRows = (uint16_t)(TMAX(pResult->numOfRows, pCell->numOfRes));
2115 2116
    }
  }
H
Haojun Liao 已提交
2117
#endif
2118 2119
}

L
Liu Jicong 已提交
2120
static int32_t compressQueryColData(SColumnInfoData* pColRes, int32_t numOfRows, char* data, int8_t compressed) {
2121 2122
  int32_t colSize = pColRes->info.bytes * numOfRows;
  return (*(tDataTypes[pColRes->info.type].compFunc))(pColRes->pData, colSize, numOfRows, data,
L
Liu Jicong 已提交
2123
                                                      colSize + COMP_OVERFLOW_BYTES, compressed, NULL, 0);
2124 2125
}

2126
int32_t doFillTimeIntervalGapsInResults(struct SFillInfo* pFillInfo, SSDataBlock* pBlock, int32_t capacity) {
L
Liu Jicong 已提交
2127 2128 2129 2130
  //  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);
  //  }
2131

2132 2133
  int32_t numOfRows = (int32_t)taosFillResultDataBlock(pFillInfo, pBlock, capacity - pBlock->info.rows);
  pBlock->info.rows += numOfRows;
2134

2135
  return pBlock->info.rows;
2136 2137
}

L
Liu Jicong 已提交
2138 2139
void queryCostStatis(SExecTaskInfo* pTaskInfo) {
  STaskCostInfo* pSummary = &pTaskInfo->cost;
2140

L
Liu Jicong 已提交
2141 2142 2143
  //  uint64_t hashSize = taosHashGetMemSize(pQInfo->runtimeEnv.pResultRowHashTable);
  //  hashSize += taosHashGetMemSize(pRuntimeEnv->tableqinfoGroupInfo.map);
  //  pSummary->hashSize = hashSize;
2144 2145 2146 2147

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

L
Liu Jicong 已提交
2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158
  //  SResultRowPool* p = pTaskInfo->pool;
  //  if (p != NULL) {
  //    pSummary->winInfoSize = getResultRowPoolMemSize(p);
  //    pSummary->numOfTimeWindows = getNumOfAllocatedResultRows(p);
  //  } else {
  //    pSummary->winInfoSize = 0;
  //    pSummary->numOfTimeWindows = 0;
  //  }
  //
  //  calculateOperatorProfResults(pQInfo);

2159 2160
  SFileBlockLoadRecorder* pRecorder = pSummary->pRecoder;
  if (pSummary->pRecoder != NULL) {
X
Xiaoyu Wang 已提交
2161 2162
    qDebug("%s :cost summary: elapsed time:%" PRId64 " us, first merge:%" PRId64
           " us, total blocks:%d, "
2163 2164 2165 2166
           "load block statis:%d, load data block:%d, total rows:%" PRId64 ", check rows:%" PRId64,
           GET_TASKID(pTaskInfo), pSummary->elapsedTime, pSummary->firstStageMergeTime, pRecorder->totalBlocks,
           pRecorder->loadBlockStatis, pRecorder->loadBlocks, pRecorder->totalRows, pRecorder->totalCheckedRows);
  }
L
Liu Jicong 已提交
2167 2168 2169
  // 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);
2170 2171
}

L
Liu Jicong 已提交
2172 2173 2174
// static void updateOffsetVal(STaskRuntimeEnv *pRuntimeEnv, SDataBlockInfo *pBlockInfo) {
//   STaskAttr *pQueryAttr = pRuntimeEnv->pQueryAttr;
//   STableQueryInfo* pTableQueryInfo = pRuntimeEnv->current;
2175
//
L
Liu Jicong 已提交
2176
//   int32_t step = GET_FORWARD_DIRECTION_FACTOR(pQueryAttr->order.order);
2177
//
L
Liu Jicong 已提交
2178 2179 2180 2181
//   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;
//   }
2182
//
L
Liu Jicong 已提交
2183 2184 2185 2186 2187
//   if (QUERY_IS_ASC_QUERY(pQueryAttr)) {
//     pQueryAttr->pos = (int32_t)pQueryAttr->limit.offset;
//   } else {
//     pQueryAttr->pos = pBlockInfo->rows - (int32_t)pQueryAttr->limit.offset - 1;
//   }
2188
//
L
Liu Jicong 已提交
2189
//   assert(pQueryAttr->pos >= 0 && pQueryAttr->pos <= pBlockInfo->rows - 1);
2190
//
L
Liu Jicong 已提交
2191 2192
//   SArray *         pDataBlock = tsdbRetrieveDataBlock(pRuntimeEnv->pTsdbReadHandle, NULL);
//   SColumnInfoData *pColInfoData = taosArrayGet(pDataBlock, 0);
2193
//
L
Liu Jicong 已提交
2194 2195
//   // update the pQueryAttr->limit.offset value, and pQueryAttr->pos value
//   TSKEY *keys = (TSKEY *) pColInfoData->pData;
2196
//
L
Liu Jicong 已提交
2197 2198 2199
//   // update the offset value
//   pTableQueryInfo->lastKey = keys[pQueryAttr->pos];
//   pQueryAttr->limit.offset = 0;
2200
//
L
Liu Jicong 已提交
2201
//   int32_t numOfRes = tableApplyFunctionsOnBlock(pRuntimeEnv, pBlockInfo, NULL, binarySearchForKey, pDataBlock);
2202
//
L
Liu Jicong 已提交
2203 2204 2205 2206
//   //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);
// }
2207

L
Liu Jicong 已提交
2208 2209
// void skipBlocks(STaskRuntimeEnv *pRuntimeEnv) {
//   STaskAttr *pQueryAttr = pRuntimeEnv->pQueryAttr;
2210
//
L
Liu Jicong 已提交
2211 2212 2213
//   if (pQueryAttr->limit.offset <= 0 || pQueryAttr->numOfFilterCols > 0) {
//     return;
//   }
2214
//
L
Liu Jicong 已提交
2215 2216
//   pQueryAttr->pos = 0;
//   int32_t step = GET_FORWARD_DIRECTION_FACTOR(pQueryAttr->order.order);
2217
//
L
Liu Jicong 已提交
2218 2219
//   STableQueryInfo* pTableQueryInfo = pRuntimeEnv->current;
//   TsdbQueryHandleT pTsdbReadHandle = pRuntimeEnv->pTsdbReadHandle;
2220
//
L
Liu Jicong 已提交
2221 2222 2223 2224 2225
//   SDataBlockInfo blockInfo = SDATA_BLOCK_INITIALIZER;
//   while (tsdbNextDataBlock(pTsdbReadHandle)) {
//     if (isTaskKilled(pRuntimeEnv->qinfo)) {
//       longjmp(pRuntimeEnv->env, TSDB_CODE_TSC_QUERY_CANCELLED);
//     }
2226
//
L
Liu Jicong 已提交
2227
//     tsdbRetrieveDataBlockInfo(pTsdbReadHandle, &blockInfo);
2228
//
L
Liu Jicong 已提交
2229 2230 2231 2232
//     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;
2233
//
L
Liu Jicong 已提交
2234 2235 2236 2237 2238 2239 2240
//       //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;
//     }
//   }
2241
//
L
Liu Jicong 已提交
2242 2243 2244 2245 2246 2247 2248 2249 2250
//   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;
2251
//
L
Liu Jicong 已提交
2252 2253 2254
//   assert(pQueryAttr->limit.offset == 0);
//   STimeWindow tw = *win;
//   getNextTimeWindow(pQueryAttr, &tw);
2255
//
L
Liu Jicong 已提交
2256 2257
//   if ((tw.skey <= pBlockInfo->window.ekey && QUERY_IS_ASC_QUERY(pQueryAttr)) ||
//       (tw.ekey >= pBlockInfo->window.skey && !QUERY_IS_ASC_QUERY(pQueryAttr))) {
2258
//
L
Liu Jicong 已提交
2259 2260 2261 2262
//     // 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);
2263
//
L
Liu Jicong 已提交
2264 2265 2266 2267
//     tw = *win;
//     int32_t startPos =
//         getNextQualifiedWindow(pQueryAttr, &tw, pBlockInfo, pColInfoData->pData, binarySearchForKey, -1);
//     assert(startPos >= 0);
2268
//
L
Liu Jicong 已提交
2269 2270
//     // set the abort info
//     pQueryAttr->pos = startPos;
2271
//
L
Liu Jicong 已提交
2272 2273 2274 2275
//     // reset the query start timestamp
//     pTableQueryInfo->win.skey = ((TSKEY *)pColInfoData->pData)[startPos];
//     pQueryAttr->window.skey = pTableQueryInfo->win.skey;
//     TSKEY key = pTableQueryInfo->win.skey;
2276
//
L
Liu Jicong 已提交
2277 2278
//     pWindowResInfo->prevSKey = tw.skey;
//     int32_t index = pRuntimeEnv->resultRowInfo.curIndex;
2279
//
L
Liu Jicong 已提交
2280 2281
//     int32_t numOfRes = tableApplyFunctionsOnBlock(pRuntimeEnv, pBlockInfo, NULL, binarySearchForKey, pDataBlock);
//     pRuntimeEnv->resultRowInfo.curIndex = index;  // restore the window index
2282
//
L
Liu Jicong 已提交
2283 2284 2285 2286
//     //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);
2287
//
L
Liu Jicong 已提交
2288 2289 2290 2291 2292
//     return key;
//   } else {  // do nothing
//     pQueryAttr->window.skey      = tw.skey;
//     pWindowResInfo->prevSKey = tw.skey;
//     pTableQueryInfo->lastKey = tw.skey;
2293
//
L
Liu Jicong 已提交
2294 2295
//     return tw.skey;
//   }
2296
//
L
Liu Jicong 已提交
2297 2298 2299 2300 2301 2302 2303 2304 2305 2306
//   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);
//   }
2307
//
L
Liu Jicong 已提交
2308 2309 2310 2311 2312
//   // 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;
//   }
2313
//
L
Liu Jicong 已提交
2314 2315 2316 2317 2318 2319 2320
//   /*
//    * 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);
2321
//
L
Liu Jicong 已提交
2322 2323
//   STimeWindow w = TSWINDOW_INITIALIZER;
//   bool ascQuery = QUERY_IS_ASC_QUERY(pQueryAttr);
2324
//
L
Liu Jicong 已提交
2325 2326
//   SResultRowInfo *pWindowResInfo = &pRuntimeEnv->resultRowInfo;
//   STableQueryInfo *pTableQueryInfo = pRuntimeEnv->current;
2327
//
L
Liu Jicong 已提交
2328 2329 2330
//   SDataBlockInfo blockInfo = SDATA_BLOCK_INITIALIZER;
//   while (tsdbNextDataBlock(pRuntimeEnv->pTsdbReadHandle)) {
//     tsdbRetrieveDataBlockInfo(pRuntimeEnv->pTsdbReadHandle, &blockInfo);
2331
//
L
Liu Jicong 已提交
2332 2333 2334 2335 2336 2337 2338 2339 2340
//     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;
//     }
2341
//
L
Liu Jicong 已提交
2342 2343
//     // the first time window
//     STimeWindow win = getActiveTimeWindow(pWindowResInfo, pWindowResInfo->prevSKey, pQueryAttr);
2344
//
L
Liu Jicong 已提交
2345 2346
//     while (pQueryAttr->limit.offset > 0) {
//       STimeWindow tw = win;
2347
//
L
Liu Jicong 已提交
2348 2349 2350
//       if ((win.ekey <= blockInfo.window.ekey && ascQuery) || (win.ekey >= blockInfo.window.skey && !ascQuery)) {
//         pQueryAttr->limit.offset -= 1;
//         pWindowResInfo->prevSKey = win.skey;
2351
//
L
Liu Jicong 已提交
2352 2353 2354 2355 2356 2357
//         // 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;
//         }
//       }
2358
//
L
Liu Jicong 已提交
2359 2360 2361 2362
//       if (pQueryAttr->limit.offset == 0) {
//         *start = doSkipIntervalProcess(pRuntimeEnv, &win, &blockInfo, pTableQueryInfo);
//         return true;
//       }
2363
//
L
Liu Jicong 已提交
2364 2365
//       // current window does not ended in current data block, try next data block
//       getNextTimeWindow(pQueryAttr, &tw);
2366
//
L
Liu Jicong 已提交
2367 2368 2369 2370 2371 2372 2373 2374 2375
//       /*
//        * 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)) {
2376
//
L
Liu Jicong 已提交
2377 2378
//         SArray *pDataBlock = tsdbRetrieveDataBlock(pRuntimeEnv->pTsdbReadHandle, NULL);
//         SColumnInfoData *pColInfoData = taosArrayGet(pDataBlock, 0);
2379
//
L
Liu Jicong 已提交
2380 2381 2382
//         if ((win.ekey > blockInfo.window.ekey && ascQuery) || (win.ekey < blockInfo.window.skey && !ascQuery)) {
//           pQueryAttr->limit.offset -= 1;
//         }
2383
//
L
Liu Jicong 已提交
2384 2385 2386 2387 2388 2389 2390 2391
//         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);
2392
//
L
Liu Jicong 已提交
2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403
//           // 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.
//       }
//     }
//   }
2404
//
L
Liu Jicong 已提交
2405 2406 2407 2408
//   // check for error
//   if (terrno != TSDB_CODE_SUCCESS) {
//     longjmp(pRuntimeEnv->env, terrno);
//   }
2409
//
L
Liu Jicong 已提交
2410 2411
//   return true;
// }
2412

2413
int32_t appendDownstream(SOperatorInfo* p, SOperatorInfo** pDownstream, int32_t num) {
H
Haojun Liao 已提交
2414
  if (p->pDownstream == NULL) {
H
Haojun Liao 已提交
2415
    assert(p->numOfDownstream == 0);
2416 2417
  }

wafwerar's avatar
wafwerar 已提交
2418
  p->pDownstream = taosMemoryCalloc(1, num * POINTER_BYTES);
2419 2420 2421 2422 2423 2424 2425
  if (p->pDownstream == NULL) {
    return TSDB_CODE_OUT_OF_MEMORY;
  }

  memcpy(p->pDownstream, pDownstream, num * POINTER_BYTES);
  p->numOfDownstream = num;
  return TSDB_CODE_SUCCESS;
2426 2427
}

wmmhello's avatar
wmmhello 已提交
2428
static void doDestroyTableList(STableListInfo* pTableqinfoList);
2429

2430
static void doTableQueryInfoTimeWindowCheck(SExecTaskInfo* pTaskInfo, STableQueryInfo* pTableQueryInfo, int32_t order) {
H
Haojun Liao 已提交
2431 2432
#if 0
    if (order == TSDB_ORDER_ASC) {
2433 2434
    assert(
        (pTableQueryInfo->win.skey <= pTableQueryInfo->win.ekey) &&
H
Haojun Liao 已提交
2435 2436
        (pTableQueryInfo->lastKey >= pTaskInfo->window.skey) &&
        (pTableQueryInfo->win.skey >= pTaskInfo->window.skey && pTableQueryInfo->win.ekey <= pTaskInfo->window.ekey));
2437 2438 2439
  } else {
    assert(
        (pTableQueryInfo->win.skey >= pTableQueryInfo->win.ekey) &&
H
Haojun Liao 已提交
2440 2441
        (pTableQueryInfo->lastKey <= pTaskInfo->window.skey) &&
        (pTableQueryInfo->win.skey <= pTaskInfo->window.skey && pTableQueryInfo->win.ekey >= pTaskInfo->window.ekey));
2442
  }
H
Haojun Liao 已提交
2443
#endif
2444 2445
}

L
Liu Jicong 已提交
2446 2447 2448 2449
// 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;
2450
//
L
Liu Jicong 已提交
2451 2452 2453
//   if (pTableQueryInfo->pTable == NULL) {
//     return;
//   }
2454
//
L
Liu Jicong 已提交
2455 2456 2457 2458 2459 2460 2461 2462 2463
//   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));
//   }
// }
2464

2465
int32_t loadRemoteDataCallback(void* param, const SDataBuf* pMsg, int32_t code) {
L
Liu Jicong 已提交
2466
  SSourceDataInfo* pSourceDataInfo = (SSourceDataInfo*)param;
H
Haojun Liao 已提交
2467 2468
  if (code == TSDB_CODE_SUCCESS) {
    pSourceDataInfo->pRsp = pMsg->pData;
2469

H
Haojun Liao 已提交
2470 2471
    SRetrieveTableRsp* pRsp = pSourceDataInfo->pRsp;
    pRsp->numOfRows = htonl(pRsp->numOfRows);
dengyihao's avatar
dengyihao 已提交
2472
    pRsp->compLen = htonl(pRsp->compLen);
2473
    pRsp->numOfCols = htonl(pRsp->numOfCols);
dengyihao's avatar
dengyihao 已提交
2474
    pRsp->useconds = htobe64(pRsp->useconds);
H
Haojun Liao 已提交
2475 2476 2477
  } else {
    pSourceDataInfo->code = code;
  }
H
Haojun Liao 已提交
2478

H
Haojun Liao 已提交
2479
  pSourceDataInfo->status = EX_SOURCE_DATA_READY;
2480
  tsem_post(&pSourceDataInfo->pEx->ready);
wmmhello's avatar
wmmhello 已提交
2481
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
2482 2483 2484 2485
}

static void destroySendMsgInfo(SMsgSendInfo* pMsgBody) {
  assert(pMsgBody != NULL);
wafwerar's avatar
wafwerar 已提交
2486 2487
  taosMemoryFreeClear(pMsgBody->msgInfo.pData);
  taosMemoryFreeClear(pMsgBody);
H
Haojun Liao 已提交
2488 2489
}

S
Shengliang Guan 已提交
2490
void qProcessFetchRsp(void* parent, SRpcMsg* pMsg, SEpSet* pEpSet) {
S
Shengliang Guan 已提交
2491 2492
  SMsgSendInfo* pSendInfo = (SMsgSendInfo*)pMsg->info.ahandle;
  assert(pMsg->info.ahandle != NULL);
H
Haojun Liao 已提交
2493 2494 2495 2496

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

  if (pMsg->contLen > 0) {
wafwerar's avatar
wafwerar 已提交
2497
    buf.pData = taosMemoryCalloc(1, pMsg->contLen);
H
Haojun Liao 已提交
2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508
    if (buf.pData == NULL) {
      terrno = TSDB_CODE_OUT_OF_MEMORY;
      pMsg->code = TSDB_CODE_OUT_OF_MEMORY;
    } else {
      memcpy(buf.pData, pMsg->pCont, pMsg->contLen);
    }
  }

  pSendInfo->fp(pSendInfo->param, &buf, pMsg->code);
  rpcFreeCont(pMsg->pCont);
  destroySendMsgInfo(pSendInfo);
2509 2510
}

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

wafwerar's avatar
wafwerar 已提交
2514
  SResFetchReq* pMsg = taosMemoryCalloc(1, sizeof(SResFetchReq));
2515 2516 2517 2518
  if (NULL == pMsg) {
    pTaskInfo->code = TSDB_CODE_QRY_OUT_OF_MEMORY;
    return pTaskInfo->code;
  }
2519

L
Liu Jicong 已提交
2520 2521
  SDownstreamSourceNode* pSource = taosArrayGet(pExchangeInfo->pSources, sourceIndex);
  SSourceDataInfo*       pDataInfo = taosArrayGet(pExchangeInfo->pSourceDataInfo, sourceIndex);
2522

L
Liu Jicong 已提交
2523 2524
  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);
2525 2526 2527 2528 2529 2530 2531

  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 已提交
2532
  SMsgSendInfo* pMsgSendInfo = taosMemoryCalloc(1, sizeof(SMsgSendInfo));
2533
  if (NULL == pMsgSendInfo) {
wafwerar's avatar
wafwerar 已提交
2534
    taosMemoryFreeClear(pMsg);
2535 2536 2537
    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 已提交
2538 2539
  }

2540 2541 2542 2543 2544
  pMsgSendInfo->param = pDataInfo;
  pMsgSendInfo->msgInfo.pData = pMsg;
  pMsgSendInfo->msgInfo.len = sizeof(SResFetchReq);
  pMsgSendInfo->msgType = TDMT_VND_FETCH;
  pMsgSendInfo->fp = loadRemoteDataCallback;
2545

2546
  int64_t transporterId = 0;
L
Liu Jicong 已提交
2547
  int32_t code = asyncSendMsgToServer(pExchangeInfo->pTransporter, &pSource->addr.epSet, &transporterId, pMsgSendInfo);
2548 2549 2550
  return TSDB_CODE_SUCCESS;
}

2551
// NOTE: sources columns are more than the destination SSDatablock columns.
2552
void relocateColumnData(SSDataBlock* pBlock, const SArray* pColMatchInfo, SArray* pCols) {
2553 2554 2555
  size_t numOfSrcCols = taosArrayGetSize(pCols);

  int32_t i = 0, j = 0;
L
Liu Jicong 已提交
2556
  while (i < numOfSrcCols && j < taosArrayGetSize(pColMatchInfo)) {
2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575
    SColumnInfoData* p = taosArrayGet(pCols, i);
    SColMatchInfo*   pmInfo = taosArrayGet(pColMatchInfo, j);
    if (!pmInfo->output) {
      j++;
      continue;
    }

    if (p->info.colId == pmInfo->colId) {
      taosArraySet(pBlock->pDataBlock, pmInfo->targetSlotId, p);
      i++;
      j++;
    } else if (p->info.colId < pmInfo->colId) {
      i++;
    } else {
      ASSERT(0);
    }
  }
}

2576
int32_t setSDataBlockFromFetchRsp(SSDataBlock* pRes, SLoadRemoteDataInfo* pLoadInfo, int32_t numOfRows, char* pData,
dengyihao's avatar
dengyihao 已提交
2577 2578
                                  int32_t compLen, int32_t numOfOutput, int64_t startTs, uint64_t* total,
                                  SArray* pColList) {
H
Haojun Liao 已提交
2579
  if (pColList == NULL) {  // data from other sources
H
Haojun Liao 已提交
2580 2581
    blockDataEnsureCapacity(pRes, numOfRows);

L
Liu Jicong 已提交
2582
    int32_t dataLen = *(int32_t*)pData;
2583 2584
    pData += sizeof(int32_t);

L
Liu Jicong 已提交
2585
    pRes->info.groupId = *(uint64_t*)pData;
2586 2587
    pData += sizeof(uint64_t);

H
Haojun Liao 已提交
2588 2589
    int32_t* colLen = (int32_t*)pData;

2590
    char* pStart = pData + sizeof(int32_t) * numOfOutput;
2591
    for (int32_t i = 0; i < numOfOutput; ++i) {
H
Haojun Liao 已提交
2592
      colLen[i] = htonl(colLen[i]);
2593
      ASSERT(colLen[i] >= 0);
H
Haojun Liao 已提交
2594

2595
      SColumnInfoData* pColInfoData = taosArrayGet(pRes->pDataBlock, i);
H
Haojun Liao 已提交
2596 2597 2598
      if (IS_VAR_DATA_TYPE(pColInfoData->info.type)) {
        pColInfoData->varmeta.length = colLen[i];
        pColInfoData->varmeta.allocLen = colLen[i];
2599

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

2603 2604 2605
        if (colLen[i] > 0) {
          pColInfoData->pData = taosMemoryMalloc(colLen[i]);
        }
H
Haojun Liao 已提交
2606 2607 2608
      } else {
        memcpy(pColInfoData->nullbitmap, pStart, BitmapLen(numOfRows));
        pStart += BitmapLen(numOfRows);
2609
      }
H
Haojun Liao 已提交
2610

2611 2612 2613 2614
      if (colLen[i] > 0) {
        memcpy(pColInfoData->pData, pStart, colLen[i]);
      }

L
Liu Jicong 已提交
2615 2616
      // TODO setting this flag to true temporarily so aggregate function on stable will
      // examine NULL value for non-primary key column
2617
      pColInfoData->hasNull = true;
H
Haojun Liao 已提交
2618
      pStart += colLen[i];
2619
    }
H
Haojun Liao 已提交
2620
  } else {  // extract data according to pColList
2621
    ASSERT(numOfOutput == taosArrayGetSize(pColList));
2622 2623 2624 2625 2626
    char* pStart = pData;

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

2627
    // todo refactor:extract method
2628
    SSysTableSchema* pSchema = (SSysTableSchema*)pStart;
dengyihao's avatar
dengyihao 已提交
2629
    for (int32_t i = 0; i < numOfCols; ++i) {
2630 2631 2632 2633 2634 2635 2636
      SSysTableSchema* p = (SSysTableSchema*)pStart;

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

H
Haojun Liao 已提交
2637 2638 2639 2640
    SSDataBlock* pBlock = taosMemoryCalloc(1, sizeof(SSDataBlock));
    pBlock->pDataBlock = taosArrayInit(numOfCols, sizeof(SColumnInfoData));
    pBlock->info.numOfCols = numOfCols;

dengyihao's avatar
dengyihao 已提交
2641
    for (int32_t i = 0; i < numOfCols; ++i) {
2642
      SColumnInfoData idata = {0};
2643

X
Xiaoyu Wang 已提交
2644
      idata.info.type = pSchema[i].type;
2645 2646
      idata.info.bytes = pSchema[i].bytes;
      idata.info.colId = pSchema[i].colId;
X
Xiaoyu Wang 已提交
2647
      idata.hasNull = true;
2648

H
Haojun Liao 已提交
2649
      taosArrayPush(pBlock->pDataBlock, &idata);
2650
      if (IS_VAR_DATA_TYPE(idata.info.type)) {
H
Haojun Liao 已提交
2651
        pBlock->info.hasVarCol = true;
2652 2653 2654
      }
    }

H
Haojun Liao 已提交
2655
    blockDataEnsureCapacity(pBlock, numOfRows);
2656

L
Liu Jicong 已提交
2657 2658
    int32_t  dataLen = *(int32_t*)pStart;
    uint64_t groupId = *(uint64_t*)(pStart + sizeof(int32_t));
2659 2660
    pStart += sizeof(int32_t) + sizeof(uint64_t);

L
Liu Jicong 已提交
2661
    int32_t* colLen = (int32_t*)(pStart);
2662 2663 2664 2665
    pStart += sizeof(int32_t) * numOfCols;

    for (int32_t i = 0; i < numOfCols; ++i) {
      colLen[i] = htonl(colLen[i]);
2666
      ASSERT(colLen[i] >= 0);
2667

H
Haojun Liao 已提交
2668
      SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, i);
2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684
      if (IS_VAR_DATA_TYPE(pColInfoData->info.type)) {
        pColInfoData->varmeta.length = colLen[i];
        pColInfoData->varmeta.allocLen = colLen[i];

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

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

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

    // data from mnode
H
Haojun Liao 已提交
2687 2688 2689
    relocateColumnData(pRes, pColList, pBlock->pDataBlock);
    taosArrayDestroy(pBlock->pDataBlock);
    taosMemoryFree(pBlock);
X
Xiaoyu Wang 已提交
2690
    //    blockDataDestroy(pBlock);
2691
  }
2692

H
Haojun Liao 已提交
2693
  pRes->info.rows = numOfRows;
2694 2695 2696

  // todo move this to time window aggregator, since the primary timestamp may not be known by exchange operator.
  blockDataUpdateTsWindow(pRes, 0);
2697

2698
  int64_t el = taosGetTimestampUs() - startTs;
2699

H
Haojun Liao 已提交
2700 2701
  pLoadInfo->totalRows += numOfRows;
  pLoadInfo->totalSize += compLen;
2702

H
Haojun Liao 已提交
2703 2704 2705
  if (total != NULL) {
    *total += numOfRows;
  }
2706

H
Haojun Liao 已提交
2707
  pLoadInfo->totalElapsed += el;
2708 2709
  return TSDB_CODE_SUCCESS;
}
2710

L
Liu Jicong 已提交
2711 2712
static void* setAllSourcesCompleted(SOperatorInfo* pOperator, int64_t startTs) {
  SExchangeInfo* pExchangeInfo = pOperator->info;
2713
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
H
Haojun Liao 已提交
2714

2715
  int64_t              el = taosGetTimestampUs() - startTs;
H
Haojun Liao 已提交
2716
  SLoadRemoteDataInfo* pLoadInfo = &pExchangeInfo->loadInfo;
2717

H
Haojun Liao 已提交
2718
  pLoadInfo->totalElapsed += el;
H
Haojun Liao 已提交
2719

2720
  size_t totalSources = taosArrayGetSize(pExchangeInfo->pSources);
L
Liu Jicong 已提交
2721 2722 2723
  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);
2724 2725 2726 2727 2728

  doSetOperatorCompleted(pOperator);
  return NULL;
}

L
Liu Jicong 已提交
2729 2730
static SSDataBlock* concurrentlyLoadRemoteDataImpl(SOperatorInfo* pOperator, SExchangeInfo* pExchangeInfo,
                                                   SExecTaskInfo* pTaskInfo) {
2731 2732 2733 2734 2735 2736 2737 2738 2739
  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);

2740
      if (pDataInfo->status == EX_SOURCE_DATA_EXHAUSTED) {
2741
        completed += 1;
H
Haojun Liao 已提交
2742 2743
        continue;
      }
2744

2745
      if (pDataInfo->status != EX_SOURCE_DATA_READY) {
2746 2747 2748
        continue;
      }

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

L
Liu Jicong 已提交
2752
      SSDataBlock*         pRes = pExchangeInfo->pResult;
H
Haojun Liao 已提交
2753
      SLoadRemoteDataInfo* pLoadInfo = &pExchangeInfo->loadInfo;
2754
      if (pRsp->numOfRows == 0) {
L
Liu Jicong 已提交
2755 2756
        qDebug("%s vgId:%d, taskID:0x%" PRIx64 " index:%d completed, rowsOfSource:%" PRIu64 ", totalRows:%" PRIu64
               " try next",
2757
               GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->taskId, i + 1, pDataInfo->totalRows,
H
Haojun Liao 已提交
2758
               pExchangeInfo->loadInfo.totalRows);
2759
        pDataInfo->status = EX_SOURCE_DATA_EXHAUSTED;
2760 2761 2762
        completed += 1;
        continue;
      }
H
Haojun Liao 已提交
2763

H
Haojun Liao 已提交
2764
      SRetrieveTableRsp* pTableRsp = pDataInfo->pRsp;
X
Xiaoyu Wang 已提交
2765 2766
      code = setSDataBlockFromFetchRsp(pExchangeInfo->pResult, pLoadInfo, pTableRsp->numOfRows, pTableRsp->data,
                                       pTableRsp->compLen, pTableRsp->numOfCols, startTs, &pDataInfo->totalRows, NULL);
2767
      if (code != 0) {
2768 2769 2770
        goto _error;
      }

2771 2772 2773
      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 已提交
2774 2775
               GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->taskId, pRes->info.rows, pDataInfo->totalRows,
               pLoadInfo->totalRows, pLoadInfo->totalSize, i + 1, totalSources);
2776
        pDataInfo->status = EX_SOURCE_DATA_EXHAUSTED;
2777
      } else {
dengyihao's avatar
dengyihao 已提交
2778 2779
        qDebug("%s fetch msg rsp from vgId:%d, taskId:0x%" PRIx64 " numOfRows:%d, totalRows:%" PRIu64
               ", totalBytes:%" PRIu64,
H
Haojun Liao 已提交
2780 2781
               GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->taskId, pRes->info.rows, pLoadInfo->totalRows,
               pLoadInfo->totalSize);
2782 2783
      }

2784 2785
      if (pDataInfo->status != EX_SOURCE_DATA_EXHAUSTED) {
        pDataInfo->status = EX_SOURCE_DATA_NOT_READY;
2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804
        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 已提交
2805 2806 2807
static SSDataBlock* concurrentlyLoadRemoteData(SOperatorInfo* pOperator) {
  SExchangeInfo* pExchangeInfo = pOperator->info;
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
H
Haojun Liao 已提交
2808

H
Haojun Liao 已提交
2809 2810 2811
  if (pOperator->status == OP_RES_TO_RETURN) {
    return concurrentlyLoadRemoteDataImpl(pOperator, pExchangeInfo, pTaskInfo);
  }
2812

L
Liu Jicong 已提交
2813
  size_t  totalSources = taosArrayGetSize(pExchangeInfo->pSources);
2814 2815 2816
  int64_t startTs = taosGetTimestampUs();

  // Asynchronously send all fetch requests to all sources.
L
Liu Jicong 已提交
2817
  for (int32_t i = 0; i < totalSources; ++i) {
2818 2819
    int32_t code = doSendFetchDataRequest(pExchangeInfo, pTaskInfo, i);
    if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
2820
      return NULL;
2821 2822 2823 2824
    }
  }

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

  tsem_wait(&pExchangeInfo->ready);
H
Haojun Liao 已提交
2829 2830
  pOperator->status = OP_RES_TO_RETURN;
  return concurrentlyLoadRemoteDataImpl(pOperator, pExchangeInfo, pTaskInfo);
2831 2832
}

L
Liu Jicong 已提交
2833 2834 2835
static int32_t prepareConcurrentlyLoad(SOperatorInfo* pOperator) {
  SExchangeInfo* pExchangeInfo = pOperator->info;
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
2836

L
Liu Jicong 已提交
2837
  size_t  totalSources = taosArrayGetSize(pExchangeInfo->pSources);
2838 2839 2840
  int64_t startTs = taosGetTimestampUs();

  // Asynchronously send all fetch requests to all sources.
L
Liu Jicong 已提交
2841
  for (int32_t i = 0; i < totalSources; ++i) {
2842 2843
    int32_t code = doSendFetchDataRequest(pExchangeInfo, pTaskInfo, i);
    if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
2844 2845
      pTaskInfo->code = code;
      return code;
2846 2847 2848 2849
    }
  }

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

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

H
Haojun Liao 已提交
2856
  return TSDB_CODE_SUCCESS;
2857 2858
}

L
Liu Jicong 已提交
2859 2860 2861
static SSDataBlock* seqLoadRemoteData(SOperatorInfo* pOperator) {
  SExchangeInfo* pExchangeInfo = pOperator->info;
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
2862

L
Liu Jicong 已提交
2863
  size_t  totalSources = taosArrayGetSize(pExchangeInfo->pSources);
2864
  int64_t startTs = taosGetTimestampUs();
2865

L
Liu Jicong 已提交
2866
  while (1) {
2867 2868
    if (pExchangeInfo->current >= totalSources) {
      return setAllSourcesCompleted(pOperator, startTs);
2869
    }
2870

2871 2872 2873
    doSendFetchDataRequest(pExchangeInfo, pTaskInfo, pExchangeInfo->current);
    tsem_wait(&pExchangeInfo->ready);

dengyihao's avatar
dengyihao 已提交
2874
    SSourceDataInfo*       pDataInfo = taosArrayGet(pExchangeInfo->pSourceDataInfo, pExchangeInfo->current);
X
Xiaoyu Wang 已提交
2875
    SDownstreamSourceNode* pSource = taosArrayGet(pExchangeInfo->pSources, pExchangeInfo->current);
2876

H
Haojun Liao 已提交
2877
    if (pDataInfo->code != TSDB_CODE_SUCCESS) {
dengyihao's avatar
dengyihao 已提交
2878 2879
      qError("%s vgId:%d, taskID:0x%" PRIx64 " error happens, code:%s", GET_TASKID(pTaskInfo), pSource->addr.nodeId,
             pSource->taskId, tstrerror(pDataInfo->code));
H
Haojun Liao 已提交
2880 2881 2882 2883
      pOperator->pTaskInfo->code = pDataInfo->code;
      return NULL;
    }

L
Liu Jicong 已提交
2884
    SRetrieveTableRsp*   pRsp = pDataInfo->pRsp;
H
Haojun Liao 已提交
2885
    SLoadRemoteDataInfo* pLoadInfo = &pExchangeInfo->loadInfo;
2886
    if (pRsp->numOfRows == 0) {
dengyihao's avatar
dengyihao 已提交
2887 2888
      qDebug("%s vgId:%d, taskID:0x%" PRIx64 " %d of total completed, rowsOfSource:%" PRIu64 ", totalRows:%" PRIu64
             " try next",
2889
             GET_TASKID(pTaskInfo), pSource->addr.nodeId, pSource->taskId, pExchangeInfo->current + 1,
H
Haojun Liao 已提交
2890
             pDataInfo->totalRows, pLoadInfo->totalRows);
H
Haojun Liao 已提交
2891

2892
      pDataInfo->status = EX_SOURCE_DATA_EXHAUSTED;
2893 2894 2895
      pExchangeInfo->current += 1;
      continue;
    }
H
Haojun Liao 已提交
2896

L
Liu Jicong 已提交
2897
    SSDataBlock*       pRes = pExchangeInfo->pResult;
H
Haojun Liao 已提交
2898
    SRetrieveTableRsp* pTableRsp = pDataInfo->pRsp;
L
Liu Jicong 已提交
2899 2900
    int32_t            code =
        setSDataBlockFromFetchRsp(pExchangeInfo->pResult, pLoadInfo, pTableRsp->numOfRows, pTableRsp->data,
2901
                                  pTableRsp->compLen, pTableRsp->numOfCols, startTs, &pDataInfo->totalRows, NULL);
2902 2903

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

2909
      pDataInfo->status = EX_SOURCE_DATA_EXHAUSTED;
2910 2911
      pExchangeInfo->current += 1;
    } else {
L
Liu Jicong 已提交
2912 2913 2914 2915
      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);
2916 2917
    }

2918
    pOperator->resultInfo.totalRows += pRes->info.rows;
2919 2920
    return pExchangeInfo->pResult;
  }
2921 2922
}

L
Liu Jicong 已提交
2923
static int32_t prepareLoadRemoteData(SOperatorInfo* pOperator) {
2924
  if (OPTR_IS_OPENED(pOperator)) {
H
Haojun Liao 已提交
2925 2926 2927
    return TSDB_CODE_SUCCESS;
  }

2928 2929
  int64_t st = taosGetTimestampUs();

L
Liu Jicong 已提交
2930
  SExchangeInfo* pExchangeInfo = pOperator->info;
2931
  if (!pExchangeInfo->seqLoadData) {
H
Haojun Liao 已提交
2932 2933 2934 2935 2936 2937
    int32_t code = prepareConcurrentlyLoad(pOperator);
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }
  }

2938
  OPTR_SET_OPENED(pOperator);
2939
  pOperator->cost.openCost = (taosGetTimestampUs() - st) / 1000.0;
H
Haojun Liao 已提交
2940 2941 2942
  return TSDB_CODE_SUCCESS;
}

2943
static SSDataBlock* doLoadRemoteData(SOperatorInfo* pOperator) {
L
Liu Jicong 已提交
2944 2945
  SExchangeInfo* pExchangeInfo = pOperator->info;
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
2946

2947
  pTaskInfo->code = pOperator->fpSet._openFn(pOperator);
2948
  if (pTaskInfo->code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
2949 2950
    return NULL;
  }
2951

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

2955
  if (pOperator->status == OP_EXEC_DONE) {
L
Liu Jicong 已提交
2956 2957 2958
    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);
2959 2960 2961 2962 2963 2964
    return NULL;
  }

  if (pExchangeInfo->seqLoadData) {
    return seqLoadRemoteData(pOperator);
  } else {
H
Haojun Liao 已提交
2965
    return concurrentlyLoadRemoteData(pOperator);
2966
  }
H
Haojun Liao 已提交
2967
}
2968

H
Haojun Liao 已提交
2969
static int32_t initDataSource(int32_t numOfSources, SExchangeInfo* pInfo) {
2970
  pInfo->pSourceDataInfo = taosArrayInit(numOfSources, sizeof(SSourceDataInfo));
H
Haojun Liao 已提交
2971 2972
  if (pInfo->pSourceDataInfo == NULL) {
    return TSDB_CODE_OUT_OF_MEMORY;
2973 2974
  }

L
Liu Jicong 已提交
2975
  for (int32_t i = 0; i < numOfSources; ++i) {
2976
    SSourceDataInfo dataInfo = {0};
H
Haojun Liao 已提交
2977
    dataInfo.status = EX_SOURCE_DATA_NOT_READY;
L
Liu Jicong 已提交
2978 2979
    dataInfo.pEx = pInfo;
    dataInfo.index = i;
2980

H
Haojun Liao 已提交
2981 2982 2983 2984 2985 2986 2987 2988 2989 2990
    void* ret = taosArrayPush(pInfo->pSourceDataInfo, &dataInfo);
    if (ret == NULL) {
      taosArrayDestroy(pInfo->pSourceDataInfo);
      return TSDB_CODE_OUT_OF_MEMORY;
    }
  }

  return TSDB_CODE_SUCCESS;
}

X
Xiaoyu Wang 已提交
2991
SOperatorInfo* createExchangeOperatorInfo(void* pTransporter, const SNodeList* pSources, SSDataBlock* pBlock,
2992
                                          SExecTaskInfo* pTaskInfo) {
L
Liu Jicong 已提交
2993
  SExchangeInfo* pInfo = taosMemoryCalloc(1, sizeof(SExchangeInfo));
wafwerar's avatar
wafwerar 已提交
2994
  SOperatorInfo* pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
2995
  if (pInfo == NULL || pOperator == NULL) {
2996
    goto _error;
H
Haojun Liao 已提交
2997 2998
  }

H
Haojun Liao 已提交
2999
  size_t numOfSources = LIST_LENGTH(pSources);
H
Haojun Liao 已提交
3000
  pInfo->pSources = taosArrayInit(numOfSources, sizeof(SDownstreamSourceNode));
H
Haojun Liao 已提交
3001 3002 3003
  pInfo->pSourceDataInfo = taosArrayInit(numOfSources, sizeof(SSourceDataInfo));
  if (pInfo->pSourceDataInfo == NULL || pInfo->pSources == NULL) {
    goto _error;
H
Haojun Liao 已提交
3004 3005
  }

L
Liu Jicong 已提交
3006 3007
  for (int32_t i = 0; i < numOfSources; ++i) {
    SNodeListNode* pNode = nodesListGetNode((SNodeList*)pSources, i);
H
Haojun Liao 已提交
3008 3009
    taosArrayPush(pInfo->pSources, pNode);
  }
3010

H
Haojun Liao 已提交
3011 3012 3013
  int32_t code = initDataSource(numOfSources, pInfo);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
3014
  }
H
Haojun Liao 已提交
3015

dengyihao's avatar
dengyihao 已提交
3016
  pInfo->pResult = pBlock;
3017 3018 3019
  pInfo->seqLoadData = true;

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

3021
  pOperator->name = "ExchangeOperator";
X
Xiaoyu Wang 已提交
3022
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_EXCHANGE;
3023 3024 3025 3026 3027
  pOperator->blocking = false;
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
  pOperator->numOfExprs = pBlock->info.numOfCols;
  pOperator->pTaskInfo = pTaskInfo;
3028

L
Liu Jicong 已提交
3029 3030
  pOperator->fpSet = createOperatorFpSet(prepareLoadRemoteData, doLoadRemoteData, NULL, NULL,
                                         destroyExchangeOperatorInfo, NULL, NULL, NULL);
3031
  pInfo->pTransporter = pTransporter;
3032
  return pOperator;
H
Haojun Liao 已提交
3033

L
Liu Jicong 已提交
3034
_error:
H
Haojun Liao 已提交
3035
  if (pInfo != NULL) {
H
Haojun Liao 已提交
3036
    destroyExchangeOperatorInfo(pInfo, numOfSources);
H
Haojun Liao 已提交
3037 3038
  }

wafwerar's avatar
wafwerar 已提交
3039 3040
  taosMemoryFreeClear(pInfo);
  taosMemoryFreeClear(pOperator);
H
Haojun Liao 已提交
3041
  pTaskInfo->code = TSDB_CODE_OUT_OF_MEMORY;
H
Haojun Liao 已提交
3042
  return NULL;
3043 3044
}

dengyihao's avatar
dengyihao 已提交
3045 3046
static int32_t doInitAggInfoSup(SAggSupporter* pAggSup, SqlFunctionCtx* pCtx, int32_t numOfOutput, size_t keyBufSize,
                                const char* pKey);
3047

3048
static void destroySortedMergeOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
3049
  SSortedMergeOperatorInfo* pInfo = (SSortedMergeOperatorInfo*)param;
H
Haojun Liao 已提交
3050
  taosArrayDestroy(pInfo->pSortInfo);
3051 3052 3053
  taosArrayDestroy(pInfo->groupInfo);

  if (pInfo->pSortHandle != NULL) {
H
Haojun Liao 已提交
3054
    tsortDestroySortHandle(pInfo->pSortHandle);
3055 3056
  }

H
Haojun Liao 已提交
3057
  blockDataDestroy(pInfo->binfo.pRes);
H
Haojun Liao 已提交
3058
  cleanupAggSup(&pInfo->aggSup);
3059
}
H
Haojun Liao 已提交
3060

L
Liu Jicong 已提交
3061
static bool needToMerge(SSDataBlock* pBlock, SArray* groupInfo, char** buf, int32_t rowIndex) {
3062 3063 3064 3065
  size_t size = taosArrayGetSize(groupInfo);
  if (size == 0) {
    return true;
  }
3066

3067 3068
  for (int32_t i = 0; i < size; ++i) {
    int32_t* index = taosArrayGet(groupInfo, i);
3069

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

3073 3074 3075
    if ((isNull && buf[i] != NULL) || (!isNull && buf[i] == NULL)) {
      return false;
    }
3076

3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089
    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;
      }
3090 3091 3092
    }
  }

3093
  return 0;
3094 3095
}

L
Liu Jicong 已提交
3096 3097 3098
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
X
Xiaoyu Wang 已提交
3099
                                             //    pCtx[j].startRow = rowIndex;
3100 3101
  }

3102 3103
  for (int32_t j = 0; j < numOfExpr; ++j) {
    int32_t functionId = pCtx[j].functionId;
L
Liu Jicong 已提交
3104 3105 3106 3107 3108 3109 3110 3111 3112
    //    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]);
    //    }
3113
  }
3114
}
3115

L
Liu Jicong 已提交
3116 3117
static void doFinalizeResultImpl(SqlFunctionCtx* pCtx, int32_t numOfExpr) {
  for (int32_t j = 0; j < numOfExpr; ++j) {
3118 3119 3120 3121
    int32_t functionId = pCtx[j].functionId;
    //    if (functionId == FUNC_TAG_DUMMY || functionId == FUNC_TS_DUMMY) {
    //      continue;
    //    }
3122

3123 3124 3125 3126
    //    if (functionId < 0) {
    //      SUdfInfo* pUdfInfo = taosArrayGet(pInfo->udfInfo, -1 * functionId - 1);
    //      doInvokeUdf(pUdfInfo, &pCtx[j], 0, TSDB_UDF_FUNC_FINALIZE);
    //    } else {
dengyihao's avatar
dengyihao 已提交
3127
    //    pCtx[j].fpSet.finalize(&pCtx[j]);
3128 3129
  }
}
3130

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

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

3138 3139 3140
    char* data = colDataGetData(pColInfo, rowIndex);
    memcpy(rowColData[i], data, colDataGetLength(pColInfo, rowIndex));
  }
3141

3142 3143
  return true;
}
3144

3145 3146
static void doMergeImpl(SOperatorInfo* pOperator, int32_t numOfExpr, SSDataBlock* pBlock) {
  SSortedMergeOperatorInfo* pInfo = pOperator->info;
3147

3148
  SqlFunctionCtx* pCtx = pInfo->binfo.pCtx;
L
Liu Jicong 已提交
3149
  for (int32_t i = 0; i < pBlock->info.numOfCols; ++i) {
X
Xiaoyu Wang 已提交
3150
    //    pCtx[i].size = 1;
3151
  }
3152

L
Liu Jicong 已提交
3153
  for (int32_t i = 0; i < pBlock->info.rows; ++i) {
3154 3155 3156 3157 3158 3159 3160 3161 3162
    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);
3163 3164
        int32_t numOfRows = getNumOfResult(pInfo->binfo.pCtx, pOperator->numOfExprs, NULL);
        //        setTagValueForMultipleRows(pCtx, pOperator->numOfExprs, numOfRows);
3165

3166
        // TODO check for available buffer;
H
Haojun Liao 已提交
3167

3168 3169 3170 3171 3172
        // next group info data
        pInfo->binfo.pRes->info.rows += numOfRows;
        for (int32_t j = 0; j < numOfExpr; ++j) {
          if (pCtx[j].functionId < 0) {
            continue;
3173
          }
3174

H
Haojun Liao 已提交
3175
          pCtx[j].fpSet.process(&pCtx[j]);
3176
        }
3177 3178 3179

        doMergeResultImpl(pInfo, pCtx, numOfExpr, i);
        pInfo->hasGroupVal = saveCurrentTuple(pInfo->groupVal, pInfo->groupInfo, pBlock, i);
H
Haojun Liao 已提交
3180
      }
3181 3182 3183 3184
    }
  }
}

3185 3186
static SSDataBlock* doMerge(SOperatorInfo* pOperator) {
  SSortedMergeOperatorInfo* pInfo = pOperator->info;
L
Liu Jicong 已提交
3187
  SSortHandle*              pHandle = pInfo->pSortHandle;
3188

3189
  SSDataBlock* pDataBlock = createOneDataBlock(pInfo->binfo.pRes, false);
3190
  blockDataEnsureCapacity(pDataBlock, pOperator->resultInfo.capacity);
3191

L
Liu Jicong 已提交
3192
  while (1) {
3193
    blockDataCleanup(pDataBlock);
3194
    while (1) {
H
Haojun Liao 已提交
3195
      STupleHandle* pTupleHandle = tsortNextTuple(pHandle);
3196 3197
      if (pTupleHandle == NULL) {
        break;
3198
      }
3199

3200 3201
      // build datablock for merge for one group
      appendOneRowToDataBlock(pDataBlock, pTupleHandle);
3202
      if (pDataBlock->info.rows >= pOperator->resultInfo.capacity) {
3203 3204
        break;
      }
3205
    }
3206

3207 3208 3209
    if (pDataBlock->info.rows == 0) {
      break;
    }
3210

3211
    setInputDataBlock(pOperator, pInfo->binfo.pCtx, pDataBlock, TSDB_ORDER_ASC, MAIN_SCAN, true);
L
Liu Jicong 已提交
3212 3213
    //  updateOutputBuf(&pInfo->binfo, &pAggInfo->bufCapacity, pBlock->info.rows * pAggInfo->resultRowFactor,
    //  pOperator->pRuntimeEnv, true);
3214
    doMergeImpl(pOperator, pOperator->numOfExprs, pDataBlock);
3215 3216
    // flush to tuple store, and after all data have been handled, return to upstream node or sink node
  }
3217

3218 3219 3220
  doFinalizeResultImpl(pInfo->binfo.pCtx, pOperator->numOfExprs);
  int32_t numOfRows = getNumOfResult(pInfo->binfo.pCtx, pOperator->numOfExprs, NULL);
  //        setTagValueForMultipleRows(pCtx, pOperator->numOfExprs, numOfRows);
3221

3222
  // TODO check for available buffer;
3223

3224 3225
  // next group info data
  pInfo->binfo.pRes->info.rows += numOfRows;
L
Liu Jicong 已提交
3226
  return (pInfo->binfo.pRes->info.rows > 0) ? pInfo->binfo.pRes : NULL;
3227
}
3228

3229
static SSDataBlock* doSortedMerge(SOperatorInfo* pOperator) {
3230 3231
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
3232 3233
  }

L
Liu Jicong 已提交
3234
  SExecTaskInfo*            pTaskInfo = pOperator->pTaskInfo;
3235
  SSortedMergeOperatorInfo* pInfo = pOperator->info;
H
Haojun Liao 已提交
3236
  if (pOperator->status == OP_RES_TO_RETURN) {
3237
    return getSortedBlockData(pInfo->pSortHandle, pInfo->binfo.pRes, pOperator->resultInfo.capacity, NULL);
3238 3239
  }

3240
  int32_t numOfBufPage = pInfo->sortBufSize / pInfo->bufPageSize;
dengyihao's avatar
dengyihao 已提交
3241 3242
  pInfo->pSortHandle = tsortCreateSortHandle(pInfo->pSortInfo, NULL, SORT_MULTISOURCE_MERGE, pInfo->bufPageSize,
                                             numOfBufPage, pInfo->binfo.pRes, "GET_TASKID(pTaskInfo)");
H
Haojun Liao 已提交
3243

3244
  tsortSetFetchRawDataFp(pInfo->pSortHandle, loadNextDataBlock, NULL, NULL);
3245

L
Liu Jicong 已提交
3246
  for (int32_t i = 0; i < pOperator->numOfDownstream; ++i) {
wmmhello's avatar
wmmhello 已提交
3247
    SSortSource* ps = taosMemoryCalloc(1, sizeof(SSortSource));
H
Haojun Liao 已提交
3248
    ps->param = pOperator->pDownstream[i];
H
Haojun Liao 已提交
3249
    tsortAddSource(pInfo->pSortHandle, ps);
3250 3251
  }

H
Haojun Liao 已提交
3252
  int32_t code = tsortOpen(pInfo->pSortHandle);
3253
  if (code != TSDB_CODE_SUCCESS) {
3254
    longjmp(pTaskInfo->env, terrno);
3255 3256
  }

H
Haojun Liao 已提交
3257
  pOperator->status = OP_RES_TO_RETURN;
3258
  return doMerge(pOperator);
3259
}
3260

L
Liu Jicong 已提交
3261 3262
static int32_t initGroupCol(SExprInfo* pExprInfo, int32_t numOfCols, SArray* pGroupInfo,
                            SSortedMergeOperatorInfo* pInfo) {
3263 3264
  if (pGroupInfo == NULL || taosArrayGetSize(pGroupInfo) == 0) {
    return 0;
H
Haojun Liao 已提交
3265 3266
  }

3267 3268 3269 3270 3271 3272 3273 3274
  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 已提交
3275 3276
  size_t numOfGroupCol = taosArrayGetSize(pInfo->groupInfo);
  for (int32_t i = 0; i < numOfGroupCol; ++i) {
3277
    SColumn* pCol = taosArrayGet(pGroupInfo, i);
L
Liu Jicong 已提交
3278
    for (int32_t j = 0; j < numOfCols; ++j) {
H
Haojun Liao 已提交
3279
      SExprInfo* pe = &pExprInfo[j];
3280
      if (pe->base.resSchema.slotId == pCol->colId) {
3281 3282
        taosArrayPush(plist, pCol);
        taosArrayPush(pInfo->groupInfo, &j);
H
Haojun Liao 已提交
3283
        len += pCol->bytes;
3284 3285
        break;
      }
H
Haojun Liao 已提交
3286 3287 3288
    }
  }

3289
  ASSERT(taosArrayGetSize(pGroupInfo) == taosArrayGetSize(plist));
H
Haojun Liao 已提交
3290

wafwerar's avatar
wafwerar 已提交
3291
  pInfo->groupVal = taosMemoryCalloc(1, (POINTER_BYTES * numOfGroupCol + len));
3292 3293 3294 3295
  if (pInfo->groupVal == NULL) {
    taosArrayDestroy(plist);
    return TSDB_CODE_OUT_OF_MEMORY;
  }
H
Haojun Liao 已提交
3296

3297
  int32_t offset = 0;
L
Liu Jicong 已提交
3298 3299
  char*   start = (char*)(pInfo->groupVal + (POINTER_BYTES * numOfGroupCol));
  for (int32_t i = 0; i < numOfGroupCol; ++i) {
3300 3301
    pInfo->groupVal[i] = start + offset;
    SColumn* pCol = taosArrayGet(plist, i);
H
Haojun Liao 已提交
3302
    offset += pCol->bytes;
3303
  }
H
Haojun Liao 已提交
3304

3305
  taosArrayDestroy(plist);
H
Haojun Liao 已提交
3306

3307 3308
  return TSDB_CODE_SUCCESS;
}
H
Haojun Liao 已提交
3309

L
Liu Jicong 已提交
3310 3311 3312
SOperatorInfo* createSortedMergeOperatorInfo(SOperatorInfo** downstream, int32_t numOfDownstream, SExprInfo* pExprInfo,
                                             int32_t num, SArray* pSortInfo, SArray* pGroupInfo,
                                             SExecTaskInfo* pTaskInfo) {
wafwerar's avatar
wafwerar 已提交
3313
  SSortedMergeOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SSortedMergeOperatorInfo));
L
Liu Jicong 已提交
3314
  SOperatorInfo*            pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
3315
  if (pInfo == NULL || pOperator == NULL) {
3316
    goto _error;
3317
  }
H
Haojun Liao 已提交
3318

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

3322 3323 3324
  if (pInfo->binfo.pCtx == NULL || pInfo->binfo.pRes == NULL) {
    goto _error;
  }
H
Haojun Liao 已提交
3325

dengyihao's avatar
dengyihao 已提交
3326
  size_t  keyBufSize = sizeof(int64_t) + sizeof(int64_t) + POINTER_BYTES;
3327
  int32_t code = doInitAggInfoSup(&pInfo->aggSup, pInfo->binfo.pCtx, num, keyBufSize, pTaskInfo->id.str);
3328 3329 3330
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
H
Haojun Liao 已提交
3331

H
Haojun Liao 已提交
3332
  setFunctionResultOutput(&pInfo->binfo, &pInfo->aggSup, MAIN_SCAN, num, pTaskInfo);
H
Haojun Liao 已提交
3333
  code = initGroupCol(pExprInfo, num, pGroupInfo, pInfo);
3334 3335 3336
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
H
Haojun Liao 已提交
3337

L
Liu Jicong 已提交
3338 3339 3340 3341 3342
  //  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 已提交
3343

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

L
Liu Jicong 已提交
3346
  pOperator->name = "SortedMerge";
X
Xiaoyu Wang 已提交
3347
  // pOperator->operatorType = OP_SortedMerge;
3348
  pOperator->blocking = true;
L
Liu Jicong 已提交
3349 3350
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
3351
  pOperator->numOfExprs = num;
L
Liu Jicong 已提交
3352
  pOperator->pExpr = pExprInfo;
H
Haojun Liao 已提交
3353

L
Liu Jicong 已提交
3354
  pOperator->pTaskInfo = pTaskInfo;
H
Haojun Liao 已提交
3355

3356 3357
  pOperator->fpSet = createOperatorFpSet(operatorDummyOpenFn, doSortedMerge, NULL, NULL, destroySortedMergeOperatorInfo,
                                         NULL, NULL, NULL);
3358 3359 3360
  code = appendDownstream(pOperator, downstream, numOfDownstream);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
3361
  }
H
Haojun Liao 已提交
3362

3363
  return pOperator;
H
Haojun Liao 已提交
3364

L
Liu Jicong 已提交
3365
_error:
3366
  if (pInfo != NULL) {
H
Haojun Liao 已提交
3367
    destroySortedMergeOperatorInfo(pInfo, num);
H
Haojun Liao 已提交
3368 3369
  }

wafwerar's avatar
wafwerar 已提交
3370 3371
  taosMemoryFreeClear(pInfo);
  taosMemoryFreeClear(pOperator);
3372 3373
  terrno = TSDB_CODE_QRY_OUT_OF_MEMORY;
  return NULL;
H
Haojun Liao 已提交
3374 3375
}

X
Xiaoyu Wang 已提交
3376
int32_t getTableScanInfo(SOperatorInfo* pOperator, int32_t* order, int32_t* scanFlag) {
3377
  // todo add more information about exchange operation
3378
  int32_t type = pOperator->operatorType;
X
Xiaoyu Wang 已提交
3379 3380
  if (type == QUERY_NODE_PHYSICAL_PLAN_EXCHANGE || type == QUERY_NODE_PHYSICAL_PLAN_SYSTABLE_SCAN ||
      type == QUERY_NODE_PHYSICAL_PLAN_STREAM_SCAN) {
3381 3382 3383
    *order = TSDB_ORDER_ASC;
    *scanFlag = MAIN_SCAN;
    return TSDB_CODE_SUCCESS;
3384
  } else if (type == QUERY_NODE_PHYSICAL_PLAN_TABLE_SCAN) {
3385 3386 3387 3388 3389
    STableScanInfo* pTableScanInfo = pOperator->info;
    *order = pTableScanInfo->cond.order;
    *scanFlag = pTableScanInfo->scanFlag;
    return TSDB_CODE_SUCCESS;
  } else {
H
Haojun Liao 已提交
3390
    if (pOperator->pDownstream == NULL || pOperator->pDownstream[0] == NULL) {
3391
      return TSDB_CODE_INVALID_PARA;
H
Haojun Liao 已提交
3392
    } else {
3393
      return getTableScanInfo(pOperator->pDownstream[0], order, scanFlag);
3394 3395 3396
    }
  }
}
3397 3398

// this is a blocking operator
L
Liu Jicong 已提交
3399
static int32_t doOpenAggregateOptr(SOperatorInfo* pOperator) {
H
Haojun Liao 已提交
3400 3401
  if (OPTR_IS_OPENED(pOperator)) {
    return TSDB_CODE_SUCCESS;
3402 3403
  }

H
Haojun Liao 已提交
3404
  SExecTaskInfo*    pTaskInfo = pOperator->pTaskInfo;
3405
  SAggOperatorInfo* pAggInfo = pOperator->info;
H
Haojun Liao 已提交
3406

dengyihao's avatar
dengyihao 已提交
3407
  SOptrBasicInfo* pInfo = &pAggInfo->binfo;
X
Xiaoyu Wang 已提交
3408
  SOperatorInfo*  downstream = pOperator->pDownstream[0];
3409

3410 3411
  int64_t st = taosGetTimestampUs();

3412 3413 3414
  int32_t order = TSDB_ORDER_ASC;
  int32_t scanFlag = MAIN_SCAN;

H
Haojun Liao 已提交
3415
  while (1) {
3416
    SSDataBlock* pBlock = downstream->fpSet.getNextFn(downstream);
3417 3418 3419 3420
    if (pBlock == NULL) {
      break;
    }

3421 3422 3423 3424
    int32_t code = getTableScanInfo(pOperator, &order, &scanFlag);
    if (code != TSDB_CODE_SUCCESS) {
      longjmp(pTaskInfo->env, code);
    }
3425

3426 3427
    // there is an scalar expression that needs to be calculated before apply the group aggregation.
    if (pAggInfo->pScalarExprInfo != NULL) {
3428
      code = projectApplyFunctions(pAggInfo->pScalarExprInfo, pBlock, pBlock, pAggInfo->pScalarCtx,
3429
                                   pAggInfo->numOfScalarExpr, NULL);
3430
      if (code != TSDB_CODE_SUCCESS) {
3431
        longjmp(pTaskInfo->env, code);
3432
      }
3433 3434
    }

3435
    // the pDataBlock are always the same one, no need to call this again
3436
    setExecutionContext(pOperator->numOfExprs, pBlock->info.groupId, pTaskInfo, pAggInfo);
3437
    setInputDataBlock(pOperator, pInfo->pCtx, pBlock, order, scanFlag, true);
3438 3439 3440 3441
    code = doAggregateImpl(pOperator, 0, pInfo->pCtx);
    if (code != 0) {
      longjmp(pTaskInfo->env, code);
    }
3442

dengyihao's avatar
dengyihao 已提交
3443
#if 0  // test for encode/decode result info
3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454
    if(pOperator->encodeResultRow){
      char *result = NULL;
      int32_t length = 0;
      SAggSupporter   *pSup = &pAggInfo->aggSup;
      pOperator->encodeResultRow(pOperator, pSup, pInfo, &result, &length);
      taosHashClear(pSup->pResultRowHashTable);
      pInfo->resultRowInfo.size = 0;
      pOperator->decodeResultRow(pOperator, pSup, pInfo, result, length);
      if(result){
        taosMemoryFree(result);
      }
3455
    }
3456
#endif
3457 3458
  }

H
Haojun Liao 已提交
3459
  closeAllResultRows(&pAggInfo->binfo.resultRowInfo);
3460
  initGroupedResultInfo(&pAggInfo->groupResInfo, pAggInfo->aggSup.pResultRowHashTable, 0);
H
Haojun Liao 已提交
3461
  OPTR_SET_OPENED(pOperator);
3462

3463
  pOperator->cost.openCost = (taosGetTimestampUs() - st) / 1000.0;
H
Haojun Liao 已提交
3464 3465 3466
  return TSDB_CODE_SUCCESS;
}

3467
static SSDataBlock* getAggregateResult(SOperatorInfo* pOperator) {
L
Liu Jicong 已提交
3468
  SAggOperatorInfo* pAggInfo = pOperator->info;
H
Haojun Liao 已提交
3469 3470 3471 3472 3473 3474
  SOptrBasicInfo*   pInfo = &pAggInfo->binfo;

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

L
Liu Jicong 已提交
3475
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
3476
  pTaskInfo->code = pOperator->fpSet._openFn(pOperator);
H
Haojun Liao 已提交
3477
  if (pTaskInfo->code != TSDB_CODE_SUCCESS) {
3478
    doSetOperatorCompleted(pOperator);
H
Haojun Liao 已提交
3479 3480 3481
    return NULL;
  }

H
Haojun Liao 已提交
3482
  blockDataEnsureCapacity(pInfo->pRes, pOperator->resultInfo.capacity);
3483
  doBuildResultDatablock(pOperator, pInfo, &pAggInfo->groupResInfo, pAggInfo->aggSup.pResultBuf);
3484
  if (pInfo->pRes->info.rows == 0 || !hashRemainDataInGroupInfo(&pAggInfo->groupResInfo)) {
H
Haojun Liao 已提交
3485 3486
    doSetOperatorCompleted(pOperator);
  }
3487

3488
  size_t rows = blockDataGetNumOfRows(pInfo->pRes);  // pInfo->pRes : NULL;
3489 3490
  pOperator->resultInfo.totalRows += rows;

3491
  return (rows == 0) ? NULL : pInfo->pRes;
3492 3493
}

dengyihao's avatar
dengyihao 已提交
3494 3495
void aggEncodeResultRow(SOperatorInfo* pOperator, SAggSupporter* pSup, SOptrBasicInfo* pInfo, char** result,
                        int32_t* length) {
wmmhello's avatar
wmmhello 已提交
3496
  int32_t size = taosHashGetSize(pSup->pResultRowHashTable);
3497
  size_t  keyLen = sizeof(uint64_t) * 2;  // estimate the key length
wmmhello's avatar
wmmhello 已提交
3498
  int32_t totalSize = sizeof(int32_t) + size * (sizeof(int32_t) + keyLen + sizeof(int32_t) + pSup->resultRowSize);
wafwerar's avatar
wafwerar 已提交
3499
  *result = taosMemoryCalloc(1, totalSize);
L
Liu Jicong 已提交
3500
  if (*result == NULL) {
3501
    longjmp(pOperator->pTaskInfo->env, TSDB_CODE_OUT_OF_MEMORY);
wmmhello's avatar
wmmhello 已提交
3502 3503 3504
  }
  *(int32_t*)(*result) = size;
  int32_t offset = sizeof(int32_t);
3505 3506

  // prepare memory
3507
  SResultRowPosition* pos = &pInfo->resultRowInfo.cur;
dengyihao's avatar
dengyihao 已提交
3508 3509
  void*               pPage = getBufPage(pSup->pResultBuf, pos->pageId);
  SResultRow*         pRow = (SResultRow*)((char*)pPage + pos->offset);
3510 3511 3512
  setBufPageDirty(pPage, true);
  releaseBufPage(pSup->pResultBuf, pPage);

dengyihao's avatar
dengyihao 已提交
3513
  void* pIter = taosHashIterate(pSup->pResultRowHashTable, NULL);
wmmhello's avatar
wmmhello 已提交
3514
  while (pIter) {
dengyihao's avatar
dengyihao 已提交
3515
    void*               key = taosHashGetKey(pIter, &keyLen);
3516
    SResultRowPosition* p1 = (SResultRowPosition*)pIter;
3517

dengyihao's avatar
dengyihao 已提交
3518
    pPage = (SFilePage*)getBufPage(pSup->pResultBuf, p1->pageId);
3519
    pRow = (SResultRow*)((char*)pPage + p1->offset);
3520 3521
    setBufPageDirty(pPage, true);
    releaseBufPage(pSup->pResultBuf, pPage);
wmmhello's avatar
wmmhello 已提交
3522 3523 3524

    // recalculate the result size
    int32_t realTotalSize = offset + sizeof(int32_t) + keyLen + sizeof(int32_t) + pSup->resultRowSize;
L
Liu Jicong 已提交
3525 3526 3527
    if (realTotalSize > totalSize) {
      char* tmp = taosMemoryRealloc(*result, realTotalSize);
      if (tmp == NULL) {
wmmhello's avatar
wmmhello 已提交
3528
        terrno = TSDB_CODE_OUT_OF_MEMORY;
wafwerar's avatar
wafwerar 已提交
3529
        taosMemoryFree(*result);
wmmhello's avatar
wmmhello 已提交
3530
        *result = NULL;
3531
        longjmp(pOperator->pTaskInfo->env, TSDB_CODE_OUT_OF_MEMORY);
L
Liu Jicong 已提交
3532
      } else {
wmmhello's avatar
wmmhello 已提交
3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544
        *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);
3545
    memcpy(*result + offset, pRow, pSup->resultRowSize);
wmmhello's avatar
wmmhello 已提交
3546 3547 3548 3549 3550
    offset += pSup->resultRowSize;

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

L
Liu Jicong 已提交
3551
  if (length) {
wmmhello's avatar
wmmhello 已提交
3552 3553 3554 3555 3556
    *length = offset;
  }
  return;
}

dengyihao's avatar
dengyihao 已提交
3557 3558
bool aggDecodeResultRow(SOperatorInfo* pOperator, SAggSupporter* pSup, SOptrBasicInfo* pInfo, char* result,
                        int32_t length) {
L
Liu Jicong 已提交
3559
  if (!result || length <= 0) {
wmmhello's avatar
wmmhello 已提交
3560 3561 3562 3563 3564 3565 3566
    return false;
  }

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

  int32_t offset = sizeof(int32_t);
L
Liu Jicong 已提交
3567
  while (count-- > 0 && length > offset) {
wmmhello's avatar
wmmhello 已提交
3568 3569 3570
    int32_t keyLen = *(int32_t*)(result + offset);
    offset += sizeof(int32_t);

L
Liu Jicong 已提交
3571 3572 3573
    uint64_t    tableGroupId = *(uint64_t*)(result + offset);
    SResultRow* resultRow = getNewResultRow_rv(pSup->pResultBuf, tableGroupId, pSup->resultRowSize);
    if (!resultRow) {
3574
      longjmp(pOperator->pTaskInfo->env, TSDB_CODE_TSC_INVALID_INPUT);
wmmhello's avatar
wmmhello 已提交
3575
    }
3576

wmmhello's avatar
wmmhello 已提交
3577
    // add a new result set for a new group
3578 3579
    SResultRowPosition pos = {.pageId = resultRow->pageId, .offset = resultRow->offset};
    taosHashPut(pSup->pResultRowHashTable, result + offset, keyLen, &pos, sizeof(SResultRowPosition));
wmmhello's avatar
wmmhello 已提交
3580 3581 3582

    offset += keyLen;
    int32_t valueLen = *(int32_t*)(result + offset);
L
Liu Jicong 已提交
3583
    if (valueLen != pSup->resultRowSize) {
3584
      longjmp(pOperator->pTaskInfo->env, TSDB_CODE_TSC_INVALID_INPUT);
wmmhello's avatar
wmmhello 已提交
3585 3586 3587 3588 3589 3590 3591 3592 3593 3594
    }
    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);
3595
    prepareResultListBuffer(&pInfo->resultRowInfo, pOperator->pTaskInfo->env);
dengyihao's avatar
dengyihao 已提交
3596
    //    pInfo->resultRowInfo.cur = pInfo->resultRowInfo.size;
L
Liu Jicong 已提交
3597 3598
    //    pInfo->resultRowInfo.pPosition[pInfo->resultRowInfo.size++] =
    //        (SResultRowPosition){.pageId = resultRow->pageId, .offset = resultRow->offset};
dengyihao's avatar
dengyihao 已提交
3599
    pInfo->resultRowInfo.cur = (SResultRowPosition){.pageId = resultRow->pageId, .offset = resultRow->offset};
wmmhello's avatar
wmmhello 已提交
3600 3601
  }

L
Liu Jicong 已提交
3602
  if (offset != length) {
3603
    longjmp(pOperator->pTaskInfo->env, TSDB_CODE_TSC_INVALID_INPUT);
wmmhello's avatar
wmmhello 已提交
3604 3605 3606 3607
  }
  return true;
}

3608 3609
enum {
  PROJECT_RETRIEVE_CONTINUE = 0x1,
L
Liu Jicong 已提交
3610
  PROJECT_RETRIEVE_DONE = 0x2,
3611 3612 3613 3614 3615
};

static int32_t handleLimitOffset(SOperatorInfo* pOperator, SSDataBlock* pBlock) {
  SProjectOperatorInfo* pProjectInfo = pOperator->info;
  SOptrBasicInfo*       pInfo = &pProjectInfo->binfo;
L
Liu Jicong 已提交
3616
  SSDataBlock*          pRes = pInfo->pRes;
3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664

  if (pProjectInfo->curSOffset > 0) {
    if (pProjectInfo->groupId == 0) {  // it is the first group
      pProjectInfo->groupId = pBlock->info.groupId;
      blockDataCleanup(pInfo->pRes);
      return PROJECT_RETRIEVE_CONTINUE;
    } else if (pProjectInfo->groupId != pBlock->info.groupId) {
      pProjectInfo->curSOffset -= 1;

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

    // set current group id of the project operator
    pProjectInfo->groupId = pBlock->info.groupId;
  }

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

      return PROJECT_RETRIEVE_DONE;
    }

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

  // here we reach the start position, according to the limit/offset requirements.

  // set current group id
  pProjectInfo->groupId = pBlock->info.groupId;

  if (pProjectInfo->curOffset >= pRes->info.rows) {
    pProjectInfo->curOffset -= pRes->info.rows;
    blockDataCleanup(pRes);
    return PROJECT_RETRIEVE_CONTINUE;
  } else if (pProjectInfo->curOffset < pRes->info.rows && pProjectInfo->curOffset > 0) {
    blockDataTrimFirstNRows(pRes, pProjectInfo->curOffset);
    pProjectInfo->curOffset = 0;
  }

3665 3666 3667
  // check for the limitation in each group
  if (pProjectInfo->limit.limit > 0 && pProjectInfo->curOutput + pRes->info.rows >= pProjectInfo->limit.limit) {
    pRes->info.rows = (int32_t)(pProjectInfo->limit.limit - pProjectInfo->curOutput);
3668 3669 3670 3671 3672

    if (pProjectInfo->slimit.limit == -1 || pProjectInfo->slimit.limit <= pProjectInfo->curGroupOutput) {
      pOperator->status = OP_EXEC_DONE;
    }

3673
    return PROJECT_RETRIEVE_DONE;
3674
  }
3675

3676
  // todo optimize performance
3677 3678
  // If there are slimit/soffset value exists, multi-round result can not be packed into one group, since the
  // they may not belong to the same group the limit/offset value is not valid in this case.
L
Liu Jicong 已提交
3679 3680
  if (pRes->info.rows >= pOperator->resultInfo.threshold || pProjectInfo->slimit.offset != -1 ||
      pProjectInfo->slimit.limit != -1) {
3681
    return PROJECT_RETRIEVE_DONE;
L
Liu Jicong 已提交
3682
  } else {  // not full enough, continue to accumulate the output data in the buffer.
3683 3684 3685 3686
    return PROJECT_RETRIEVE_CONTINUE;
  }
}

3687
static SSDataBlock* doProjectOperation(SOperatorInfo* pOperator) {
3688
  SProjectOperatorInfo* pProjectInfo = pOperator->info;
L
Liu Jicong 已提交
3689
  SOptrBasicInfo*       pInfo = &pProjectInfo->binfo;
3690 3691

  SSDataBlock* pRes = pInfo->pRes;
3692
  blockDataCleanup(pRes);
3693

3694
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
3695 3696 3697
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }
dengyihao's avatar
dengyihao 已提交
3698

H
Haojun Liao 已提交
3699
#if 0
3700 3701 3702 3703 3704
  if (pProjectInfo->existDataBlock) {  // TODO refactor
    SSDataBlock* pBlock = pProjectInfo->existDataBlock;
    pProjectInfo->existDataBlock = NULL;

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

H
Haojun Liao 已提交
3707
    blockDataEnsureCapacity(pInfo->pRes, pBlock->info.rows);
3708
    projectApplyFunctions(pOperator->pExpr, pInfo->pRes, pBlock, pInfo->pCtx, pOperator->numOfExprs);
L
Liu Jicong 已提交
3709
    if (pRes->info.rows >= pProjectInfo->binfo.capacity * 0.8) {
3710 3711
      copyTsColoum(pRes, pInfo->pCtx, pOperator->numOfExprs);
      resetResultRowEntryResult(pInfo->pCtx, pOperator->numOfExprs);
3712 3713 3714
      return pRes;
    }
  }
H
Haojun Liao 已提交
3715
#endif
3716

3717
  int64_t st = 0;
3718 3719 3720
  int32_t order = 0;
  int32_t scanFlag = 0;

3721 3722 3723 3724
  if (pOperator->cost.openCost == 0) {
    st = taosGetTimestampUs();
  }

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

L
Liu Jicong 已提交
3727
  while (1) {
H
Haojun Liao 已提交
3728
    // The downstream exec may change the value of the newgroup, so use a local variable instead.
3729
    SSDataBlock* pBlock = downstream->fpSet.getNextFn(downstream);
3730
    if (pBlock == NULL) {
3731
      doSetOperatorCompleted(pOperator);
3732 3733 3734
      break;
    }

3735
#if 0
3736
    // Return result of the previous group in the firstly.
3737
    if (false) {
3738 3739 3740
      if (pRes->info.rows > 0) {
        pProjectInfo->existDataBlock = pBlock;
        break;
L
Liu Jicong 已提交
3741
      } else {  // init output buffer for a new group data
3742
        initCtxOutputBuffer(pInfo->pCtx, pOperator->numOfExprs);
3743 3744
      }
    }
3745
#endif
3746 3747

    // the pDataBlock are always the same one, no need to call this again
3748
    int32_t code = getTableScanInfo(pOperator->pDownstream[0], &order, &scanFlag);
3749 3750 3751
    if (code != TSDB_CODE_SUCCESS) {
      longjmp(pTaskInfo->env, code);
    }
3752

3753
    setInputDataBlock(pOperator, pInfo->pCtx, pBlock, order, scanFlag, false);
3754 3755
    blockDataEnsureCapacity(pInfo->pRes, pInfo->pRes->info.rows + pBlock->info.rows);

X
Xiaoyu Wang 已提交
3756 3757
    code = projectApplyFunctions(pOperator->pExpr, pInfo->pRes, pBlock, pInfo->pCtx, pOperator->numOfExprs,
                                 pProjectInfo->pPseudoColInfo);
3758 3759
    if (code != TSDB_CODE_SUCCESS) {
      longjmp(pTaskInfo->env, code);
3760 3761
    }

3762 3763
    int32_t status = handleLimitOffset(pOperator, pBlock);
    if (status == PROJECT_RETRIEVE_CONTINUE) {
H
Haojun Liao 已提交
3764
      continue;
L
Liu Jicong 已提交
3765
    } else if (status == PROJECT_RETRIEVE_DONE) {
3766 3767 3768
      break;
    }
  }
dengyihao's avatar
dengyihao 已提交
3769

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

3772 3773 3774 3775
  size_t rows = pInfo->pRes->info.rows;
  pOperator->resultInfo.totalRows += rows;

  if (pOperator->cost.openCost == 0) {
3776
    pOperator->cost.openCost = (taosGetTimestampUs() - st) / 1000.0;
3777 3778
  }

3779
  return (rows > 0) ? pInfo->pRes : NULL;
3780 3781
}

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

L
Liu Jicong 已提交
3786 3787
  int64_t ekey = Q_STATUS_EQUAL(pTaskInfo->status, TASK_COMPLETED) ? pTaskInfo->window.ekey
                                                                   : pInfo->existNewGroupBlock->info.window.ekey;
3788 3789
  taosResetFillInfo(pInfo->pFillInfo, getFillInfoStart(pInfo->pFillInfo));

3790
  taosFillSetStartInfo(pInfo->pFillInfo, pInfo->existNewGroupBlock->info.rows, ekey);
3791 3792
  taosFillSetInputDataBlock(pInfo->pFillInfo, pInfo->existNewGroupBlock);

3793
  doFillTimeIntervalGapsInResults(pInfo->pFillInfo, pInfo->pRes, pResultInfo->capacity);
3794 3795 3796 3797
  pInfo->existNewGroupBlock = NULL;
  *newgroup = true;
}

L
Liu Jicong 已提交
3798 3799
static void doHandleRemainBlockFromNewGroup(SFillOperatorInfo* pInfo, SResultInfo* pResultInfo, bool* newgroup,
                                            SExecTaskInfo* pTaskInfo) {
3800 3801
  if (taosFillHasMoreResults(pInfo->pFillInfo)) {
    *newgroup = false;
3802
    doFillTimeIntervalGapsInResults(pInfo->pFillInfo, pInfo->pRes, (int32_t)pResultInfo->capacity);
H
Haojun Liao 已提交
3803
    if (pInfo->pRes->info.rows > pResultInfo->threshold || (!pInfo->multigroupResult)) {
3804 3805 3806 3807 3808 3809
      return;
    }
  }

  // handle the cached new group data block
  if (pInfo->existNewGroupBlock) {
3810
    doHandleRemainBlockForNewGroupImpl(pInfo, pResultInfo, newgroup, pTaskInfo);
3811 3812 3813
  }
}

3814
static SSDataBlock* doFill(SOperatorInfo* pOperator) {
L
Liu Jicong 已提交
3815 3816
  SFillOperatorInfo* pInfo = pOperator->info;
  SExecTaskInfo*     pTaskInfo = pOperator->pTaskInfo;
3817

H
Haojun Liao 已提交
3818
  SResultInfo* pResultInfo = &pOperator->resultInfo;
3819 3820 3821
  SSDataBlock* pResBlock = pInfo->pRes;

  blockDataCleanup(pResBlock);
3822 3823 3824 3825
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

3826
  // todo handle different group data interpolation
X
Xiaoyu Wang 已提交
3827 3828
  bool  n = false;
  bool* newgroup = &n;
3829
  doHandleRemainBlockFromNewGroup(pInfo, pResultInfo, newgroup, pTaskInfo);
3830 3831
  if (pResBlock->info.rows > pResultInfo->threshold || (!pInfo->multigroupResult && pResBlock->info.rows > 0)) {
    return pResBlock;
H
Haojun Liao 已提交
3832
  }
3833

H
Haojun Liao 已提交
3834
  SOperatorInfo* pDownstream = pOperator->pDownstream[0];
L
Liu Jicong 已提交
3835
  while (1) {
3836
    SSDataBlock* pBlock = pDownstream->fpSet.getNextFn(pDownstream);
3837 3838 3839 3840 3841 3842 3843 3844 3845 3846
    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
3847
      taosFillSetStartInfo(pInfo->pFillInfo, 0, pTaskInfo->window.ekey);
3848 3849 3850 3851 3852 3853 3854
    } else {
      if (pBlock == NULL) {
        if (pInfo->totalInputRows == 0) {
          pOperator->status = OP_EXEC_DONE;
          return NULL;
        }

3855
        taosFillSetStartInfo(pInfo->pFillInfo, 0, pTaskInfo->window.ekey);
3856 3857 3858 3859 3860 3861 3862
      } else {
        pInfo->totalInputRows += pBlock->info.rows;
        taosFillSetStartInfo(pInfo->pFillInfo, pBlock->info.rows, pBlock->info.window.ekey);
        taosFillSetInputDataBlock(pInfo->pFillInfo, pBlock);
      }
    }

3863 3864
    blockDataEnsureCapacity(pResBlock, pOperator->resultInfo.capacity);
    doFillTimeIntervalGapsInResults(pInfo->pFillInfo, pResBlock, pOperator->resultInfo.capacity);
3865 3866

    // current group has no more result to return
3867
    if (pResBlock->info.rows > 0) {
3868 3869
      // 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
3870 3871
      if (pResBlock->info.rows > pResultInfo->threshold || pBlock == NULL || (!pInfo->multigroupResult)) {
        return pResBlock;
3872 3873
      }

3874
      doHandleRemainBlockFromNewGroup(pInfo, pResultInfo, newgroup, pTaskInfo);
3875 3876
      if (pResBlock->info.rows > pOperator->resultInfo.threshold || pBlock == NULL) {
        return pResBlock;
3877 3878 3879
      }
    } else if (pInfo->existNewGroupBlock) {  // try next group
      assert(pBlock != NULL);
3880
      doHandleRemainBlockForNewGroupImpl(pInfo, pResultInfo, newgroup, pTaskInfo);
3881 3882
      if (pResBlock->info.rows > pResultInfo->threshold) {
        return pResBlock;
3883 3884 3885 3886 3887 3888 3889 3890
      }
    } else {
      return NULL;
    }
  }
}

// todo set the attribute of query scan count
H
Haojun Liao 已提交
3891
static int32_t getNumOfScanTimes(STaskAttr* pQueryAttr) {
L
Liu Jicong 已提交
3892
  for (int32_t i = 0; i < pQueryAttr->numOfOutput; ++i) {
3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906
    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;
  }

3907
  if (pOperator->fpSet.closeFn != NULL) {
3908
    pOperator->fpSet.closeFn(pOperator->info, pOperator->numOfExprs);
3909 3910
  }

H
Haojun Liao 已提交
3911
  if (pOperator->pDownstream != NULL) {
L
Liu Jicong 已提交
3912
    for (int32_t i = 0; i < pOperator->numOfDownstream; ++i) {
H
Haojun Liao 已提交
3913
      destroyOperatorInfo(pOperator->pDownstream[i]);
3914 3915
    }

wafwerar's avatar
wafwerar 已提交
3916
    taosMemoryFreeClear(pOperator->pDownstream);
H
Haojun Liao 已提交
3917
    pOperator->numOfDownstream = 0;
3918 3919
  }

H
Haojun Liao 已提交
3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930
  if (pOperator->pExpr != NULL) {
    for (int32_t i = 0; i < pOperator->numOfExprs; ++i) {
      SExprInfo* pExprInfo = &pOperator->pExpr[i];
      if (pExprInfo->pExpr->nodeType == QUERY_NODE_COLUMN) {
        taosMemoryFree(pExprInfo->base.pParam[0].pCol);
      }
      taosMemoryFree(pExprInfo->base.pParam);
      taosMemoryFree(pExprInfo->pExpr);
    }
  }

D
fix bug  
dapan 已提交
3931
  taosMemoryFreeClear(pOperator->pExpr);
wafwerar's avatar
wafwerar 已提交
3932 3933
  taosMemoryFreeClear(pOperator->info);
  taosMemoryFreeClear(pOperator);
3934 3935
}

3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950
int32_t getBufferPgSize(int32_t rowSize, uint32_t* defaultPgsz, uint32_t* defaultBufsz) {
  *defaultPgsz = 4096;
  while (*defaultPgsz < rowSize * 4) {
    *defaultPgsz <<= 1u;
  }

  // at least four pages need to be in buffer
  *defaultBufsz = 4096 * 256;
  if ((*defaultBufsz) <= (*defaultPgsz)) {
    (*defaultBufsz) = (*defaultPgsz) * 4;
  }

  return 0;
}

dengyihao's avatar
dengyihao 已提交
3951 3952
int32_t doInitAggInfoSup(SAggSupporter* pAggSup, SqlFunctionCtx* pCtx, int32_t numOfOutput, size_t keyBufSize,
                         const char* pKey) {
3953 3954
  _hash_fn_t hashFn = taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY);

dengyihao's avatar
dengyihao 已提交
3955 3956
  pAggSup->resultRowSize = getResultRowSize(pCtx, numOfOutput);
  pAggSup->keyBuf = taosMemoryCalloc(1, keyBufSize + POINTER_BYTES + sizeof(int64_t));
3957 3958
  pAggSup->pResultRowHashTable = taosHashInit(10, hashFn, true, HASH_NO_LOCK);

H
Haojun Liao 已提交
3959
  if (pAggSup->keyBuf == NULL || pAggSup->pResultRowHashTable == NULL) {
3960 3961 3962
    return TSDB_CODE_OUT_OF_MEMORY;
  }

3963 3964 3965
  uint32_t defaultPgsz  = 0;
  uint32_t defaultBufsz = 0;
  getBufferPgSize(pAggSup->resultRowSize, &defaultPgsz, &defaultBufsz);
H
Haojun Liao 已提交
3966

3967
  int32_t  code = createDiskbasedBuf(&pAggSup->pResultBuf, defaultPgsz, defaultBufsz, pKey, TD_TMP_DIR_PATH);
H
Haojun Liao 已提交
3968 3969 3970 3971
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

3972 3973 3974
  return TSDB_CODE_SUCCESS;
}

3975
void cleanupAggSup(SAggSupporter* pAggSup) {
wafwerar's avatar
wafwerar 已提交
3976
  taosMemoryFreeClear(pAggSup->keyBuf);
3977
  taosHashCleanup(pAggSup->pResultRowHashTable);
H
Haojun Liao 已提交
3978
  destroyDiskbasedBuf(pAggSup->pResultBuf);
3979 3980
}

H
Haojun Liao 已提交
3981
int32_t initAggInfo(SOptrBasicInfo* pBasicInfo, SAggSupporter* pAggSup, SExprInfo* pExprInfo, int32_t numOfCols,
3982
                    SSDataBlock* pResultBlock, size_t keyBufSize, const char* pkey) {
3983
  pBasicInfo->pCtx = createSqlFunctionCtx(pExprInfo, numOfCols, &pBasicInfo->rowCellInfoOffset);
H
Haojun Liao 已提交
3984 3985
  pBasicInfo->pRes = pResultBlock;

3986
  doInitAggInfoSup(pAggSup, pBasicInfo->pCtx, numOfCols, keyBufSize, pkey);
3987

L
Liu Jicong 已提交
3988
  for (int32_t i = 0; i < numOfCols; ++i) {
3989 3990 3991
    pBasicInfo->pCtx[i].pBuf = pAggSup->pResultBuf;
  }

3992
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
3993 3994
}

3995 3996 3997 3998 3999 4000 4001 4002 4003
void initResultSizeInfo(SOperatorInfo* pOperator, int32_t numOfRows) {
  pOperator->resultInfo.capacity = numOfRows;
  pOperator->resultInfo.threshold = numOfRows * 0.75;

  if (pOperator->resultInfo.threshold == 0) {
    pOperator->resultInfo.capacity = numOfRows;
  }
}

wmmhello's avatar
wmmhello 已提交
4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023
//static STableQueryInfo* initTableQueryInfo(const STableListInfo* pTableListInfo) {
//  int32_t size = taosArrayGetSize(pTableListInfo->pTableList);
//  if (size == 0) {
//    return NULL;
//  }
//
//  STableQueryInfo* pTableQueryInfo = taosMemoryCalloc(size, sizeof(STableQueryInfo));
//  if (pTableQueryInfo == NULL) {
//    return NULL;
//  }
//
//  for (int32_t j = 0; j < size; ++j) {
//    STableKeyInfo*   pk = taosArrayGet(pTableListInfo->pTableList, j);
//    STableQueryInfo* pTQueryInfo = &pTableQueryInfo[j];
//    pTQueryInfo->lastKey = pk->lastKey;
//  }
//
//  pTableQueryInfo->lastKey = 0;
//  return pTableQueryInfo;
//}
H
Haojun Liao 已提交
4024

L
Liu Jicong 已提交
4025
SOperatorInfo* createAggregateOperatorInfo(SOperatorInfo* downstream, SExprInfo* pExprInfo, int32_t numOfCols,
4026
                                           SSDataBlock* pResultBlock, SExprInfo* pScalarExprInfo,
wmmhello's avatar
wmmhello 已提交
4027
                                           int32_t numOfScalarExpr, SExecTaskInfo* pTaskInfo) {
wafwerar's avatar
wafwerar 已提交
4028
  SAggOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SAggOperatorInfo));
L
Liu Jicong 已提交
4029
  SOperatorInfo*    pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
4030 4031 4032
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }
H
Haojun Liao 已提交
4033

4034
  int32_t numOfRows = 1024;
dengyihao's avatar
dengyihao 已提交
4035
  size_t  keyBufSize = sizeof(int64_t) + sizeof(int64_t) + POINTER_BYTES;
4036 4037

  initResultSizeInfo(pOperator, numOfRows);
dengyihao's avatar
dengyihao 已提交
4038 4039
  int32_t code =
      initAggInfo(&pInfo->binfo, &pInfo->aggSup, pExprInfo, numOfCols, pResultBlock, keyBufSize, pTaskInfo->id.str);
L
Liu Jicong 已提交
4040
  if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
4041 4042
    goto _error;
  }
H
Haojun Liao 已提交
4043

H
Haojun Liao 已提交
4044 4045 4046 4047
  int32_t numOfGroup = 10;  // todo replaced with true value
  pInfo->groupId = INT32_MIN;
  initResultRowInfo(&pInfo->binfo.resultRowInfo, numOfGroup);

4048 4049
  pInfo->pScalarExprInfo = pScalarExprInfo;
  pInfo->numOfScalarExpr = numOfScalarExpr;
4050
  if (pInfo->pScalarExprInfo != NULL) {
4051
    pInfo->pScalarCtx = createSqlFunctionCtx(pScalarExprInfo, numOfScalarExpr, &pInfo->rowCellInfoOffset);
4052
  }
4053

dengyihao's avatar
dengyihao 已提交
4054
  pOperator->name = "TableAggregate";
X
Xiaoyu Wang 已提交
4055
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_AGG;
4056
  pOperator->blocking = true;
dengyihao's avatar
dengyihao 已提交
4057 4058 4059
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
  pOperator->pExpr = pExprInfo;
4060
  pOperator->numOfExprs = numOfCols;
dengyihao's avatar
dengyihao 已提交
4061
  pOperator->pTaskInfo = pTaskInfo;
H
Haojun Liao 已提交
4062

4063 4064
  pOperator->fpSet = createOperatorFpSet(doOpenAggregateOptr, getAggregateResult, NULL, NULL, destroyAggOperatorInfo,
                                         aggEncodeResultRow, aggDecodeResultRow, NULL);
H
Haojun Liao 已提交
4065 4066 4067 4068 4069

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

  return pOperator;
L
Liu Jicong 已提交
4072
_error:
H
Haojun Liao 已提交
4073
  destroyAggOperatorInfo(pInfo, numOfCols);
wafwerar's avatar
wafwerar 已提交
4074 4075
  taosMemoryFreeClear(pInfo);
  taosMemoryFreeClear(pOperator);
H
Haojun Liao 已提交
4076 4077
  pTaskInfo->code = TSDB_CODE_OUT_OF_MEMORY;
  return NULL;
4078 4079
}

H
Haojun Liao 已提交
4080
void doDestroyBasicInfo(SOptrBasicInfo* pInfo, int32_t numOfOutput) {
4081 4082
  assert(pInfo != NULL);

4083
  destroySqlFunctionCtx(pInfo->pCtx, numOfOutput);
wafwerar's avatar
wafwerar 已提交
4084
  taosMemoryFreeClear(pInfo->rowCellInfoOffset);
4085 4086

  cleanupResultRowInfo(&pInfo->resultRowInfo);
H
Haojun Liao 已提交
4087
  pInfo->pRes = blockDataDestroy(pInfo->pRes);
4088 4089
}

H
Haojun Liao 已提交
4090
void destroyBasicOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
4091
  SOptrBasicInfo* pInfo = (SOptrBasicInfo*)param;
4092 4093
  doDestroyBasicInfo(pInfo, numOfOutput);
}
H
Haojun Liao 已提交
4094 4095

void destroyAggOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
4096
  SAggOperatorInfo* pInfo = (SAggOperatorInfo*)param;
4097 4098
  doDestroyBasicInfo(&pInfo->binfo, numOfOutput);
}
4099

H
Haojun Liao 已提交
4100
void destroySFillOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
4101
  SFillOperatorInfo* pInfo = (SFillOperatorInfo*)param;
4102
  pInfo->pFillInfo = taosDestroyFillInfo(pInfo->pFillInfo);
H
Haojun Liao 已提交
4103
  pInfo->pRes = blockDataDestroy(pInfo->pRes);
wafwerar's avatar
wafwerar 已提交
4104
  taosMemoryFreeClear(pInfo->p);
4105 4106
}

H
Haojun Liao 已提交
4107
static void destroyProjectOperatorInfo(void* param, int32_t numOfOutput) {
D
fix bug  
dapan 已提交
4108 4109 4110
  if (NULL == param) {
    return;
  }
L
Liu Jicong 已提交
4111
  SProjectOperatorInfo* pInfo = (SProjectOperatorInfo*)param;
4112
  doDestroyBasicInfo(&pInfo->binfo, numOfOutput);
H
Haojun Liao 已提交
4113
  cleanupAggSup(&pInfo->aggSup);
H
Haojun Liao 已提交
4114
  taosArrayDestroy(pInfo->pPseudoColInfo);
4115 4116
}

H
Haojun Liao 已提交
4117
void destroyExchangeOperatorInfo(void* param, int32_t numOfOutput) {
L
Liu Jicong 已提交
4118
  SExchangeInfo* pExInfo = (SExchangeInfo*)param;
H
Haojun Liao 已提交
4119 4120 4121 4122 4123 4124 4125 4126 4127
  taosArrayDestroy(pExInfo->pSources);
  taosArrayDestroy(pExInfo->pSourceDataInfo);
  if (pExInfo->pResult != NULL) {
    blockDataDestroy(pExInfo->pResult);
  }

  tsem_destroy(&pExInfo->ready);
}

H
Haojun Liao 已提交
4128 4129
static SArray* setRowTsColumnOutputInfo(SqlFunctionCtx* pCtx, int32_t numOfCols) {
  SArray* pList = taosArrayInit(4, sizeof(int32_t));
dengyihao's avatar
dengyihao 已提交
4130
  for (int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
4131 4132 4133 4134 4135 4136 4137 4138
    if (fmIsPseudoColumnFunc(pCtx[i].functionId)) {
      taosArrayPush(pList, &i);
    }
  }

  return pList;
}

L
Liu Jicong 已提交
4139
SOperatorInfo* createProjectOperatorInfo(SOperatorInfo* downstream, SExprInfo* pExprInfo, int32_t num,
dengyihao's avatar
dengyihao 已提交
4140 4141
                                         SSDataBlock* pResBlock, SLimit* pLimit, SLimit* pSlimit,
                                         SExecTaskInfo* pTaskInfo) {
wafwerar's avatar
wafwerar 已提交
4142
  SProjectOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SProjectOperatorInfo));
L
Liu Jicong 已提交
4143
  SOperatorInfo*        pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
4144 4145 4146
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }
4147

X
Xiaoyu Wang 已提交
4148 4149 4150
  pInfo->limit = *pLimit;
  pInfo->slimit = *pSlimit;
  pInfo->curOffset = pLimit->offset;
H
Haojun Liao 已提交
4151 4152
  pInfo->curSOffset = pSlimit->offset;

H
Haojun Liao 已提交
4153
  pInfo->binfo.pRes = pResBlock;
H
Haojun Liao 已提交
4154 4155 4156

  int32_t numOfCols = num;
  int32_t numOfRows = 4096;
dengyihao's avatar
dengyihao 已提交
4157
  size_t  keyBufSize = sizeof(int64_t) + sizeof(int64_t) + POINTER_BYTES;
4158

4159 4160 4161 4162 4163
  // Make sure the size of SSDataBlock will never exceed the size of 2MB.
  int32_t TWOMB = 2 * 1024 * 1024;
  if (numOfRows * pResBlock->info.rowSize > TWOMB) {
    numOfRows = TWOMB / pResBlock->info.rowSize;
  }
4164
  initResultSizeInfo(pOperator, numOfRows);
4165

4166
  initAggInfo(&pInfo->binfo, &pInfo->aggSup, pExprInfo, numOfCols, pResBlock, keyBufSize, pTaskInfo->id.str);
H
Haojun Liao 已提交
4167
  setFunctionResultOutput(&pInfo->binfo, &pInfo->aggSup, MAIN_SCAN, numOfCols, pTaskInfo);
4168

X
Xiaoyu Wang 已提交
4169 4170
  pInfo->pPseudoColInfo = setRowTsColumnOutputInfo(pInfo->binfo.pCtx, numOfCols);
  pOperator->name = "ProjectOperator";
H
Haojun Liao 已提交
4171
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_PROJECT;
X
Xiaoyu Wang 已提交
4172 4173 4174 4175 4176 4177
  pOperator->blocking = false;
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
  pOperator->pExpr = pExprInfo;
  pOperator->numOfExprs = num;
  pOperator->pTaskInfo = pTaskInfo;
4178

L
Liu Jicong 已提交
4179 4180
  pOperator->fpSet = createOperatorFpSet(operatorDummyOpenFn, doProjectOperation, NULL, NULL,
                                         destroyProjectOperatorInfo, NULL, NULL, NULL);
L
Liu Jicong 已提交
4181

4182
  int32_t code = appendDownstream(pOperator, &downstream, 1);
H
Haojun Liao 已提交
4183
  if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
4184 4185
    goto _error;
  }
4186 4187

  return pOperator;
H
Haojun Liao 已提交
4188

L
Liu Jicong 已提交
4189
_error:
H
Haojun Liao 已提交
4190 4191
  pTaskInfo->code = TSDB_CODE_OUT_OF_MEMORY;
  return NULL;
4192 4193
}

4194
static int32_t initFillInfo(SFillOperatorInfo* pInfo, SExprInfo* pExpr, int32_t numOfCols, SNodeListNode* pValNode,
L
Liu Jicong 已提交
4195
                            STimeWindow win, int32_t capacity, const char* id, SInterval* pInterval, int32_t fillType) {
4196
  SFillColInfo* pColInfo = createFillColInfo(pExpr, numOfCols, pValNode);
H
Haojun Liao 已提交
4197 4198

  STimeWindow w = TSWINDOW_INITIALIZER;
4199
  getAlignQueryTimeWindow(pInterval, pInterval->precision, win.skey, &w);
H
Haojun Liao 已提交
4200 4201

  int32_t order = TSDB_ORDER_ASC;
4202
  pInfo->pFillInfo = taosCreateFillInfo(order, w.skey, 0, capacity, numOfCols, pInterval, fillType, pColInfo, id);
H
Haojun Liao 已提交
4203

wafwerar's avatar
wafwerar 已提交
4204
  pInfo->p = taosMemoryCalloc(numOfCols, POINTER_BYTES);
H
Haojun Liao 已提交
4205 4206 4207 4208 4209 4210 4211
  if (pInfo->pFillInfo == NULL || pInfo->p == NULL) {
    return TSDB_CODE_OUT_OF_MEMORY;
  } else {
    return TSDB_CODE_SUCCESS;
  }
}

L
Liu Jicong 已提交
4212
SOperatorInfo* createFillOperatorInfo(SOperatorInfo* downstream, SExprInfo* pExpr, int32_t numOfCols,
X
Xiaoyu Wang 已提交
4213 4214 4215
                                      SInterval* pInterval, STimeWindow* pWindow, SSDataBlock* pResBlock,
                                      int32_t fillType, SNodeListNode* pValueNode, bool multigroupResult,
                                      SExecTaskInfo* pTaskInfo) {
wafwerar's avatar
wafwerar 已提交
4216
  SFillOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SFillOperatorInfo));
L
Liu Jicong 已提交
4217
  SOperatorInfo*     pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
4218

L
Liu Jicong 已提交
4219
  pInfo->pRes = pResBlock;
4220 4221
  pInfo->multigroupResult = multigroupResult;

4222 4223
  int32_t type = TSDB_FILL_NONE;
  switch (fillType) {
dengyihao's avatar
dengyihao 已提交
4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241
    case FILL_MODE_PREV:
      type = TSDB_FILL_PREV;
      break;
    case FILL_MODE_NONE:
      type = TSDB_FILL_NONE;
      break;
    case FILL_MODE_NULL:
      type = TSDB_FILL_NULL;
      break;
    case FILL_MODE_NEXT:
      type = TSDB_FILL_NEXT;
      break;
    case FILL_MODE_VALUE:
      type = TSDB_FILL_SET_VALUE;
      break;
    case FILL_MODE_LINEAR:
      type = TSDB_FILL_LINEAR;
      break;
4242 4243 4244 4245
    default:
      type = TSDB_FILL_NONE;
  }

H
Haojun Liao 已提交
4246
  SResultInfo* pResultInfo = &pOperator->resultInfo;
4247 4248
  initResultSizeInfo(pOperator, 4096);

X
Xiaoyu Wang 已提交
4249 4250
  int32_t code = initFillInfo(pInfo, pExpr, numOfCols, pValueNode, *pWindow, pResultInfo->capacity, pTaskInfo->id.str,
                              pInterval, type);
4251 4252 4253
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
4254

dengyihao's avatar
dengyihao 已提交
4255
  pOperator->name = "FillOperator";
4256
  pOperator->blocking = false;
dengyihao's avatar
dengyihao 已提交
4257
  pOperator->status = OP_NOT_OPENED;
4258
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_FILL;
dengyihao's avatar
dengyihao 已提交
4259
  pOperator->pExpr = pExpr;
4260
  pOperator->numOfExprs = numOfCols;
dengyihao's avatar
dengyihao 已提交
4261
  pOperator->info = pInfo;
H
Haojun Liao 已提交
4262

L
Liu Jicong 已提交
4263 4264
  pOperator->fpSet =
      createOperatorFpSet(operatorDummyOpenFn, doFill, NULL, NULL, destroySFillOperatorInfo, NULL, NULL, NULL);
4265
  pOperator->pTaskInfo = pTaskInfo;
4266
  code = appendDownstream(pOperator, &downstream, 1);
4267
  return pOperator;
H
Haojun Liao 已提交
4268

L
Liu Jicong 已提交
4269
_error:
wafwerar's avatar
wafwerar 已提交
4270 4271
  taosMemoryFreeClear(pOperator);
  taosMemoryFreeClear(pInfo);
H
Haojun Liao 已提交
4272
  return NULL;
4273 4274
}

L
Liu Jicong 已提交
4275 4276
static SResSchema createResSchema(int32_t type, int32_t bytes, int32_t slotId, int32_t scale, int32_t precision,
                                  const char* name) {
H
Haojun Liao 已提交
4277
  SResSchema s = {0};
dengyihao's avatar
dengyihao 已提交
4278 4279 4280 4281
  s.scale = scale;
  s.type = type;
  s.bytes = bytes;
  s.slotId = slotId;
H
Haojun Liao 已提交
4282
  s.precision = precision;
H
Haojun Liao 已提交
4283 4284 4285 4286
  strncpy(s.name, name, tListLen(s.name));

  return s;
}
H
Haojun Liao 已提交
4287

4288
static SColumn* createColumn(int32_t blockId, int32_t slotId, int32_t colId, SDataType* pType) {
H
Haojun Liao 已提交
4289 4290 4291 4292 4293 4294
  SColumn* pCol = taosMemoryCalloc(1, sizeof(SColumn));
  if (pCol == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

dengyihao's avatar
dengyihao 已提交
4295
  pCol->slotId = slotId;
X
Xiaoyu Wang 已提交
4296 4297 4298 4299
  pCol->colId = colId;
  pCol->bytes = pType->bytes;
  pCol->type = pType->type;
  pCol->scale = pType->scale;
dengyihao's avatar
dengyihao 已提交
4300
  pCol->precision = pType->precision;
H
Haojun Liao 已提交
4301 4302 4303 4304 4305
  pCol->dataBlockId = blockId;

  return pCol;
}

H
Haojun Liao 已提交
4306
SExprInfo* createExprInfo(SNodeList* pNodeList, SNodeList* pGroupKeys, int32_t* numOfExprs) {
H
Haojun Liao 已提交
4307
  int32_t numOfFuncs = LIST_LENGTH(pNodeList);
H
Haojun Liao 已提交
4308 4309 4310 4311
  int32_t numOfGroupKeys = 0;
  if (pGroupKeys != NULL) {
    numOfGroupKeys = LIST_LENGTH(pGroupKeys);
  }
H
Haojun Liao 已提交
4312

H
Haojun Liao 已提交
4313
  *numOfExprs = numOfFuncs + numOfGroupKeys;
wafwerar's avatar
wafwerar 已提交
4314
  SExprInfo* pExprs = taosMemoryCalloc(*numOfExprs, sizeof(SExprInfo));
H
Haojun Liao 已提交
4315

L
Liu Jicong 已提交
4316
  for (int32_t i = 0; i < (*numOfExprs); ++i) {
H
Haojun Liao 已提交
4317 4318 4319 4320 4321 4322
    STargetNode* pTargetNode = NULL;
    if (i < numOfFuncs) {
      pTargetNode = (STargetNode*)nodesListGetNode(pNodeList, i);
    } else {
      pTargetNode = (STargetNode*)nodesListGetNode(pGroupKeys, i - numOfFuncs);
    }
H
Haojun Liao 已提交
4323

4324
    SExprInfo* pExp = &pExprs[i];
H
Haojun Liao 已提交
4325

wafwerar's avatar
wafwerar 已提交
4326
    pExp->pExpr = taosMemoryCalloc(1, sizeof(tExprNode));
H
Haojun Liao 已提交
4327
    pExp->pExpr->_function.num = 1;
H
Haojun Liao 已提交
4328
    pExp->pExpr->_function.functionId = -1;
H
Haojun Liao 已提交
4329

4330
    int32_t type = nodeType(pTargetNode->pExpr);
H
Haojun Liao 已提交
4331
    // it is a project query, or group by column
4332
    if (type == QUERY_NODE_COLUMN) {
H
Haojun Liao 已提交
4333
      pExp->pExpr->nodeType = QUERY_NODE_COLUMN;
L
Liu Jicong 已提交
4334
      SColumnNode* pColNode = (SColumnNode*)pTargetNode->pExpr;
H
Haojun Liao 已提交
4335

G
Ganlin Zhao 已提交
4336 4337 4338
      pExp->base.pParam = taosMemoryCalloc(1, sizeof(SFunctParam));
      pExp->base.numOfParams = 1;

H
Haojun Liao 已提交
4339
      SDataType* pType = &pColNode->node.resType;
dengyihao's avatar
dengyihao 已提交
4340 4341
      pExp->base.resSchema = createResSchema(pType->type, pType->bytes, pTargetNode->slotId, pType->scale,
                                             pType->precision, pColNode->colName);
4342
      pExp->base.pParam[0].pCol = createColumn(pColNode->dataBlockId, pColNode->slotId, pColNode->colId, pType);
H
Haojun Liao 已提交
4343
      pExp->base.pParam[0].type = FUNC_PARAM_TYPE_COLUMN;
4344
    } else if (type == QUERY_NODE_VALUE) {
4345 4346 4347 4348 4349 4350 4351
      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;
dengyihao's avatar
dengyihao 已提交
4352 4353
      pExp->base.resSchema = createResSchema(pType->type, pType->bytes, pTargetNode->slotId, pType->scale,
                                             pType->precision, pValNode->node.aliasName);
4354 4355
      pExp->base.pParam[0].type = FUNC_PARAM_TYPE_VALUE;
      valueNodeToVariant(pValNode, &pExp->base.pParam[0].param);
4356
    } else if (type == QUERY_NODE_FUNCTION) {
H
Haojun Liao 已提交
4357
      pExp->pExpr->nodeType = QUERY_NODE_FUNCTION;
H
Haojun Liao 已提交
4358 4359 4360
      SFunctionNode* pFuncNode = (SFunctionNode*)pTargetNode->pExpr;

      SDataType* pType = &pFuncNode->node.resType;
dengyihao's avatar
dengyihao 已提交
4361 4362
      pExp->base.resSchema = createResSchema(pType->type, pType->bytes, pTargetNode->slotId, pType->scale,
                                             pType->precision, pFuncNode->node.aliasName);
H
Haojun Liao 已提交
4363

H
Haojun Liao 已提交
4364
      pExp->pExpr->_function.functionId = pFuncNode->funcId;
H
Haojun Liao 已提交
4365
      pExp->pExpr->_function.pFunctNode = pFuncNode;
4366

dengyihao's avatar
dengyihao 已提交
4367 4368
      strncpy(pExp->pExpr->_function.functionName, pFuncNode->functionName,
              tListLen(pExp->pExpr->_function.functionName));
4369 4370 4371 4372 4373
#if 1
      // todo refactor: add the parameter for tbname function
      if (strcmp(pExp->pExpr->_function.functionName, "tbname") == 0) {
        pFuncNode->pParameterList = nodesMakeList();
        ASSERT(LIST_LENGTH(pFuncNode->pParameterList) == 0);
X
Xiaoyu Wang 已提交
4374 4375
        SValueNode* res = (SValueNode*)nodesMakeNode(QUERY_NODE_VALUE);
        if (NULL == res) {  // todo handle error
4376
        } else {
X
Xiaoyu Wang 已提交
4377
          res->node.resType = (SDataType){.bytes = sizeof(int64_t), .type = TSDB_DATA_TYPE_BIGINT};
4378 4379 4380 4381
          nodesListAppend(pFuncNode->pParameterList, res);
        }
      }
#endif
H
Haojun Liao 已提交
4382 4383

      int32_t numOfParam = LIST_LENGTH(pFuncNode->pParameterList);
G
Ganlin Zhao 已提交
4384 4385 4386 4387

      pExp->base.pParam = taosMemoryCalloc(numOfParam, sizeof(SFunctParam));
      pExp->base.numOfParams = numOfParam;

H
Haojun Liao 已提交
4388
      for (int32_t j = 0; j < numOfParam; ++j) {
4389
        SNode* p1 = nodesListGetNode(pFuncNode->pParameterList, j);
G
Ganlin Zhao 已提交
4390
        if (p1->type == QUERY_NODE_COLUMN) {
dengyihao's avatar
dengyihao 已提交
4391
          SColumnNode* pcn = (SColumnNode*)p1;
G
Ganlin Zhao 已提交
4392 4393

          pExp->base.pParam[j].type = FUNC_PARAM_TYPE_COLUMN;
4394
          pExp->base.pParam[j].pCol = createColumn(pcn->dataBlockId, pcn->slotId, pcn->colId, &pcn->node.resType);
G
Ganlin Zhao 已提交
4395 4396 4397
        } else if (p1->type == QUERY_NODE_VALUE) {
          SValueNode* pvn = (SValueNode*)p1;
          pExp->base.pParam[j].type = FUNC_PARAM_TYPE_VALUE;
4398
          valueNodeToVariant(pvn, &pExp->base.pParam[j].param);
G
Ganlin Zhao 已提交
4399
        }
H
Haojun Liao 已提交
4400
      }
4401
    } else if (type == QUERY_NODE_OPERATOR) {
H
Haojun Liao 已提交
4402
      pExp->pExpr->nodeType = QUERY_NODE_OPERATOR;
L
Liu Jicong 已提交
4403
      SOperatorNode* pNode = (SOperatorNode*)pTargetNode->pExpr;
4404

G
Ganlin Zhao 已提交
4405 4406 4407
      pExp->base.pParam = taosMemoryCalloc(1, sizeof(SFunctParam));
      pExp->base.numOfParams = 1;

4408
      SDataType* pType = &pNode->node.resType;
dengyihao's avatar
dengyihao 已提交
4409 4410
      pExp->base.resSchema = createResSchema(pType->type, pType->bytes, pTargetNode->slotId, pType->scale,
                                             pType->precision, pNode->node.aliasName);
4411 4412 4413
      pExp->pExpr->_optrRoot.pRootNode = pTargetNode->pExpr;
    } else {
      ASSERT(0);
H
Haojun Liao 已提交
4414 4415 4416
    }
  }

H
Haojun Liao 已提交
4417
  return pExprs;
H
Haojun Liao 已提交
4418 4419
}

D
dapan1121 已提交
4420
static SExecTaskInfo* createExecTaskInfo(uint64_t queryId, uint64_t taskId, EOPTR_EXEC_MODEL model, char* dbFName) {
wafwerar's avatar
wafwerar 已提交
4421
  SExecTaskInfo* pTaskInfo = taosMemoryCalloc(1, sizeof(SExecTaskInfo));
4422
  setTaskStatus(pTaskInfo, TASK_NOT_COMPLETED);
H
Haojun Liao 已提交
4423

D
dapan1121 已提交
4424
  pTaskInfo->schemaVer.dbname = strdup(dbFName);
4425
  pTaskInfo->cost.created = taosGetTimestampMs();
H
Haojun Liao 已提交
4426
  pTaskInfo->id.queryId = queryId;
dengyihao's avatar
dengyihao 已提交
4427
  pTaskInfo->execModel = model;
H
Haojun Liao 已提交
4428

wafwerar's avatar
wafwerar 已提交
4429
  char* p = taosMemoryCalloc(1, 128);
L
Liu Jicong 已提交
4430
  snprintf(p, 128, "TID:0x%" PRIx64 " QID:0x%" PRIx64, taskId, queryId);
H
Haojun Liao 已提交
4431
  pTaskInfo->id.str = p;
H
Haojun Liao 已提交
4432

4433 4434
  return pTaskInfo;
}
H
Haojun Liao 已提交
4435

L
Liu Jicong 已提交
4436
static tsdbReaderT doCreateDataReader(STableScanPhysiNode* pTableScanNode, SReadHandle* pHandle,
wmmhello's avatar
wmmhello 已提交
4437
                                      STableListInfo* pTableGroupInfo, uint64_t queryId, uint64_t taskId, SNode* pTagCond);
H
Haojun Liao 已提交
4438

wmmhello's avatar
wmmhello 已提交
4439 4440
static int32_t getTableList(void* metaHandle, int32_t tableType, uint64_t tableUid, STableListInfo* pListInfo, SNode* pTagCond);
static SArray* extractTableIdList(const STableListInfo* pTableGroupInfo);
H
Haojun Liao 已提交
4441
static SArray* extractColumnInfo(SNodeList* pNodeList);
4442

4443
static SArray* createSortInfo(SNodeList* pNodeList);
4444
static SArray* extractPartitionColInfo(SNodeList* pNodeList);
4445

X
Xiaoyu Wang 已提交
4446
void extractTableSchemaVersion(SReadHandle* pHandle, uint64_t uid, SExecTaskInfo* pTaskInfo) {
4447 4448 4449 4450 4451 4452 4453
  SMetaReader mr = {0};
  metaReaderInit(&mr, pHandle->meta, 0);
  metaGetTableEntryByUid(&mr, uid);

  pTaskInfo->schemaVer.tablename = strdup(mr.me.name);

  if (mr.me.type == TSDB_SUPER_TABLE) {
4454 4455
    pTaskInfo->schemaVer.sversion = mr.me.stbEntry.schemaRow.version;
    pTaskInfo->schemaVer.tversion = mr.me.stbEntry.schemaTag.version;
4456 4457 4458
  } else if (mr.me.type == TSDB_CHILD_TABLE) {
    tb_uid_t suid = mr.me.ctbEntry.suid;
    metaGetTableEntryByUid(&mr, suid);
4459 4460
    pTaskInfo->schemaVer.sversion = mr.me.stbEntry.schemaRow.version;
    pTaskInfo->schemaVer.tversion = mr.me.stbEntry.schemaTag.version;
4461
  } else {
4462
    pTaskInfo->schemaVer.sversion = mr.me.ntbEntry.schemaRow.version;
4463
  }
4464 4465

  metaReaderClear(&mr);
4466 4467
}

H
Haojun Liao 已提交
4468
SOperatorInfo* createOperatorTree(SPhysiNode* pPhyNode, SExecTaskInfo* pTaskInfo, SReadHandle* pHandle,
wmmhello's avatar
wmmhello 已提交
4469
                                  uint64_t queryId, uint64_t taskId, STableListInfo* pTableListInfo, SNode* pTagCond) {
4470 4471
  int32_t type = nodeType(pPhyNode);

X
Xiaoyu Wang 已提交
4472
  if (pPhyNode->pChildren == NULL || LIST_LENGTH(pPhyNode->pChildren) == 0) {
H
Haojun Liao 已提交
4473
    if (QUERY_NODE_PHYSICAL_PLAN_TABLE_SCAN == type) {
dengyihao's avatar
dengyihao 已提交
4474
      STableScanPhysiNode* pTableScanNode = (STableScanPhysiNode*)pPhyNode;
H
Haojun Liao 已提交
4475

wmmhello's avatar
wmmhello 已提交
4476
      tsdbReaderT pDataReader = doCreateDataReader(pTableScanNode, pHandle, pTableListInfo, (uint64_t)queryId, taskId, pTagCond);
4477
      if (pDataReader == NULL && terrno != 0) {
4478 4479
        return NULL;
      }
4480

4481
      extractTableSchemaVersion(pHandle, pTableScanNode->scan.uid, pTaskInfo);
4482
      SOperatorInfo* pOperator = createTableScanOperatorInfo(pTableScanNode, pDataReader, pHandle, pTaskInfo);
4483

4484 4485
      STableScanInfo* pScanInfo = pOperator->info;
      pTaskInfo->cost.pRecoder = &pScanInfo->readRecorder;
4486

4487
      return pOperator;
H
Haojun Liao 已提交
4488
    } else if (QUERY_NODE_PHYSICAL_PLAN_EXCHANGE == type) {
H
Haojun Liao 已提交
4489
      SExchangePhysiNode* pExchange = (SExchangePhysiNode*)pPhyNode;
4490
      SSDataBlock*        pResBlock = createResDataBlock(pExchange->node.pOutputDataBlockDesc);
4491
      return createExchangeOperatorInfo(pHandle->pMsgCb->clientRpc, pExchange->pSrcEndPoints, pResBlock, pTaskInfo);
H
Haojun Liao 已提交
4492
    } else if (QUERY_NODE_PHYSICAL_PLAN_STREAM_SCAN == type) {
X
Xiaoyu Wang 已提交
4493
      SScanPhysiNode*      pScanPhyNode = (SScanPhysiNode*)pPhyNode;  // simple child table.
5
54liuyao 已提交
4494
      STableScanPhysiNode* pTableScanNode = (STableScanPhysiNode*)pPhyNode;
4495

5
54liuyao 已提交
4496 4497
      tsdbReaderT pDataReader = NULL;
      if (pHandle->vnode) {
wmmhello's avatar
wmmhello 已提交
4498
        pDataReader = doCreateDataReader(pTableScanNode, pHandle, pTableListInfo, (uint64_t)queryId, taskId, pTagCond);
wmmhello's avatar
wmmhello 已提交
4499 4500
      } else {
        getTableList(pHandle->meta, pScanPhyNode->tableType, pScanPhyNode->uid, pTableListInfo, pTagCond);
5
54liuyao 已提交
4501
      }
4502

5
54liuyao 已提交
4503
      if (pDataReader == NULL && terrno != 0) {
4504
        qDebug("%s pDataReader is NULL", GET_TASKID(pTaskInfo));
5
54liuyao 已提交
4505 4506
        // return NULL;
      } else {
4507
        qDebug("%s pDataReader is not NULL", GET_TASKID(pTaskInfo));
5
54liuyao 已提交
4508
      }
H
Haojun Liao 已提交
4509

wmmhello's avatar
wmmhello 已提交
4510
      SArray* tableIdList = extractTableIdList(pTableListInfo);
4511
      SOperatorInfo* pOperator = createStreamScanOperatorInfo(pDataReader, pHandle, tableIdList, pTableScanNode, pTaskInfo);
4512

4513
      taosArrayDestroy(tableIdList);
H
Haojun Liao 已提交
4514
      return pOperator;
H
Haojun Liao 已提交
4515
    } else if (QUERY_NODE_PHYSICAL_PLAN_SYSTABLE_SCAN == type) {
L
Liu Jicong 已提交
4516
      SSystemTableScanPhysiNode* pSysScanPhyNode = (SSystemTableScanPhysiNode*)pPhyNode;
L
Liu Jicong 已提交
4517
      SScanPhysiNode*            pScanNode = &pSysScanPhyNode->scan;
H
Haojun Liao 已提交
4518

4519 4520 4521
      SDataBlockDescNode* pDescNode = pScanNode->node.pOutputDataBlockDesc;

      SSDataBlock* pResBlock = createResDataBlock(pDescNode);
4522

4523
      int32_t numOfOutputCols = 0;
X
Xiaoyu Wang 已提交
4524 4525
      SArray* colList =
          extractColMatchInfo(pScanNode->pScanCols, pDescNode, &numOfOutputCols, pTaskInfo, COL_MATCH_FROM_COL_ID);
L
Liu Jicong 已提交
4526
      SOperatorInfo* pOperator = createSysTableScanOperatorInfo(
L
Liu Jicong 已提交
4527 4528
          pHandle, pResBlock, &pScanNode->tableName, pScanNode->node.pConditions, pSysScanPhyNode->mgmtEpSet, colList,
          pTaskInfo, pSysScanPhyNode->showRewrite, pSysScanPhyNode->accountId);
H
Haojun Liao 已提交
4529
      return pOperator;
4530
    } else if (QUERY_NODE_PHYSICAL_PLAN_TAG_SCAN == type) {
X
Xiaoyu Wang 已提交
4531
      STagScanPhysiNode* pScanPhyNode = (STagScanPhysiNode*)pPhyNode;
4532 4533 4534 4535

      SDataBlockDescNode* pDescNode = pScanPhyNode->node.pOutputDataBlockDesc;

      SSDataBlock* pResBlock = createResDataBlock(pDescNode);
4536

wmmhello's avatar
wmmhello 已提交
4537
      int32_t code = getTableList(pHandle->meta, pScanPhyNode->tableType, pScanPhyNode->uid, pTableListInfo, pTagCond);
4538 4539 4540 4541
      if (code != TSDB_CODE_SUCCESS) {
        return NULL;
      }

X
Xiaoyu Wang 已提交
4542
      int32_t    num = 0;
4543 4544 4545
      SExprInfo* pExprInfo = createExprInfo(pScanPhyNode->pScanPseudoCols, NULL, &num);

      int32_t numOfOutputCols = 0;
X
Xiaoyu Wang 已提交
4546 4547
      SArray* colList = extractColMatchInfo(pScanPhyNode->pScanPseudoCols, pDescNode, &numOfOutputCols, pTaskInfo,
                                            COL_MATCH_FROM_COL_ID);
4548

X
Xiaoyu Wang 已提交
4549
      SOperatorInfo* pOperator =
wmmhello's avatar
wmmhello 已提交
4550
          createTagScanOperatorInfo(pHandle, pExprInfo, num, pResBlock, colList, pTableListInfo, pTaskInfo);
4551
      return pOperator;
H
Haojun Liao 已提交
4552 4553
    } else {
      ASSERT(0);
H
Haojun Liao 已提交
4554 4555 4556
    }
  }

4557 4558
  int32_t num = 0;
  size_t  size = LIST_LENGTH(pPhyNode->pChildren);
H
Haojun Liao 已提交
4559

4560
  SOperatorInfo** ops = taosMemoryCalloc(size, POINTER_BYTES);
dengyihao's avatar
dengyihao 已提交
4561
  for (int32_t i = 0; i < size; ++i) {
4562
    SPhysiNode* pChildNode = (SPhysiNode*)nodesListGetNode(pPhyNode->pChildren, i);
wmmhello's avatar
wmmhello 已提交
4563
    ops[i] = createOperatorTree(pChildNode, pTaskInfo, pHandle, queryId, taskId, pTableListInfo, pTagCond);
4564 4565 4566
    if (ops[i] == NULL) {
      return NULL;
    }
4567
  }
H
Haojun Liao 已提交
4568

4569
  SOperatorInfo* pOptr = NULL;
H
Haojun Liao 已提交
4570
  if (QUERY_NODE_PHYSICAL_PLAN_PROJECT == type) {
dengyihao's avatar
dengyihao 已提交
4571 4572
    SProjectPhysiNode* pProjPhyNode = (SProjectPhysiNode*)pPhyNode;
    SExprInfo*         pExprInfo = createExprInfo(pProjPhyNode->pProjections, NULL, &num);
H
Haojun Liao 已提交
4573

4574
    SSDataBlock* pResBlock = createResDataBlock(pPhyNode->pOutputDataBlockDesc);
dengyihao's avatar
dengyihao 已提交
4575 4576
    SLimit       limit = {.limit = pProjPhyNode->limit, .offset = pProjPhyNode->offset};
    SLimit       slimit = {.limit = pProjPhyNode->slimit, .offset = pProjPhyNode->soffset};
4577
    pOptr = createProjectOperatorInfo(ops[0], pExprInfo, num, pResBlock, &limit, &slimit, pTaskInfo);
H
Haojun Liao 已提交
4578 4579 4580
  } else if (QUERY_NODE_PHYSICAL_PLAN_AGG == type) {
    SAggPhysiNode* pAggNode = (SAggPhysiNode*)pPhyNode;
    SExprInfo*     pExprInfo = createExprInfo(pAggNode->pAggFuncs, pAggNode->pGroupKeys, &num);
4581
    SSDataBlock*   pResBlock = createResDataBlock(pPhyNode->pOutputDataBlockDesc);
H
Haojun Liao 已提交
4582

dengyihao's avatar
dengyihao 已提交
4583
    int32_t    numOfScalarExpr = 0;
4584 4585 4586 4587 4588
    SExprInfo* pScalarExprInfo = NULL;
    if (pAggNode->pExprs != NULL) {
      pScalarExprInfo = createExprInfo(pAggNode->pExprs, NULL, &numOfScalarExpr);
    }

H
Haojun Liao 已提交
4589 4590
    if (pAggNode->pGroupKeys != NULL) {
      SArray* pColList = extractColumnInfo(pAggNode->pGroupKeys);
dengyihao's avatar
dengyihao 已提交
4591
      pOptr = createGroupOperatorInfo(ops[0], pExprInfo, num, pResBlock, pColList, pAggNode->node.pConditions,
wmmhello's avatar
wmmhello 已提交
4592
                                      pScalarExprInfo, numOfScalarExpr, pTaskInfo);
H
Haojun Liao 已提交
4593
    } else {
dengyihao's avatar
dengyihao 已提交
4594
      pOptr = createAggregateOperatorInfo(ops[0], pExprInfo, num, pResBlock, pScalarExprInfo, numOfScalarExpr,
wmmhello's avatar
wmmhello 已提交
4595
                                          pTaskInfo);
H
Haojun Liao 已提交
4596
    }
X
Xiaoyu Wang 已提交
4597
  } else if (QUERY_NODE_PHYSICAL_PLAN_INTERVAL == type || QUERY_NODE_PHYSICAL_PLAN_STREAM_INTERVAL == type) {
H
Haojun Liao 已提交
4598
    SIntervalPhysiNode* pIntervalPhyNode = (SIntervalPhysiNode*)pPhyNode;
H
Haojun Liao 已提交
4599

H
Haojun Liao 已提交
4600
    SExprInfo*   pExprInfo = createExprInfo(pIntervalPhyNode->window.pFuncs, NULL, &num);
4601
    SSDataBlock* pResBlock = createResDataBlock(pPhyNode->pOutputDataBlockDesc);
H
Haojun Liao 已提交
4602

dengyihao's avatar
dengyihao 已提交
4603 4604 4605 4606 4607 4608
    SInterval interval = {.interval = pIntervalPhyNode->interval,
                          .sliding = pIntervalPhyNode->sliding,
                          .intervalUnit = pIntervalPhyNode->intervalUnit,
                          .slidingUnit = pIntervalPhyNode->slidingUnit,
                          .offset = pIntervalPhyNode->offset,
                          .precision = ((SColumnNode*)pIntervalPhyNode->window.pTspk)->node.resType.precision};
H
Haojun Liao 已提交
4609

dengyihao's avatar
dengyihao 已提交
4610 4611
    STimeWindowAggSupp as = {.waterMark = pIntervalPhyNode->window.watermark,
                             .calTrigger = pIntervalPhyNode->window.triggerType};
4612

4613
    int32_t tsSlotId = ((SColumnNode*)pIntervalPhyNode->window.pTspk)->slotId;
wmmhello's avatar
wmmhello 已提交
4614
    pOptr = createIntervalOperatorInfo(ops[0], pExprInfo, num, pResBlock, &interval, tsSlotId, &as, pTaskInfo);
4615

H
Haojun Liao 已提交
4616
  } else if (QUERY_NODE_PHYSICAL_PLAN_SORT == type) {
H
Haojun Liao 已提交
4617
    SSortPhysiNode* pSortPhyNode = (SSortPhysiNode*)pPhyNode;
H
Haojun Liao 已提交
4618

4619 4620 4621
    SDataBlockDescNode* pDescNode = pPhyNode->pOutputDataBlockDesc;

    SSDataBlock* pResBlock = createResDataBlock(pDescNode);
4622
    SArray*      info = createSortInfo(pSortPhyNode->pSortKeys);
4623 4624

    int32_t    numOfCols = 0;
4625 4626 4627
    SExprInfo* pExprInfo = createExprInfo(pSortPhyNode->pExprs, NULL, &numOfCols);

    int32_t numOfOutputCols = 0;
X
Xiaoyu Wang 已提交
4628 4629
    SArray* pColList =
        extractColMatchInfo(pSortPhyNode->pTargets, pDescNode, &numOfOutputCols, pTaskInfo, COL_MATCH_FROM_SLOT_ID);
4630

4631
    pOptr = createSortOperatorInfo(ops[0], pResBlock, info, pExprInfo, numOfCols, pColList, pTaskInfo);
H
Haojun Liao 已提交
4632
  } else if (QUERY_NODE_PHYSICAL_PLAN_SESSION_WINDOW == type) {
H
Haojun Liao 已提交
4633 4634
    SSessionWinodwPhysiNode* pSessionNode = (SSessionWinodwPhysiNode*)pPhyNode;

X
Xiaoyu Wang 已提交
4635 4636
    STimeWindowAggSupp as = {.waterMark = pSessionNode->window.watermark,
                             .calTrigger = pSessionNode->window.triggerType};
4637

H
Haojun Liao 已提交
4638
    SExprInfo*   pExprInfo = createExprInfo(pSessionNode->window.pFuncs, NULL, &num);
4639
    SSDataBlock* pResBlock = createResDataBlock(pPhyNode->pOutputDataBlockDesc);
4640 4641
    int32_t      tsSlotId = ((SColumnNode*)pSessionNode->window.pTspk)->slotId;

X
Xiaoyu Wang 已提交
4642 4643
    pOptr =
        createSessionAggOperatorInfo(ops[0], pExprInfo, num, pResBlock, pSessionNode->gap, tsSlotId, &as, pTaskInfo);
5
54liuyao 已提交
4644 4645 4646 4647 4648 4649 4650 4651 4652 4653
  } else if (QUERY_NODE_PHYSICAL_PLAN_STREAM_SESSION_WINDOW == type) {
    SSessionWinodwPhysiNode* pSessionNode = (SSessionWinodwPhysiNode*)pPhyNode;

    STimeWindowAggSupp as = {.waterMark = pSessionNode->window.watermark,
                             .calTrigger = pSessionNode->window.triggerType};

    SExprInfo*   pExprInfo = createExprInfo(pSessionNode->window.pFuncs, NULL, &num);
    SSDataBlock* pResBlock = createResDataBlock(pPhyNode->pOutputDataBlockDesc);
    int32_t      tsSlotId = ((SColumnNode*)pSessionNode->window.pTspk)->slotId;

4654 4655
    pOptr = createStreamSessionAggOperatorInfo(ops[0], pExprInfo, num, pResBlock, pSessionNode->gap, tsSlotId, &as,
                                               pTaskInfo);
5
54liuyao 已提交
4656

H
Haojun Liao 已提交
4657
  } else if (QUERY_NODE_PHYSICAL_PLAN_PARTITION == type) {
dengyihao's avatar
dengyihao 已提交
4658 4659 4660
    SPartitionPhysiNode* pPartNode = (SPartitionPhysiNode*)pPhyNode;
    SArray*              pColList = extractPartitionColInfo(pPartNode->pPartitionKeys);
    SSDataBlock*         pResBlock = createResDataBlock(pPhyNode->pOutputDataBlockDesc);
4661 4662

    SExprInfo* pExprInfo = createExprInfo(pPartNode->pTargets, NULL, &num);
wmmhello's avatar
wmmhello 已提交
4663
    pOptr = createPartitionOperatorInfo(ops[0], pExprInfo, num, pResBlock, pColList, pTaskInfo);
4664
  } else if (QUERY_NODE_PHYSICAL_PLAN_STATE_WINDOW == type) {
dengyihao's avatar
dengyihao 已提交
4665
    SStateWinodwPhysiNode* pStateNode = (SStateWinodwPhysiNode*)pPhyNode;
4666

4667 4668
    STimeWindowAggSupp as = {.waterMark = pStateNode->window.watermark, .calTrigger = pStateNode->window.triggerType};

dengyihao's avatar
dengyihao 已提交
4669
    SExprInfo*   pExprInfo = createExprInfo(pStateNode->window.pFuncs, NULL, &num);
4670
    SSDataBlock* pResBlock = createResDataBlock(pPhyNode->pOutputDataBlockDesc);
4671 4672
    int32_t      tsSlotId = ((SColumnNode*)pStateNode->window.pTspk)->slotId;

4673
    SColumnNode* pColNode = (SColumnNode*)((STargetNode*)pStateNode->pStateKey)->pExpr;
X
Xiaoyu Wang 已提交
4674
    SColumn      col = extractColumnFromColumnNode(pColNode);
4675
    pOptr = createStatewindowOperatorInfo(ops[0], pExprInfo, num, pResBlock, &as, tsSlotId, &col, pTaskInfo);
4676
  } else if (QUERY_NODE_PHYSICAL_PLAN_JOIN == type) {
dengyihao's avatar
dengyihao 已提交
4677 4678
    SJoinPhysiNode* pJoinNode = (SJoinPhysiNode*)pPhyNode;
    SSDataBlock*    pResBlock = createResDataBlock(pPhyNode->pOutputDataBlockDesc);
4679 4680

    SExprInfo* pExprInfo = createExprInfo(pJoinNode->pTargets, NULL, &num);
H
Haojun Liao 已提交
4681
    pOptr = createMergeJoinOperatorInfo(ops, size, pExprInfo, num, pResBlock, pJoinNode->pOnConditions, pTaskInfo);
4682 4683
  } else if (QUERY_NODE_PHYSICAL_PLAN_FILL == type) {
    SFillPhysiNode* pFillNode = (SFillPhysiNode*)pPhyNode;
X
Xiaoyu Wang 已提交
4684 4685
    SSDataBlock*    pResBlock = createResDataBlock(pPhyNode->pOutputDataBlockDesc);
    SExprInfo*      pExprInfo = createExprInfo(pFillNode->pTargets, NULL, &num);
4686

4687
    SInterval* pInterval = &((SIntervalAggOperatorInfo*)ops[0]->info)->interval;
X
Xiaoyu Wang 已提交
4688 4689
    pOptr = createFillOperatorInfo(ops[0], pExprInfo, num, pInterval, &pFillNode->timeRange, pResBlock, pFillNode->mode,
                                   (SNodeListNode*)pFillNode->pValues, false, pTaskInfo);
H
Haojun Liao 已提交
4690 4691
  } else {
    ASSERT(0);
H
Haojun Liao 已提交
4692
  }
4693 4694 4695

  taosMemoryFree(ops);
  return pOptr;
4696
}
H
Haojun Liao 已提交
4697

4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709
int32_t compareTimeWindow(const void* p1, const void* p2, const void* param) {
  const SQueryTableDataCond *pCond = param;
  const STimeWindow *pWin1 = p1;
  const STimeWindow *pWin2 = p2;
  if (pCond->order == TSDB_ORDER_ASC) {
    return pWin1->skey - pWin2->skey;
  } else if (pCond->order == TSDB_ORDER_DESC) {
    return pWin2->skey - pWin1->skey;
  }
  return 0;
}

4710
int32_t initQueryTableDataCond(SQueryTableDataCond* pCond, const STableScanPhysiNode* pTableScanNode) {
4711 4712 4713 4714 4715 4716
  pCond->loadExternalRows = false;

  pCond->order = pTableScanNode->scanSeq[0] > 0 ? TSDB_ORDER_ASC : TSDB_ORDER_DESC;
  pCond->numOfCols = LIST_LENGTH(pTableScanNode->scan.pScanCols);
  pCond->colList = taosMemoryCalloc(pCond->numOfCols, sizeof(SColumnInfo));
  if (pCond->colList == NULL) {
H
Haojun Liao 已提交
4717
    terrno = TSDB_CODE_QRY_OUT_OF_MEMORY;
4718 4719 4720
    return terrno;
  }

4721 4722 4723 4724 4725
  //pCond->twindow = pTableScanNode->scanRange;
  //TODO: get it from stable scan node
  pCond->numOfTWindows = 1;
  pCond->twindows = taosMemoryCalloc(pCond->numOfTWindows, sizeof(STimeWindow));
  pCond->twindows[0] = pTableScanNode->scanRange;
4726 4727

#if 1
L
Liu Jicong 已提交
4728
  // todo work around a problem, remove it later
4729 4730 4731 4732 4733
  for (int32_t i = 0; i < pCond->numOfTWindows; ++i) {
    if ((pCond->order == TSDB_ORDER_ASC && pCond->twindows[i].skey > pCond->twindows[i].ekey) ||
        (pCond->order == TSDB_ORDER_DESC && pCond->twindows[i].skey < pCond->twindows[i].ekey)) {
      TSWAP(pCond->twindows[i].skey, pCond->twindows[i].ekey);
    }
H
Haojun Liao 已提交
4734
  }
4735
#endif
H
Haojun Liao 已提交
4736

4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748
  for (int32_t i = 0; i < pCond->numOfTWindows; ++i) {
    if ((pCond->order == TSDB_ORDER_ASC && pCond->twindows[i].skey > pCond->twindows[i].ekey) ||
        (pCond->order == TSDB_ORDER_DESC && pCond->twindows[i].skey < pCond->twindows[i].ekey)) {
      TSWAP(pCond->twindows[i].skey, pCond->twindows[i].ekey);
    }
  }
  taosqsort(pCond->twindows,
            pCond->numOfTWindows,
            sizeof(STimeWindow),
            pCond,
            compareTimeWindow);

4749 4750
  pCond->type = BLOCK_LOAD_OFFSET_SEQ_ORDER;
  //  pCond->type = pTableScanNode->scanFlag;
H
Haojun Liao 已提交
4751

H
Haojun Liao 已提交
4752
  int32_t j = 0;
4753
  for (int32_t i = 0; i < pCond->numOfCols; ++i) {
H
Haojun Liao 已提交
4754 4755
    STargetNode* pNode = (STargetNode*)nodesListGetNode(pTableScanNode->scan.pScanCols, i);
    SColumnNode* pColNode = (SColumnNode*)pNode->pExpr;
H
Haojun Liao 已提交
4756 4757 4758
    if (pColNode->colType == COLUMN_TYPE_TAG) {
      continue;
    }
H
Haojun Liao 已提交
4759

4760 4761 4762
    pCond->colList[j].type = pColNode->node.resType.type;
    pCond->colList[j].bytes = pColNode->node.resType.bytes;
    pCond->colList[j].colId = pColNode->colId;
H
Haojun Liao 已提交
4763
    j += 1;
H
Haojun Liao 已提交
4764 4765
  }

4766 4767
  pCond->numOfCols = j;
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
4768
}
H
Haojun Liao 已提交
4769

4770 4771
SColumn extractColumnFromColumnNode(SColumnNode* pColNode) {
  SColumn c = {0};
X
Xiaoyu Wang 已提交
4772 4773 4774 4775 4776
  c.slotId = pColNode->slotId;
  c.colId = pColNode->colId;
  c.type = pColNode->node.resType.type;
  c.bytes = pColNode->node.resType.bytes;
  c.scale = pColNode->node.resType.scale;
4777 4778 4779 4780
  c.precision = pColNode->node.resType.precision;
  return c;
}

H
Haojun Liao 已提交
4781
SArray* extractColumnInfo(SNodeList* pNodeList) {
L
Liu Jicong 已提交
4782
  size_t  numOfCols = LIST_LENGTH(pNodeList);
H
Haojun Liao 已提交
4783 4784 4785 4786 4787 4788
  SArray* pList = taosArrayInit(numOfCols, sizeof(SColumn));
  if (pList == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

L
Liu Jicong 已提交
4789 4790
  for (int32_t i = 0; i < numOfCols; ++i) {
    STargetNode* pNode = (STargetNode*)nodesListGetNode(pNodeList, i);
H
Haojun Liao 已提交
4791

4792 4793 4794
    if (nodeType(pNode->pExpr) == QUERY_NODE_COLUMN) {
      SColumnNode* pColNode = (SColumnNode*)pNode->pExpr;

4795
      SColumn c = extractColumnFromColumnNode(pColNode);
4796 4797
      taosArrayPush(pList, &c);
    } else if (nodeType(pNode->pExpr) == QUERY_NODE_VALUE) {
L
Liu Jicong 已提交
4798 4799
      SValueNode* pValNode = (SValueNode*)pNode->pExpr;
      SColumn     c = {0};
4800
      c.slotId = pNode->slotId;
L
Liu Jicong 已提交
4801 4802 4803 4804
      c.colId = pNode->slotId;
      c.type = pValNode->node.type;
      c.bytes = pValNode->node.resType.bytes;
      c.scale = pValNode->node.resType.scale;
4805 4806 4807 4808
      c.precision = pValNode->node.resType.precision;

      taosArrayPush(pList, &c);
    }
H
Haojun Liao 已提交
4809 4810 4811 4812 4813
  }

  return pList;
}

4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827
SArray* extractPartitionColInfo(SNodeList* pNodeList) {
  size_t  numOfCols = LIST_LENGTH(pNodeList);
  SArray* pList = taosArrayInit(numOfCols, sizeof(SColumn));
  if (pList == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

  for (int32_t i = 0; i < numOfCols; ++i) {
    SColumnNode* pColNode = (SColumnNode*)nodesListGetNode(pNodeList, i);

    // todo extract method
    SColumn c = {0};
    c.slotId = pColNode->slotId;
dengyihao's avatar
dengyihao 已提交
4828 4829 4830
    c.colId = pColNode->colId;
    c.type = pColNode->node.resType.type;
    c.bytes = pColNode->node.resType.bytes;
4831 4832 4833 4834 4835 4836 4837 4838 4839
    c.precision = pColNode->node.resType.precision;
    c.scale = pColNode->node.resType.scale;

    taosArrayPush(pList, &c);
  }

  return pList;
}

4840
SArray* createSortInfo(SNodeList* pNodeList) {
L
Liu Jicong 已提交
4841
  size_t  numOfCols = LIST_LENGTH(pNodeList);
H
Haojun Liao 已提交
4842 4843 4844 4845 4846 4847
  SArray* pList = taosArrayInit(numOfCols, sizeof(SBlockOrderInfo));
  if (pList == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return pList;
  }

L
Liu Jicong 已提交
4848
  for (int32_t i = 0; i < numOfCols; ++i) {
4849
    SOrderByExprNode* pSortKey = (SOrderByExprNode*)nodesListGetNode(pNodeList, i);
L
Liu Jicong 已提交
4850 4851
    SBlockOrderInfo   bi = {0};
    bi.order = (pSortKey->order == ORDER_ASC) ? TSDB_ORDER_ASC : TSDB_ORDER_DESC;
H
Haojun Liao 已提交
4852 4853 4854
    bi.nullFirst = (pSortKey->nullOrder == NULL_ORDER_FIRST);

    SColumnNode* pColNode = (SColumnNode*)pSortKey->pExpr;
4855
    bi.slotId = pColNode->slotId;
H
Haojun Liao 已提交
4856 4857 4858 4859 4860 4861
    taosArrayPush(pList, &bi);
  }

  return pList;
}

X
Xiaoyu Wang 已提交
4862
SArray* extractColMatchInfo(SNodeList* pNodeList, SDataBlockDescNode* pOutputNodeList, int32_t* numOfOutputCols,
4863
                            SExecTaskInfo* pTaskInfo, int32_t type) {
L
Liu Jicong 已提交
4864
  size_t  numOfCols = LIST_LENGTH(pNodeList);
H
Haojun Liao 已提交
4865 4866 4867 4868 4869 4870
  SArray* pList = taosArrayInit(numOfCols, sizeof(SColMatchInfo));
  if (pList == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

L
Liu Jicong 已提交
4871 4872 4873
  for (int32_t i = 0; i < numOfCols; ++i) {
    STargetNode* pNode = (STargetNode*)nodesListGetNode(pNodeList, i);
    SColumnNode* pColNode = (SColumnNode*)pNode->pExpr;
H
Haojun Liao 已提交
4874 4875

    SColMatchInfo c = {0};
X
Xiaoyu Wang 已提交
4876 4877 4878 4879
    c.output = true;
    c.colId = pColNode->colId;
    c.srcSlotId = pColNode->slotId;
    c.matchType = type;
H
Haojun Liao 已提交
4880 4881 4882 4883
    c.targetSlotId = pNode->slotId;
    taosArrayPush(pList, &c);
  }

H
Haojun Liao 已提交
4884 4885
  *numOfOutputCols = 0;
  int32_t num = LIST_LENGTH(pOutputNodeList->pSlots);
L
Liu Jicong 已提交
4886 4887
  for (int32_t i = 0; i < num; ++i) {
    SSlotDescNode* pNode = (SSlotDescNode*)nodesListGetNode(pOutputNodeList->pSlots, i);
4888

4889
    // todo: add reserve flag check
4890 4891
    // it is a column reserved for the arithmetic expression calculation
    if (pNode->slotId >= numOfCols) {
4892 4893 4894 4895
      (*numOfOutputCols) += 1;
      continue;
    }

H
Haojun Liao 已提交
4896
    SColMatchInfo* info = taosArrayGet(pList, pNode->slotId);
H
Haojun Liao 已提交
4897 4898 4899 4900 4901
    if (pNode->output) {
      (*numOfOutputCols) += 1;
    } else {
      info->output = false;
    }
H
Haojun Liao 已提交
4902 4903
  }

H
Haojun Liao 已提交
4904 4905 4906
  return pList;
}

4907
int32_t getTableList(void* metaHandle, int32_t tableType, uint64_t tableUid, STableListInfo* pListInfo, SNode* pTagCond) {
wmmhello's avatar
wmmhello 已提交
4908
  int32_t code = TSDB_CODE_SUCCESS;
wmmhello's avatar
wmmhello 已提交
4909
  pListInfo->pTableList = taosArrayInit(8, sizeof(STableKeyInfo));
wmmhello's avatar
wmmhello 已提交
4910

wmmhello's avatar
wmmhello 已提交
4911
  if (tableType == TSDB_SUPER_TABLE) {
wmmhello's avatar
wmmhello 已提交
4912
    if(pTagCond){
wmmhello's avatar
wmmhello 已提交
4913
      SArray* res = taosArrayInit(8, sizeof(uint64_t));
wmmhello's avatar
wmmhello 已提交
4914
      code = doFilterTag(pTagCond, res);
wmmhello's avatar
wmmhello 已提交
4915 4916 4917
      if (code != TSDB_CODE_SUCCESS) {
        qError("doFilterTag error:%d", code);
        taosArrayDestroy(res);
wmmhello's avatar
wmmhello 已提交
4918
        terrno = code;
wmmhello's avatar
wmmhello 已提交
4919 4920 4921 4922 4923 4924 4925
        return code;
      }
      for(int i = 0; i < taosArrayGetSize(res); i++){
        STableKeyInfo info = {.lastKey = TSKEY_INITIAL_VAL, .uid = *(uint64_t*)taosArrayGet(res, i)};
        taosArrayPush(pListInfo->pTableList, &info);
      }
      taosArrayDestroy(res);
wmmhello's avatar
wmmhello 已提交
4926
    }else{
wmmhello's avatar
wmmhello 已提交
4927
      code = tsdbGetAllTableList(metaHandle, tableUid, pListInfo->pTableList);
wmmhello's avatar
wmmhello 已提交
4928
    }
H
Haojun Liao 已提交
4929
  } else {  // Create one table group.
wmmhello's avatar
wmmhello 已提交
4930 4931
    STableKeyInfo info = {.lastKey = 0, .uid = tableUid};
    taosArrayPush(pListInfo->pTableList, &info);
4932 4933 4934 4935
  }

  return code;
}
H
Haojun Liao 已提交
4936

wmmhello's avatar
wmmhello 已提交
4937
SArray* extractTableIdList(const STableListInfo* pTableGroupInfo) {
4938 4939
  SArray* tableIdList = taosArrayInit(4, sizeof(uint64_t));

wmmhello's avatar
wmmhello 已提交
4940 4941 4942 4943
  // Transfer the Array of STableKeyInfo into uid list.
  for (int32_t i = 0; i < taosArrayGetSize(pTableGroupInfo->pTableList); ++i) {
    STableKeyInfo* pkeyInfo = taosArrayGet(pTableGroupInfo->pTableList, i);
    taosArrayPush(tableIdList, &pkeyInfo->uid);
4944 4945 4946 4947 4948
  }

  return tableIdList;
}

L
Liu Jicong 已提交
4949
tsdbReaderT doCreateDataReader(STableScanPhysiNode* pTableScanNode, SReadHandle* pHandle,
wmmhello's avatar
wmmhello 已提交
4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961
                               STableListInfo* pTableListInfo, uint64_t queryId, uint64_t taskId, SNode* pTagCond) {
  int32_t  code = getTableList(pHandle->meta, pTableScanNode->scan.tableType, pTableScanNode->scan.uid, pTableListInfo, pTagCond);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }

  if (taosArrayGetSize(pTableListInfo->pTableList) == 0) {
    code = 0;
    qDebug("no table qualified for query, TID:0x%" PRIx64 ", QID:0x%" PRIx64, taskId, queryId);
    goto _error;
  }

4962
  SQueryTableDataCond cond = {0};
wmmhello's avatar
wmmhello 已提交
4963
  code = initQueryTableDataCond(&cond, pTableScanNode);
4964
  if (code != TSDB_CODE_SUCCESS) {
wmmhello's avatar
wmmhello 已提交
4965
    goto _error;
X
Xiaoyu Wang 已提交
4966
  }
4967

wmmhello's avatar
wmmhello 已提交
4968
  return tsdbQueryTables(pHandle->vnode, &cond, pTableListInfo, queryId, taskId);
wmmhello's avatar
wmmhello 已提交
4969 4970 4971 4972

_error:
  terrno = code;
  return NULL;
H
Haojun Liao 已提交
4973 4974
}

dengyihao's avatar
dengyihao 已提交
4975 4976
int32_t createExecTaskInfoImpl(SSubplan* pPlan, SExecTaskInfo** pTaskInfo, SReadHandle* pHandle, uint64_t taskId,
                               EOPTR_EXEC_MODEL model) {
H
Haojun Liao 已提交
4977 4978
  uint64_t queryId = pPlan->id.queryId;

H
Haojun Liao 已提交
4979
  int32_t code = TSDB_CODE_SUCCESS;
D
dapan1121 已提交
4980
  *pTaskInfo = createExecTaskInfo(queryId, taskId, model, pPlan->dbFName);
H
Haojun Liao 已提交
4981 4982 4983 4984
  if (*pTaskInfo == NULL) {
    code = TSDB_CODE_QRY_OUT_OF_MEMORY;
    goto _complete;
  }
H
Haojun Liao 已提交
4985

L
Liu Jicong 已提交
4986
  (*pTaskInfo)->pRoot =
wmmhello's avatar
wmmhello 已提交
4987
      createOperatorTree(pPlan->pNode, *pTaskInfo, pHandle, queryId, taskId, &(*pTaskInfo)->tableqinfoList, pPlan->pTagCond);
D
dapan1121 已提交
4988
  if (NULL == (*pTaskInfo)->pRoot) {
L
Liu Jicong 已提交
4989
    code = terrno;
D
dapan1121 已提交
4990 4991
    goto _complete;
  }
H
Haojun Liao 已提交
4992

4993
  if ((*pTaskInfo)->pRoot == NULL) {
H
Haojun Liao 已提交
4994
    code = TSDB_CODE_QRY_OUT_OF_MEMORY;
H
Haojun Liao 已提交
4995
    goto _complete;
4996 4997
  }

H
Haojun Liao 已提交
4998 4999
  return code;

H
Haojun Liao 已提交
5000
_complete:
wafwerar's avatar
wafwerar 已提交
5001
  taosMemoryFreeClear(*pTaskInfo);
H
Haojun Liao 已提交
5002 5003 5004

  terrno = code;
  return code;
H
Haojun Liao 已提交
5005 5006
}

H
Haojun Liao 已提交
5007
void setResultBufSize(STaskAttr* pQueryAttr, SResultInfo* pResultInfo) {
5008 5009 5010 5011 5012 5013 5014 5015
  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;

dengyihao's avatar
dengyihao 已提交
5016 5017 5018 5019 5020 5021 5022 5023 5024 5025
  //  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;
  //  }
5026 5027

  pResultInfo->threshold = (int32_t)(pResultInfo->capacity * THRESHOLD_RATIO);
H
Haojun Liao 已提交
5028
  pResultInfo->totalRows = 0;
5029 5030
}

L
Liu Jicong 已提交
5031
// TODO refactor
5032
void freeColumnFilterInfo(SColumnFilterInfo* pFilter, int32_t numOfFilters) {
L
Liu Jicong 已提交
5033 5034 5035
  if (pFilter == NULL || numOfFilters == 0) {
    return;
  }
5036

L
Liu Jicong 已提交
5037 5038 5039
  for (int32_t i = 0; i < numOfFilters; i++) {
    if (pFilter[i].filterstr && pFilter[i].pz) {
      taosMemoryFree((void*)(pFilter[i].pz));
5040
    }
L
Liu Jicong 已提交
5041
  }
5042

L
Liu Jicong 已提交
5043
  taosMemoryFree(pFilter);
5044 5045
}

wmmhello's avatar
wmmhello 已提交
5046 5047 5048
static void doDestroyTableList(STableListInfo* pTableqinfoList) {
  taosArrayDestroy(pTableqinfoList->pTableList);
  taosHashCleanup(pTableqinfoList->map);
5049

wmmhello's avatar
wmmhello 已提交
5050 5051
  pTableqinfoList->pTableList = NULL;
  pTableqinfoList->map = NULL;
5052 5053
}

L
Liu Jicong 已提交
5054
void doDestroyTask(SExecTaskInfo* pTaskInfo) {
H
Haojun Liao 已提交
5055 5056
  qDebug("%s execTask is freed", GET_TASKID(pTaskInfo));

wmmhello's avatar
wmmhello 已提交
5057
  doDestroyTableList(&pTaskInfo->tableqinfoList);
H
Haojun Liao 已提交
5058
  destroyOperatorInfo(pTaskInfo->pRoot);
L
Liu Jicong 已提交
5059 5060
  //  taosArrayDestroy(pTaskInfo->summary.queryProfEvents);
  //  taosHashCleanup(pTaskInfo->summary.operatorProfResults);
5061

5062 5063
  taosMemoryFree(pTaskInfo->schemaVer.dbname);
  taosMemoryFree(pTaskInfo->schemaVer.tablename);
wafwerar's avatar
wafwerar 已提交
5064 5065 5066
  taosMemoryFreeClear(pTaskInfo->sql);
  taosMemoryFreeClear(pTaskInfo->id.str);
  taosMemoryFreeClear(pTaskInfo);
5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078
}

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 已提交
5079
      int32_t len = (varDataLen(val) > maxLen) ? maxLen : varDataLen(val);
5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091
      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 已提交
5092 5093
  //  size_t s3 = sizeof(STableCheckInfo);  buffer consumption in tsdb
  return (int64_t)(s1 * 1.5 * numOfTables);
5094 5095 5096 5097 5098 5099 5100
}

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 已提交
5101
    while (1) {
5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127
      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 已提交
5128

dengyihao's avatar
dengyihao 已提交
5129 5130
int32_t getOperatorExplainExecInfo(SOperatorInfo* operatorInfo, SExplainExecInfo** pRes, int32_t* capacity,
                                   int32_t* resNum) {
D
dapan1121 已提交
5131 5132
  if (*resNum >= *capacity) {
    *capacity += 10;
dengyihao's avatar
dengyihao 已提交
5133

D
dapan1121 已提交
5134 5135
    *pRes = taosMemoryRealloc(*pRes, (*capacity) * sizeof(SExplainExecInfo));
    if (NULL == *pRes) {
D
dapan1121 已提交
5136
      qError("malloc %d failed", (*capacity) * (int32_t)sizeof(SExplainExecInfo));
D
dapan1121 已提交
5137 5138 5139 5140
      return TSDB_CODE_QRY_OUT_OF_MEMORY;
    }
  }

5141 5142 5143 5144 5145
  SExplainExecInfo* pInfo = &(*pRes)[*resNum];

  pInfo->numOfRows = operatorInfo->resultInfo.totalRows;
  pInfo->startupCost = operatorInfo->cost.openCost;
  pInfo->totalCost = operatorInfo->cost.totalCost;
D
dapan1121 已提交
5146

5147
  if (operatorInfo->fpSet.getExplainFn) {
5148
    int32_t code = operatorInfo->fpSet.getExplainFn(operatorInfo, &pInfo->verboseInfo, &pInfo->verboseLen);
D
dapan1121 已提交
5149
    if (code) {
5150
      qError("%s operator getExplainFn failed, code:%s", GET_TASKID(operatorInfo->pTaskInfo), tstrerror(code));
D
dapan1121 已提交
5151 5152
      return code;
    }
5153 5154 5155
  } else {
    pInfo->verboseLen = 0;
    pInfo->verboseInfo = NULL;
D
dapan1121 已提交
5156
  }
dengyihao's avatar
dengyihao 已提交
5157

D
dapan1121 已提交
5158
  ++(*resNum);
dengyihao's avatar
dengyihao 已提交
5159

D
dapan1121 已提交
5160
  int32_t code = 0;
D
dapan1121 已提交
5161 5162
  for (int32_t i = 0; i < operatorInfo->numOfDownstream; ++i) {
    code = getOperatorExplainExecInfo(operatorInfo->pDownstream[i], pRes, capacity, resNum);
D
dapan1121 已提交
5163 5164 5165 5166 5167 5168 5169
    if (code) {
      taosMemoryFreeClear(*pRes);
      return TSDB_CODE_QRY_OUT_OF_MEMORY;
    }
  }

  return TSDB_CODE_SUCCESS;
D
dapan1121 已提交
5170
}
5
54liuyao 已提交
5171

5
54liuyao 已提交
5172
int32_t initCacheSupporter(SCatchSupporter* pCatchSup, size_t rowSize, const char* pKey, const char* pDir) {
5
54liuyao 已提交
5173 5174 5175
  pCatchSup->keySize = sizeof(int64_t) + sizeof(int64_t) + sizeof(TSKEY);
  pCatchSup->pKeyBuf = taosMemoryCalloc(1, pCatchSup->keySize);
  _hash_fn_t hashFn = taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY);
X
Xiaoyu Wang 已提交
5176
  pCatchSup->pWindowHashTable = taosHashInit(10000, hashFn, true, HASH_NO_LOCK);
5
54liuyao 已提交
5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203
  if (pCatchSup->pKeyBuf == NULL || pCatchSup->pWindowHashTable == NULL) {
    return TSDB_CODE_OUT_OF_MEMORY;
  }

  int32_t pageSize = rowSize * 32;
  int32_t bufSize = pageSize * 4096;
  return createDiskbasedBuf(&pCatchSup->pDataBuf, pageSize, bufSize, pKey, pDir);
}

int32_t initStreamAggSupporter(SStreamAggSupporter* pSup, const char* pKey) {
  pSup->keySize = sizeof(int64_t) + sizeof(TSKEY);
  pSup->pKeyBuf = taosMemoryCalloc(1, pSup->keySize);
  pSup->pResultRows = taosArrayInit(1024, sizeof(SResultWindowInfo));
  if (pSup->pKeyBuf == NULL || pSup->pResultRows == NULL) {
    return TSDB_CODE_OUT_OF_MEMORY;
  }

  int32_t pageSize = 4096;
  while (pageSize < pSup->resultRowSize * 4) {
    pageSize <<= 1u;
  }
  // at least four pages need to be in buffer
  int32_t bufSize = 4096 * 256;
  if (bufSize <= pageSize) {
    bufSize = pageSize * 4;
  }
  return createDiskbasedBuf(&pSup->pResultBuf, pageSize, bufSize, pKey, "/tmp/");
5
54liuyao 已提交
5204
}