scanoperator.c 111.0 KB
Newer Older
H
Haojun Liao 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/*
 * 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/>.
 */

16
#include "executorimpl.h"
H
Haojun Liao 已提交
17
#include "filter.h"
18
#include "function.h"
19
#include "functionMgt.h"
L
Liu Jicong 已提交
20
#include "os.h"
H
Haojun Liao 已提交
21
#include "querynodes.h"
22
#include "systable.h"
H
Haojun Liao 已提交
23
#include "tname.h"
24
#include "ttime.h"
H
Haojun Liao 已提交
25 26 27 28 29 30 31 32

#include "tdatablock.h"
#include "tmsg.h"

#include "query.h"
#include "tcompare.h"
#include "thash.h"
#include "ttypes.h"
33
#include "vnode.h"
H
Haojun Liao 已提交
34 35

#define SET_REVERSE_SCAN_FLAG(_info) ((_info)->scanFlag = REVERSE_SCAN)
36
#define SWITCH_ORDER(n)              (((n) = ((n) == TSDB_ORDER_ASC) ? TSDB_ORDER_DESC : TSDB_ORDER_ASC))
37

38
static int32_t buildSysDbTableInfo(const SSysTableScanInfo* pInfo, int32_t capacity);
L
Liu Jicong 已提交
39 40
static int32_t buildDbTableInfoBlock(const SSDataBlock* p, const SSysTableMeta* pSysDbTableMeta, size_t size,
                                     const char* dbName);
41

L
Liu Jicong 已提交
42
static bool processBlockWithProbability(const SSampleExecInfo* pInfo);
43

44
bool processBlockWithProbability(const SSampleExecInfo* pInfo) {
45 46 47 48 49 50 51 52 53 54 55 56
#if 0
  if (pInfo->sampleRatio == 1) {
    return true;
  }

  uint32_t val = taosRandR((uint32_t*) &pInfo->seed);
  return (val % ((uint32_t)(1/pInfo->sampleRatio))) == 0;
#else
  return true;
#endif
}

57
static void switchCtxOrder(SqlFunctionCtx* pCtx, int32_t numOfOutput) {
H
Haojun Liao 已提交
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
  for (int32_t i = 0; i < numOfOutput; ++i) {
    SWITCH_ORDER(pCtx[i].order);
  }
}

static void setupQueryRangeForReverseScan(STableScanInfo* pTableScanInfo) {
#if 0
  int32_t numOfGroups = (int32_t)(GET_NUM_OF_TABLEGROUP(pRuntimeEnv));
  for(int32_t i = 0; i < numOfGroups; ++i) {
    SArray *group = GET_TABLEGROUP(pRuntimeEnv, i);
    SArray *tableKeyGroup = taosArrayGetP(pQueryAttr->tableGroupInfo.pGroupList, i);

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

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

86 87 88 89 90 91 92 93 94
static void getNextTimeWindow(SInterval* pInterval, STimeWindow* tw, int32_t order) {
  int32_t factor = GET_FORWARD_DIRECTION_FACTOR(order);
  if (pInterval->intervalUnit != 'n' && pInterval->intervalUnit != 'y') {
    tw->skey += pInterval->sliding * factor;
    tw->ekey = tw->skey + pInterval->interval - 1;
    return;
  }

  int64_t key = tw->skey, interval = pInterval->interval;
95
  // convert key to second
96 97 98 99 100 101 102
  key = convertTimePrecision(key, pInterval->precision, TSDB_TIME_PRECISION_MILLI) / 1000;

  if (pInterval->intervalUnit == 'y') {
    interval *= 12;
  }

  struct tm tm;
103
  time_t    t = (time_t)key;
104 105 106 107 108
  taosLocalTime(&t, &tm);

  int mon = (int)(tm.tm_year * 12 + tm.tm_mon + interval * factor);
  tm.tm_year = mon / 12;
  tm.tm_mon = mon % 12;
wafwerar's avatar
wafwerar 已提交
109
  tw->skey = convertTimePrecision((int64_t)taosMktime(&tm) * 1000LL, TSDB_TIME_PRECISION_MILLI, pInterval->precision);
110 111 112 113

  mon = (int)(mon + interval);
  tm.tm_year = mon / 12;
  tm.tm_mon = mon % 12;
wafwerar's avatar
wafwerar 已提交
114
  tw->ekey = convertTimePrecision((int64_t)taosMktime(&tm) * 1000LL, TSDB_TIME_PRECISION_MILLI, pInterval->precision);
115 116 117 118

  tw->ekey -= 1;
}

119
static bool overlapWithTimeWindow(SInterval* pInterval, SDataBlockInfo* pBlockInfo, int32_t order) {
120 121 122 123 124 125 126
  STimeWindow w = {0};

  // 0 by default, which means it is not a interval operator of the upstream operator.
  if (pInterval->interval == 0) {
    return false;
  }

127
  if (order == TSDB_ORDER_ASC) {
128
    w = getAlignQueryTimeWindow(pInterval, pInterval->precision, pBlockInfo->window.skey);
129 130
    assert(w.ekey >= pBlockInfo->window.skey);

S
slzhou 已提交
131
    if (TMAX(w.skey, pBlockInfo->window.skey) <= TMIN(w.ekey, pBlockInfo->window.ekey)) {
132 133 134
      return true;
    }

135 136
    while (1) {
      getNextTimeWindow(pInterval, &w, order);
137 138 139 140 141 142 143 144 145 146
      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 {
147
    w = getAlignQueryTimeWindow(pInterval, pInterval->precision, pBlockInfo->window.ekey);
148 149 150 151 152 153
    assert(w.skey <= pBlockInfo->window.ekey);

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

154
    while (1) {
155 156 157 158 159 160 161 162 163 164
      getNextTimeWindow(pInterval, &w, order);
      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;
      }
    }
165 166 167 168 169
  }

  return false;
}

170 171 172 173 174 175 176 177 178 179 180
// this function is for table scanner to extract temporary results of upstream aggregate results.
static SResultRow* getTableGroupOutputBuf(SOperatorInfo* pOperator, uint64_t groupId, SFilePage** pPage) {
  if (pOperator->operatorType != QUERY_NODE_PHYSICAL_PLAN_TABLE_SCAN) {
    return NULL;
  }

  int64_t buf[2] = {0};
  SET_RES_WINDOW_KEY((char*)buf, &groupId, sizeof(groupId), groupId);

  STableScanInfo* pTableScanInfo = pOperator->info;

L
Liu Jicong 已提交
181 182
  SResultRowPosition* p1 = (SResultRowPosition*)taosHashGet(pTableScanInfo->pdInfo.pAggSup->pResultRowHashTable, buf,
                                                            GET_RES_WINDOW_KEY_LEN(sizeof(groupId)));
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230

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

  *pPage = getBufPage(pTableScanInfo->pdInfo.pAggSup->pResultBuf, p1->pageId);
  return (SResultRow*)((char*)(*pPage) + p1->offset);
}

static int32_t doDynamicPruneDataBlock(SOperatorInfo* pOperator, SDataBlockInfo* pBlockInfo, uint32_t* status) {
  STableScanInfo* pTableScanInfo = pOperator->info;

  if (pTableScanInfo->pdInfo.pExprSup == NULL) {
    return TSDB_CODE_SUCCESS;
  }

  SExprSupp* pSup1 = pTableScanInfo->pdInfo.pExprSup;

  SFilePage*  pPage = NULL;
  SResultRow* pRow = getTableGroupOutputBuf(pOperator, pBlockInfo->groupId, &pPage);

  if (pRow == NULL) {
    return TSDB_CODE_SUCCESS;
  }

  bool notLoadBlock = true;
  for (int32_t i = 0; i < pSup1->numOfExprs; ++i) {
    int32_t functionId = pSup1->pCtx[i].functionId;

    SResultRowEntryInfo* pEntry = getResultEntryInfo(pRow, i, pTableScanInfo->pdInfo.pExprSup->rowEntryInfoOffset);

    int32_t reqStatus = fmFuncDynDataRequired(functionId, pEntry, &pBlockInfo->window);
    if (reqStatus != FUNC_DATA_REQUIRED_NOT_LOAD) {
      notLoadBlock = false;
      break;
    }
  }

  // release buffer pages
  releaseBufPage(pTableScanInfo->pdInfo.pAggSup->pResultBuf, pPage);

  if (notLoadBlock) {
    *status = FUNC_DATA_REQUIRED_NOT_LOAD;
  }

  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
231 232 233 234 235 236 237 238 239 240
static FORCE_INLINE bool doFilterByBlockSMA(const SNode* pFilterNode, SColumnDataAgg** pColsAgg, int32_t numOfCols,
                                            int32_t numOfRows) {
  if (pColsAgg == NULL || pFilterNode == NULL) {
    return true;
  }

  SFilterInfo* filter = NULL;

  // todo move to the initialization function
  int32_t code = filterInitFromNode((SNode*)pFilterNode, &filter, 0);
L
Liu Jicong 已提交
241
  bool    keep = filterRangeExecute(filter, pColsAgg, numOfCols, numOfRows);
H
Haojun Liao 已提交
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281

  filterFreeInfo(filter);
  return keep;
}

static bool doLoadBlockSMA(STableScanInfo* pTableScanInfo, SSDataBlock* pBlock, SExecTaskInfo* pTaskInfo) {
  bool             allColumnsHaveAgg = true;
  SColumnDataAgg** pColAgg = NULL;

  int32_t code = tsdbRetrieveDatablockSMA(pTableScanInfo->dataReader, &pColAgg, &allColumnsHaveAgg);
  if (code != TSDB_CODE_SUCCESS) {
    longjmp(pTaskInfo->env, code);
  }

  if (!allColumnsHaveAgg) {
    return false;
  }

  //  if (allColumnsHaveAgg == true) {
  int32_t numOfCols = taosArrayGetSize(pBlock->pDataBlock);

  // todo create this buffer during creating operator
  if (pBlock->pBlockAgg == NULL) {
    pBlock->pBlockAgg = taosMemoryCalloc(numOfCols, POINTER_BYTES);
    if (pBlock->pBlockAgg == NULL) {
      longjmp(pTaskInfo->env, TSDB_CODE_OUT_OF_MEMORY);
    }
  }

  for (int32_t i = 0; i < taosArrayGetSize(pTableScanInfo->pColMatchInfo); ++i) {
    SColMatchInfo* pColMatchInfo = taosArrayGet(pTableScanInfo->pColMatchInfo, i);
    if (!pColMatchInfo->output) {
      continue;
    }
    pBlock->pBlockAgg[pColMatchInfo->targetSlotId] = pColAgg[i];
  }

  return true;
}

L
Liu Jicong 已提交
282 283
static int32_t loadDataBlock(SOperatorInfo* pOperator, STableScanInfo* pTableScanInfo, SSDataBlock* pBlock,
                             uint32_t* status) {
284
  SExecTaskInfo*  pTaskInfo = pOperator->pTaskInfo;
285 286
  STableScanInfo* pInfo = pOperator->info;

287
  SFileBlockLoadRecorder* pCost = &pTableScanInfo->readRecorder;
H
Haojun Liao 已提交
288 289

  pCost->totalBlocks += 1;
290
  pCost->totalRows += pBlock->info.rows;
H
Haojun Liao 已提交
291
  bool loadSMA = false;
H
Haojun Liao 已提交
292

293
  *status = pInfo->dataBlockLoadFlag;
294
  if (pTableScanInfo->pFilterNode != NULL ||
295
      overlapWithTimeWindow(&pTableScanInfo->pdInfo.interval, &pBlock->info, pTableScanInfo->cond.order)) {
296 297 298 299
    (*status) = FUNC_DATA_REQUIRED_DATA_LOAD;
  }

  SDataBlockInfo* pBlockInfo = &pBlock->info;
300
  taosMemoryFreeClear(pBlock->pBlockAgg);
301 302

  if (*status == FUNC_DATA_REQUIRED_FILTEROUT) {
303 304
    qDebug("%s data block filter out, brange:%" PRId64 "-%" PRId64 ", rows:%d", GET_TASKID(pTaskInfo),
           pBlockInfo->window.skey, pBlockInfo->window.ekey, pBlockInfo->rows);
305 306 307
    pCost->filterOutBlocks += 1;
    return TSDB_CODE_SUCCESS;
  } else if (*status == FUNC_DATA_REQUIRED_NOT_LOAD) {
308 309
    qDebug("%s data block skipped, brange:%" PRId64 "-%" PRId64 ", rows:%d", GET_TASKID(pTaskInfo),
           pBlockInfo->window.skey, pBlockInfo->window.ekey, pBlockInfo->rows);
310
    pCost->skipBlocks += 1;
311

312 313 314
    return TSDB_CODE_SUCCESS;
  } else if (*status == FUNC_DATA_REQUIRED_STATIS_LOAD) {
    pCost->loadBlockStatis += 1;
L
Liu Jicong 已提交
315
    loadSMA = true;  // mark the operation of load sma;
H
Haojun Liao 已提交
316
    bool success = doLoadBlockSMA(pTableScanInfo, pBlock, pTaskInfo);
L
Liu Jicong 已提交
317
    if (success) {  // failed to load the block sma data, data block statistics does not exist, load data block instead
318 319 320 321
      qDebug("%s data block SMA loaded, brange:%" PRId64 "-%" PRId64 ", rows:%d", GET_TASKID(pTaskInfo),
             pBlockInfo->window.skey, pBlockInfo->window.ekey, pBlockInfo->rows);
      return TSDB_CODE_SUCCESS;
    } else {
322
      qDebug("%s failed to load SMA, since not all columns have SMA", GET_TASKID(pTaskInfo));
H
Haojun Liao 已提交
323
      *status = FUNC_DATA_REQUIRED_DATA_LOAD;
324
    }
H
Haojun Liao 已提交
325
  }
326

H
Haojun Liao 已提交
327
  ASSERT(*status == FUNC_DATA_REQUIRED_DATA_LOAD);
328

H
Haojun Liao 已提交
329
  // try to filter data block according to sma info
330 331 332 333 334 335 336 337 338 339 340 341 342
  if (pTableScanInfo->pFilterNode != NULL && (!loadSMA)) {
    bool success = doLoadBlockSMA(pTableScanInfo, pBlock, pTaskInfo);
    if (success) {
      size_t size = taosArrayGetSize(pBlock->pDataBlock);
      bool   keep = doFilterByBlockSMA(pTableScanInfo->pFilterNode, pBlock->pBlockAgg, size, pBlockInfo->rows);
      if (!keep) {
        qDebug("%s data block filter out by block SMA, brange:%" PRId64 "-%" PRId64 ", rows:%d", GET_TASKID(pTaskInfo),
               pBlockInfo->window.skey, pBlockInfo->window.ekey, pBlockInfo->rows);
        pCost->filterOutBlocks += 1;
        (*status) = FUNC_DATA_REQUIRED_FILTEROUT;

        return TSDB_CODE_SUCCESS;
      }
343
    }
H
Haojun Liao 已提交
344
  }
345

346 347 348
  // free the sma info, since it should not be involved in later computing process.
  taosMemoryFreeClear(pBlock->pBlockAgg);

349
  // try to filter data block according to current results
350 351
  doDynamicPruneDataBlock(pOperator, pBlockInfo, status);
  if (*status == FUNC_DATA_REQUIRED_NOT_LOAD) {
352
    qDebug("%s data block skipped due to dynamic prune, brange:%" PRId64 "-%" PRId64 ", rows:%d", GET_TASKID(pTaskInfo),
353 354 355 356 357 358
           pBlockInfo->window.skey, pBlockInfo->window.ekey, pBlockInfo->rows);
    pCost->skipBlocks += 1;

    return TSDB_CODE_SUCCESS;
  }

H
Haojun Liao 已提交
359 360
  pCost->totalCheckedRows += pBlock->info.rows;
  pCost->loadBlocks += 1;
361

H
Haojun Liao 已提交
362 363 364
  SArray* pCols = tsdbRetrieveDataBlock(pTableScanInfo->dataReader, NULL);
  if (pCols == NULL) {
    return terrno;
H
Haojun Liao 已提交
365 366
  }

367
  relocateColumnData(pBlock, pTableScanInfo->pColMatchInfo, pCols, true);
368 369

  // currently only the tbname pseudo column
370
  if (pTableScanInfo->pseudoSup.numOfExprs > 0) {
371
    SExprSupp* pSup = &pTableScanInfo->pseudoSup;
H
Haojun Liao 已提交
372

L
Liu Jicong 已提交
373 374
    int32_t code = addTagPseudoColumnData(&pTableScanInfo->readHandle, pSup->pExprInfo, pSup->numOfExprs, pBlock,
                                          GET_TASKID(pTaskInfo));
H
Haojun Liao 已提交
375 376 377
    if (code != TSDB_CODE_SUCCESS) {
      longjmp(pTaskInfo->env, code);
    }
378 379
  }

380 381 382
  if (pTableScanInfo->pFilterNode != NULL) {
    int64_t st = taosGetTimestampUs();
    doFilter(pTableScanInfo->pFilterNode, pBlock, pTableScanInfo->pColMatchInfo);
383

384 385
    double el = (taosGetTimestampUs() - st) / 1000.0;
    pTableScanInfo->readRecorder.filterTime += el;
386

387 388 389 390 391 392 393
    if (pBlock->info.rows == 0) {
      pCost->filterOutBlocks += 1;
      qDebug("%s data block filter out, brange:%" PRId64 "-%" PRId64 ", rows:%d, elapsed time:%.2f ms",
             GET_TASKID(pTaskInfo), pBlockInfo->window.skey, pBlockInfo->window.ekey, pBlockInfo->rows, el);
    } else {
      qDebug("%s data block filter applied, elapsed time:%.2f ms", GET_TASKID(pTaskInfo), el);
    }
394 395
  }

H
Haojun Liao 已提交
396 397 398
  return TSDB_CODE_SUCCESS;
}

399
static void prepareForDescendingScan(STableScanInfo* pTableScanInfo, SqlFunctionCtx* pCtx, int32_t numOfOutput) {
H
Haojun Liao 已提交
400 401 402
  SET_REVERSE_SCAN_FLAG(pTableScanInfo);

  switchCtxOrder(pCtx, numOfOutput);
403
  //  setupQueryRangeForReverseScan(pTableScanInfo);
H
Haojun Liao 已提交
404

405
  pTableScanInfo->cond.order = TSDB_ORDER_DESC;
H
Haojun Liao 已提交
406 407
  STimeWindow* pTWindow = &pTableScanInfo->cond.twindows;
  TSWAP(pTWindow->skey, pTWindow->ekey);
H
Haojun Liao 已提交
408 409
}

H
Haojun Liao 已提交
410
int32_t addTagPseudoColumnData(SReadHandle* pHandle, SExprInfo* pPseudoExpr, int32_t numOfPseudoExpr,
L
Liu Jicong 已提交
411
                               SSDataBlock* pBlock, const char* idStr) {
412
  // currently only the tbname pseudo column
413
  if (numOfPseudoExpr == 0) {
H
Haojun Liao 已提交
414
    return TSDB_CODE_SUCCESS;
415 416 417
  }

  SMetaReader mr = {0};
418
  metaReaderInit(&mr, pHandle->meta, 0);
H
Haojun Liao 已提交
419 420
  int32_t code = metaGetTableEntryByUid(&mr, pBlock->info.uid);
  if (code != TSDB_CODE_SUCCESS) {
L
Liu Jicong 已提交
421
    qError("failed to get table meta, uid:0x%" PRIx64 ", code:%s, %s", pBlock->info.uid, tstrerror(terrno), idStr);
H
Haojun Liao 已提交
422 423 424
    metaReaderClear(&mr);
    return terrno;
  }
425

426 427
  for (int32_t j = 0; j < numOfPseudoExpr; ++j) {
    SExprInfo* pExpr = &pPseudoExpr[j];
428 429 430 431

    int32_t dstSlotId = pExpr->base.resSchema.slotId;

    SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, dstSlotId);
D
dapan1121 已提交
432
    colInfoDataCleanup(pColInfoData, pBlock->info.rows);
433 434 435 436 437

    int32_t functionId = pExpr->pExpr->_function.functionId;

    // this is to handle the tbname
    if (fmIsScanPseudoColumnFunc(functionId)) {
438
      setTbNameColData(pHandle->meta, pBlock, pColInfoData, functionId);
439
    } else {  // these are tags
wmmhello's avatar
wmmhello 已提交
440 441
      STagVal tagVal = {0};
      tagVal.cid = pExpr->base.pParam[0].pCol->colId;
442
      const char* p = metaGetTableTagVal(&mr.me, pColInfoData->info.type, &tagVal);
wmmhello's avatar
wmmhello 已提交
443

444 445 446 447
      char* data = NULL;
      if (pColInfoData->info.type != TSDB_DATA_TYPE_JSON && p != NULL) {
        data = tTagValToData((const STagVal*)p, false);
      } else {
wmmhello's avatar
wmmhello 已提交
448
        data = (char*)p;
wmmhello's avatar
wmmhello 已提交
449
      }
450

H
Haojun Liao 已提交
451 452 453
      bool isNullVal = (data == NULL) || (pColInfoData->info.type == TSDB_DATA_TYPE_JSON && tTagIsJsonNull(data));
      if (isNullVal) {
        colDataAppendNNULL(pColInfoData, 0, pBlock->info.rows);
H
Haojun Liao 已提交
454
      } else if (pColInfoData->info.type != TSDB_DATA_TYPE_JSON) {
H
Haojun Liao 已提交
455
        colDataAppendNItems(pColInfoData, 0, data, pBlock->info.rows);
L
Liu Jicong 已提交
456
      } else {  // todo opt for json tag
H
Haojun Liao 已提交
457
        for (int32_t i = 0; i < pBlock->info.rows; ++i) {
H
Haojun Liao 已提交
458
          colDataAppend(pColInfoData, i, data, false);
H
Haojun Liao 已提交
459
        }
460
      }
461

462 463
      if (data && (pColInfoData->info.type != TSDB_DATA_TYPE_JSON) && p != NULL &&
          IS_VAR_DATA_TYPE(((const STagVal*)p)->type)) {
wmmhello's avatar
wmmhello 已提交
464
        taosMemoryFree(data);
wmmhello's avatar
wmmhello 已提交
465
      }
466 467 468 469
    }
  }

  metaReaderClear(&mr);
H
Haojun Liao 已提交
470
  return TSDB_CODE_SUCCESS;
471 472
}

473 474 475 476
void setTbNameColData(void* pMeta, const SSDataBlock* pBlock, SColumnInfoData* pColInfoData, int32_t functionId) {
  struct SScalarFuncExecFuncs fpSet = {0};
  fmGetScalarFuncExecFuncs(functionId, &fpSet);

477 478
  SColumnInfoData infoData = createColumnInfoData(TSDB_DATA_TYPE_BIGINT, sizeof(uint64_t), 1);
  colInfoDataEnsureCapacity(&infoData, 1);
479

480
  colDataAppendInt64(&infoData, 0, (int64_t*)&pBlock->info.uid);
481
  SScalarParam srcParam = {.numOfRows = pBlock->info.rows, .param = pMeta, .columnData = &infoData};
482 483 484

  SScalarParam param = {.columnData = pColInfoData};
  fpSet.process(&srcParam, 1, &param);
D
dapan1121 已提交
485
  colDataDestroy(&infoData);
486 487
}

488
static SSDataBlock* doTableScanImpl(SOperatorInfo* pOperator) {
H
Haojun Liao 已提交
489
  STableScanInfo* pTableScanInfo = pOperator->info;
490
  SExecTaskInfo*  pTaskInfo = pOperator->pTaskInfo;
L
Liu Jicong 已提交
491
  SSDataBlock*    pBlock = pTableScanInfo->pResBlock;
H
Haojun Liao 已提交
492

493 494
  int64_t st = taosGetTimestampUs();

495
  while (tsdbNextDataBlock(pTableScanInfo->dataReader)) {
496 497
    if (isTaskKilled(pTaskInfo)) {
      longjmp(pTaskInfo->env, TSDB_CODE_TSC_QUERY_CANCELLED);
498
    }
H
Haojun Liao 已提交
499

500 501 502 503 504 505
    // process this data block based on the probabilities
    bool processThisBlock = processBlockWithProbability(&pTableScanInfo->sample);
    if (!processThisBlock) {
      continue;
    }

506 507 508 509 510 511 512 513
    blockDataCleanup(pBlock);

    SDataBlockInfo binfo = pBlock->info;
    tsdbRetrieveDataBlockInfo(pTableScanInfo->dataReader, &binfo);

    binfo.capacity = binfo.rows;
    blockDataEnsureCapacity(pBlock, binfo.rows);
    pBlock->info = binfo;
L
Liu Jicong 已提交
514
    ASSERT(binfo.uid != 0);
H
Haojun Liao 已提交
515

516 517 518 519 520
    uint64_t* groupId = taosHashGet(pTaskInfo->tableqinfoList.map, &pBlock->info.uid, sizeof(int64_t));
    if (groupId) {
      pBlock->info.groupId = *groupId;
    }

521 522 523 524 525 526
    uint32_t status = 0;
    int32_t  code = loadDataBlock(pOperator, pTableScanInfo, pBlock, &status);
    //    int32_t  code = loadDataBlockOnDemand(pOperator->pRuntimeEnv, pTableScanInfo, pBlock, &status);
    if (code != TSDB_CODE_SUCCESS) {
      longjmp(pOperator->pTaskInfo->env, code);
    }
527

528 529 530
    // current block is filter out according to filter condition, continue load the next block
    if (status == FUNC_DATA_REQUIRED_FILTEROUT || pBlock->info.rows == 0) {
      continue;
531
    }
532 533 534 535 536

    pOperator->resultInfo.totalRows = pTableScanInfo->readRecorder.totalRows;
    pTableScanInfo->readRecorder.elapsedTime += (taosGetTimestampUs() - st) / 1000.0;

    pOperator->cost.totalCost = pTableScanInfo->readRecorder.elapsedTime;
537 538

    // todo refactor
L
Liu Jicong 已提交
539 540 541 542 543
    /*pTableScanInfo->lastStatus.uid = pBlock->info.uid;*/
    /*pTableScanInfo->lastStatus.ts = pBlock->info.window.ekey;*/
    pTaskInfo->streamInfo.lastStatus.type = TMQ_OFFSET__SNAPSHOT_DATA;
    pTaskInfo->streamInfo.lastStatus.uid = pBlock->info.uid;
    pTaskInfo->streamInfo.lastStatus.ts = pBlock->info.window.ekey;
544

L
Liu Jicong 已提交
545
    ASSERT(pBlock->info.uid != 0);
546
    return pBlock;
H
Haojun Liao 已提交
547 548 549 550
  }
  return NULL;
}

wmmhello's avatar
wmmhello 已提交
551
static SSDataBlock* doTableScanGroup(SOperatorInfo* pOperator) {
H
Haojun Liao 已提交
552 553 554 555
  STableScanInfo* pTableScanInfo = pOperator->info;
  SExecTaskInfo*  pTaskInfo = pOperator->pTaskInfo;

  // The read handle is not initialized yet, since no qualified tables exists
556
  if (pTableScanInfo->dataReader == NULL || pOperator->status == OP_EXEC_DONE) {
H
Haojun Liao 已提交
557 558 559
    return NULL;
  }

560 561
  // do the ascending order traverse in the first place.
  while (pTableScanInfo->scanTimes < pTableScanInfo->scanInfo.numOfAsc) {
H
Haojun Liao 已提交
562 563 564 565
    SSDataBlock* p = doTableScanImpl(pOperator);
    if (p != NULL) {
      ASSERT(p->info.uid != 0);
      return p;
H
Haojun Liao 已提交
566 567
    }

568
    pTableScanInfo->scanTimes += 1;
569

570
    if (pTableScanInfo->scanTimes < pTableScanInfo->scanInfo.numOfAsc) {
571 572
      setTaskStatus(pTaskInfo, TASK_NOT_COMPLETED);
      pTableScanInfo->scanFlag = REPEAT_SCAN;
L
Liu Jicong 已提交
573 574 575 576
      qDebug(
          "%s start to repeat ascending order scan data SELECT last_row(*),hostname from cpu group by hostname;blocks "
          "due to query func required",
          GET_TASKID(pTaskInfo));
H
Haojun Liao 已提交
577

578
      // do prepare for the next round table scan operation
H
Haojun Liao 已提交
579
      tsdbReaderReset(pTableScanInfo->dataReader, &pTableScanInfo->cond);
H
Haojun Liao 已提交
580
    }
581
  }
H
Haojun Liao 已提交
582

583
  int32_t total = pTableScanInfo->scanInfo.numOfAsc + pTableScanInfo->scanInfo.numOfDesc;
584
  if (pTableScanInfo->scanTimes < total) {
585
    if (pTableScanInfo->cond.order == TSDB_ORDER_ASC) {
H
Haojun Liao 已提交
586 587
      prepareForDescendingScan(pTableScanInfo, pOperator->exprSupp.pCtx, 0);
      tsdbReaderReset(pTableScanInfo->dataReader, &pTableScanInfo->cond);
588
      qDebug("%s start to descending order scan data blocks due to query func required", GET_TASKID(pTaskInfo));
589
    }
H
Haojun Liao 已提交
590

591
    while (pTableScanInfo->scanTimes < total) {
H
Haojun Liao 已提交
592 593 594
      SSDataBlock* p = doTableScanImpl(pOperator);
      if (p != NULL) {
        return p;
595
      }
H
Haojun Liao 已提交
596

597
      pTableScanInfo->scanTimes += 1;
H
Haojun Liao 已提交
598

599
      if (pTableScanInfo->scanTimes < total) {
600 601
        setTaskStatus(pTaskInfo, TASK_NOT_COMPLETED);
        pTableScanInfo->scanFlag = REPEAT_SCAN;
H
Haojun Liao 已提交
602

603 604
        qDebug("%s start to repeat descending order scan data blocks due to query func required",
               GET_TASKID(pTaskInfo));
H
Haojun Liao 已提交
605
        tsdbReaderReset(pTableScanInfo->dataReader, &pTableScanInfo->cond);
606
      }
H
Haojun Liao 已提交
607 608 609
    }
  }

wmmhello's avatar
wmmhello 已提交
610 611 612 613 614 615 616
  return NULL;
}

static SSDataBlock* doTableScan(SOperatorInfo* pOperator) {
  STableScanInfo* pInfo = pOperator->info;
  SExecTaskInfo*  pTaskInfo = pOperator->pTaskInfo;

L
Liu Jicong 已提交
617 618
  // if scan table by table
  if (pInfo->scanMode == TABLE_SCAN__TABLE_ORDER) {
L
Liu Jicong 已提交
619
    if (pInfo->noTable) return NULL;
L
Liu Jicong 已提交
620
    while (1) {
L
Liu Jicong 已提交
621 622 623 624 625 626 627 628 629 630 631
      SSDataBlock* result = doTableScanGroup(pOperator);
      if (result) {
        return result;
      }
      // if no data, switch to next table and continue scan
      pInfo->currentTable++;
      if (pInfo->currentTable >= taosArrayGetSize(pTaskInfo->tableqinfoList.pTableList)) {
        return NULL;
      }
      STableKeyInfo* pTableInfo = taosArrayGet(pTaskInfo->tableqinfoList.pTableList, pInfo->currentTable);
      tsdbSetTableId(pInfo->dataReader, pTableInfo->uid);
H
Haojun Liao 已提交
632
      tsdbReaderReset(pInfo->dataReader, &pInfo->cond);
L
Liu Jicong 已提交
633 634 635 636
      pInfo->scanTimes = 0;
    }
  }

637
  if (pInfo->currentGroupId == -1) {
wmmhello's avatar
wmmhello 已提交
638
    pInfo->currentGroupId++;
wmmhello's avatar
wmmhello 已提交
639
    if (pInfo->currentGroupId >= taosArrayGetSize(pTaskInfo->tableqinfoList.pGroupList)) {
wmmhello's avatar
wmmhello 已提交
640
      setTaskStatus(pTaskInfo, TASK_COMPLETED);
wmmhello's avatar
wmmhello 已提交
641 642
      return NULL;
    }
H
Haojun Liao 已提交
643

644
    SArray* tableList = taosArrayGetP(pTaskInfo->tableqinfoList.pGroupList, pInfo->currentGroupId);
H
Haojun Liao 已提交
645 646 647

    tsdbReaderClose(pInfo->dataReader);

648 649
    int32_t code = tsdbReaderOpen(pInfo->readHandle.vnode, &pInfo->cond, tableList, (STsdbReader**)&pInfo->dataReader,
                                  GET_TASKID(pTaskInfo));
650 651 652 653
    if (code != TSDB_CODE_SUCCESS) {
      longjmp(pTaskInfo->env, code);
      return NULL;
    }
wmmhello's avatar
wmmhello 已提交
654 655 656
  }

  SSDataBlock* result = doTableScanGroup(pOperator);
657
  if (result) {
wmmhello's avatar
wmmhello 已提交
658 659 660 661 662
    return result;
  }

  pInfo->currentGroupId++;
  if (pInfo->currentGroupId >= taosArrayGetSize(pTaskInfo->tableqinfoList.pGroupList)) {
wmmhello's avatar
wmmhello 已提交
663
    setTaskStatus(pTaskInfo, TASK_COMPLETED);
wmmhello's avatar
wmmhello 已提交
664 665 666
    return NULL;
  }

667
  SArray* tableList = taosArrayGetP(pTaskInfo->tableqinfoList.pGroupList, pInfo->currentGroupId);
668
  //  tsdbSetTableList(pInfo->dataReader, tableList);
wmmhello's avatar
wmmhello 已提交
669

H
Haojun Liao 已提交
670
  tsdbReaderReset(pInfo->dataReader, &pInfo->cond);
wmmhello's avatar
wmmhello 已提交
671 672 673
  pInfo->scanTimes = 0;

  result = doTableScanGroup(pOperator);
674
  if (result) {
wmmhello's avatar
wmmhello 已提交
675 676 677
    return result;
  }

678 679
  setTaskStatus(pTaskInfo, TASK_COMPLETED);
  return NULL;
H
Haojun Liao 已提交
680 681
}

682 683
static int32_t getTableScannerExecInfo(struct SOperatorInfo* pOptr, void** pOptrExplain, uint32_t* len) {
  SFileBlockLoadRecorder* pRecorder = taosMemoryCalloc(1, sizeof(SFileBlockLoadRecorder));
684
  STableScanInfo*         pTableScanInfo = pOptr->info;
685 686 687 688 689 690
  *pRecorder = pTableScanInfo->readRecorder;
  *pOptrExplain = pRecorder;
  *len = sizeof(SFileBlockLoadRecorder);
  return 0;
}

691 692
static void destroyTableScanOperatorInfo(void* param, int32_t numOfOutput) {
  STableScanInfo* pTableScanInfo = (STableScanInfo*)param;
H
Haojun Liao 已提交
693
  blockDataDestroy(pTableScanInfo->pResBlock);
694
  cleanupQueryTableDataCond(&pTableScanInfo->cond);
H
Haojun Liao 已提交
695

H
refact  
Hongze Cheng 已提交
696
  tsdbReaderClose(pTableScanInfo->dataReader);
697 698 699 700

  if (pTableScanInfo->pColMatchInfo != NULL) {
    taosArrayDestroy(pTableScanInfo->pColMatchInfo);
  }
L
Liu Jicong 已提交
701

702
  cleanupExprSupp(&pTableScanInfo->pseudoSup);
D
dapan1121 已提交
703
  taosMemoryFreeClear(param);
704 705
}

wmmhello's avatar
wmmhello 已提交
706
SOperatorInfo* createTableScanOperatorInfo(STableScanPhysiNode* pTableScanNode, SReadHandle* readHandle,
707
                                           SExecTaskInfo* pTaskInfo) {
H
Haojun Liao 已提交
708 709 710
  STableScanInfo* pInfo = taosMemoryCalloc(1, sizeof(STableScanInfo));
  SOperatorInfo*  pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
  if (pInfo == NULL || pOperator == NULL) {
711
    goto _error;
H
Haojun Liao 已提交
712 713
  }

714
  SDataBlockDescNode* pDescNode = pTableScanNode->scan.node.pOutputDataBlockDesc;
715
  int32_t             numOfCols = 0;
716
  SArray* pColList = extractColMatchInfo(pTableScanNode->scan.pScanCols, pDescNode, &numOfCols, COL_MATCH_FROM_COL_ID);
L
Liu Jicong 已提交
717

718 719
  int32_t code = initQueryTableDataCond(&pInfo->cond, pTableScanNode);
  if (code != TSDB_CODE_SUCCESS) {
720
    goto _error;
721 722 723
  }

  if (pTableScanNode->scan.pScanPseudoCols != NULL) {
724
    SExprSupp* pSup = &pInfo->pseudoSup;
725 726
    pSup->pExprInfo = createExprInfo(pTableScanNode->scan.pScanPseudoCols, NULL, &pSup->numOfExprs);
    pSup->pCtx = createSqlFunctionCtx(pSup->pExprInfo, pSup->numOfExprs, &pSup->rowEntryInfoOffset);
727 728
  }

729
  pInfo->scanInfo = (SScanInfo){.numOfAsc = pTableScanNode->scanSeq[0], .numOfDesc = pTableScanNode->scanSeq[1]};
730
  pInfo->pdInfo.interval = extractIntervalInfo(pTableScanNode);
731 732 733
  pInfo->readHandle = *readHandle;
  pInfo->sample.sampleRatio = pTableScanNode->ratio;
  pInfo->sample.seed = taosGetTimestampSec();
734

735
  pInfo->dataBlockLoadFlag = pTableScanNode->dataRequired;
736 737 738 739
  pInfo->pResBlock = createResDataBlock(pDescNode);
  pInfo->pFilterNode = pTableScanNode->scan.node.pConditions;
  pInfo->scanFlag = MAIN_SCAN;
  pInfo->pColMatchInfo = pColList;
wmmhello's avatar
wmmhello 已提交
740
  pInfo->currentGroupId = -1;
741
  pInfo->assignBlockUid = pTableScanNode->assignBlockUid;
742 743

  pOperator->name = "TableScanOperator";  // for debug purpose
L
Liu Jicong 已提交
744
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_TABLE_SCAN;
745 746 747
  pOperator->blocking = false;
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
748
  pOperator->exprSupp.numOfExprs = numOfCols;
749
  pOperator->pTaskInfo = pTaskInfo;
750

751 752
  pOperator->fpSet = createOperatorFpSet(operatorDummyOpenFn, doTableScan, NULL, NULL, destroyTableScanOperatorInfo,
                                         NULL, NULL, getTableScannerExecInfo);
753 754 755

  // for non-blocking operator, the open cost is always 0
  pOperator->cost.openCost = 0;
H
Haojun Liao 已提交
756
  return pOperator;
757

758
_error:
759 760 761 762 763
  taosMemoryFreeClear(pInfo);
  taosMemoryFreeClear(pOperator);

  pTaskInfo->code = TSDB_CODE_QRY_OUT_OF_MEMORY;
  return NULL;
H
Haojun Liao 已提交
764 765
}

766
SOperatorInfo* createTableSeqScanOperatorInfo(void* pReadHandle, SExecTaskInfo* pTaskInfo) {
H
Haojun Liao 已提交
767
  STableScanInfo* pInfo = taosMemoryCalloc(1, sizeof(STableScanInfo));
L
Liu Jicong 已提交
768
  SOperatorInfo*  pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
769

L
Liu Jicong 已提交
770 771
  pInfo->dataReader = pReadHandle;
  //  pInfo->prevGroupId       = -1;
H
Haojun Liao 已提交
772

773
  pOperator->name = "TableSeqScanOperator";
H
Haojun Liao 已提交
774
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_TABLE_SEQ_SCAN;
775 776 777 778
  pOperator->blocking = false;
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
  pOperator->pTaskInfo = pTaskInfo;
H
Haojun Liao 已提交
779

780
  pOperator->fpSet = createOperatorFpSet(operatorDummyOpenFn, doTableScanImpl, NULL, NULL, NULL, NULL, NULL, NULL);
H
Haojun Liao 已提交
781 782 783
  return pOperator;
}

H
Haojun Liao 已提交
784 785
static int32_t doGetTableRowSize(void* pMeta, uint64_t uid, int32_t* rowLen, const char* idstr) {
  *rowLen = 0;
H
Haojun Liao 已提交
786

787
  SMetaReader mr = {0};
788
  metaReaderInit(&mr, pMeta, 0);
H
Haojun Liao 已提交
789 790
  int32_t code = metaGetTableEntryByUid(&mr, uid);
  if (code != TSDB_CODE_SUCCESS) {
L
Liu Jicong 已提交
791
    qError("failed to get table meta, uid:0x%" PRIx64 ", code:%s, %s", uid, tstrerror(terrno), idstr);
H
Haojun Liao 已提交
792 793 794 795
    metaReaderClear(&mr);
    return terrno;
  }

796 797
  if (mr.me.type == TSDB_SUPER_TABLE) {
    int32_t numOfCols = mr.me.stbEntry.schemaRow.nCols;
798
    for (int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
799
      (*rowLen) += mr.me.stbEntry.schemaRow.pSchema[i].bytes;
800 801 802
    }
  } else if (mr.me.type == TSDB_CHILD_TABLE) {
    uint64_t suid = mr.me.ctbEntry.suid;
803
    tDecoderClear(&mr.coder);
H
Haojun Liao 已提交
804 805
    code = metaGetTableEntryByUid(&mr, suid);
    if (code != TSDB_CODE_SUCCESS) {
L
Liu Jicong 已提交
806
      qError("failed to get table meta, uid:0x%" PRIx64 ", code:%s, %s", suid, tstrerror(terrno), idstr);
H
Haojun Liao 已提交
807 808 809 810
      metaReaderClear(&mr);
      return terrno;
    }

811 812
    int32_t numOfCols = mr.me.stbEntry.schemaRow.nCols;

813
    for (int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
814
      (*rowLen) += mr.me.stbEntry.schemaRow.pSchema[i].bytes;
815 816 817
    }
  } else if (mr.me.type == TSDB_NORMAL_TABLE) {
    int32_t numOfCols = mr.me.ntbEntry.schemaRow.nCols;
818
    for (int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
819
      (*rowLen) += mr.me.ntbEntry.schemaRow.pSchema[i].bytes;
820 821 822 823
    }
  }

  metaReaderClear(&mr);
H
Haojun Liao 已提交
824
  return TSDB_CODE_SUCCESS;
825 826 827 828 829 830 831 832
}

static SSDataBlock* doBlockInfoScan(SOperatorInfo* pOperator) {
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

  SBlockDistInfo* pBlockScanInfo = pOperator->info;
L
Liu Jicong 已提交
833
  SExecTaskInfo*  pTaskInfo = pOperator->pTaskInfo;
834 835

  STableBlockDistInfo blockDistInfo = {.minRows = INT_MAX, .maxRows = INT_MIN};
L
Liu Jicong 已提交
836 837
  int32_t code = doGetTableRowSize(pBlockScanInfo->readHandle.meta, pBlockScanInfo->uid, &blockDistInfo.rowSize,
                                   GET_TASKID(pTaskInfo));
H
Haojun Liao 已提交
838
  if (code != TSDB_CODE_SUCCESS) {
L
Liu Jicong 已提交
839
    longjmp(pTaskInfo->env, code);
H
Haojun Liao 已提交
840
  }
841 842 843

  tsdbGetFileBlocksDistInfo(pBlockScanInfo->pHandle, &blockDistInfo);
  blockDistInfo.numOfInmemRows = (int32_t)tsdbGetNumOfRowsInMemTable(pBlockScanInfo->pHandle);
H
Haojun Liao 已提交
844

845
  SSDataBlock* pBlock = pBlockScanInfo->pResBlock;
H
Haojun Liao 已提交
846

847
  int32_t          slotId = pOperator->exprSupp.pExprInfo->base.resSchema.slotId;
848
  SColumnInfoData* pColInfo = taosArrayGet(pBlock->pDataBlock, slotId);
H
Haojun Liao 已提交
849

850
  int32_t len = tSerializeBlockDistInfo(NULL, 0, &blockDistInfo);
851
  char*   p = taosMemoryCalloc(1, len + VARSTR_HEADER_SIZE);
852 853 854
  tSerializeBlockDistInfo(varDataVal(p), len, &blockDistInfo);
  varDataSetLen(p, len);

855
  blockDataEnsureCapacity(pBlock, 1);
856 857
  colDataAppend(pColInfo, 0, p, false);
  taosMemoryFree(p);
H
Haojun Liao 已提交
858

859 860
  pBlock->info.rows = 1;

H
Haojun Liao 已提交
861 862 863 864
  pOperator->status = OP_EXEC_DONE;
  return pBlock;
}

865
static void destroyBlockDistScanOperatorInfo(void* param, int32_t numOfOutput) {
866
  SBlockDistInfo* pDistInfo = (SBlockDistInfo*)param;
867
  blockDataDestroy(pDistInfo->pResBlock);
H
Hongze Cheng 已提交
868
  tsdbReaderClose(pDistInfo->pHandle);
D
dapan1121 已提交
869
  taosMemoryFreeClear(param);
870 871
}

872 873
SOperatorInfo* createDataBlockInfoScanOperator(void* dataReader, SReadHandle* readHandle, uint64_t uid,
                                               SBlockDistScanPhysiNode* pBlockScanNode, SExecTaskInfo* pTaskInfo) {
874
  SBlockDistInfo* pInfo = taosMemoryCalloc(1, sizeof(SBlockDistInfo));
875
  SOperatorInfo*  pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
876 877 878 879 880
  if (pInfo == NULL || pOperator == NULL) {
    pTaskInfo->code = TSDB_CODE_OUT_OF_MEMORY;
    goto _error;
  }

881
  pInfo->pHandle = dataReader;
882
  pInfo->readHandle = *readHandle;
883 884
  pInfo->uid = uid;
  pInfo->pResBlock = createResDataBlock(pBlockScanNode->node.pOutputDataBlockDesc);
885

886
  int32_t    numOfCols = 0;
887
  SExprInfo* pExprInfo = createExprInfo(pBlockScanNode->pScanPseudoCols, NULL, &numOfCols);
888
  int32_t    code = initExprSupp(&pOperator->exprSupp, pExprInfo, numOfCols);
889 890 891
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
H
Haojun Liao 已提交
892

893
  pOperator->name = "DataBlockDistScanOperator";
894
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_BLOCK_DIST_SCAN;
895 896 897
  pOperator->blocking = false;
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
898 899 900 901
  pOperator->pTaskInfo = pTaskInfo;

  pOperator->fpSet = createOperatorFpSet(operatorDummyOpenFn, doBlockInfoScan, NULL, NULL,
                                         destroyBlockDistScanOperatorInfo, NULL, NULL, NULL);
H
Haojun Liao 已提交
902 903
  return pOperator;

904
_error:
H
Haojun Liao 已提交
905 906 907 908 909
  taosMemoryFreeClear(pInfo);
  taosMemoryFreeClear(pOperator);
  return NULL;
}

910
static void doClearBufferedBlocks(SStreamScanInfo* pInfo) {
H
Haojun Liao 已提交
911 912 913 914 915 916 917 918 919 920
  size_t total = taosArrayGetSize(pInfo->pBlockLists);

  pInfo->validBlockIndex = 0;
  for (int32_t i = 0; i < total; ++i) {
    SSDataBlock* p = taosArrayGetP(pInfo->pBlockLists, i);
    blockDataDestroy(p);
  }
  taosArrayClear(pInfo->pBlockLists);
}

921
static bool isSessionWindow(SStreamScanInfo* pInfo) {
L
Liu Jicong 已提交
922 923
  return pInfo->sessionSup.parentType == QUERY_NODE_PHYSICAL_PLAN_STREAM_SESSION ||
         pInfo->sessionSup.parentType == QUERY_NODE_PHYSICAL_PLAN_STREAM_SESSION;
5
54liuyao 已提交
924 925
}

926
static bool isStateWindow(SStreamScanInfo* pInfo) {
927
  return pInfo->sessionSup.parentType == QUERY_NODE_PHYSICAL_PLAN_STREAM_STATE;
5
54liuyao 已提交
928
}
5
54liuyao 已提交
929

L
Liu Jicong 已提交
930 931
static bool isIntervalWindow(SStreamScanInfo* pInfo) {
  return pInfo->sessionSup.parentType == QUERY_NODE_PHYSICAL_PLAN_STREAM_INTERVAL ||
5
54liuyao 已提交
932 933 934 935 936 937
         pInfo->sessionSup.parentType == QUERY_NODE_PHYSICAL_PLAN_STREAM_SEMI_INTERVAL ||
         pInfo->sessionSup.parentType == QUERY_NODE_PHYSICAL_PLAN_STREAM_FINAL_INTERVAL;
}

static bool isSignleIntervalWindow(SStreamScanInfo* pInfo) {
  return pInfo->sessionSup.parentType == QUERY_NODE_PHYSICAL_PLAN_STREAM_INTERVAL;
L
Liu Jicong 已提交
938 939
}

940 941 942 943
static bool isSlidingWindow(SStreamScanInfo* pInfo) {
  return isIntervalWindow(pInfo) && pInfo->interval.interval != pInfo->interval.sliding;
}

944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964
static uint64_t getGroupId(SOperatorInfo* pOperator, uint64_t uid) {
  uint64_t* groupId = taosHashGet(pOperator->pTaskInfo->tableqinfoList.map, &uid, sizeof(int64_t));
  if (groupId) {
    return *groupId;
  }
  return 0;
  /* Todo(liuyao) for partition by column
  recordNewGroupKeys(pTableScanInfo->pGroupCols, pTableScanInfo->pGroupColVals, pBlock, rowId);
  int32_t len = buildGroupKeys(pTableScanInfo->keyBuf, pTableScanInfo->pGroupColVals);
  uint64_t resId = 0;
  uint64_t* groupId = taosHashGet(pTableScanInfo->pGroupSet, pTableScanInfo->keyBuf, len);
  if (groupId) {
    return *groupId;
  } else if (len != 0) {
    resId = calcGroupId(pTableScanInfo->keyBuf, len);
    taosHashPut(pTableScanInfo->pGroupSet, pTableScanInfo->keyBuf, len, &resId, sizeof(uint64_t));
  }
  return resId;
  */
}

965
static void setGroupId(SStreamScanInfo* pInfo, SSDataBlock* pBlock, int32_t groupColIndex, int32_t rowIndex) {
966 967
  SColumnInfoData* pColInfo = taosArrayGet(pBlock->pDataBlock, groupColIndex);
  uint64_t*        groupCol = (uint64_t*)pColInfo->pData;
968
  ASSERT(rowIndex < pBlock->info.rows);
969
  pInfo->groupId = groupCol[rowIndex];
970 971
}

L
Liu Jicong 已提交
972
void resetTableScanInfo(STableScanInfo* pTableScanInfo, STimeWindow* pWin) {
H
Haojun Liao 已提交
973
  pTableScanInfo->cond.twindows = *pWin;
L
Liu Jicong 已提交
974 975 976 977 978 979 980 981 982 983 984 985 986 987 988
  pTableScanInfo->scanTimes = 0;
  pTableScanInfo->currentGroupId = -1;
}

static bool prepareRangeScan(SStreamScanInfo* pInfo, SSDataBlock* pBlock, int32_t* pRowIndex) {
  if ((*pRowIndex) == pBlock->info.rows) {
    return false;
  }

  ASSERT(taosArrayGetSize(pBlock->pDataBlock) >= 3);
  SColumnInfoData* pStartTsCol = taosArrayGet(pBlock->pDataBlock, START_TS_COLUMN_INDEX);
  TSKEY*           startData = (TSKEY*)pStartTsCol->pData;
  SColumnInfoData* pEndTsCol = taosArrayGet(pBlock->pDataBlock, END_TS_COLUMN_INDEX);
  TSKEY*           endData = (TSKEY*)pEndTsCol->pData;
  STimeWindow      win = {.skey = startData[*pRowIndex], .ekey = endData[*pRowIndex]};
989 990 991 992 993 994

  SColumnInfoData* pCalStartTsCol = taosArrayGet(pBlock->pDataBlock, CALCULATE_START_TS_COLUMN_INDEX);
  TSKEY*           calStartData = (TSKEY*)pCalStartTsCol->pData;
  SColumnInfoData* pCalEndTsCol = taosArrayGet(pBlock->pDataBlock, CALCULATE_END_TS_COLUMN_INDEX);
  TSKEY*           calEndData = (TSKEY*)pCalEndTsCol->pData;

L
Liu Jicong 已提交
995
  setGroupId(pInfo, pBlock, GROUPID_COLUMN_INDEX, *pRowIndex);
996 997 998 999
  if (isSlidingWindow(pInfo)) {
    pInfo->updateWin.skey = calStartData[*pRowIndex];
    pInfo->updateWin.ekey = calEndData[*pRowIndex];
  }
L
Liu Jicong 已提交
1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010
  (*pRowIndex)++;

  for (; *pRowIndex < pBlock->info.rows; (*pRowIndex)++) {
    if (win.skey == startData[*pRowIndex]) {
      win.ekey = TMAX(win.ekey, endData[*pRowIndex]);
      continue;
    }
    if (win.skey == endData[*pRowIndex]) {
      win.skey = TMIN(win.skey, startData[*pRowIndex]);
      continue;
    }
1011 1012
    ASSERT(!(win.skey > startData[*pRowIndex] && win.ekey < endData[*pRowIndex]) ||
           !(isInTimeWindow(&win, startData[*pRowIndex], 0) || isInTimeWindow(&win, endData[*pRowIndex], 0)));
L
Liu Jicong 已提交
1013 1014 1015 1016
    break;
  }

  resetTableScanInfo(pInfo->pTableScanOp->info, &win);
1017
  pInfo->pTableScanOp->status = OP_OPENED;
L
Liu Jicong 已提交
1018 1019 1020
  return true;
}

1021 1022 1023
static STimeWindow getSlidingWindow(TSKEY* tsCol, SInterval* pInterval, SDataBlockInfo* pDataBlockInfo,
                                    int32_t* pRowIndex) {
  SResultRowInfo dumyInfo;
5
54liuyao 已提交
1024
  dumyInfo.cur.pageId = -1;
1025
  STimeWindow win = getActiveTimeWindow(NULL, &dumyInfo, tsCol[*pRowIndex], pInterval, TSDB_ORDER_ASC);
5
54liuyao 已提交
1026 1027 1028
  STimeWindow endWin = win;
  STimeWindow preWin = win;
  while (1) {
1029 1030
    (*pRowIndex) += getNumOfRowsInTimeWindow(pDataBlockInfo, tsCol, *pRowIndex, endWin.ekey, binarySearchForKey, NULL,
                                             TSDB_ORDER_ASC);
5
54liuyao 已提交
1031 1032 1033 1034 1035
    do {
      preWin = endWin;
      getNextTimeWindow(pInterval, &endWin, TSDB_ORDER_ASC);
    } while (tsCol[(*pRowIndex) - 1] >= endWin.skey);
    endWin = preWin;
1036
    if (win.ekey == endWin.ekey || (*pRowIndex) == pDataBlockInfo->rows) {
5
54liuyao 已提交
1037 1038 1039 1040 1041 1042
      win.ekey = endWin.ekey;
      return win;
    }
    win.ekey = endWin.ekey;
  }
}
5
54liuyao 已提交
1043

L
Liu Jicong 已提交
1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054
static SSDataBlock* doRangeScan(SStreamScanInfo* pInfo, SSDataBlock* pSDB, int32_t tsColIndex, int32_t* pRowIndex) {
  while (1) {
    SSDataBlock* pResult = NULL;
    pResult = doTableScan(pInfo->pTableScanOp);
    if (!pResult && prepareRangeScan(pInfo, pSDB, pRowIndex)) {
      // scan next window data
      pResult = doTableScan(pInfo->pTableScanOp);
    }
    if (!pResult) {
      blockDataCleanup(pSDB);
      *pRowIndex = 0;
5
54liuyao 已提交
1055
      pInfo->updateWin = (STimeWindow){.skey = INT64_MIN, .ekey = INT64_MAX};
H
Hongze Cheng 已提交
1056 1057 1058
      STableScanInfo* pTableScanInfo = pInfo->pTableScanOp->info;
      tsdbReaderClose(pTableScanInfo->dataReader);
      pTableScanInfo->dataReader = NULL;
1059 1060
      return NULL;
    }
L
Liu Jicong 已提交
1061

1062
    if (pResult->info.groupId == pInfo->groupId) {
5
54liuyao 已提交
1063
      pResult->info.calWin = pInfo->updateWin;
1064
      return pResult;
5
54liuyao 已提交
1065 1066
    }
  }
1067
}
1068

1069 1070 1071
static int32_t generateSessionScanRange(SStreamScanInfo* pInfo, SSDataBlock* pSrcBlock, SSDataBlock* pDestBlock) {
  if (pSrcBlock->info.rows == 0) {
    return TSDB_CODE_SUCCESS;
1072
  }
1073 1074
  blockDataCleanup(pDestBlock);
  int32_t code = blockDataEnsureCapacity(pDestBlock, pSrcBlock->info.rows);
1075
  if (code != TSDB_CODE_SUCCESS) {
1076
    return code;
L
Liu Jicong 已提交
1077
  }
1078 1079
  ASSERT(taosArrayGetSize(pSrcBlock->pDataBlock) >= 3);
  SColumnInfoData* pStartTsCol = taosArrayGet(pSrcBlock->pDataBlock, START_TS_COLUMN_INDEX);
L
Liu Jicong 已提交
1080
  TSKEY*           startData = (TSKEY*)pStartTsCol->pData;
1081
  SColumnInfoData* pEndTsCol = taosArrayGet(pSrcBlock->pDataBlock, END_TS_COLUMN_INDEX);
L
Liu Jicong 已提交
1082
  TSKEY*           endData = (TSKEY*)pEndTsCol->pData;
1083 1084
  SColumnInfoData* pUidCol = taosArrayGet(pSrcBlock->pDataBlock, UID_COLUMN_INDEX);
  uint64_t*        uidCol = (uint64_t*)pUidCol->pData;
L
Liu Jicong 已提交
1085

1086 1087 1088
  SColumnInfoData* pDestStartCol = taosArrayGet(pDestBlock->pDataBlock, START_TS_COLUMN_INDEX);
  SColumnInfoData* pDestEndCol = taosArrayGet(pDestBlock->pDataBlock, END_TS_COLUMN_INDEX);
  SColumnInfoData* pDestGpCol = taosArrayGet(pDestBlock->pDataBlock, GROUPID_COLUMN_INDEX);
L
Liu Jicong 已提交
1089
  int32_t          dummy = 0;
1090 1091
  for (int32_t i = 0; i < pSrcBlock->info.rows; i++) {
    uint64_t groupId = getGroupId(pInfo->pTableScanOp, uidCol[i]);
L
Liu Jicong 已提交
1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104
    // gap must be 0.
    SResultWindowInfo* pStartWin =
        getCurSessionWindow(pInfo->sessionSup.pStreamAggSup, startData[i], endData[i], groupId, 0, &dummy);
    if (!pStartWin) {
      // window has been closed.
      continue;
    }
    SResultWindowInfo* pEndWin =
        getCurSessionWindow(pInfo->sessionSup.pStreamAggSup, endData[i], endData[i], groupId, 0, &dummy);
    ASSERT(pEndWin);
    colDataAppend(pDestStartCol, i, (const char*)&pStartWin->win.skey, false);
    colDataAppend(pDestEndCol, i, (const char*)&pEndWin->win.ekey, false);
    colDataAppend(pDestGpCol, i, (const char*)&groupId, false);
1105
    pDestBlock->info.rows++;
L
Liu Jicong 已提交
1106
  }
1107
  return TSDB_CODE_SUCCESS;
L
Liu Jicong 已提交
1108
}
1109 1110 1111 1112 1113 1114

static int32_t generateIntervalScanRange(SStreamScanInfo* pInfo, SSDataBlock* pSrcBlock, SSDataBlock* pDestBlock) {
  blockDataCleanup(pDestBlock);
  int32_t rows = pSrcBlock->info.rows;
  if (rows == 0) {
    return TSDB_CODE_SUCCESS;
1115
  }
1116 1117 1118 1119 1120 1121 1122
  int32_t code = blockDataEnsureCapacity(pDestBlock, rows);
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

  SColumnInfoData* pTsCol = (SColumnInfoData*)taosArrayGet(pSrcBlock->pDataBlock, START_TS_COLUMN_INDEX);
  SColumnInfoData* pUidCol = taosArrayGet(pSrcBlock->pDataBlock, UID_COLUMN_INDEX);
1123
  uint64_t*        uidCol = (uint64_t*)pUidCol->pData;
1124
  ASSERT(pTsCol->info.type == TSDB_DATA_TYPE_TIMESTAMP);
1125
  TSKEY*           tsCol = (TSKEY*)pTsCol->pData;
1126 1127 1128 1129 1130
  SColumnInfoData* pStartTsCol = taosArrayGet(pDestBlock->pDataBlock, START_TS_COLUMN_INDEX);
  SColumnInfoData* pEndTsCol = taosArrayGet(pDestBlock->pDataBlock, END_TS_COLUMN_INDEX);
  SColumnInfoData* pGpCol = taosArrayGet(pDestBlock->pDataBlock, GROUPID_COLUMN_INDEX);
  SColumnInfoData* pCalStartTsCol = taosArrayGet(pDestBlock->pDataBlock, CALCULATE_START_TS_COLUMN_INDEX);
  SColumnInfoData* pCalEndTsCol = taosArrayGet(pDestBlock->pDataBlock, CALCULATE_END_TS_COLUMN_INDEX);
1131 1132
  uint64_t         groupId = getGroupId(pInfo->pTableScanOp, uidCol[0]);
  for (int32_t i = 0; i < rows;) {
1133 1134 1135 1136 1137 1138 1139 1140
    colDataAppend(pCalStartTsCol, pDestBlock->info.rows, (const char*)(tsCol + i), false);
    STimeWindow win = getSlidingWindow(tsCol, &pInfo->interval, &pSrcBlock->info, &i);
    colDataAppend(pCalEndTsCol, pDestBlock->info.rows, (const char*)(tsCol + i - 1), false);

    colDataAppend(pStartTsCol, pDestBlock->info.rows, (const char*)(&win.skey), false);
    colDataAppend(pEndTsCol, pDestBlock->info.rows, (const char*)(&win.ekey), false);
    colDataAppend(pGpCol, pDestBlock->info.rows, (const char*)(&groupId), false);
    pDestBlock->info.rows++;
5
54liuyao 已提交
1141
  }
1142 1143 1144 1145
  // all rows have same group id
  pDestBlock->info.groupId = groupId;
  return TSDB_CODE_SUCCESS;
}
1146

1147 1148 1149 1150 1151 1152
static int32_t generateScanRange(SStreamScanInfo* pInfo, SSDataBlock* pSrcBlock, SSDataBlock* pDestBlock) {
  int32_t code = TSDB_CODE_SUCCESS;
  if (isIntervalWindow(pInfo)) {
    code = generateIntervalScanRange(pInfo, pSrcBlock, pDestBlock);
  } else {
    code = generateSessionScanRange(pInfo, pSrcBlock, pDestBlock);
1153
  }
1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166
  pDestBlock->info.type = STREAM_CLEAR;
  blockDataUpdateTsWindow(pDestBlock, 0);
  return code;
}

void appendOneRow(SSDataBlock* pBlock, TSKEY* pStartTs, TSKEY* pEndTs, uint64_t* pUid) {
  SColumnInfoData* pStartTsCol = taosArrayGet(pBlock->pDataBlock, START_TS_COLUMN_INDEX);
  SColumnInfoData* pEndTsCol = taosArrayGet(pBlock->pDataBlock, END_TS_COLUMN_INDEX);
  SColumnInfoData* pUidCol = taosArrayGet(pBlock->pDataBlock, UID_COLUMN_INDEX);
  colDataAppend(pStartTsCol, pBlock->info.rows, (const char*)pStartTs, false);
  colDataAppend(pEndTsCol, pBlock->info.rows, (const char*)pEndTs, false);
  colDataAppend(pUidCol, pBlock->info.rows, (const char*)pUid, false);
  pBlock->info.rows++;
5
54liuyao 已提交
1167 1168
}

1169
static void checkUpdateData(SStreamScanInfo* pInfo, bool invertible, SSDataBlock* pBlock, bool out) {
1170 1171 1172 1173
  if (out) {
    blockDataCleanup(pInfo->pUpdateDataRes);
    blockDataEnsureCapacity(pInfo->pUpdateDataRes, pBlock->info.rows);
  }
1174 1175
  SColumnInfoData* pColDataInfo = taosArrayGet(pBlock->pDataBlock, pInfo->primaryTsIndex);
  ASSERT(pColDataInfo->info.type == TSDB_DATA_TYPE_TIMESTAMP);
5
54liuyao 已提交
1176
  TSKEY* tsCol = (TSKEY*)pColDataInfo->pData;
1177
  for (int32_t rowId = 0; rowId < pBlock->info.rows; rowId++) {
5
54liuyao 已提交
1178 1179
    SResultRowInfo dumyInfo;
    dumyInfo.cur.pageId = -1;
L
Liu Jicong 已提交
1180
    bool        isClosed = false;
5
54liuyao 已提交
1181 1182 1183 1184 1185
    STimeWindow win = {.skey = INT64_MIN, .ekey = INT64_MAX};
    if (isOverdue(tsCol[rowId], &pInfo->twAggSup)) {
      win = getActiveTimeWindow(NULL, &dumyInfo, tsCol[rowId], &pInfo->interval, TSDB_ORDER_ASC);
      isClosed = isCloseWindow(&win, &pInfo->twAggSup);
    }
L
Liu Jicong 已提交
1186
    bool inserted = updateInfoIsTableInserted(pInfo->pUpdateInfo, pBlock->info.uid);
5
54liuyao 已提交
1187 1188
    // must check update info first.
    bool update = updateInfoIsUpdated(pInfo->pUpdateInfo, pBlock->info.uid, tsCol[rowId]);
L
Liu Jicong 已提交
1189 1190 1191
    bool closedWin = isClosed && inserted && isSignleIntervalWindow(pInfo) &&
                     isDeletedWindow(&win, pBlock->info.groupId, pInfo->sessionSup.pIntervalAggSup);
    if ((update || closedWin) && out) {
1192
      appendOneRow(pInfo->pUpdateDataRes, tsCol + rowId, tsCol + rowId, &pBlock->info.uid);
1193 1194
    }
  }
1195 1196 1197 1198
  if (out) {
    blockDataUpdateTsWindow(pInfo->pUpdateDataRes, 0);
    pInfo->pUpdateDataRes->info.type = STREAM_CLEAR;
  }
1199 1200 1201 1202 1203 1204 1205
}

static void setBlockGroupId(SOperatorInfo* pOperator, SSDataBlock* pBlock, int32_t uidColIndex) {
  ASSERT(taosArrayGetSize(pBlock->pDataBlock) >= 3);
  SColumnInfoData* pColDataInfo = taosArrayGet(pBlock->pDataBlock, uidColIndex);
  uint64_t*        uidCol = (uint64_t*)pColDataInfo->pData;
  ASSERT(pBlock->info.rows > 0);
1206
  for (int32_t i = 0; i < pBlock->info.rows; i++) {
1207
    uidCol[i] = getGroupId(pOperator, uidCol[i]);
5
54liuyao 已提交
1208 1209
  }
}
L
Liu Jicong 已提交
1210

L
Liu Jicong 已提交
1211 1212 1213 1214 1215
static int32_t setBlockIntoRes(SStreamScanInfo* pInfo, const SSDataBlock* pBlock) {
  SDataBlockInfo* pBlockInfo = &pInfo->pRes->info;
  SOperatorInfo*  pOperator = pInfo->pStreamScanOp;
  SExecTaskInfo*  pTaskInfo = pInfo->pStreamScanOp->pTaskInfo;

1216 1217
  blockDataEnsureCapacity(pInfo->pRes, pBlock->info.rows);

L
Liu Jicong 已提交
1218 1219 1220
  pInfo->pRes->info.rows = pBlock->info.rows;
  pInfo->pRes->info.uid = pBlock->info.uid;
  pInfo->pRes->info.type = STREAM_NORMAL;
1221
  pInfo->pRes->info.version = pBlock->info.version;
L
Liu Jicong 已提交
1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240

  uint64_t* groupIdPre = taosHashGet(pOperator->pTaskInfo->tableqinfoList.map, &pBlock->info.uid, sizeof(int64_t));
  if (groupIdPre) {
    pInfo->pRes->info.groupId = *groupIdPre;
  } else {
    pInfo->pRes->info.groupId = 0;
  }

  // todo extract method
  for (int32_t i = 0; i < taosArrayGetSize(pInfo->pColMatchInfo); ++i) {
    SColMatchInfo* pColMatchInfo = taosArrayGet(pInfo->pColMatchInfo, i);
    if (!pColMatchInfo->output) {
      continue;
    }

    bool colExists = false;
    for (int32_t j = 0; j < blockDataGetNumOfCols(pBlock); ++j) {
      SColumnInfoData* pResCol = bdGetColumnInfoData(pBlock, j);
      if (pResCol->info.colId == pColMatchInfo->colId) {
1241 1242
        SColumnInfoData* pDst = taosArrayGet(pInfo->pRes->pDataBlock, pColMatchInfo->targetSlotId);
        colDataAssign(pDst, pResCol, pBlock->info.rows, &pInfo->pRes->info);
L
Liu Jicong 已提交
1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256
        colExists = true;
        break;
      }
    }

    // the required column does not exists in submit block, let's set it to be all null value
    if (!colExists) {
      SColumnInfoData* pDst = taosArrayGet(pInfo->pRes->pDataBlock, pColMatchInfo->targetSlotId);
      colDataAppendNNULL(pDst, 0, pBlockInfo->rows);
    }
  }

  // currently only the tbname pseudo column
  if (pInfo->numOfPseudoExpr > 0) {
L
Liu Jicong 已提交
1257 1258
    int32_t code = addTagPseudoColumnData(&pInfo->readHandle, pInfo->pPseudoExpr, pInfo->numOfPseudoExpr, pInfo->pRes,
                                          GET_TASKID(pTaskInfo));
H
Haojun Liao 已提交
1259
    if (code != TSDB_CODE_SUCCESS) {
L
Liu Jicong 已提交
1260
      blockDataFreeRes((SSDataBlock*)pBlock);
H
Haojun Liao 已提交
1261 1262
      longjmp(pTaskInfo->env, code);
    }
L
Liu Jicong 已提交
1263 1264
  }

1265
  doFilter(pInfo->pCondition, pInfo->pRes, NULL);
L
Liu Jicong 已提交
1266
  blockDataUpdateTsWindow(pInfo->pRes, pInfo->primaryTsIndex);
L
Liu Jicong 已提交
1267
  blockDataFreeRes((SSDataBlock*)pBlock);
L
Liu Jicong 已提交
1268 1269
  return 0;
}
5
54liuyao 已提交
1270

1271
static SSDataBlock* doStreamScan(SOperatorInfo* pOperator) {
H
Haojun Liao 已提交
1272
  // NOTE: this operator does never check if current status is done or not
1273 1274
  SExecTaskInfo*   pTaskInfo = pOperator->pTaskInfo;
  SStreamScanInfo* pInfo = pOperator->info;
H
Haojun Liao 已提交
1275

L
Liu Jicong 已提交
1276
  qDebug("stream scan called");
L
Liu Jicong 已提交
1277 1278 1279 1280 1281 1282 1283 1284 1285
  if (pTaskInfo->streamInfo.prepareStatus.type == TMQ_OFFSET__LOG) {
    while (1) {
      SFetchRet ret = {0};
      tqNextBlock(pInfo->tqReader, &ret);
      if (ret.fetchType == FETCH_TYPE__DATA) {
        blockDataCleanup(pInfo->pRes);
        if (setBlockIntoRes(pInfo, &ret.data) < 0) {
          ASSERT(0);
        }
L
Liu Jicong 已提交
1286
        // TODO clean data block
L
Liu Jicong 已提交
1287
        if (pInfo->pRes->info.rows > 0) {
L
Liu Jicong 已提交
1288
          qDebug("stream scan log return %d rows", pInfo->pRes->info.rows);
L
Liu Jicong 已提交
1289 1290 1291 1292 1293 1294 1295 1296
          return pInfo->pRes;
        }
      } else if (ret.fetchType == FETCH_TYPE__META) {
        ASSERT(0);
        pTaskInfo->streamInfo.lastStatus = ret.offset;
        pTaskInfo->streamInfo.metaBlk = ret.meta;
        return NULL;
      } else if (ret.fetchType == FETCH_TYPE__NONE) {
L
Liu Jicong 已提交
1297
        pTaskInfo->streamInfo.lastStatus = ret.offset;
1298 1299 1300 1301 1302
        ASSERT(pTaskInfo->streamInfo.lastStatus.version >= pTaskInfo->streamInfo.prepareStatus.version);
        ASSERT(pTaskInfo->streamInfo.lastStatus.version + 1 == pInfo->tqReader->pWalReader->curVersion);
        char formatBuf[80];
        tFormatOffset(formatBuf, 80, &ret.offset);
        qDebug("stream scan log return null, offset %s", formatBuf);
L
Liu Jicong 已提交
1303 1304 1305 1306 1307
        return NULL;
      } else {
        ASSERT(0);
      }
    }
L
Liu Jicong 已提交
1308 1309
  } else if (pTaskInfo->streamInfo.prepareStatus.type == TMQ_OFFSET__SNAPSHOT_DATA) {
    SSDataBlock* pResult = doTableScan(pInfo->pTableScanOp);
L
Liu Jicong 已提交
1310 1311 1312 1313 1314 1315
    if (pResult && pResult->info.rows > 0) {
      qDebug("stream scan tsdb return %d rows", pResult->info.rows);
      return pResult;
    }
    qDebug("stream scan tsdb return null");
    return NULL;
L
Liu Jicong 已提交
1316 1317 1318 1319
  } else if (pTaskInfo->streamInfo.prepareStatus.type == TMQ_OFFSET__SNAPSHOT_META) {
    // TODO scan meta
    ASSERT(0);
    return NULL;
H
Haojun Liao 已提交
1320 1321
  }

L
Liu Jicong 已提交
1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339
  if (pTaskInfo->streamInfo.recoverStep == STREAM_RECOVER_STEP__PREPARE) {
    STableScanInfo* pTSInfo = pInfo->pTableScanOp->info;
    memcpy(&pTSInfo->cond, &pTaskInfo->streamInfo.tableCond, sizeof(SQueryTableDataCond));
    pTSInfo->scanTimes = 0;
    pTSInfo->currentGroupId = -1;
    pTaskInfo->streamInfo.recoverStep = STREAM_RECOVER_STEP__SCAN;
  }

  if (pTaskInfo->streamInfo.recoverStep == STREAM_RECOVER_STEP__SCAN) {
    SSDataBlock* pBlock = doTableScan(pInfo->pTableScanOp);
    if (pBlock != NULL) {
      return pBlock;
    }
    // TODO fill in bloom filter
    pTaskInfo->streamInfo.recoverStep = STREAM_RECOVER_STEP__NONE;
    return NULL;
  }

5
54liuyao 已提交
1340
  size_t total = taosArrayGetSize(pInfo->pBlockLists);
1341
  // TODO: refactor
L
Liu Jicong 已提交
1342
  if (pInfo->blockType == STREAM_INPUT__DATA_BLOCK) {
H
Haojun Liao 已提交
1343
    if (pInfo->validBlockIndex >= total) {
L
Liu Jicong 已提交
1344
      /*doClearBufferedBlocks(pInfo);*/
L
Liu Jicong 已提交
1345
      /*pOperator->status = OP_EXEC_DONE;*/
H
Haojun Liao 已提交
1346 1347 1348
      return NULL;
    }

1349
    int32_t      current = pInfo->validBlockIndex++;
1350
    SSDataBlock* pBlock = taosArrayGetP(pInfo->pBlockLists, current);
1351
    // TODO move into scan
5
54liuyao 已提交
1352 1353
    pBlock->info.calWin.skey = INT64_MIN;
    pBlock->info.calWin.ekey = INT64_MAX;
1354
    blockDataUpdateTsWindow(pBlock, 0);
1355
    switch (pBlock->info.type) {
L
Liu Jicong 已提交
1356 1357 1358
      case STREAM_NORMAL:
      case STREAM_GET_ALL:
        return pBlock;
1359 1360 1361
      case STREAM_RETRIEVE: {
        pInfo->blockType = STREAM_INPUT__DATA_SUBMIT;
        pInfo->scanMode = STREAM_SCAN_FROM_DATAREADER_RETRIEVE;
1362 1363
        copyDataBlock(pInfo->pUpdateRes, pBlock);
        prepareRangeScan(pInfo, pInfo->pUpdateRes, &pInfo->updateResIndex);
1364 1365 1366 1367 1368
        updateInfoAddCloseWindowSBF(pInfo->pUpdateInfo);
      } break;
      case STREAM_DELETE_DATA: {
        pInfo->blockType = STREAM_INPUT__DATA_SUBMIT;
        pInfo->updateResIndex = 0;
1369 1370 1371 1372 1373
        generateScanRange(pInfo, pBlock, pInfo->pUpdateRes);
        prepareRangeScan(pInfo, pInfo->pUpdateRes, &pInfo->updateResIndex);
        copyDataBlock(pInfo->pDeleteDataRes, pInfo->pUpdateRes);
        pInfo->scanMode = STREAM_SCAN_FROM_DATAREADER_RANGE;
        return pInfo->pDeleteDataRes;
1374 1375 1376
      } break;
      default:
        break;
5
54liuyao 已提交
1377
    }
1378
    return pBlock;
L
Liu Jicong 已提交
1379
  } else if (pInfo->blockType == STREAM_INPUT__DATA_SUBMIT) {
L
Liu Jicong 已提交
1380
    qDebug("scan mode %d", pInfo->scanMode);
5
54liuyao 已提交
1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396
    switch (pInfo->scanMode) {
      case STREAM_SCAN_FROM_RES: {
        blockDataDestroy(pInfo->pUpdateRes);
        pInfo->scanMode = STREAM_SCAN_FROM_READERHANDLE;
        return pInfo->pRes;
      } break;
      case STREAM_SCAN_FROM_UPDATERES: {
        generateScanRange(pInfo, pInfo->pUpdateDataRes, pInfo->pUpdateRes);
        prepareRangeScan(pInfo, pInfo->pUpdateRes, &pInfo->updateResIndex);
        pInfo->scanMode = STREAM_SCAN_FROM_DATAREADER_RANGE;
        return pInfo->pUpdateRes;
      } break;
      case STREAM_SCAN_FROM_DATAREADER_RANGE:
      case STREAM_SCAN_FROM_DATAREADER_RETRIEVE: {
        SSDataBlock* pSDB = doRangeScan(pInfo, pInfo->pUpdateRes, pInfo->primaryTsIndex, &pInfo->updateResIndex);
        if (pSDB) {
1397
          STableScanInfo* pTableScanInfo = pInfo->pTableScanOp->info;
L
Liu Jicong 已提交
1398 1399
          uint64_t        version = getReaderMaxVersion(pTableScanInfo->dataReader);
          updateInfoSetScanRange(pInfo->pUpdateInfo, &pTableScanInfo->cond.twindows, pInfo->groupId, version);
5
54liuyao 已提交
1400 1401 1402 1403 1404 1405 1406 1407
          pSDB->info.type = pInfo->scanMode == STREAM_SCAN_FROM_DATAREADER_RANGE ? STREAM_NORMAL : STREAM_PULL_DATA;
          checkUpdateData(pInfo, true, pSDB, false);
          return pSDB;
        }
        pInfo->scanMode = STREAM_SCAN_FROM_READERHANDLE;
      } break;
      default:
        break;
1408
    }
1409

5
54liuyao 已提交
1410 1411
    SStreamAggSupporter* pSup = pInfo->sessionSup.pStreamAggSup;
    if (isStateWindow(pInfo) && pSup->pScanBlock->info.rows > 0) {
1412 1413
      pInfo->scanMode = STREAM_SCAN_FROM_DATAREADER_RANGE;
      pInfo->updateResIndex = 0;
5
54liuyao 已提交
1414 1415
      copyDataBlock(pInfo->pUpdateRes, pSup->pScanBlock);
      blockDataCleanup(pSup->pScanBlock);
1416 1417
      prepareRangeScan(pInfo, pInfo->pUpdateRes, &pInfo->updateResIndex);
      return pInfo->pUpdateRes;
5
54liuyao 已提交
1418
    }
5
54liuyao 已提交
1419

H
Haojun Liao 已提交
1420 1421
    SDataBlockInfo* pBlockInfo = &pInfo->pRes->info;

1422
    int32_t totBlockNum = taosArrayGetSize(pInfo->pBlockLists);
1423

1424 1425 1426 1427 1428
    while (1) {
      if (pInfo->tqReader->pMsg == NULL) {
        if (pInfo->validBlockIndex >= totBlockNum) {
          return NULL;
        }
1429

1430 1431 1432 1433 1434 1435 1436 1437
        int32_t     current = pInfo->validBlockIndex++;
        SSubmitReq* pSubmit = taosArrayGetP(pInfo->pBlockLists, current);
        if (tqReaderSetDataMsg(pInfo->tqReader, pSubmit, 0) < 0) {
          qError("submit msg messed up when initing stream submit block %p, current %d, total %d", pSubmit, current,
                 totBlockNum);
          pInfo->tqReader->pMsg = NULL;
          continue;
        }
H
Haojun Liao 已提交
1438 1439
      }

1440 1441 1442 1443
      blockDataCleanup(pInfo->pRes);

      while (tqNextDataBlock(pInfo->tqReader)) {
        SSDataBlock block = {0};
1444

1445 1446 1447 1448 1449 1450 1451 1452
        int32_t code = tqRetrieveDataBlock(&block, pInfo->tqReader);

        if (code != TSDB_CODE_SUCCESS || block.info.rows == 0) {
          continue;
        }

        setBlockIntoRes(pInfo, &block);

L
Liu Jicong 已提交
1453 1454
        if (updateInfoIgnore(pInfo->pUpdateInfo, &pInfo->pRes->info.window, pInfo->pRes->info.groupId,
                             pInfo->pRes->info.version)) {
1455 1456 1457 1458 1459
          printDataBlock(pInfo->pRes, "stream scan ignore");
          blockDataCleanup(pInfo->pRes);
          continue;
        }

1460 1461 1462 1463
        if (pBlockInfo->rows > 0) {
          break;
        }
      }
5
54liuyao 已提交
1464 1465
      if (pBlockInfo->rows > 0) {
        break;
J
jiacy-jcy 已提交
1466 1467
      } else {
        pInfo->tqReader->pMsg = NULL;
1468
        continue;
5
54liuyao 已提交
1469
      }
1470
      /*blockDataCleanup(pInfo->pRes);*/
H
Haojun Liao 已提交
1471 1472 1473 1474
    }

    // record the scan action.
    pInfo->numOfExec++;
1475
    pOperator->resultInfo.totalRows += pBlockInfo->rows;
1476
    printDataBlock(pInfo->pRes, "stream scan");
H
Haojun Liao 已提交
1477

5
54liuyao 已提交
1478
    if (pBlockInfo->rows == 0) {
5
54liuyao 已提交
1479
      updateInfoDestoryColseWinSBF(pInfo->pUpdateInfo);
L
Liu Jicong 已提交
1480
      /*pOperator->status = OP_EXEC_DONE;*/
5
54liuyao 已提交
1481
    } else if (pInfo->pUpdateInfo) {
1482
      checkUpdateData(pInfo, true, pInfo->pRes, true);
5
54liuyao 已提交
1483
      pInfo->twAggSup.maxTs = TMAX(pInfo->twAggSup.maxTs, pBlockInfo->window.ekey);
1484 1485
      if (pInfo->pUpdateDataRes->info.rows > 0) {
        if (pInfo->pUpdateDataRes->info.type == STREAM_CLEAR) {
5
54liuyao 已提交
1486 1487
          pInfo->updateResIndex = 0;
          pInfo->scanMode = STREAM_SCAN_FROM_UPDATERES;
1488
        } else if (pInfo->pUpdateDataRes->info.type == STREAM_INVERT) {
5
54liuyao 已提交
1489
          pInfo->scanMode = STREAM_SCAN_FROM_RES;
1490
          return pInfo->pUpdateDataRes;
5
54liuyao 已提交
1491
        }
5
54liuyao 已提交
1492
      }
1493
    }
1494

L
Liu Jicong 已提交
1495
    qDebug("scan rows: %d", pBlockInfo->rows);
5
54liuyao 已提交
1496
    return (pBlockInfo->rows == 0) ? NULL : pInfo->pRes;
1497

L
Liu Jicong 已提交
1498 1499 1500
  } else {
    ASSERT(0);
    return NULL;
H
Haojun Liao 已提交
1501 1502 1503
  }
}

L
Liu Jicong 已提交
1504 1505 1506 1507 1508
static SSDataBlock* doRawScan(SOperatorInfo* pInfo) {
  //
  return NULL;
}

1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520
static SArray* extractTableIdList(const STableListInfo* pTableGroupInfo) {
  SArray* tableIdList = taosArrayInit(4, sizeof(uint64_t));

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

  return tableIdList;
}

L
Liu Jicong 已提交
1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533
// for subscribing db or stb (not including column),
// if this scan is used, meta data can be return
// and schemas are decided when scanning
SOperatorInfo* createRawScanOperatorInfo(SReadHandle* pHandle, STableScanPhysiNode* pTableScanNode,
                                         SExecTaskInfo* pTaskInfo, STimeWindowAggSupp* pTwSup) {
  // create operator
  // create tb reader
  // create meta reader
  // create tq reader

  return NULL;
}

1534 1535 1536 1537
static void destroyStreamScanOperatorInfo(void* param, int32_t numOfOutput) {
  SStreamScanInfo* pStreamScan = (SStreamScanInfo*)param;
  if (pStreamScan->pTableScanOp && pStreamScan->pTableScanOp->info) {
    STableScanInfo* pTableScanInfo = pStreamScan->pTableScanOp->info;
5
54liuyao 已提交
1538
    destroyTableScanOperatorInfo(pTableScanInfo, numOfOutput);
5
54liuyao 已提交
1539
    taosMemoryFreeClear(pStreamScan->pTableScanOp);
1540 1541 1542 1543 1544 1545 1546
  }
  if (pStreamScan->tqReader) {
    tqCloseReader(pStreamScan->tqReader);
  }
  if (pStreamScan->pColMatchInfo) {
    taosArrayDestroy(pStreamScan->pColMatchInfo);
  }
C
Cary Xu 已提交
1547 1548 1549 1550
  if (pStreamScan->pPseudoExpr) {
    destroyExprInfo(pStreamScan->pPseudoExpr, pStreamScan->numOfPseudoExpr);
    taosMemoryFreeClear(pStreamScan->pPseudoExpr);
  }
C
Cary Xu 已提交
1551

L
Liu Jicong 已提交
1552
  updateInfoDestroy(pStreamScan->pUpdateInfo);
1553 1554 1555 1556
  blockDataDestroy(pStreamScan->pRes);
  blockDataDestroy(pStreamScan->pUpdateRes);
  blockDataDestroy(pStreamScan->pPullDataRes);
  blockDataDestroy(pStreamScan->pDeleteDataRes);
5
54liuyao 已提交
1557
  blockDataDestroy(pStreamScan->pUpdateDataRes);
1558 1559 1560 1561
  taosArrayDestroy(pStreamScan->pBlockLists);
  taosMemoryFree(pStreamScan);
}

1562
SOperatorInfo* createStreamScanOperatorInfo(SReadHandle* pHandle, STableScanPhysiNode* pTableScanNode, SNode* pTagCond,
1563
                                            SExecTaskInfo* pTaskInfo) {
1564 1565
  SStreamScanInfo* pInfo = taosMemoryCalloc(1, sizeof(SStreamScanInfo));
  SOperatorInfo*   pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
1566

H
Haojun Liao 已提交
1567 1568
  if (pInfo == NULL || pOperator == NULL) {
    terrno = TSDB_CODE_QRY_OUT_OF_MEMORY;
1569
    goto _error;
H
Haojun Liao 已提交
1570 1571
  }

1572
  SScanPhysiNode*     pScanPhyNode = &pTableScanNode->scan;
1573
  SDataBlockDescNode* pDescNode = pScanPhyNode->node.pOutputDataBlockDesc;
H
Haojun Liao 已提交
1574

1575
  pInfo->pTagCond = pTagCond;
1576
  pInfo->pGroupTags = pTableScanNode->pGroupTags;
1577 1578 1579 1580 1581
  pInfo->twAggSup = (STimeWindowAggSupp){
      .waterMark = pTableScanNode->watermark,
      .calTrigger = pTableScanNode->triggerType,
      .maxTs = INT64_MIN,
  };
1582

1583
  int32_t numOfCols = 0;
1584
  pInfo->pColMatchInfo = extractColMatchInfo(pScanPhyNode->pScanCols, pDescNode, &numOfCols, COL_MATCH_FROM_COL_ID);
1585 1586 1587

  int32_t numOfOutput = taosArrayGetSize(pInfo->pColMatchInfo);
  SArray* pColIds = taosArrayInit(numOfOutput, sizeof(int16_t));
1588
  for (int32_t i = 0; i < numOfOutput; ++i) {
1589 1590 1591
    SColMatchInfo* id = taosArrayGet(pInfo->pColMatchInfo, i);

    int16_t colId = id->colId;
1592
    taosArrayPush(pColIds, &colId);
1593
    if (id->colId == PRIMARYKEY_TIMESTAMP_COL_ID) {
5
54liuyao 已提交
1594 1595
      pInfo->primaryTsIndex = id->targetSlotId;
    }
H
Haojun Liao 已提交
1596 1597 1598 1599
  }

  pInfo->pBlockLists = taosArrayInit(4, POINTER_BYTES);
  if (pInfo->pBlockLists == NULL) {
1600 1601
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    goto _error;
H
Haojun Liao 已提交
1602 1603
  }

5
54liuyao 已提交
1604
  if (pHandle->vnode) {
L
Liu Jicong 已提交
1605
    SOperatorInfo*  pTableScanOp = createTableScanOperatorInfo(pTableScanNode, pHandle, pTaskInfo);
L
Liu Jicong 已提交
1606
    STableScanInfo* pTSInfo = (STableScanInfo*)pTableScanOp->info;
1607
    if (pHandle->version > 0) {
L
Liu Jicong 已提交
1608
      pTSInfo->cond.endVersion = pHandle->version;
1609
    }
L
Liu Jicong 已提交
1610 1611

    SArray* tableList = taosArrayGetP(pTaskInfo->tableqinfoList.pGroupList, 0);
1612
    if (pHandle->initTableReader) {
L
Liu Jicong 已提交
1613 1614 1615
      pTSInfo->scanMode = TABLE_SCAN__TABLE_ORDER;
      pTSInfo->dataReader = NULL;
      if (tsdbReaderOpen(pHandle->vnode, &pTSInfo->cond, tableList, &pTSInfo->dataReader, NULL) < 0) {
L
Liu Jicong 已提交
1616 1617
        ASSERT(0);
      }
L
Liu Jicong 已提交
1618 1619
    }

L
Liu Jicong 已提交
1620 1621 1622 1623
    if (pHandle->initTqReader) {
      ASSERT(pHandle->tqReader == NULL);
      pInfo->tqReader = tqOpenReader(pHandle->vnode);
      ASSERT(pInfo->tqReader);
1624
    } else {
L
Liu Jicong 已提交
1625 1626
      ASSERT(pHandle->tqReader);
      pInfo->tqReader = pHandle->tqReader;
1627 1628
    }

1629 1630
    if (pTSInfo->pdInfo.interval.interval > 0) {
      pInfo->pUpdateInfo = updateInfoInitP(&pTSInfo->pdInfo.interval, pInfo->twAggSup.waterMark);
L
Liu Jicong 已提交
1631 1632 1633
    } else {
      pInfo->pUpdateInfo = NULL;
    }
1634 1635

    pInfo->pTableScanOp = pTableScanOp;
1636
    pInfo->interval = pTSInfo->pdInfo.interval;
L
Liu Jicong 已提交
1637

L
Liu Jicong 已提交
1638 1639 1640
    pInfo->readHandle = *pHandle;
    pInfo->tableUid = pScanPhyNode->uid;

L
Liu Jicong 已提交
1641
    // set the extract column id to streamHandle
L
Liu Jicong 已提交
1642
    tqReaderSetColIdList(pInfo->tqReader, pColIds);
L
Liu Jicong 已提交
1643
    SArray* tableIdList = extractTableIdList(&pTaskInfo->tableqinfoList);
L
Liu Jicong 已提交
1644
    int32_t code = tqReaderSetTbUidList(pInfo->tqReader, tableIdList);
L
Liu Jicong 已提交
1645 1646 1647 1648 1649
    if (code != 0) {
      taosArrayDestroy(tableIdList);
      goto _error;
    }
    taosArrayDestroy(tableIdList);
L
Liu Jicong 已提交
1650
    memcpy(&pTaskInfo->streamInfo.tableCond, &pTSInfo->cond, sizeof(SQueryTableDataCond));
5
54liuyao 已提交
1651 1652
  }

1653 1654 1655 1656 1657
  // create the pseduo columns info
  if (pTableScanNode->scan.pScanPseudoCols != NULL) {
    pInfo->pPseudoExpr = createExprInfo(pTableScanNode->scan.pScanPseudoCols, NULL, &pInfo->numOfPseudoExpr);
  }

1658
  pInfo->pRes = createResDataBlock(pDescNode);
1659
  pInfo->pUpdateRes = createSpecialDataBlock(STREAM_CLEAR);
1660 1661
  pInfo->pCondition = pScanPhyNode->node.pConditions;
  pInfo->scanMode = STREAM_SCAN_FROM_READERHANDLE;
1662 1663
  pInfo->sessionSup =
      (SessionWindowSupporter){.pStreamAggSup = NULL, .gap = -1, .parentType = QUERY_NODE_PHYSICAL_PLAN};
1664
  pInfo->groupId = 0;
1665
  pInfo->pPullDataRes = createSpecialDataBlock(STREAM_RETRIEVE);
1666
  pInfo->pStreamScanOp = pOperator;
1667
  pInfo->deleteDataIndex = 0;
1668
  pInfo->pDeleteDataRes = createSpecialDataBlock(STREAM_DELETE_DATA);
5
54liuyao 已提交
1669
  pInfo->updateWin = (STimeWindow){.skey = INT64_MAX, .ekey = INT64_MAX};
1670
  pInfo->pUpdateDataRes = createSpecialDataBlock(STREAM_CLEAR);
X
Xiaoyu Wang 已提交
1671
  pInfo->assignBlockUid = pTableScanNode->assignBlockUid;
L
Liu Jicong 已提交
1672

1673
  pOperator->name = "StreamScanOperator";
L
Liu Jicong 已提交
1674
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_STREAM_SCAN;
1675 1676 1677
  pOperator->blocking = false;
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
1678
  pOperator->exprSupp.numOfExprs = taosArrayGetSize(pInfo->pRes->pDataBlock);
1679
  pOperator->pTaskInfo = pTaskInfo;
H
Haojun Liao 已提交
1680

1681 1682
  pOperator->fpSet = createOperatorFpSet(operatorDummyOpenFn, doStreamScan, NULL, NULL, destroyStreamScanOperatorInfo,
                                         NULL, NULL, NULL);
1683

H
Haojun Liao 已提交
1684
  return pOperator;
1685

L
Liu Jicong 已提交
1686
_error:
1687 1688 1689
  taosMemoryFreeClear(pInfo);
  taosMemoryFreeClear(pOperator);
  return NULL;
H
Haojun Liao 已提交
1690 1691 1692 1693 1694 1695 1696
}

static void destroySysScanOperator(void* param, int32_t numOfOutput) {
  SSysTableScanInfo* pInfo = (SSysTableScanInfo*)param;
  tsem_destroy(&pInfo->ready);
  blockDataDestroy(pInfo->pRes);

1697
  const char* name = tNameGetTableName(&pInfo->name);
D
dapan1121 已提交
1698 1699
  if (strncasecmp(name, TSDB_INS_TABLE_TABLES, TSDB_TABLE_FNAME_LEN) == 0 ||
      strncasecmp(name, TSDB_INS_TABLE_TAGS, TSDB_TABLE_FNAME_LEN) == 0 || pInfo->pCur != NULL) {
H
Haojun Liao 已提交
1700
    metaCloseTbCursor(pInfo->pCur);
1701
    pInfo->pCur = NULL;
H
Haojun Liao 已提交
1702
  }
H
Haojun Liao 已提交
1703 1704

  taosArrayDestroy(pInfo->scanCols);
1705
  taosMemoryFreeClear(pInfo->pUser);
D
dapan1121 已提交
1706 1707

  taosMemoryFreeClear(param);
H
Haojun Liao 已提交
1708 1709
}

X
Xiaoyu Wang 已提交
1710
static int32_t getSysTableDbNameColId(const char* pTable) {
D
dapan1121 已提交
1711
  // if (0 == strcmp(TSDB_INS_TABLE_INDEXES, pTable)) {
X
Xiaoyu Wang 已提交
1712 1713
  //   return 1;
  // }
X
Xiaoyu Wang 已提交
1714 1715 1716
  return TSDB_INS_USER_STABLES_DBNAME_COLID;
}

H
Haojun Liao 已提交
1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737
EDealRes getDBNameFromConditionWalker(SNode* pNode, void* pContext) {
  int32_t   code = TSDB_CODE_SUCCESS;
  ENodeType nType = nodeType(pNode);

  switch (nType) {
    case QUERY_NODE_OPERATOR: {
      SOperatorNode* node = (SOperatorNode*)pNode;
      if (OP_TYPE_EQUAL == node->opType) {
        *(int32_t*)pContext = 1;
        return DEAL_RES_CONTINUE;
      }

      *(int32_t*)pContext = 0;
      return DEAL_RES_IGNORE_CHILD;
    }
    case QUERY_NODE_COLUMN: {
      if (1 != *(int32_t*)pContext) {
        return DEAL_RES_CONTINUE;
      }

      SColumnNode* node = (SColumnNode*)pNode;
X
Xiaoyu Wang 已提交
1738
      if (getSysTableDbNameColId(node->tableName) == node->colId) {
H
Haojun Liao 已提交
1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754
        *(int32_t*)pContext = 2;
        return DEAL_RES_CONTINUE;
      }

      *(int32_t*)pContext = 0;
      return DEAL_RES_CONTINUE;
    }
    case QUERY_NODE_VALUE: {
      if (2 != *(int32_t*)pContext) {
        return DEAL_RES_CONTINUE;
      }

      SValueNode* node = (SValueNode*)pNode;
      char*       dbName = nodesGetValueFromNode(node);
      strncpy(pContext, varDataVal(dbName), varDataLen(dbName));
      *((char*)pContext + varDataLen(dbName)) = 0;
1755
      return DEAL_RES_END;  // stop walk
H
Haojun Liao 已提交
1756 1757 1758 1759 1760 1761 1762
    }
    default:
      break;
  }
  return DEAL_RES_CONTINUE;
}

1763
static void getDBNameFromCondition(SNode* pCondition, const char* dbName) {
H
Haojun Liao 已提交
1764 1765 1766
  if (NULL == pCondition) {
    return;
  }
L
Liu Jicong 已提交
1767
  nodesWalkExpr(pCondition, getDBNameFromConditionWalker, (char*)dbName);
H
Haojun Liao 已提交
1768 1769
}

D
dapan1121 已提交
1770
static int32_t loadSysTableCallback(void* param, SDataBuf* pMsg, int32_t code) {
H
Haojun Liao 已提交
1771 1772 1773 1774 1775 1776 1777
  SOperatorInfo*     operator=(SOperatorInfo*) param;
  SSysTableScanInfo* pScanResInfo = (SSysTableScanInfo*)operator->info;
  if (TSDB_CODE_SUCCESS == code) {
    pScanResInfo->pRsp = pMsg->pData;

    SRetrieveMetaTableRsp* pRsp = pScanResInfo->pRsp;
    pRsp->numOfRows = htonl(pRsp->numOfRows);
1778 1779 1780
    pRsp->useconds = htobe64(pRsp->useconds);
    pRsp->handle = htobe64(pRsp->handle);
    pRsp->compLen = htonl(pRsp->compLen);
H
Haojun Liao 已提交
1781 1782 1783 1784 1785
  } else {
    operator->pTaskInfo->code = code;
  }

  tsem_post(&pScanResInfo->ready);
wmmhello's avatar
wmmhello 已提交
1786
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
1787 1788 1789 1790 1791 1792 1793
}

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

1794
  doFilter(pInfo->pCondition, pInfo->pRes, NULL);
H
Haojun Liao 已提交
1795 1796 1797
  return pInfo->pRes->info.rows == 0 ? NULL : pInfo->pRes;
}

1798
static SSDataBlock* buildInfoSchemaTableMetaBlock(char* tableName) {
L
Liu Jicong 已提交
1799 1800
  size_t               size = 0;
  const SSysTableMeta* pMeta = NULL;
1801 1802 1803
  getInfosDbMeta(&pMeta, &size);

  int32_t index = 0;
L
Liu Jicong 已提交
1804
  for (int32_t i = 0; i < size; ++i) {
1805
    if (strcmp(pMeta[i].name, tableName) == 0) {
1806 1807 1808 1809
      index = i;
      break;
    }
  }
1810

1811
  SSDataBlock* pBlock = createDataBlock();
L
Liu Jicong 已提交
1812
  for (int32_t i = 0; i < pMeta[index].colNum; ++i) {
L
Liu Jicong 已提交
1813 1814
    SColumnInfoData colInfoData =
        createColumnInfoData(pMeta[index].schema[i].type, pMeta[index].schema[i].bytes, i + 1);
1815
    blockDataAppendColInfo(pBlock, &colInfoData);
1816 1817
  }

1818 1819 1820
  return pBlock;
}

1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901
int32_t convertTagDataToStr(char* str, int type, void* buf, int32_t bufSize, int32_t* len) {
  int32_t n = 0;

  switch (type) {
    case TSDB_DATA_TYPE_NULL:
      n = sprintf(str, "null");
      break;

    case TSDB_DATA_TYPE_BOOL:
      n = sprintf(str, (*(int8_t*)buf) ? "true" : "false");
      break;

    case TSDB_DATA_TYPE_TINYINT:
      n = sprintf(str, "%d", *(int8_t*)buf);
      break;

    case TSDB_DATA_TYPE_SMALLINT:
      n = sprintf(str, "%d", *(int16_t*)buf);
      break;

    case TSDB_DATA_TYPE_INT:
      n = sprintf(str, "%d", *(int32_t*)buf);
      break;

    case TSDB_DATA_TYPE_BIGINT:
    case TSDB_DATA_TYPE_TIMESTAMP:
      n = sprintf(str, "%" PRId64, *(int64_t*)buf);
      break;

    case TSDB_DATA_TYPE_FLOAT:
      n = sprintf(str, "%.5f", GET_FLOAT_VAL(buf));
      break;

    case TSDB_DATA_TYPE_DOUBLE:
      n = sprintf(str, "%.9f", GET_DOUBLE_VAL(buf));
      break;

    case TSDB_DATA_TYPE_BINARY:
      if (bufSize < 0) {
        return TSDB_CODE_TSC_INVALID_VALUE;
      }

      memcpy(str, buf, bufSize);
      n = bufSize;
      break;
    case TSDB_DATA_TYPE_NCHAR:
      if (bufSize < 0) {
        return TSDB_CODE_TSC_INVALID_VALUE;
      }

      int32_t length = taosUcs4ToMbs((TdUcs4*)buf, bufSize, str);
      if (length <= 0) {
        return TSDB_CODE_TSC_INVALID_VALUE;
      }
      n = length;
      break;
    case TSDB_DATA_TYPE_UTINYINT:
      n = sprintf(str, "%u", *(uint8_t*)buf);
      break;

    case TSDB_DATA_TYPE_USMALLINT:
      n = sprintf(str, "%u", *(uint16_t*)buf);
      break;

    case TSDB_DATA_TYPE_UINT:
      n = sprintf(str, "%u", *(uint32_t*)buf);
      break;

    case TSDB_DATA_TYPE_UBIGINT:
      n = sprintf(str, "%" PRIu64, *(uint64_t*)buf);
      break;

    default:
      return TSDB_CODE_TSC_INVALID_VALUE;
  }

  if (len) *len = n;

  return TSDB_CODE_SUCCESS;
}

S
shenglian zhou 已提交
1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926
static SSDataBlock* sysTableScanUserTags(SOperatorInfo* pOperator) {
  SExecTaskInfo*     pTaskInfo = pOperator->pTaskInfo;
  SSysTableScanInfo* pInfo = pOperator->info;
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

  if (pInfo->pCur == NULL) {
    pInfo->pCur = metaOpenTbCursor(pInfo->readHandle.meta);
  }

  blockDataCleanup(pInfo->pRes);
  int32_t numOfRows = 0;

  const char* db = NULL;
  int32_t     vgId = 0;
  vnodeGetInfo(pInfo->readHandle.vnode, &db, &vgId);

  SName sn = {0};
  char  dbname[TSDB_DB_FNAME_LEN + VARSTR_HEADER_SIZE] = {0};
  tNameFromString(&sn, db, T_NAME_ACCT | T_NAME_DB);

  tNameGetDbName(&sn, varDataVal(dbname));
  varDataSetLen(dbname, strlen(varDataVal(dbname)));

D
dapan1121 已提交
1927
  SSDataBlock* p = buildInfoSchemaTableMetaBlock(TSDB_INS_TABLE_TAGS);
S
shenglian zhou 已提交
1928 1929 1930 1931
  blockDataEnsureCapacity(p, pOperator->resultInfo.capacity);

  int32_t ret = 0;
  while ((ret = metaTbCursorNext(pInfo->pCur)) == 0) {
1932 1933 1934
    if (pInfo->pCur->mr.me.type != TSDB_CHILD_TABLE) {
      continue;
    }
S
shenglian zhou 已提交
1935

1936 1937
    char tableName[TSDB_TABLE_NAME_LEN + VARSTR_HEADER_SIZE] = {0};
    STR_TO_VARSTR(tableName, pInfo->pCur->mr.me.name);
S
shenglian zhou 已提交
1938

1939 1940
    SMetaReader smr = {0};
    metaReaderInit(&smr, pInfo->readHandle.meta, 0);
S
shenglian zhou 已提交
1941

1942 1943 1944 1945 1946 1947 1948 1949 1950 1951
    uint64_t suid = pInfo->pCur->mr.me.ctbEntry.suid;
    int32_t  code = metaGetTableEntryByUid(&smr, suid);
    if (code != TSDB_CODE_SUCCESS) {
      qError("failed to get super table meta, uid:0x%" PRIx64 ", code:%s, %s", suid, tstrerror(terrno),
             GET_TASKID(pTaskInfo));
      metaReaderClear(&smr);
      metaCloseTbCursor(pInfo->pCur);
      pInfo->pCur = NULL;
      longjmp(pTaskInfo->env, terrno);
    }
S
shenglian zhou 已提交
1952

1953 1954
    char stableName[TSDB_TABLE_NAME_LEN + VARSTR_HEADER_SIZE] = {0};
    STR_TO_VARSTR(stableName, smr.me.name);
S
shenglian zhou 已提交
1955

1956 1957 1958
    int32_t numOfTags = smr.me.stbEntry.schemaTag.nCols;
    for (int32_t i = 0; i < numOfTags; ++i) {
      SColumnInfoData* pColInfoData = NULL;
S
shenglian zhou 已提交
1959

1960 1961 1962
      // table name
      pColInfoData = taosArrayGet(p->pDataBlock, 0);
      colDataAppend(pColInfoData, numOfRows, tableName, false);
S
shenglian zhou 已提交
1963

1964 1965 1966
      // database name
      pColInfoData = taosArrayGet(p->pDataBlock, 1);
      colDataAppend(pColInfoData, numOfRows, dbname, false);
S
shenglian zhou 已提交
1967 1968 1969

      // super table name
      pColInfoData = taosArrayGet(p->pDataBlock, 2);
1970
      colDataAppend(pColInfoData, numOfRows, stableName, false);
S
shenglian zhou 已提交
1971

1972
      // tag name
1973 1974
      char tagName[TSDB_COL_NAME_LEN + VARSTR_HEADER_SIZE] = {0};
      STR_TO_VARSTR(tagName, smr.me.stbEntry.schemaTag.pSchema[i].name);
S
shenglian zhou 已提交
1975
      pColInfoData = taosArrayGet(p->pDataBlock, 3);
1976
      colDataAppend(pColInfoData, numOfRows, tagName, false);
S
shenglian zhou 已提交
1977

1978
      // tag type
1979
      int8_t tagType = smr.me.stbEntry.schemaTag.pSchema[i].type;
S
shenglian zhou 已提交
1980
      pColInfoData = taosArrayGet(p->pDataBlock, 4);
1981
      char tagTypeStr[VARSTR_HEADER_SIZE + 32];
1982
      int  tagTypeLen = sprintf(varDataVal(tagTypeStr), "%s", tDataTypes[tagType].name);
1983
      if (tagType == TSDB_DATA_TYPE_VARCHAR) {
1984 1985
        tagTypeLen += sprintf(varDataVal(tagTypeStr) + tagTypeLen, "(%d)",
                              (int32_t)(smr.me.stbEntry.schemaTag.pSchema[i].bytes - VARSTR_HEADER_SIZE));
1986
      } else if (tagType == TSDB_DATA_TYPE_NCHAR) {
1987 1988 1989
        tagTypeLen +=
            sprintf(varDataVal(tagTypeStr) + tagTypeLen, "(%d)",
                    (int32_t)((smr.me.stbEntry.schemaTag.pSchema[i].bytes - VARSTR_HEADER_SIZE) / TSDB_NCHAR_SIZE));
1990 1991 1992
      }
      varDataSetLen(tagTypeStr, tagTypeLen);
      colDataAppend(pColInfoData, numOfRows, (char*)tagTypeStr, false);
1993 1994 1995

      STagVal tagVal = {0};
      tagVal.cid = smr.me.stbEntry.schemaTag.pSchema[i].colId;
S
shenglian zhou 已提交
1996 1997
      char*    tagData = NULL;
      uint32_t tagLen = 0;
1998

S
shenglian zhou 已提交
1999
      if (tagType == TSDB_DATA_TYPE_JSON) {
2000
        tagData = (char*)pInfo->pCur->mr.me.ctbEntry.pTags;
S
shenglian zhou 已提交
2001
      } else {
S
shenglian zhou 已提交
2002 2003 2004 2005 2006 2007 2008 2009 2010 2011
        bool exist = tTagGet((STag*)pInfo->pCur->mr.me.ctbEntry.pTags, &tagVal);
        if (exist) {
          if (IS_VAR_DATA_TYPE(tagType)) {
            tagData = (char*)tagVal.pData;
            tagLen = tagVal.nData;
          } else {
            tagData = (char*)&tagVal.i64;
            tagLen = tDataTypes[tagType].bytes;
          }
        }
S
shenglian zhou 已提交
2012 2013
      }

2014
      char* tagVarChar = NULL;
S
shenglian zhou 已提交
2015
      if (tagData != NULL) {
2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026
        if (tagType == TSDB_DATA_TYPE_JSON) {
          char* tagJson = parseTagDatatoJson(tagData);
          tagVarChar = taosMemoryMalloc(strlen(tagJson) + VARSTR_HEADER_SIZE);
          memcpy(varDataVal(tagVarChar), tagJson, strlen(tagJson));
          varDataSetLen(tagVarChar, strlen(tagJson));
          taosMemoryFree(tagJson);
        } else {
          int32_t bufSize = IS_VAR_DATA_TYPE(tagType) ? (tagLen + VARSTR_HEADER_SIZE)
                                                      : (3 + DBL_MANT_DIG - DBL_MIN_EXP + VARSTR_HEADER_SIZE);
          tagVarChar = taosMemoryMalloc(bufSize);
          int32_t len = -1;
2027
          convertTagDataToStr(varDataVal(tagVarChar), tagType, tagData, tagLen, &len);
2028
          varDataSetLen(tagVarChar, len);
S
shenglian zhou 已提交
2029
        }
2030
      }
S
shenglian zhou 已提交
2031 2032 2033 2034
      pColInfoData = taosArrayGet(p->pDataBlock, 5);
      colDataAppend(pColInfoData, numOfRows, tagVarChar,
                    (tagData == NULL) || (tagType == TSDB_DATA_TYPE_JSON && tTagIsJsonNull(tagData)));
      taosMemoryFree(tagVarChar);
2035
      ++numOfRows;
S
shenglian zhou 已提交
2036
    }
2037
    metaReaderClear(&smr);
S
shenglian zhou 已提交
2038

2039
    if (numOfRows >= pOperator->resultInfo.capacity) {
S
shenglian zhou 已提交
2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062
      break;
    }
  }

  // todo temporarily free the cursor here, the true reason why the free is not valid needs to be found
  if (ret != 0) {
    metaCloseTbCursor(pInfo->pCur);
    pInfo->pCur = NULL;
    doSetOperatorCompleted(pOperator);
  }

  p->info.rows = numOfRows;
  pInfo->pRes->info.rows = numOfRows;

  relocateColumnData(pInfo->pRes, pInfo->scanCols, p->pDataBlock, false);
  doFilterResult(pInfo);

  blockDataDestroy(p);

  pInfo->loadInfo.totalRows += pInfo->pRes->info.rows;
  return (pInfo->pRes->info.rows == 0) ? NULL : pInfo->pRes;
}

2063
static SSDataBlock* sysTableScanUserTables(SOperatorInfo* pOperator) {
H
Haojun Liao 已提交
2064 2065
  SExecTaskInfo*     pTaskInfo = pOperator->pTaskInfo;
  SSysTableScanInfo* pInfo = pOperator->info;
2066 2067 2068
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }
H
Haojun Liao 已提交
2069

2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081
  // the retrieve is executed on the mnode, so return tables that belongs to the information schema database.
  if (pInfo->readHandle.mnd != NULL) {
    buildSysDbTableInfo(pInfo, pOperator->resultInfo.capacity);

    doFilterResult(pInfo);
    pInfo->loadInfo.totalRows += pInfo->pRes->info.rows;

    doSetOperatorCompleted(pOperator);
    return (pInfo->pRes->info.rows == 0) ? NULL : pInfo->pRes;
  } else {
    if (pInfo->pCur == NULL) {
      pInfo->pCur = metaOpenTbCursor(pInfo->readHandle.meta);
2082 2083
    }

2084 2085
    blockDataCleanup(pInfo->pRes);
    int32_t numOfRows = 0;
2086

2087 2088 2089
    const char* db = NULL;
    int32_t     vgId = 0;
    vnodeGetInfo(pInfo->readHandle.vnode, &db, &vgId);
2090

2091 2092 2093
    SName sn = {0};
    char  dbname[TSDB_DB_FNAME_LEN + VARSTR_HEADER_SIZE] = {0};
    tNameFromString(&sn, db, T_NAME_ACCT | T_NAME_DB);
2094

2095 2096
    tNameGetDbName(&sn, varDataVal(dbname));
    varDataSetLen(dbname, strlen(varDataVal(dbname)));
2097

D
dapan1121 已提交
2098
    SSDataBlock* p = buildInfoSchemaTableMetaBlock(TSDB_INS_TABLE_TABLES);
2099
    blockDataEnsureCapacity(p, pOperator->resultInfo.capacity);
2100

2101
    char n[TSDB_TABLE_NAME_LEN + VARSTR_HEADER_SIZE] = {0};
2102

2103 2104 2105
    int32_t ret = 0;
    while ((ret = metaTbCursorNext(pInfo->pCur)) == 0) {
      STR_TO_VARSTR(n, pInfo->pCur->mr.me.name);
2106

2107 2108 2109
      // table name
      SColumnInfoData* pColInfoData = taosArrayGet(p->pDataBlock, 0);
      colDataAppend(pColInfoData, numOfRows, n, false);
2110

2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131
      // database name
      pColInfoData = taosArrayGet(p->pDataBlock, 1);
      colDataAppend(pColInfoData, numOfRows, dbname, false);

      // vgId
      pColInfoData = taosArrayGet(p->pDataBlock, 6);
      colDataAppend(pColInfoData, numOfRows, (char*)&vgId, false);

      int32_t tableType = pInfo->pCur->mr.me.type;
      if (tableType == TSDB_CHILD_TABLE) {
        // create time
        int64_t ts = pInfo->pCur->mr.me.ctbEntry.ctime;
        pColInfoData = taosArrayGet(p->pDataBlock, 2);
        colDataAppend(pColInfoData, numOfRows, (char*)&ts, false);

        SMetaReader mr = {0};
        metaReaderInit(&mr, pInfo->readHandle.meta, 0);

        uint64_t suid = pInfo->pCur->mr.me.ctbEntry.suid;
        int32_t  code = metaGetTableEntryByUid(&mr, suid);
        if (code != TSDB_CODE_SUCCESS) {
H
Hongze Cheng 已提交
2132 2133
          qError("failed to get super table meta, cname:%s, suid:0x%" PRIx64 ", code:%s, %s", pInfo->pCur->mr.me.name,
                 suid, tstrerror(terrno), GET_TASKID(pTaskInfo));
2134 2135 2136 2137 2138
          metaReaderClear(&mr);
          metaCloseTbCursor(pInfo->pCur);
          pInfo->pCur = NULL;
          longjmp(pTaskInfo->env, terrno);
        }
2139

2140 2141 2142
        // number of columns
        pColInfoData = taosArrayGet(p->pDataBlock, 3);
        colDataAppend(pColInfoData, numOfRows, (char*)&mr.me.stbEntry.schemaRow.nCols, false);
2143

2144 2145 2146
        // super table name
        STR_TO_VARSTR(n, mr.me.name);
        pColInfoData = taosArrayGet(p->pDataBlock, 4);
2147
        colDataAppend(pColInfoData, numOfRows, n, false);
2148
        metaReaderClear(&mr);
2149

2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160
        // table comment
        pColInfoData = taosArrayGet(p->pDataBlock, 8);
        if (pInfo->pCur->mr.me.ctbEntry.commentLen > 0) {
          char comment[TSDB_TB_COMMENT_LEN + VARSTR_HEADER_SIZE] = {0};
          STR_TO_VARSTR(comment, pInfo->pCur->mr.me.ctbEntry.comment);
          colDataAppend(pColInfoData, numOfRows, comment, false);
        } else if (pInfo->pCur->mr.me.ctbEntry.commentLen == 0) {
          char comment[VARSTR_HEADER_SIZE + VARSTR_HEADER_SIZE] = {0};
          STR_TO_VARSTR(comment, "");
          colDataAppend(pColInfoData, numOfRows, comment, false);
        } else {
2161 2162
          colDataAppendNULL(pColInfoData, numOfRows);
        }
2163

2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184
        // uid
        pColInfoData = taosArrayGet(p->pDataBlock, 5);
        colDataAppend(pColInfoData, numOfRows, (char*)&pInfo->pCur->mr.me.uid, false);

        // ttl
        pColInfoData = taosArrayGet(p->pDataBlock, 7);
        colDataAppend(pColInfoData, numOfRows, (char*)&pInfo->pCur->mr.me.ctbEntry.ttlDays, false);

        STR_TO_VARSTR(n, "CHILD_TABLE");
      } else if (tableType == TSDB_NORMAL_TABLE) {
        // create time
        pColInfoData = taosArrayGet(p->pDataBlock, 2);
        colDataAppend(pColInfoData, numOfRows, (char*)&pInfo->pCur->mr.me.ntbEntry.ctime, false);

        // number of columns
        pColInfoData = taosArrayGet(p->pDataBlock, 3);
        colDataAppend(pColInfoData, numOfRows, (char*)&pInfo->pCur->mr.me.ntbEntry.schemaRow.nCols, false);

        // super table name
        pColInfoData = taosArrayGet(p->pDataBlock, 4);
        colDataAppendNULL(pColInfoData, numOfRows);
2185

2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197
        // table comment
        pColInfoData = taosArrayGet(p->pDataBlock, 8);
        if (pInfo->pCur->mr.me.ntbEntry.commentLen > 0) {
          char comment[TSDB_TB_COMMENT_LEN + VARSTR_HEADER_SIZE] = {0};
          STR_TO_VARSTR(comment, pInfo->pCur->mr.me.ntbEntry.comment);
          colDataAppend(pColInfoData, numOfRows, comment, false);
        } else if (pInfo->pCur->mr.me.ntbEntry.commentLen == 0) {
          char comment[VARSTR_HEADER_SIZE + VARSTR_HEADER_SIZE] = {0};
          STR_TO_VARSTR(comment, "");
          colDataAppend(pColInfoData, numOfRows, comment, false);
        } else {
          colDataAppendNULL(pColInfoData, numOfRows);
2198
        }
2199 2200 2201 2202 2203 2204 2205 2206 2207 2208

        // uid
        pColInfoData = taosArrayGet(p->pDataBlock, 5);
        colDataAppend(pColInfoData, numOfRows, (char*)&pInfo->pCur->mr.me.uid, false);

        // ttl
        pColInfoData = taosArrayGet(p->pDataBlock, 7);
        colDataAppend(pColInfoData, numOfRows, (char*)&pInfo->pCur->mr.me.ntbEntry.ttlDays, false);

        STR_TO_VARSTR(n, "NORMAL_TABLE");
H
Haojun Liao 已提交
2209 2210
      }

2211 2212 2213 2214 2215
      pColInfoData = taosArrayGet(p->pDataBlock, 9);
      colDataAppend(pColInfoData, numOfRows, n, false);

      if (++numOfRows >= pOperator->resultInfo.capacity) {
        break;
2216
      }
2217
    }
2218

2219 2220 2221 2222 2223 2224
    // todo temporarily free the cursor here, the true reason why the free is not valid needs to be found
    if (ret != 0) {
      metaCloseTbCursor(pInfo->pCur);
      pInfo->pCur = NULL;
      doSetOperatorCompleted(pOperator);
    }
H
Haojun Liao 已提交
2225

2226 2227
    p->info.rows = numOfRows;
    pInfo->pRes->info.rows = numOfRows;
H
Haojun Liao 已提交
2228

2229 2230
    relocateColumnData(pInfo->pRes, pInfo->scanCols, p->pDataBlock, false);
    doFilterResult(pInfo);
2231

2232 2233 2234 2235 2236 2237 2238
    blockDataDestroy(p);

    pInfo->loadInfo.totalRows += pInfo->pRes->info.rows;
    return (pInfo->pRes->info.rows == 0) ? NULL : pInfo->pRes;
  }
}

2239 2240 2241 2242 2243 2244 2245 2246
static SSDataBlock* sysTableScanUserSTables(SOperatorInfo* pOperator) {
  SExecTaskInfo*     pTaskInfo = pOperator->pTaskInfo;
  SSysTableScanInfo* pInfo = pOperator->info;
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

  pInfo->pRes->info.rows = 0;
D
dapan1121 已提交
2247
  pOperator->status = OP_EXEC_DONE;
2248 2249 2250 2251 2252

  pInfo->loadInfo.totalRows += pInfo->pRes->info.rows;
  return (pInfo->pRes->info.rows == 0) ? NULL : pInfo->pRes;
}

2253 2254 2255 2256
static SSDataBlock* doSysTableScan(SOperatorInfo* pOperator) {
  // build message and send to mnode to fetch the content of system tables.
  SExecTaskInfo*     pTaskInfo = pOperator->pTaskInfo;
  SSysTableScanInfo* pInfo = pOperator->info;
L
Liu Jicong 已提交
2257
  char               dbName[TSDB_DB_NAME_LEN] = {0};
2258 2259

  const char* name = tNameGetTableName(&pInfo->name);
D
dapan1121 已提交
2260 2261 2262 2263
  if (pInfo->showRewrite) {
    getDBNameFromCondition(pInfo->pCondition, dbName);
    sprintf(pInfo->req.db, "%d.%s", pInfo->accountId, dbName);
  }
H
Hongze Cheng 已提交
2264

D
dapan1121 已提交
2265
  if (strncasecmp(name, TSDB_INS_TABLE_TABLES, TSDB_TABLE_FNAME_LEN) == 0) {
2266
    return sysTableScanUserTables(pOperator);
D
dapan1121 已提交
2267
  } else if (strncasecmp(name, TSDB_INS_TABLE_TAGS, TSDB_TABLE_FNAME_LEN) == 0) {
2268
    return sysTableScanUserTags(pOperator);
L
Liu Jicong 已提交
2269 2270
  } else if (strncasecmp(name, TSDB_INS_TABLE_STABLES, TSDB_TABLE_FNAME_LEN) == 0 && pInfo->showRewrite &&
             IS_SYS_DBNAME(dbName)) {
2271
    return sysTableScanUserSTables(pOperator);
H
Haojun Liao 已提交
2272 2273 2274 2275 2276
  } else {  // load the meta from mnode of the given epset
    if (pOperator->status == OP_EXEC_DONE) {
      return NULL;
    }

2277 2278 2279
    while (1) {
      int64_t startTs = taosGetTimestampUs();
      strncpy(pInfo->req.tb, tNameGetTableName(&pInfo->name), tListLen(pInfo->req.tb));
2280
      strcpy(pInfo->req.user, pInfo->pUser);
H
Haojun Liao 已提交
2281

2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292
      int32_t contLen = tSerializeSRetrieveTableReq(NULL, 0, &pInfo->req);
      char*   buf1 = taosMemoryCalloc(1, contLen);
      tSerializeSRetrieveTableReq(buf1, contLen, &pInfo->req);

      // send the fetch remote task result reques
      SMsgSendInfo* pMsgSendInfo = taosMemoryCalloc(1, sizeof(SMsgSendInfo));
      if (NULL == pMsgSendInfo) {
        qError("%s prepare message %d failed", GET_TASKID(pTaskInfo), (int32_t)sizeof(SMsgSendInfo));
        pTaskInfo->code = TSDB_CODE_QRY_OUT_OF_MEMORY;
        return NULL;
      }
H
Haojun Liao 已提交
2293

L
Liu Jicong 已提交
2294 2295
      int32_t msgType = (strcasecmp(name, TSDB_INS_TABLE_DNODE_VARIABLES) == 0) ? TDMT_DND_SYSTABLE_RETRIEVE
                                                                                : TDMT_MND_SYSTABLE_RETRIEVE;
D
dapan1121 已提交
2296

2297 2298 2299
      pMsgSendInfo->param = pOperator;
      pMsgSendInfo->msgInfo.pData = buf1;
      pMsgSendInfo->msgInfo.len = contLen;
D
dapan1121 已提交
2300
      pMsgSendInfo->msgType = msgType;
2301
      pMsgSendInfo->fp = loadSysTableCallback;
D
dapan1121 已提交
2302
      pMsgSendInfo->requestId = pTaskInfo->id.queryId;
H
Haojun Liao 已提交
2303

2304
      int64_t transporterId = 0;
2305 2306
      int32_t code =
          asyncSendMsgToServer(pInfo->readHandle.pMsgCb->clientRpc, &pInfo->epSet, &transporterId, pMsgSendInfo);
2307
      tsem_wait(&pInfo->ready);
H
Haojun Liao 已提交
2308

2309 2310 2311 2312 2313
      if (pTaskInfo->code) {
        qDebug("%s load meta data from mnode failed, totalRows:%" PRIu64 ", code:%s", GET_TASKID(pTaskInfo),
               pInfo->loadInfo.totalRows, tstrerror(pTaskInfo->code));
        return NULL;
      }
H
Haojun Liao 已提交
2314

2315 2316
      SRetrieveMetaTableRsp* pRsp = pInfo->pRsp;
      pInfo->req.showId = pRsp->handle;
H
Haojun Liao 已提交
2317

2318 2319
      if (pRsp->numOfRows == 0 || pRsp->completed) {
        pOperator->status = OP_EXEC_DONE;
2320
        qDebug("%s load meta data from mnode completed, rowsOfSource:%d, totalRows:%" PRIu64, GET_TASKID(pTaskInfo),
2321
               pRsp->numOfRows, pInfo->loadInfo.totalRows);
H
Haojun Liao 已提交
2322

2323
        if (pRsp->numOfRows == 0) {
H
Haojun Liao 已提交
2324
          taosMemoryFree(pRsp);
2325 2326 2327
          return NULL;
        }
      }
H
Haojun Liao 已提交
2328

2329
      char* pStart = pRsp->data;
2330 2331
      extractDataBlockFromFetchRsp(pInfo->pRes, pRsp->data, pOperator->exprSupp.numOfExprs, pInfo->scanCols, &pStart);
      updateLoadRemoteInfo(&pInfo->loadInfo, pRsp->numOfRows, pRsp->compLen, startTs, pOperator);
H
Haojun Liao 已提交
2332

2333 2334
      // todo log the filter info
      doFilterResult(pInfo);
H
Haojun Liao 已提交
2335
      taosMemoryFree(pRsp);
2336 2337
      if (pInfo->pRes->info.rows > 0) {
        return pInfo->pRes;
D
dapan1121 已提交
2338 2339
      } else if (pOperator->status == OP_EXEC_DONE) {
        return NULL;
2340
      }
2341
    }
H
Haojun Liao 已提交
2342 2343 2344
  }
}

2345
int32_t buildSysDbTableInfo(const SSysTableScanInfo* pInfo, int32_t capacity) {
D
dapan1121 已提交
2346
  SSDataBlock* p = buildInfoSchemaTableMetaBlock(TSDB_INS_TABLE_TABLES);
2347
  blockDataEnsureCapacity(p, capacity);
2348

L
Liu Jicong 已提交
2349
  size_t               size = 0;
2350 2351 2352 2353 2354 2355 2356 2357 2358
  const SSysTableMeta* pSysDbTableMeta = NULL;

  getInfosDbMeta(&pSysDbTableMeta, &size);
  p->info.rows = buildDbTableInfoBlock(p, pSysDbTableMeta, size, TSDB_INFORMATION_SCHEMA_DB);

  getPerfDbMeta(&pSysDbTableMeta, &size);
  p->info.rows = buildDbTableInfoBlock(p, pSysDbTableMeta, size, TSDB_PERFORMANCE_SCHEMA_DB);

  pInfo->pRes->info.rows = p->info.rows;
2359
  relocateColumnData(pInfo->pRes, pInfo->scanCols, p->pDataBlock, false);
2360 2361 2362
  blockDataDestroy(p);

  return pInfo->pRes->info.rows;
2363 2364
}

L
Liu Jicong 已提交
2365 2366 2367
int32_t buildDbTableInfoBlock(const SSDataBlock* p, const SSysTableMeta* pSysDbTableMeta, size_t size,
                              const char* dbName) {
  char    n[TSDB_TABLE_FNAME_LEN + VARSTR_HEADER_SIZE] = {0};
2368 2369
  int32_t numOfRows = p->info.rows;

L
Liu Jicong 已提交
2370
  for (int32_t i = 0; i < size; ++i) {
2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390
    const SSysTableMeta* pm = &pSysDbTableMeta[i];

    SColumnInfoData* pColInfoData = taosArrayGet(p->pDataBlock, 0);

    STR_TO_VARSTR(n, pm->name);
    colDataAppend(pColInfoData, numOfRows, n, false);

    // database name
    STR_TO_VARSTR(n, dbName);
    pColInfoData = taosArrayGet(p->pDataBlock, 1);
    colDataAppend(pColInfoData, numOfRows, n, false);

    // create time
    pColInfoData = taosArrayGet(p->pDataBlock, 2);
    colDataAppendNULL(pColInfoData, numOfRows);

    // number of columns
    pColInfoData = taosArrayGet(p->pDataBlock, 3);
    colDataAppend(pColInfoData, numOfRows, (char*)&pm->colNum, false);

L
Liu Jicong 已提交
2391
    for (int32_t j = 4; j <= 8; ++j) {
2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406
      pColInfoData = taosArrayGet(p->pDataBlock, j);
      colDataAppendNULL(pColInfoData, numOfRows);
    }

    STR_TO_VARSTR(n, "SYSTEM_TABLE");

    pColInfoData = taosArrayGet(p->pDataBlock, 9);
    colDataAppend(pColInfoData, numOfRows, n, false);

    numOfRows += 1;
  }

  return numOfRows;
}

2407
SOperatorInfo* createSysTableScanOperatorInfo(void* readHandle, SSystemTableScanPhysiNode* pScanPhyNode,
2408
                                              const char* pUser, SExecTaskInfo* pTaskInfo) {
H
Haojun Liao 已提交
2409 2410 2411
  SSysTableScanInfo* pInfo = taosMemoryCalloc(1, sizeof(SSysTableScanInfo));
  SOperatorInfo*     pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
  if (pInfo == NULL || pOperator == NULL) {
2412
    goto _error;
H
Haojun Liao 已提交
2413 2414
  }

2415 2416 2417
  SScanPhysiNode* pScanNode = &pScanPhyNode->scan;

  SDataBlockDescNode* pDescNode = pScanNode->node.pOutputDataBlockDesc;
2418
  SSDataBlock*        pResBlock = createResDataBlock(pDescNode);
2419 2420

  int32_t num = 0;
2421
  SArray* colList = extractColMatchInfo(pScanNode->pScanCols, pDescNode, &num, COL_MATCH_FROM_COL_ID);
2422

2423 2424
  pInfo->accountId = pScanPhyNode->accountId;
  pInfo->pUser = taosMemoryStrDup((void*)pUser);
2425
  pInfo->showRewrite = pScanPhyNode->showRewrite;
2426 2427 2428
  pInfo->pRes = pResBlock;
  pInfo->pCondition = pScanNode->node.pConditions;
  pInfo->scanCols = colList;
2429

2430
  initResultSizeInfo(&pOperator->resultInfo, 4096);
H
Haojun Liao 已提交
2431

2432
  tNameAssign(&pInfo->name, &pScanNode->tableName);
2433
  const char* name = tNameGetTableName(&pInfo->name);
2434

D
dapan1121 已提交
2435 2436
  if (strncasecmp(name, TSDB_INS_TABLE_TABLES, TSDB_TABLE_FNAME_LEN) == 0 ||
      strncasecmp(name, TSDB_INS_TABLE_TAGS, TSDB_TABLE_FNAME_LEN) == 0) {
L
Liu Jicong 已提交
2437
    pInfo->readHandle = *(SReadHandle*)readHandle;
2438
    blockDataEnsureCapacity(pInfo->pRes, pOperator->resultInfo.capacity);
H
Haojun Liao 已提交
2439 2440
  } else {
    tsem_init(&pInfo->ready, 0, 0);
2441
    pInfo->epSet = pScanPhyNode->mgmtEpSet;
2442
    pInfo->readHandle = *(SReadHandle*)readHandle;
H
Haojun Liao 已提交
2443 2444
  }

2445
  pOperator->name = "SysTableScanOperator";
H
Haojun Liao 已提交
2446
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_SYSTABLE_SCAN;
2447 2448 2449
  pOperator->blocking = false;
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
2450
  pOperator->exprSupp.numOfExprs = taosArrayGetSize(pResBlock->pDataBlock);
2451
  pOperator->pTaskInfo = pTaskInfo;
2452

L
Liu Jicong 已提交
2453 2454
  pOperator->fpSet =
      createOperatorFpSet(operatorDummyOpenFn, doSysTableScan, NULL, NULL, destroySysScanOperator, NULL, NULL, NULL);
H
Haojun Liao 已提交
2455 2456

  return pOperator;
2457

2458
_error:
2459 2460 2461 2462
  taosMemoryFreeClear(pInfo);
  taosMemoryFreeClear(pOperator);
  terrno = TSDB_CODE_QRY_OUT_OF_MEMORY;
  return NULL;
H
Haojun Liao 已提交
2463
}
H
Haojun Liao 已提交
2464

2465
static SSDataBlock* doTagScan(SOperatorInfo* pOperator) {
H
Haojun Liao 已提交
2466 2467 2468 2469
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

2470 2471 2472
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;

  STagScanInfo* pInfo = pOperator->info;
2473
  SExprInfo*    pExprInfo = &pOperator->exprSupp.pExprInfo[0];
2474
  SSDataBlock*  pRes = pInfo->pRes;
H
Haojun Liao 已提交
2475

wmmhello's avatar
wmmhello 已提交
2476 2477
  int32_t size = taosArrayGetSize(pInfo->pTableList->pTableList);
  if (size == 0) {
H
Haojun Liao 已提交
2478 2479 2480 2481
    setTaskStatus(pTaskInfo, TASK_COMPLETED);
    return NULL;
  }

2482 2483 2484
  char        str[512] = {0};
  int32_t     count = 0;
  SMetaReader mr = {0};
2485
  metaReaderInit(&mr, pInfo->readHandle.meta, 0);
H
Haojun Liao 已提交
2486

wmmhello's avatar
wmmhello 已提交
2487 2488
  while (pInfo->curPos < size && count < pOperator->resultInfo.capacity) {
    STableKeyInfo* item = taosArrayGet(pInfo->pTableList->pTableList, pInfo->curPos);
L
Liu Jicong 已提交
2489
    int32_t        code = metaGetTableEntryByUid(&mr, item->uid);
2490
    tDecoderClear(&mr.coder);
H
Haojun Liao 已提交
2491
    if (code != TSDB_CODE_SUCCESS) {
L
Liu Jicong 已提交
2492 2493
      qError("failed to get table meta, uid:0x%" PRIx64 ", code:%s, %s", item->uid, tstrerror(terrno),
             GET_TASKID(pTaskInfo));
H
Haojun Liao 已提交
2494 2495 2496
      metaReaderClear(&mr);
      longjmp(pTaskInfo->env, terrno);
    }
H
Haojun Liao 已提交
2497

2498
    for (int32_t j = 0; j < pOperator->exprSupp.numOfExprs; ++j) {
2499 2500 2501 2502 2503 2504
      SColumnInfoData* pDst = taosArrayGet(pRes->pDataBlock, pExprInfo[j].base.resSchema.slotId);

      // refactor later
      if (fmIsScanPseudoColumnFunc(pExprInfo[j].pExpr->_function.functionId)) {
        STR_TO_VARSTR(str, mr.me.name);
        colDataAppend(pDst, count, str, false);
2505
      } else {  // it is a tag value
wmmhello's avatar
wmmhello 已提交
2506 2507 2508 2509
        STagVal val = {0};
        val.cid = pExprInfo[j].base.pParam[0].pCol->colId;
        const char* p = metaGetTableTagVal(&mr.me, pDst->info.type, &val);

2510 2511 2512 2513
        char* data = NULL;
        if (pDst->info.type != TSDB_DATA_TYPE_JSON && p != NULL) {
          data = tTagValToData((const STagVal*)p, false);
        } else {
wmmhello's avatar
wmmhello 已提交
2514 2515
          data = (char*)p;
        }
L
Liu Jicong 已提交
2516 2517
        colDataAppend(pDst, count, data,
                      (data == NULL) || (pDst->info.type == TSDB_DATA_TYPE_JSON && tTagIsJsonNull(data)));
2518

2519 2520
        if (pDst->info.type != TSDB_DATA_TYPE_JSON && p != NULL && IS_VAR_DATA_TYPE(((const STagVal*)p)->type) &&
            data != NULL) {
wmmhello's avatar
wmmhello 已提交
2521
          taosMemoryFree(data);
wmmhello's avatar
wmmhello 已提交
2522
        }
H
Haojun Liao 已提交
2523 2524 2525
      }
    }

2526
    count += 1;
wmmhello's avatar
wmmhello 已提交
2527
    if (++pInfo->curPos >= size) {
2528
      doSetOperatorCompleted(pOperator);
H
Haojun Liao 已提交
2529 2530 2531
    }
  }

2532 2533
  metaReaderClear(&mr);

2534
  // qDebug("QInfo:0x%"PRIx64" create tag values results completed, rows:%d", GET_TASKID(pRuntimeEnv), count);
H
Haojun Liao 已提交
2535
  if (pOperator->status == OP_EXEC_DONE) {
2536
    setTaskStatus(pTaskInfo, TASK_COMPLETED);
H
Haojun Liao 已提交
2537 2538 2539
  }

  pRes->info.rows = count;
wmmhello's avatar
wmmhello 已提交
2540
  pOperator->resultInfo.totalRows += count;
2541

2542
  return (pRes->info.rows == 0) ? NULL : pInfo->pRes;
H
Haojun Liao 已提交
2543 2544 2545 2546 2547
}

static void destroyTagScanOperatorInfo(void* param, int32_t numOfOutput) {
  STagScanInfo* pInfo = (STagScanInfo*)param;
  pInfo->pRes = blockDataDestroy(pInfo->pRes);
L
Liu Jicong 已提交
2548

S
shenglian zhou 已提交
2549
  taosArrayDestroy(pInfo->pColMatchInfo);
L
Liu Jicong 已提交
2550

D
dapan1121 已提交
2551
  taosMemoryFreeClear(param);
H
Haojun Liao 已提交
2552 2553
}

2554 2555
SOperatorInfo* createTagScanOperatorInfo(SReadHandle* pReadHandle, STagScanPhysiNode* pPhyNode,
                                         STableListInfo* pTableListInfo, SExecTaskInfo* pTaskInfo) {
2556
  STagScanInfo*  pInfo = taosMemoryCalloc(1, sizeof(STagScanInfo));
H
Haojun Liao 已提交
2557 2558 2559 2560 2561
  SOperatorInfo* pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }

2562 2563
  SDataBlockDescNode* pDescNode = pPhyNode->node.pOutputDataBlockDesc;

2564
  int32_t    num = 0;
2565 2566
  int32_t    numOfExprs = 0;
  SExprInfo* pExprInfo = createExprInfo(pPhyNode->pScanPseudoCols, NULL, &numOfExprs);
L
Liu Jicong 已提交
2567
  SArray*    colList = extractColMatchInfo(pPhyNode->pScanPseudoCols, pDescNode, &num, COL_MATCH_FROM_COL_ID);
2568

2569 2570 2571 2572
  int32_t code = initExprSupp(&pOperator->exprSupp, pExprInfo, numOfExprs);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
2573

2574 2575 2576 2577 2578
  pInfo->pTableList = pTableListInfo;
  pInfo->pColMatchInfo = colList;
  pInfo->pRes = createResDataBlock(pDescNode);
  pInfo->readHandle = *pReadHandle;
  pInfo->curPos = 0;
2579

2580
  pOperator->name = "TagScanOperator";
2581
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_TAG_SCAN;
2582

2583 2584 2585 2586
  pOperator->blocking = false;
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
  pOperator->pTaskInfo = pTaskInfo;
2587

2588
  initResultSizeInfo(&pOperator->resultInfo, 4096);
2589 2590
  blockDataEnsureCapacity(pInfo->pRes, pOperator->resultInfo.capacity);

2591 2592
  pOperator->fpSet =
      createOperatorFpSet(operatorDummyOpenFn, doTagScan, NULL, NULL, destroyTagScanOperatorInfo, NULL, NULL, NULL);
H
Haojun Liao 已提交
2593 2594

  return pOperator;
2595

2596
_error:
H
Haojun Liao 已提交
2597 2598 2599 2600 2601
  taosMemoryFree(pInfo);
  taosMemoryFree(pOperator);
  terrno = TSDB_CODE_OUT_OF_MEMORY;
  return NULL;
}
2602

H
Haojun Liao 已提交
2603
int32_t createScanTableListInfo(SScanPhysiNode* pScanNode, SNodeList* pGroupTags, bool groupSort, SReadHandle* pHandle,
2604 2605
                                STableListInfo* pTableListInfo, SNode* pTagCond, SNode* pTagIndexCond,
                                const char* idStr) {
H
Haojun Liao 已提交
2606 2607
  int64_t st = taosGetTimestampUs();

2608
  int32_t code = getTableList(pHandle->meta, pHandle->vnode, pScanNode, pTagCond, pTagIndexCond, pTableListInfo);
2609
  if (code != TSDB_CODE_SUCCESS) {
2610
    return code;
2611 2612
  }

H
Haojun Liao 已提交
2613
  int64_t st1 = taosGetTimestampUs();
L
Liu Jicong 已提交
2614
  qDebug("generate queried table list completed, elapsed time:%.2f ms %s", (st1 - st) / 1000.0, idStr);
H
Haojun Liao 已提交
2615

2616
  if (taosArrayGetSize(pTableListInfo->pTableList) == 0) {
2617
    qDebug("no table qualified for query, %s" PRIx64, idStr);
2618 2619
    return TSDB_CODE_SUCCESS;
  }
2620

H
Haojun Liao 已提交
2621 2622
  pTableListInfo->needSortTableByGroupId = groupSort;
  code = generateGroupIdMap(pTableListInfo, pHandle, pGroupTags);
2623
  if (code != TSDB_CODE_SUCCESS) {
wmmhello's avatar
wmmhello 已提交
2624
    return code;
2625 2626
  }

H
Haojun Liao 已提交
2627
  int64_t st2 = taosGetTimestampUs();
L
Liu Jicong 已提交
2628
  qDebug("generate group id map completed, elapsed time:%.2f ms %s", (st2 - st1) / 1000.0, idStr);
H
Haojun Liao 已提交
2629

2630 2631 2632
  return TSDB_CODE_SUCCESS;
}

S
slzhou 已提交
2633
int32_t createMultipleDataReaders(SQueryTableDataCond* pQueryCond, SReadHandle* pHandle, STableListInfo* pTableListInfo,
H
Haojun Liao 已提交
2634
                                  int32_t tableStartIdx, int32_t tableEndIdx, SArray* arrayReader, const char* idstr) {
S
slzhou 已提交
2635 2636 2637 2638
  for (int32_t i = tableStartIdx; i <= tableEndIdx; ++i) {
    SArray* subTableList = taosArrayInit(1, sizeof(STableKeyInfo));
    taosArrayPush(subTableList, taosArrayGet(pTableListInfo->pTableList, i));

H
Haojun Liao 已提交
2639 2640
    STsdbReader* pReader = NULL;
    tsdbReaderOpen(pHandle->vnode, pQueryCond, subTableList, &pReader, idstr);
S
slzhou 已提交
2641 2642 2643 2644 2645 2646 2647 2648
    taosArrayPush(arrayReader, &pReader);

    taosArrayDestroy(subTableList);
  }

  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
2649
// todo refactor
2650 2651
static int32_t loadDataBlockFromOneTable(SOperatorInfo* pOperator, STableMergeScanInfo* pTableScanInfo,
                                         int32_t readerIdx, SSDataBlock* pBlock, uint32_t* status) {
L
Liu Jicong 已提交
2652
  SExecTaskInfo*       pTaskInfo = pOperator->pTaskInfo;
S
shenglian zhou 已提交
2653
  STableMergeScanInfo* pInfo = pOperator->info;
2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679

  SFileBlockLoadRecorder* pCost = &pTableScanInfo->readRecorder;

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

  *status = pInfo->dataBlockLoadFlag;
  if (pTableScanInfo->pFilterNode != NULL ||
      overlapWithTimeWindow(&pTableScanInfo->interval, &pBlock->info, pTableScanInfo->cond.order)) {
    (*status) = FUNC_DATA_REQUIRED_DATA_LOAD;
  }

  SDataBlockInfo* pBlockInfo = &pBlock->info;
  taosMemoryFreeClear(pBlock->pBlockAgg);

  if (*status == FUNC_DATA_REQUIRED_FILTEROUT) {
    qDebug("%s data block filter out, brange:%" PRId64 "-%" PRId64 ", rows:%d", GET_TASKID(pTaskInfo),
           pBlockInfo->window.skey, pBlockInfo->window.ekey, pBlockInfo->rows);
    pCost->filterOutBlocks += 1;
    return TSDB_CODE_SUCCESS;
  } else if (*status == FUNC_DATA_REQUIRED_NOT_LOAD) {
    qDebug("%s data block skipped, brange:%" PRId64 "-%" PRId64 ", rows:%d", GET_TASKID(pTaskInfo),
           pBlockInfo->window.skey, pBlockInfo->window.ekey, pBlockInfo->rows);
    pCost->skipBlocks += 1;

    // clear all data in pBlock that are set when handing the previous block
2680
    for (int32_t i = 0; i < taosArrayGetSize(pBlock->pDataBlock); ++i) {
2681 2682 2683 2684 2685 2686 2687 2688 2689 2690
      SColumnInfoData* pcol = taosArrayGet(pBlock->pDataBlock, i);
      pcol->pData = NULL;
    }

    return TSDB_CODE_SUCCESS;
  } else if (*status == FUNC_DATA_REQUIRED_STATIS_LOAD) {
    pCost->loadBlockStatis += 1;

    bool             allColumnsHaveAgg = true;
    SColumnDataAgg** pColAgg = NULL;
H
Hongze Cheng 已提交
2691
    STsdbReader*     reader = taosArrayGetP(pTableScanInfo->dataReaders, readerIdx);
2692
    tsdbRetrieveDatablockSMA(reader, &pColAgg, &allColumnsHaveAgg);
2693 2694

    if (allColumnsHaveAgg == true) {
2695
      int32_t numOfCols = taosArrayGetSize(pBlock->pDataBlock);
2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719

      // todo create this buffer during creating operator
      if (pBlock->pBlockAgg == NULL) {
        pBlock->pBlockAgg = taosMemoryCalloc(numOfCols, POINTER_BYTES);
      }

      for (int32_t i = 0; i < numOfCols; ++i) {
        SColMatchInfo* pColMatchInfo = taosArrayGet(pTableScanInfo->pColMatchInfo, i);
        if (!pColMatchInfo->output) {
          continue;
        }
        pBlock->pBlockAgg[pColMatchInfo->targetSlotId] = pColAgg[i];
      }

      return TSDB_CODE_SUCCESS;
    } else {  // failed to load the block sma data, data block statistics does not exist, load data block instead
      *status = FUNC_DATA_REQUIRED_DATA_LOAD;
    }
  }

  ASSERT(*status == FUNC_DATA_REQUIRED_DATA_LOAD);

  // todo filter data block according to the block sma data firstly
#if 0
H
Haojun Liao 已提交
2720
  if (!doFilterByBlockSMA(pBlock->pBlockStatis, pTableScanInfo->pCtx, pBlockInfo->rows)) {
2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731
    pCost->filterOutBlocks += 1;
    qDebug("%s data block filter out, brange:%" PRId64 "-%" PRId64 ", rows:%d", GET_TASKID(pTaskInfo), pBlockInfo->window.skey,
           pBlockInfo->window.ekey, pBlockInfo->rows);
    (*status) = FUNC_DATA_REQUIRED_FILTEROUT;
    return TSDB_CODE_SUCCESS;
  }
#endif

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

H
Hongze Cheng 已提交
2732
  STsdbReader* reader = taosArrayGetP(pTableScanInfo->dataReaders, readerIdx);
2733 2734 2735 2736 2737
  SArray*      pCols = tsdbRetrieveDataBlock(reader, NULL);
  if (pCols == NULL) {
    return terrno;
  }

2738
  relocateColumnData(pBlock, pTableScanInfo->pColMatchInfo, pCols, true);
2739 2740

  // currently only the tbname pseudo column
S
shenglian zhou 已提交
2741 2742 2743
  if (pTableScanInfo->pseudoSup.numOfExprs > 0) {
    int32_t code = addTagPseudoColumnData(&pTableScanInfo->readHandle, pTableScanInfo->pseudoSup.pExprInfo,
                                          pTableScanInfo->pseudoSup.numOfExprs, pBlock, GET_TASKID(pTaskInfo));
H
Haojun Liao 已提交
2744 2745 2746
    if (code != TSDB_CODE_SUCCESS) {
      longjmp(pTaskInfo->env, code);
    }
2747 2748
  }

2749 2750 2751
  if (pTableScanInfo->pFilterNode != NULL) {
    int64_t st = taosGetTimestampMs();
    doFilter(pTableScanInfo->pFilterNode, pBlock, pTableScanInfo->pColMatchInfo);
2752

2753 2754
    double el = (taosGetTimestampUs() - st) / 1000.0;
    pTableScanInfo->readRecorder.filterTime += el;
2755

2756 2757 2758 2759 2760 2761 2762
    if (pBlock->info.rows == 0) {
      pCost->filterOutBlocks += 1;
      qDebug("%s data block filter out, brange:%" PRId64 "-%" PRId64 ", rows:%d, elapsed time:%.2f ms",
             GET_TASKID(pTaskInfo), pBlockInfo->window.skey, pBlockInfo->window.ekey, pBlockInfo->rows, el);
    } else {
      qDebug("%s data block filter applied, elapsed time:%.2f ms", GET_TASKID(pTaskInfo), el);
    }
2763 2764 2765 2766 2767 2768 2769 2770
  }

  return TSDB_CODE_SUCCESS;
}

typedef struct STableMergeScanSortSourceParam {
  SOperatorInfo* pOperator;
  int32_t        readerIdx;
2771
  SSDataBlock*   inputBlock;
2772 2773 2774 2775 2776 2777
} STableMergeScanSortSourceParam;

static SSDataBlock* getTableDataBlock(void* param) {
  STableMergeScanSortSourceParam* source = param;
  SOperatorInfo*                  pOperator = source->pOperator;
  int32_t                         readerIdx = source->readerIdx;
2778
  SSDataBlock*                    pBlock = source->inputBlock;
2779 2780 2781 2782
  STableMergeScanInfo*            pTableScanInfo = pOperator->info;

  int64_t st = taosGetTimestampUs();

2783 2784
  blockDataCleanup(pBlock);

H
Hongze Cheng 已提交
2785
  STsdbReader* reader = taosArrayGetP(pTableScanInfo->dataReaders, readerIdx);
2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796
  while (tsdbNextDataBlock(reader)) {
    if (isTaskKilled(pOperator->pTaskInfo)) {
      longjmp(pOperator->pTaskInfo->env, TSDB_CODE_TSC_QUERY_CANCELLED);
    }

    // process this data block based on the probabilities
    bool processThisBlock = processBlockWithProbability(&pTableScanInfo->sample);
    if (!processThisBlock) {
      continue;
    }

2797 2798 2799 2800
    blockDataCleanup(pBlock);
    SDataBlockInfo binfo = pBlock->info;
    tsdbRetrieveDataBlockInfo(reader, &binfo);

2801
    blockDataEnsureCapacity(pBlock, binfo.rows);
2802 2803 2804 2805
    pBlock->info.type = binfo.type;
    pBlock->info.uid = binfo.uid;
    pBlock->info.window = binfo.window;
    pBlock->info.rows = binfo.rows;
2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831

    uint32_t status = 0;
    int32_t  code = loadDataBlockFromOneTable(pOperator, pTableScanInfo, readerIdx, pBlock, &status);
    //    int32_t  code = loadDataBlockOnDemand(pOperator->pRuntimeEnv, pTableScanInfo, pBlock, &status);
    if (code != TSDB_CODE_SUCCESS) {
      longjmp(pOperator->pTaskInfo->env, code);
    }

    // current block is filter out according to filter condition, continue load the next block
    if (status == FUNC_DATA_REQUIRED_FILTEROUT || pBlock->info.rows == 0) {
      continue;
    }

    uint64_t* groupId = taosHashGet(pOperator->pTaskInfo->tableqinfoList.map, &pBlock->info.uid, sizeof(int64_t));
    if (groupId) {
      pBlock->info.groupId = *groupId;
    }

    pOperator->resultInfo.totalRows = pTableScanInfo->readRecorder.totalRows;
    pTableScanInfo->readRecorder.elapsedTime += (taosGetTimestampUs() - st) / 1000.0;

    return pBlock;
  }
  return NULL;
}

2832 2833 2834 2835 2836 2837 2838 2839 2840
SArray* generateSortByTsInfo(SArray* colMatchInfo, int32_t order) {
  int32_t tsTargetSlotId = 0;
  for (int32_t i = 0; i < taosArrayGetSize(colMatchInfo); ++i) {
    SColMatchInfo* colInfo = taosArrayGet(colMatchInfo, i);
    if (colInfo->colId == PRIMARYKEY_TIMESTAMP_COL_ID) {
      tsTargetSlotId = colInfo->targetSlotId;
    }
  }

2841 2842 2843
  SArray*         pList = taosArrayInit(1, sizeof(SBlockOrderInfo));
  SBlockOrderInfo bi = {0};
  bi.order = order;
2844
  bi.slotId = tsTargetSlotId;
2845 2846 2847 2848 2849 2850 2851
  bi.nullFirst = NULL_ORDER_FIRST;

  taosArrayPush(pList, &bi);

  return pList;
}

2852
int32_t startGroupTableMergeScan(SOperatorInfo* pOperator) {
2853 2854 2855
  STableMergeScanInfo* pInfo = pOperator->info;
  SExecTaskInfo*       pTaskInfo = pOperator->pTaskInfo;

S
slzhou 已提交
2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866
  {
    size_t  tableListSize = taosArrayGetSize(pInfo->tableListInfo->pTableList);
    int32_t i = pInfo->tableStartIndex + 1;
    for (; i < tableListSize; ++i) {
      STableKeyInfo* tableKeyInfo = taosArrayGet(pInfo->tableListInfo->pTableList, i);
      if (tableKeyInfo->groupId != pInfo->groupId) {
        break;
      }
    }
    pInfo->tableEndIndex = i - 1;
  }
2867

S
slzhou 已提交
2868 2869
  int32_t tableStartIdx = pInfo->tableStartIndex;
  int32_t tableEndIdx = pInfo->tableEndIndex;
2870

S
slzhou 已提交
2871
  STableListInfo* tableListInfo = pInfo->tableListInfo;
2872
  pInfo->dataReaders = taosArrayInit(64, POINTER_BYTES);
S
slzhou 已提交
2873
  createMultipleDataReaders(&pInfo->cond, &pInfo->readHandle, tableListInfo, tableStartIdx, tableEndIdx,
2874
                            pInfo->dataReaders, GET_TASKID(pTaskInfo));
2875

2876 2877
  // todo the total available buffer should be determined by total capacity of buffer of this task.
  // the additional one is reserved for merge result
S
slzhou 已提交
2878
  pInfo->sortBufSize = pInfo->bufPageSize * (tableEndIdx - tableStartIdx + 1 + 1);
2879
  int32_t numOfBufPage = pInfo->sortBufSize / pInfo->bufPageSize;
L
Liu Jicong 已提交
2880 2881
  pInfo->pSortHandle = tsortCreateSortHandle(pInfo->pSortInfo, SORT_MULTISOURCE_MERGE, pInfo->bufPageSize, numOfBufPage,
                                             pInfo->pSortInputBlock, pTaskInfo->id.str);
2882 2883 2884 2885

  tsortSetFetchRawDataFp(pInfo->pSortHandle, getTableDataBlock, NULL, NULL);

  size_t numReaders = taosArrayGetSize(pInfo->dataReaders);
2886 2887 2888 2889 2890 2891 2892 2893
  for (int32_t i = 0; i < numReaders; ++i) {
    STableMergeScanSortSourceParam param = {0};
    param.readerIdx = i;
    param.pOperator = pOperator;
    param.inputBlock = createOneDataBlock(pInfo->pResBlock, false);
    taosArrayPush(pInfo->sortSourceParams, &param);
  }

2894 2895
  for (int32_t i = 0; i < numReaders; ++i) {
    SSortSource*                    ps = taosMemoryCalloc(1, sizeof(SSortSource));
2896
    STableMergeScanSortSourceParam* param = taosArrayGet(pInfo->sortSourceParams, i);
2897 2898 2899 2900 2901 2902 2903 2904 2905 2906
    ps->param = param;
    tsortAddSource(pInfo->pSortHandle, ps);
  }

  int32_t code = tsortOpen(pInfo->pSortHandle);

  if (code != TSDB_CODE_SUCCESS) {
    longjmp(pTaskInfo->env, terrno);
  }

2907 2908 2909 2910 2911 2912 2913
  return TSDB_CODE_SUCCESS;
}

int32_t stopGroupTableMergeScan(SOperatorInfo* pOperator) {
  STableMergeScanInfo* pInfo = pOperator->info;
  SExecTaskInfo*       pTaskInfo = pOperator->pTaskInfo;

2914 2915
  size_t numReaders = taosArrayGetSize(pInfo->dataReaders);

2916 2917 2918 2919 2920 2921 2922
  SSortExecInfo sortExecInfo = tsortGetSortExecInfo(pInfo->pSortHandle);
  pInfo->sortExecInfo.sortMethod = sortExecInfo.sortMethod;
  pInfo->sortExecInfo.sortBuffer = sortExecInfo.sortBuffer;
  pInfo->sortExecInfo.loops += sortExecInfo.loops;
  pInfo->sortExecInfo.readBytes += sortExecInfo.readBytes;
  pInfo->sortExecInfo.writeBytes += sortExecInfo.writeBytes;

2923 2924 2925 2926
  for (int32_t i = 0; i < numReaders; ++i) {
    STableMergeScanSortSourceParam* param = taosArrayGet(pInfo->sortSourceParams, i);
    blockDataDestroy(param->inputBlock);
  }
2927 2928
  taosArrayClear(pInfo->sortSourceParams);

2929 2930 2931
  tsortDestroySortHandle(pInfo->pSortHandle);

  for (int32_t i = 0; i < numReaders; ++i) {
H
Haojun Liao 已提交
2932 2933
    STsdbReader* reader = taosArrayGetP(pInfo->dataReaders, i);
    tsdbReaderClose(reader);
2934
  }
2935 2936
  taosArrayDestroy(pInfo->dataReaders);
  pInfo->dataReaders = NULL;
2937 2938 2939
  return TSDB_CODE_SUCCESS;
}

L
Liu Jicong 已提交
2940 2941
SSDataBlock* getSortedTableMergeScanBlockData(SSortHandle* pHandle, SSDataBlock* pResBlock, int32_t capacity,
                                              SOperatorInfo* pOperator) {
2942 2943 2944
  STableMergeScanInfo* pInfo = pOperator->info;
  SExecTaskInfo*       pTaskInfo = pOperator->pTaskInfo;

2945 2946
  blockDataCleanup(pResBlock);
  blockDataEnsureCapacity(pResBlock, capacity);
2947 2948

  while (1) {
2949
    STupleHandle* pTupleHandle = tsortNextTuple(pHandle);
2950 2951 2952 2953
    if (pTupleHandle == NULL) {
      break;
    }

2954 2955
    appendOneRowToDataBlock(pResBlock, pTupleHandle);
    if (pResBlock->info.rows >= capacity) {
2956 2957 2958 2959
      break;
    }
  }

2960 2961
  qDebug("%s get sorted row blocks, rows:%d", GET_TASKID(pTaskInfo), pResBlock->info.rows);
  return (pResBlock->info.rows > 0) ? pResBlock : NULL;
2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975
}

SSDataBlock* doTableMergeScan(SOperatorInfo* pOperator) {
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

  SExecTaskInfo*       pTaskInfo = pOperator->pTaskInfo;
  STableMergeScanInfo* pInfo = pOperator->info;

  int32_t code = pOperator->fpSet._openFn(pOperator);
  if (code != TSDB_CODE_SUCCESS) {
    longjmp(pTaskInfo->env, code);
  }
S
slzhou 已提交
2976 2977 2978
  size_t tableListSize = taosArrayGetSize(pInfo->tableListInfo->pTableList);
  if (!pInfo->hasGroupId) {
    pInfo->hasGroupId = true;
2979

S
slzhou 已提交
2980
    if (tableListSize == 0) {
2981 2982 2983
      doSetOperatorCompleted(pOperator);
      return NULL;
    }
S
slzhou 已提交
2984 2985
    pInfo->tableStartIndex = 0;
    pInfo->groupId = ((STableKeyInfo*)taosArrayGet(pInfo->tableListInfo->pTableList, pInfo->tableStartIndex))->groupId;
2986 2987
    startGroupTableMergeScan(pOperator);
  }
S
slzhou 已提交
2988 2989
  SSDataBlock* pBlock = NULL;
  while (pInfo->tableStartIndex < tableListSize) {
L
Liu Jicong 已提交
2990 2991
    pBlock = getSortedTableMergeScanBlockData(pInfo->pSortHandle, pInfo->pResBlock, pOperator->resultInfo.capacity,
                                              pOperator);
S
slzhou 已提交
2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006
    if (pBlock != NULL) {
      pBlock->info.groupId = pInfo->groupId;
      pOperator->resultInfo.totalRows += pBlock->info.rows;
      return pBlock;
    } else {
      stopGroupTableMergeScan(pOperator);
      if (pInfo->tableEndIndex >= tableListSize - 1) {
        doSetOperatorCompleted(pOperator);
        break;
      }
      pInfo->tableStartIndex = pInfo->tableEndIndex + 1;
      pInfo->groupId =
          ((STableKeyInfo*)taosArrayGet(pInfo->tableListInfo->pTableList, pInfo->tableStartIndex))->groupId;
      startGroupTableMergeScan(pOperator);
    }
wmmhello's avatar
wmmhello 已提交
3007 3008
  }

3009 3010 3011 3012 3013
  return pBlock;
}

void destroyTableMergeScanOperatorInfo(void* param, int32_t numOfOutput) {
  STableMergeScanInfo* pTableScanInfo = (STableMergeScanInfo*)param;
3014
  cleanupQueryTableDataCond(&pTableScanInfo->cond);
3015
  taosArrayDestroy(pTableScanInfo->sortSourceParams);
3016 3017

  for (int32_t i = 0; i < taosArrayGetSize(pTableScanInfo->dataReaders); ++i) {
H
Hongze Cheng 已提交
3018
    STsdbReader* reader = taosArrayGetP(pTableScanInfo->dataReaders, i);
H
refact  
Hongze Cheng 已提交
3019
    tsdbReaderClose(reader);
3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030
  }
  taosArrayDestroy(pTableScanInfo->dataReaders);

  if (pTableScanInfo->pColMatchInfo != NULL) {
    taosArrayDestroy(pTableScanInfo->pColMatchInfo);
  }

  pTableScanInfo->pResBlock = blockDataDestroy(pTableScanInfo->pResBlock);
  pTableScanInfo->pSortInputBlock = blockDataDestroy(pTableScanInfo->pSortInputBlock);

  taosArrayDestroy(pTableScanInfo->pSortInfo);
3031
  cleanupExprSupp(&pTableScanInfo->pseudoSup);
L
Liu Jicong 已提交
3032

3033
  taosMemoryFreeClear(pTableScanInfo->rowEntryInfoOffset);
D
dapan1121 已提交
3034
  taosMemoryFreeClear(param);
3035 3036
}

3037 3038
typedef struct STableMergeScanExecInfo {
  SFileBlockLoadRecorder blockRecorder;
L
Liu Jicong 已提交
3039
  SSortExecInfo          sortExecInfo;
3040 3041
} STableMergeScanExecInfo;

3042 3043
int32_t getTableMergeScanExplainExecInfo(SOperatorInfo* pOptr, void** pOptrExplain, uint32_t* len) {
  ASSERT(pOptr != NULL);
3044 3045
  // TODO: merge these two info into one struct
  STableMergeScanExecInfo* execInfo = taosMemoryCalloc(1, sizeof(STableMergeScanExecInfo));
L
Liu Jicong 已提交
3046
  STableMergeScanInfo*     pInfo = pOptr->info;
3047
  execInfo->blockRecorder = pInfo->readRecorder;
3048
  execInfo->sortExecInfo = pInfo->sortExecInfo;
3049 3050 3051

  *pOptrExplain = execInfo;
  *len = sizeof(STableMergeScanExecInfo);
L
Liu Jicong 已提交
3052

3053 3054 3055
  return TSDB_CODE_SUCCESS;
}

S
slzhou 已提交
3056 3057 3058
int32_t compareTableKeyInfoByGid(const void* p1, const void* p2) {
  const STableKeyInfo* info1 = p1;
  const STableKeyInfo* info2 = p2;
3059 3060 3061 3062 3063 3064 3065
  if (info1->groupId < info2->groupId) {
    return -1;
  } else if (info1->groupId > info2->groupId) {
    return 1;
  } else {
    return 0;
  }
S
slzhou 已提交
3066 3067
}

3068
SOperatorInfo* createTableMergeScanOperatorInfo(STableScanPhysiNode* pTableScanNode, STableListInfo* pTableListInfo,
3069
                                                SReadHandle* readHandle, SExecTaskInfo* pTaskInfo) {
3070 3071 3072 3073 3074
  STableMergeScanInfo* pInfo = taosMemoryCalloc(1, sizeof(STableMergeScanInfo));
  SOperatorInfo*       pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }
3075
  if (pTableScanNode->pGroupTags) {
S
slzhou 已提交
3076 3077
    taosArraySort(pTableListInfo->pTableList, compareTableKeyInfoByGid);
  }
3078 3079 3080 3081

  SDataBlockDescNode* pDescNode = pTableScanNode->scan.node.pOutputDataBlockDesc;

  int32_t numOfCols = 0;
L
Liu Jicong 已提交
3082
  SArray* pColList = extractColMatchInfo(pTableScanNode->scan.pScanCols, pDescNode, &numOfCols, COL_MATCH_FROM_COL_ID);
3083 3084 3085 3086 3087 3088 3089

  int32_t code = initQueryTableDataCond(&pInfo->cond, pTableScanNode);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }

  if (pTableScanNode->scan.pScanPseudoCols != NULL) {
3090 3091 3092
    SExprSupp* pSup = &pInfo->pseudoSup;
    pSup->pExprInfo = createExprInfo(pTableScanNode->scan.pScanPseudoCols, NULL, &pSup->numOfExprs);
    pSup->pCtx = createSqlFunctionCtx(pSup->pExprInfo, pSup->numOfExprs, &pSup->rowEntryInfoOffset);
3093 3094 3095 3096
  }

  pInfo->scanInfo = (SScanInfo){.numOfAsc = pTableScanNode->scanSeq[0], .numOfDesc = pTableScanNode->scanSeq[1]};

L
Liu Jicong 已提交
3097 3098
  pInfo->readHandle = *readHandle;
  pInfo->interval = extractIntervalInfo(pTableScanNode);
3099
  pInfo->sample.sampleRatio = pTableScanNode->ratio;
L
Liu Jicong 已提交
3100 3101 3102
  pInfo->sample.seed = taosGetTimestampSec();
  pInfo->dataBlockLoadFlag = pTableScanNode->dataRequired;
  pInfo->pFilterNode = pTableScanNode->scan.node.pConditions;
3103
  pInfo->tableListInfo = pTableListInfo;
L
Liu Jicong 已提交
3104 3105
  pInfo->scanFlag = MAIN_SCAN;
  pInfo->pColMatchInfo = pColList;
3106 3107

  pInfo->pResBlock = createResDataBlock(pDescNode);
3108
  pInfo->sortSourceParams = taosArrayInit(64, sizeof(STableMergeScanSortSourceParam));
3109

3110
  pInfo->pSortInfo = generateSortByTsInfo(pInfo->pColMatchInfo, pInfo->cond.order);
3111
  pInfo->pSortInputBlock = createOneDataBlock(pInfo->pResBlock, false);
3112

3113
  int32_t rowSize = pInfo->pResBlock->info.rowSize;
L
Liu Jicong 已提交
3114
  pInfo->bufPageSize = getProperSortPageSize(rowSize);
3115

L
Liu Jicong 已提交
3116
  pOperator->name = "TableMergeScanOperator";
3117
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_TABLE_MERGE_SCAN;
L
Liu Jicong 已提交
3118 3119 3120
  pOperator->blocking = false;
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
L
Liu Jicong 已提交
3121
  pOperator->exprSupp.numOfExprs = numOfCols;
L
Liu Jicong 已提交
3122
  pOperator->pTaskInfo = pTaskInfo;
3123
  initResultSizeInfo(&pOperator->resultInfo, 1024);
3124 3125

  pOperator->fpSet =
3126 3127
      createOperatorFpSet(operatorDummyOpenFn, doTableMergeScan, NULL, NULL, destroyTableMergeScanOperatorInfo, NULL,
                          NULL, getTableMergeScanExplainExecInfo);
3128 3129 3130 3131 3132 3133 3134 3135 3136
  pOperator->cost.openCost = 0;
  return pOperator;

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