scanoperator.c 171.2 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 <vnode.h>
17
#include "executorimpl.h"
H
Haojun Liao 已提交
18
#include "filter.h"
19
#include "function.h"
20
#include "functionMgt.h"
L
Liu Jicong 已提交
21
#include "os.h"
H
Haojun Liao 已提交
22
#include "querynodes.h"
23
#include "systable.h"
H
Haojun Liao 已提交
24
#include "tname.h"
25
#include "ttime.h"
H
Haojun Liao 已提交
26 27 28 29 30 31 32 33

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

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

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

39
static int32_t buildSysDbTableInfo(const SSysTableScanInfo* pInfo, int32_t capacity);
40 41
static int32_t buildDbTableInfoBlock(bool sysInfo, const SSDataBlock* p, const SSysTableMeta* pSysDbTableMeta,
                                     size_t size, const char* dbName);
42

dengyihao's avatar
dengyihao 已提交
43 44 45
static char* SYSTABLE_IDX_COLUMN[] = {"table_name", "db_name",     "create_time",      "columns",
                                      "ttl",        "stable_name", "vgroup_id', 'uid", "type"};

dengyihao's avatar
opt mem  
dengyihao 已提交
46
static char* SYSTABLE_SPECIAL_COL[] = {"db_name", "vgroup_id"};
dengyihao's avatar
dengyihao 已提交
47

dengyihao's avatar
dengyihao 已提交
48 49 50
typedef int32_t (*__sys_filte)(void* pMeta, SNode* cond, SArray* result);
typedef int32_t (*__sys_check)(SNode* cond);

dengyihao's avatar
dengyihao 已提交
51
typedef struct {
dengyihao's avatar
dengyihao 已提交
52 53 54
  const char* name;
  __sys_check chkFunc;
  __sys_filte fltFunc;
dengyihao's avatar
dengyihao 已提交
55 56
} SSTabFltFuncDef;

dengyihao's avatar
dengyihao 已提交
57 58
typedef struct {
  void* pMeta;
dengyihao's avatar
dengyihao 已提交
59
  void* pVnode;
dengyihao's avatar
dengyihao 已提交
60 61
} SSTabFltArg;

H
Haojun Liao 已提交
62 63 64 65 66 67 68 69 70 71 72 73
typedef struct STableMergeScanExecInfo {
  SFileBlockLoadRecorder blockRecorder;
  SSortExecInfo          sortExecInfo;
} STableMergeScanExecInfo;

typedef struct STableMergeScanSortSourceParam {
  SOperatorInfo* pOperator;
  int32_t        readerIdx;
  uint64_t       uid;
  SSDataBlock*   inputBlock;
} STableMergeScanSortSourceParam;

dengyihao's avatar
dengyihao 已提交
74
static int32_t sysChkFilter__Comm(SNode* pNode);
dengyihao's avatar
dengyihao 已提交
75 76 77 78 79 80 81 82 83 84
static int32_t sysChkFilter__DBName(SNode* pNode);
static int32_t sysChkFilter__VgroupId(SNode* pNode);
static int32_t sysChkFilter__TableName(SNode* pNode);
static int32_t sysChkFilter__CreateTime(SNode* pNode);
static int32_t sysChkFilter__Ncolumn(SNode* pNode);
static int32_t sysChkFilter__Ttl(SNode* pNode);
static int32_t sysChkFilter__STableName(SNode* pNode);
static int32_t sysChkFilter__Uid(SNode* pNode);
static int32_t sysChkFilter__Type(SNode* pNode);

H
Haojun Liao 已提交
85 86 87 88 89 90 91 92 93
static int32_t sysFilte__DbName(void* arg, SNode* pNode, SArray* result);
static int32_t sysFilte__VgroupId(void* arg, SNode* pNode, SArray* result);
static int32_t sysFilte__TableName(void* arg, SNode* pNode, SArray* result);
static int32_t sysFilte__CreateTime(void* arg, SNode* pNode, SArray* result);
static int32_t sysFilte__Ncolumn(void* arg, SNode* pNode, SArray* result);
static int32_t sysFilte__Ttl(void* arg, SNode* pNode, SArray* result);
static int32_t sysFilte__STableName(void* arg, SNode* pNode, SArray* result);
static int32_t sysFilte__Uid(void* arg, SNode* pNode, SArray* result);
static int32_t sysFilte__Type(void* arg, SNode* pNode, SArray* result);
dengyihao's avatar
dengyihao 已提交
94 95 96 97 98 99 100 101 102 103 104

const SSTabFltFuncDef filterDict[] = {
    {.name = "table_name", .chkFunc = sysChkFilter__TableName, .fltFunc = sysFilte__TableName},
    {.name = "db_name", .chkFunc = sysChkFilter__DBName, .fltFunc = sysFilte__DbName},
    {.name = "create_time", .chkFunc = sysChkFilter__CreateTime, .fltFunc = sysFilte__CreateTime},
    {.name = "columns", .chkFunc = sysChkFilter__Ncolumn, .fltFunc = sysFilte__Ncolumn},
    {.name = "ttl", .chkFunc = sysChkFilter__Ttl, .fltFunc = sysFilte__Ttl},
    {.name = "stable_name", .chkFunc = sysChkFilter__STableName, .fltFunc = sysFilte__STableName},
    {.name = "vgroup_id", .chkFunc = sysChkFilter__VgroupId, .fltFunc = sysFilte__VgroupId},
    {.name = "uid", .chkFunc = sysChkFilter__Uid, .fltFunc = sysFilte__Uid},
    {.name = "type", .chkFunc = sysChkFilter__Type, .fltFunc = sysFilte__Type}};
dengyihao's avatar
dengyihao 已提交
105

dengyihao's avatar
dengyihao 已提交
106
#define SYSTAB_FILTER_DICT_SIZE (sizeof(filterDict) / sizeof(filterDict[0]))
dengyihao's avatar
dengyihao 已提交
107

dengyihao's avatar
dengyihao 已提交
108
static int32_t optSysTabFilte(void* arg, SNode* cond, SArray* result);
dengyihao's avatar
dengyihao 已提交
109
static int32_t optSysTabFilteImpl(void* arg, SNode* cond, SArray* result);
dengyihao's avatar
dengyihao 已提交
110
static int32_t optSysCheckOper(SNode* pOpear);
H
Haojun Liao 已提交
111
static int32_t optSysMergeRslt(SArray* mRslt, SArray* rslt);
dengyihao's avatar
dengyihao 已提交
112

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

115 116 117
static int32_t sysTableUserTagsFillOneTableTags(const SSysTableScanInfo* pInfo, SMetaReader* smrSuperTable,
                                                SMetaReader* smrChildTable, const char* dbname, const char* tableName,
                                                int32_t* pNumOfRows, const SSDataBlock* dataBlock);
118

H
Haojun Liao 已提交
119 120 121 122
static void relocateAndFilterSysTagsScanResult(SSysTableScanInfo* pInfo, int32_t numOfRows, SSDataBlock* dataBlock,
                                               SFilterInfo* pFilterInfo);

bool processBlockWithProbability(const SSampleExecInfo* pInfo) {
123 124 125 126 127 128 129 130 131 132 133 134
#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
}

135
static void switchCtxOrder(SqlFunctionCtx* pCtx, int32_t numOfOutput) {
H
Haojun Liao 已提交
136 137 138 139 140
  for (int32_t i = 0; i < numOfOutput; ++i) {
    SWITCH_ORDER(pCtx[i].order);
  }
}

141 142 143 144 145 146 147 148 149
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;
150
  // convert key to second
151 152 153 154 155 156 157
  key = convertTimePrecision(key, pInterval->precision, TSDB_TIME_PRECISION_MILLI) / 1000;

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

  struct tm tm;
158
  time_t    t = (time_t)key;
159 160 161 162 163
  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 已提交
164
  tw->skey = convertTimePrecision((int64_t)taosMktime(&tm) * 1000LL, TSDB_TIME_PRECISION_MILLI, pInterval->precision);
165 166 167 168

  mon = (int)(mon + interval);
  tm.tm_year = mon / 12;
  tm.tm_mon = mon % 12;
wafwerar's avatar
wafwerar 已提交
169
  tw->ekey = convertTimePrecision((int64_t)taosMktime(&tm) * 1000LL, TSDB_TIME_PRECISION_MILLI, pInterval->precision);
170 171 172 173

  tw->ekey -= 1;
}

174
static bool overlapWithTimeWindow(SInterval* pInterval, SDataBlockInfo* pBlockInfo, int32_t order) {
175 176 177 178 179 180 181
  STimeWindow w = {0};

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

182
  if (order == TSDB_ORDER_ASC) {
183
    w = getAlignQueryTimeWindow(pInterval, pInterval->precision, pBlockInfo->window.skey);
184 185
    assert(w.ekey >= pBlockInfo->window.skey);

S
slzhou 已提交
186
    if (TMAX(w.skey, pBlockInfo->window.skey) <= TMIN(w.ekey, pBlockInfo->window.ekey)) {
187 188 189
      return true;
    }

190 191
    while (1) {
      getNextTimeWindow(pInterval, &w, order);
192 193 194 195 196
      if (w.skey > pBlockInfo->window.ekey) {
        break;
      }

      assert(w.ekey > pBlockInfo->window.ekey);
197
      if (TMAX(w.skey, pBlockInfo->window.skey) <= pBlockInfo->window.ekey) {
198 199 200 201
        return true;
      }
    }
  } else {
202
    w = getAlignQueryTimeWindow(pInterval, pInterval->precision, pBlockInfo->window.ekey);
203 204
    assert(w.skey <= pBlockInfo->window.ekey);

205
    if (TMAX(w.skey, pBlockInfo->window.skey) <= TMIN(w.ekey, pBlockInfo->window.ekey)) {
206 207 208
      return true;
    }

209
    while (1) {
210 211 212 213 214 215
      getNextTimeWindow(pInterval, &w, order);
      if (w.ekey < pBlockInfo->window.skey) {
        break;
      }

      assert(w.skey < pBlockInfo->window.skey);
216
      if (pBlockInfo->window.skey <= TMIN(w.ekey, pBlockInfo->window.ekey)) {
217 218 219
        return true;
      }
    }
220 221 222 223 224
  }

  return false;
}

225 226 227 228 229 230 231 232 233 234 235
// 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;

236 237
  SResultRowPosition* p1 = (SResultRowPosition*)tSimpleHashGet(pTableScanInfo->pdInfo.pAggSup->pResultRowHashTable, buf,
                                                               GET_RES_WINDOW_KEY_LEN(sizeof(groupId)));
238 239 240 241 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 282 283 284 285

  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 已提交
286
static bool doFilterByBlockSMA(SFilterInfo* pFilterInfo, SColumnDataAgg** pColsAgg, int32_t numOfCols,
287
                               int32_t numOfRows) {
H
Haojun Liao 已提交
288
  if (pColsAgg == NULL || pFilterInfo == NULL) {
H
Haojun Liao 已提交
289 290 291
    return true;
  }

H
Haojun Liao 已提交
292
  bool keep = filterRangeExecute(pFilterInfo, pColsAgg, numOfCols, numOfRows);
H
Haojun Liao 已提交
293 294 295 296 297 298 299 300 301
  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) {
302
    T_LONG_JMP(pTaskInfo->env, code);
H
Haojun Liao 已提交
303 304 305 306 307 308 309 310 311 312 313 314 315
  }

  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) {
316
      T_LONG_JMP(pTaskInfo->env, TSDB_CODE_OUT_OF_MEMORY);
H
Haojun Liao 已提交
317 318 319
    }
  }

320 321
  size_t num = taosArrayGetSize(pTableScanInfo->matchInfo.pList);
  for (int32_t i = 0; i < num; ++i) {
H
Haojun Liao 已提交
322 323
    SColMatchItem* pColMatchInfo = taosArrayGet(pTableScanInfo->matchInfo.pList, i);
    if (!pColMatchInfo->needOutput) {
H
Haojun Liao 已提交
324 325
      continue;
    }
H
Haojun Liao 已提交
326 327

    pBlock->pBlockAgg[pColMatchInfo->dstSlotId] = pColAgg[i];
H
Haojun Liao 已提交
328 329 330 331 332
  }

  return true;
}

333 334
static void doSetTagColumnData(STableScanInfo* pTableScanInfo, SSDataBlock* pBlock, SExecTaskInfo* pTaskInfo,
                               int32_t rows) {
H
Haojun Liao 已提交
335 336 337
  if (pTableScanInfo->pseudoSup.numOfExprs > 0) {
    SExprSupp* pSup = &pTableScanInfo->pseudoSup;

338
    int32_t code = addTagPseudoColumnData(&pTableScanInfo->readHandle, pSup->pExprInfo, pSup->numOfExprs, pBlock, rows,
339
                                          GET_TASKID(pTaskInfo), &pTableScanInfo->metaCache);
H
Haojun Liao 已提交
340 341 342 343 344 345
    if (code != TSDB_CODE_SUCCESS) {
      T_LONG_JMP(pTaskInfo->env, code);
    }
  }
}

346 347
// todo handle the slimit info
void applyLimitOffset(SLimitInfo* pLimitInfo, SSDataBlock* pBlock, SExecTaskInfo* pTaskInfo, SOperatorInfo* pOperator) {
348
  SLimit*     pLimit = &pLimitInfo->limit;
H
Haojun Liao 已提交
349
  const char* id = GET_TASKID(pTaskInfo);
350 351 352 353 354

  if (pLimit->offset > 0 && pLimitInfo->remainOffset > 0) {
    if (pLimitInfo->remainOffset >= pBlock->info.rows) {
      pLimitInfo->remainOffset -= pBlock->info.rows;
      pBlock->info.rows = 0;
H
Haojun Liao 已提交
355
      qDebug("current block ignore due to offset, current:%" PRId64 ", %s", pLimitInfo->remainOffset, id);
356 357 358 359 360 361 362 363 364 365 366 367
    } else {
      blockDataTrimFirstNRows(pBlock, pLimitInfo->remainOffset);
      pLimitInfo->remainOffset = 0;
    }
  }

  if (pLimit->limit != -1 && pLimit->limit <= (pLimitInfo->numOfOutputRows + pBlock->info.rows)) {
    // limit the output rows
    int32_t overflowRows = pLimitInfo->numOfOutputRows + pBlock->info.rows - pLimit->limit;
    int32_t keep = pBlock->info.rows - overflowRows;

    blockDataKeepFirstNRows(pBlock, keep);
H
Haojun Liao 已提交
368
    qDebug("output limit %" PRId64 " has reached, %s", pLimit->limit, id);
369 370 371 372
    pOperator->status = OP_EXEC_DONE;
  }
}

L
Liu Jicong 已提交
373 374
static int32_t loadDataBlock(SOperatorInfo* pOperator, STableScanInfo* pTableScanInfo, SSDataBlock* pBlock,
                             uint32_t* status) {
375
  SExecTaskInfo*  pTaskInfo = pOperator->pTaskInfo;
376 377
  STableScanInfo* pInfo = pOperator->info;

378
  SFileBlockLoadRecorder* pCost = &pTableScanInfo->readRecorder;
H
Haojun Liao 已提交
379 380

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

H
Haojun Liao 已提交
383
  bool loadSMA = false;
H
Haojun Liao 已提交
384

385
  *status = pInfo->dataBlockLoadFlag;
H
Haojun Liao 已提交
386
  if (pOperator->exprSupp.pFilterInfo != NULL ||
387
      overlapWithTimeWindow(&pTableScanInfo->pdInfo.interval, &pBlock->info, pTableScanInfo->cond.order)) {
388 389 390 391
    (*status) = FUNC_DATA_REQUIRED_DATA_LOAD;
  }

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

  if (*status == FUNC_DATA_REQUIRED_FILTEROUT) {
395 396
    qDebug("%s data block filter out, brange:%" PRId64 "-%" PRId64 ", rows:%d", GET_TASKID(pTaskInfo),
           pBlockInfo->window.skey, pBlockInfo->window.ekey, pBlockInfo->rows);
397
    pCost->filterOutBlocks += 1;
398
    pCost->totalRows += pBlock->info.rows;
399 400
    return TSDB_CODE_SUCCESS;
  } else if (*status == FUNC_DATA_REQUIRED_NOT_LOAD) {
401 402
    qDebug("%s data block skipped, brange:%" PRId64 "-%" PRId64 ", rows:%d", GET_TASKID(pTaskInfo),
           pBlockInfo->window.skey, pBlockInfo->window.ekey, pBlockInfo->rows);
403
    doSetTagColumnData(pTableScanInfo, pBlock, pTaskInfo, 1);
404 405
    pCost->skipBlocks += 1;
    return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
406
  } else if (*status == FUNC_DATA_REQUIRED_SMA_LOAD) {
407
    pCost->loadBlockStatis += 1;
L
Liu Jicong 已提交
408
    loadSMA = true;  // mark the operation of load sma;
H
Haojun Liao 已提交
409
    bool success = doLoadBlockSMA(pTableScanInfo, pBlock, pTaskInfo);
L
Liu Jicong 已提交
410
    if (success) {  // failed to load the block sma data, data block statistics does not exist, load data block instead
411 412
      qDebug("%s data block SMA loaded, brange:%" PRId64 "-%" PRId64 ", rows:%d", GET_TASKID(pTaskInfo),
             pBlockInfo->window.skey, pBlockInfo->window.ekey, pBlockInfo->rows);
413
      doSetTagColumnData(pTableScanInfo, pBlock, pTaskInfo, 1);
414 415
      return TSDB_CODE_SUCCESS;
    } else {
416
      qDebug("%s failed to load SMA, since not all columns have SMA", GET_TASKID(pTaskInfo));
H
Haojun Liao 已提交
417
      *status = FUNC_DATA_REQUIRED_DATA_LOAD;
418
    }
H
Haojun Liao 已提交
419
  }
420

H
Haojun Liao 已提交
421
  ASSERT(*status == FUNC_DATA_REQUIRED_DATA_LOAD);
422

H
Haojun Liao 已提交
423
  // try to filter data block according to sma info
H
Haojun Liao 已提交
424
  if (pOperator->exprSupp.pFilterInfo != NULL && (!loadSMA)) {
425 426 427
    bool success = doLoadBlockSMA(pTableScanInfo, pBlock, pTaskInfo);
    if (success) {
      size_t size = taosArrayGetSize(pBlock->pDataBlock);
H
Haojun Liao 已提交
428
      bool   keep = doFilterByBlockSMA(pOperator->exprSupp.pFilterInfo, pBlock->pBlockAgg, size, pBlockInfo->rows);
429 430 431 432 433 434 435 436
      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;
      }
437
    }
H
Haojun Liao 已提交
438
  }
439

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

443
  // try to filter data block according to current results
444 445
  doDynamicPruneDataBlock(pOperator, pBlockInfo, status);
  if (*status == FUNC_DATA_REQUIRED_NOT_LOAD) {
446
    qDebug("%s data block skipped due to dynamic prune, brange:%" PRId64 "-%" PRId64 ", rows:%d", GET_TASKID(pTaskInfo),
447 448 449
           pBlockInfo->window.skey, pBlockInfo->window.ekey, pBlockInfo->rows);
    pCost->skipBlocks += 1;

450
    *status = FUNC_DATA_REQUIRED_FILTEROUT;
451 452 453
    return TSDB_CODE_SUCCESS;
  }

H
Haojun Liao 已提交
454 455
  pCost->totalCheckedRows += pBlock->info.rows;
  pCost->loadBlocks += 1;
456

H
Haojun Liao 已提交
457 458 459
  SArray* pCols = tsdbRetrieveDataBlock(pTableScanInfo->dataReader, NULL);
  if (pCols == NULL) {
    return terrno;
H
Haojun Liao 已提交
460 461
  }

H
Haojun Liao 已提交
462
  relocateColumnData(pBlock, pTableScanInfo->matchInfo.pList, pCols, true);
463
  doSetTagColumnData(pTableScanInfo, pBlock, pTaskInfo, pBlock->info.rows);
464

H
Haojun Liao 已提交
465 466
  // restore the previous value
  pCost->totalRows -= pBlock->info.rows;
467

H
Haojun Liao 已提交
468
  if (pOperator->exprSupp.pFilterInfo != NULL) {
469
    int64_t st = taosGetTimestampUs();
H
Haojun Liao 已提交
470
    doFilter(pBlock, pOperator->exprSupp.pFilterInfo, &pTableScanInfo->matchInfo);
471

472 473
    double el = (taosGetTimestampUs() - st) / 1000.0;
    pTableScanInfo->readRecorder.filterTime += el;
474

475 476 477 478 479 480 481
    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);
    }
482 483
  }

484
  applyLimitOffset(&pInfo->limitInfo, pBlock, pTaskInfo, pOperator);
485

H
Haojun Liao 已提交
486 487
  pCost->totalRows += pBlock->info.rows;
  pInfo->limitInfo.numOfOutputRows = pCost->totalRows;
H
Haojun Liao 已提交
488 489 490
  return TSDB_CODE_SUCCESS;
}

491
static void prepareForDescendingScan(STableScanInfo* pTableScanInfo, SqlFunctionCtx* pCtx, int32_t numOfOutput) {
H
Haojun Liao 已提交
492 493 494
  SET_REVERSE_SCAN_FLAG(pTableScanInfo);

  switchCtxOrder(pCtx, numOfOutput);
495
  pTableScanInfo->cond.order = TSDB_ORDER_DESC;
H
Haojun Liao 已提交
496 497
  STimeWindow* pTWindow = &pTableScanInfo->cond.twindows;
  TSWAP(pTWindow->skey, pTWindow->ekey);
H
Haojun Liao 已提交
498 499
}

500 501
typedef struct STableCachedVal {
  const char* pName;
502
  STag*       pTags;
503 504
} STableCachedVal;

505 506 507 508 509 510 511 512 513 514 515
static void freeTableCachedVal(void* param) {
  if (param == NULL) {
    return;
  }

  STableCachedVal* pVal = param;
  taosMemoryFree((void*)pVal->pName);
  taosMemoryFree(pVal->pTags);
  taosMemoryFree(pVal);
}

516 517
// const void *key, size_t keyLen, void *value
static void freeCachedMetaItem(const void* key, size_t keyLen, void* value) { freeTableCachedVal(value); }
518

519 520
int32_t addTagPseudoColumnData(SReadHandle* pHandle, const SExprInfo* pExpr, int32_t numOfExpr, SSDataBlock* pBlock,
                               int32_t rows, const char* idStr, STableMetaCacheInfo* pCache) {
521
  // currently only the tbname pseudo column
522
  if (numOfExpr <= 0) {
H
Haojun Liao 已提交
523
    return TSDB_CODE_SUCCESS;
524 525
  }

526 527
  int32_t code = 0;

528 529 530 531
  // backup the rows
  int32_t backupRows = pBlock->info.rows;
  pBlock->info.rows = rows;

532
  bool            freeReader = false;
533
  STableCachedVal val = {0};
534 535

  SMetaReader mr = {0};
536
  LRUHandle*  h = NULL;
537

538
  // 1. check if it is existed in meta cache
539
  if (pCache == NULL) {
540 541 542 543 544 545 546 547 548
    metaReaderInit(&mr, pHandle->meta, 0);
    code = metaGetTableEntryByUid(&mr, pBlock->info.uid);
    if (code != TSDB_CODE_SUCCESS) {
      qError("failed to get table meta, uid:0x%" PRIx64 ", code:%s, %s", pBlock->info.uid, tstrerror(terrno), idStr);
      metaReaderClear(&mr);
      return terrno;
    }

    metaReaderReleaseLock(&mr);
549

550 551
    val.pName = mr.me.name;
    val.pTags = (STag*)mr.me.ctbEntry.pTags;
552 553

    freeReader = true;
554
  } else {
555 556
    pCache->metaFetch += 1;

H
Haojun Liao 已提交
557
    h = taosLRUCacheLookup(pCache->pTableMetaEntryCache, &pBlock->info.uid, sizeof(pBlock->info.uid));
558 559 560 561 562 563 564 565 566 567 568 569 570
    if (h == NULL) {
      metaReaderInit(&mr, pHandle->meta, 0);
      code = metaGetTableEntryByUid(&mr, pBlock->info.uid);
      if (code != TSDB_CODE_SUCCESS) {
        qError("failed to get table meta, uid:0x%" PRIx64 ", code:%s, %s", pBlock->info.uid, tstrerror(terrno), idStr);
        metaReaderClear(&mr);
        return terrno;
      }

      metaReaderReleaseLock(&mr);

      STableCachedVal* pVal = taosMemoryMalloc(sizeof(STableCachedVal));
      pVal->pName = strdup(mr.me.name);
H
Haojun Liao 已提交
571
      pVal->pTags = NULL;
572

H
Haojun Liao 已提交
573 574 575 576 577 578
      // only child table has tag value
      if (mr.me.type == TSDB_CHILD_TABLE) {
        STag* pTag = (STag*)mr.me.ctbEntry.pTags;
        pVal->pTags = taosMemoryMalloc(pTag->len);
        memcpy(pVal->pTags, mr.me.ctbEntry.pTags, pTag->len);
      }
579

H
Haojun Liao 已提交
580
      val = *pVal;
581
      freeReader = true;
H
Haojun Liao 已提交
582

583 584
      int32_t ret = taosLRUCacheInsert(pCache->pTableMetaEntryCache, &pBlock->info.uid, sizeof(uint64_t), pVal,
                                       sizeof(STableCachedVal), freeCachedMetaItem, NULL, TAOS_LRU_PRIORITY_LOW);
585 586 587 588 589 590 591 592
      if (ret != TAOS_LRU_STATUS_OK) {
        qError("failed to put meta into lru cache, code:%d, %s", ret, idStr);
        freeTableCachedVal(pVal);
      }
    } else {
      pCache->cacheHit += 1;
      STableCachedVal* pVal = taosLRUCacheValue(pCache->pTableMetaEntryCache, h);
      val = *pVal;
H
Haojun Liao 已提交
593
      taosLRUCacheRelease(pCache->pTableMetaEntryCache, h, false);
594
    }
H
Haojun Liao 已提交
595

596 597
    qDebug("retrieve table meta from cache:%" PRIu64 ", hit:%" PRIu64 " miss:%" PRIu64 ", %s", pCache->metaFetch,
           pCache->cacheHit, (pCache->metaFetch - pCache->cacheHit), idStr);
H
Haojun Liao 已提交
598
  }
599

600 601
  for (int32_t j = 0; j < numOfExpr; ++j) {
    const SExprInfo* pExpr1 = &pExpr[j];
602
    int32_t          dstSlotId = pExpr1->base.resSchema.slotId;
603 604

    SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, dstSlotId);
D
dapan1121 已提交
605
    colInfoDataCleanup(pColInfoData, pBlock->info.rows);
606

607
    int32_t functionId = pExpr1->pExpr->_function.functionId;
608 609 610

    // this is to handle the tbname
    if (fmIsScanPseudoColumnFunc(functionId)) {
611
      setTbNameColData(pBlock, pColInfoData, functionId, val.pName);
612
    } else {  // these are tags
wmmhello's avatar
wmmhello 已提交
613
      STagVal tagVal = {0};
614 615
      tagVal.cid = pExpr1->base.pParam[0].pCol->colId;
      const char* p = metaGetTableTagVal(val.pTags, pColInfoData->info.type, &tagVal);
wmmhello's avatar
wmmhello 已提交
616

617 618 619 620
      char* data = NULL;
      if (pColInfoData->info.type != TSDB_DATA_TYPE_JSON && p != NULL) {
        data = tTagValToData((const STagVal*)p, false);
      } else {
wmmhello's avatar
wmmhello 已提交
621
        data = (char*)p;
wmmhello's avatar
wmmhello 已提交
622
      }
623

H
Haojun Liao 已提交
624 625 626
      bool isNullVal = (data == NULL) || (pColInfoData->info.type == TSDB_DATA_TYPE_JSON && tTagIsJsonNull(data));
      if (isNullVal) {
        colDataAppendNNULL(pColInfoData, 0, pBlock->info.rows);
H
Haojun Liao 已提交
627
      } else if (pColInfoData->info.type != TSDB_DATA_TYPE_JSON) {
H
Haojun Liao 已提交
628
        colDataAppendNItems(pColInfoData, 0, data, pBlock->info.rows);
H
Haojun Liao 已提交
629 630 631
        if (IS_VAR_DATA_TYPE(((const STagVal*)p)->type)) {
          taosMemoryFree(data);
        }
L
Liu Jicong 已提交
632
      } else {  // todo opt for json tag
H
Haojun Liao 已提交
633
        for (int32_t i = 0; i < pBlock->info.rows; ++i) {
H
Haojun Liao 已提交
634
          colDataAppend(pColInfoData, i, data, false);
H
Haojun Liao 已提交
635
        }
636 637 638 639
      }
    }
  }

640 641
  // restore the rows
  pBlock->info.rows = backupRows;
642 643 644 645
  if (freeReader) {
    metaReaderClear(&mr);
  }

H
Haojun Liao 已提交
646
  return TSDB_CODE_SUCCESS;
647 648
}

H
Haojun Liao 已提交
649
void setTbNameColData(const SSDataBlock* pBlock, SColumnInfoData* pColInfoData, int32_t functionId, const char* name) {
650 651 652
  struct SScalarFuncExecFuncs fpSet = {0};
  fmGetScalarFuncExecFuncs(functionId, &fpSet);

H
Haojun Liao 已提交
653
  size_t len = TSDB_TABLE_FNAME_LEN + VARSTR_HEADER_SIZE;
654
  char   buf[TSDB_TABLE_FNAME_LEN + VARSTR_HEADER_SIZE] = {0};
H
Haojun Liao 已提交
655 656 657
  STR_TO_VARSTR(buf, name)

  SColumnInfoData infoData = createColumnInfoData(TSDB_DATA_TYPE_VARCHAR, len, 1);
658

H
Haojun Liao 已提交
659 660
  colInfoDataEnsureCapacity(&infoData, 1, false);
  colDataAppend(&infoData, 0, buf, false);
661

H
Haojun Liao 已提交
662
  SScalarParam srcParam = {.numOfRows = pBlock->info.rows, .columnData = &infoData};
663
  SScalarParam param = {.columnData = pColInfoData};
H
Haojun Liao 已提交
664 665 666 667 668 669 670

  if (fpSet.process != NULL) {
    fpSet.process(&srcParam, 1, &param);
  } else {
    qError("failed to get the corresponding callback function, functionId:%d", functionId);
  }

D
dapan1121 已提交
671
  colDataDestroy(&infoData);
672 673
}

674
static SSDataBlock* doTableScanImpl(SOperatorInfo* pOperator) {
H
Haojun Liao 已提交
675
  STableScanInfo* pTableScanInfo = pOperator->info;
676
  SExecTaskInfo*  pTaskInfo = pOperator->pTaskInfo;
L
Liu Jicong 已提交
677
  SSDataBlock*    pBlock = pTableScanInfo->pResBlock;
H
Haojun Liao 已提交
678

679 680
  int64_t st = taosGetTimestampUs();

681
  while (tsdbNextDataBlock(pTableScanInfo->dataReader)) {
682
    if (isTaskKilled(pTaskInfo)) {
683
      T_LONG_JMP(pTaskInfo->env, TSDB_CODE_TSC_QUERY_CANCELLED);
684
    }
H
Haojun Liao 已提交
685

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

692
    blockDataCleanup(pBlock);
H
Haojun Liao 已提交
693
    SDataBlockInfo* pBInfo = &pBlock->info;
H
Haojun Liao 已提交
694 695 696 697

    int32_t rows = 0;
    tsdbRetrieveDataBlockInfo(pTableScanInfo->dataReader, &rows, &pBInfo->uid, &pBInfo->window);

698
    blockDataEnsureCapacity(pBlock, rows);  // todo remove it latter
H
Haojun Liao 已提交
699
    pBInfo->rows = rows;
700

H
Haojun Liao 已提交
701
    ASSERT(pBInfo->uid != 0);
H
Haojun Liao 已提交
702
    pBlock->info.groupId = getTableGroupId(pTaskInfo->pTableInfoList, pBlock->info.uid);
703

704 705 706 707
    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) {
708
      T_LONG_JMP(pOperator->pTaskInfo->env, code);
709
    }
710

711 712 713
    // 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;
714
    }
715 716 717 718 719

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

    pOperator->cost.totalCost = pTableScanInfo->readRecorder.elapsedTime;
720 721

    // todo refactor
L
Liu Jicong 已提交
722 723 724 725 726
    /*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;
727

L
Liu Jicong 已提交
728
    ASSERT(pBlock->info.uid != 0);
729
    return pBlock;
H
Haojun Liao 已提交
730 731 732 733
  }
  return NULL;
}

H
Haojun Liao 已提交
734
static SSDataBlock* doGroupedTableScan(SOperatorInfo* pOperator) {
H
Haojun Liao 已提交
735 736 737 738
  STableScanInfo* pTableScanInfo = pOperator->info;
  SExecTaskInfo*  pTaskInfo = pOperator->pTaskInfo;

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

743 744
  // do the ascending order traverse in the first place.
  while (pTableScanInfo->scanTimes < pTableScanInfo->scanInfo.numOfAsc) {
H
Haojun Liao 已提交
745 746 747
    SSDataBlock* p = doTableScanImpl(pOperator);
    if (p != NULL) {
      return p;
H
Haojun Liao 已提交
748 749
    }

750
    pTableScanInfo->scanTimes += 1;
751

752
    if (pTableScanInfo->scanTimes < pTableScanInfo->scanInfo.numOfAsc) {
753 754
      setTaskStatus(pTaskInfo, TASK_NOT_COMPLETED);
      pTableScanInfo->scanFlag = REPEAT_SCAN;
755
      qDebug("start to repeat ascending order scan data blocks due to query func required, %s", GET_TASKID(pTaskInfo));
H
Haojun Liao 已提交
756

757
      // do prepare for the next round table scan operation
H
Haojun Liao 已提交
758
      tsdbReaderReset(pTableScanInfo->dataReader, &pTableScanInfo->cond);
H
Haojun Liao 已提交
759
    }
760
  }
H
Haojun Liao 已提交
761

762
  int32_t total = pTableScanInfo->scanInfo.numOfAsc + pTableScanInfo->scanInfo.numOfDesc;
763
  if (pTableScanInfo->scanTimes < total) {
764
    if (pTableScanInfo->cond.order == TSDB_ORDER_ASC) {
H
Haojun Liao 已提交
765 766
      prepareForDescendingScan(pTableScanInfo, pOperator->exprSupp.pCtx, 0);
      tsdbReaderReset(pTableScanInfo->dataReader, &pTableScanInfo->cond);
767
      qDebug("%s start to descending order scan data blocks due to query func required", GET_TASKID(pTaskInfo));
768
    }
H
Haojun Liao 已提交
769

770
    while (pTableScanInfo->scanTimes < total) {
H
Haojun Liao 已提交
771 772 773
      SSDataBlock* p = doTableScanImpl(pOperator);
      if (p != NULL) {
        return p;
774
      }
H
Haojun Liao 已提交
775

776
      pTableScanInfo->scanTimes += 1;
H
Haojun Liao 已提交
777

778
      if (pTableScanInfo->scanTimes < total) {
779 780
        setTaskStatus(pTaskInfo, TASK_NOT_COMPLETED);
        pTableScanInfo->scanFlag = REPEAT_SCAN;
H
Haojun Liao 已提交
781

782
        qDebug("%s start to repeat descending order scan data blocks", GET_TASKID(pTaskInfo));
H
Haojun Liao 已提交
783
        tsdbReaderReset(pTableScanInfo->dataReader, &pTableScanInfo->cond);
784
      }
H
Haojun Liao 已提交
785 786 787
    }
  }

wmmhello's avatar
wmmhello 已提交
788 789 790 791 792 793 794
  return NULL;
}

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

795
  // scan table one by one sequentially
L
Liu Jicong 已提交
796
  if (pInfo->scanMode == TABLE_SCAN__TABLE_ORDER) {
H
Haojun Liao 已提交
797
    int32_t numOfTables = tableListGetSize(pTaskInfo->pTableInfoList);
H
Haojun Liao 已提交
798

L
Liu Jicong 已提交
799
    while (1) {
H
Haojun Liao 已提交
800
      SSDataBlock* result = doGroupedTableScan(pOperator);
L
Liu Jicong 已提交
801 802 803
      if (result) {
        return result;
      }
H
Haojun Liao 已提交
804

L
Liu Jicong 已提交
805 806
      // if no data, switch to next table and continue scan
      pInfo->currentTable++;
H
Haojun Liao 已提交
807
      if (pInfo->currentTable >= numOfTables) {
L
Liu Jicong 已提交
808 809
        return NULL;
      }
H
Haojun Liao 已提交
810

H
Haojun Liao 已提交
811
      STableKeyInfo* pTableInfo = tableListGetInfo(pTaskInfo->pTableInfoList, pInfo->currentTable);
812
      tsdbSetTableList(pInfo->dataReader, pTableInfo, 1);
L
Liu Jicong 已提交
813 814
      qDebug("set uid:%" PRIu64 " into scanner, total tables:%d, index:%d %s", pTableInfo->uid, numOfTables,
             pInfo->currentTable, pTaskInfo->id.str);
H
Haojun Liao 已提交
815

H
Haojun Liao 已提交
816
      tsdbReaderReset(pInfo->dataReader, &pInfo->cond);
L
Liu Jicong 已提交
817 818
      pInfo->scanTimes = 0;
    }
819 820
  } else {  // scan table group by group sequentially
    if (pInfo->currentGroupId == -1) {
H
Haojun Liao 已提交
821
      if ((++pInfo->currentGroupId) >= tableListGetOutputGroups(pTaskInfo->pTableInfoList)) {
H
Haojun Liao 已提交
822
        setOperatorCompleted(pOperator);
823 824
        return NULL;
      }
825

5
54liuyao 已提交
826
      int32_t        num = 0;
827
      STableKeyInfo* pList = NULL;
H
Haojun Liao 已提交
828
      tableListGetGroupList(pTaskInfo->pTableInfoList, pInfo->currentGroupId, &pList, &num);
829 830
      ASSERT(pInfo->dataReader == NULL);

5
54liuyao 已提交
831 832
      int32_t code = tsdbReaderOpen(pInfo->readHandle.vnode, &pInfo->cond, pList, num,
                                    (STsdbReader**)&pInfo->dataReader, GET_TASKID(pTaskInfo));
833 834 835
      if (code != TSDB_CODE_SUCCESS) {
        T_LONG_JMP(pTaskInfo->env, code);
      }
wmmhello's avatar
wmmhello 已提交
836
    }
H
Haojun Liao 已提交
837

H
Haojun Liao 已提交
838
    SSDataBlock* result = doGroupedTableScan(pOperator);
839
    if (result != NULL) {
H
Haojun Liao 已提交
840
      ASSERT(result->info.uid != 0);
841 842
      return result;
    }
H
Haojun Liao 已提交
843

H
Haojun Liao 已提交
844
    if ((++pInfo->currentGroupId) >= tableListGetOutputGroups(pTaskInfo->pTableInfoList)) {
H
Haojun Liao 已提交
845
      setOperatorCompleted(pOperator);
846 847
      return NULL;
    }
wmmhello's avatar
wmmhello 已提交
848

849 850 851 852
    // reset value for the next group data output
    pOperator->status = OP_OPENED;
    pInfo->limitInfo.numOfOutputRows = 0;
    pInfo->limitInfo.remainOffset = pInfo->limitInfo.limit.offset;
wmmhello's avatar
wmmhello 已提交
853

5
54liuyao 已提交
854
    int32_t        num = 0;
855
    STableKeyInfo* pList = NULL;
H
Haojun Liao 已提交
856
    tableListGetGroupList(pTaskInfo->pTableInfoList, pInfo->currentGroupId, &pList, &num);
wmmhello's avatar
wmmhello 已提交
857

858 859 860
    tsdbSetTableList(pInfo->dataReader, pList, num);
    tsdbReaderReset(pInfo->dataReader, &pInfo->cond);
    pInfo->scanTimes = 0;
wmmhello's avatar
wmmhello 已提交
861

H
Haojun Liao 已提交
862
    result = doGroupedTableScan(pOperator);
863 864 865
    if (result != NULL) {
      return result;
    }
866

H
Haojun Liao 已提交
867
    setOperatorCompleted(pOperator);
868 869
    return NULL;
  }
H
Haojun Liao 已提交
870 871
}

872 873
static int32_t getTableScannerExecInfo(struct SOperatorInfo* pOptr, void** pOptrExplain, uint32_t* len) {
  SFileBlockLoadRecorder* pRecorder = taosMemoryCalloc(1, sizeof(SFileBlockLoadRecorder));
874
  STableScanInfo*         pTableScanInfo = pOptr->info;
875 876 877 878 879 880
  *pRecorder = pTableScanInfo->readRecorder;
  *pOptrExplain = pRecorder;
  *len = sizeof(SFileBlockLoadRecorder);
  return 0;
}

881
static void destroyTableScanOperatorInfo(void* param) {
882
  STableScanInfo* pTableScanInfo = (STableScanInfo*)param;
H
Haojun Liao 已提交
883
  blockDataDestroy(pTableScanInfo->pResBlock);
884
  cleanupQueryTableDataCond(&pTableScanInfo->cond);
H
Haojun Liao 已提交
885

H
refact  
Hongze Cheng 已提交
886
  tsdbReaderClose(pTableScanInfo->dataReader);
887
  pTableScanInfo->dataReader = NULL;
888

H
Haojun Liao 已提交
889 890
  if (pTableScanInfo->matchInfo.pList != NULL) {
    taosArrayDestroy(pTableScanInfo->matchInfo.pList);
891
  }
L
Liu Jicong 已提交
892

893
  taosLRUCacheCleanup(pTableScanInfo->metaCache.pTableMetaEntryCache);
894
  cleanupExprSupp(&pTableScanInfo->pseudoSup);
D
dapan1121 已提交
895
  taosMemoryFreeClear(param);
896 897
}

898
SOperatorInfo* createTableScanOperatorInfo(STableScanPhysiNode* pTableScanNode, SReadHandle* readHandle,
899
                                           SExecTaskInfo* pTaskInfo) {
H
Haojun Liao 已提交
900 901 902
  STableScanInfo* pInfo = taosMemoryCalloc(1, sizeof(STableScanInfo));
  SOperatorInfo*  pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
  if (pInfo == NULL || pOperator == NULL) {
903
    goto _error;
H
Haojun Liao 已提交
904 905
  }

906
  SScanPhysiNode*     pScanNode = &pTableScanNode->scan;
H
Haojun Liao 已提交
907
  SDataBlockDescNode* pDescNode = pScanNode->node.pOutputDataBlockDesc;
908 909

  int32_t numOfCols = 0;
910 911
  int32_t code =
      extractColMatchInfo(pScanNode->pScanCols, pDescNode, &numOfCols, COL_MATCH_FROM_COL_ID, &pInfo->matchInfo);
912 913 914 915
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }

H
Haojun Liao 已提交
916
  initLimitInfo(pScanNode->node.pLimit, pScanNode->node.pSlimit, &pInfo->limitInfo);
H
Haojun Liao 已提交
917
  code = initQueryTableDataCond(&pInfo->cond, pTableScanNode);
918
  if (code != TSDB_CODE_SUCCESS) {
919
    goto _error;
920 921
  }

H
Haojun Liao 已提交
922
  if (pScanNode->pScanPseudoCols != NULL) {
923
    SExprSupp* pSup = &pInfo->pseudoSup;
H
Haojun Liao 已提交
924
    pSup->pExprInfo = createExprInfo(pScanNode->pScanPseudoCols, NULL, &pSup->numOfExprs);
925
    pSup->pCtx = createSqlFunctionCtx(pSup->pExprInfo, pSup->numOfExprs, &pSup->rowEntryInfoOffset);
926 927
  }

928
  pInfo->scanInfo = (SScanInfo){.numOfAsc = pTableScanNode->scanSeq[0], .numOfDesc = pTableScanNode->scanSeq[1]};
929
  pInfo->pdInfo.interval = extractIntervalInfo(pTableScanNode);
930 931 932
  pInfo->readHandle = *readHandle;
  pInfo->sample.sampleRatio = pTableScanNode->ratio;
  pInfo->sample.seed = taosGetTimestampSec();
933

934
  pInfo->dataBlockLoadFlag = pTableScanNode->dataRequired;
H
Haojun Liao 已提交
935 936

  initResultSizeInfo(&pOperator->resultInfo, 4096);
937
  pInfo->pResBlock = createResDataBlock(pDescNode);
H
Haojun Liao 已提交
938
  blockDataEnsureCapacity(pInfo->pResBlock, pOperator->resultInfo.capacity);
H
Haojun Liao 已提交
939

H
Haojun Liao 已提交
940 941 942
  code = filterInitFromNode((SNode*)pTableScanNode->scan.node.pConditions, &pOperator->exprSupp.pFilterInfo, 0);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
H
Haojun Liao 已提交
943 944
  }

945
  pInfo->scanFlag = MAIN_SCAN;
wmmhello's avatar
wmmhello 已提交
946
  pInfo->currentGroupId = -1;
947
  pInfo->assignBlockUid = pTableScanNode->assignBlockUid;
948

L
Liu Jicong 已提交
949 950
  setOperatorInfo(pOperator, "TableScanOperator", QUERY_NODE_PHYSICAL_PLAN_TABLE_SCAN, false, OP_NOT_OPENED, pInfo,
                  pTaskInfo);
951
  pOperator->exprSupp.numOfExprs = numOfCols;
952

953
  pInfo->metaCache.pTableMetaEntryCache = taosLRUCacheInit(1024 * 128, -1, .5);
954 955 956 957
  if (pInfo->metaCache.pTableMetaEntryCache == NULL) {
    code = terrno;
    goto _error;
  }
958

959
  taosLRUCacheSetStrictCapacity(pInfo->metaCache.pTableMetaEntryCache, false);
H
Haojun Liao 已提交
960
  pOperator->fpSet = createOperatorFpSet(operatorDummyOpenFn, doTableScan, NULL, destroyTableScanOperatorInfo,
961
                                         getTableScannerExecInfo);
962 963 964

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

967
_error:
968 969 970
  if (pInfo != NULL) {
    destroyTableScanOperatorInfo(pInfo);
  }
971

972 973
  taosMemoryFreeClear(pOperator);
  pTaskInfo->code = code;
974
  return NULL;
H
Haojun Liao 已提交
975 976
}

977
SOperatorInfo* createTableSeqScanOperatorInfo(void* pReadHandle, SExecTaskInfo* pTaskInfo) {
H
Haojun Liao 已提交
978
  STableScanInfo* pInfo = taosMemoryCalloc(1, sizeof(STableScanInfo));
L
Liu Jicong 已提交
979
  SOperatorInfo*  pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
980

L
Liu Jicong 已提交
981 982
  pInfo->dataReader = pReadHandle;
  //  pInfo->prevGroupId       = -1;
H
Haojun Liao 已提交
983

L
Liu Jicong 已提交
984 985
  setOperatorInfo(pOperator, "TableSeqScanOperator", QUERY_NODE_PHYSICAL_PLAN_TABLE_SEQ_SCAN, false, OP_NOT_OPENED,
                  pInfo, pTaskInfo);
H
Haojun Liao 已提交
986
  pOperator->fpSet = createOperatorFpSet(operatorDummyOpenFn, doTableScanImpl, NULL, NULL, NULL);
H
Haojun Liao 已提交
987 988 989
  return pOperator;
}

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

993
  SMetaReader mr = {0};
994
  metaReaderInit(&mr, pMeta, 0);
H
Haojun Liao 已提交
995 996
  int32_t code = metaGetTableEntryByUid(&mr, uid);
  if (code != TSDB_CODE_SUCCESS) {
L
Liu Jicong 已提交
997
    qError("failed to get table meta, uid:0x%" PRIx64 ", code:%s, %s", uid, tstrerror(terrno), idstr);
H
Haojun Liao 已提交
998 999 1000 1001
    metaReaderClear(&mr);
    return terrno;
  }

1002 1003
  if (mr.me.type == TSDB_SUPER_TABLE) {
    int32_t numOfCols = mr.me.stbEntry.schemaRow.nCols;
1004
    for (int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
1005
      (*rowLen) += mr.me.stbEntry.schemaRow.pSchema[i].bytes;
1006 1007 1008
    }
  } else if (mr.me.type == TSDB_CHILD_TABLE) {
    uint64_t suid = mr.me.ctbEntry.suid;
1009
    tDecoderClear(&mr.coder);
H
Haojun Liao 已提交
1010 1011
    code = metaGetTableEntryByUid(&mr, suid);
    if (code != TSDB_CODE_SUCCESS) {
L
Liu Jicong 已提交
1012
      qError("failed to get table meta, uid:0x%" PRIx64 ", code:%s, %s", suid, tstrerror(terrno), idstr);
H
Haojun Liao 已提交
1013 1014 1015 1016
      metaReaderClear(&mr);
      return terrno;
    }

1017 1018
    int32_t numOfCols = mr.me.stbEntry.schemaRow.nCols;

1019
    for (int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
1020
      (*rowLen) += mr.me.stbEntry.schemaRow.pSchema[i].bytes;
1021 1022 1023
    }
  } else if (mr.me.type == TSDB_NORMAL_TABLE) {
    int32_t numOfCols = mr.me.ntbEntry.schemaRow.nCols;
1024
    for (int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
1025
      (*rowLen) += mr.me.ntbEntry.schemaRow.pSchema[i].bytes;
1026 1027 1028 1029
    }
  }

  metaReaderClear(&mr);
H
Haojun Liao 已提交
1030
  return TSDB_CODE_SUCCESS;
1031 1032 1033 1034 1035 1036 1037 1038
}

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

  SBlockDistInfo* pBlockScanInfo = pOperator->info;
L
Liu Jicong 已提交
1039
  SExecTaskInfo*  pTaskInfo = pOperator->pTaskInfo;
1040 1041

  STableBlockDistInfo blockDistInfo = {.minRows = INT_MAX, .maxRows = INT_MIN};
1042 1043
  int32_t             code = doGetTableRowSize(pBlockScanInfo->readHandle.meta, pBlockScanInfo->uid,
                                               (int32_t*)&blockDistInfo.rowSize, GET_TASKID(pTaskInfo));
H
Haojun Liao 已提交
1044
  if (code != TSDB_CODE_SUCCESS) {
1045
    T_LONG_JMP(pTaskInfo->env, code);
H
Haojun Liao 已提交
1046
  }
1047 1048 1049

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

1051
  SSDataBlock* pBlock = pBlockScanInfo->pResBlock;
H
Haojun Liao 已提交
1052

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

1056
  int32_t len = tSerializeBlockDistInfo(NULL, 0, &blockDistInfo);
1057
  char*   p = taosMemoryCalloc(1, len + VARSTR_HEADER_SIZE);
1058 1059 1060 1061 1062
  tSerializeBlockDistInfo(varDataVal(p), len, &blockDistInfo);
  varDataSetLen(p, len);

  colDataAppend(pColInfo, 0, p, false);
  taosMemoryFree(p);
H
Haojun Liao 已提交
1063

1064
  pBlock->info.rows = 1;
H
Haojun Liao 已提交
1065 1066 1067 1068
  pOperator->status = OP_EXEC_DONE;
  return pBlock;
}

1069
static void destroyBlockDistScanOperatorInfo(void* param) {
1070
  SBlockDistInfo* pDistInfo = (SBlockDistInfo*)param;
1071
  blockDataDestroy(pDistInfo->pResBlock);
H
Hongze Cheng 已提交
1072
  tsdbReaderClose(pDistInfo->pHandle);
D
dapan1121 已提交
1073
  taosMemoryFreeClear(param);
1074 1075
}

1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099
static int32_t initTableblockDistQueryCond(uint64_t uid, SQueryTableDataCond* pCond) {
  memset(pCond, 0, sizeof(SQueryTableDataCond));

  pCond->order = TSDB_ORDER_ASC;
  pCond->numOfCols = 1;
  pCond->colList = taosMemoryCalloc(1, sizeof(SColumnInfo));
  if (pCond->colList == NULL) {
    terrno = TSDB_CODE_QRY_OUT_OF_MEMORY;
    return terrno;
  }

  pCond->colList->colId = 1;
  pCond->colList->type = TSDB_DATA_TYPE_TIMESTAMP;
  pCond->colList->bytes = sizeof(TSKEY);

  pCond->twindows = (STimeWindow){.skey = INT64_MIN, .ekey = INT64_MAX};
  pCond->suid = uid;
  pCond->type = TIMEWINDOW_RANGE_CONTAINED;
  pCond->startVersion = -1;
  pCond->endVersion = -1;

  return TSDB_CODE_SUCCESS;
}

5
54liuyao 已提交
1100 1101
SOperatorInfo* createDataBlockInfoScanOperator(SReadHandle* readHandle, SBlockDistScanPhysiNode* pBlockScanNode,
                                               SExecTaskInfo* pTaskInfo) {
1102
  SBlockDistInfo* pInfo = taosMemoryCalloc(1, sizeof(SBlockDistInfo));
1103
  SOperatorInfo*  pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
1104 1105 1106 1107 1108
  if (pInfo == NULL || pOperator == NULL) {
    pTaskInfo->code = TSDB_CODE_OUT_OF_MEMORY;
    goto _error;
  }

1109 1110 1111 1112 1113
  {
    SQueryTableDataCond cond = {0};

    int32_t code = initTableblockDistQueryCond(pBlockScanNode->suid, &cond);
    if (code != TSDB_CODE_SUCCESS) {
dengyihao's avatar
merge  
dengyihao 已提交
1114
      goto _error;
1115 1116 1117
    }

    STableListInfo* pTableListInfo = pTaskInfo->pTableInfoList;
5
54liuyao 已提交
1118 1119
    size_t          num = tableListGetSize(pTableListInfo);
    void*           pList = tableListGetInfo(pTableListInfo, 0);
1120

dengyihao's avatar
dengyihao 已提交
1121
    code = tsdbReaderOpen(readHandle->vnode, &cond, pList, num, &pInfo->pHandle, pTaskInfo->id.str);
1122
    cleanupQueryTableDataCond(&cond);
dengyihao's avatar
dengyihao 已提交
1123 1124 1125
    if (code != 0) {
      goto _error;
    }
1126 1127
  }

1128
  pInfo->readHandle = *readHandle;
1129
  pInfo->uid = pBlockScanNode->suid;
H
Haojun Liao 已提交
1130

1131
  pInfo->pResBlock = createResDataBlock(pBlockScanNode->node.pOutputDataBlockDesc);
H
Haojun Liao 已提交
1132
  blockDataEnsureCapacity(pInfo->pResBlock, 1);
1133

1134
  int32_t    numOfCols = 0;
1135
  SExprInfo* pExprInfo = createExprInfo(pBlockScanNode->pScanPseudoCols, NULL, &numOfCols);
1136
  int32_t    code = initExprSupp(&pOperator->exprSupp, pExprInfo, numOfCols);
1137 1138 1139
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
H
Haojun Liao 已提交
1140

L
Liu Jicong 已提交
1141 1142 1143 1144
  setOperatorInfo(pOperator, "DataBlockDistScanOperator", QUERY_NODE_PHYSICAL_PLAN_BLOCK_DIST_SCAN, false,
                  OP_NOT_OPENED, pInfo, pTaskInfo);
  pOperator->fpSet =
      createOperatorFpSet(operatorDummyOpenFn, doBlockInfoScan, NULL, destroyBlockDistScanOperatorInfo, NULL);
H
Haojun Liao 已提交
1145 1146
  return pOperator;

1147
_error:
H
Haojun Liao 已提交
1148 1149 1150 1151 1152
  taosMemoryFreeClear(pInfo);
  taosMemoryFreeClear(pOperator);
  return NULL;
}

1153
static FORCE_INLINE void doClearBufferedBlocks(SStreamScanInfo* pInfo) {
L
Liu Jicong 已提交
1154 1155
  taosArrayClear(pInfo->pBlockLists);
  pInfo->validBlockIndex = 0;
H
Haojun Liao 已提交
1156 1157
}

1158
static bool isSessionWindow(SStreamScanInfo* pInfo) {
H
Haojun Liao 已提交
1159
  return pInfo->windowSup.parentType == QUERY_NODE_PHYSICAL_PLAN_STREAM_SESSION;
5
54liuyao 已提交
1160 1161
}

1162
static bool isStateWindow(SStreamScanInfo* pInfo) {
1163
  return pInfo->windowSup.parentType == QUERY_NODE_PHYSICAL_PLAN_STREAM_STATE;
5
54liuyao 已提交
1164
}
5
54liuyao 已提交
1165

L
Liu Jicong 已提交
1166
static bool isIntervalWindow(SStreamScanInfo* pInfo) {
1167 1168 1169
  return pInfo->windowSup.parentType == QUERY_NODE_PHYSICAL_PLAN_STREAM_INTERVAL ||
         pInfo->windowSup.parentType == QUERY_NODE_PHYSICAL_PLAN_STREAM_SEMI_INTERVAL ||
         pInfo->windowSup.parentType == QUERY_NODE_PHYSICAL_PLAN_STREAM_FINAL_INTERVAL;
5
54liuyao 已提交
1170 1171 1172
}

static bool isSignleIntervalWindow(SStreamScanInfo* pInfo) {
1173
  return pInfo->windowSup.parentType == QUERY_NODE_PHYSICAL_PLAN_STREAM_INTERVAL;
L
Liu Jicong 已提交
1174 1175
}

1176 1177 1178 1179
static bool isSlidingWindow(SStreamScanInfo* pInfo) {
  return isIntervalWindow(pInfo) && pInfo->interval.interval != pInfo->interval.sliding;
}

1180
static void setGroupId(SStreamScanInfo* pInfo, SSDataBlock* pBlock, int32_t groupColIndex, int32_t rowIndex) {
1181 1182
  SColumnInfoData* pColInfo = taosArrayGet(pBlock->pDataBlock, groupColIndex);
  uint64_t*        groupCol = (uint64_t*)pColInfo->pData;
1183
  ASSERT(rowIndex < pBlock->info.rows);
1184
  pInfo->groupId = groupCol[rowIndex];
1185 1186
}

L
Liu Jicong 已提交
1187
void resetTableScanInfo(STableScanInfo* pTableScanInfo, STimeWindow* pWin) {
H
Haojun Liao 已提交
1188
  pTableScanInfo->cond.twindows = *pWin;
L
Liu Jicong 已提交
1189 1190
  pTableScanInfo->scanTimes = 0;
  pTableScanInfo->currentGroupId = -1;
1191 1192
  tsdbReaderClose(pTableScanInfo->dataReader);
  pTableScanInfo->dataReader = NULL;
1193 1194
}

L
Liu Jicong 已提交
1195 1196
static SSDataBlock* readPreVersionData(SOperatorInfo* pTableScanOp, uint64_t tbUid, TSKEY startTs, TSKEY endTs,
                                       int64_t maxVersion) {
1197
  STableKeyInfo tblInfo = {.uid = tbUid, .groupId = 0};
1198

1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211
  STableScanInfo*     pTableScanInfo = pTableScanOp->info;
  SQueryTableDataCond cond = pTableScanInfo->cond;

  cond.startVersion = -1;
  cond.endVersion = maxVersion;
  cond.twindows = (STimeWindow){.skey = startTs, .ekey = endTs};

  SExecTaskInfo* pTaskInfo = pTableScanOp->pTaskInfo;

  SSDataBlock* pBlock = pTableScanInfo->pResBlock;
  blockDataCleanup(pBlock);

  STsdbReader* pReader = NULL;
5
54liuyao 已提交
1212 1213
  int32_t      code = tsdbReaderOpen(pTableScanInfo->readHandle.vnode, &cond, &tblInfo, 1, (STsdbReader**)&pReader,
                                     GET_TASKID(pTaskInfo));
1214 1215
  if (code != TSDB_CODE_SUCCESS) {
    terrno = code;
dengyihao's avatar
dengyihao 已提交
1216
    T_LONG_JMP(pTaskInfo->env, code);
1217 1218 1219 1220 1221
    return NULL;
  }

  bool hasBlock = tsdbNextDataBlock(pReader);
  if (hasBlock) {
H
Haojun Liao 已提交
1222
    SDataBlockInfo* pBInfo = &pBlock->info;
1223

H
Haojun Liao 已提交
1224 1225
    int32_t rows = 0;
    tsdbRetrieveDataBlockInfo(pReader, &rows, &pBInfo->uid, &pBInfo->window);
1226

H
Haojun Liao 已提交
1227
    SArray* pCols = tsdbRetrieveDataBlock(pReader, NULL);
H
Haojun Liao 已提交
1228 1229
    blockDataEnsureCapacity(pBlock, rows);
    pBlock->info.rows = rows;
1230 1231

    relocateColumnData(pBlock, pTableScanInfo->matchInfo.pList, pCols, true);
1232
    doSetTagColumnData(pTableScanInfo, pBlock, pTaskInfo, rows);
H
Haojun Liao 已提交
1233

H
Haojun Liao 已提交
1234
    pBlock->info.groupId = getTableGroupId(pTaskInfo->pTableInfoList, pBInfo->uid);
1235 1236 1237 1238
  }

  tsdbReaderClose(pReader);
  qDebug("retrieve prev rows:%d, skey:%" PRId64 ", ekey:%" PRId64 " uid:%" PRIu64 ", max ver:%" PRId64
5
54liuyao 已提交
1239 1240
         ", suid:%" PRIu64,
         pBlock->info.rows, startTs, endTs, tbUid, maxVersion, cond.suid);
1241 1242

  return pBlock->info.rows > 0 ? pBlock : NULL;
1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253
}

static uint64_t getGroupIdByCol(SStreamScanInfo* pInfo, uint64_t uid, TSKEY ts, int64_t maxVersion) {
  SSDataBlock* pPreRes = readPreVersionData(pInfo->pTableScanOp, uid, ts, ts, maxVersion);
  if (!pPreRes || pPreRes->info.rows == 0) {
    return 0;
  }
  ASSERT(pPreRes->info.rows == 1);
  return calGroupIdByData(&pInfo->partitionSup, pInfo->pPartScalarSup, pPreRes, 0);
}

5
54liuyao 已提交
1254
static uint64_t getGroupIdByUid(SStreamScanInfo* pInfo, uint64_t uid) {
H
Haojun Liao 已提交
1255
  return getTableGroupId(pInfo->pTableScanOp->pTaskInfo->pTableInfoList, uid);
1256 1257
}

5
54liuyao 已提交
1258 1259 1260 1261 1262 1263 1264 1265
static uint64_t getGroupIdByData(SStreamScanInfo* pInfo, uint64_t uid, TSKEY ts, int64_t maxVersion) {
  if (pInfo->partitionSup.needCalc) {
    return getGroupIdByCol(pInfo, uid, ts, maxVersion);
  }

  return getGroupIdByUid(pInfo, uid);
}

L
Liu Jicong 已提交
1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276
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]};
1277 1278 1279
  SColumnInfoData* pGpCol = taosArrayGet(pBlock->pDataBlock, GROUPID_COLUMN_INDEX);
  uint64_t*        gpData = (uint64_t*)pGpCol->pData;
  uint64_t         groupId = gpData[*pRowIndex];
1280 1281 1282 1283 1284 1285

  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 已提交
1286
  setGroupId(pInfo, pBlock, GROUPID_COLUMN_INDEX, *pRowIndex);
1287 1288 1289 1290
  if (isSlidingWindow(pInfo)) {
    pInfo->updateWin.skey = calStartData[*pRowIndex];
    pInfo->updateWin.ekey = calEndData[*pRowIndex];
  }
L
Liu Jicong 已提交
1291 1292 1293
  (*pRowIndex)++;

  for (; *pRowIndex < pBlock->info.rows; (*pRowIndex)++) {
1294
    if (win.skey == startData[*pRowIndex] && groupId == gpData[*pRowIndex]) {
L
Liu Jicong 已提交
1295 1296 1297
      win.ekey = TMAX(win.ekey, endData[*pRowIndex]);
      continue;
    }
1298
    if (win.skey == endData[*pRowIndex] && groupId == gpData[*pRowIndex]) {
L
Liu Jicong 已提交
1299 1300 1301
      win.skey = TMIN(win.skey, startData[*pRowIndex]);
      continue;
    }
1302 1303
    ASSERT(!(win.skey > startData[*pRowIndex] && win.ekey < endData[*pRowIndex]) ||
           !(isInTimeWindow(&win, startData[*pRowIndex], 0) || isInTimeWindow(&win, endData[*pRowIndex], 0)));
L
Liu Jicong 已提交
1304 1305 1306 1307
    break;
  }

  resetTableScanInfo(pInfo->pTableScanOp->info, &win);
1308
  pInfo->pTableScanOp->status = OP_OPENED;
L
Liu Jicong 已提交
1309 1310 1311
  return true;
}

5
54liuyao 已提交
1312
static STimeWindow getSlidingWindow(TSKEY* startTsCol, TSKEY* endTsCol, uint64_t* gpIdCol, SInterval* pInterval,
1313
                                    SDataBlockInfo* pDataBlockInfo, int32_t* pRowIndex, bool hasGroup) {
H
Haojun Liao 已提交
1314
  SResultRowInfo dumyInfo = {0};
5
54liuyao 已提交
1315
  dumyInfo.cur.pageId = -1;
1316
  STimeWindow win = getActiveTimeWindow(NULL, &dumyInfo, startTsCol[*pRowIndex], pInterval, TSDB_ORDER_ASC);
5
54liuyao 已提交
1317 1318
  STimeWindow endWin = win;
  STimeWindow preWin = win;
5
54liuyao 已提交
1319
  uint64_t    groupId = gpIdCol[*pRowIndex];
H
Haojun Liao 已提交
1320

5
54liuyao 已提交
1321
  while (1) {
1322 1323 1324
    if (hasGroup) {
      (*pRowIndex) += 1;
    } else {
5
54liuyao 已提交
1325 1326 1327 1328 1329 1330
      while ((groupId == gpIdCol[(*pRowIndex)] && startTsCol[*pRowIndex] < endWin.ekey)) {
        (*pRowIndex) += 1;
        if ((*pRowIndex) == pDataBlockInfo->rows) {
          break;
        }
      }
1331
    }
5
54liuyao 已提交
1332

5
54liuyao 已提交
1333 1334 1335
    do {
      preWin = endWin;
      getNextTimeWindow(pInterval, &endWin, TSDB_ORDER_ASC);
1336
    } while (endTsCol[(*pRowIndex) - 1] >= endWin.skey);
5
54liuyao 已提交
1337
    endWin = preWin;
5
54liuyao 已提交
1338
    if (win.ekey == endWin.ekey || (*pRowIndex) == pDataBlockInfo->rows || groupId != gpIdCol[*pRowIndex]) {
5
54liuyao 已提交
1339 1340 1341 1342 1343 1344
      win.ekey = endWin.ekey;
      return win;
    }
    win.ekey = endWin.ekey;
  }
}
5
54liuyao 已提交
1345

L
Liu Jicong 已提交
1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356
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 已提交
1357
      pInfo->updateWin = (STimeWindow){.skey = INT64_MIN, .ekey = INT64_MAX};
H
Hongze Cheng 已提交
1358 1359 1360
      STableScanInfo* pTableScanInfo = pInfo->pTableScanOp->info;
      tsdbReaderClose(pTableScanInfo->dataReader);
      pTableScanInfo->dataReader = NULL;
1361 1362
      return NULL;
    }
L
Liu Jicong 已提交
1363

H
Haojun Liao 已提交
1364
    doFilter(pResult, pInfo->pTableScanOp->exprSupp.pFilterInfo, NULL);
1365 1366 1367 1368
    if (pResult->info.rows == 0) {
      continue;
    }

1369 1370 1371 1372 1373 1374 1375 1376
    if (pInfo->partitionSup.needCalc) {
      SSDataBlock* tmpBlock = createOneDataBlock(pResult, true);
      blockDataCleanup(pResult);
      for (int32_t i = 0; i < tmpBlock->info.rows; i++) {
        if (calGroupIdByData(&pInfo->partitionSup, pInfo->pPartScalarSup, tmpBlock, i) == pInfo->groupId) {
          for (int32_t j = 0; j < pInfo->pTableScanOp->exprSupp.numOfExprs; j++) {
            SColumnInfoData* pSrcCol = taosArrayGet(tmpBlock->pDataBlock, j);
            SColumnInfoData* pDestCol = taosArrayGet(pResult->pDataBlock, j);
L
Liu Jicong 已提交
1377 1378
            bool             isNull = colDataIsNull(pSrcCol, tmpBlock->info.rows, i, NULL);
            char*            pSrcData = colDataGetData(pSrcCol, i);
1379 1380 1381 1382 1383
            colDataAppend(pDestCol, pResult->info.rows, pSrcData, isNull);
          }
          pResult->info.rows++;
        }
      }
H
Haojun Liao 已提交
1384 1385 1386

      blockDataDestroy(tmpBlock);

1387 1388 1389 1390 1391
      if (pResult->info.rows > 0) {
        pResult->info.calWin = pInfo->updateWin;
        return pResult;
      }
    } else if (pResult->info.groupId == pInfo->groupId) {
5
54liuyao 已提交
1392
      pResult->info.calWin = pInfo->updateWin;
1393
      return pResult;
5
54liuyao 已提交
1394 1395
    }
  }
1396
}
1397

1398 1399 1400
static int32_t generateSessionScanRange(SStreamScanInfo* pInfo, SSDataBlock* pSrcBlock, SSDataBlock* pDestBlock) {
  if (pSrcBlock->info.rows == 0) {
    return TSDB_CODE_SUCCESS;
1401
  }
1402 1403
  blockDataCleanup(pDestBlock);
  int32_t code = blockDataEnsureCapacity(pDestBlock, pSrcBlock->info.rows);
1404
  if (code != TSDB_CODE_SUCCESS) {
1405
    return code;
L
Liu Jicong 已提交
1406
  }
1407 1408
  ASSERT(taosArrayGetSize(pSrcBlock->pDataBlock) >= 3);
  SColumnInfoData* pStartTsCol = taosArrayGet(pSrcBlock->pDataBlock, START_TS_COLUMN_INDEX);
L
Liu Jicong 已提交
1409
  TSKEY*           startData = (TSKEY*)pStartTsCol->pData;
1410
  SColumnInfoData* pEndTsCol = taosArrayGet(pSrcBlock->pDataBlock, END_TS_COLUMN_INDEX);
L
Liu Jicong 已提交
1411
  TSKEY*           endData = (TSKEY*)pEndTsCol->pData;
1412 1413
  SColumnInfoData* pUidCol = taosArrayGet(pSrcBlock->pDataBlock, UID_COLUMN_INDEX);
  uint64_t*        uidCol = (uint64_t*)pUidCol->pData;
L
Liu Jicong 已提交
1414

1415 1416
  SColumnInfoData* pDestStartCol = taosArrayGet(pDestBlock->pDataBlock, START_TS_COLUMN_INDEX);
  SColumnInfoData* pDestEndCol = taosArrayGet(pDestBlock->pDataBlock, END_TS_COLUMN_INDEX);
5
54liuyao 已提交
1417
  SColumnInfoData* pDestUidCol = taosArrayGet(pDestBlock->pDataBlock, UID_COLUMN_INDEX);
1418
  SColumnInfoData* pDestGpCol = taosArrayGet(pDestBlock->pDataBlock, GROUPID_COLUMN_INDEX);
5
54liuyao 已提交
1419 1420
  SColumnInfoData* pDestCalStartTsCol = taosArrayGet(pDestBlock->pDataBlock, CALCULATE_START_TS_COLUMN_INDEX);
  SColumnInfoData* pDestCalEndTsCol = taosArrayGet(pDestBlock->pDataBlock, CALCULATE_END_TS_COLUMN_INDEX);
L
Liu Jicong 已提交
1421
  int64_t          version = pSrcBlock->info.version - 1;
1422
  for (int32_t i = 0; i < pSrcBlock->info.rows; i++) {
1423
    uint64_t groupId = getGroupIdByData(pInfo, uidCol[i], startData[i], version);
L
Liu Jicong 已提交
1424
    // gap must be 0.
5
54liuyao 已提交
1425
    SSessionKey startWin = {0};
1426
    getCurSessionWindow(pInfo->windowSup.pStreamAggSup, startData[i], startData[i], groupId, &startWin);
5
54liuyao 已提交
1427
    if (IS_INVALID_SESSION_WIN_KEY(startWin)) {
L
Liu Jicong 已提交
1428 1429 1430
      // window has been closed.
      continue;
    }
5
54liuyao 已提交
1431 1432 1433 1434 1435 1436
    SSessionKey endWin = {0};
    getCurSessionWindow(pInfo->windowSup.pStreamAggSup, endData[i], endData[i], groupId, &endWin);
    ASSERT(!IS_INVALID_SESSION_WIN_KEY(endWin));
    colDataAppend(pDestStartCol, i, (const char*)&startWin.win.skey, false);
    colDataAppend(pDestEndCol, i, (const char*)&endWin.win.ekey, false);

5
54liuyao 已提交
1437
    colDataAppendNULL(pDestUidCol, i);
L
Liu Jicong 已提交
1438
    colDataAppend(pDestGpCol, i, (const char*)&groupId, false);
5
54liuyao 已提交
1439 1440
    colDataAppendNULL(pDestCalStartTsCol, i);
    colDataAppendNULL(pDestCalEndTsCol, i);
1441
    pDestBlock->info.rows++;
L
Liu Jicong 已提交
1442
  }
1443
  return TSDB_CODE_SUCCESS;
L
Liu Jicong 已提交
1444
}
1445 1446 1447 1448 1449 1450

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;
1451
  }
5
54liuyao 已提交
1452
  int32_t code = blockDataEnsureCapacity(pDestBlock, rows);
1453 1454 1455 1456
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

1457 1458
  SColumnInfoData* pSrcStartTsCol = (SColumnInfoData*)taosArrayGet(pSrcBlock->pDataBlock, START_TS_COLUMN_INDEX);
  SColumnInfoData* pSrcEndTsCol = (SColumnInfoData*)taosArrayGet(pSrcBlock->pDataBlock, END_TS_COLUMN_INDEX);
1459 1460 1461 1462
  SColumnInfoData* pSrcUidCol = taosArrayGet(pSrcBlock->pDataBlock, UID_COLUMN_INDEX);
  uint64_t*        srcUidData = (uint64_t*)pSrcUidCol->pData;
  SColumnInfoData* pSrcGpCol = taosArrayGet(pSrcBlock->pDataBlock, GROUPID_COLUMN_INDEX);
  uint64_t*        srcGp = (uint64_t*)pSrcGpCol->pData;
1463 1464 1465
  ASSERT(pSrcStartTsCol->info.type == TSDB_DATA_TYPE_TIMESTAMP);
  TSKEY*           srcStartTsCol = (TSKEY*)pSrcStartTsCol->pData;
  TSKEY*           srcEndTsCol = (TSKEY*)pSrcEndTsCol->pData;
1466 1467
  SColumnInfoData* pStartTsCol = taosArrayGet(pDestBlock->pDataBlock, START_TS_COLUMN_INDEX);
  SColumnInfoData* pEndTsCol = taosArrayGet(pDestBlock->pDataBlock, END_TS_COLUMN_INDEX);
1468
  SColumnInfoData* pDeUidCol = taosArrayGet(pDestBlock->pDataBlock, UID_COLUMN_INDEX);
1469 1470 1471
  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);
L
Liu Jicong 已提交
1472
  int64_t          version = pSrcBlock->info.version - 1;
1473
  for (int32_t i = 0; i < rows;) {
1474
    uint64_t srcUid = srcUidData[i];
5
54liuyao 已提交
1475 1476 1477 1478 1479
    uint64_t groupId = srcGp[i];
    if (groupId == 0) {
      groupId = getGroupIdByData(pInfo, srcUid, srcStartTsCol[i], version);
    }
    TSKEY calStartTs = srcStartTsCol[i];
1480
    colDataAppend(pCalStartTsCol, pDestBlock->info.rows, (const char*)(&calStartTs), false);
5
54liuyao 已提交
1481
    STimeWindow win = getSlidingWindow(srcStartTsCol, srcEndTsCol, srcGp, &pInfo->interval, &pSrcBlock->info, &i,
1482 1483
                                       pInfo->partitionSup.needCalc);
    TSKEY       calEndTs = srcStartTsCol[i - 1];
1484 1485
    colDataAppend(pCalEndTsCol, pDestBlock->info.rows, (const char*)(&calEndTs), false);
    colDataAppend(pDeUidCol, pDestBlock->info.rows, (const char*)(&srcUid), false);
1486 1487 1488 1489
    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 已提交
1490
  }
1491 1492
  return TSDB_CODE_SUCCESS;
}
1493

1494
static int32_t generateDeleteResultBlock(SStreamScanInfo* pInfo, SSDataBlock* pSrcBlock, SSDataBlock* pDestBlock) {
5
54liuyao 已提交
1495 1496 1497
  blockDataCleanup(pDestBlock);
  int32_t rows = pSrcBlock->info.rows;
  if (rows == 0) {
1498 1499
    return TSDB_CODE_SUCCESS;
  }
5
54liuyao 已提交
1500
  int32_t code = blockDataEnsureCapacity(pDestBlock, rows);
1501 1502 1503 1504
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

5
54liuyao 已提交
1505 1506 1507 1508 1509 1510 1511 1512 1513 1514
  SColumnInfoData* pSrcStartTsCol = (SColumnInfoData*)taosArrayGet(pSrcBlock->pDataBlock, START_TS_COLUMN_INDEX);
  SColumnInfoData* pSrcEndTsCol = (SColumnInfoData*)taosArrayGet(pSrcBlock->pDataBlock, END_TS_COLUMN_INDEX);
  SColumnInfoData* pSrcUidCol = taosArrayGet(pSrcBlock->pDataBlock, UID_COLUMN_INDEX);
  uint64_t*        srcUidData = (uint64_t*)pSrcUidCol->pData;
  SColumnInfoData* pSrcGpCol = taosArrayGet(pSrcBlock->pDataBlock, GROUPID_COLUMN_INDEX);
  uint64_t*        srcGp = (uint64_t*)pSrcGpCol->pData;
  ASSERT(pSrcStartTsCol->info.type == TSDB_DATA_TYPE_TIMESTAMP);
  TSKEY*  srcStartTsCol = (TSKEY*)pSrcStartTsCol->pData;
  TSKEY*  srcEndTsCol = (TSKEY*)pSrcEndTsCol->pData;
  int64_t version = pSrcBlock->info.version - 1;
1515
  for (int32_t i = 0; i < pSrcBlock->info.rows; i++) {
5
54liuyao 已提交
1516 1517 1518 1519 1520 1521
    uint64_t srcUid = srcUidData[i];
    uint64_t groupId = srcGp[i];
    if (groupId == 0) {
      groupId = getGroupIdByData(pInfo, srcUid, srcStartTsCol[i], version);
    }
    appendOneRowToStreamSpecialBlock(pDestBlock, srcStartTsCol + i, srcEndTsCol + i, srcUidData + i, &groupId, NULL);
1522 1523 1524 1525
  }
  return TSDB_CODE_SUCCESS;
}

1526 1527 1528 1529
static int32_t generateScanRange(SStreamScanInfo* pInfo, SSDataBlock* pSrcBlock, SSDataBlock* pDestBlock) {
  int32_t code = TSDB_CODE_SUCCESS;
  if (isIntervalWindow(pInfo)) {
    code = generateIntervalScanRange(pInfo, pSrcBlock, pDestBlock);
1530
  } else if (isSessionWindow(pInfo) || isStateWindow(pInfo)) {
1531
    code = generateSessionScanRange(pInfo, pSrcBlock, pDestBlock);
5
54liuyao 已提交
1532 1533
  } else {
    code = generateDeleteResultBlock(pInfo, pSrcBlock, pDestBlock);
1534
  }
1535
  pDestBlock->info.type = STREAM_CLEAR;
1536
  pDestBlock->info.version = pSrcBlock->info.version;
1537 1538 1539 1540
  blockDataUpdateTsWindow(pDestBlock, 0);
  return code;
}

L
Liu Jicong 已提交
1541 1542 1543 1544 1545 1546 1547 1548 1549
static void calBlockTag(SExprSupp* pTagCalSup, SSDataBlock* pBlock, SSDataBlock* pResBlock) {
  if (pTagCalSup == NULL || pTagCalSup->numOfExprs == 0) return;
  if (pBlock == NULL || pBlock->info.rows == 0) return;

  SSDataBlock* pSrcBlock = blockCopyOneRow(pBlock, 0);
  ASSERT(pSrcBlock->info.rows == 1);

  blockDataEnsureCapacity(pResBlock, 1);

H
Haojun Liao 已提交
1550
  projectApplyFunctions(pTagCalSup->pExprInfo, pResBlock, pSrcBlock, pTagCalSup->pCtx, 1, NULL);
L
Liu Jicong 已提交
1551 1552 1553
  ASSERT(pResBlock->info.rows == 1);

  // build tagArray
1554 1555 1556 1557 1558
  /*SArray* tagArray = taosArrayInit(0, sizeof(void*));*/
  /*STagVal tagVal = {*/
  /*.cid = 0,*/
  /*.type = 0,*/
  /*};*/
L
Liu Jicong 已提交
1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586
  // build STag
  // set STag

  blockDataDestroy(pSrcBlock);
}

static void calBlockTbName(SExprSupp* pTbNameCalSup, SSDataBlock* pBlock) {
  if (pTbNameCalSup == NULL || pTbNameCalSup->numOfExprs == 0) return;
  if (pBlock == NULL || pBlock->info.rows == 0) return;

  SSDataBlock* pSrcBlock = blockCopyOneRow(pBlock, 0);
  ASSERT(pSrcBlock->info.rows == 1);

  SSDataBlock* pResBlock = createDataBlock();
  pResBlock->info.rowSize = VARSTR_HEADER_SIZE + TSDB_TABLE_NAME_LEN;
  SColumnInfoData data = createColumnInfoData(TSDB_DATA_TYPE_VARCHAR, TSDB_TABLE_NAME_LEN, 0);
  taosArrayPush(pResBlock->pDataBlock, &data);
  blockDataEnsureCapacity(pResBlock, 1);

  projectApplyFunctions(pTbNameCalSup->pExprInfo, pResBlock, pSrcBlock, pTbNameCalSup->pCtx, 1, NULL);
  ASSERT(pResBlock->info.rows == 1);
  ASSERT(taosArrayGetSize(pResBlock->pDataBlock) == 1);
  SColumnInfoData* pCol = taosArrayGet(pResBlock->pDataBlock, 0);
  ASSERT(pCol->info.type == TSDB_DATA_TYPE_VARCHAR);

  void* pData = colDataGetData(pCol, 0);
  // TODO check tbname validation
  if (pData != (void*)-1 && pData != NULL) {
1587
    memset(pBlock->info.parTbName, 0, TSDB_TABLE_NAME_LEN);
L
Liu Jicong 已提交
1588
    int32_t len = TMIN(varDataLen(pData), TSDB_TABLE_NAME_LEN - 1);
1589 1590
    memcpy(pBlock->info.parTbName, varDataVal(pData), len);
    /*pBlock->info.parTbName[len + 1] = 0;*/
L
Liu Jicong 已提交
1591 1592 1593 1594 1595 1596 1597 1598
  } else {
    pBlock->info.parTbName[0] = 0;
  }

  blockDataDestroy(pSrcBlock);
  blockDataDestroy(pResBlock);
}

1599 1600
void appendOneRowToStreamSpecialBlock(SSDataBlock* pBlock, TSKEY* pStartTs, TSKEY* pEndTs, uint64_t* pUid,
                                      uint64_t* pGp, void* pTbName) {
1601 1602
  SColumnInfoData* pStartTsCol = taosArrayGet(pBlock->pDataBlock, START_TS_COLUMN_INDEX);
  SColumnInfoData* pEndTsCol = taosArrayGet(pBlock->pDataBlock, END_TS_COLUMN_INDEX);
1603 1604
  SColumnInfoData* pUidCol = taosArrayGet(pBlock->pDataBlock, UID_COLUMN_INDEX);
  SColumnInfoData* pGpCol = taosArrayGet(pBlock->pDataBlock, GROUPID_COLUMN_INDEX);
1605 1606
  SColumnInfoData* pCalStartCol = taosArrayGet(pBlock->pDataBlock, CALCULATE_START_TS_COLUMN_INDEX);
  SColumnInfoData* pCalEndCol = taosArrayGet(pBlock->pDataBlock, CALCULATE_END_TS_COLUMN_INDEX);
1607
  SColumnInfoData* pTableCol = taosArrayGet(pBlock->pDataBlock, TABLE_NAME_COLUMN_INDEX);
1608 1609
  colDataAppend(pStartTsCol, pBlock->info.rows, (const char*)pStartTs, false);
  colDataAppend(pEndTsCol, pBlock->info.rows, (const char*)pEndTs, false);
1610 1611
  colDataAppend(pUidCol, pBlock->info.rows, (const char*)pUid, false);
  colDataAppend(pGpCol, pBlock->info.rows, (const char*)pGp, false);
1612 1613
  colDataAppend(pCalStartCol, pBlock->info.rows, (const char*)pStartTs, false);
  colDataAppend(pCalEndCol, pBlock->info.rows, (const char*)pEndTs, false);
1614
  colDataAppend(pTableCol, pBlock->info.rows, (const char*)pTbName, pTbName == NULL);
1615
  pBlock->info.rows++;
5
54liuyao 已提交
1616 1617
}

1618
static void checkUpdateData(SStreamScanInfo* pInfo, bool invertible, SSDataBlock* pBlock, bool out) {
1619 1620
  if (out) {
    blockDataCleanup(pInfo->pUpdateDataRes);
5
54liuyao 已提交
1621
    blockDataEnsureCapacity(pInfo->pUpdateDataRes, pBlock->info.rows * 2);
1622
  }
1623 1624
  SColumnInfoData* pColDataInfo = taosArrayGet(pBlock->pDataBlock, pInfo->primaryTsIndex);
  ASSERT(pColDataInfo->info.type == TSDB_DATA_TYPE_TIMESTAMP);
5
54liuyao 已提交
1625
  TSKEY* tsCol = (TSKEY*)pColDataInfo->pData;
L
Liu Jicong 已提交
1626
  bool   tableInserted = updateInfoIsTableInserted(pInfo->pUpdateInfo, pBlock->info.uid);
1627
  for (int32_t rowId = 0; rowId < pBlock->info.rows; rowId++) {
5
54liuyao 已提交
1628 1629
    SResultRowInfo dumyInfo;
    dumyInfo.cur.pageId = -1;
L
Liu Jicong 已提交
1630
    bool        isClosed = false;
5
54liuyao 已提交
1631
    STimeWindow win = {.skey = INT64_MIN, .ekey = INT64_MAX};
L
Liu Jicong 已提交
1632
    if (tableInserted && isOverdue(tsCol[rowId], &pInfo->twAggSup)) {
5
54liuyao 已提交
1633 1634 1635
      win = getActiveTimeWindow(NULL, &dumyInfo, tsCol[rowId], &pInfo->interval, TSDB_ORDER_ASC);
      isClosed = isCloseWindow(&win, &pInfo->twAggSup);
    }
5
54liuyao 已提交
1636 1637
    // must check update info first.
    bool update = updateInfoIsUpdated(pInfo->pUpdateInfo, pBlock->info.uid, tsCol[rowId]);
L
Liu Jicong 已提交
1638
    bool closedWin = isClosed && isSignleIntervalWindow(pInfo) &&
1639 1640
                     isDeletedStreamWindow(&win, pBlock->info.groupId,
                                           pInfo->pTableScanOp->pTaskInfo->streamInfo.pState, &pInfo->twAggSup);
L
Liu Jicong 已提交
1641
    if ((update || closedWin) && out) {
L
Liu Jicong 已提交
1642
      qDebug("stream update check not pass, update %d, closedWin %d", update, closedWin);
5
54liuyao 已提交
1643
      uint64_t gpId = 0;
1644 1645
      appendOneRowToStreamSpecialBlock(pInfo->pUpdateDataRes, tsCol + rowId, tsCol + rowId, &pBlock->info.uid, &gpId,
                                       NULL);
5
54liuyao 已提交
1646 1647
      if (closedWin && pInfo->partitionSup.needCalc) {
        gpId = calGroupIdByData(&pInfo->partitionSup, pInfo->pPartScalarSup, pBlock, rowId);
1648 1649
        appendOneRowToStreamSpecialBlock(pInfo->pUpdateDataRes, tsCol + rowId, tsCol + rowId, &pBlock->info.uid, &gpId,
                                         NULL);
5
54liuyao 已提交
1650
      }
1651 1652
    }
  }
1653 1654
  if (out && pInfo->pUpdateDataRes->info.rows > 0) {
    pInfo->pUpdateDataRes->info.version = pBlock->info.version;
1655
    blockDataUpdateTsWindow(pInfo->pUpdateDataRes, 0);
1656
    pInfo->pUpdateDataRes->info.type = pInfo->partitionSup.needCalc ? STREAM_DELETE_DATA : STREAM_CLEAR;
5
54liuyao 已提交
1657 1658
  }
}
L
Liu Jicong 已提交
1659

1660
static int32_t setBlockIntoRes(SStreamScanInfo* pInfo, const SSDataBlock* pBlock, bool filter) {
L
Liu Jicong 已提交
1661 1662
  SDataBlockInfo* pBlockInfo = &pInfo->pRes->info;
  SOperatorInfo*  pOperator = pInfo->pStreamScanOp;
L
Liu Jicong 已提交
1663
  SExecTaskInfo*  pTaskInfo = pOperator->pTaskInfo;
L
Liu Jicong 已提交
1664

1665 1666
  blockDataEnsureCapacity(pInfo->pRes, pBlock->info.rows);

L
Liu Jicong 已提交
1667 1668 1669
  pInfo->pRes->info.rows = pBlock->info.rows;
  pInfo->pRes->info.uid = pBlock->info.uid;
  pInfo->pRes->info.type = STREAM_NORMAL;
1670
  pInfo->pRes->info.version = pBlock->info.version;
L
Liu Jicong 已提交
1671

H
Haojun Liao 已提交
1672
  pInfo->pRes->info.groupId = getTableGroupId(pTaskInfo->pTableInfoList, pBlock->info.uid);
L
Liu Jicong 已提交
1673 1674

  // todo extract method
H
Haojun Liao 已提交
1675 1676 1677
  for (int32_t i = 0; i < taosArrayGetSize(pInfo->matchInfo.pList); ++i) {
    SColMatchItem* pColMatchInfo = taosArrayGet(pInfo->matchInfo.pList, i);
    if (!pColMatchInfo->needOutput) {
L
Liu Jicong 已提交
1678 1679 1680 1681 1682 1683 1684
      continue;
    }

    bool colExists = false;
    for (int32_t j = 0; j < blockDataGetNumOfCols(pBlock); ++j) {
      SColumnInfoData* pResCol = bdGetColumnInfoData(pBlock, j);
      if (pResCol->info.colId == pColMatchInfo->colId) {
H
Haojun Liao 已提交
1685
        SColumnInfoData* pDst = taosArrayGet(pInfo->pRes->pDataBlock, pColMatchInfo->dstSlotId);
1686
        colDataAssign(pDst, pResCol, pBlock->info.rows, &pInfo->pRes->info);
L
Liu Jicong 已提交
1687 1688 1689 1690 1691 1692 1693
        colExists = true;
        break;
      }
    }

    // the required column does not exists in submit block, let's set it to be all null value
    if (!colExists) {
H
Haojun Liao 已提交
1694
      SColumnInfoData* pDst = taosArrayGet(pInfo->pRes->pDataBlock, pColMatchInfo->dstSlotId);
L
Liu Jicong 已提交
1695 1696 1697 1698 1699 1700
      colDataAppendNNULL(pDst, 0, pBlockInfo->rows);
    }
  }

  // currently only the tbname pseudo column
  if (pInfo->numOfPseudoExpr > 0) {
L
Liu Jicong 已提交
1701
    int32_t code = addTagPseudoColumnData(&pInfo->readHandle, pInfo->pPseudoExpr, pInfo->numOfPseudoExpr, pInfo->pRes,
1702
                                          pInfo->pRes->info.rows, GET_TASKID(pTaskInfo), NULL);
H
Haojun Liao 已提交
1703
    if (code != TSDB_CODE_SUCCESS) {
L
Liu Jicong 已提交
1704
      blockDataFreeRes((SSDataBlock*)pBlock);
1705
      T_LONG_JMP(pTaskInfo->env, code);
H
Haojun Liao 已提交
1706
    }
L
Liu Jicong 已提交
1707 1708
  }

1709
  if (filter) {
H
Haojun Liao 已提交
1710
    doFilter(pInfo->pRes, pOperator->exprSupp.pFilterInfo, NULL);
1711
  }
1712

L
Liu Jicong 已提交
1713
  blockDataUpdateTsWindow(pInfo->pRes, pInfo->primaryTsIndex);
L
Liu Jicong 已提交
1714
  blockDataFreeRes((SSDataBlock*)pBlock);
L
Liu Jicong 已提交
1715

L
Liu Jicong 已提交
1716
  calBlockTbName(&pInfo->tbnameCalSup, pInfo->pRes);
L
Liu Jicong 已提交
1717 1718
  return 0;
}
5
54liuyao 已提交
1719

L
Liu Jicong 已提交
1720
static SSDataBlock* doQueueScan(SOperatorInfo* pOperator) {
1721 1722
  SExecTaskInfo*   pTaskInfo = pOperator->pTaskInfo;
  SStreamScanInfo* pInfo = pOperator->info;
H
Haojun Liao 已提交
1723

L
Liu Jicong 已提交
1724
  qDebug("queue scan called");
L
Liu Jicong 已提交
1725 1726 1727 1728 1729 1730 1731 1732

  if (pTaskInfo->streamInfo.pReq != NULL) {
    if (pInfo->tqReader->pMsg == NULL) {
      pInfo->tqReader->pMsg = pTaskInfo->streamInfo.pReq;
      const SSubmitReq* pSubmit = pInfo->tqReader->pMsg;
      if (tqReaderSetDataMsg(pInfo->tqReader, pSubmit, 0) < 0) {
        qError("submit msg messed up when initing stream submit block %p", pSubmit);
        pInfo->tqReader->pMsg = NULL;
L
Liu Jicong 已提交
1733
        pTaskInfo->streamInfo.pReq = NULL;
L
Liu Jicong 已提交
1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749
        ASSERT(0);
      }
    }

    blockDataCleanup(pInfo->pRes);
    SDataBlockInfo* pBlockInfo = &pInfo->pRes->info;

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

      int32_t code = tqRetrieveDataBlock(&block, pInfo->tqReader);

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

1750
      setBlockIntoRes(pInfo, &block, true);
L
Liu Jicong 已提交
1751 1752 1753 1754 1755 1756 1757 1758

      if (pBlockInfo->rows > 0) {
        return pInfo->pRes;
      }
    }

    pInfo->tqReader->pMsg = NULL;
    pTaskInfo->streamInfo.pReq = NULL;
L
Liu Jicong 已提交
1759
    return NULL;
L
Liu Jicong 已提交
1760 1761
  }

L
Liu Jicong 已提交
1762 1763 1764
  if (pTaskInfo->streamInfo.prepareStatus.type == TMQ_OFFSET__SNAPSHOT_DATA) {
    SSDataBlock* pResult = doTableScan(pInfo->pTableScanOp);
    if (pResult && pResult->info.rows > 0) {
L
Liu Jicong 已提交
1765
      qDebug("queue scan tsdb return %d rows", pResult->info.rows);
1766
      pTaskInfo->streamInfo.returned = 1;
L
Liu Jicong 已提交
1767 1768
      return pResult;
    } else {
1769 1770 1771 1772 1773
      if (!pTaskInfo->streamInfo.returned) {
        STableScanInfo* pTSInfo = pInfo->pTableScanOp->info;
        tsdbReaderClose(pTSInfo->dataReader);
        pTSInfo->dataReader = NULL;
        tqOffsetResetToLog(&pTaskInfo->streamInfo.prepareStatus, pTaskInfo->streamInfo.snapshotVer);
1774
        qDebug("queue scan tsdb over, switch to wal ver %" PRId64 "", pTaskInfo->streamInfo.snapshotVer + 1);
1775
        if (tqSeekVer(pInfo->tqReader, pTaskInfo->streamInfo.snapshotVer + 1) < 0) {
1776
          tqOffsetResetToLog(&pTaskInfo->streamInfo.lastStatus, pTaskInfo->streamInfo.snapshotVer);
1777 1778 1779 1780
          return NULL;
        }
        ASSERT(pInfo->tqReader->pWalReader->curVersion == pTaskInfo->streamInfo.snapshotVer + 1);
      } else {
L
Liu Jicong 已提交
1781 1782
        return NULL;
      }
1783 1784 1785
    }
  }

L
Liu Jicong 已提交
1786 1787 1788 1789 1790 1791
  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);
1792
        if (setBlockIntoRes(pInfo, &ret.data, true) < 0) {
L
Liu Jicong 已提交
1793 1794 1795
          ASSERT(0);
        }
        if (pInfo->pRes->info.rows > 0) {
L
Liu Jicong 已提交
1796
          pOperator->status = OP_EXEC_RECV;
L
Liu Jicong 已提交
1797
          qDebug("queue scan log return %d rows", pInfo->pRes->info.rows);
L
Liu Jicong 已提交
1798 1799 1800 1801
          return pInfo->pRes;
        }
      } else if (ret.fetchType == FETCH_TYPE__META) {
        ASSERT(0);
L
Liu Jicong 已提交
1802 1803 1804
        //        pTaskInfo->streamInfo.lastStatus = ret.offset;
        //        pTaskInfo->streamInfo.metaBlk = ret.meta;
        //        return NULL;
L
Liu Jicong 已提交
1805 1806
      } else if (ret.fetchType == FETCH_TYPE__NONE ||
                 (ret.fetchType == FETCH_TYPE__SEP && pOperator->status == OP_EXEC_RECV)) {
L
Liu Jicong 已提交
1807
        pTaskInfo->streamInfo.lastStatus = ret.offset;
1808 1809 1810 1811
        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);
L
Liu Jicong 已提交
1812
        qDebug("queue scan log return null, offset %s", formatBuf);
L
Liu Jicong 已提交
1813
        pOperator->status = OP_OPENED;
L
Liu Jicong 已提交
1814 1815 1816
        return NULL;
      }
    }
L
Liu Jicong 已提交
1817
#if 0
1818
    } else if (pTaskInfo->streamInfo.prepareStatus.type == TMQ_OFFSET__SNAPSHOT_DATA) {
L
Liu Jicong 已提交
1819
    SSDataBlock* pResult = doTableScan(pInfo->pTableScanOp);
L
Liu Jicong 已提交
1820 1821 1822 1823 1824 1825
    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 已提交
1826
#endif
L
Liu Jicong 已提交
1827 1828 1829
  } else {
    ASSERT(0);
    return NULL;
H
Haojun Liao 已提交
1830
  }
L
Liu Jicong 已提交
1831 1832
}

L
Liu Jicong 已提交
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
static int32_t filterDelBlockByUid(SSDataBlock* pDst, const SSDataBlock* pSrc, SStreamScanInfo* pInfo) {
  STqReader* pReader = pInfo->tqReader;
  int32_t    rows = pSrc->info.rows;
  blockDataEnsureCapacity(pDst, rows);

  SColumnInfoData* pSrcStartCol = taosArrayGet(pSrc->pDataBlock, START_TS_COLUMN_INDEX);
  uint64_t*        startCol = (uint64_t*)pSrcStartCol->pData;
  SColumnInfoData* pSrcEndCol = taosArrayGet(pSrc->pDataBlock, END_TS_COLUMN_INDEX);
  uint64_t*        endCol = (uint64_t*)pSrcEndCol->pData;
  SColumnInfoData* pSrcUidCol = taosArrayGet(pSrc->pDataBlock, UID_COLUMN_INDEX);
  uint64_t*        uidCol = (uint64_t*)pSrcUidCol->pData;

  SColumnInfoData* pDstStartCol = taosArrayGet(pDst->pDataBlock, START_TS_COLUMN_INDEX);
  SColumnInfoData* pDstEndCol = taosArrayGet(pDst->pDataBlock, END_TS_COLUMN_INDEX);
  SColumnInfoData* pDstUidCol = taosArrayGet(pDst->pDataBlock, UID_COLUMN_INDEX);
  int32_t          j = 0;
  for (int32_t i = 0; i < rows; i++) {
    if (taosHashGet(pReader->tbIdHash, &uidCol[i], sizeof(uint64_t))) {
      colDataAppend(pDstStartCol, j, (const char*)&startCol[i], false);
      colDataAppend(pDstEndCol, j, (const char*)&endCol[i], false);
      colDataAppend(pDstUidCol, j, (const char*)&uidCol[i], false);

      colDataAppendNULL(taosArrayGet(pDst->pDataBlock, GROUPID_COLUMN_INDEX), j);
      colDataAppendNULL(taosArrayGet(pDst->pDataBlock, CALCULATE_START_TS_COLUMN_INDEX), j);
      colDataAppendNULL(taosArrayGet(pDst->pDataBlock, CALCULATE_END_TS_COLUMN_INDEX), j);
      j++;
    }
  }
L
Liu Jicong 已提交
1861
  uint32_t cap = pDst->info.capacity;
L
Liu Jicong 已提交
1862 1863
  pDst->info = pSrc->info;
  pDst->info.rows = j;
L
Liu Jicong 已提交
1864
  pDst->info.capacity = cap;
L
Liu Jicong 已提交
1865 1866 1867 1868

  return 0;
}

5
54liuyao 已提交
1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892
// for partition by tag
static void setBlockGroupIdByUid(SStreamScanInfo* pInfo, SSDataBlock* pBlock) {
  SColumnInfoData* pStartTsCol = taosArrayGet(pBlock->pDataBlock, START_TS_COLUMN_INDEX);
  TSKEY*           startTsCol = (TSKEY*)pStartTsCol->pData;
  SColumnInfoData* pGpCol = taosArrayGet(pBlock->pDataBlock, GROUPID_COLUMN_INDEX);
  uint64_t*        gpCol = (uint64_t*)pGpCol->pData;
  SColumnInfoData* pUidCol = taosArrayGet(pBlock->pDataBlock, UID_COLUMN_INDEX);
  uint64_t*        uidCol = (uint64_t*)pUidCol->pData;
  int32_t          rows = pBlock->info.rows;
  if (!pInfo->partitionSup.needCalc) {
    for (int32_t i = 0; i < rows; i++) {
      uint64_t groupId = getGroupIdByUid(pInfo, uidCol[i]);
      colDataAppend(pGpCol, i, (const char*)&groupId, false);
    }
  } else {
    // SSDataBlock* pPreRes = readPreVersionData(pInfo->pTableScanOp, uidCol[i], startTsCol, ts, maxVersion);
    // if (!pPreRes || pPreRes->info.rows == 0) {
    //   return 0;
    // }
    // ASSERT(pPreRes->info.rows == 1);
    // return calGroupIdByData(&pInfo->partitionSup, pInfo->pPartScalarSup, pPreRes, 0);
  }
}

L
Liu Jicong 已提交
1893 1894 1895 1896 1897
static SSDataBlock* doStreamScan(SOperatorInfo* pOperator) {
  // NOTE: this operator does never check if current status is done or not
  SExecTaskInfo*   pTaskInfo = pOperator->pTaskInfo;
  SStreamScanInfo* pInfo = pOperator->info;

L
Liu Jicong 已提交
1898
  qDebug("stream scan called");
L
Liu Jicong 已提交
1899 1900 1901 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 1927 1928 1929 1930 1931
#if 0
  SStreamState* pState = pTaskInfo->streamInfo.pState;
  if (pState) {
    printf(">>>>>>>> stream write backend\n");
    SWinKey key = {
        .ts = 1,
        .groupId = 2,
    };
    char tmp[100] = "abcdefg1";
    if (streamStatePut(pState, &key, &tmp, strlen(tmp) + 1) < 0) {
      ASSERT(0);
    }

    key.ts = 2;
    char tmp2[100] = "abcdefg2";
    if (streamStatePut(pState, &key, &tmp2, strlen(tmp2) + 1) < 0) {
      ASSERT(0);
    }

    key.groupId = 5;
    key.ts = 1;
    char tmp3[100] = "abcdefg3";
    if (streamStatePut(pState, &key, &tmp3, strlen(tmp3) + 1) < 0) {
      ASSERT(0);
    }

    char*   val2 = NULL;
    int32_t sz;
    if (streamStateGet(pState, &key, (void**)&val2, &sz) < 0) {
      ASSERT(0);
    }
    printf("stream read %s %d\n", val2, sz);
    streamFreeVal(val2);
H
Haojun Liao 已提交
1932
  }
L
Liu Jicong 已提交
1933
#endif
H
Haojun Liao 已提交
1934

1935 1936
  if (pTaskInfo->streamInfo.recoverStep == STREAM_RECOVER_STEP__PREPARE1 ||
      pTaskInfo->streamInfo.recoverStep == STREAM_RECOVER_STEP__PREPARE2) {
L
Liu Jicong 已提交
1937 1938
    STableScanInfo* pTSInfo = pInfo->pTableScanOp->info;
    memcpy(&pTSInfo->cond, &pTaskInfo->streamInfo.tableCond, sizeof(SQueryTableDataCond));
1939
    if (pTaskInfo->streamInfo.recoverStep == STREAM_RECOVER_STEP__PREPARE1) {
1940
      pTSInfo->cond.startVersion = 0;
1941
      pTSInfo->cond.endVersion = pTaskInfo->streamInfo.fillHistoryVer1;
1942 1943
      qDebug("stream recover step 1, from %" PRId64 " to %" PRId64, pTSInfo->cond.startVersion,
             pTSInfo->cond.endVersion);
1944 1945 1946
    } else {
      pTSInfo->cond.startVersion = pTaskInfo->streamInfo.fillHistoryVer1 + 1;
      pTSInfo->cond.endVersion = pTaskInfo->streamInfo.fillHistoryVer2;
1947 1948
      qDebug("stream recover step 2, from %" PRId64 " to %" PRId64, pTSInfo->cond.startVersion,
             pTSInfo->cond.endVersion);
1949
    }
L
Liu Jicong 已提交
1950 1951 1952 1953 1954

    /*resetTableScanInfo(pTSInfo, pWin);*/
    tsdbReaderClose(pTSInfo->dataReader);
    pTSInfo->dataReader = NULL;

L
Liu Jicong 已提交
1955 1956 1957 1958 1959 1960 1961 1962
    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) {
L
Liu Jicong 已提交
1963 1964
      calBlockTbName(&pInfo->tbnameCalSup, pBlock);
      updateInfoFillBlockData(pInfo->pUpdateInfo, pBlock, pInfo->primaryTsIndex);
1965
      qDebug("stream recover scan get block, rows %d", pBlock->info.rows);
L
Liu Jicong 已提交
1966 1967 1968
      return pBlock;
    }
    pTaskInfo->streamInfo.recoverStep = STREAM_RECOVER_STEP__NONE;
L
Liu Jicong 已提交
1969
    STableScanInfo* pTSInfo = pInfo->pTableScanOp->info;
1970 1971 1972 1973
    tsdbReaderClose(pTSInfo->dataReader);
    pTSInfo->dataReader = NULL;

    pTSInfo->cond.startVersion = -1;
L
Liu Jicong 已提交
1974 1975
    pTSInfo->cond.endVersion = -1;

L
Liu Jicong 已提交
1976 1977 1978
    return NULL;
  }

5
54liuyao 已提交
1979
  size_t total = taosArrayGetSize(pInfo->pBlockLists);
5
54liuyao 已提交
1980
// TODO: refactor
L
Liu Jicong 已提交
1981
FETCH_NEXT_BLOCK:
L
Liu Jicong 已提交
1982
  if (pInfo->blockType == STREAM_INPUT__DATA_BLOCK) {
H
Haojun Liao 已提交
1983
    if (pInfo->validBlockIndex >= total) {
L
Liu Jicong 已提交
1984
      doClearBufferedBlocks(pInfo);
L
Liu Jicong 已提交
1985
      /*pOperator->status = OP_EXEC_DONE;*/
H
Haojun Liao 已提交
1986 1987 1988
      return NULL;
    }

1989
    int32_t      current = pInfo->validBlockIndex++;
1990
    SSDataBlock* pBlock = taosArrayGetP(pInfo->pBlockLists, current);
1991
    // TODO move into scan
5
54liuyao 已提交
1992 1993
    pBlock->info.calWin.skey = INT64_MIN;
    pBlock->info.calWin.ekey = INT64_MAX;
1994
    blockDataUpdateTsWindow(pBlock, 0);
1995
    switch (pBlock->info.type) {
L
Liu Jicong 已提交
1996 1997 1998
      case STREAM_NORMAL:
      case STREAM_GET_ALL:
        return pBlock;
1999 2000 2001
      case STREAM_RETRIEVE: {
        pInfo->blockType = STREAM_INPUT__DATA_SUBMIT;
        pInfo->scanMode = STREAM_SCAN_FROM_DATAREADER_RETRIEVE;
2002 2003
        copyDataBlock(pInfo->pUpdateRes, pBlock);
        prepareRangeScan(pInfo, pInfo->pUpdateRes, &pInfo->updateResIndex);
2004 2005 2006
        updateInfoAddCloseWindowSBF(pInfo->pUpdateInfo);
      } break;
      case STREAM_DELETE_DATA: {
2007
        printDataBlock(pBlock, "stream scan delete recv");
L
Liu Jicong 已提交
2008
        SSDataBlock* pDelBlock = NULL;
L
Liu Jicong 已提交
2009
        if (pInfo->tqReader) {
L
Liu Jicong 已提交
2010
          pDelBlock = createSpecialDataBlock(STREAM_DELETE_DATA);
L
Liu Jicong 已提交
2011
          filterDelBlockByUid(pDelBlock, pBlock, pInfo);
L
Liu Jicong 已提交
2012 2013
        } else {
          pDelBlock = pBlock;
L
Liu Jicong 已提交
2014
        }
5
54liuyao 已提交
2015 2016
        setBlockGroupIdByUid(pInfo, pDelBlock);
        printDataBlock(pDelBlock, "stream scan delete recv filtered");
2017
        if (!isIntervalWindow(pInfo) && !isSessionWindow(pInfo) && !isStateWindow(pInfo)) {
L
Liu Jicong 已提交
2018
          generateDeleteResultBlock(pInfo, pDelBlock, pInfo->pDeleteDataRes);
2019
          pInfo->pDeleteDataRes->info.type = STREAM_DELETE_RESULT;
L
Liu Jicong 已提交
2020
          printDataBlock(pDelBlock, "stream scan delete result");
H
Haojun Liao 已提交
2021 2022
          blockDataDestroy(pDelBlock);

L
Liu Jicong 已提交
2023 2024 2025 2026 2027
          if (pInfo->pDeleteDataRes->info.rows > 0) {
            return pInfo->pDeleteDataRes;
          } else {
            goto FETCH_NEXT_BLOCK;
          }
2028 2029 2030
        } else {
          pInfo->blockType = STREAM_INPUT__DATA_SUBMIT;
          pInfo->updateResIndex = 0;
L
Liu Jicong 已提交
2031
          generateScanRange(pInfo, pDelBlock, pInfo->pUpdateRes);
2032 2033 2034 2035
          prepareRangeScan(pInfo, pInfo->pUpdateRes, &pInfo->updateResIndex);
          copyDataBlock(pInfo->pDeleteDataRes, pInfo->pUpdateRes);
          pInfo->pDeleteDataRes->info.type = STREAM_DELETE_DATA;
          pInfo->scanMode = STREAM_SCAN_FROM_DATAREADER_RANGE;
L
Liu Jicong 已提交
2036 2037 2038 2039
          printDataBlock(pDelBlock, "stream scan delete data");
          if (pInfo->tqReader) {
            blockDataDestroy(pDelBlock);
          }
L
Liu Jicong 已提交
2040 2041 2042 2043 2044
          if (pInfo->pDeleteDataRes->info.rows > 0) {
            return pInfo->pDeleteDataRes;
          } else {
            goto FETCH_NEXT_BLOCK;
          }
2045
        }
2046 2047 2048
      } break;
      default:
        break;
5
54liuyao 已提交
2049
    }
2050
    // printDataBlock(pBlock, "stream scan recv");
2051
    return pBlock;
L
Liu Jicong 已提交
2052
  } else if (pInfo->blockType == STREAM_INPUT__DATA_SUBMIT) {
L
Liu Jicong 已提交
2053
    qDebug("scan mode %d", pInfo->scanMode);
5
54liuyao 已提交
2054 2055 2056 2057 2058 2059
    switch (pInfo->scanMode) {
      case STREAM_SCAN_FROM_RES: {
        blockDataDestroy(pInfo->pUpdateRes);
        pInfo->scanMode = STREAM_SCAN_FROM_READERHANDLE;
        return pInfo->pRes;
      } break;
2060
      case STREAM_SCAN_FROM_DELETE_DATA: {
2061 2062 2063 2064 2065 2066 2067
        generateScanRange(pInfo, pInfo->pUpdateDataRes, pInfo->pUpdateRes);
        prepareRangeScan(pInfo, pInfo->pUpdateRes, &pInfo->updateResIndex);
        pInfo->scanMode = STREAM_SCAN_FROM_DATAREADER_RANGE;
        copyDataBlock(pInfo->pDeleteDataRes, pInfo->pUpdateRes);
        pInfo->pDeleteDataRes->info.type = STREAM_DELETE_DATA;
        return pInfo->pDeleteDataRes;
      } break;
5
54liuyao 已提交
2068 2069 2070 2071 2072 2073 2074 2075 2076 2077
      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) {
2078
          STableScanInfo* pTableScanInfo = pInfo->pTableScanOp->info;
L
Liu Jicong 已提交
2079 2080
          uint64_t        version = getReaderMaxVersion(pTableScanInfo->dataReader);
          updateInfoSetScanRange(pInfo->pUpdateInfo, &pTableScanInfo->cond.twindows, pInfo->groupId, version);
5
54liuyao 已提交
2081 2082
          pSDB->info.type = pInfo->scanMode == STREAM_SCAN_FROM_DATAREADER_RANGE ? STREAM_NORMAL : STREAM_PULL_DATA;
          checkUpdateData(pInfo, true, pSDB, false);
2083
          // printDataBlock(pSDB, "stream scan update");
L
Liu Jicong 已提交
2084
          calBlockTbName(&pInfo->tbnameCalSup, pSDB);
5
54liuyao 已提交
2085 2086
          return pSDB;
        }
2087
        blockDataCleanup(pInfo->pUpdateDataRes);
5
54liuyao 已提交
2088 2089 2090 2091
        pInfo->scanMode = STREAM_SCAN_FROM_READERHANDLE;
      } break;
      default:
        break;
2092
    }
2093

2094
    SStreamAggSupporter* pSup = pInfo->windowSup.pStreamAggSup;
5
54liuyao 已提交
2095
    if (isStateWindow(pInfo) && pSup->pScanBlock->info.rows > 0) {
2096 2097
      pInfo->scanMode = STREAM_SCAN_FROM_DATAREADER_RANGE;
      pInfo->updateResIndex = 0;
5
54liuyao 已提交
2098 2099
      copyDataBlock(pInfo->pUpdateRes, pSup->pScanBlock);
      blockDataCleanup(pSup->pScanBlock);
2100 2101
      prepareRangeScan(pInfo, pInfo->pUpdateRes, &pInfo->updateResIndex);
      return pInfo->pUpdateRes;
5
54liuyao 已提交
2102
    }
5
54liuyao 已提交
2103

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

2106
    int32_t totBlockNum = taosArrayGetSize(pInfo->pBlockLists);
2107

L
Liu Jicong 已提交
2108
  NEXT_SUBMIT_BLK:
2109 2110 2111
    while (1) {
      if (pInfo->tqReader->pMsg == NULL) {
        if (pInfo->validBlockIndex >= totBlockNum) {
5
54liuyao 已提交
2112
          updateInfoDestoryColseWinSBF(pInfo->pUpdateInfo);
L
Liu Jicong 已提交
2113
          doClearBufferedBlocks(pInfo);
2114 2115
          return NULL;
        }
2116

2117 2118 2119 2120 2121 2122 2123 2124
        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 已提交
2125 2126
      }

2127 2128 2129 2130
      blockDataCleanup(pInfo->pRes);

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

2132 2133 2134 2135 2136 2137
        int32_t code = tqRetrieveDataBlock(&block, pInfo->tqReader);

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

2138
        setBlockIntoRes(pInfo, &block, false);
2139

L
Liu Jicong 已提交
2140 2141
        if (updateInfoIgnore(pInfo->pUpdateInfo, &pInfo->pRes->info.window, pInfo->pRes->info.groupId,
                             pInfo->pRes->info.version)) {
2142 2143 2144 2145 2146
          printDataBlock(pInfo->pRes, "stream scan ignore");
          blockDataCleanup(pInfo->pRes);
          continue;
        }

2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162
        if (pInfo->pUpdateInfo) {
          checkUpdateData(pInfo, true, pInfo->pRes, true);
          pInfo->twAggSup.maxTs = TMAX(pInfo->twAggSup.maxTs, pBlockInfo->window.ekey);
          if (pInfo->pUpdateDataRes->info.rows > 0) {
            pInfo->updateResIndex = 0;
            if (pInfo->pUpdateDataRes->info.type == STREAM_CLEAR) {
              pInfo->scanMode = STREAM_SCAN_FROM_UPDATERES;
            } else if (pInfo->pUpdateDataRes->info.type == STREAM_INVERT) {
              pInfo->scanMode = STREAM_SCAN_FROM_RES;
              return pInfo->pUpdateDataRes;
            } else if (pInfo->pUpdateDataRes->info.type == STREAM_DELETE_DATA) {
              pInfo->scanMode = STREAM_SCAN_FROM_DELETE_DATA;
            }
          }
        }

H
Haojun Liao 已提交
2163
        doFilter(pInfo->pRes, pOperator->exprSupp.pFilterInfo, NULL);
2164 2165 2166
        blockDataUpdateTsWindow(pInfo->pRes, pInfo->primaryTsIndex);

        if (pBlockInfo->rows > 0 || pInfo->pUpdateDataRes->info.rows > 0) {
2167 2168 2169
          break;
        }
      }
2170
      if (pBlockInfo->rows > 0 || pInfo->pUpdateDataRes->info.rows > 0) {
5
54liuyao 已提交
2171
        break;
J
jiacy-jcy 已提交
2172 2173
      } else {
        pInfo->tqReader->pMsg = NULL;
2174
        continue;
5
54liuyao 已提交
2175
      }
2176
      /*blockDataCleanup(pInfo->pRes);*/
H
Haojun Liao 已提交
2177 2178 2179 2180
    }

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

L
Liu Jicong 已提交
2184
    qDebug("scan rows: %d", pBlockInfo->rows);
L
Liu Jicong 已提交
2185 2186 2187
    if (pBlockInfo->rows > 0) {
      return pInfo->pRes;
    }
2188 2189 2190 2191 2192 2193

    if (pInfo->pUpdateDataRes->info.rows > 0) {
      goto FETCH_NEXT_BLOCK;
    }

    goto NEXT_SUBMIT_BLK;
L
Liu Jicong 已提交
2194 2195 2196
  } else {
    ASSERT(0);
    return NULL;
H
Haojun Liao 已提交
2197 2198 2199
  }
}

H
Haojun Liao 已提交
2200
static SArray* extractTableIdList(const STableListInfo* pTableListInfo) {
2201 2202 2203
  SArray* tableIdList = taosArrayInit(4, sizeof(uint64_t));

  // Transfer the Array of STableKeyInfo into uid list.
H
Haojun Liao 已提交
2204 2205 2206
  size_t size = tableListGetSize(pTableListInfo);
  for (int32_t i = 0; i < size; ++i) {
    STableKeyInfo* pkeyInfo = tableListGetInfo(pTableListInfo, i);
2207 2208 2209 2210 2211 2212
    taosArrayPush(tableIdList, &pkeyInfo->uid);
  }

  return tableIdList;
}

2213
static SSDataBlock* doRawScan(SOperatorInfo* pOperator) {
L
Liu Jicong 已提交
2214 2215
  // NOTE: this operator does never check if current status is done or not
  SExecTaskInfo*      pTaskInfo = pOperator->pTaskInfo;
2216
  SStreamRawScanInfo* pInfo = pOperator->info;
L
Liu Jicong 已提交
2217
  pTaskInfo->streamInfo.metaRsp.metaRspLen = 0;  // use metaRspLen !=0 to judge if data is meta
wmmhello's avatar
wmmhello 已提交
2218
  pTaskInfo->streamInfo.metaRsp.metaRsp = NULL;
2219

wmmhello's avatar
wmmhello 已提交
2220
  qDebug("tmqsnap doRawScan called");
L
Liu Jicong 已提交
2221
  if (pTaskInfo->streamInfo.prepareStatus.type == TMQ_OFFSET__SNAPSHOT_DATA) {
wmmhello's avatar
wmmhello 已提交
2222
    SSDataBlock* pBlock = &pInfo->pRes;
2223

2224
    if (pInfo->dataReader && tsdbNextDataBlock(pInfo->dataReader)) {
wmmhello's avatar
wmmhello 已提交
2225 2226 2227
      if (isTaskKilled(pTaskInfo)) {
        longjmp(pTaskInfo->env, TSDB_CODE_TSC_QUERY_CANCELLED);
      }
2228

H
Haojun Liao 已提交
2229 2230 2231
      int32_t rows = 0;
      tsdbRetrieveDataBlockInfo(pInfo->dataReader, &rows, &pBlock->info.uid, &pBlock->info.window);
      pBlock->info.rows = rows;
2232

wmmhello's avatar
wmmhello 已提交
2233 2234 2235
      SArray* pCols = tsdbRetrieveDataBlock(pInfo->dataReader, NULL);
      pBlock->pDataBlock = pCols;
      if (pCols == NULL) {
wmmhello's avatar
wmmhello 已提交
2236
        longjmp(pTaskInfo->env, terrno);
wmmhello's avatar
wmmhello 已提交
2237 2238
      }

2239
      qDebug("tmqsnap doRawScan get data uid:%" PRId64 "", pBlock->info.uid);
wmmhello's avatar
wmmhello 已提交
2240 2241 2242 2243 2244
      pTaskInfo->streamInfo.lastStatus.type = TMQ_OFFSET__SNAPSHOT_DATA;
      pTaskInfo->streamInfo.lastStatus.uid = pBlock->info.uid;
      pTaskInfo->streamInfo.lastStatus.ts = pBlock->info.window.ekey;
      return pBlock;
    }
wmmhello's avatar
wmmhello 已提交
2245 2246

    SMetaTableInfo mtInfo = getUidfromSnapShot(pInfo->sContext);
L
Liu Jicong 已提交
2247
    if (mtInfo.uid == 0) {  // read snapshot done, change to get data from wal
wmmhello's avatar
wmmhello 已提交
2248 2249
      qDebug("tmqsnap read snapshot done, change to get data from wal");
      pTaskInfo->streamInfo.prepareStatus.uid = mtInfo.uid;
wmmhello's avatar
wmmhello 已提交
2250 2251
      pTaskInfo->streamInfo.lastStatus.type = TMQ_OFFSET__LOG;
      pTaskInfo->streamInfo.lastStatus.version = pInfo->sContext->snapVersion;
L
Liu Jicong 已提交
2252
    } else {
wmmhello's avatar
wmmhello 已提交
2253 2254
      pTaskInfo->streamInfo.prepareStatus.uid = mtInfo.uid;
      pTaskInfo->streamInfo.prepareStatus.ts = INT64_MIN;
2255
      qDebug("tmqsnap change get data uid:%" PRId64 "", mtInfo.uid);
wmmhello's avatar
wmmhello 已提交
2256 2257
      qStreamPrepareScan(pTaskInfo, &pTaskInfo->streamInfo.prepareStatus, pInfo->sContext->subType);
    }
2258
    tDeleteSSchemaWrapper(mtInfo.schema);
wmmhello's avatar
wmmhello 已提交
2259
    qDebug("tmqsnap stream scan tsdb return null");
wmmhello's avatar
wmmhello 已提交
2260
    return NULL;
L
Liu Jicong 已提交
2261 2262 2263 2264 2265 2266 2267
  } else if (pTaskInfo->streamInfo.prepareStatus.type == TMQ_OFFSET__SNAPSHOT_META) {
    SSnapContext* sContext = pInfo->sContext;
    void*         data = NULL;
    int32_t       dataLen = 0;
    int16_t       type = 0;
    int64_t       uid = 0;
    if (getMetafromSnapShot(sContext, &data, &dataLen, &type, &uid) < 0) {
wmmhello's avatar
wmmhello 已提交
2268
      qError("tmqsnap getMetafromSnapShot error");
wmmhello's avatar
wmmhello 已提交
2269
      taosMemoryFreeClear(data);
2270 2271 2272
      return NULL;
    }

L
Liu Jicong 已提交
2273
    if (!sContext->queryMetaOrData) {  // change to get data next poll request
wmmhello's avatar
wmmhello 已提交
2274 2275 2276 2277
      pTaskInfo->streamInfo.lastStatus.type = TMQ_OFFSET__SNAPSHOT_META;
      pTaskInfo->streamInfo.lastStatus.uid = uid;
      pTaskInfo->streamInfo.metaRsp.rspOffset.type = TMQ_OFFSET__SNAPSHOT_DATA;
      pTaskInfo->streamInfo.metaRsp.rspOffset.uid = 0;
wmmhello's avatar
wmmhello 已提交
2278
      pTaskInfo->streamInfo.metaRsp.rspOffset.ts = INT64_MIN;
L
Liu Jicong 已提交
2279
    } else {
wmmhello's avatar
wmmhello 已提交
2280 2281 2282 2283 2284 2285 2286
      pTaskInfo->streamInfo.lastStatus.type = TMQ_OFFSET__SNAPSHOT_META;
      pTaskInfo->streamInfo.lastStatus.uid = uid;
      pTaskInfo->streamInfo.metaRsp.rspOffset = pTaskInfo->streamInfo.lastStatus;
      pTaskInfo->streamInfo.metaRsp.resMsgType = type;
      pTaskInfo->streamInfo.metaRsp.metaRspLen = dataLen;
      pTaskInfo->streamInfo.metaRsp.metaRsp = data;
    }
2287

wmmhello's avatar
wmmhello 已提交
2288
    return NULL;
2289
  }
L
Liu Jicong 已提交
2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327
  //  else if (pTaskInfo->streamInfo.prepareStatus.type == TMQ_OFFSET__LOG) {
  //    int64_t fetchVer = pTaskInfo->streamInfo.prepareStatus.version + 1;
  //
  //    while(1){
  //      if (tqFetchLog(pInfo->tqReader->pWalReader, pInfo->sContext->withMeta, &fetchVer, &pInfo->pCkHead) < 0) {
  //        qDebug("tmqsnap tmq poll: consumer log end. offset %" PRId64, fetchVer);
  //        pTaskInfo->streamInfo.lastStatus.version = fetchVer;
  //        pTaskInfo->streamInfo.lastStatus.type = TMQ_OFFSET__LOG;
  //        return NULL;
  //      }
  //      SWalCont* pHead = &pInfo->pCkHead->head;
  //      qDebug("tmqsnap tmq poll: consumer log offset %" PRId64 " msgType %d", fetchVer, pHead->msgType);
  //
  //      if (pHead->msgType == TDMT_VND_SUBMIT) {
  //        SSubmitReq* pCont = (SSubmitReq*)&pHead->body;
  //        tqReaderSetDataMsg(pInfo->tqReader, pCont, 0);
  //        SSDataBlock* block = tqLogScanExec(pInfo->sContext->subType, pInfo->tqReader, pInfo->pFilterOutTbUid,
  //        &pInfo->pRes); if(block){
  //          pTaskInfo->streamInfo.lastStatus.type = TMQ_OFFSET__LOG;
  //          pTaskInfo->streamInfo.lastStatus.version = fetchVer;
  //          qDebug("tmqsnap fetch data msg, ver:%" PRId64 ", type:%d", pHead->version, pHead->msgType);
  //          return block;
  //        }else{
  //          fetchVer++;
  //        }
  //      } else{
  //        ASSERT(pInfo->sContext->withMeta);
  //        ASSERT(IS_META_MSG(pHead->msgType));
  //        qDebug("tmqsnap fetch meta msg, ver:%" PRId64 ", type:%d", pHead->version, pHead->msgType);
  //        pTaskInfo->streamInfo.metaRsp.rspOffset.version = fetchVer;
  //        pTaskInfo->streamInfo.metaRsp.rspOffset.type = TMQ_OFFSET__LOG;
  //        pTaskInfo->streamInfo.metaRsp.resMsgType = pHead->msgType;
  //        pTaskInfo->streamInfo.metaRsp.metaRspLen = pHead->bodyLen;
  //        pTaskInfo->streamInfo.metaRsp.metaRsp = taosMemoryMalloc(pHead->bodyLen);
  //        memcpy(pTaskInfo->streamInfo.metaRsp.metaRsp, pHead->body, pHead->bodyLen);
  //        return NULL;
  //      }
  //    }
2328 2329 2330
  return NULL;
}

wmmhello's avatar
wmmhello 已提交
2331
static void destroyRawScanOperatorInfo(void* param) {
wmmhello's avatar
wmmhello 已提交
2332 2333 2334 2335 2336 2337
  SStreamRawScanInfo* pRawScan = (SStreamRawScanInfo*)param;
  tsdbReaderClose(pRawScan->dataReader);
  destroySnapContext(pRawScan->sContext);
  taosMemoryFree(pRawScan);
}

L
Liu Jicong 已提交
2338 2339 2340
// for subscribing db or stb (not including column),
// if this scan is used, meta data can be return
// and schemas are decided when scanning
2341
SOperatorInfo* createRawScanOperatorInfo(SReadHandle* pHandle, SExecTaskInfo* pTaskInfo) {
L
Liu Jicong 已提交
2342 2343 2344 2345 2346
  // create operator
  // create tb reader
  // create meta reader
  // create tq reader

H
Haojun Liao 已提交
2347 2348
  int32_t code = TSDB_CODE_SUCCESS;

2349
  SStreamRawScanInfo* pInfo = taosMemoryCalloc(1, sizeof(SStreamRawScanInfo));
L
Liu Jicong 已提交
2350
  SOperatorInfo*      pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
2351
  if (pInfo == NULL || pOperator == NULL) {
H
Haojun Liao 已提交
2352 2353
    code = TSDB_CODE_OUT_OF_MEMORY;
    goto _end;
2354 2355
  }

wmmhello's avatar
wmmhello 已提交
2356 2357
  pInfo->vnode = pHandle->vnode;

2358
  pInfo->sContext = pHandle->sContext;
L
Liu Jicong 已提交
2359 2360
  setOperatorInfo(pOperator, "RawScanOperator", QUERY_NODE_PHYSICAL_PLAN_TABLE_SCAN, false, OP_NOT_OPENED, pInfo,
                  pTaskInfo);
2361

H
Haojun Liao 已提交
2362
  pOperator->fpSet = createOperatorFpSet(NULL, doRawScan, NULL, destroyRawScanOperatorInfo, NULL);
2363
  return pOperator;
H
Haojun Liao 已提交
2364

L
Liu Jicong 已提交
2365
_end:
H
Haojun Liao 已提交
2366 2367 2368 2369
  taosMemoryFree(pInfo);
  taosMemoryFree(pOperator);
  pTaskInfo->code = code;
  return NULL;
L
Liu Jicong 已提交
2370 2371
}

2372
static void destroyStreamScanOperatorInfo(void* param) {
2373 2374
  SStreamScanInfo* pStreamScan = (SStreamScanInfo*)param;
  if (pStreamScan->pTableScanOp && pStreamScan->pTableScanOp->info) {
5
54liuyao 已提交
2375
    destroyOperatorInfo(pStreamScan->pTableScanOp);
2376 2377 2378 2379
  }
  if (pStreamScan->tqReader) {
    tqCloseReader(pStreamScan->tqReader);
  }
H
Haojun Liao 已提交
2380 2381
  if (pStreamScan->matchInfo.pList) {
    taosArrayDestroy(pStreamScan->matchInfo.pList);
2382
  }
C
Cary Xu 已提交
2383 2384
  if (pStreamScan->pPseudoExpr) {
    destroyExprInfo(pStreamScan->pPseudoExpr, pStreamScan->numOfPseudoExpr);
L
Liu Jicong 已提交
2385
    taosMemoryFree(pStreamScan->pPseudoExpr);
C
Cary Xu 已提交
2386
  }
C
Cary Xu 已提交
2387

L
Liu Jicong 已提交
2388
  updateInfoDestroy(pStreamScan->pUpdateInfo);
2389 2390 2391 2392
  blockDataDestroy(pStreamScan->pRes);
  blockDataDestroy(pStreamScan->pUpdateRes);
  blockDataDestroy(pStreamScan->pPullDataRes);
  blockDataDestroy(pStreamScan->pDeleteDataRes);
5
54liuyao 已提交
2393
  blockDataDestroy(pStreamScan->pUpdateDataRes);
2394 2395 2396 2397
  taosArrayDestroy(pStreamScan->pBlockLists);
  taosMemoryFree(pStreamScan);
}

2398
SOperatorInfo* createStreamScanOperatorInfo(SReadHandle* pHandle, STableScanPhysiNode* pTableScanNode, SNode* pTagCond,
2399
                                            SExecTaskInfo* pTaskInfo) {
2400 2401
  SStreamScanInfo* pInfo = taosMemoryCalloc(1, sizeof(SStreamScanInfo));
  SOperatorInfo*   pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
2402

H
Haojun Liao 已提交
2403 2404
  if (pInfo == NULL || pOperator == NULL) {
    terrno = TSDB_CODE_QRY_OUT_OF_MEMORY;
2405
    goto _error;
H
Haojun Liao 已提交
2406 2407
  }

2408
  SScanPhysiNode*     pScanPhyNode = &pTableScanNode->scan;
2409
  SDataBlockDescNode* pDescNode = pScanPhyNode->node.pOutputDataBlockDesc;
H
Haojun Liao 已提交
2410

2411
  pInfo->pTagCond = pTagCond;
2412
  pInfo->pGroupTags = pTableScanNode->pGroupTags;
2413

2414
  int32_t numOfCols = 0;
2415 2416
  int32_t code =
      extractColMatchInfo(pScanPhyNode->pScanCols, pDescNode, &numOfCols, COL_MATCH_FROM_COL_ID, &pInfo->matchInfo);
H
Haojun Liao 已提交
2417 2418 2419
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
2420

H
Haojun Liao 已提交
2421
  int32_t numOfOutput = taosArrayGetSize(pInfo->matchInfo.pList);
2422
  SArray* pColIds = taosArrayInit(numOfOutput, sizeof(int16_t));
2423
  for (int32_t i = 0; i < numOfOutput; ++i) {
H
Haojun Liao 已提交
2424
    SColMatchItem* id = taosArrayGet(pInfo->matchInfo.pList, i);
2425 2426

    int16_t colId = id->colId;
2427
    taosArrayPush(pColIds, &colId);
2428
    if (id->colId == PRIMARYKEY_TIMESTAMP_COL_ID) {
H
Haojun Liao 已提交
2429
      pInfo->primaryTsIndex = id->dstSlotId;
5
54liuyao 已提交
2430
    }
H
Haojun Liao 已提交
2431 2432
  }

L
Liu Jicong 已提交
2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445
  if (pTableScanNode->pSubtable != NULL) {
    SExprInfo* pSubTableExpr = taosMemoryCalloc(1, sizeof(SExprInfo));
    if (pSubTableExpr == NULL) {
      terrno = TSDB_CODE_OUT_OF_MEMORY;
      goto _error;
    }
    pInfo->tbnameCalSup.pExprInfo = pSubTableExpr;
    createExprFromOneNode(pSubTableExpr, pTableScanNode->pSubtable, 0);
    if (initExprSupp(&pInfo->tbnameCalSup, pSubTableExpr, 1) != 0) {
      goto _error;
    }
  }

2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458
  if (pTableScanNode->pTags != NULL) {
    int32_t    numOfTags;
    SExprInfo* pTagExpr = createExprInfo(pTableScanNode->pTags, NULL, &numOfTags);
    if (pTagExpr == NULL) {
      terrno = TSDB_CODE_OUT_OF_MEMORY;
      goto _error;
    }
    if (initExprSupp(&pInfo->tagCalSup, pTagExpr, numOfTags) != 0) {
      terrno = TSDB_CODE_OUT_OF_MEMORY;
      goto _error;
    }
  }

H
Haojun Liao 已提交
2459 2460
  pInfo->pBlockLists = taosArrayInit(4, POINTER_BYTES);
  if (pInfo->pBlockLists == NULL) {
2461 2462
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    goto _error;
H
Haojun Liao 已提交
2463 2464
  }

5
54liuyao 已提交
2465
  if (pHandle->vnode) {
L
Liu Jicong 已提交
2466
    SOperatorInfo*  pTableScanOp = createTableScanOperatorInfo(pTableScanNode, pHandle, pTaskInfo);
L
Liu Jicong 已提交
2467
    STableScanInfo* pTSInfo = (STableScanInfo*)pTableScanOp->info;
2468
    if (pHandle->version > 0) {
L
Liu Jicong 已提交
2469
      pTSInfo->cond.endVersion = pHandle->version;
2470
    }
L
Liu Jicong 已提交
2471

2472
    STableKeyInfo* pList = NULL;
5
54liuyao 已提交
2473
    int32_t        num = 0;
H
Haojun Liao 已提交
2474
    tableListGetGroupList(pTaskInfo->pTableInfoList, 0, &pList, &num);
2475

2476
    if (pHandle->initTableReader) {
L
Liu Jicong 已提交
2477 2478
      pTSInfo->scanMode = TABLE_SCAN__TABLE_ORDER;
      pTSInfo->dataReader = NULL;
H
Haojun Liao 已提交
2479
      code = tsdbReaderOpen(pHandle->vnode, &pTSInfo->cond, pList, num, &pTSInfo->dataReader, NULL);
dengyihao's avatar
dengyihao 已提交
2480 2481
      if (code != 0) {
        terrno = code;
H
Haojun Liao 已提交
2482
        destroyTableScanOperatorInfo(pTableScanOp);
2483
        goto _error;
L
Liu Jicong 已提交
2484
      }
L
Liu Jicong 已提交
2485 2486
    }

L
Liu Jicong 已提交
2487 2488 2489 2490
    if (pHandle->initTqReader) {
      ASSERT(pHandle->tqReader == NULL);
      pInfo->tqReader = tqOpenReader(pHandle->vnode);
      ASSERT(pInfo->tqReader);
2491
    } else {
L
Liu Jicong 已提交
2492 2493
      ASSERT(pHandle->tqReader);
      pInfo->tqReader = pHandle->tqReader;
2494 2495
    }

2496
    pInfo->pUpdateInfo = NULL;
2497
    pInfo->pTableScanOp = pTableScanOp;
2498 2499 2500
    if (pInfo->pTableScanOp->pTaskInfo->streamInfo.pState) {
      streamStateSetNumber(pInfo->pTableScanOp->pTaskInfo->streamInfo.pState, -1);
    }
L
Liu Jicong 已提交
2501

L
Liu Jicong 已提交
2502 2503
    pInfo->readHandle = *pHandle;
    pInfo->tableUid = pScanPhyNode->uid;
L
Liu Jicong 已提交
2504
    pTaskInfo->streamInfo.snapshotVer = pHandle->version;
L
Liu Jicong 已提交
2505

L
Liu Jicong 已提交
2506
    // set the extract column id to streamHandle
L
Liu Jicong 已提交
2507
    tqReaderSetColIdList(pInfo->tqReader, pColIds);
H
Haojun Liao 已提交
2508
    SArray* tableIdList = extractTableIdList(pTaskInfo->pTableInfoList);
2509
    code = tqReaderSetTbUidList(pInfo->tqReader, tableIdList);
L
Liu Jicong 已提交
2510 2511 2512 2513 2514
    if (code != 0) {
      taosArrayDestroy(tableIdList);
      goto _error;
    }
    taosArrayDestroy(tableIdList);
L
Liu Jicong 已提交
2515
    memcpy(&pTaskInfo->streamInfo.tableCond, &pTSInfo->cond, sizeof(SQueryTableDataCond));
L
Liu Jicong 已提交
2516 2517
  } else {
    taosArrayDestroy(pColIds);
5
54liuyao 已提交
2518 2519
  }

2520 2521 2522 2523 2524
  // create the pseduo columns info
  if (pTableScanNode->scan.pScanPseudoCols != NULL) {
    pInfo->pPseudoExpr = createExprInfo(pTableScanNode->scan.pScanPseudoCols, NULL, &pInfo->numOfPseudoExpr);
  }

H
Haojun Liao 已提交
2525 2526 2527 2528 2529
  code = filterInitFromNode((SNode*)pScanPhyNode->node.pConditions, &pOperator->exprSupp.pFilterInfo, 0);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }

2530
  pInfo->pRes = createResDataBlock(pDescNode);
2531
  pInfo->pUpdateRes = createSpecialDataBlock(STREAM_CLEAR);
2532
  pInfo->scanMode = STREAM_SCAN_FROM_READERHANDLE;
L
Liu Jicong 已提交
2533
  pInfo->windowSup = (SWindowSupporter){.pStreamAggSup = NULL, .gap = -1, .parentType = QUERY_NODE_PHYSICAL_PLAN};
2534
  pInfo->groupId = 0;
2535
  pInfo->pPullDataRes = createSpecialDataBlock(STREAM_RETRIEVE);
2536
  pInfo->pStreamScanOp = pOperator;
2537
  pInfo->deleteDataIndex = 0;
2538
  pInfo->pDeleteDataRes = createSpecialDataBlock(STREAM_DELETE_DATA);
5
54liuyao 已提交
2539
  pInfo->updateWin = (STimeWindow){.skey = INT64_MAX, .ekey = INT64_MAX};
2540
  pInfo->pUpdateDataRes = createSpecialDataBlock(STREAM_CLEAR);
X
Xiaoyu Wang 已提交
2541
  pInfo->assignBlockUid = pTableScanNode->assignBlockUid;
2542
  pInfo->partitionSup.needCalc = false;
L
Liu Jicong 已提交
2543

L
Liu Jicong 已提交
2544 2545
  setOperatorInfo(pOperator, "StreamScanOperator", QUERY_NODE_PHYSICAL_PLAN_STREAM_SCAN, false, OP_NOT_OPENED, pInfo,
                  pTaskInfo);
2546
  pOperator->exprSupp.numOfExprs = taosArrayGetSize(pInfo->pRes->pDataBlock);
H
Haojun Liao 已提交
2547

L
Liu Jicong 已提交
2548
  __optr_fn_t nextFn = pTaskInfo->execModel == OPTR_EXEC_MODEL_STREAM ? doStreamScan : doQueueScan;
H
Haojun Liao 已提交
2549
  pOperator->fpSet = createOperatorFpSet(operatorDummyOpenFn, nextFn, NULL, destroyStreamScanOperatorInfo, NULL);
2550

H
Haojun Liao 已提交
2551
  return pOperator;
2552

L
Liu Jicong 已提交
2553
_error:
H
Haojun Liao 已提交
2554 2555 2556 2557 2558 2559 2560 2561
  if (pColIds != NULL) {
    taosArrayDestroy(pColIds);
  }

  if (pInfo != NULL) {
    destroyStreamScanOperatorInfo(pInfo);
  }

2562 2563
  taosMemoryFreeClear(pOperator);
  return NULL;
H
Haojun Liao 已提交
2564 2565
}

2566
static void destroySysScanOperator(void* param) {
H
Haojun Liao 已提交
2567 2568 2569 2570
  SSysTableScanInfo* pInfo = (SSysTableScanInfo*)param;
  tsem_destroy(&pInfo->ready);
  blockDataDestroy(pInfo->pRes);

2571
  const char* name = tNameGetTableName(&pInfo->name);
D
dapan1121 已提交
2572 2573
  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 已提交
2574
    metaCloseTbCursor(pInfo->pCur);
2575
    pInfo->pCur = NULL;
H
Haojun Liao 已提交
2576
  }
dengyihao's avatar
dengyihao 已提交
2577 2578 2579 2580 2581
  if (pInfo->pIdx) {
    taosArrayDestroy(pInfo->pIdx->uids);
    taosMemoryFree(pInfo->pIdx);
    pInfo->pIdx = NULL;
  }
H
Haojun Liao 已提交
2582

H
Haojun Liao 已提交
2583
  taosArrayDestroy(pInfo->matchInfo.pList);
2584
  taosMemoryFreeClear(pInfo->pUser);
D
dapan1121 已提交
2585 2586

  taosMemoryFreeClear(param);
H
Haojun Liao 已提交
2587 2588
}

X
Xiaoyu Wang 已提交
2589
static int32_t getSysTableDbNameColId(const char* pTable) {
D
dapan1121 已提交
2590
  // if (0 == strcmp(TSDB_INS_TABLE_INDEXES, pTable)) {
X
Xiaoyu Wang 已提交
2591 2592
  //   return 1;
  // }
X
Xiaoyu Wang 已提交
2593 2594 2595
  return TSDB_INS_USER_STABLES_DBNAME_COLID;
}

H
Haojun Liao 已提交
2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616
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 已提交
2617
      if (getSysTableDbNameColId(node->tableName) == node->colId) {
H
Haojun Liao 已提交
2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633
        *(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;
2634
      return DEAL_RES_END;  // stop walk
H
Haojun Liao 已提交
2635 2636 2637 2638 2639 2640 2641
    }
    default:
      break;
  }
  return DEAL_RES_CONTINUE;
}

2642
static void getDBNameFromCondition(SNode* pCondition, const char* dbName) {
H
Haojun Liao 已提交
2643 2644 2645
  if (NULL == pCondition) {
    return;
  }
L
Liu Jicong 已提交
2646
  nodesWalkExpr(pCondition, getDBNameFromConditionWalker, (char*)dbName);
H
Haojun Liao 已提交
2647 2648
}

D
dapan1121 已提交
2649
static int32_t loadSysTableCallback(void* param, SDataBuf* pMsg, int32_t code) {
H
Haojun Liao 已提交
2650 2651 2652 2653 2654 2655 2656
  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);
2657 2658 2659
    pRsp->useconds = htobe64(pRsp->useconds);
    pRsp->handle = htobe64(pRsp->handle);
    pRsp->compLen = htonl(pRsp->compLen);
H
Haojun Liao 已提交
2660 2661 2662 2663 2664
  } else {
    operator->pTaskInfo->code = code;
  }

  tsem_post(&pScanResInfo->ready);
wmmhello's avatar
wmmhello 已提交
2665
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
2666 2667
}

H
Haojun Liao 已提交
2668 2669 2670
static SSDataBlock* doFilterResult(SSDataBlock* pDataBlock, SFilterInfo* pFilterInfo) {
  if (pFilterInfo == NULL) {
    return pDataBlock->info.rows == 0 ? NULL : pDataBlock;
H
Haojun Liao 已提交
2671 2672
  }

H
Haojun Liao 已提交
2673 2674
  doFilter(pDataBlock, pFilterInfo, NULL);
  return pDataBlock->info.rows == 0 ? NULL : pDataBlock;
H
Haojun Liao 已提交
2675 2676
}

2677
static SSDataBlock* buildInfoSchemaTableMetaBlock(char* tableName) {
L
Liu Jicong 已提交
2678 2679
  size_t               size = 0;
  const SSysTableMeta* pMeta = NULL;
2680 2681 2682
  getInfosDbMeta(&pMeta, &size);

  int32_t index = 0;
L
Liu Jicong 已提交
2683
  for (int32_t i = 0; i < size; ++i) {
2684
    if (strcmp(pMeta[i].name, tableName) == 0) {
2685 2686 2687 2688
      index = i;
      break;
    }
  }
2689

2690
  SSDataBlock* pBlock = createDataBlock();
L
Liu Jicong 已提交
2691
  for (int32_t i = 0; i < pMeta[index].colNum; ++i) {
L
Liu Jicong 已提交
2692 2693
    SColumnInfoData colInfoData =
        createColumnInfoData(pMeta[index].schema[i].type, pMeta[index].schema[i].bytes, i + 1);
2694
    blockDataAppendColInfo(pBlock, &colInfoData);
2695 2696
  }

2697 2698 2699
  return pBlock;
}

2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780
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;
}

2781 2782 2783 2784 2785 2786 2787
static bool sysTableIsOperatorCondOnOneTable(SNode* pCond, char* condTable) {
  SOperatorNode* node = (SOperatorNode*)pCond;
  if (node->opType == OP_TYPE_EQUAL) {
    if (nodeType(node->pLeft) == QUERY_NODE_COLUMN &&
        strcasecmp(nodesGetNameFromColumnNode(node->pLeft), "table_name") == 0 &&
        nodeType(node->pRight) == QUERY_NODE_VALUE) {
      SValueNode* pValue = (SValueNode*)node->pRight;
2788 2789 2790 2791
      if (pValue->node.resType.type == TSDB_DATA_TYPE_NCHAR || pValue->node.resType.type == TSDB_DATA_TYPE_VARCHAR ||
          pValue->node.resType.type == TSDB_DATA_TYPE_BINARY) {
        char* value = nodesGetValueFromNode(pValue);
        strncpy(condTable, varDataVal(value), TSDB_TABLE_NAME_LEN);
2792 2793 2794 2795 2796 2797 2798 2799
        return true;
      }
    }
  }
  return false;
}

static bool sysTableIsCondOnOneTable(SNode* pCond, char* condTable) {
S
slzhou 已提交
2800 2801 2802
  if (pCond == NULL) {
    return false;
  }
2803 2804 2805
  if (nodeType(pCond) == QUERY_NODE_LOGIC_CONDITION) {
    SLogicConditionNode* node = (SLogicConditionNode*)pCond;
    if (LOGIC_COND_TYPE_AND == node->condType) {
S
slzhou 已提交
2806 2807 2808 2809
      SNode* pChild = NULL;
      FOREACH(pChild, node->pParameterList) {
        if (QUERY_NODE_OPERATOR == nodeType(pChild) && sysTableIsOperatorCondOnOneTable(pChild, condTable)) {
          return true;
2810 2811 2812 2813
        }
      }
    }
  }
S
slzhou 已提交
2814

2815 2816 2817
  if (QUERY_NODE_OPERATOR == nodeType(pCond)) {
    return sysTableIsOperatorCondOnOneTable(pCond, condTable);
  }
S
slzhou 已提交
2818

2819 2820 2821
  return false;
}

S
shenglian zhou 已提交
2822 2823 2824 2825 2826 2827 2828 2829 2830 2831
static SSDataBlock* sysTableScanUserTags(SOperatorInfo* pOperator) {
  SExecTaskInfo*     pTaskInfo = pOperator->pTaskInfo;
  SSysTableScanInfo* pInfo = pOperator->info;
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

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

2832 2833 2834
  SSDataBlock* dataBlock = buildInfoSchemaTableMetaBlock(TSDB_INS_TABLE_TAGS);
  blockDataEnsureCapacity(dataBlock, pOperator->resultInfo.capacity);

S
shenglian zhou 已提交
2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845
  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)));

2846
  char condTableName[TSDB_TABLE_NAME_LEN] = {0};
S
slzhou 已提交
2847 2848
  // optimize when sql like where table_name='tablename' and xxx.
  if (pInfo->pCondition && sysTableIsCondOnOneTable(pInfo->pCondition, condTableName)) {
2849 2850 2851
    char tableName[TSDB_TABLE_NAME_LEN + VARSTR_HEADER_SIZE] = {0};
    STR_TO_VARSTR(tableName, condTableName);

2852 2853
    SMetaReader smrChildTable = {0};
    metaReaderInit(&smrChildTable, pInfo->readHandle.meta, 0);
H
Haojun Liao 已提交
2854 2855 2856 2857 2858 2859
    int32_t code = metaGetTableEntryByName(&smrChildTable, condTableName);
    if (code != TSDB_CODE_SUCCESS) {
      // terrno has been set by metaGetTableEntryByName, therefore, return directly
      return NULL;
    }

2860 2861 2862 2863 2864 2865
    if (smrChildTable.me.type != TSDB_CHILD_TABLE) {
      metaReaderClear(&smrChildTable);
      blockDataDestroy(dataBlock);
      pInfo->loadInfo.totalRows = 0;
      return NULL;
    }
H
Haojun Liao 已提交
2866

2867
    SMetaReader smrSuperTable = {0};
2868
    metaReaderInit(&smrSuperTable, pInfo->readHandle.meta, META_READER_NOLOCK);
H
Haojun Liao 已提交
2869 2870 2871 2872 2873 2874
    code = metaGetTableEntryByUid(&smrSuperTable, smrChildTable.me.ctbEntry.suid);
    if (code != TSDB_CODE_SUCCESS) {
      // terrno has been set by metaGetTableEntryByUid
      return NULL;
    }

2875 2876 2877
    sysTableUserTagsFillOneTableTags(pInfo, &smrSuperTable, &smrChildTable, dbname, tableName, &numOfRows, dataBlock);
    metaReaderClear(&smrSuperTable);
    metaReaderClear(&smrChildTable);
2878
    if (numOfRows > 0) {
H
Haojun Liao 已提交
2879
      relocateAndFilterSysTagsScanResult(pInfo, numOfRows, dataBlock, pOperator->exprSupp.pFilterInfo);
2880 2881 2882 2883
      numOfRows = 0;
    }
    blockDataDestroy(dataBlock);
    pInfo->loadInfo.totalRows += pInfo->pRes->info.rows;
H
Haojun Liao 已提交
2884
    setOperatorCompleted(pOperator);
2885 2886
    return (pInfo->pRes->info.rows == 0) ? NULL : pInfo->pRes;
  }
S
shenglian zhou 已提交
2887 2888

  int32_t ret = 0;
2889 2890 2891 2892
  if (pInfo->pCur == NULL) {
    pInfo->pCur = metaOpenTbCursor(pInfo->readHandle.meta);
  }

S
shenglian zhou 已提交
2893
  while ((ret = metaTbCursorNext(pInfo->pCur)) == 0) {
2894 2895 2896
    if (pInfo->pCur->mr.me.type != TSDB_CHILD_TABLE) {
      continue;
    }
S
shenglian zhou 已提交
2897

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

2901 2902
    SMetaReader smrSuperTable = {0};
    metaReaderInit(&smrSuperTable, pInfo->readHandle.meta, 0);
2903
    uint64_t suid = pInfo->pCur->mr.me.ctbEntry.suid;
2904
    int32_t  code = metaGetTableEntryByUid(&smrSuperTable, suid);
2905 2906 2907
    if (code != TSDB_CODE_SUCCESS) {
      qError("failed to get super table meta, uid:0x%" PRIx64 ", code:%s, %s", suid, tstrerror(terrno),
             GET_TASKID(pTaskInfo));
2908
      metaReaderClear(&smrSuperTable);
2909 2910
      metaCloseTbCursor(pInfo->pCur);
      pInfo->pCur = NULL;
2911
      T_LONG_JMP(pTaskInfo->env, terrno);
2912
    }
S
shenglian zhou 已提交
2913

2914
    sysTableUserTagsFillOneTableTags(pInfo, &smrSuperTable, &pInfo->pCur->mr, dbname, tableName, &numOfRows, dataBlock);
2915

2916
    metaReaderClear(&smrSuperTable);
S
shenglian zhou 已提交
2917

2918
    if (numOfRows >= pOperator->resultInfo.capacity) {
H
Haojun Liao 已提交
2919
      relocateAndFilterSysTagsScanResult(pInfo, numOfRows, dataBlock, pOperator->exprSupp.pFilterInfo);
2920 2921 2922 2923 2924
      numOfRows = 0;

      if (pInfo->pRes->info.rows > 0) {
        break;
      }
S
shenglian zhou 已提交
2925 2926 2927
    }
  }

2928
  if (numOfRows > 0) {
H
Haojun Liao 已提交
2929
    relocateAndFilterSysTagsScanResult(pInfo, numOfRows, dataBlock, pOperator->exprSupp.pFilterInfo);
2930 2931 2932
    numOfRows = 0;
  }

2933
  blockDataDestroy(dataBlock);
S
shenglian zhou 已提交
2934 2935 2936
  if (ret != 0) {
    metaCloseTbCursor(pInfo->pCur);
    pInfo->pCur = NULL;
H
Haojun Liao 已提交
2937
    setOperatorCompleted(pOperator);
S
shenglian zhou 已提交
2938 2939 2940 2941 2942 2943
  }

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

H
Haojun Liao 已提交
2944 2945
void relocateAndFilterSysTagsScanResult(SSysTableScanInfo* pInfo, int32_t numOfRows, SSDataBlock* dataBlock,
                                        SFilterInfo* pFilterInfo) {
2946 2947 2948
  dataBlock->info.rows = numOfRows;
  pInfo->pRes->info.rows = numOfRows;

H
Haojun Liao 已提交
2949
  relocateColumnData(pInfo->pRes, pInfo->matchInfo.pList, dataBlock->pDataBlock, false);
H
Haojun Liao 已提交
2950
  doFilterResult(pInfo->pRes, pFilterInfo);
2951 2952 2953
  blockDataCleanup(dataBlock);
}

2954 2955 2956
static int32_t sysTableUserTagsFillOneTableTags(const SSysTableScanInfo* pInfo, SMetaReader* smrSuperTable,
                                                SMetaReader* smrChildTable, const char* dbname, const char* tableName,
                                                int32_t* pNumOfRows, const SSDataBlock* dataBlock) {
2957
  char stableName[TSDB_TABLE_NAME_LEN + VARSTR_HEADER_SIZE] = {0};
2958
  STR_TO_VARSTR(stableName, (*smrSuperTable).me.name);
2959 2960 2961

  int32_t numOfRows = *pNumOfRows;

2962
  int32_t numOfTags = (*smrSuperTable).me.stbEntry.schemaTag.nCols;
2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979
  for (int32_t i = 0; i < numOfTags; ++i) {
    SColumnInfoData* pColInfoData = NULL;

    // table name
    pColInfoData = taosArrayGet(dataBlock->pDataBlock, 0);
    colDataAppend(pColInfoData, numOfRows, tableName, false);

    // database name
    pColInfoData = taosArrayGet(dataBlock->pDataBlock, 1);
    colDataAppend(pColInfoData, numOfRows, dbname, false);

    // super table name
    pColInfoData = taosArrayGet(dataBlock->pDataBlock, 2);
    colDataAppend(pColInfoData, numOfRows, stableName, false);

    // tag name
    char tagName[TSDB_COL_NAME_LEN + VARSTR_HEADER_SIZE] = {0};
2980
    STR_TO_VARSTR(tagName, (*smrSuperTable).me.stbEntry.schemaTag.pSchema[i].name);
2981 2982 2983 2984
    pColInfoData = taosArrayGet(dataBlock->pDataBlock, 3);
    colDataAppend(pColInfoData, numOfRows, tagName, false);

    // tag type
2985
    int8_t tagType = (*smrSuperTable).me.stbEntry.schemaTag.pSchema[i].type;
2986 2987 2988 2989 2990
    pColInfoData = taosArrayGet(dataBlock->pDataBlock, 4);
    char tagTypeStr[VARSTR_HEADER_SIZE + 32];
    int  tagTypeLen = sprintf(varDataVal(tagTypeStr), "%s", tDataTypes[tagType].name);
    if (tagType == TSDB_DATA_TYPE_VARCHAR) {
      tagTypeLen += sprintf(varDataVal(tagTypeStr) + tagTypeLen, "(%d)",
2991
                            (int32_t)((*smrSuperTable).me.stbEntry.schemaTag.pSchema[i].bytes - VARSTR_HEADER_SIZE));
2992
    } else if (tagType == TSDB_DATA_TYPE_NCHAR) {
2993 2994 2995
      tagTypeLen += sprintf(
          varDataVal(tagTypeStr) + tagTypeLen, "(%d)",
          (int32_t)(((*smrSuperTable).me.stbEntry.schemaTag.pSchema[i].bytes - VARSTR_HEADER_SIZE) / TSDB_NCHAR_SIZE));
2996 2997 2998 2999 3000
    }
    varDataSetLen(tagTypeStr, tagTypeLen);
    colDataAppend(pColInfoData, numOfRows, (char*)tagTypeStr, false);

    STagVal tagVal = {0};
3001
    tagVal.cid = (*smrSuperTable).me.stbEntry.schemaTag.pSchema[i].colId;
3002 3003 3004 3005
    char*    tagData = NULL;
    uint32_t tagLen = 0;

    if (tagType == TSDB_DATA_TYPE_JSON) {
3006
      tagData = (char*)smrChildTable->me.ctbEntry.pTags;
3007
    } else {
3008
      bool exist = tTagGet((STag*)smrChildTable->me.ctbEntry.pTags, &tagVal);
3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048
      if (exist) {
        if (IS_VAR_DATA_TYPE(tagType)) {
          tagData = (char*)tagVal.pData;
          tagLen = tagVal.nData;
        } else {
          tagData = (char*)&tagVal.i64;
          tagLen = tDataTypes[tagType].bytes;
        }
      }
    }

    char* tagVarChar = NULL;
    if (tagData != NULL) {
      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;
        convertTagDataToStr(varDataVal(tagVarChar), tagType, tagData, tagLen, &len);
        varDataSetLen(tagVarChar, len);
      }
    }
    pColInfoData = taosArrayGet(dataBlock->pDataBlock, 5);
    colDataAppend(pColInfoData, numOfRows, tagVarChar,
                  (tagData == NULL) || (tagType == TSDB_DATA_TYPE_JSON && tTagIsJsonNull(tagData)));
    taosMemoryFree(tagVarChar);
    ++numOfRows;
  }

  *pNumOfRows = numOfRows;

  return TSDB_CODE_SUCCESS;
}

dengyihao's avatar
dengyihao 已提交
3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074
typedef int (*__optSysFilter)(void* a, void* b, int16_t dtype);

int optSysDoCompare(__compar_fn_t func, int8_t comparType, void* a, void* b) {
  int32_t cmp = func(a, b);
  switch (comparType) {
    case OP_TYPE_LOWER_THAN:
      if (cmp < 0) return 0;
      break;
    case OP_TYPE_LOWER_EQUAL: {
      if (cmp <= 0) return 0;
      break;
    }
    case OP_TYPE_GREATER_THAN: {
      if (cmp > 0) return 0;
      break;
    }
    case OP_TYPE_GREATER_EQUAL: {
      if (cmp >= 0) return 0;
      break;
    }
    case OP_TYPE_EQUAL: {
      if (cmp == 0) return 0;
      break;
    }
    default:
      return -1;
3075
  }
dengyihao's avatar
dengyihao 已提交
3076
  return cmp;
dengyihao's avatar
dengyihao 已提交
3077
}
H
Haojun Liao 已提交
3078

dengyihao's avatar
dengyihao 已提交
3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098
static int optSysFilterFuncImpl__LowerThan(void* a, void* b, int16_t dtype) {
  __compar_fn_t func = getComparFunc(dtype, 0);
  return optSysDoCompare(func, OP_TYPE_LOWER_THAN, a, b);
}
static int optSysFilterFuncImpl__LowerEqual(void* a, void* b, int16_t dtype) {
  __compar_fn_t func = getComparFunc(dtype, 0);
  return optSysDoCompare(func, OP_TYPE_LOWER_EQUAL, a, b);
}
static int optSysFilterFuncImpl__GreaterThan(void* a, void* b, int16_t dtype) {
  __compar_fn_t func = getComparFunc(dtype, 0);
  return optSysDoCompare(func, OP_TYPE_GREATER_THAN, a, b);
}
static int optSysFilterFuncImpl__GreaterEqual(void* a, void* b, int16_t dtype) {
  __compar_fn_t func = getComparFunc(dtype, 0);
  return optSysDoCompare(func, OP_TYPE_GREATER_EQUAL, a, b);
}
static int optSysFilterFuncImpl__Equal(void* a, void* b, int16_t dtype) {
  __compar_fn_t func = getComparFunc(dtype, 0);
  return optSysDoCompare(func, OP_TYPE_EQUAL, a, b);
}
3099

dengyihao's avatar
dengyihao 已提交
3100 3101 3102 3103
static int optSysFilterFuncImpl__NoEqual(void* a, void* b, int16_t dtype) {
  __compar_fn_t func = getComparFunc(dtype, 0);
  return optSysDoCompare(func, OP_TYPE_NOT_EQUAL, a, b);
}
dengyihao's avatar
dengyihao 已提交
3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117
static __optSysFilter optSysGetFilterFunc(int32_t ctype, bool* reverse) {
  if (ctype == OP_TYPE_LOWER_EQUAL || ctype == OP_TYPE_LOWER_THAN) {
    *reverse = true;
  }
  if (ctype == OP_TYPE_LOWER_THAN)
    return optSysFilterFuncImpl__LowerThan;
  else if (ctype == OP_TYPE_LOWER_EQUAL)
    return optSysFilterFuncImpl__LowerEqual;
  else if (ctype == OP_TYPE_GREATER_THAN)
    return optSysFilterFuncImpl__GreaterThan;
  else if (ctype == OP_TYPE_GREATER_EQUAL)
    return optSysFilterFuncImpl__GreaterEqual;
  else if (ctype == OP_TYPE_EQUAL)
    return optSysFilterFuncImpl__Equal;
dengyihao's avatar
dengyihao 已提交
3118 3119
  else if (ctype == OP_TYPE_NOT_EQUAL)
    return optSysFilterFuncImpl__NoEqual;
dengyihao's avatar
dengyihao 已提交
3120 3121
  return NULL;
}
dengyihao's avatar
dengyihao 已提交
3122 3123
static int32_t sysFilte__DbName(void* arg, SNode* pNode, SArray* result) {
  void* pVnode = ((SSTabFltArg*)arg)->pVnode;
3124

dengyihao's avatar
dengyihao 已提交
3125 3126
  const char* db = NULL;
  vnodeGetInfo(pVnode, &db, NULL);
dengyihao's avatar
dengyihao 已提交
3127

dengyihao's avatar
dengyihao 已提交
3128 3129 3130 3131 3132 3133
  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)));
dengyihao's avatar
dengyihao 已提交
3134

dengyihao's avatar
dengyihao 已提交
3135
  SOperatorNode* pOper = (SOperatorNode*)pNode;
dengyihao's avatar
dengyihao 已提交
3136
  SValueNode*    pVal = (SValueNode*)pOper->pRight;
dengyihao's avatar
dengyihao 已提交
3137

dengyihao's avatar
dengyihao 已提交
3138 3139
  bool           reverse = false;
  __optSysFilter func = optSysGetFilterFunc(pOper->opType, &reverse);
dengyihao's avatar
dengyihao 已提交
3140 3141 3142 3143 3144
  if (func == NULL) return -1;

  int ret = func(dbname, pVal->datum.p, TSDB_DATA_TYPE_VARCHAR);
  if (ret == 0) return 0;

dengyihao's avatar
dengyihao 已提交
3145
  return -2;
dengyihao's avatar
dengyihao 已提交
3146
}
dengyihao's avatar
dengyihao 已提交
3147 3148
static int32_t sysFilte__VgroupId(void* arg, SNode* pNode, SArray* result) {
  void* pVnode = ((SSTabFltArg*)arg)->pVnode;
dengyihao's avatar
dengyihao 已提交
3149

dengyihao's avatar
dengyihao 已提交
3150 3151
  int64_t vgId = 0;
  vnodeGetInfo(pVnode, NULL, (int32_t*)&vgId);
dengyihao's avatar
dengyihao 已提交
3152

dengyihao's avatar
dengyihao 已提交
3153
  SOperatorNode* pOper = (SOperatorNode*)pNode;
dengyihao's avatar
dengyihao 已提交
3154 3155
  SValueNode*    pVal = (SValueNode*)pOper->pRight;

dengyihao's avatar
dengyihao 已提交
3156 3157 3158
  bool reverse = false;

  __optSysFilter func = optSysGetFilterFunc(pOper->opType, &reverse);
dengyihao's avatar
dengyihao 已提交
3159 3160 3161 3162
  if (func == NULL) return -1;

  int ret = func(&vgId, &pVal->datum.i, TSDB_DATA_TYPE_BIGINT);
  if (ret == 0) return 0;
dengyihao's avatar
dengyihao 已提交
3163

dengyihao's avatar
dengyihao 已提交
3164
  return -1;
dengyihao's avatar
dengyihao 已提交
3165
}
dengyihao's avatar
dengyihao 已提交
3166 3167
static int32_t sysFilte__TableName(void* arg, SNode* pNode, SArray* result) {
  void* pMeta = ((SSTabFltArg*)arg)->pMeta;
dengyihao's avatar
dengyihao 已提交
3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181

  SOperatorNode* pOper = (SOperatorNode*)pNode;
  SValueNode*    pVal = (SValueNode*)pOper->pRight;
  bool           reverse = false;

  __optSysFilter func = optSysGetFilterFunc(pOper->opType, &reverse);
  if (func == NULL) return -1;

  SMetaFltParam param = {.suid = 0,
                         .cid = 0,
                         .type = TSDB_DATA_TYPE_VARCHAR,
                         .val = pVal->datum.p,
                         .reverse = reverse,
                         .filterFunc = func};
dengyihao's avatar
dengyihao 已提交
3182
  return -1;
dengyihao's avatar
dengyihao 已提交
3183 3184
}

dengyihao's avatar
dengyihao 已提交
3185 3186
static int32_t sysFilte__CreateTime(void* arg, SNode* pNode, SArray* result) {
  void* pMeta = ((SSTabFltArg*)arg)->pMeta;
dengyihao's avatar
dengyihao 已提交
3187 3188 3189 3190 3191 3192 3193

  SOperatorNode* pOper = (SOperatorNode*)pNode;
  SValueNode*    pVal = (SValueNode*)pOper->pRight;
  bool           reverse = false;

  __optSysFilter func = optSysGetFilterFunc(pOper->opType, &reverse);
  if (func == NULL) return -1;
dengyihao's avatar
dengyihao 已提交
3194 3195 3196 3197 3198 3199 3200 3201 3202 3203

  SMetaFltParam param = {.suid = 0,
                         .cid = 0,
                         .type = TSDB_DATA_TYPE_BIGINT,
                         .val = &pVal->datum.i,
                         .reverse = reverse,
                         .filterFunc = func};

  int32_t ret = metaFilterCreateTime(pMeta, &param, result);
  return ret;
dengyihao's avatar
dengyihao 已提交
3204
}
dengyihao's avatar
dengyihao 已提交
3205 3206
static int32_t sysFilte__Ncolumn(void* arg, SNode* pNode, SArray* result) {
  void* pMeta = ((SSTabFltArg*)arg)->pMeta;
dengyihao's avatar
dengyihao 已提交
3207 3208 3209 3210 3211 3212

  SOperatorNode* pOper = (SOperatorNode*)pNode;
  SValueNode*    pVal = (SValueNode*)pOper->pRight;
  bool           reverse = false;

  __optSysFilter func = optSysGetFilterFunc(pOper->opType, &reverse);
dengyihao's avatar
dengyihao 已提交
3213 3214
  if (func == NULL) return -1;
  return -1;
dengyihao's avatar
dengyihao 已提交
3215 3216
}

dengyihao's avatar
dengyihao 已提交
3217 3218
static int32_t sysFilte__Ttl(void* arg, SNode* pNode, SArray* result) {
  void* pMeta = ((SSTabFltArg*)arg)->pMeta;
dengyihao's avatar
dengyihao 已提交
3219 3220 3221 3222 3223 3224

  SOperatorNode* pOper = (SOperatorNode*)pNode;
  SValueNode*    pVal = (SValueNode*)pOper->pRight;
  bool           reverse = false;

  __optSysFilter func = optSysGetFilterFunc(pOper->opType, &reverse);
dengyihao's avatar
dengyihao 已提交
3225 3226
  if (func == NULL) return -1;
  return -1;
dengyihao's avatar
dengyihao 已提交
3227
}
dengyihao's avatar
dengyihao 已提交
3228 3229
static int32_t sysFilte__STableName(void* arg, SNode* pNode, SArray* result) {
  void* pMeta = ((SSTabFltArg*)arg)->pMeta;
dengyihao's avatar
dengyihao 已提交
3230 3231 3232 3233 3234 3235

  SOperatorNode* pOper = (SOperatorNode*)pNode;
  SValueNode*    pVal = (SValueNode*)pOper->pRight;
  bool           reverse = false;

  __optSysFilter func = optSysGetFilterFunc(pOper->opType, &reverse);
dengyihao's avatar
dengyihao 已提交
3236 3237
  if (func == NULL) return -1;
  return -1;
dengyihao's avatar
dengyihao 已提交
3238
}
dengyihao's avatar
dengyihao 已提交
3239 3240
static int32_t sysFilte__Uid(void* arg, SNode* pNode, SArray* result) {
  void* pMeta = ((SSTabFltArg*)arg)->pMeta;
dengyihao's avatar
dengyihao 已提交
3241 3242 3243 3244 3245 3246

  SOperatorNode* pOper = (SOperatorNode*)pNode;
  SValueNode*    pVal = (SValueNode*)pOper->pRight;
  bool           reverse = false;

  __optSysFilter func = optSysGetFilterFunc(pOper->opType, &reverse);
dengyihao's avatar
dengyihao 已提交
3247 3248
  if (func == NULL) return -1;
  return -1;
dengyihao's avatar
dengyihao 已提交
3249
}
dengyihao's avatar
dengyihao 已提交
3250 3251
static int32_t sysFilte__Type(void* arg, SNode* pNode, SArray* result) {
  void* pMeta = ((SSTabFltArg*)arg)->pMeta;
dengyihao's avatar
dengyihao 已提交
3252 3253 3254 3255 3256 3257

  SOperatorNode* pOper = (SOperatorNode*)pNode;
  SValueNode*    pVal = (SValueNode*)pOper->pRight;
  bool           reverse = false;

  __optSysFilter func = optSysGetFilterFunc(pOper->opType, &reverse);
dengyihao's avatar
dengyihao 已提交
3258
  if (func == NULL) return -1;
dengyihao's avatar
dengyihao 已提交
3259
  return -1;
dengyihao's avatar
dengyihao 已提交
3260
}
dengyihao's avatar
dengyihao 已提交
3261 3262 3263 3264 3265
static int32_t sysChkFilter__Comm(SNode* pNode) {
  // impl
  SOperatorNode* pOper = (SOperatorNode*)pNode;
  EOperatorType  opType = pOper->opType;
  if (opType != OP_TYPE_EQUAL && opType != OP_TYPE_LOWER_EQUAL && opType != OP_TYPE_LOWER_THAN &&
dengyihao's avatar
dengyihao 已提交
3266
      opType != OP_TYPE_GREATER_EQUAL && opType != OP_TYPE_GREATER_THAN) {
dengyihao's avatar
dengyihao 已提交
3267
    return -1;
dengyihao's avatar
dengyihao 已提交
3268 3269 3270 3271
  }
  return 0;
}

dengyihao's avatar
dengyihao 已提交
3272 3273
static int32_t sysChkFilter__DBName(SNode* pNode) {
  SOperatorNode* pOper = (SOperatorNode*)pNode;
dengyihao's avatar
dengyihao 已提交
3274 3275 3276 3277 3278 3279

  if (pOper->opType != OP_TYPE_EQUAL && pOper->opType != OP_TYPE_NOT_EQUAL) {
    return -1;
  }

  SValueNode* pVal = (SValueNode*)pOper->pRight;
dengyihao's avatar
dengyihao 已提交
3280
  if (!IS_STR_DATA_TYPE(pVal->node.resType.type)) {
dengyihao's avatar
dengyihao 已提交
3281 3282
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
3283

dengyihao's avatar
dengyihao 已提交
3284 3285 3286 3287 3288
  return 0;
}
static int32_t sysChkFilter__VgroupId(SNode* pNode) {
  SOperatorNode* pOper = (SOperatorNode*)pNode;
  SValueNode*    pVal = (SValueNode*)pOper->pRight;
dengyihao's avatar
dengyihao 已提交
3289
  if (!IS_INTEGER_TYPE(pVal->node.resType.type)) {
dengyihao's avatar
dengyihao 已提交
3290 3291
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
3292
  return sysChkFilter__Comm(pNode);
dengyihao's avatar
dengyihao 已提交
3293 3294 3295 3296
}
static int32_t sysChkFilter__TableName(SNode* pNode) {
  SOperatorNode* pOper = (SOperatorNode*)pNode;
  SValueNode*    pVal = (SValueNode*)pOper->pRight;
dengyihao's avatar
dengyihao 已提交
3297
  if (!IS_STR_DATA_TYPE(pVal->node.resType.type)) {
dengyihao's avatar
dengyihao 已提交
3298 3299
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
3300
  return sysChkFilter__Comm(pNode);
dengyihao's avatar
dengyihao 已提交
3301 3302 3303 3304 3305
}
static int32_t sysChkFilter__CreateTime(SNode* pNode) {
  SOperatorNode* pOper = (SOperatorNode*)pNode;
  SValueNode*    pVal = (SValueNode*)pOper->pRight;

dengyihao's avatar
dengyihao 已提交
3306
  if (!IS_TIMESTAMP_TYPE(pVal->node.resType.type)) {
dengyihao's avatar
dengyihao 已提交
3307 3308
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
3309
  return sysChkFilter__Comm(pNode);
dengyihao's avatar
dengyihao 已提交
3310 3311 3312 3313 3314 3315
}

static int32_t sysChkFilter__Ncolumn(SNode* pNode) {
  SOperatorNode* pOper = (SOperatorNode*)pNode;
  SValueNode*    pVal = (SValueNode*)pOper->pRight;

dengyihao's avatar
dengyihao 已提交
3316
  if (!IS_INTEGER_TYPE(pVal->node.resType.type)) {
dengyihao's avatar
dengyihao 已提交
3317 3318
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
3319
  return sysChkFilter__Comm(pNode);
dengyihao's avatar
dengyihao 已提交
3320 3321 3322 3323 3324
}
static int32_t sysChkFilter__Ttl(SNode* pNode) {
  SOperatorNode* pOper = (SOperatorNode*)pNode;
  SValueNode*    pVal = (SValueNode*)pOper->pRight;

dengyihao's avatar
dengyihao 已提交
3325
  if (!IS_INTEGER_TYPE(pVal->node.resType.type)) {
dengyihao's avatar
dengyihao 已提交
3326 3327
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
3328
  return sysChkFilter__Comm(pNode);
dengyihao's avatar
dengyihao 已提交
3329 3330 3331 3332
}
static int32_t sysChkFilter__STableName(SNode* pNode) {
  SOperatorNode* pOper = (SOperatorNode*)pNode;
  SValueNode*    pVal = (SValueNode*)pOper->pRight;
dengyihao's avatar
dengyihao 已提交
3333
  if (!IS_STR_DATA_TYPE(pVal->node.resType.type)) {
dengyihao's avatar
dengyihao 已提交
3334 3335
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
3336
  return sysChkFilter__Comm(pNode);
dengyihao's avatar
dengyihao 已提交
3337 3338 3339 3340
}
static int32_t sysChkFilter__Uid(SNode* pNode) {
  SOperatorNode* pOper = (SOperatorNode*)pNode;
  SValueNode*    pVal = (SValueNode*)pOper->pRight;
dengyihao's avatar
dengyihao 已提交
3341
  if (!IS_INTEGER_TYPE(pVal->node.resType.type)) {
dengyihao's avatar
dengyihao 已提交
3342 3343
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
3344
  return sysChkFilter__Comm(pNode);
dengyihao's avatar
dengyihao 已提交
3345 3346 3347 3348
}
static int32_t sysChkFilter__Type(SNode* pNode) {
  SOperatorNode* pOper = (SOperatorNode*)pNode;
  SValueNode*    pVal = (SValueNode*)pOper->pRight;
dengyihao's avatar
dengyihao 已提交
3349
  if (!IS_INTEGER_TYPE(pVal->node.resType.type)) {
dengyihao's avatar
dengyihao 已提交
3350 3351
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
3352
  return sysChkFilter__Comm(pNode);
dengyihao's avatar
dengyihao 已提交
3353
}
dengyihao's avatar
dengyihao 已提交
3354
static int32_t optSysTabFilteImpl(void* arg, SNode* cond, SArray* result) {
dengyihao's avatar
dengyihao 已提交
3355
  if (optSysCheckOper(cond) != 0) return -1;
dengyihao's avatar
dengyihao 已提交
3356 3357 3358

  SOperatorNode* pNode = (SOperatorNode*)cond;

dengyihao's avatar
dengyihao 已提交
3359 3360
  int8_t i = 0;
  for (; i < SYSTAB_FILTER_DICT_SIZE; i++) {
dengyihao's avatar
dengyihao 已提交
3361 3362
    if (strcmp(filterDict[i].name, ((SColumnNode*)(pNode->pLeft))->colName) == 0) {
      break;
3363
    }
dengyihao's avatar
dengyihao 已提交
3364 3365
  }
  if (i >= SYSTAB_FILTER_DICT_SIZE) return -1;
3366

dengyihao's avatar
dengyihao 已提交
3367
  if (filterDict[i].chkFunc(cond) != 0) return -1;
3368

dengyihao's avatar
dengyihao 已提交
3369 3370
  return filterDict[i].fltFunc(arg, cond, result);
}
3371

dengyihao's avatar
dengyihao 已提交
3372 3373
static int32_t optSysCheckOper(SNode* pOpear) {
  if (nodeType(pOpear) != QUERY_NODE_OPERATOR) return -1;
3374

dengyihao's avatar
dengyihao 已提交
3375
  SOperatorNode* pOper = (SOperatorNode*)pOpear;
dengyihao's avatar
dengyihao 已提交
3376 3377 3378
  if (pOper->opType < OP_TYPE_GREATER_THAN || pOper->opType > OP_TYPE_NOT_EQUAL) {
    return -1;
  }
3379

dengyihao's avatar
dengyihao 已提交
3380 3381 3382 3383
  if (nodeType(pOper->pLeft) != QUERY_NODE_COLUMN || nodeType(pOper->pRight) != QUERY_NODE_VALUE) {
    return -1;
  }
  return 0;
dengyihao's avatar
dengyihao 已提交
3384
}
3385

dengyihao's avatar
dengyihao 已提交
3386 3387 3388 3389 3390 3391 3392 3393
static int tableUidCompare(const void* a, const void* b) {
  int64_t u1 = *(int64_t*)a;
  int64_t u2 = *(int64_t*)b;
  if (u1 == u2) {
    return 0;
  }
  return u1 < u2 ? -1 : 1;
}
dengyihao's avatar
opt mem  
dengyihao 已提交
3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448

typedef struct MergeIndex {
  int idx;
  int len;
} MergeIndex;

static FORCE_INLINE int optSysBinarySearch(SArray* arr, int s, int e, uint64_t k) {
  uint64_t v;
  int32_t  m;
  while (s <= e) {
    m = s + (e - s) / 2;
    v = *(uint64_t*)taosArrayGet(arr, m);
    if (v >= k) {
      e = m - 1;
    } else {
      s = m + 1;
    }
  }
  return s;
}

void optSysIntersection(SArray* in, SArray* out) {
  int32_t sz = (int32_t)taosArrayGetSize(in);
  if (sz <= 0) {
    return;
  }
  MergeIndex* mi = taosMemoryCalloc(sz, sizeof(MergeIndex));
  for (int i = 0; i < sz; i++) {
    SArray* t = taosArrayGetP(in, i);
    mi[i].len = (int32_t)taosArrayGetSize(t);
    mi[i].idx = 0;
  }

  SArray* base = taosArrayGetP(in, 0);
  for (int i = 0; i < taosArrayGetSize(base); i++) {
    uint64_t tgt = *(uint64_t*)taosArrayGet(base, i);
    bool     has = true;
    for (int j = 1; j < taosArrayGetSize(in); j++) {
      SArray* oth = taosArrayGetP(in, j);
      int     mid = optSysBinarySearch(oth, mi[j].idx, mi[j].len - 1, tgt);
      if (mid >= 0 && mid < mi[j].len) {
        uint64_t val = *(uint64_t*)taosArrayGet(oth, mid);
        has = (val == tgt ? true : false);
        mi[j].idx = mid;
      } else {
        has = false;
      }
    }
    if (has == true) {
      taosArrayPush(out, &tgt);
    }
  }
  taosMemoryFreeClear(mi);
}

dengyihao's avatar
dengyihao 已提交
3449 3450 3451
static int32_t optSysMergeRslt(SArray* mRslt, SArray* rslt) {
  // TODO, find comm mem from mRslt
  for (int i = 0; i < taosArrayGetSize(mRslt); i++) {
dengyihao's avatar
opt mem  
dengyihao 已提交
3452 3453 3454 3455 3456 3457
    SArray* arslt = taosArrayGetP(mRslt, i);
    taosArraySort(arslt, tableUidCompare);
  }
  optSysIntersection(mRslt, rslt);
  return 0;
}
3458

dengyihao's avatar
opt mem  
dengyihao 已提交
3459 3460 3461 3462 3463 3464 3465
static int32_t optSysSpecialColumn(SNode* cond) {
  SOperatorNode* pOper = (SOperatorNode*)cond;
  SColumnNode*   pCol = (SColumnNode*)pOper->pLeft;
  for (int i = 0; i < sizeof(SYSTABLE_SPECIAL_COL) / sizeof(SYSTABLE_SPECIAL_COL[0]); i++) {
    if (0 == strcmp(pCol->colName, SYSTABLE_SPECIAL_COL[i])) {
      return 1;
    }
dengyihao's avatar
dengyihao 已提交
3466 3467 3468
  }
  return 0;
}
3469

dengyihao's avatar
dengyihao 已提交
3470 3471 3472 3473
static int32_t optSysTabFilte(void* arg, SNode* cond, SArray* result) {
  int ret = -1;
  if (nodeType(cond) == QUERY_NODE_OPERATOR) {
    ret = optSysTabFilteImpl(arg, cond, result);
dengyihao's avatar
dengyihao 已提交
3474 3475 3476
    if (ret == 0) {
      SOperatorNode* pOper = (SOperatorNode*)cond;
      SColumnNode*   pCol = (SColumnNode*)pOper->pLeft;
dengyihao's avatar
dengyihao 已提交
3477
      if (0 == strcmp(pCol->colName, "create_time")) {
dengyihao's avatar
dengyihao 已提交
3478 3479 3480 3481
        return 0;
      }
      return -1;
    }
dengyihao's avatar
dengyihao 已提交
3482 3483
    return ret;
  }
3484

dengyihao's avatar
dengyihao 已提交
3485 3486 3487
  if (nodeType(cond) != QUERY_NODE_LOGIC_CONDITION || ((SLogicConditionNode*)cond)->condType != LOGIC_COND_TYPE_AND) {
    return ret;
  }
3488

dengyihao's avatar
dengyihao 已提交
3489 3490
  SLogicConditionNode* pNode = (SLogicConditionNode*)cond;
  SNodeList*           pList = (SNodeList*)pNode->pParameterList;
3491

dengyihao's avatar
dengyihao 已提交
3492
  int32_t len = LIST_LENGTH(pList);
3493

dengyihao's avatar
dengyihao 已提交
3494
  bool    hasIdx = false;
dengyihao's avatar
dengyihao 已提交
3495
  bool    hasRslt = true;
dengyihao's avatar
dengyihao 已提交
3496
  SArray* mRslt = taosArrayInit(len, POINTER_BYTES);
3497

dengyihao's avatar
dengyihao 已提交
3498 3499 3500
  SListCell* cell = pList->pHead;
  for (int i = 0; i < len; i++) {
    if (cell == NULL) break;
3501

dengyihao's avatar
dengyihao 已提交
3502
    SArray* aRslt = taosArrayInit(16, sizeof(int64_t));
3503

dengyihao's avatar
dengyihao 已提交
3504 3505
    ret = optSysTabFilteImpl(arg, cell->pNode, aRslt);
    if (ret == 0) {
dengyihao's avatar
dengyihao 已提交
3506
      // has index
dengyihao's avatar
dengyihao 已提交
3507
      hasIdx = true;
dengyihao's avatar
opt mem  
dengyihao 已提交
3508 3509 3510 3511 3512 3513
      if (optSysSpecialColumn(cell->pNode) == 0) {
        taosArrayPush(mRslt, &aRslt);
      } else {
        // db_name/vgroup not result
        taosArrayDestroy(aRslt);
      }
dengyihao's avatar
dengyihao 已提交
3514
    } else if (ret == -2) {
dengyihao's avatar
dengyihao 已提交
3515
      // current vg
dengyihao's avatar
dengyihao 已提交
3516 3517 3518 3519 3520 3521
      hasIdx = true;
      hasRslt = false;
      taosArrayDestroy(aRslt);
      break;
    } else {
      taosArrayDestroy(aRslt);
dengyihao's avatar
dengyihao 已提交
3522 3523 3524
    }
    cell = cell->pNext;
  }
dengyihao's avatar
dengyihao 已提交
3525 3526 3527
  if (hasRslt && hasIdx) {
    optSysMergeRslt(mRslt, result);
  }
3528

dengyihao's avatar
dengyihao 已提交
3529 3530 3531
  for (int i = 0; i < taosArrayGetSize(mRslt); i++) {
    SArray* aRslt = taosArrayGetP(mRslt, i);
    taosArrayDestroy(aRslt);
dengyihao's avatar
dengyihao 已提交
3532
  }
dengyihao's avatar
dengyihao 已提交
3533
  taosArrayDestroy(mRslt);
dengyihao's avatar
dengyihao 已提交
3534 3535 3536 3537
  if (hasRslt == false) {
    return -2;
  }
  if (hasRslt && hasIdx) {
dengyihao's avatar
dengyihao 已提交
3538 3539 3540 3541 3542
    cell = pList->pHead;
    for (int i = 0; i < len; i++) {
      if (cell == NULL) break;
      SOperatorNode* pOper = (SOperatorNode*)cell->pNode;
      SColumnNode*   pCol = (SColumnNode*)pOper->pLeft;
dengyihao's avatar
dengyihao 已提交
3543
      if (0 == strcmp(pCol->colName, "create_time")) {
dengyihao's avatar
dengyihao 已提交
3544 3545 3546 3547 3548
        return 0;
      }
      cell = cell->pNext;
    }
    return -1;
dengyihao's avatar
dengyihao 已提交
3549 3550
  }
  return -1;
dengyihao's avatar
dengyihao 已提交
3551
}
3552

dengyihao's avatar
dengyihao 已提交
3553
static SSDataBlock* sysTableBuildUserTablesByUids(SOperatorInfo* pOperator) {
dengyihao's avatar
dengyihao 已提交
3554 3555
  SExecTaskInfo*     pTaskInfo = pOperator->pTaskInfo;
  SSysTableScanInfo* pInfo = pOperator->info;
3556

dengyihao's avatar
dengyihao 已提交
3557
  SSysTableIndex* pIdx = pInfo->pIdx;
dengyihao's avatar
dengyihao 已提交
3558 3559
  blockDataCleanup(pInfo->pRes);
  int32_t numOfRows = 0;
3560

dengyihao's avatar
dengyihao 已提交
3561
  int ret = 0;
3562

dengyihao's avatar
dengyihao 已提交
3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576
  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)));

  SSDataBlock* p = buildInfoSchemaTableMetaBlock(TSDB_INS_TABLE_TABLES);
  blockDataEnsureCapacity(p, pOperator->resultInfo.capacity);

dengyihao's avatar
dengyihao 已提交
3577 3578 3579 3580
  char    n[TSDB_TABLE_NAME_LEN + VARSTR_HEADER_SIZE] = {0};
  int32_t i = pIdx->lastIdx;
  for (; i < taosArrayGetSize(pIdx->uids); i++) {
    tb_uid_t* uid = taosArrayGet(pIdx->uids, i);
3581

dengyihao's avatar
dengyihao 已提交
3582
    SMetaReader mr = {0};
dengyihao's avatar
dengyihao 已提交
3583
    metaReaderInit(&mr, pInfo->readHandle.meta, 0);
H
Haojun Liao 已提交
3584
    ret = metaGetTableEntryByUid(&mr, *uid);
dengyihao's avatar
dengyihao 已提交
3585 3586 3587 3588 3589 3590 3591 3592 3593
    if (ret < 0) {
      metaReaderClear(&mr);
      continue;
    }
    STR_TO_VARSTR(n, mr.me.name);

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

dengyihao's avatar
dengyihao 已提交
3595 3596 3597
    // database name
    pColInfoData = taosArrayGet(p->pDataBlock, 1);
    colDataAppend(pColInfoData, numOfRows, dbname, false);
3598

dengyihao's avatar
dengyihao 已提交
3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612
    // vgId
    pColInfoData = taosArrayGet(p->pDataBlock, 6);
    colDataAppend(pColInfoData, numOfRows, (char*)&vgId, false);

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

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

dengyihao's avatar
dengyihao 已提交
3613 3614
      int64_t suid = mr.me.ctbEntry.suid;
      int32_t code = metaGetTableEntryByUid(&mr1, suid);
dengyihao's avatar
dengyihao 已提交
3615 3616 3617 3618
      if (code != TSDB_CODE_SUCCESS) {
        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));
        metaReaderClear(&mr1);
dengyihao's avatar
dengyihao 已提交
3619
        metaReaderClear(&mr);
dengyihao's avatar
dengyihao 已提交
3620
        T_LONG_JMP(pTaskInfo->env, terrno);
H
Haojun Liao 已提交
3621
      }
dengyihao's avatar
dengyihao 已提交
3622
      pColInfoData = taosArrayGet(p->pDataBlock, 3);
dengyihao's avatar
dengyihao 已提交
3623
      colDataAppend(pColInfoData, numOfRows, (char*)&mr1.me.stbEntry.schemaRow.nCols, false);
H
Haojun Liao 已提交
3624

dengyihao's avatar
dengyihao 已提交
3625 3626 3627
      // super table name
      STR_TO_VARSTR(n, mr1.me.name);
      pColInfoData = taosArrayGet(p->pDataBlock, 4);
3628
      colDataAppend(pColInfoData, numOfRows, n, false);
dengyihao's avatar
dengyihao 已提交
3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643
      metaReaderClear(&mr1);

      // table comment
      pColInfoData = taosArrayGet(p->pDataBlock, 8);
      if (mr.me.ctbEntry.commentLen > 0) {
        char comment[TSDB_TB_COMMENT_LEN + VARSTR_HEADER_SIZE] = {0};
        STR_TO_VARSTR(comment, mr.me.ctbEntry.comment);
        colDataAppend(pColInfoData, numOfRows, comment, false);
      } else if (mr.me.ctbEntry.commentLen == 0) {
        char comment[VARSTR_HEADER_SIZE + VARSTR_HEADER_SIZE] = {0};
        STR_TO_VARSTR(comment, "");
        colDataAppend(pColInfoData, numOfRows, comment, false);
      } else {
        colDataAppendNULL(pColInfoData, numOfRows);
      }
3644

dengyihao's avatar
dengyihao 已提交
3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669
      // uid
      pColInfoData = taosArrayGet(p->pDataBlock, 5);
      colDataAppend(pColInfoData, numOfRows, (char*)&mr.me.uid, false);

      // ttl
      pColInfoData = taosArrayGet(p->pDataBlock, 7);
      colDataAppend(pColInfoData, numOfRows, (char*)&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);

      // table comment
      pColInfoData = taosArrayGet(p->pDataBlock, 8);
dengyihao's avatar
dengyihao 已提交
3670
      if (mr.me.ntbEntry.commentLen > 0) {
dengyihao's avatar
dengyihao 已提交
3671
        char comment[TSDB_TB_COMMENT_LEN + VARSTR_HEADER_SIZE] = {0};
dengyihao's avatar
dengyihao 已提交
3672
        STR_TO_VARSTR(comment, mr.me.ntbEntry.comment);
dengyihao's avatar
dengyihao 已提交
3673
        colDataAppend(pColInfoData, numOfRows, comment, false);
dengyihao's avatar
dengyihao 已提交
3674
      } else if (mr.me.ntbEntry.commentLen == 0) {
dengyihao's avatar
dengyihao 已提交
3675 3676 3677 3678 3679 3680
        char comment[VARSTR_HEADER_SIZE + VARSTR_HEADER_SIZE] = {0};
        STR_TO_VARSTR(comment, "");
        colDataAppend(pColInfoData, numOfRows, comment, false);
      } else {
        colDataAppendNULL(pColInfoData, numOfRows);
      }
3681

dengyihao's avatar
dengyihao 已提交
3682 3683
      // uid
      pColInfoData = taosArrayGet(p->pDataBlock, 5);
dengyihao's avatar
dengyihao 已提交
3684
      colDataAppend(pColInfoData, numOfRows, (char*)&mr.me.uid, false);
3685

dengyihao's avatar
dengyihao 已提交
3686 3687
      // ttl
      pColInfoData = taosArrayGet(p->pDataBlock, 7);
dengyihao's avatar
dengyihao 已提交
3688
      colDataAppend(pColInfoData, numOfRows, (char*)&mr.me.ntbEntry.ttlDays, false);
3689

dengyihao's avatar
dengyihao 已提交
3690 3691
      STR_TO_VARSTR(n, "NORMAL_TABLE");
      // impl later
3692
    }
3693

dengyihao's avatar
dengyihao 已提交
3694 3695
    metaReaderClear(&mr);

dengyihao's avatar
dengyihao 已提交
3696 3697 3698 3699
    pColInfoData = taosArrayGet(p->pDataBlock, 9);
    colDataAppend(pColInfoData, numOfRows, n, false);

    if (++numOfRows >= pOperator->resultInfo.capacity) {
3700 3701 3702
      p->info.rows = numOfRows;
      pInfo->pRes->info.rows = numOfRows;

H
Haojun Liao 已提交
3703
      relocateColumnData(pInfo->pRes, pInfo->matchInfo.pList, p->pDataBlock, false);
H
Haojun Liao 已提交
3704
      doFilterResult(pInfo->pRes, pOperator->exprSupp.pFilterInfo);
3705 3706 3707

      blockDataCleanup(p);
      numOfRows = 0;
dengyihao's avatar
dengyihao 已提交
3708 3709 3710 3711

      if (pInfo->pRes->info.rows > 0) {
        break;
      }
3712
    }
dengyihao's avatar
dengyihao 已提交
3713
  }
3714

dengyihao's avatar
dengyihao 已提交
3715 3716 3717
  if (numOfRows > 0) {
    p->info.rows = numOfRows;
    pInfo->pRes->info.rows = numOfRows;
3718

H
Haojun Liao 已提交
3719
    relocateColumnData(pInfo->pRes, pInfo->matchInfo.pList, p->pDataBlock, false);
H
Haojun Liao 已提交
3720
    doFilterResult(pInfo->pRes, pOperator->exprSupp.pFilterInfo);
dengyihao's avatar
dengyihao 已提交
3721 3722 3723 3724 3725

    blockDataCleanup(p);
    numOfRows = 0;
  }

dengyihao's avatar
dengyihao 已提交
3726
  if (i >= taosArrayGetSize(pIdx->uids)) {
H
Haojun Liao 已提交
3727
    setOperatorCompleted(pOperator);
dengyihao's avatar
dengyihao 已提交
3728
  } else {
dengyihao's avatar
dengyihao 已提交
3729
    pIdx->lastIdx = i + 1;
dengyihao's avatar
dengyihao 已提交
3730
  }
dengyihao's avatar
dengyihao 已提交
3731

dengyihao's avatar
dengyihao 已提交
3732
  blockDataDestroy(p);
dengyihao's avatar
dengyihao 已提交
3733 3734 3735 3736

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

dengyihao's avatar
dengyihao 已提交
3738
static SSDataBlock* sysTableBuildUserTables(SOperatorInfo* pOperator) {
dengyihao's avatar
dengyihao 已提交
3739 3740
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;

H
Haojun Liao 已提交
3741
  SSysTableScanInfo* pInfo = pOperator->info;
dengyihao's avatar
dengyihao 已提交
3742 3743
  if (pInfo->pCur == NULL) {
    pInfo->pCur = metaOpenTbCursor(pInfo->readHandle.meta);
3744
  }
H
Haojun Liao 已提交
3745

dengyihao's avatar
dengyihao 已提交
3746 3747
  blockDataCleanup(pInfo->pRes);
  int32_t numOfRows = 0;
3748

dengyihao's avatar
dengyihao 已提交
3749 3750 3751
  const char* db = NULL;
  int32_t     vgId = 0;
  vnodeGetInfo(pInfo->readHandle.vnode, &db, &vgId);
3752

dengyihao's avatar
dengyihao 已提交
3753 3754 3755
  SName sn = {0};
  char  dbname[TSDB_DB_FNAME_LEN + VARSTR_HEADER_SIZE] = {0};
  tNameFromString(&sn, db, T_NAME_ACCT | T_NAME_DB);
3756

dengyihao's avatar
dengyihao 已提交
3757 3758
  tNameGetDbName(&sn, varDataVal(dbname));
  varDataSetLen(dbname, strlen(varDataVal(dbname)));
3759

dengyihao's avatar
dengyihao 已提交
3760 3761
  SSDataBlock* p = buildInfoSchemaTableMetaBlock(TSDB_INS_TABLE_TABLES);
  blockDataEnsureCapacity(p, pOperator->resultInfo.capacity);
3762

dengyihao's avatar
dengyihao 已提交
3763
  char n[TSDB_TABLE_NAME_LEN + VARSTR_HEADER_SIZE] = {0};
3764

dengyihao's avatar
dengyihao 已提交
3765 3766 3767
  int32_t ret = 0;
  while ((ret = metaTbCursorNext(pInfo->pCur)) == 0) {
    STR_TO_VARSTR(n, pInfo->pCur->mr.me.name);
3768

dengyihao's avatar
dengyihao 已提交
3769 3770 3771
    // table name
    SColumnInfoData* pColInfoData = taosArrayGet(p->pDataBlock, 0);
    colDataAppend(pColInfoData, numOfRows, n, false);
3772

dengyihao's avatar
dengyihao 已提交
3773 3774 3775
    // database name
    pColInfoData = taosArrayGet(p->pDataBlock, 1);
    colDataAppend(pColInfoData, numOfRows, dbname, false);
3776

dengyihao's avatar
dengyihao 已提交
3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795
    // 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, META_READER_NOLOCK);

      uint64_t suid = pInfo->pCur->mr.me.ctbEntry.suid;
      int32_t  code = metaGetTableEntryByUid(&mr, suid);
      if (code != TSDB_CODE_SUCCESS) {
        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));
3796
        metaReaderClear(&mr);
dengyihao's avatar
dengyihao 已提交
3797 3798 3799 3800
        metaCloseTbCursor(pInfo->pCur);
        pInfo->pCur = NULL;
        T_LONG_JMP(pTaskInfo->env, terrno);
      }
3801

dengyihao's avatar
dengyihao 已提交
3802 3803 3804
      // number of columns
      pColInfoData = taosArrayGet(p->pDataBlock, 3);
      colDataAppend(pColInfoData, numOfRows, (char*)&mr.me.stbEntry.schemaRow.nCols, false);
3805

dengyihao's avatar
dengyihao 已提交
3806 3807 3808 3809 3810
      // super table name
      STR_TO_VARSTR(n, mr.me.name);
      pColInfoData = taosArrayGet(p->pDataBlock, 4);
      colDataAppend(pColInfoData, numOfRows, n, false);
      metaReaderClear(&mr);
3811

dengyihao's avatar
dengyihao 已提交
3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822
      // 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 {
3823
        colDataAppendNULL(pColInfoData, numOfRows);
H
Haojun Liao 已提交
3824 3825
      }

dengyihao's avatar
dengyihao 已提交
3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860
      // 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);

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

dengyihao's avatar
dengyihao 已提交
3862 3863 3864
      // uid
      pColInfoData = taosArrayGet(p->pDataBlock, 5);
      colDataAppend(pColInfoData, numOfRows, (char*)&pInfo->pCur->mr.me.uid, false);
3865

dengyihao's avatar
dengyihao 已提交
3866 3867 3868
      // ttl
      pColInfoData = taosArrayGet(p->pDataBlock, 7);
      colDataAppend(pColInfoData, numOfRows, (char*)&pInfo->pCur->mr.me.ntbEntry.ttlDays, false);
3869

dengyihao's avatar
dengyihao 已提交
3870
      STR_TO_VARSTR(n, "NORMAL_TABLE");
3871
    }
H
Haojun Liao 已提交
3872

dengyihao's avatar
dengyihao 已提交
3873 3874 3875 3876
    pColInfoData = taosArrayGet(p->pDataBlock, 9);
    colDataAppend(pColInfoData, numOfRows, n, false);

    if (++numOfRows >= pOperator->resultInfo.capacity) {
3877 3878 3879
      p->info.rows = numOfRows;
      pInfo->pRes->info.rows = numOfRows;

H
Haojun Liao 已提交
3880
      relocateColumnData(pInfo->pRes, pInfo->matchInfo.pList, p->pDataBlock, false);
H
Haojun Liao 已提交
3881
      doFilterResult(pInfo->pRes, pOperator->exprSupp.pFilterInfo);
3882 3883 3884

      blockDataCleanup(p);
      numOfRows = 0;
dengyihao's avatar
dengyihao 已提交
3885 3886 3887 3888

      if (pInfo->pRes->info.rows > 0) {
        break;
      }
3889
    }
dengyihao's avatar
dengyihao 已提交
3890
  }
3891

dengyihao's avatar
dengyihao 已提交
3892 3893 3894
  if (numOfRows > 0) {
    p->info.rows = numOfRows;
    pInfo->pRes->info.rows = numOfRows;
3895

H
Haojun Liao 已提交
3896
    relocateColumnData(pInfo->pRes, pInfo->matchInfo.pList, p->pDataBlock, false);
H
Haojun Liao 已提交
3897
    doFilterResult(pInfo->pRes, pOperator->exprSupp.pFilterInfo);
H
Haojun Liao 已提交
3898

dengyihao's avatar
dengyihao 已提交
3899 3900 3901 3902 3903 3904 3905 3906 3907 3908
    blockDataCleanup(p);
    numOfRows = 0;
  }

  blockDataDestroy(p);

  // 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;
H
Haojun Liao 已提交
3909
    setOperatorCompleted(pOperator);
dengyihao's avatar
dengyihao 已提交
3910 3911 3912 3913 3914
  }

  pInfo->loadInfo.totalRows += pInfo->pRes->info.rows;
  return (pInfo->pRes->info.rows == 0) ? NULL : pInfo->pRes;
}
dengyihao's avatar
dengyihao 已提交
3915

dengyihao's avatar
dengyihao 已提交
3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927
static SSDataBlock* sysTableScanUserTables(SOperatorInfo* pOperator) {
  SExecTaskInfo*     pTaskInfo = pOperator->pTaskInfo;
  SSysTableScanInfo* pInfo = pOperator->info;

  SNode* pCondition = pInfo->pCondition;
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

  // 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);
H
Haojun Liao 已提交
3928
    doFilterResult(pInfo->pRes, pOperator->exprSupp.pFilterInfo);
3929
    pInfo->loadInfo.totalRows += pInfo->pRes->info.rows;
dengyihao's avatar
dengyihao 已提交
3930

H
Haojun Liao 已提交
3931
    setOperatorCompleted(pOperator);
3932
    return (pInfo->pRes->info.rows == 0) ? NULL : pInfo->pRes;
dengyihao's avatar
dengyihao 已提交
3933
  } else {
dengyihao's avatar
dengyihao 已提交
3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957
    if (pInfo->showRewrite == false) {
      if (pCondition != NULL && pInfo->pIdx == NULL) {
        SSTabFltArg arg = {.pMeta = pInfo->readHandle.meta, .pVnode = pInfo->readHandle.vnode};

        SSysTableIndex* idx = taosMemoryMalloc(sizeof(SSysTableIndex));
        idx->init = 0;
        idx->uids = taosArrayInit(128, sizeof(int64_t));
        idx->lastIdx = 0;

        pInfo->pIdx = idx;  // set idx arg

        int flt = optSysTabFilte(&arg, pCondition, idx->uids);
        if (flt == 0) {
          pInfo->pIdx->init = 1;
          SSDataBlock* blk = sysTableBuildUserTablesByUids(pOperator);
          return blk;
        } else if (flt == -2) {
          qDebug("%s failed to get sys table info by idx, empty result", GET_TASKID(pTaskInfo));
          return NULL;
        } else if (flt == -1) {
          // not idx
          qDebug("%s failed to get sys table info by idx, scan sys table one by one", GET_TASKID(pTaskInfo));
        }
      } else if (pCondition != NULL && (pInfo->pIdx != NULL && pInfo->pIdx->init == 1)) {
dengyihao's avatar
dengyihao 已提交
3958
        SSDataBlock* blk = sysTableBuildUserTablesByUids(pOperator);
dengyihao's avatar
dengyihao 已提交
3959 3960
        return blk;
      }
dengyihao's avatar
dengyihao 已提交
3961
    }
dengyihao's avatar
dengyihao 已提交
3962

dengyihao's avatar
dengyihao 已提交
3963
    return sysTableBuildUserTables(pOperator);
3964
  }
dengyihao's avatar
dengyihao 已提交
3965
  return NULL;
3966 3967
}

3968 3969 3970 3971 3972 3973 3974 3975
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 已提交
3976
  pOperator->status = OP_EXEC_DONE;
3977 3978 3979 3980 3981

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

3982 3983 3984 3985
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 已提交
3986
  char               dbName[TSDB_DB_NAME_LEN] = {0};
3987 3988

  const char* name = tNameGetTableName(&pInfo->name);
D
dapan1121 已提交
3989 3990 3991 3992
  if (pInfo->showRewrite) {
    getDBNameFromCondition(pInfo->pCondition, dbName);
    sprintf(pInfo->req.db, "%d.%s", pInfo->accountId, dbName);
  }
H
Hongze Cheng 已提交
3993

D
dapan1121 已提交
3994
  if (strncasecmp(name, TSDB_INS_TABLE_TABLES, TSDB_TABLE_FNAME_LEN) == 0) {
3995
    return sysTableScanUserTables(pOperator);
D
dapan1121 已提交
3996
  } else if (strncasecmp(name, TSDB_INS_TABLE_TAGS, TSDB_TABLE_FNAME_LEN) == 0) {
3997
    return sysTableScanUserTags(pOperator);
L
Liu Jicong 已提交
3998 3999
  } else if (strncasecmp(name, TSDB_INS_TABLE_STABLES, TSDB_TABLE_FNAME_LEN) == 0 && pInfo->showRewrite &&
             IS_SYS_DBNAME(dbName)) {
4000
    return sysTableScanUserSTables(pOperator);
H
Haojun Liao 已提交
4001 4002 4003 4004 4005
  } else {  // load the meta from mnode of the given epset
    if (pOperator->status == OP_EXEC_DONE) {
      return NULL;
    }

4006 4007
    while (1) {
      int64_t startTs = taosGetTimestampUs();
H
Haojun Liao 已提交
4008
      tstrncpy(pInfo->req.tb, tNameGetTableName(&pInfo->name), tListLen(pInfo->req.tb));
H
Haojun Liao 已提交
4009
      tstrncpy(pInfo->req.user, pInfo->pUser, tListLen(pInfo->req.user));
H
Haojun Liao 已提交
4010

4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021
      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 已提交
4022

L
Liu Jicong 已提交
4023 4024
      int32_t msgType = (strcasecmp(name, TSDB_INS_TABLE_DNODE_VARIABLES) == 0) ? TDMT_DND_SYSTABLE_RETRIEVE
                                                                                : TDMT_MND_SYSTABLE_RETRIEVE;
D
dapan1121 已提交
4025

4026 4027 4028
      pMsgSendInfo->param = pOperator;
      pMsgSendInfo->msgInfo.pData = buf1;
      pMsgSendInfo->msgInfo.len = contLen;
D
dapan1121 已提交
4029
      pMsgSendInfo->msgType = msgType;
4030
      pMsgSendInfo->fp = loadSysTableCallback;
D
dapan1121 已提交
4031
      pMsgSendInfo->requestId = pTaskInfo->id.queryId;
H
Haojun Liao 已提交
4032

4033
      int64_t transporterId = 0;
4034 4035
      int32_t code =
          asyncSendMsgToServer(pInfo->readHandle.pMsgCb->clientRpc, &pInfo->epSet, &transporterId, pMsgSendInfo);
4036
      tsem_wait(&pInfo->ready);
H
Haojun Liao 已提交
4037

4038 4039 4040 4041 4042
      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 已提交
4043

4044 4045
      SRetrieveMetaTableRsp* pRsp = pInfo->pRsp;
      pInfo->req.showId = pRsp->handle;
H
Haojun Liao 已提交
4046

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

4052
        if (pRsp->numOfRows == 0) {
H
Haojun Liao 已提交
4053
          taosMemoryFree(pRsp);
4054 4055 4056
          return NULL;
        }
      }
H
Haojun Liao 已提交
4057

4058
      char* pStart = pRsp->data;
H
Haojun Liao 已提交
4059
      extractDataBlockFromFetchRsp(pInfo->pRes, pRsp->data, pInfo->matchInfo.pList, &pStart);
4060
      updateLoadRemoteInfo(&pInfo->loadInfo, pRsp->numOfRows, pRsp->compLen, startTs, pOperator);
H
Haojun Liao 已提交
4061

4062
      // todo log the filter info
H
Haojun Liao 已提交
4063
      doFilterResult(pInfo->pRes, pOperator->exprSupp.pFilterInfo);
H
Haojun Liao 已提交
4064
      taosMemoryFree(pRsp);
4065 4066
      if (pInfo->pRes->info.rows > 0) {
        return pInfo->pRes;
D
dapan1121 已提交
4067 4068
      } else if (pOperator->status == OP_EXEC_DONE) {
        return NULL;
4069
      }
4070
    }
H
Haojun Liao 已提交
4071 4072 4073
  }
}

4074
int32_t buildSysDbTableInfo(const SSysTableScanInfo* pInfo, int32_t capacity) {
D
dapan1121 已提交
4075
  SSDataBlock* p = buildInfoSchemaTableMetaBlock(TSDB_INS_TABLE_TABLES);
4076
  blockDataEnsureCapacity(p, capacity);
4077

L
Liu Jicong 已提交
4078
  size_t               size = 0;
4079 4080 4081
  const SSysTableMeta* pSysDbTableMeta = NULL;

  getInfosDbMeta(&pSysDbTableMeta, &size);
4082
  p->info.rows = buildDbTableInfoBlock(pInfo->sysInfo, p, pSysDbTableMeta, size, TSDB_INFORMATION_SCHEMA_DB);
4083 4084

  getPerfDbMeta(&pSysDbTableMeta, &size);
4085
  p->info.rows = buildDbTableInfoBlock(pInfo->sysInfo, p, pSysDbTableMeta, size, TSDB_PERFORMANCE_SCHEMA_DB);
4086 4087

  pInfo->pRes->info.rows = p->info.rows;
H
Haojun Liao 已提交
4088
  relocateColumnData(pInfo->pRes, pInfo->matchInfo.pList, p->pDataBlock, false);
4089 4090 4091
  blockDataDestroy(p);

  return pInfo->pRes->info.rows;
4092 4093
}

4094
int32_t buildDbTableInfoBlock(bool sysInfo, const SSDataBlock* p, const SSysTableMeta* pSysDbTableMeta, size_t size,
L
Liu Jicong 已提交
4095 4096
                              const char* dbName) {
  char    n[TSDB_TABLE_FNAME_LEN + VARSTR_HEADER_SIZE] = {0};
4097 4098
  int32_t numOfRows = p->info.rows;

L
Liu Jicong 已提交
4099
  for (int32_t i = 0; i < size; ++i) {
4100
    const SSysTableMeta* pm = &pSysDbTableMeta[i];
4101 4102 4103
    if (!sysInfo && pm->sysInfo) {
      continue;
    }
4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122

    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 已提交
4123
    for (int32_t j = 4; j <= 8; ++j) {
4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138
      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;
}

4139
SOperatorInfo* createSysTableScanOperatorInfo(void* readHandle, SSystemTableScanPhysiNode* pScanPhyNode,
4140
                                              const char* pUser, SExecTaskInfo* pTaskInfo) {
H
Haojun Liao 已提交
4141 4142 4143
  SSysTableScanInfo* pInfo = taosMemoryCalloc(1, sizeof(SSysTableScanInfo));
  SOperatorInfo*     pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
  if (pInfo == NULL || pOperator == NULL) {
4144
    goto _error;
H
Haojun Liao 已提交
4145 4146
  }

H
Haojun Liao 已提交
4147
  SScanPhysiNode*     pScanNode = &pScanPhyNode->scan;
4148 4149 4150
  SDataBlockDescNode* pDescNode = pScanNode->node.pOutputDataBlockDesc;

  int32_t num = 0;
H
Haojun Liao 已提交
4151
  int32_t code = extractColMatchInfo(pScanNode->pScanCols, pDescNode, &num, COL_MATCH_FROM_COL_ID, &pInfo->matchInfo);
H
Haojun Liao 已提交
4152 4153 4154
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
4155

4156 4157
  pInfo->accountId = pScanPhyNode->accountId;
  pInfo->pUser = taosMemoryStrDup((void*)pUser);
4158
  pInfo->sysInfo = pScanPhyNode->sysInfo;
4159
  pInfo->showRewrite = pScanPhyNode->showRewrite;
H
Haojun Liao 已提交
4160
  pInfo->pRes = createResDataBlock(pDescNode);
4161

4162
  pInfo->pCondition = pScanNode->node.pConditions;
4163 4164 4165 4166
  code = filterInitFromNode(pScanNode->node.pConditions, &pOperator->exprSupp.pFilterInfo, 0);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
4167

4168
  initResultSizeInfo(&pOperator->resultInfo, 4096);
4169
  blockDataEnsureCapacity(pInfo->pRes, pOperator->resultInfo.capacity);
H
Haojun Liao 已提交
4170

4171
  tNameAssign(&pInfo->name, &pScanNode->tableName);
4172
  const char* name = tNameGetTableName(&pInfo->name);
4173

D
dapan1121 已提交
4174 4175
  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 已提交
4176
    pInfo->readHandle = *(SReadHandle*)readHandle;
H
Haojun Liao 已提交
4177 4178
  } else {
    tsem_init(&pInfo->ready, 0, 0);
4179
    pInfo->epSet = pScanPhyNode->mgmtEpSet;
4180
    pInfo->readHandle = *(SReadHandle*)readHandle;
H
Haojun Liao 已提交
4181 4182
  }

L
Liu Jicong 已提交
4183 4184
  setOperatorInfo(pOperator, "SysTableScanOperator", QUERY_NODE_PHYSICAL_PLAN_SYSTABLE_SCAN, false, OP_NOT_OPENED,
                  pInfo, pTaskInfo);
H
Haojun Liao 已提交
4185
  pOperator->exprSupp.numOfExprs = taosArrayGetSize(pInfo->pRes->pDataBlock);
H
Haojun Liao 已提交
4186
  pOperator->fpSet = createOperatorFpSet(operatorDummyOpenFn, doSysTableScan, NULL, destroySysScanOperator, NULL);
H
Haojun Liao 已提交
4187
  return pOperator;
4188

4189
_error:
H
Haojun Liao 已提交
4190 4191 4192
  if (pInfo != NULL) {
    destroySysScanOperator(pInfo);
  }
4193
  taosMemoryFreeClear(pOperator);
4194
  pTaskInfo->code = code;
4195
  return NULL;
H
Haojun Liao 已提交
4196
}
H
Haojun Liao 已提交
4197

4198
static SSDataBlock* doTagScan(SOperatorInfo* pOperator) {
H
Haojun Liao 已提交
4199 4200 4201 4202
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

4203 4204 4205
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;

  STagScanInfo* pInfo = pOperator->info;
4206
  SExprInfo*    pExprInfo = &pOperator->exprSupp.pExprInfo[0];
4207
  SSDataBlock*  pRes = pInfo->pRes;
4208
  blockDataCleanup(pRes);
H
Haojun Liao 已提交
4209

H
Haojun Liao 已提交
4210
  int32_t size = tableListGetSize(pTaskInfo->pTableInfoList);
wmmhello's avatar
wmmhello 已提交
4211
  if (size == 0) {
H
Haojun Liao 已提交
4212 4213 4214 4215
    setTaskStatus(pTaskInfo, TASK_COMPLETED);
    return NULL;
  }

4216 4217 4218
  char        str[512] = {0};
  int32_t     count = 0;
  SMetaReader mr = {0};
4219
  metaReaderInit(&mr, pInfo->readHandle.meta, 0);
H
Haojun Liao 已提交
4220

wmmhello's avatar
wmmhello 已提交
4221
  while (pInfo->curPos < size && count < pOperator->resultInfo.capacity) {
H
Haojun Liao 已提交
4222
    STableKeyInfo* item = tableListGetInfo(pInfo->pTableList, pInfo->curPos);
L
Liu Jicong 已提交
4223
    int32_t        code = metaGetTableEntryByUid(&mr, item->uid);
4224
    tDecoderClear(&mr.coder);
H
Haojun Liao 已提交
4225
    if (code != TSDB_CODE_SUCCESS) {
L
Liu Jicong 已提交
4226 4227
      qError("failed to get table meta, uid:0x%" PRIx64 ", code:%s, %s", item->uid, tstrerror(terrno),
             GET_TASKID(pTaskInfo));
H
Haojun Liao 已提交
4228
      metaReaderClear(&mr);
4229
      T_LONG_JMP(pTaskInfo->env, terrno);
H
Haojun Liao 已提交
4230
    }
H
Haojun Liao 已提交
4231

4232
    for (int32_t j = 0; j < pOperator->exprSupp.numOfExprs; ++j) {
4233 4234 4235 4236 4237 4238
      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);
4239
      } else {  // it is a tag value
wmmhello's avatar
wmmhello 已提交
4240 4241
        STagVal val = {0};
        val.cid = pExprInfo[j].base.pParam[0].pCol->colId;
4242
        const char* p = metaGetTableTagVal(mr.me.ctbEntry.pTags, pDst->info.type, &val);
wmmhello's avatar
wmmhello 已提交
4243

4244 4245 4246 4247
        char* data = NULL;
        if (pDst->info.type != TSDB_DATA_TYPE_JSON && p != NULL) {
          data = tTagValToData((const STagVal*)p, false);
        } else {
wmmhello's avatar
wmmhello 已提交
4248 4249
          data = (char*)p;
        }
L
Liu Jicong 已提交
4250 4251
        colDataAppend(pDst, count, data,
                      (data == NULL) || (pDst->info.type == TSDB_DATA_TYPE_JSON && tTagIsJsonNull(data)));
4252

4253 4254
        if (pDst->info.type != TSDB_DATA_TYPE_JSON && p != NULL && IS_VAR_DATA_TYPE(((const STagVal*)p)->type) &&
            data != NULL) {
wmmhello's avatar
wmmhello 已提交
4255
          taosMemoryFree(data);
wmmhello's avatar
wmmhello 已提交
4256
        }
H
Haojun Liao 已提交
4257 4258 4259
      }
    }

4260
    count += 1;
wmmhello's avatar
wmmhello 已提交
4261
    if (++pInfo->curPos >= size) {
H
Haojun Liao 已提交
4262
      setOperatorCompleted(pOperator);
H
Haojun Liao 已提交
4263 4264 4265
    }
  }

4266 4267
  metaReaderClear(&mr);

4268
  // qDebug("QInfo:0x%"PRIx64" create tag values results completed, rows:%d", GET_TASKID(pRuntimeEnv), count);
H
Haojun Liao 已提交
4269
  if (pOperator->status == OP_EXEC_DONE) {
4270
    setTaskStatus(pTaskInfo, TASK_COMPLETED);
H
Haojun Liao 已提交
4271 4272 4273
  }

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

4276
  return (pRes->info.rows == 0) ? NULL : pInfo->pRes;
H
Haojun Liao 已提交
4277 4278
}

4279
static void destroyTagScanOperatorInfo(void* param) {
H
Haojun Liao 已提交
4280 4281
  STagScanInfo* pInfo = (STagScanInfo*)param;
  pInfo->pRes = blockDataDestroy(pInfo->pRes);
H
Haojun Liao 已提交
4282
  taosArrayDestroy(pInfo->matchInfo.pList);
D
dapan1121 已提交
4283
  taosMemoryFreeClear(param);
H
Haojun Liao 已提交
4284 4285
}

4286 4287
SOperatorInfo* createTagScanOperatorInfo(SReadHandle* pReadHandle, STagScanPhysiNode* pPhyNode,
                                         STableListInfo* pTableListInfo, SExecTaskInfo* pTaskInfo) {
4288
  STagScanInfo*  pInfo = taosMemoryCalloc(1, sizeof(STagScanInfo));
H
Haojun Liao 已提交
4289 4290 4291 4292 4293
  SOperatorInfo* pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }

4294 4295 4296 4297
  SDataBlockDescNode* pDescNode = pPhyNode->node.pOutputDataBlockDesc;

  int32_t    numOfExprs = 0;
  SExprInfo* pExprInfo = createExprInfo(pPhyNode->pScanPseudoCols, NULL, &numOfExprs);
4298
  int32_t    code = initExprSupp(&pOperator->exprSupp, pExprInfo, numOfExprs);
4299 4300 4301
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
4302

H
Haojun Liao 已提交
4303 4304
  int32_t num = 0;
  code = extractColMatchInfo(pPhyNode->pScanPseudoCols, pDescNode, &num, COL_MATCH_FROM_COL_ID, &pInfo->matchInfo);
4305 4306 4307
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
4308

4309 4310 4311 4312
  pInfo->pTableList = pTableListInfo;
  pInfo->pRes = createResDataBlock(pDescNode);
  pInfo->readHandle = *pReadHandle;
  pInfo->curPos = 0;
4313

L
Liu Jicong 已提交
4314 4315
  setOperatorInfo(pOperator, "TagScanOperator", QUERY_NODE_PHYSICAL_PLAN_TAG_SCAN, false, OP_NOT_OPENED, pInfo,
                  pTaskInfo);
4316
  initResultSizeInfo(&pOperator->resultInfo, 4096);
4317 4318
  blockDataEnsureCapacity(pInfo->pRes, pOperator->resultInfo.capacity);

H
Haojun Liao 已提交
4319
  pOperator->fpSet = createOperatorFpSet(operatorDummyOpenFn, doTagScan, NULL, destroyTagScanOperatorInfo, NULL);
H
Haojun Liao 已提交
4320 4321

  return pOperator;
4322

4323
_error:
H
Haojun Liao 已提交
4324 4325 4326 4327 4328
  taosMemoryFree(pInfo);
  taosMemoryFree(pOperator);
  terrno = TSDB_CODE_OUT_OF_MEMORY;
  return NULL;
}
4329

H
Haojun Liao 已提交
4330
// todo refactor
4331
static int32_t loadDataBlockFromOneTable(SOperatorInfo* pOperator, STableMergeScanInfo* pTableScanInfo,
H
Haojun Liao 已提交
4332
                                         SSDataBlock* pBlock, uint32_t* status) {
L
Liu Jicong 已提交
4333
  SExecTaskInfo*       pTaskInfo = pOperator->pTaskInfo;
S
shenglian zhou 已提交
4334
  STableMergeScanInfo* pInfo = pOperator->info;
4335 4336 4337 4338 4339 4340 4341

  SFileBlockLoadRecorder* pCost = &pTableScanInfo->readRecorder;

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

  *status = pInfo->dataBlockLoadFlag;
H
Haojun Liao 已提交
4342
  if (pOperator->exprSupp.pFilterInfo != NULL ||
4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360
      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
4361
    for (int32_t i = 0; i < taosArrayGetSize(pBlock->pDataBlock); ++i) {
4362 4363 4364 4365 4366
      SColumnInfoData* pcol = taosArrayGet(pBlock->pDataBlock, i);
      pcol->pData = NULL;
    }

    return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
4367
  } else if (*status == FUNC_DATA_REQUIRED_SMA_LOAD) {
4368 4369 4370 4371 4372 4373
    pCost->loadBlockStatis += 1;

    bool             allColumnsHaveAgg = true;
    SColumnDataAgg** pColAgg = NULL;

    if (allColumnsHaveAgg == true) {
4374
      int32_t numOfCols = taosArrayGetSize(pBlock->pDataBlock);
4375 4376 4377 4378 4379 4380 4381

      // 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) {
H
Haojun Liao 已提交
4382 4383
        SColMatchItem* pColMatchInfo = taosArrayGet(pTableScanInfo->matchInfo.pList, i);
        if (!pColMatchInfo->needOutput) {
4384 4385
          continue;
        }
H
Haojun Liao 已提交
4386
        pBlock->pBlockAgg[pColMatchInfo->dstSlotId] = pColAgg[i];
4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398
      }

      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 已提交
4399
  if (!doFilterByBlockSMA(pBlock->pBlockStatis, pTableScanInfo->pCtx, pBlockInfo->rows)) {
4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410
    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;

4411
  STsdbReader* reader = pTableScanInfo->pReader;
4412 4413 4414 4415 4416
  SArray*      pCols = tsdbRetrieveDataBlock(reader, NULL);
  if (pCols == NULL) {
    return terrno;
  }

H
Haojun Liao 已提交
4417
  relocateColumnData(pBlock, pTableScanInfo->matchInfo.pList, pCols, true);
4418 4419

  // currently only the tbname pseudo column
H
Haojun Liao 已提交
4420 4421 4422
  SExprSupp* pSup = &pTableScanInfo->pseudoSup;

  int32_t code = addTagPseudoColumnData(&pTableScanInfo->readHandle, pSup->pExprInfo, pSup->numOfExprs, pBlock,
4423
                                        pBlock->info.rows, GET_TASKID(pTaskInfo), NULL);
H
Haojun Liao 已提交
4424 4425
  if (code != TSDB_CODE_SUCCESS) {
    T_LONG_JMP(pTaskInfo->env, code);
4426 4427
  }

4428
  if (pOperator->exprSupp.pFilterInfo != NULL) {
4429
    int64_t st = taosGetTimestampMs();
H
Haojun Liao 已提交
4430
    doFilter(pBlock, pOperator->exprSupp.pFilterInfo, &pTableScanInfo->matchInfo);
4431

4432 4433
    double el = (taosGetTimestampUs() - st) / 1000.0;
    pTableScanInfo->readRecorder.filterTime += el;
4434

4435 4436 4437 4438 4439 4440 4441
    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);
    }
4442 4443 4444 4445 4446
  }

  return TSDB_CODE_SUCCESS;
}

dengyihao's avatar
dengyihao 已提交
4447
static SSDataBlock* getTableDataBlockImpl(void* param) {
dengyihao's avatar
opt mem  
dengyihao 已提交
4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460
  STableMergeScanSortSourceParam* source = param;
  SOperatorInfo*                  pOperator = source->pOperator;
  STableMergeScanInfo*            pInfo = pOperator->info;
  SExecTaskInfo*                  pTaskInfo = pOperator->pTaskInfo;
  int32_t                         readIdx = source->readerIdx;
  SSDataBlock*                    pBlock = source->inputBlock;
  STableMergeScanInfo*            pTableScanInfo = pOperator->info;

  SQueryTableDataCond* pQueryCond = taosArrayGet(pTableScanInfo->queryConds, readIdx);
  blockDataCleanup(pBlock);

  int64_t st = taosGetTimestampUs();

5
54liuyao 已提交
4461
  void*        p = tableListGetInfo(pInfo->tableListInfo, readIdx + pInfo->tableStartIndex);
dengyihao's avatar
opt mem  
dengyihao 已提交
4462
  SReadHandle* pHandle = &pInfo->readHandle;
dengyihao's avatar
dengyihao 已提交
4463 4464 4465

  int32_t code = tsdbReaderOpen(pHandle->vnode, pQueryCond, p, 1, &pInfo->pReader, GET_TASKID(pTaskInfo));
  if (code != 0) {
H
Haojun Liao 已提交
4466
    T_LONG_JMP(pTaskInfo->env, code);
dengyihao's avatar
dengyihao 已提交
4467
  }
dengyihao's avatar
opt mem  
dengyihao 已提交
4468 4469 4470

  STsdbReader* reader = pInfo->pReader;
  while (tsdbNextDataBlock(reader)) {
H
Haojun Liao 已提交
4471 4472
    if (isTaskKilled(pTaskInfo)) {
      T_LONG_JMP(pTaskInfo->env, TSDB_CODE_TSC_QUERY_CANCELLED);
dengyihao's avatar
opt mem  
dengyihao 已提交
4473 4474 4475 4476 4477 4478 4479 4480 4481 4482
    }

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

    blockDataCleanup(pBlock);

H
Haojun Liao 已提交
4483 4484 4485 4486
    int32_t rows = 0;
    tsdbRetrieveDataBlockInfo(reader, &rows, &pBlock->info.uid, &pBlock->info.window);
    blockDataEnsureCapacity(pBlock, rows);
    pBlock->info.rows = rows;
dengyihao's avatar
opt mem  
dengyihao 已提交
4487

H
Haojun Liao 已提交
4488
    if (pQueryCond->order == TSDB_ORDER_ASC) {
dengyihao's avatar
opt mem  
dengyihao 已提交
4489 4490 4491 4492
      pQueryCond->twindows.skey = pBlock->info.window.ekey + 1;
    } else {
      pQueryCond->twindows.ekey = pBlock->info.window.skey - 1;
    }
dengyihao's avatar
opt mem  
dengyihao 已提交
4493 4494

    uint32_t status = 0;
H
Haojun Liao 已提交
4495
    code = loadDataBlockFromOneTable(pOperator, pTableScanInfo, pBlock, &status);
dengyihao's avatar
opt mem  
dengyihao 已提交
4496
    if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
4497
      T_LONG_JMP(pTaskInfo->env, code);
dengyihao's avatar
opt mem  
dengyihao 已提交
4498 4499 4500 4501 4502 4503 4504
    }

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

H
Haojun Liao 已提交
4505
    pBlock->info.groupId = getTableGroupId(pTaskInfo->pTableInfoList, pBlock->info.uid);
dengyihao's avatar
opt mem  
dengyihao 已提交
4506

H
Haojun Liao 已提交
4507
    pOperator->resultInfo.totalRows += pBlock->info.rows;
dengyihao's avatar
opt mem  
dengyihao 已提交
4508 4509 4510
    pTableScanInfo->readRecorder.elapsedTime += (taosGetTimestampUs() - st) / 1000.0;

    tsdbReaderClose(pInfo->pReader);
dengyihao's avatar
opt mem  
dengyihao 已提交
4511
    pInfo->pReader = NULL;
dengyihao's avatar
opt mem  
dengyihao 已提交
4512 4513
    return pBlock;
  }
H
Haojun Liao 已提交
4514

dengyihao's avatar
opt mem  
dengyihao 已提交
4515
  tsdbReaderClose(pInfo->pReader);
dengyihao's avatar
opt mem  
dengyihao 已提交
4516
  pInfo->pReader = NULL;
dengyihao's avatar
opt mem  
dengyihao 已提交
4517 4518 4519
  return NULL;
}

4520 4521 4522
SArray* generateSortByTsInfo(SArray* colMatchInfo, int32_t order) {
  int32_t tsTargetSlotId = 0;
  for (int32_t i = 0; i < taosArrayGetSize(colMatchInfo); ++i) {
H
Haojun Liao 已提交
4523
    SColMatchItem* colInfo = taosArrayGet(colMatchInfo, i);
4524
    if (colInfo->colId == PRIMARYKEY_TIMESTAMP_COL_ID) {
H
Haojun Liao 已提交
4525
      tsTargetSlotId = colInfo->dstSlotId;
4526 4527 4528
    }
  }

4529 4530 4531
  SArray*         pList = taosArrayInit(1, sizeof(SBlockOrderInfo));
  SBlockOrderInfo bi = {0};
  bi.order = order;
4532
  bi.slotId = tsTargetSlotId;
4533 4534 4535 4536 4537 4538 4539
  bi.nullFirst = NULL_ORDER_FIRST;

  taosArrayPush(pList, &bi);

  return pList;
}

dengyihao's avatar
opt mem  
dengyihao 已提交
4540 4541 4542 4543 4544 4545 4546 4547
int32_t dumpSQueryTableCond(const SQueryTableDataCond* src, SQueryTableDataCond* dst) {
  memcpy((void*)dst, (void*)src, sizeof(SQueryTableDataCond));
  dst->colList = taosMemoryCalloc(src->numOfCols, sizeof(SColumnInfo));
  for (int i = 0; i < src->numOfCols; i++) {
    dst->colList[i] = src->colList[i];
  }
  return 0;
}
H
Haojun Liao 已提交
4548

4549
int32_t startGroupTableMergeScan(SOperatorInfo* pOperator) {
4550 4551 4552
  STableMergeScanInfo* pInfo = pOperator->info;
  SExecTaskInfo*       pTaskInfo = pOperator->pTaskInfo;

S
slzhou 已提交
4553
  {
H
Haojun Liao 已提交
4554
    size_t  numOfTables = tableListGetSize(pInfo->tableListInfo);
S
slzhou 已提交
4555
    int32_t i = pInfo->tableStartIndex + 1;
H
Haojun Liao 已提交
4556 4557
    for (; i < numOfTables; ++i) {
      STableKeyInfo* tableKeyInfo = tableListGetInfo(pInfo->tableListInfo, i);
S
slzhou 已提交
4558 4559 4560 4561 4562 4563
      if (tableKeyInfo->groupId != pInfo->groupId) {
        break;
      }
    }
    pInfo->tableEndIndex = i - 1;
  }
4564

S
slzhou 已提交
4565 4566
  int32_t tableStartIdx = pInfo->tableStartIndex;
  int32_t tableEndIdx = pInfo->tableEndIndex;
4567

dengyihao's avatar
opt mem  
dengyihao 已提交
4568
  pInfo->pReader = NULL;
4569

4570 4571
  // 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 已提交
4572
  pInfo->sortBufSize = pInfo->bufPageSize * (tableEndIdx - tableStartIdx + 1 + 1);
4573
  int32_t numOfBufPage = pInfo->sortBufSize / pInfo->bufPageSize;
L
Liu Jicong 已提交
4574 4575
  pInfo->pSortHandle = tsortCreateSortHandle(pInfo->pSortInfo, SORT_MULTISOURCE_MERGE, pInfo->bufPageSize, numOfBufPage,
                                             pInfo->pSortInputBlock, pTaskInfo->id.str);
4576

dengyihao's avatar
dengyihao 已提交
4577
  tsortSetFetchRawDataFp(pInfo->pSortHandle, getTableDataBlockImpl, NULL, NULL);
dengyihao's avatar
opt mem  
dengyihao 已提交
4578 4579 4580 4581 4582 4583

  // one table has one data block
  int32_t numOfTable = tableEndIdx - tableStartIdx + 1;
  pInfo->queryConds = taosArrayInit(numOfTable, sizeof(SQueryTableDataCond));

  for (int32_t i = 0; i < numOfTable; ++i) {
4584 4585 4586 4587 4588
    STableMergeScanSortSourceParam param = {0};
    param.readerIdx = i;
    param.pOperator = pOperator;
    param.inputBlock = createOneDataBlock(pInfo->pResBlock, false);
    taosArrayPush(pInfo->sortSourceParams, &param);
dengyihao's avatar
opt mem  
dengyihao 已提交
4589 4590 4591 4592

    SQueryTableDataCond cond;
    dumpSQueryTableCond(&pInfo->cond, &cond);
    taosArrayPush(pInfo->queryConds, &cond);
4593 4594
  }

dengyihao's avatar
opt mem  
dengyihao 已提交
4595
  for (int32_t i = 0; i < numOfTable; ++i) {
4596
    SSortSource*                    ps = taosMemoryCalloc(1, sizeof(SSortSource));
4597
    STableMergeScanSortSourceParam* param = taosArrayGet(pInfo->sortSourceParams, i);
4598 4599 4600 4601 4602 4603 4604
    ps->param = param;
    tsortAddSource(pInfo->pSortHandle, ps);
  }

  int32_t code = tsortOpen(pInfo->pSortHandle);

  if (code != TSDB_CODE_SUCCESS) {
4605
    T_LONG_JMP(pTaskInfo->env, terrno);
4606 4607
  }

4608 4609 4610 4611 4612 4613 4614
  return TSDB_CODE_SUCCESS;
}

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

dengyihao's avatar
dengyihao 已提交
4615
  int32_t numOfTable = taosArrayGetSize(pInfo->queryConds);
4616

4617 4618 4619 4620 4621 4622 4623
  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;

dengyihao's avatar
dengyihao 已提交
4624
  for (int32_t i = 0; i < numOfTable; ++i) {
4625 4626 4627
    STableMergeScanSortSourceParam* param = taosArrayGet(pInfo->sortSourceParams, i);
    blockDataDestroy(param->inputBlock);
  }
4628 4629
  taosArrayClear(pInfo->sortSourceParams);

4630 4631
  tsortDestroySortHandle(pInfo->pSortHandle);

dengyihao's avatar
opt mem  
dengyihao 已提交
4632 4633 4634
  for (int32_t i = 0; i < taosArrayGetSize(pInfo->queryConds); i++) {
    SQueryTableDataCond* cond = taosArrayGet(pInfo->queryConds, i);
    taosMemoryFree(cond->colList);
4635
  }
dengyihao's avatar
opt mem  
dengyihao 已提交
4636 4637 4638
  taosArrayDestroy(pInfo->queryConds);
  pInfo->queryConds = NULL;

4639 4640 4641
  return TSDB_CODE_SUCCESS;
}

L
Liu Jicong 已提交
4642 4643
SSDataBlock* getSortedTableMergeScanBlockData(SSortHandle* pHandle, SSDataBlock* pResBlock, int32_t capacity,
                                              SOperatorInfo* pOperator) {
4644 4645 4646
  STableMergeScanInfo* pInfo = pOperator->info;
  SExecTaskInfo*       pTaskInfo = pOperator->pTaskInfo;

4647
  blockDataCleanup(pResBlock);
4648 4649

  while (1) {
4650
    STupleHandle* pTupleHandle = tsortNextTuple(pHandle);
4651 4652 4653 4654
    if (pTupleHandle == NULL) {
      break;
    }

4655 4656
    appendOneRowToDataBlock(pResBlock, pTupleHandle);
    if (pResBlock->info.rows >= capacity) {
4657 4658 4659 4660
      break;
    }
  }

4661
  qDebug("%s get sorted row blocks, rows:%d", GET_TASKID(pTaskInfo), pResBlock->info.rows);
4662 4663 4664
  applyLimitOffset(&pInfo->limitInfo, pResBlock, pTaskInfo, pOperator);
  pInfo->limitInfo.numOfOutputRows += pResBlock->info.rows;

4665
  return (pResBlock->info.rows > 0) ? pResBlock : NULL;
4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677
}

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) {
4678
    T_LONG_JMP(pTaskInfo->env, code);
4679
  }
4680

H
Haojun Liao 已提交
4681
  size_t tableListSize = tableListGetSize(pInfo->tableListInfo);
S
slzhou 已提交
4682 4683
  if (!pInfo->hasGroupId) {
    pInfo->hasGroupId = true;
4684

S
slzhou 已提交
4685
    if (tableListSize == 0) {
H
Haojun Liao 已提交
4686
      setOperatorCompleted(pOperator);
4687 4688
      return NULL;
    }
S
slzhou 已提交
4689
    pInfo->tableStartIndex = 0;
H
Haojun Liao 已提交
4690
    pInfo->groupId = ((STableKeyInfo*)tableListGetInfo(pInfo->tableListInfo, pInfo->tableStartIndex))->groupId;
4691 4692
    startGroupTableMergeScan(pOperator);
  }
4693

S
slzhou 已提交
4694 4695
  SSDataBlock* pBlock = NULL;
  while (pInfo->tableStartIndex < tableListSize) {
L
Liu Jicong 已提交
4696 4697
    pBlock = getSortedTableMergeScanBlockData(pInfo->pSortHandle, pInfo->pResBlock, pOperator->resultInfo.capacity,
                                              pOperator);
S
slzhou 已提交
4698 4699 4700 4701 4702 4703 4704
    if (pBlock != NULL) {
      pBlock->info.groupId = pInfo->groupId;
      pOperator->resultInfo.totalRows += pBlock->info.rows;
      return pBlock;
    } else {
      stopGroupTableMergeScan(pOperator);
      if (pInfo->tableEndIndex >= tableListSize - 1) {
H
Haojun Liao 已提交
4705
        setOperatorCompleted(pOperator);
S
slzhou 已提交
4706 4707 4708
        break;
      }
      pInfo->tableStartIndex = pInfo->tableEndIndex + 1;
H
Haojun Liao 已提交
4709
      pInfo->groupId = tableListGetInfo(pInfo->tableListInfo, pInfo->tableStartIndex)->groupId;
S
slzhou 已提交
4710 4711
      startGroupTableMergeScan(pOperator);
    }
wmmhello's avatar
wmmhello 已提交
4712 4713
  }

4714 4715 4716
  return pBlock;
}

4717
void destroyTableMergeScanOperatorInfo(void* param) {
4718
  STableMergeScanInfo* pTableScanInfo = (STableMergeScanInfo*)param;
4719
  cleanupQueryTableDataCond(&pTableScanInfo->cond);
4720

dengyihao's avatar
dengyihao 已提交
4721 4722 4723
  int32_t numOfTable = taosArrayGetSize(pTableScanInfo->queryConds);

  for (int32_t i = 0; i < numOfTable; i++) {
H
Haojun Liao 已提交
4724 4725
    STableMergeScanSortSourceParam* p = taosArrayGet(pTableScanInfo->sortSourceParams, i);
    blockDataDestroy(p->inputBlock);
4726
  }
H
Haojun Liao 已提交
4727

4728
  taosArrayDestroy(pTableScanInfo->sortSourceParams);
4729

dengyihao's avatar
opt mem  
dengyihao 已提交
4730
  tsdbReaderClose(pTableScanInfo->pReader);
dengyihao's avatar
dengyihao 已提交
4731
  pTableScanInfo->pReader = NULL;
dengyihao's avatar
opt mem  
dengyihao 已提交
4732

dengyihao's avatar
opt mem  
dengyihao 已提交
4733 4734 4735
  for (int i = 0; i < taosArrayGetSize(pTableScanInfo->queryConds); i++) {
    SQueryTableDataCond* pCond = taosArrayGet(pTableScanInfo->queryConds, i);
    taosMemoryFree(pCond->colList);
4736
  }
dengyihao's avatar
opt mem  
dengyihao 已提交
4737
  taosArrayDestroy(pTableScanInfo->queryConds);
4738

H
Haojun Liao 已提交
4739 4740
  if (pTableScanInfo->matchInfo.pList != NULL) {
    taosArrayDestroy(pTableScanInfo->matchInfo.pList);
4741 4742 4743 4744 4745 4746
  }

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

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

4749
  taosMemoryFreeClear(pTableScanInfo->rowEntryInfoOffset);
D
dapan1121 已提交
4750
  taosMemoryFreeClear(param);
4751 4752 4753 4754
}

int32_t getTableMergeScanExplainExecInfo(SOperatorInfo* pOptr, void** pOptrExplain, uint32_t* len) {
  ASSERT(pOptr != NULL);
4755 4756
  // TODO: merge these two info into one struct
  STableMergeScanExecInfo* execInfo = taosMemoryCalloc(1, sizeof(STableMergeScanExecInfo));
L
Liu Jicong 已提交
4757
  STableMergeScanInfo*     pInfo = pOptr->info;
4758
  execInfo->blockRecorder = pInfo->readRecorder;
4759
  execInfo->sortExecInfo = pInfo->sortExecInfo;
4760 4761 4762

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

4764 4765 4766
  return TSDB_CODE_SUCCESS;
}

4767
SOperatorInfo* createTableMergeScanOperatorInfo(STableScanPhysiNode* pTableScanNode, STableListInfo* pTableListInfo,
4768
                                                SReadHandle* readHandle, SExecTaskInfo* pTaskInfo) {
4769 4770 4771 4772 4773
  STableMergeScanInfo* pInfo = taosMemoryCalloc(1, sizeof(STableMergeScanInfo));
  SOperatorInfo*       pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }
4774

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

  int32_t numOfCols = 0;
4778 4779
  int32_t code = extractColMatchInfo(pTableScanNode->scan.pScanCols, pDescNode, &numOfCols, COL_MATCH_FROM_COL_ID,
                                     &pInfo->matchInfo);
H
Haojun Liao 已提交
4780 4781 4782
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
4783

H
Haojun Liao 已提交
4784
  code = initQueryTableDataCond(&pInfo->cond, pTableScanNode);
4785
  if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
4786
    taosArrayDestroy(pInfo->matchInfo.pList);
4787 4788 4789 4790
    goto _error;
  }

  if (pTableScanNode->scan.pScanPseudoCols != NULL) {
4791 4792 4793
    SExprSupp* pSup = &pInfo->pseudoSup;
    pSup->pExprInfo = createExprInfo(pTableScanNode->scan.pScanPseudoCols, NULL, &pSup->numOfExprs);
    pSup->pCtx = createSqlFunctionCtx(pSup->pExprInfo, pSup->numOfExprs, &pSup->rowEntryInfoOffset);
4794 4795 4796 4797
  }

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

L
Liu Jicong 已提交
4798 4799
  pInfo->readHandle = *readHandle;
  pInfo->interval = extractIntervalInfo(pTableScanNode);
4800
  pInfo->sample.sampleRatio = pTableScanNode->ratio;
L
Liu Jicong 已提交
4801 4802
  pInfo->sample.seed = taosGetTimestampSec();
  pInfo->dataBlockLoadFlag = pTableScanNode->dataRequired;
H
Haojun Liao 已提交
4803 4804 4805 4806 4807 4808

  code = filterInitFromNode((SNode*)pTableScanNode->scan.node.pConditions, &pOperator->exprSupp.pFilterInfo, 0);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }

4809
  pInfo->tableListInfo = pTableListInfo;
L
Liu Jicong 已提交
4810
  pInfo->scanFlag = MAIN_SCAN;
4811

H
Haojun Liao 已提交
4812
  initResultSizeInfo(&pOperator->resultInfo, 1024);
4813
  pInfo->pResBlock = createResDataBlock(pDescNode);
H
Haojun Liao 已提交
4814 4815
  blockDataEnsureCapacity(pInfo->pResBlock, pOperator->resultInfo.capacity);

4816
  pInfo->sortSourceParams = taosArrayInit(64, sizeof(STableMergeScanSortSourceParam));
4817

H
Haojun Liao 已提交
4818
  pInfo->pSortInfo = generateSortByTsInfo(pInfo->matchInfo.pList, pInfo->cond.order);
4819
  pInfo->pSortInputBlock = createOneDataBlock(pInfo->pResBlock, false);
4820
  initLimitInfo(pTableScanNode->scan.node.pLimit, pTableScanNode->scan.node.pSlimit, &pInfo->limitInfo);
4821

4822
  int32_t rowSize = pInfo->pResBlock->info.rowSize;
L
Liu Jicong 已提交
4823
  pInfo->bufPageSize = getProperSortPageSize(rowSize);
4824

L
Liu Jicong 已提交
4825 4826
  setOperatorInfo(pOperator, "TableMergeScanOperator", QUERY_NODE_PHYSICAL_PLAN_TABLE_MERGE_SCAN, false, OP_NOT_OPENED,
                  pInfo, pTaskInfo);
L
Liu Jicong 已提交
4827
  pOperator->exprSupp.numOfExprs = numOfCols;
4828

L
Liu Jicong 已提交
4829 4830
  pOperator->fpSet = createOperatorFpSet(operatorDummyOpenFn, doTableMergeScan, NULL, destroyTableMergeScanOperatorInfo,
                                         getTableMergeScanExplainExecInfo);
4831 4832 4833 4834 4835 4836 4837 4838 4839
  pOperator->cost.openCost = 0;
  return pOperator;

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