scanoperator.c 133.4 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/>.
 */

dengyihao's avatar
dengyihao 已提交
16 17
// clang-format off

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

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

#include "query.h"
#include "tcompare.h"
#include "thash.h"
#include "ttypes.h"
35 36
#include "operator.h"
#include "querytask.h"
H
Haojun Liao 已提交
37

38 39 40
#include "storageapi.h"
#include "wal.h"

D
dapan1121 已提交
41 42
int32_t scanDebug = 0;

X
Xiaoyu Wang 已提交
43
#define MULTI_READER_MAX_TABLE_NUM   5000
H
Haojun Liao 已提交
44
#define SET_REVERSE_SCAN_FLAG(_info) ((_info)->scanFlag = REVERSE_SCAN)
45
#define SWITCH_ORDER(n)              (((n) = ((n) == TSDB_ORDER_ASC) ? TSDB_ORDER_DESC : TSDB_ORDER_ASC))
L
fix bug  
liuyao 已提交
46
#define STREAM_SCAN_OP_NAME          "StreamScanOperator"
47

H
Haojun Liao 已提交
48 49 50 51 52 53 54 55 56 57
typedef struct STableMergeScanExecInfo {
  SFileBlockLoadRecorder blockRecorder;
  SSortExecInfo          sortExecInfo;
} STableMergeScanExecInfo;

typedef struct STableMergeScanSortSourceParam {
  SOperatorInfo* pOperator;
  int32_t        readerIdx;
  uint64_t       uid;
  SSDataBlock*   inputBlock;
D
dapan1121 已提交
58 59
  bool           multiReader;
  STsdbReader*   dataReader;
H
Haojun Liao 已提交
60 61
} STableMergeScanSortSourceParam;

62 63 64 65 66 67 68 69 70 71
typedef struct STableCountScanOperatorInfo {
  SReadHandle  readHandle;
  SSDataBlock* pRes;

  STableCountScanSupp supp;

  int32_t currGrpIdx;
  SArray* stbUidList;  // when group by db_name and/or stable_name
} STableCountScanOperatorInfo;

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

H
Haojun Liao 已提交
74
bool processBlockWithProbability(const SSampleExecInfo* pInfo) {
75 76 77 78 79 80 81 82 83 84 85 86
#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
}

87
static void switchCtxOrder(SqlFunctionCtx* pCtx, int32_t numOfOutput) {
H
Haojun Liao 已提交
88 89 90 91 92
  for (int32_t i = 0; i < numOfOutput; ++i) {
    SWITCH_ORDER(pCtx[i].order);
  }
}

93
static bool overlapWithTimeWindow(SInterval* pInterval, SDataBlockInfo* pBlockInfo, int32_t order) {
94 95 96 97 98 99 100
  STimeWindow w = {0};

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

101
  if (order == TSDB_ORDER_ASC) {
102
    w = getAlignQueryTimeWindow(pInterval, pBlockInfo->window.skey);
103
    ASSERT(w.ekey >= pBlockInfo->window.skey);
104

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

109 110
    while (1) {
      getNextTimeWindow(pInterval, &w, order);
111 112 113 114
      if (w.skey > pBlockInfo->window.ekey) {
        break;
      }

115
      ASSERT(w.ekey > pBlockInfo->window.ekey);
116
      if (TMAX(w.skey, pBlockInfo->window.skey) <= pBlockInfo->window.ekey) {
117 118 119 120
        return true;
      }
    }
  } else {
121
    w = getAlignQueryTimeWindow(pInterval, pBlockInfo->window.ekey);
122
    ASSERT(w.skey <= pBlockInfo->window.ekey);
123

124
    if (w.skey > pBlockInfo->window.skey) {
125 126 127
      return true;
    }

128
    while (1) {
129 130 131 132 133
      getNextTimeWindow(pInterval, &w, order);
      if (w.ekey < pBlockInfo->window.skey) {
        break;
      }

H
Haojun Liao 已提交
134
      ASSERT(w.skey < pBlockInfo->window.skey);
135
      if (pBlockInfo->window.skey <= TMIN(w.ekey, pBlockInfo->window.ekey)) {
136 137 138
        return true;
      }
    }
139 140 141 142 143
  }

  return false;
}

144 145 146 147 148 149 150 151 152 153 154
// 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;

S
slzhou 已提交
155 156
  SResultRowPosition* p1 = (SResultRowPosition*)tSimpleHashGet(pTableScanInfo->base.pdInfo.pAggSup->pResultRowHashTable,
                                                               buf, GET_RES_WINDOW_KEY_LEN(sizeof(groupId)));
157 158 159 160 161

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

H
Haojun Liao 已提交
162
  *pPage = getBufPage(pTableScanInfo->base.pdInfo.pAggSup->pResultBuf, p1->pageId);
163 164 165
  if (NULL == *pPage) {
    return NULL;
  }
L
Liu Jicong 已提交
166

167 168 169
  return (SResultRow*)((char*)(*pPage) + p1->offset);
}

170 171 172 173 174 175 176 177
static int32_t insertTableToScanIgnoreList(STableScanInfo* pTableScanInfo, uint64_t uid) {
  if (NULL == pTableScanInfo->pIgnoreTables) {
    int32_t tableNum = taosArrayGetSize(pTableScanInfo->base.pTableListInfo->pTableList);
    pTableScanInfo->pIgnoreTables = taosHashInit(tableNum,  taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT), true, HASH_NO_LOCK);
    if (NULL == pTableScanInfo->pIgnoreTables) {
      return TSDB_CODE_OUT_OF_MEMORY;
    }
  }
H
Haojun Liao 已提交
178

179 180 181 182 183
  taosHashPut(pTableScanInfo->pIgnoreTables, &uid, sizeof(uid), &pTableScanInfo->scanTimes, sizeof(pTableScanInfo->scanTimes));

  return TSDB_CODE_SUCCESS;
}

184 185
static int32_t doDynamicPruneDataBlock(SOperatorInfo* pOperator, SDataBlockInfo* pBlockInfo, uint32_t* status) {
  STableScanInfo* pTableScanInfo = pOperator->info;
186
  int32_t code = TSDB_CODE_SUCCESS;
187

H
Haojun Liao 已提交
188
  if (pTableScanInfo->base.pdInfo.pExprSup == NULL) {
189 190 191
    return TSDB_CODE_SUCCESS;
  }

H
Haojun Liao 已提交
192
  SExprSupp* pSup1 = pTableScanInfo->base.pdInfo.pExprSup;
193 194

  SFilePage*  pPage = NULL;
H
Haojun Liao 已提交
195
  SResultRow* pRow = getTableGroupOutputBuf(pOperator, pBlockInfo->id.groupId, &pPage);
196 197 198 199 200 201 202 203 204

  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;

H
Haojun Liao 已提交
205
    SResultRowEntryInfo* pEntry = getResultEntryInfo(pRow, i, pTableScanInfo->base.pdInfo.pExprSup->rowEntryInfoOffset);
206 207 208 209 210 211 212 213 214

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

  // release buffer pages
H
Haojun Liao 已提交
215
  releaseBufPage(pTableScanInfo->base.pdInfo.pAggSup->pResultBuf, pPage);
216 217 218

  if (notLoadBlock) {
    *status = FUNC_DATA_REQUIRED_NOT_LOAD;
219
    code = insertTableToScanIgnoreList(pTableScanInfo, pBlockInfo->id.uid);
220 221
  }

222
  return code;
223 224
}

H
Haojun Liao 已提交
225
static bool doFilterByBlockSMA(SFilterInfo* pFilterInfo, SColumnDataAgg** pColsAgg, int32_t numOfCols,
226
                               int32_t numOfRows) {
H
Haojun Liao 已提交
227
  if (pColsAgg == NULL || pFilterInfo == NULL) {
H
Haojun Liao 已提交
228 229 230
    return true;
  }

H
Haojun Liao 已提交
231
  bool keep = filterRangeExecute(pFilterInfo, pColsAgg, numOfCols, numOfRows);
H
Haojun Liao 已提交
232 233 234
  return keep;
}

H
Haojun Liao 已提交
235
static bool doLoadBlockSMA(STableScanBase* pTableScanInfo, SSDataBlock* pBlock, SExecTaskInfo* pTaskInfo) {
236 237
  SStorageAPI* pAPI = &pTaskInfo->storageAPI;

H
Haojun Liao 已提交
238
  bool    allColumnsHaveAgg = true;
G
Ganlin Zhao 已提交
239
  bool    hasNullSMA = false;
H
Haojun Liao 已提交
240
  int32_t code = pAPI->tsdReader.tsdReaderRetrieveBlockSMAInfo(pTableScanInfo->dataReader, pBlock, &allColumnsHaveAgg, &hasNullSMA);
H
Haojun Liao 已提交
241
  if (code != TSDB_CODE_SUCCESS) {
242
    T_LONG_JMP(pTaskInfo->env, code);
H
Haojun Liao 已提交
243 244
  }

G
Ganlin Zhao 已提交
245
  if (!allColumnsHaveAgg || hasNullSMA) {
H
Haojun Liao 已提交
246 247 248 249 250
    return false;
  }
  return true;
}

H
Haojun Liao 已提交
251
static void doSetTagColumnData(STableScanBase* pTableScanInfo, SSDataBlock* pBlock, SExecTaskInfo* pTaskInfo,
252
                               int32_t rows) {
H
Haojun Liao 已提交
253 254 255
  if (pTableScanInfo->pseudoSup.numOfExprs > 0) {
    SExprSupp* pSup = &pTableScanInfo->pseudoSup;

256
    int32_t code = addTagPseudoColumnData(&pTableScanInfo->readHandle, pSup->pExprInfo, pSup->numOfExprs, pBlock, rows,
257
                                          GET_TASKID(pTaskInfo), &pTableScanInfo->metaCache);
H
Haojun Liao 已提交
258
    // ignore the table not exists error, since this table may have been dropped during the scan procedure.
H
Haojun Liao 已提交
259
    if (code != TSDB_CODE_SUCCESS && code != TSDB_CODE_PAR_TABLE_NOT_EXIST) {
H
Haojun Liao 已提交
260 261
      T_LONG_JMP(pTaskInfo->env, code);
    }
H
Haojun Liao 已提交
262 263 264

    // reset the error code.
    terrno = 0;
H
Haojun Liao 已提交
265 266 267
  }
}

268
bool applyLimitOffset(SLimitInfo* pLimitInfo, SSDataBlock* pBlock, SExecTaskInfo* pTaskInfo) {
269
  SLimit*     pLimit = &pLimitInfo->limit;
H
Haojun Liao 已提交
270
  const char* id = GET_TASKID(pTaskInfo);
271

272
  if (pLimitInfo->remainOffset > 0) {
273 274
    if (pLimitInfo->remainOffset >= pBlock->info.rows) {
      pLimitInfo->remainOffset -= pBlock->info.rows;
H
Haojun Liao 已提交
275
      blockDataEmpty(pBlock);
H
Haojun Liao 已提交
276
      qDebug("current block ignore due to offset, current:%" PRId64 ", %s", pLimitInfo->remainOffset, id);
277
      return false;
278
    } else {
279
      blockDataTrimFirstRows(pBlock, pLimitInfo->remainOffset);
280 281 282 283 284 285
      pLimitInfo->remainOffset = 0;
    }
  }

  if (pLimit->limit != -1 && pLimit->limit <= (pLimitInfo->numOfOutputRows + pBlock->info.rows)) {
    // limit the output rows
286
    int32_t keep = (int32_t)(pLimit->limit - pLimitInfo->numOfOutputRows);
287
    blockDataKeepFirstNRows(pBlock, keep);
288 289

    pLimitInfo->numOfOutputRows += pBlock->info.rows;
H
Haojun Liao 已提交
290
    qDebug("output limit %" PRId64 " has reached, %s", pLimit->limit, id);
291
    return true;
292
  }
293

294
  pLimitInfo->numOfOutputRows += pBlock->info.rows;
295
  return false;
296 297
}

H
Haojun Liao 已提交
298
static int32_t loadDataBlock(SOperatorInfo* pOperator, STableScanBase* pTableScanInfo, SSDataBlock* pBlock,
L
Liu Jicong 已提交
299
                             uint32_t* status) {
S
slzhou 已提交
300
  SExecTaskInfo*          pTaskInfo = pOperator->pTaskInfo;
301 302
  SStorageAPI* pAPI = &pTaskInfo->storageAPI;

303
  SFileBlockLoadRecorder* pCost = &pTableScanInfo->readRecorder;
H
Haojun Liao 已提交
304 305

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

H
Haojun Liao 已提交
308
  bool loadSMA = false;
H
Haojun Liao 已提交
309
  *status = pTableScanInfo->dataBlockLoadFlag;
H
Haojun Liao 已提交
310
  if (pOperator->exprSupp.pFilterInfo != NULL ||
311
      overlapWithTimeWindow(&pTableScanInfo->pdInfo.interval, &pBlock->info, pTableScanInfo->cond.order)) {
312 313 314 315
    (*status) = FUNC_DATA_REQUIRED_DATA_LOAD;
  }

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

  if (*status == FUNC_DATA_REQUIRED_FILTEROUT) {
X
Xiaoyu Wang 已提交
319
    qDebug("%s data block filter out, brange:%" PRId64 "-%" PRId64 ", rows:%" PRId64, GET_TASKID(pTaskInfo),
320
           pBlockInfo->window.skey, pBlockInfo->window.ekey, pBlockInfo->rows);
321
    pCost->filterOutBlocks += 1;
322
    pCost->totalRows += pBlock->info.rows;
323
    pAPI->tsdReader.tsdReaderReleaseDataBlock(pTableScanInfo->dataReader);
324 325
    return TSDB_CODE_SUCCESS;
  } else if (*status == FUNC_DATA_REQUIRED_NOT_LOAD) {
X
Xiaoyu Wang 已提交
326 327 328
    qDebug("%s data block skipped, brange:%" PRId64 "-%" PRId64 ", rows:%" PRId64 ", uid:%" PRIu64,
           GET_TASKID(pTaskInfo), pBlockInfo->window.skey, pBlockInfo->window.ekey, pBlockInfo->rows,
           pBlockInfo->id.uid);
G
Ganlin Zhao 已提交
329
    doSetTagColumnData(pTableScanInfo, pBlock, pTaskInfo, pBlock->info.rows);
330
    pCost->skipBlocks += 1;
331
    pAPI->tsdReader.tsdReaderReleaseDataBlock(pTableScanInfo->dataReader);
332
    return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
333
  } else if (*status == FUNC_DATA_REQUIRED_SMA_LOAD) {
334
    pCost->loadBlockStatis += 1;
L
Liu Jicong 已提交
335
    loadSMA = true;  // mark the operation of load sma;
H
Haojun Liao 已提交
336
    bool success = doLoadBlockSMA(pTableScanInfo, pBlock, pTaskInfo);
L
Liu Jicong 已提交
337
    if (success) {  // failed to load the block sma data, data block statistics does not exist, load data block instead
X
Xiaoyu Wang 已提交
338
      qDebug("%s data block SMA loaded, brange:%" PRId64 "-%" PRId64 ", rows:%" PRId64, GET_TASKID(pTaskInfo),
339
             pBlockInfo->window.skey, pBlockInfo->window.ekey, pBlockInfo->rows);
G
Ganlin Zhao 已提交
340
      doSetTagColumnData(pTableScanInfo, pBlock, pTaskInfo, pBlock->info.rows);
341
      pAPI->tsdReader.tsdReaderReleaseDataBlock(pTableScanInfo->dataReader);
342 343
      return TSDB_CODE_SUCCESS;
    } else {
344
      qDebug("%s failed to load SMA, since not all columns have SMA", GET_TASKID(pTaskInfo));
H
Haojun Liao 已提交
345
      *status = FUNC_DATA_REQUIRED_DATA_LOAD;
346
    }
H
Haojun Liao 已提交
347
  }
348

H
Haojun Liao 已提交
349
  ASSERT(*status == FUNC_DATA_REQUIRED_DATA_LOAD);
350

H
Haojun Liao 已提交
351
  // try to filter data block according to sma info
H
Haojun Liao 已提交
352
  if (pOperator->exprSupp.pFilterInfo != NULL && (!loadSMA)) {
353 354 355
    bool success = doLoadBlockSMA(pTableScanInfo, pBlock, pTaskInfo);
    if (success) {
      size_t size = taosArrayGetSize(pBlock->pDataBlock);
H
Haojun Liao 已提交
356
      bool   keep = doFilterByBlockSMA(pOperator->exprSupp.pFilterInfo, pBlock->pBlockAgg, size, pBlockInfo->rows);
357
      if (!keep) {
X
Xiaoyu Wang 已提交
358 359
        qDebug("%s data block filter out by block SMA, brange:%" PRId64 "-%" PRId64 ", rows:%" PRId64,
               GET_TASKID(pTaskInfo), pBlockInfo->window.skey, pBlockInfo->window.ekey, pBlockInfo->rows);
360 361 362
        pCost->filterOutBlocks += 1;
        (*status) = FUNC_DATA_REQUIRED_FILTEROUT;

363
        pAPI->tsdReader.tsdReaderReleaseDataBlock(pTableScanInfo->dataReader);
364 365
        return TSDB_CODE_SUCCESS;
      }
366
    }
H
Haojun Liao 已提交
367
  }
368

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

372
  // try to filter data block according to current results
373 374
  doDynamicPruneDataBlock(pOperator, pBlockInfo, status);
  if (*status == FUNC_DATA_REQUIRED_NOT_LOAD) {
X
Xiaoyu Wang 已提交
375 376
    qDebug("%s data block skipped due to dynamic prune, brange:%" PRId64 "-%" PRId64 ", rows:%" PRId64,
           GET_TASKID(pTaskInfo), pBlockInfo->window.skey, pBlockInfo->window.ekey, pBlockInfo->rows);
377
    pCost->skipBlocks += 1;
378
    pAPI->tsdReader.tsdReaderReleaseDataBlock(pTableScanInfo->dataReader);
379

380 381
    STableScanInfo* p1 = pOperator->info;
    if (taosHashGetSize(p1->pIgnoreTables) == taosArrayGetSize(p1->base.pTableListInfo->pTableList)) {
382 383 384 385
      *status = FUNC_DATA_REQUIRED_ALL_FILTEROUT;
    } else {
      *status = FUNC_DATA_REQUIRED_FILTEROUT;
    }
386 387 388
    return TSDB_CODE_SUCCESS;
  }

H
Haojun Liao 已提交
389 390
  pCost->totalCheckedRows += pBlock->info.rows;
  pCost->loadBlocks += 1;
391

392
  SSDataBlock* p = pAPI->tsdReader.tsdReaderRetrieveDataBlock(pTableScanInfo->dataReader, NULL);
H
Haojun Liao 已提交
393
  if (p == NULL) {
H
Haojun Liao 已提交
394
    return terrno;
H
Haojun Liao 已提交
395 396
  }

H
Haojun Liao 已提交
397
  ASSERT(p == pBlock);
398
  doSetTagColumnData(pTableScanInfo, pBlock, pTaskInfo, pBlock->info.rows);
399

H
Haojun Liao 已提交
400 401
  // restore the previous value
  pCost->totalRows -= pBlock->info.rows;
402

H
Haojun Liao 已提交
403
  if (pOperator->exprSupp.pFilterInfo != NULL) {
404
    int64_t st = taosGetTimestampUs();
H
Haojun Liao 已提交
405
    doFilter(pBlock, pOperator->exprSupp.pFilterInfo, &pTableScanInfo->matchInfo);
406

407 408
    double el = (taosGetTimestampUs() - st) / 1000.0;
    pTableScanInfo->readRecorder.filterTime += el;
409

410 411
    if (pBlock->info.rows == 0) {
      pCost->filterOutBlocks += 1;
D
dapan1121 已提交
412
      qDebug("%s data block filter out, brange:%" PRId64 "-%" PRId64 ", rows:%" PRId64 ", elapsed time:%.2f ms",
413 414 415 416
             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);
    }
417 418
  }

419
  bool limitReached = applyLimitOffset(&pTableScanInfo->limitInfo, pBlock, pTaskInfo);
X
Xiaoyu Wang 已提交
420
  if (limitReached) {  // set operator flag is done
421 422
    setOperatorCompleted(pOperator);
  }
423

H
Haojun Liao 已提交
424
  pCost->totalRows += pBlock->info.rows;
H
Haojun Liao 已提交
425 426 427
  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
428
static void prepareForDescendingScan(STableScanBase* pTableScanInfo, SqlFunctionCtx* pCtx, int32_t numOfOutput) {
H
Haojun Liao 已提交
429 430 431
  SET_REVERSE_SCAN_FLAG(pTableScanInfo);

  switchCtxOrder(pCtx, numOfOutput);
432
  pTableScanInfo->cond.order = TSDB_ORDER_DESC;
H
Haojun Liao 已提交
433 434
  STimeWindow* pTWindow = &pTableScanInfo->cond.twindows;
  TSWAP(pTWindow->skey, pTWindow->ekey);
H
Haojun Liao 已提交
435 436
}

437 438
typedef struct STableCachedVal {
  const char* pName;
439
  STag*       pTags;
440 441
} STableCachedVal;

442 443 444 445 446 447 448 449 450 451 452
static void freeTableCachedVal(void* param) {
  if (param == NULL) {
    return;
  }

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

H
Haojun Liao 已提交
453 454
static STableCachedVal* createTableCacheVal(const SMetaReader* pMetaReader) {
  STableCachedVal* pVal = taosMemoryMalloc(sizeof(STableCachedVal));
455
  pVal->pName = taosStrdup(pMetaReader->me.name);
H
Haojun Liao 已提交
456 457 458 459
  pVal->pTags = NULL;

  // only child table has tag value
  if (pMetaReader->me.type == TSDB_CHILD_TABLE) {
460
    STag* pTag = (STag*)pMetaReader->me.ctbEntry.pTags;
H
Haojun Liao 已提交
461 462 463 464 465 466 467
    pVal->pTags = taosMemoryMalloc(pTag->len);
    memcpy(pVal->pTags, pTag, pTag->len);
  }

  return pVal;
}

468 469
// const void *key, size_t keyLen, void *value
static void freeCachedMetaItem(const void* key, size_t keyLen, void* value) { freeTableCachedVal(value); }
470

471 472 473 474 475
static void doSetNullValue(SSDataBlock* pBlock, const SExprInfo* pExpr, int32_t numOfExpr) {
  for (int32_t j = 0; j < numOfExpr; ++j) {
    int32_t dstSlotId = pExpr[j].base.resSchema.slotId;

    SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, dstSlotId);
476
    colDataSetNNULL(pColInfoData, 0, pBlock->info.rows);
477 478 479
  }
}

480 481
int32_t addTagPseudoColumnData(SReadHandle* pHandle, const SExprInfo* pExpr, int32_t numOfExpr, SSDataBlock* pBlock,
                               int32_t rows, const char* idStr, STableMetaCacheInfo* pCache) {
482
  // currently only the tbname pseudo column
483
  if (numOfExpr <= 0) {
H
Haojun Liao 已提交
484
    return TSDB_CODE_SUCCESS;
485 486
  }

487
  int32_t code = 0;
488
  bool    freeReader = false;
489

490 491 492 493
  // backup the rows
  int32_t backupRows = pBlock->info.rows;
  pBlock->info.rows = rows;

494
  STableCachedVal val = {0};
495 496

  SMetaReader mr = {0};
497
  LRUHandle*  h = NULL;
498

499 500 501
  // todo refactor: extract method
  // the handling of the null data should be packed in the extracted method

502
  // 1. check if it is existed in meta cache
503
  if (pCache == NULL) {
H
Haojun Liao 已提交
504
    pHandle->api.metaReaderFn.initReader(&mr, pHandle->vnode, 0, &pHandle->api.metaFn);
505
    code = pHandle->api.metaReaderFn.getEntryGetUidCache(&mr, pBlock->info.id.uid);
506
    if (code != TSDB_CODE_SUCCESS) {
507
      // when encounter the TSDB_CODE_PAR_TABLE_NOT_EXIST error, we proceed.
H
Haojun Liao 已提交
508
      if (terrno == TSDB_CODE_PAR_TABLE_NOT_EXIST) {
S
slzhou 已提交
509 510
        qWarn("failed to get table meta, table may have been dropped, uid:0x%" PRIx64 ", code:%s, %s",
              pBlock->info.id.uid, tstrerror(terrno), idStr);
511 512 513

        // append null value before return to caller, since the caller will ignore this error code and proceed
        doSetNullValue(pBlock, pExpr, numOfExpr);
H
Haojun Liao 已提交
514
      } else {
S
slzhou 已提交
515 516
        qError("failed to get table meta, uid:0x%" PRIx64 ", code:%s, %s", pBlock->info.id.uid, tstrerror(terrno),
               idStr);
H
Haojun Liao 已提交
517
      }
518
      pHandle->api.metaReaderFn.clearReader(&mr);
519 520 521
      return terrno;
    }

522
    pHandle->api.metaReaderFn.readerReleaseLock(&mr);
523

524 525
    val.pName = mr.me.name;
    val.pTags = (STag*)mr.me.ctbEntry.pTags;
526 527

    freeReader = true;
528
  } else {
529 530
    pCache->metaFetch += 1;

H
Haojun Liao 已提交
531
    h = taosLRUCacheLookup(pCache->pTableMetaEntryCache, &pBlock->info.id.uid, sizeof(pBlock->info.id.uid));
532
    if (h == NULL) {
H
Haojun Liao 已提交
533
      pHandle->api.metaReaderFn.initReader(&mr, pHandle->vnode, 0, &pHandle->api.metaFn);
534
      code = pHandle->api.metaReaderFn.getEntryGetUidCache(&mr, pBlock->info.id.uid);
535
      if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
536
        if (terrno == TSDB_CODE_PAR_TABLE_NOT_EXIST) {
537
          qWarn("failed to get table meta, table may have been dropped, uid:0x%" PRIx64 ", code:%s, %s",
H
Haojun Liao 已提交
538
                pBlock->info.id.uid, tstrerror(terrno), idStr);
539 540
          // append null value before return to caller, since the caller will ignore this error code and proceed
          doSetNullValue(pBlock, pExpr, numOfExpr);
H
Haojun Liao 已提交
541
        } else {
H
Haojun Liao 已提交
542
          qError("failed to get table meta, uid:0x%" PRIx64 ", code:%s, %s", pBlock->info.id.uid, tstrerror(terrno),
543
                 idStr);
H
Haojun Liao 已提交
544
        }
545
        pHandle->api.metaReaderFn.clearReader(&mr);
546 547 548
        return terrno;
      }

549
      pHandle->api.metaReaderFn.readerReleaseLock(&mr);
550

H
Haojun Liao 已提交
551
      STableCachedVal* pVal = createTableCacheVal(&mr);
552

H
Haojun Liao 已提交
553
      val = *pVal;
554
      freeReader = true;
H
Haojun Liao 已提交
555

H
Haojun Liao 已提交
556
      int32_t ret = taosLRUCacheInsert(pCache->pTableMetaEntryCache, &pBlock->info.id.uid, sizeof(uint64_t), pVal,
557
                                       sizeof(STableCachedVal), freeCachedMetaItem, NULL, TAOS_LRU_PRIORITY_LOW);
558 559 560 561 562 563 564 565
      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 已提交
566

H
Haojun Liao 已提交
567
      taosLRUCacheRelease(pCache->pTableMetaEntryCache, h, false);
568
    }
H
Haojun Liao 已提交
569

570 571
    qDebug("retrieve table meta from cache:%" PRIu64 ", hit:%" PRIu64 " miss:%" PRIu64 ", %s", pCache->metaFetch,
           pCache->cacheHit, (pCache->metaFetch - pCache->cacheHit), idStr);
H
Haojun Liao 已提交
572
  }
573

574 575
  for (int32_t j = 0; j < numOfExpr; ++j) {
    const SExprInfo* pExpr1 = &pExpr[j];
576
    int32_t          dstSlotId = pExpr1->base.resSchema.slotId;
577 578

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

581
    int32_t functionId = pExpr1->pExpr->_function.functionId;
582 583 584

    // this is to handle the tbname
    if (fmIsScanPseudoColumnFunc(functionId)) {
585
      setTbNameColData(pBlock, pColInfoData, functionId, val.pName);
586
    } else {  // these are tags
wmmhello's avatar
wmmhello 已提交
587
      STagVal tagVal = {0};
588
      tagVal.cid = pExpr1->base.pParam[0].pCol->colId;
589
      const char* p = pHandle->api.metaFn.extractTagVal(val.pTags, pColInfoData->info.type, &tagVal);
wmmhello's avatar
wmmhello 已提交
590

591 592 593 594
      char* data = NULL;
      if (pColInfoData->info.type != TSDB_DATA_TYPE_JSON && p != NULL) {
        data = tTagValToData((const STagVal*)p, false);
      } else {
wmmhello's avatar
wmmhello 已提交
595
        data = (char*)p;
wmmhello's avatar
wmmhello 已提交
596
      }
597

H
Haojun Liao 已提交
598 599
      bool isNullVal = (data == NULL) || (pColInfoData->info.type == TSDB_DATA_TYPE_JSON && tTagIsJsonNull(data));
      if (isNullVal) {
600
        colDataSetNNULL(pColInfoData, 0, pBlock->info.rows);
H
Haojun Liao 已提交
601
      } else if (pColInfoData->info.type != TSDB_DATA_TYPE_JSON) {
D
dapan1121 已提交
602
        code = colDataSetNItems(pColInfoData, 0, data, pBlock->info.rows, false);
H
Haojun Liao 已提交
603 604 605
        if (IS_VAR_DATA_TYPE(((const STagVal*)p)->type)) {
          taosMemoryFree(data);
        }
D
dapan1121 已提交
606 607
        if (code) {
          if (freeReader) {
608
            pHandle->api.metaReaderFn.clearReader(&mr);
D
dapan1121 已提交
609 610 611
          }
          return code;
        }
L
Liu Jicong 已提交
612
      } else {  // todo opt for json tag
H
Haojun Liao 已提交
613
        for (int32_t i = 0; i < pBlock->info.rows; ++i) {
614
          colDataSetVal(pColInfoData, i, data, false);
H
Haojun Liao 已提交
615
        }
616 617 618 619
      }
    }
  }

620 621
  // restore the rows
  pBlock->info.rows = backupRows;
622
  if (freeReader) {
623
    pHandle->api.metaReaderFn.clearReader(&mr);
624 625
  }

H
Haojun Liao 已提交
626
  return TSDB_CODE_SUCCESS;
627 628
}

H
Haojun Liao 已提交
629
void setTbNameColData(const SSDataBlock* pBlock, SColumnInfoData* pColInfoData, int32_t functionId, const char* name) {
630 631 632
  struct SScalarFuncExecFuncs fpSet = {0};
  fmGetScalarFuncExecFuncs(functionId, &fpSet);

H
Haojun Liao 已提交
633
  size_t len = TSDB_TABLE_FNAME_LEN + VARSTR_HEADER_SIZE;
634
  char   buf[TSDB_TABLE_FNAME_LEN + VARSTR_HEADER_SIZE] = {0};
H
Haojun Liao 已提交
635 636 637
  STR_TO_VARSTR(buf, name)

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

H
Haojun Liao 已提交
639
  colInfoDataEnsureCapacity(&infoData, 1, false);
640
  colDataSetVal(&infoData, 0, buf, false);
641

H
Haojun Liao 已提交
642
  SScalarParam srcParam = {.numOfRows = pBlock->info.rows, .columnData = &infoData};
643
  SScalarParam param = {.columnData = pColInfoData};
H
Haojun Liao 已提交
644 645 646 647 648 649 650

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

D
dapan1121 已提交
651
  colDataDestroy(&infoData);
652 653
}

654
static SSDataBlock* doTableScanImpl(SOperatorInfo* pOperator) {
H
Haojun Liao 已提交
655
  STableScanInfo* pTableScanInfo = pOperator->info;
656
  SExecTaskInfo*  pTaskInfo = pOperator->pTaskInfo;
657 658
  SStorageAPI*    pAPI = &pTaskInfo->storageAPI;

L
Liu Jicong 已提交
659
  SSDataBlock*    pBlock = pTableScanInfo->pResBlock;
D
dapan1121 已提交
660 661
  bool            hasNext = false;
  int32_t         code = TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
662

663 664
  int64_t st = taosGetTimestampUs();

D
dapan1121 已提交
665
  while (true) {
666
    code = pAPI->tsdReader.tsdNextDataBlock(pTableScanInfo->base.dataReader, &hasNext);
D
dapan1121 已提交
667
    if (code) {
668
      pAPI->tsdReader.tsdReaderReleaseDataBlock(pTableScanInfo->base.dataReader);
D
dapan1121 已提交
669 670 671 672 673 674
      T_LONG_JMP(pTaskInfo->env, code);
    }

    if (!hasNext) {
      break;
    }
X
Xiaoyu Wang 已提交
675

676
    if (isTaskKilled(pTaskInfo)) {
677
      pAPI->tsdReader.tsdReaderReleaseDataBlock(pTableScanInfo->base.dataReader);
678
      T_LONG_JMP(pTaskInfo->env, pTaskInfo->code);
679
    }
H
Haojun Liao 已提交
680

681
    if (pOperator->status == OP_EXEC_DONE) {
682
      pAPI->tsdReader.tsdReaderReleaseDataBlock(pTableScanInfo->base.dataReader);
683 684 685
      break;
    }

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

D
dapan1121 已提交
692
    if (pBlock->info.id.uid) {
693
      pBlock->info.id.groupId = getTableGroupId(pTableScanInfo->base.pTableListInfo, pBlock->info.id.uid);
D
dapan1121 已提交
694
    }
695

696
    uint32_t status = 0;
697
    code = loadDataBlock(pOperator, &pTableScanInfo->base, pBlock, &status);
698
    if (code != TSDB_CODE_SUCCESS) {
699
      T_LONG_JMP(pTaskInfo->env, code);
700
    }
701

702 703 704 705
    if (status == FUNC_DATA_REQUIRED_ALL_FILTEROUT) {
      break;
    }

706 707 708
    // 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;
709
    }
710

H
Haojun Liao 已提交
711 712
    pOperator->resultInfo.totalRows = pTableScanInfo->base.readRecorder.totalRows;
    pTableScanInfo->base.readRecorder.elapsedTime += (taosGetTimestampUs() - st) / 1000.0;
713

H
Haojun Liao 已提交
714
    pOperator->cost.totalCost = pTableScanInfo->base.readRecorder.elapsedTime;
715
    return pBlock;
H
Haojun Liao 已提交
716 717 718 719
  }
  return NULL;
}

H
Haojun Liao 已提交
720
static SSDataBlock* doGroupedTableScan(SOperatorInfo* pOperator) {
H
Haojun Liao 已提交
721 722
  STableScanInfo* pTableScanInfo = pOperator->info;
  SExecTaskInfo*  pTaskInfo = pOperator->pTaskInfo;
723
  SStorageAPI* pAPI = &pTaskInfo->storageAPI;
H
Haojun Liao 已提交
724 725

  // The read handle is not initialized yet, since no qualified tables exists
H
Haojun Liao 已提交
726
  if (pTableScanInfo->base.dataReader == NULL || pOperator->status == OP_EXEC_DONE) {
H
Haojun Liao 已提交
727 728 729
    return NULL;
  }

730 731
  // do the ascending order traverse in the first place.
  while (pTableScanInfo->scanTimes < pTableScanInfo->scanInfo.numOfAsc) {
H
Haojun Liao 已提交
732 733 734
    SSDataBlock* p = doTableScanImpl(pOperator);
    if (p != NULL) {
      return p;
H
Haojun Liao 已提交
735 736
    }

737
    pTableScanInfo->scanTimes += 1;
738
    taosHashClear(pTableScanInfo->pIgnoreTables);
739

740
    if (pTableScanInfo->scanTimes < pTableScanInfo->scanInfo.numOfAsc) {
741
      setTaskStatus(pTaskInfo, TASK_NOT_COMPLETED);
G
Ganlin Zhao 已提交
742 743
      pTableScanInfo->base.scanFlag = MAIN_SCAN;
      pTableScanInfo->base.dataBlockLoadFlag = FUNC_DATA_REQUIRED_DATA_LOAD;
744
      qDebug("start to repeat ascending order scan data blocks due to query func required, %s", GET_TASKID(pTaskInfo));
H
Haojun Liao 已提交
745

746
      // do prepare for the next round table scan operation
747
      pAPI->tsdReader.tsdReaderResetStatus(pTableScanInfo->base.dataReader, &pTableScanInfo->base.cond);
H
Haojun Liao 已提交
748
    }
749
  }
H
Haojun Liao 已提交
750

751
  int32_t total = pTableScanInfo->scanInfo.numOfAsc + pTableScanInfo->scanInfo.numOfDesc;
752
  if (pTableScanInfo->scanTimes < total) {
H
Haojun Liao 已提交
753 754
    if (pTableScanInfo->base.cond.order == TSDB_ORDER_ASC) {
      prepareForDescendingScan(&pTableScanInfo->base, pOperator->exprSupp.pCtx, 0);
755
      pAPI->tsdReader.tsdReaderResetStatus(pTableScanInfo->base.dataReader, &pTableScanInfo->base.cond);
756
      qDebug("%s start to descending order scan data blocks due to query func required", GET_TASKID(pTaskInfo));
757
    }
H
Haojun Liao 已提交
758

759
    while (pTableScanInfo->scanTimes < total) {
H
Haojun Liao 已提交
760 761 762
      SSDataBlock* p = doTableScanImpl(pOperator);
      if (p != NULL) {
        return p;
763
      }
H
Haojun Liao 已提交
764

765
      pTableScanInfo->scanTimes += 1;
766
      taosHashClear(pTableScanInfo->pIgnoreTables);
H
Haojun Liao 已提交
767

768
      if (pTableScanInfo->scanTimes < total) {
769
        setTaskStatus(pTaskInfo, TASK_NOT_COMPLETED);
G
Ganlin Zhao 已提交
770
        pTableScanInfo->base.scanFlag = MAIN_SCAN;
H
Haojun Liao 已提交
771

772
        qDebug("%s start to repeat descending order scan data blocks", GET_TASKID(pTaskInfo));
773
        pAPI->tsdReader.tsdReaderResetStatus(pTableScanInfo->base.dataReader, &pTableScanInfo->base.cond);
774
      }
H
Haojun Liao 已提交
775 776 777
    }
  }

wmmhello's avatar
wmmhello 已提交
778 779 780 781 782 783
  return NULL;
}

static SSDataBlock* doTableScan(SOperatorInfo* pOperator) {
  STableScanInfo* pInfo = pOperator->info;
  SExecTaskInfo*  pTaskInfo = pOperator->pTaskInfo;
784
  SStorageAPI*    pAPI = &pTaskInfo->storageAPI;
wmmhello's avatar
wmmhello 已提交
785

786
  // scan table one by one sequentially
L
Liu Jicong 已提交
787
  if (pInfo->scanMode == TABLE_SCAN__TABLE_ORDER) {
X
Xiaoyu Wang 已提交
788
    int32_t       numOfTables = 0;  // tableListGetSize(pTaskInfo->pTableListInfo);
789
    STableKeyInfo tInfo = {0};
H
Haojun Liao 已提交
790

L
Liu Jicong 已提交
791
    while (1) {
H
Haojun Liao 已提交
792
      SSDataBlock* result = doGroupedTableScan(pOperator);
H
Haojun Liao 已提交
793
      if (result || (pOperator->status == OP_EXEC_DONE) || isTaskKilled(pTaskInfo)) {
L
Liu Jicong 已提交
794 795
        return result;
      }
H
Haojun Liao 已提交
796

L
Liu Jicong 已提交
797 798
      // if no data, switch to next table and continue scan
      pInfo->currentTable++;
799 800

      taosRLockLatch(&pTaskInfo->lock);
801
      numOfTables = tableListGetSize(pInfo->base.pTableListInfo);
802

H
Haojun Liao 已提交
803
      if (pInfo->currentTable >= numOfTables) {
H
Haojun Liao 已提交
804
        qDebug("all table checked in table list, total:%d, return NULL, %s", numOfTables, GET_TASKID(pTaskInfo));
805
        taosRUnLockLatch(&pTaskInfo->lock);
L
Liu Jicong 已提交
806 807
        return NULL;
      }
H
Haojun Liao 已提交
808

X
Xiaoyu Wang 已提交
809
      tInfo = *(STableKeyInfo*)tableListGetInfo(pInfo->base.pTableListInfo, pInfo->currentTable);
810 811
      taosRUnLockLatch(&pTaskInfo->lock);

812
      pAPI->tsdReader.tsdSetQueryTableList(pInfo->base.dataReader, &tInfo, 1);
813
      qDebug("set uid:%" PRIu64 " into scanner, total tables:%d, index:%d/%d %s", tInfo.uid, numOfTables,
H
Haojun Liao 已提交
814
             pInfo->currentTable, numOfTables, GET_TASKID(pTaskInfo));
H
Haojun Liao 已提交
815

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

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

831
      int32_t code = pAPI->tsdReader.tsdReaderOpen(pInfo->base.readHandle.vnode, &pInfo->base.cond, pList, num, pInfo->pResBlock,
832
                                    (void**)&pInfo->base.dataReader, GET_TASKID(pTaskInfo), pInfo->countOnly, &pInfo->pIgnoreTables);
833 834 835
      if (code != TSDB_CODE_SUCCESS) {
        T_LONG_JMP(pTaskInfo->env, code);
      }
836 837 838 839

      if (pInfo->pResBlock->info.capacity > pOperator->resultInfo.capacity) {
        pOperator->resultInfo.capacity = pInfo->pResBlock->info.capacity;
      }
wmmhello's avatar
wmmhello 已提交
840
    }
H
Haojun Liao 已提交
841

H
Haojun Liao 已提交
842
    SSDataBlock* result = doGroupedTableScan(pOperator);
843 844 845
    if (result != NULL) {
      return result;
    }
H
Haojun Liao 已提交
846

847
    if ((++pInfo->currentGroupId) >= tableListGetOutputGroups(pInfo->base.pTableListInfo)) {
H
Haojun Liao 已提交
848
      setOperatorCompleted(pOperator);
849 850
      return NULL;
    }
wmmhello's avatar
wmmhello 已提交
851

852 853
    // reset value for the next group data output
    pOperator->status = OP_OPENED;
854
    resetLimitInfoForNextGroup(&pInfo->base.limitInfo);
wmmhello's avatar
wmmhello 已提交
855

5
54liuyao 已提交
856
    int32_t        num = 0;
857
    STableKeyInfo* pList = NULL;
858
    tableListGetGroupList(pInfo->base.pTableListInfo, pInfo->currentGroupId, &pList, &num);
wmmhello's avatar
wmmhello 已提交
859

860 861
    pAPI->tsdReader.tsdSetQueryTableList(pInfo->base.dataReader, pList, num);
    pAPI->tsdReader.tsdReaderResetStatus(pInfo->base.dataReader, &pInfo->base.cond);
862
    pInfo->scanTimes = 0;
wmmhello's avatar
wmmhello 已提交
863

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

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

874 875
static int32_t getTableScannerExecInfo(struct SOperatorInfo* pOptr, void** pOptrExplain, uint32_t* len) {
  SFileBlockLoadRecorder* pRecorder = taosMemoryCalloc(1, sizeof(SFileBlockLoadRecorder));
876
  STableScanInfo*         pTableScanInfo = pOptr->info;
H
Haojun Liao 已提交
877
  *pRecorder = pTableScanInfo->base.readRecorder;
878 879 880 881 882
  *pOptrExplain = pRecorder;
  *len = sizeof(SFileBlockLoadRecorder);
  return 0;
}

883
static void destroyTableScanBase(STableScanBase* pBase, TsdReader* pAPI) {
884
  cleanupQueryTableDataCond(&pBase->cond);
H
Haojun Liao 已提交
885

886
  pAPI->tsdReaderClose(pBase->dataReader);
887
  pBase->dataReader = NULL;
888

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

893
  tableListDestroy(pBase->pTableListInfo);
894 895 896 897 898 899 900
  taosLRUCacheCleanup(pBase->metaCache.pTableMetaEntryCache);
  cleanupExprSupp(&pBase->pseudoSup);
}

static void destroyTableScanOperatorInfo(void* param) {
  STableScanInfo* pTableScanInfo = (STableScanInfo*)param;
  blockDataDestroy(pTableScanInfo->pResBlock);
901
  taosHashCleanup(pTableScanInfo->pIgnoreTables);
H
Haojun Liao 已提交
902
  destroyTableScanBase(&pTableScanInfo->base, &pTableScanInfo->base.readerAPI);
D
dapan1121 已提交
903
  taosMemoryFreeClear(param);
904 905
}

906
SOperatorInfo* createTableScanOperatorInfo(STableScanPhysiNode* pTableScanNode, SReadHandle* readHandle,
907
                                           STableListInfo* pTableListInfo, SExecTaskInfo* pTaskInfo) {
X
Xiaoyu Wang 已提交
908
  int32_t         code = 0;
H
Haojun Liao 已提交
909 910 911
  STableScanInfo* pInfo = taosMemoryCalloc(1, sizeof(STableScanInfo));
  SOperatorInfo*  pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
  if (pInfo == NULL || pOperator == NULL) {
912
    code = TSDB_CODE_OUT_OF_MEMORY;
913
    goto _error;
H
Haojun Liao 已提交
914 915
  }

916
  SScanPhysiNode*     pScanNode = &pTableScanNode->scan;
H
Haojun Liao 已提交
917
  SDataBlockDescNode* pDescNode = pScanNode->node.pOutputDataBlockDesc;
918 919

  int32_t numOfCols = 0;
X
Xiaoyu Wang 已提交
920
  code =
H
Haojun Liao 已提交
921
      extractColMatchInfo(pScanNode->pScanCols, pDescNode, &numOfCols, COL_MATCH_FROM_COL_ID, &pInfo->base.matchInfo);
922 923 924 925
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }

H
Haojun Liao 已提交
926
  initLimitInfo(pScanNode->node.pLimit, pScanNode->node.pSlimit, &pInfo->base.limitInfo);
H
Haojun Liao 已提交
927
  code = initQueryTableDataCond(&pInfo->base.cond, pTableScanNode);
928
  if (code != TSDB_CODE_SUCCESS) {
929
    goto _error;
930 931
  }

H
Haojun Liao 已提交
932
  if (pScanNode->pScanPseudoCols != NULL) {
H
Haojun Liao 已提交
933
    SExprSupp* pSup = &pInfo->base.pseudoSup;
H
Haojun Liao 已提交
934
    pSup->pExprInfo = createExprInfo(pScanNode->pScanPseudoCols, NULL, &pSup->numOfExprs);
935
    pSup->pCtx = createSqlFunctionCtx(pSup->pExprInfo, pSup->numOfExprs, &pSup->rowEntryInfoOffset, &pTaskInfo->storageAPI.functionStore);
936 937
  }

938
  pInfo->scanInfo = (SScanInfo){.numOfAsc = pTableScanNode->scanSeq[0], .numOfDesc = pTableScanNode->scanSeq[1]};
G
Ganlin Zhao 已提交
939
  pInfo->base.scanFlag = (pInfo->scanInfo.numOfAsc > 1) ? PRE_SCAN : MAIN_SCAN;
H
Haojun Liao 已提交
940

H
Haojun Liao 已提交
941 942
  pInfo->base.pdInfo.interval = extractIntervalInfo(pTableScanNode);
  pInfo->base.readHandle = *readHandle;
H
Haojun Liao 已提交
943 944
  pInfo->base.dataBlockLoadFlag = pTableScanNode->dataRequired;

945 946
  pInfo->sample.sampleRatio = pTableScanNode->ratio;
  pInfo->sample.seed = taosGetTimestampSec();
947

H
Haojun Liao 已提交
948
  pInfo->base.readerAPI = pTaskInfo->storageAPI.tsdReader;
H
Haojun Liao 已提交
949
  initResultSizeInfo(&pOperator->resultInfo, 4096);
H
Haojun Liao 已提交
950
  pInfo->pResBlock = createDataBlockFromDescNode(pDescNode);
X
Xiaoyu Wang 已提交
951
  //  blockDataEnsureCapacity(pInfo->pResBlock, pOperator->resultInfo.capacity);
H
Haojun Liao 已提交
952

H
Haojun Liao 已提交
953 954 955
  code = filterInitFromNode((SNode*)pTableScanNode->scan.node.pConditions, &pOperator->exprSupp.pFilterInfo, 0);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
H
Haojun Liao 已提交
956 957
  }

wmmhello's avatar
wmmhello 已提交
958
  pInfo->currentGroupId = -1;
959
  pInfo->assignBlockUid = pTableScanNode->assignBlockUid;
960
  pInfo->hasGroupByTag = pTableScanNode->pGroupTags ? true : false;
961

L
Liu Jicong 已提交
962 963
  setOperatorInfo(pOperator, "TableScanOperator", QUERY_NODE_PHYSICAL_PLAN_TABLE_SCAN, false, OP_NOT_OPENED, pInfo,
                  pTaskInfo);
964
  pOperator->exprSupp.numOfExprs = numOfCols;
965

966
  pInfo->base.pTableListInfo = pTableListInfo;
H
Haojun Liao 已提交
967 968
  pInfo->base.metaCache.pTableMetaEntryCache = taosLRUCacheInit(1024 * 128, -1, .5);
  if (pInfo->base.metaCache.pTableMetaEntryCache == NULL) {
969 970 971
    code = terrno;
    goto _error;
  }
972

D
dapan1121 已提交
973 974 975 976
  if (scanDebug) {
    pInfo->countOnly = true;
  }

H
Haojun Liao 已提交
977
  taosLRUCacheSetStrictCapacity(pInfo->base.metaCache.pTableMetaEntryCache, false);
978 979
  pOperator->fpSet = createOperatorFpSet(optrDummyOpenFn, doTableScan, NULL, destroyTableScanOperatorInfo,
                                         optrDefaultBufFn, getTableScannerExecInfo);
980 981 982

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

985
_error:
986 987 988
  if (pInfo != NULL) {
    destroyTableScanOperatorInfo(pInfo);
  }
989

990 991
  taosMemoryFreeClear(pOperator);
  pTaskInfo->code = code;
992
  return NULL;
H
Haojun Liao 已提交
993 994
}

995
SOperatorInfo* createTableSeqScanOperatorInfo(void* pReadHandle, SExecTaskInfo* pTaskInfo) {
H
Haojun Liao 已提交
996
  STableScanInfo* pInfo = taosMemoryCalloc(1, sizeof(STableScanInfo));
L
Liu Jicong 已提交
997
  SOperatorInfo*  pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
998

H
Haojun Liao 已提交
999
  pInfo->base.dataReader = pReadHandle;
L
Liu Jicong 已提交
1000
  //  pInfo->prevGroupId       = -1;
H
Haojun Liao 已提交
1001

L
Liu Jicong 已提交
1002 1003
  setOperatorInfo(pOperator, "TableSeqScanOperator", QUERY_NODE_PHYSICAL_PLAN_TABLE_SEQ_SCAN, false, OP_NOT_OPENED,
                  pInfo, pTaskInfo);
1004
  pOperator->fpSet = createOperatorFpSet(optrDummyOpenFn, doTableScanImpl, NULL, NULL, optrDefaultBufFn, NULL);
H
Haojun Liao 已提交
1005 1006 1007
  return pOperator;
}

1008
FORCE_INLINE void doClearBufferedBlocks(SStreamScanInfo* pInfo) {
5
54liuyao 已提交
1009
  qDebug("clear buff blocks:%d", (int32_t)taosArrayGetSize(pInfo->pBlockLists));
L
Liu Jicong 已提交
1010 1011
  taosArrayClear(pInfo->pBlockLists);
  pInfo->validBlockIndex = 0;
H
Haojun Liao 已提交
1012 1013
}

1014
static bool isSessionWindow(SStreamScanInfo* pInfo) {
H
Haojun Liao 已提交
1015
  return pInfo->windowSup.parentType == QUERY_NODE_PHYSICAL_PLAN_STREAM_SESSION;
5
54liuyao 已提交
1016 1017
}

1018
static bool isStateWindow(SStreamScanInfo* pInfo) {
1019
  return pInfo->windowSup.parentType == QUERY_NODE_PHYSICAL_PLAN_STREAM_STATE;
5
54liuyao 已提交
1020
}
5
54liuyao 已提交
1021

L
Liu Jicong 已提交
1022
static bool isIntervalWindow(SStreamScanInfo* pInfo) {
1023 1024 1025
  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 已提交
1026 1027 1028
}

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

1032 1033 1034 1035
static bool isSlidingWindow(SStreamScanInfo* pInfo) {
  return isIntervalWindow(pInfo) && pInfo->interval.interval != pInfo->interval.sliding;
}

1036
static void setGroupId(SStreamScanInfo* pInfo, SSDataBlock* pBlock, int32_t groupColIndex, int32_t rowIndex) {
1037 1038
  SColumnInfoData* pColInfo = taosArrayGet(pBlock->pDataBlock, groupColIndex);
  uint64_t*        groupCol = (uint64_t*)pColInfo->pData;
1039
  ASSERT(rowIndex < pBlock->info.rows);
1040
  pInfo->groupId = groupCol[rowIndex];
1041 1042
}

1043
void resetTableScanInfo(STableScanInfo* pTableScanInfo, STimeWindow* pWin, uint64_t ver) {
H
Haojun Liao 已提交
1044
  pTableScanInfo->base.cond.twindows = *pWin;
L
liuyao 已提交
1045
  pTableScanInfo->base.cond.startVersion = 0;
1046
  pTableScanInfo->base.cond.endVersion = ver;
L
Liu Jicong 已提交
1047 1048
  pTableScanInfo->scanTimes = 0;
  pTableScanInfo->currentGroupId = -1;
H
Haojun Liao 已提交
1049
  pTableScanInfo->base.readerAPI.tsdReaderClose(pTableScanInfo->base.dataReader);
H
Haojun Liao 已提交
1050
  pTableScanInfo->base.dataReader = NULL;
1051 1052
}

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

1057
  STableScanInfo*     pTableScanInfo = pTableScanOp->info;
H
Haojun Liao 已提交
1058
  SQueryTableDataCond cond = pTableScanInfo->base.cond;
1059 1060 1061 1062 1063 1064

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

  SExecTaskInfo* pTaskInfo = pTableScanOp->pTaskInfo;
1065
  SStorageAPI*   pAPI = &pTaskInfo->storageAPI;
1066 1067 1068

  SSDataBlock* pBlock = pTableScanInfo->pResBlock;
  STsdbReader* pReader = NULL;
1069
  int32_t      code = pAPI->tsdReader.tsdReaderOpen(pTableScanInfo->base.readHandle.vnode, &cond, &tblInfo, 1, pBlock,
1070
                                     (void**)&pReader, GET_TASKID(pTaskInfo), false, NULL);
1071 1072
  if (code != TSDB_CODE_SUCCESS) {
    terrno = code;
dengyihao's avatar
dengyihao 已提交
1073
    T_LONG_JMP(pTaskInfo->env, code);
1074 1075 1076
    return NULL;
  }

D
dapan1121 已提交
1077
  bool hasNext = false;
1078
  code = pAPI->tsdReader.tsdNextDataBlock(pReader, &hasNext);
1079 1080
  if (code != TSDB_CODE_SUCCESS) {
    terrno = code;
dengyihao's avatar
dengyihao 已提交
1081
    T_LONG_JMP(pTaskInfo->env, code);
1082 1083 1084
    return NULL;
  }

D
dapan1121 已提交
1085
  if (hasNext) {
1086
    /*SSDataBlock* p = */ pAPI->tsdReader.tsdReaderRetrieveDataBlock(pReader, NULL);
H
Haojun Liao 已提交
1087
    doSetTagColumnData(&pTableScanInfo->base, pBlock, pTaskInfo, pBlock->info.rows);
1088
    pBlock->info.id.groupId = getTableGroupId(pTableScanInfo->base.pTableListInfo, pBlock->info.id.uid);
1089 1090
  }

1091
  pAPI->tsdReader.tsdReaderClose(pReader);
D
dapan1121 已提交
1092
  qDebug("retrieve prev rows:%" PRId64 ", skey:%" PRId64 ", ekey:%" PRId64 " uid:%" PRIu64 ", max ver:%" PRId64
5
54liuyao 已提交
1093 1094
         ", suid:%" PRIu64,
         pBlock->info.rows, startTs, endTs, tbUid, maxVersion, cond.suid);
1095 1096

  return pBlock->info.rows > 0 ? pBlock : NULL;
1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107
}

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 已提交
1108
static uint64_t getGroupIdByUid(SStreamScanInfo* pInfo, uint64_t uid) {
1109
  STableScanInfo* pTableScanInfo = pInfo->pTableScanOp->info;
1110
  return getTableGroupId(pTableScanInfo->base.pTableListInfo, uid);
1111 1112
}

5
54liuyao 已提交
1113 1114 1115 1116 1117 1118 1119 1120
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 已提交
1121
static bool prepareRangeScan(SStreamScanInfo* pInfo, SSDataBlock* pBlock, int32_t* pRowIndex) {
5
54liuyao 已提交
1122 1123 1124
  if (pBlock->info.rows == 0) {
    return false;
  }
L
Liu Jicong 已提交
1125 1126 1127 1128 1129 1130 1131 1132 1133 1134
  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]};
1135 1136 1137
  SColumnInfoData* pGpCol = taosArrayGet(pBlock->pDataBlock, GROUPID_COLUMN_INDEX);
  uint64_t*        gpData = (uint64_t*)pGpCol->pData;
  uint64_t         groupId = gpData[*pRowIndex];
1138 1139 1140 1141 1142 1143

  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 已提交
1144
  setGroupId(pInfo, pBlock, GROUPID_COLUMN_INDEX, *pRowIndex);
1145 1146 1147 1148
  if (isSlidingWindow(pInfo)) {
    pInfo->updateWin.skey = calStartData[*pRowIndex];
    pInfo->updateWin.ekey = calEndData[*pRowIndex];
  }
L
Liu Jicong 已提交
1149 1150 1151
  (*pRowIndex)++;

  for (; *pRowIndex < pBlock->info.rows; (*pRowIndex)++) {
1152
    if (win.skey == startData[*pRowIndex] && groupId == gpData[*pRowIndex]) {
L
Liu Jicong 已提交
1153 1154 1155
      win.ekey = TMAX(win.ekey, endData[*pRowIndex]);
      continue;
    }
1156

1157
    if (win.skey == endData[*pRowIndex] && groupId == gpData[*pRowIndex]) {
L
Liu Jicong 已提交
1158 1159 1160
      win.skey = TMIN(win.skey, startData[*pRowIndex]);
      continue;
    }
1161

1162 1163
    ASSERT(!(win.skey > startData[*pRowIndex] && win.ekey < endData[*pRowIndex]) ||
           !(isInTimeWindow(&win, startData[*pRowIndex], 0) || isInTimeWindow(&win, endData[*pRowIndex], 0)));
L
Liu Jicong 已提交
1164 1165 1166
    break;
  }

1167
  STableScanInfo* pTScanInfo = pInfo->pTableScanOp->info;
L
liuyao 已提交
1168
  qDebug("prepare range scan start:%" PRId64 ",end:%" PRId64 ",maxVer:%" PRIu64, win.skey, win.ekey, pInfo->pUpdateInfo->maxDataVersion);
1169
  resetTableScanInfo(pInfo->pTableScanOp->info, &win, pInfo->pUpdateInfo->maxDataVersion);
1170
  pInfo->pTableScanOp->status = OP_OPENED;
L
Liu Jicong 已提交
1171 1172 1173
  return true;
}

5
54liuyao 已提交
1174
static STimeWindow getSlidingWindow(TSKEY* startTsCol, TSKEY* endTsCol, uint64_t* gpIdCol, SInterval* pInterval,
1175
                                    SDataBlockInfo* pDataBlockInfo, int32_t* pRowIndex, bool hasGroup) {
H
Haojun Liao 已提交
1176
  SResultRowInfo dumyInfo = {0};
5
54liuyao 已提交
1177
  dumyInfo.cur.pageId = -1;
1178
  STimeWindow win = getActiveTimeWindow(NULL, &dumyInfo, startTsCol[*pRowIndex], pInterval, TSDB_ORDER_ASC);
5
54liuyao 已提交
1179 1180
  STimeWindow endWin = win;
  STimeWindow preWin = win;
5
54liuyao 已提交
1181
  uint64_t    groupId = gpIdCol[*pRowIndex];
H
Haojun Liao 已提交
1182

5
54liuyao 已提交
1183
  while (1) {
1184 1185 1186
    if (hasGroup) {
      (*pRowIndex) += 1;
    } else {
5
54liuyao 已提交
1187
      while ((groupId == gpIdCol[(*pRowIndex)] && startTsCol[*pRowIndex] <= endWin.ekey)) {
5
54liuyao 已提交
1188 1189 1190 1191 1192
        (*pRowIndex) += 1;
        if ((*pRowIndex) == pDataBlockInfo->rows) {
          break;
        }
      }
1193
    }
5
54liuyao 已提交
1194

5
54liuyao 已提交
1195 1196 1197
    do {
      preWin = endWin;
      getNextTimeWindow(pInterval, &endWin, TSDB_ORDER_ASC);
1198
    } while (endTsCol[(*pRowIndex) - 1] >= endWin.skey);
5
54liuyao 已提交
1199
    endWin = preWin;
5
54liuyao 已提交
1200
    if (win.ekey == endWin.ekey || (*pRowIndex) == pDataBlockInfo->rows || groupId != gpIdCol[*pRowIndex]) {
5
54liuyao 已提交
1201 1202 1203 1204 1205 1206
      win.ekey = endWin.ekey;
      return win;
    }
    win.ekey = endWin.ekey;
  }
}
5
54liuyao 已提交
1207

L
Liu Jicong 已提交
1208
static SSDataBlock* doRangeScan(SStreamScanInfo* pInfo, SSDataBlock* pSDB, int32_t tsColIndex, int32_t* pRowIndex) {
L
liuyao 已提交
1209
  qInfo("do stream range scan. windows index:%d", *pRowIndex);
L
liuyao 已提交
1210
  bool prepareRes = true;
L
Liu Jicong 已提交
1211 1212 1213
  while (1) {
    SSDataBlock* pResult = NULL;
    pResult = doTableScan(pInfo->pTableScanOp);
L
liuyao 已提交
1214 1215
    if (!pResult) {
      prepareRes = prepareRangeScan(pInfo, pSDB, pRowIndex);
L
Liu Jicong 已提交
1216 1217 1218 1219
      // scan next window data
      pResult = doTableScan(pInfo->pTableScanOp);
    }
    if (!pResult) {
L
liuyao 已提交
1220 1221 1222
      if (prepareRes) {
        continue;
      }
L
Liu Jicong 已提交
1223 1224
      blockDataCleanup(pSDB);
      *pRowIndex = 0;
5
54liuyao 已提交
1225
      pInfo->updateWin = (STimeWindow){.skey = INT64_MIN, .ekey = INT64_MAX};
H
Hongze Cheng 已提交
1226
      STableScanInfo* pTableScanInfo = pInfo->pTableScanOp->info;
H
Haojun Liao 已提交
1227
      pTableScanInfo->base.readerAPI.tsdReaderClose(pTableScanInfo->base.dataReader);
H
Haojun Liao 已提交
1228
      pTableScanInfo->base.dataReader = NULL;
1229 1230
      return NULL;
    }
L
Liu Jicong 已提交
1231

H
Haojun Liao 已提交
1232
    doFilter(pResult, pInfo->pTableScanOp->exprSupp.pFilterInfo, NULL);
1233 1234 1235 1236
    if (pResult->info.rows == 0) {
      continue;
    }

1237 1238 1239 1240 1241 1242 1243 1244
    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 已提交
1245 1246
            bool             isNull = colDataIsNull(pSrcCol, tmpBlock->info.rows, i, NULL);
            char*            pSrcData = colDataGetData(pSrcCol, i);
1247
            colDataSetVal(pDestCol, pResult->info.rows, pSrcData, isNull);
1248 1249 1250 1251
          }
          pResult->info.rows++;
        }
      }
H
Haojun Liao 已提交
1252 1253 1254

      blockDataDestroy(tmpBlock);

1255 1256 1257 1258
      if (pResult->info.rows > 0) {
        pResult->info.calWin = pInfo->updateWin;
        return pResult;
      }
H
Haojun Liao 已提交
1259
    } else if (pResult->info.id.groupId == pInfo->groupId) {
5
54liuyao 已提交
1260
      pResult->info.calWin = pInfo->updateWin;
1261
      return pResult;
5
54liuyao 已提交
1262 1263
    }
  }
1264
}
1265

1266
static int32_t getPreSessionWindow(SStreamAggSupporter* pAggSup, TSKEY startTs, TSKEY endTs, uint64_t groupId,
X
Xiaoyu Wang 已提交
1267
                                   SSessionKey* pKey) {
1268 1269 1270
  pKey->win.skey = startTs;
  pKey->win.ekey = endTs;
  pKey->groupId = groupId;
X
Xiaoyu Wang 已提交
1271

1272 1273
  void* pCur = pAggSup->stateStore.streamStateSessionSeekKeyCurrentPrev(pAggSup->pState, pKey);
  int32_t          code = pAggSup->stateStore.streamStateSessionGetKVByCur(pCur, pKey, NULL, 0);
1274 1275 1276
  if (code != TSDB_CODE_SUCCESS) {
    SET_SESSION_WIN_KEY_INVALID(pKey);
  }
D
dapan1121 已提交
1277 1278

  taosMemoryFree(pCur);
1279 1280 1281
  return code;
}

1282
static int32_t generateSessionScanRange(SStreamScanInfo* pInfo, SSDataBlock* pSrcBlock, SSDataBlock* pDestBlock) {
5
54liuyao 已提交
1283
  blockDataCleanup(pDestBlock);
1284 1285
  if (pSrcBlock->info.rows == 0) {
    return TSDB_CODE_SUCCESS;
1286
  }
1287
  int32_t code = blockDataEnsureCapacity(pDestBlock, pSrcBlock->info.rows);
1288
  if (code != TSDB_CODE_SUCCESS) {
1289
    return code;
L
Liu Jicong 已提交
1290
  }
1291 1292
  ASSERT(taosArrayGetSize(pSrcBlock->pDataBlock) >= 3);
  SColumnInfoData* pStartTsCol = taosArrayGet(pSrcBlock->pDataBlock, START_TS_COLUMN_INDEX);
L
Liu Jicong 已提交
1293
  TSKEY*           startData = (TSKEY*)pStartTsCol->pData;
1294
  SColumnInfoData* pEndTsCol = taosArrayGet(pSrcBlock->pDataBlock, END_TS_COLUMN_INDEX);
L
Liu Jicong 已提交
1295
  TSKEY*           endData = (TSKEY*)pEndTsCol->pData;
1296 1297
  SColumnInfoData* pUidCol = taosArrayGet(pSrcBlock->pDataBlock, UID_COLUMN_INDEX);
  uint64_t*        uidCol = (uint64_t*)pUidCol->pData;
L
Liu Jicong 已提交
1298

1299 1300
  SColumnInfoData* pDestStartCol = taosArrayGet(pDestBlock->pDataBlock, START_TS_COLUMN_INDEX);
  SColumnInfoData* pDestEndCol = taosArrayGet(pDestBlock->pDataBlock, END_TS_COLUMN_INDEX);
5
54liuyao 已提交
1301
  SColumnInfoData* pDestUidCol = taosArrayGet(pDestBlock->pDataBlock, UID_COLUMN_INDEX);
1302
  SColumnInfoData* pDestGpCol = taosArrayGet(pDestBlock->pDataBlock, GROUPID_COLUMN_INDEX);
5
54liuyao 已提交
1303 1304
  SColumnInfoData* pDestCalStartTsCol = taosArrayGet(pDestBlock->pDataBlock, CALCULATE_START_TS_COLUMN_INDEX);
  SColumnInfoData* pDestCalEndTsCol = taosArrayGet(pDestBlock->pDataBlock, CALCULATE_END_TS_COLUMN_INDEX);
H
Haojun Liao 已提交
1305
  int64_t          ver = pSrcBlock->info.version - 1;
1306
  for (int32_t i = 0; i < pSrcBlock->info.rows; i++) {
H
Haojun Liao 已提交
1307
    uint64_t groupId = getGroupIdByData(pInfo, uidCol[i], startData[i], ver);
L
Liu Jicong 已提交
1308
    // gap must be 0.
5
54liuyao 已提交
1309
    SSessionKey startWin = {0};
1310
    getCurSessionWindow(pInfo->windowSup.pStreamAggSup, startData[i], startData[i], groupId, &startWin);
5
54liuyao 已提交
1311
    if (IS_INVALID_SESSION_WIN_KEY(startWin)) {
L
Liu Jicong 已提交
1312 1313 1314
      // window has been closed.
      continue;
    }
5
54liuyao 已提交
1315 1316
    SSessionKey endWin = {0};
    getCurSessionWindow(pInfo->windowSup.pStreamAggSup, endData[i], endData[i], groupId, &endWin);
X
Xiaoyu Wang 已提交
1317
    if (IS_INVALID_SESSION_WIN_KEY(endWin)) {
1318 1319 1320 1321
      getPreSessionWindow(pInfo->windowSup.pStreamAggSup, endData[i], endData[i], groupId, &endWin);
    }
    if (IS_INVALID_SESSION_WIN_KEY(startWin)) {
      // window has been closed.
X
Xiaoyu Wang 已提交
1322
      qError("generate session scan range failed. rang start:%" PRIx64 ", end:%" PRIx64, startData[i], endData[i]);
1323 1324
      continue;
    }
1325 1326
    colDataSetVal(pDestStartCol, i, (const char*)&startWin.win.skey, false);
    colDataSetVal(pDestEndCol, i, (const char*)&endWin.win.ekey, false);
5
54liuyao 已提交
1327

1328
    colDataSetNULL(pDestUidCol, i);
1329
    colDataSetVal(pDestGpCol, i, (const char*)&groupId, false);
1330 1331
    colDataSetNULL(pDestCalStartTsCol, i);
    colDataSetNULL(pDestCalEndTsCol, i);
1332
    pDestBlock->info.rows++;
L
Liu Jicong 已提交
1333
  }
1334
  return TSDB_CODE_SUCCESS;
L
Liu Jicong 已提交
1335
}
1336 1337 1338 1339 1340 1341

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

1344 1345
  SColumnInfoData* pSrcStartTsCol = (SColumnInfoData*)taosArrayGet(pSrcBlock->pDataBlock, START_TS_COLUMN_INDEX);
  SColumnInfoData* pSrcEndTsCol = (SColumnInfoData*)taosArrayGet(pSrcBlock->pDataBlock, END_TS_COLUMN_INDEX);
1346 1347
  SColumnInfoData* pSrcUidCol = taosArrayGet(pSrcBlock->pDataBlock, UID_COLUMN_INDEX);
  SColumnInfoData* pSrcGpCol = taosArrayGet(pSrcBlock->pDataBlock, GROUPID_COLUMN_INDEX);
5
54liuyao 已提交
1348

L
Liu Jicong 已提交
1349
  uint64_t* srcUidData = (uint64_t*)pSrcUidCol->pData;
1350
  ASSERT(pSrcStartTsCol->info.type == TSDB_DATA_TYPE_TIMESTAMP);
5
54liuyao 已提交
1351 1352
  TSKEY*  srcStartTsCol = (TSKEY*)pSrcStartTsCol->pData;
  TSKEY*  srcEndTsCol = (TSKEY*)pSrcEndTsCol->pData;
H
Haojun Liao 已提交
1353
  int64_t ver = pSrcBlock->info.version - 1;
5
54liuyao 已提交
1354 1355 1356 1357 1358

  if (pInfo->partitionSup.needCalc && srcStartTsCol[0] != srcEndTsCol[0]) {
    uint64_t     srcUid = srcUidData[0];
    TSKEY        startTs = srcStartTsCol[0];
    TSKEY        endTs = srcEndTsCol[0];
H
Haojun Liao 已提交
1359
    SSDataBlock* pPreRes = readPreVersionData(pInfo->pTableScanOp, srcUid, startTs, endTs, ver);
5
54liuyao 已提交
1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386
    printDataBlock(pPreRes, "pre res");
    blockDataCleanup(pSrcBlock);
    int32_t code = blockDataEnsureCapacity(pSrcBlock, pPreRes->info.rows);
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

    SColumnInfoData* pTsCol = (SColumnInfoData*)taosArrayGet(pPreRes->pDataBlock, pInfo->primaryTsIndex);
    rows = pPreRes->info.rows;

    for (int32_t i = 0; i < rows; i++) {
      uint64_t groupId = calGroupIdByData(&pInfo->partitionSup, pInfo->pPartScalarSup, pPreRes, i);
      appendOneRowToStreamSpecialBlock(pSrcBlock, ((TSKEY*)pTsCol->pData) + i, ((TSKEY*)pTsCol->pData) + i, &srcUid,
                                       &groupId, NULL);
    }
    printDataBlock(pSrcBlock, "new delete");
  }
  uint64_t* srcGp = (uint64_t*)pSrcGpCol->pData;
  srcStartTsCol = (TSKEY*)pSrcStartTsCol->pData;
  srcEndTsCol = (TSKEY*)pSrcEndTsCol->pData;
  srcUidData = (uint64_t*)pSrcUidCol->pData;

  int32_t code = blockDataEnsureCapacity(pDestBlock, rows);
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

1387 1388
  SColumnInfoData* pStartTsCol = taosArrayGet(pDestBlock->pDataBlock, START_TS_COLUMN_INDEX);
  SColumnInfoData* pEndTsCol = taosArrayGet(pDestBlock->pDataBlock, END_TS_COLUMN_INDEX);
1389
  SColumnInfoData* pDeUidCol = taosArrayGet(pDestBlock->pDataBlock, UID_COLUMN_INDEX);
1390 1391 1392
  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);
1393
  for (int32_t i = 0; i < rows;) {
1394
    uint64_t srcUid = srcUidData[i];
5
54liuyao 已提交
1395 1396
    uint64_t groupId = srcGp[i];
    if (groupId == 0) {
H
Haojun Liao 已提交
1397
      groupId = getGroupIdByData(pInfo, srcUid, srcStartTsCol[i], ver);
5
54liuyao 已提交
1398 1399
    }
    TSKEY calStartTs = srcStartTsCol[i];
1400
    colDataSetVal(pCalStartTsCol, pDestBlock->info.rows, (const char*)(&calStartTs), false);
5
54liuyao 已提交
1401
    STimeWindow win = getSlidingWindow(srcStartTsCol, srcEndTsCol, srcGp, &pInfo->interval, &pSrcBlock->info, &i,
1402 1403
                                       pInfo->partitionSup.needCalc);
    TSKEY       calEndTs = srcStartTsCol[i - 1];
1404 1405 1406 1407 1408
    colDataSetVal(pCalEndTsCol, pDestBlock->info.rows, (const char*)(&calEndTs), false);
    colDataSetVal(pDeUidCol, pDestBlock->info.rows, (const char*)(&srcUid), false);
    colDataSetVal(pStartTsCol, pDestBlock->info.rows, (const char*)(&win.skey), false);
    colDataSetVal(pEndTsCol, pDestBlock->info.rows, (const char*)(&win.ekey), false);
    colDataSetVal(pGpCol, pDestBlock->info.rows, (const char*)(&groupId), false);
1409
    pDestBlock->info.rows++;
5
54liuyao 已提交
1410
  }
1411 1412
  return TSDB_CODE_SUCCESS;
}
1413

1414
static int32_t generateDeleteResultBlock(SStreamScanInfo* pInfo, SSDataBlock* pSrcBlock, SSDataBlock* pDestBlock) {
5
54liuyao 已提交
1415 1416 1417
  blockDataCleanup(pDestBlock);
  int32_t rows = pSrcBlock->info.rows;
  if (rows == 0) {
1418 1419
    return TSDB_CODE_SUCCESS;
  }
5
54liuyao 已提交
1420
  int32_t code = blockDataEnsureCapacity(pDestBlock, rows);
1421 1422 1423 1424
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

5
54liuyao 已提交
1425 1426 1427 1428 1429 1430 1431 1432 1433
  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;
H
Haojun Liao 已提交
1434
  int64_t ver = pSrcBlock->info.version - 1;
1435
  for (int32_t i = 0; i < pSrcBlock->info.rows; i++) {
5
54liuyao 已提交
1436 1437
    uint64_t srcUid = srcUidData[i];
    uint64_t groupId = srcGp[i];
L
Liu Jicong 已提交
1438
    char*    tbname[VARSTR_HEADER_SIZE + TSDB_TABLE_NAME_LEN] = {0};
5
54liuyao 已提交
1439
    if (groupId == 0) {
H
Haojun Liao 已提交
1440
      groupId = getGroupIdByData(pInfo, srcUid, srcStartTsCol[i], ver);
5
54liuyao 已提交
1441
    }
L
Liu Jicong 已提交
1442
    if (pInfo->tbnameCalSup.pExprInfo) {
1443
      void* parTbname = NULL;
1444
      pInfo->stateStore.streamStateGetParName(pInfo->pStreamScanOp->pTaskInfo->streamInfo.pState, groupId, &parTbname);
1445

L
Liu Jicong 已提交
1446 1447
      memcpy(varDataVal(tbname), parTbname, TSDB_TABLE_NAME_LEN);
      varDataSetLen(tbname, strlen(varDataVal(tbname)));
1448
      pInfo->stateStore.streamStateFreeVal(parTbname);
L
Liu Jicong 已提交
1449 1450 1451
    }
    appendOneRowToStreamSpecialBlock(pDestBlock, srcStartTsCol + i, srcEndTsCol + i, srcUidData + i, &groupId,
                                     tbname[0] == 0 ? NULL : tbname);
1452 1453 1454 1455
  }
  return TSDB_CODE_SUCCESS;
}

1456 1457 1458 1459
static int32_t generateScanRange(SStreamScanInfo* pInfo, SSDataBlock* pSrcBlock, SSDataBlock* pDestBlock) {
  int32_t code = TSDB_CODE_SUCCESS;
  if (isIntervalWindow(pInfo)) {
    code = generateIntervalScanRange(pInfo, pSrcBlock, pDestBlock);
1460
  } else if (isSessionWindow(pInfo) || isStateWindow(pInfo)) {
1461
    code = generateSessionScanRange(pInfo, pSrcBlock, pDestBlock);
5
54liuyao 已提交
1462 1463
  } else {
    code = generateDeleteResultBlock(pInfo, pSrcBlock, pDestBlock);
1464
  }
1465
  pDestBlock->info.type = STREAM_CLEAR;
1466
  pDestBlock->info.version = pSrcBlock->info.version;
1467
  pDestBlock->info.dataLoad = 1;
1468 1469 1470 1471
  blockDataUpdateTsWindow(pDestBlock, 0);
  return code;
}

5
54liuyao 已提交
1472
static void calBlockTbName(SStreamScanInfo* pInfo, SSDataBlock* pBlock) {
1473
  SExprSupp*    pTbNameCalSup = &pInfo->tbnameCalSup;
5
54liuyao 已提交
1474 1475
  blockDataCleanup(pInfo->pCreateTbRes);
  if (pInfo->tbnameCalSup.numOfExprs == 0 && pInfo->tagCalSup.numOfExprs == 0) {
L
Liu Jicong 已提交
1476
    pBlock->info.parTbName[0] = 0;
L
Liu Jicong 已提交
1477
  } else {
5
54liuyao 已提交
1478
    appendCreateTableRow(pInfo->pStreamScanOp->pTaskInfo->streamInfo.pState, &pInfo->tbnameCalSup, &pInfo->tagCalSup,
1479
                         pBlock->info.id.groupId, pBlock, 0, pInfo->pCreateTbRes, &pInfo->stateStore);
L
Liu Jicong 已提交
1480
  }
L
Liu Jicong 已提交
1481 1482
}

1483 1484
void appendOneRowToStreamSpecialBlock(SSDataBlock* pBlock, TSKEY* pStartTs, TSKEY* pEndTs, uint64_t* pUid,
                                      uint64_t* pGp, void* pTbName) {
1485 1486
  SColumnInfoData* pStartTsCol = taosArrayGet(pBlock->pDataBlock, START_TS_COLUMN_INDEX);
  SColumnInfoData* pEndTsCol = taosArrayGet(pBlock->pDataBlock, END_TS_COLUMN_INDEX);
1487 1488
  SColumnInfoData* pUidCol = taosArrayGet(pBlock->pDataBlock, UID_COLUMN_INDEX);
  SColumnInfoData* pGpCol = taosArrayGet(pBlock->pDataBlock, GROUPID_COLUMN_INDEX);
1489 1490
  SColumnInfoData* pCalStartCol = taosArrayGet(pBlock->pDataBlock, CALCULATE_START_TS_COLUMN_INDEX);
  SColumnInfoData* pCalEndCol = taosArrayGet(pBlock->pDataBlock, CALCULATE_END_TS_COLUMN_INDEX);
1491
  SColumnInfoData* pTableCol = taosArrayGet(pBlock->pDataBlock, TABLE_NAME_COLUMN_INDEX);
1492 1493 1494 1495 1496 1497 1498
  colDataSetVal(pStartTsCol, pBlock->info.rows, (const char*)pStartTs, false);
  colDataSetVal(pEndTsCol, pBlock->info.rows, (const char*)pEndTs, false);
  colDataSetVal(pUidCol, pBlock->info.rows, (const char*)pUid, false);
  colDataSetVal(pGpCol, pBlock->info.rows, (const char*)pGp, false);
  colDataSetVal(pCalStartCol, pBlock->info.rows, (const char*)pStartTs, false);
  colDataSetVal(pCalEndCol, pBlock->info.rows, (const char*)pEndTs, false);
  colDataSetVal(pTableCol, pBlock->info.rows, (const char*)pTbName, pTbName == NULL);
1499
  pBlock->info.rows++;
5
54liuyao 已提交
1500 1501
}

1502
static void checkUpdateData(SStreamScanInfo* pInfo, bool invertible, SSDataBlock* pBlock, bool out) {
1503 1504
  if (out) {
    blockDataCleanup(pInfo->pUpdateDataRes);
5
54liuyao 已提交
1505
    blockDataEnsureCapacity(pInfo->pUpdateDataRes, pBlock->info.rows * 2);
1506
  }
1507 1508
  SColumnInfoData* pColDataInfo = taosArrayGet(pBlock->pDataBlock, pInfo->primaryTsIndex);
  ASSERT(pColDataInfo->info.type == TSDB_DATA_TYPE_TIMESTAMP);
5
54liuyao 已提交
1509
  TSKEY* tsCol = (TSKEY*)pColDataInfo->pData;
1510
  bool   tableInserted = pInfo->stateStore.updateInfoIsTableInserted(pInfo->pUpdateInfo, pBlock->info.id.uid);
1511
  for (int32_t rowId = 0; rowId < pBlock->info.rows; rowId++) {
5
54liuyao 已提交
1512 1513
    SResultRowInfo dumyInfo;
    dumyInfo.cur.pageId = -1;
L
Liu Jicong 已提交
1514
    bool        isClosed = false;
5
54liuyao 已提交
1515
    STimeWindow win = {.skey = INT64_MIN, .ekey = INT64_MAX};
X
Xiaoyu Wang 已提交
1516
    bool        overDue = isOverdue(tsCol[rowId], &pInfo->twAggSup);
1517 1518 1519 1520 1521
    if (pInfo->igExpired && overDue) {
      continue;
    }

    if (tableInserted && overDue) {
5
54liuyao 已提交
1522 1523 1524
      win = getActiveTimeWindow(NULL, &dumyInfo, tsCol[rowId], &pInfo->interval, TSDB_ORDER_ASC);
      isClosed = isCloseWindow(&win, &pInfo->twAggSup);
    }
5
54liuyao 已提交
1525
    // must check update info first.
1526
    bool update = pInfo->stateStore.updateInfoIsUpdated(pInfo->pUpdateInfo, pBlock->info.id.uid, tsCol[rowId]);
L
Liu Jicong 已提交
1527
    bool closedWin = isClosed && isSignleIntervalWindow(pInfo) &&
1528
                     isDeletedStreamWindow(&win, pBlock->info.id.groupId, pInfo->pState, &pInfo->twAggSup, &pInfo->stateStore);
L
Liu Jicong 已提交
1529
    if ((update || closedWin) && out) {
L
Liu Jicong 已提交
1530
      qDebug("stream update check not pass, update %d, closedWin %d", update, closedWin);
5
54liuyao 已提交
1531
      uint64_t gpId = 0;
H
Haojun Liao 已提交
1532
      appendOneRowToStreamSpecialBlock(pInfo->pUpdateDataRes, tsCol + rowId, tsCol + rowId, &pBlock->info.id.uid, &gpId,
1533
                                       NULL);
5
54liuyao 已提交
1534 1535
      if (closedWin && pInfo->partitionSup.needCalc) {
        gpId = calGroupIdByData(&pInfo->partitionSup, pInfo->pPartScalarSup, pBlock, rowId);
S
slzhou 已提交
1536 1537
        appendOneRowToStreamSpecialBlock(pInfo->pUpdateDataRes, tsCol + rowId, tsCol + rowId, &pBlock->info.id.uid,
                                         &gpId, NULL);
5
54liuyao 已提交
1538
      }
1539 1540
    }
  }
1541 1542
  if (out && pInfo->pUpdateDataRes->info.rows > 0) {
    pInfo->pUpdateDataRes->info.version = pBlock->info.version;
1543
    pInfo->pUpdateDataRes->info.dataLoad = 1;
1544
    blockDataUpdateTsWindow(pInfo->pUpdateDataRes, 0);
1545
    pInfo->pUpdateDataRes->info.type = pInfo->partitionSup.needCalc ? STREAM_DELETE_DATA : STREAM_CLEAR;
5
54liuyao 已提交
1546 1547
  }
}
L
Liu Jicong 已提交
1548

1549
static int32_t setBlockIntoRes(SStreamScanInfo* pInfo, const SSDataBlock* pBlock, bool filter) {
L
Liu Jicong 已提交
1550 1551
  SDataBlockInfo* pBlockInfo = &pInfo->pRes->info;
  SOperatorInfo*  pOperator = pInfo->pStreamScanOp;
L
Liu Jicong 已提交
1552
  SExecTaskInfo*  pTaskInfo = pOperator->pTaskInfo;
L
Liu Jicong 已提交
1553

1554 1555
  blockDataEnsureCapacity(pInfo->pRes, pBlock->info.rows);

1556 1557 1558 1559
  pBlockInfo->rows = pBlock->info.rows;
  pBlockInfo->id.uid = pBlock->info.id.uid;
  pBlockInfo->type = STREAM_NORMAL;
  pBlockInfo->version = pBlock->info.version;
L
Liu Jicong 已提交
1560

1561
  STableScanInfo* pTableScanInfo = pInfo->pTableScanOp->info;
1562
  pBlockInfo->id.groupId = getTableGroupId(pTableScanInfo->base.pTableListInfo, pBlock->info.id.uid);
L
Liu Jicong 已提交
1563 1564

  // todo extract method
H
Haojun Liao 已提交
1565 1566 1567
  for (int32_t i = 0; i < taosArrayGetSize(pInfo->matchInfo.pList); ++i) {
    SColMatchItem* pColMatchInfo = taosArrayGet(pInfo->matchInfo.pList, i);
    if (!pColMatchInfo->needOutput) {
L
Liu Jicong 已提交
1568 1569 1570 1571 1572 1573 1574
      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 已提交
1575
        SColumnInfoData* pDst = taosArrayGet(pInfo->pRes->pDataBlock, pColMatchInfo->dstSlotId);
1576
        colDataAssign(pDst, pResCol, pBlock->info.rows, &pInfo->pRes->info);
L
Liu Jicong 已提交
1577 1578 1579 1580 1581 1582 1583
        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 已提交
1584
      SColumnInfoData* pDst = taosArrayGet(pInfo->pRes->pDataBlock, pColMatchInfo->dstSlotId);
1585
      colDataSetNNULL(pDst, 0, pBlockInfo->rows);
L
Liu Jicong 已提交
1586 1587 1588 1589 1590
    }
  }

  // currently only the tbname pseudo column
  if (pInfo->numOfPseudoExpr > 0) {
L
Liu Jicong 已提交
1591
    int32_t code = addTagPseudoColumnData(&pInfo->readHandle, pInfo->pPseudoExpr, pInfo->numOfPseudoExpr, pInfo->pRes,
1592
                                          pBlockInfo->rows, GET_TASKID(pTaskInfo), &pTableScanInfo->base.metaCache);
K
kailixu 已提交
1593 1594
    // ignore the table not exists error, since this table may have been dropped during the scan procedure.
    if (code != TSDB_CODE_SUCCESS && code != TSDB_CODE_PAR_TABLE_NOT_EXIST) {
L
Liu Jicong 已提交
1595
      blockDataFreeRes((SSDataBlock*)pBlock);
1596
      T_LONG_JMP(pTaskInfo->env, code);
H
Haojun Liao 已提交
1597
    }
K
kailixu 已提交
1598 1599 1600

    // reset the error code.
    terrno = 0;
L
Liu Jicong 已提交
1601 1602
  }

1603
  if (filter) {
H
Haojun Liao 已提交
1604
    doFilter(pInfo->pRes, pOperator->exprSupp.pFilterInfo, NULL);
1605
  }
1606

1607
  pInfo->pRes->info.dataLoad = 1;
L
Liu Jicong 已提交
1608
  blockDataUpdateTsWindow(pInfo->pRes, pInfo->primaryTsIndex);
L
Liu Jicong 已提交
1609

L
Liu Jicong 已提交
1610
  calBlockTbName(pInfo, pInfo->pRes);
L
Liu Jicong 已提交
1611 1612
  return 0;
}
5
54liuyao 已提交
1613

L
Liu Jicong 已提交
1614
static SSDataBlock* doQueueScan(SOperatorInfo* pOperator) {
1615 1616 1617
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
  SStorageAPI*   pAPI = &pTaskInfo->storageAPI;

1618
  SStreamScanInfo* pInfo = pOperator->info;
X
Xiaoyu Wang 已提交
1619
  const char*      id = GET_TASKID(pTaskInfo);
H
Haojun Liao 已提交
1620

1621
  qDebug("start to exec queue scan, %s", id);
L
Liu Jicong 已提交
1622

1623
  if (isTaskKilled(pTaskInfo)) {
L
Liu Jicong 已提交
1624
    return NULL;
L
Liu Jicong 已提交
1625 1626
  }

1627
  if (pTaskInfo->streamInfo.currentOffset.type == TMQ_OFFSET__SNAPSHOT_DATA) {
L
Liu Jicong 已提交
1628 1629
    SSDataBlock* pResult = doTableScan(pInfo->pTableScanOp);
    if (pResult && pResult->info.rows > 0) {
1630 1631 1632
//      qDebug("queue scan tsdb return %" PRId64 " rows min:%" PRId64 " max:%" PRId64 " wal curVersion:%" PRId64,
//             pResult->info.rows, pResult->info.window.skey, pResult->info.window.ekey,
//             pInfo->tqReader->pWalReader->curVersion);
1633
      tqOffsetResetToData(&pTaskInfo->streamInfo.currentOffset, pResult->info.id.uid, pResult->info.window.ekey);
L
Liu Jicong 已提交
1634
      return pResult;
1635
    }
1636

1637
    STableScanInfo* pTSInfo = pInfo->pTableScanOp->info;
1638
    pAPI->tsdReader.tsdReaderClose(pTSInfo->base.dataReader);
H
Haojun Liao 已提交
1639

1640 1641
    pTSInfo->base.dataReader = NULL;
    qDebug("queue scan tsdb over, switch to wal ver %" PRId64 "", pTaskInfo->streamInfo.snapshotVer + 1);
1642
    if (pAPI->tqReaderFn.tqReaderSeek(pInfo->tqReader, pTaskInfo->streamInfo.snapshotVer + 1, pTaskInfo->id.str) < 0) {
1643
      return NULL;
1644
    }
1645

wmmhello's avatar
wmmhello 已提交
1646
    tqOffsetResetToLog(&pTaskInfo->streamInfo.currentOffset, pTaskInfo->streamInfo.snapshotVer);
1647 1648
  }

1649
  if (pTaskInfo->streamInfo.currentOffset.type == TMQ_OFFSET__LOG) {
1650

L
Liu Jicong 已提交
1651
    while (1) {
1652 1653
      bool hasResult = pAPI->tqReaderFn.tqReaderNextBlockInWal(pInfo->tqReader, id);

H
Haojun Liao 已提交
1654
      SSDataBlock* pRes = pAPI->tqReaderFn.tqGetResultBlock(pInfo->tqReader);
1655
      struct SWalReader* pWalReader = pAPI->tqReaderFn.tqReaderGetWalReader(pInfo->tqReader);
1656 1657

      // curVersion move to next, so currentOffset = curVersion - 1
1658
      tqOffsetResetToLog(&pTaskInfo->streamInfo.currentOffset, pWalReader->curVersion - 1);
1659

1660
      if (hasResult) {
1661
        qDebug("doQueueScan get data from log %" PRId64 " rows, version:%" PRId64, pRes->info.rows,
X
Xiaoyu Wang 已提交
1662
               pTaskInfo->streamInfo.currentOffset.version);
L
Liu Jicong 已提交
1663
        blockDataCleanup(pInfo->pRes);
1664
        setBlockIntoRes(pInfo, pRes, true);
L
Liu Jicong 已提交
1665 1666 1667
        if (pInfo->pRes->info.rows > 0) {
          return pInfo->pRes;
        }
1668
      } else {
wmmhello's avatar
wmmhello 已提交
1669
        qDebug("doQueueScan get none from log, return, version:%" PRId64, pTaskInfo->streamInfo.currentOffset.version);
L
Liu Jicong 已提交
1670 1671 1672
        return NULL;
      }
    }
L
Liu Jicong 已提交
1673
  } else {
1674
    qError("unexpected streamInfo prepare type: %d", pTaskInfo->streamInfo.currentOffset.type);
L
Liu Jicong 已提交
1675
    return NULL;
H
Haojun Liao 已提交
1676
  }
L
Liu Jicong 已提交
1677 1678
}

L
Liu Jicong 已提交
1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693
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);
1694 1695

  int32_t j = 0;
L
Liu Jicong 已提交
1696
  for (int32_t i = 0; i < rows; i++) {
1697
    if (pInfo->readerFn.tqReaderIsQueriedTable(pReader, uidCol[i])) {
1698 1699 1700
      colDataSetVal(pDstStartCol, j, (const char*)&startCol[i], false);
      colDataSetVal(pDstEndCol, j, (const char*)&endCol[i], false);
      colDataSetVal(pDstUidCol, j, (const char*)&uidCol[i], false);
L
Liu Jicong 已提交
1701

1702 1703 1704
      colDataSetNULL(taosArrayGet(pDst->pDataBlock, GROUPID_COLUMN_INDEX), j);
      colDataSetNULL(taosArrayGet(pDst->pDataBlock, CALCULATE_START_TS_COLUMN_INDEX), j);
      colDataSetNULL(taosArrayGet(pDst->pDataBlock, CALCULATE_END_TS_COLUMN_INDEX), j);
L
Liu Jicong 已提交
1705 1706 1707
      j++;
    }
  }
1708

L
Liu Jicong 已提交
1709
  uint32_t cap = pDst->info.capacity;
L
Liu Jicong 已提交
1710 1711
  pDst->info = pSrc->info;
  pDst->info.rows = j;
L
Liu Jicong 已提交
1712
  pDst->info.capacity = cap;
L
Liu Jicong 已提交
1713 1714 1715 1716

  return 0;
}

5
54liuyao 已提交
1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728
// 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]);
1729
      colDataSetVal(pGpCol, i, (const char*)&groupId, false);
5
54liuyao 已提交
1730 1731 1732 1733
    }
  }
}

5
54liuyao 已提交
1734
static void doCheckUpdate(SStreamScanInfo* pInfo, TSKEY endKey, SSDataBlock* pBlock) {
L
liuyao 已提交
1735
  if (!pInfo->igCheckUpdate && pInfo->pUpdateInfo) {
1736
    pInfo->pUpdateInfo->maxDataVersion = TMAX(pInfo->pUpdateInfo->maxDataVersion, pBlock->info.version);
5
54liuyao 已提交
1737
    checkUpdateData(pInfo, true, pBlock, true);
5
54liuyao 已提交
1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748
    pInfo->twAggSup.maxTs = TMAX(pInfo->twAggSup.maxTs, endKey);
    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;
      }
5
54liuyao 已提交
1749 1750 1751 1752
    }
  }
}

1753 1754 1755 1756 1757 1758
//int32_t streamScanOperatorEncode(SStreamScanInfo* pInfo, void** pBuff) {
//  int32_t len = updateInfoSerialize(NULL, 0, pInfo->pUpdateInfo);
//  *pBuff = taosMemoryCalloc(1, len);
//  updateInfoSerialize(*pBuff, len, pInfo->pUpdateInfo);
//  return len;
//}
L
liuyao 已提交
1759 1760

// other properties are recovered from the execution plan
1761
void streamScanOperatorDecode(void* pBuff, int32_t len, SStreamScanInfo* pInfo) {
L
fix bug  
liuyao 已提交
1762
  if (!pBuff || len == 0) {
L
liuyao 已提交
1763 1764 1765
    return;
  }

1766 1767
  void* pUpInfo = pInfo->stateStore.updateInfoInit(0, TSDB_TIME_PRECISION_MILLI, 0);
  int32_t      code = pInfo->stateStore.updateInfoDeserialize(pBuff, len, pUpInfo);
L
liuyao 已提交
1768 1769 1770 1771 1772
  if (code == TSDB_CODE_SUCCESS) {
    pInfo->pUpdateInfo = pUpInfo;
  }
}

L
Liu Jicong 已提交
1773 1774
static SSDataBlock* doStreamScan(SOperatorInfo* pOperator) {
  // NOTE: this operator does never check if current status is done or not
1775 1776
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
  const char*    id = GET_TASKID(pTaskInfo);
1777

1778
  SStorageAPI*     pAPI = &pTaskInfo->storageAPI;
L
Liu Jicong 已提交
1779 1780
  SStreamScanInfo* pInfo = pOperator->info;

1781
  qDebug("stream scan started, %s", id);
H
Haojun Liao 已提交
1782

1783 1784
  if (pTaskInfo->streamInfo.recoverStep == STREAM_RECOVER_STEP__PREPARE1 ||
      pTaskInfo->streamInfo.recoverStep == STREAM_RECOVER_STEP__PREPARE2) {
L
Liu Jicong 已提交
1785
    STableScanInfo* pTSInfo = pInfo->pTableScanOp->info;
H
Haojun Liao 已提交
1786
    memcpy(&pTSInfo->base.cond, &pTaskInfo->streamInfo.tableCond, sizeof(SQueryTableDataCond));
1787

1788
    if (pTaskInfo->streamInfo.recoverStep == STREAM_RECOVER_STEP__PREPARE1) {
1789 1790 1791 1792 1793 1794
      pTSInfo->base.cond.startVersion = pTaskInfo->streamInfo.fillHistoryVer.minVer;
      pTSInfo->base.cond.endVersion = pTaskInfo->streamInfo.fillHistoryVer.maxVer;

      pTSInfo->base.cond.twindows = pTaskInfo->streamInfo.fillHistoryWindow;
      qDebug("stream recover step1, verRange:%" PRId64 "-%" PRId64 " window:%"PRId64"-%"PRId64", %s", pTSInfo->base.cond.startVersion,
             pTSInfo->base.cond.endVersion, pTSInfo->base.cond.twindows.skey, pTSInfo->base.cond.twindows.ekey, id);
5
54liuyao 已提交
1795
      pTaskInfo->streamInfo.recoverStep = STREAM_RECOVER_STEP__SCAN1;
1796
    } else {
1797
      pTSInfo->base.cond.startVersion = pTaskInfo->streamInfo.fillHistoryVer.minVer + 1;
H
Haojun Liao 已提交
1798
      pTSInfo->base.cond.endVersion = pTaskInfo->streamInfo.fillHistoryVer2;
1799 1800
      qDebug("stream recover step2, verRange:%" PRId64 " - %" PRId64", %s", pTSInfo->base.cond.startVersion,
             pTSInfo->base.cond.endVersion, id);
5
54liuyao 已提交
1801
      pTaskInfo->streamInfo.recoverStep = STREAM_RECOVER_STEP__SCAN2;
1802
    }
L
Liu Jicong 已提交
1803

1804
    pAPI->tsdReader.tsdReaderClose(pTSInfo->base.dataReader);
D
dapan1121 已提交
1805

H
Haojun Liao 已提交
1806
    pTSInfo->base.dataReader = NULL;
L
Liu Jicong 已提交
1807
    pInfo->pTableScanOp->status = OP_OPENED;
L
Liu Jicong 已提交
1808

L
Liu Jicong 已提交
1809 1810
    pTSInfo->scanTimes = 0;
    pTSInfo->currentGroupId = -1;
L
Liu Jicong 已提交
1811
    pTaskInfo->streamInfo.recoverScanFinished = false;
L
Liu Jicong 已提交
1812 1813
  }

5
54liuyao 已提交
1814 1815
  if (pTaskInfo->streamInfo.recoverStep == STREAM_RECOVER_STEP__SCAN1 ||
      pTaskInfo->streamInfo.recoverStep == STREAM_RECOVER_STEP__SCAN2) {
L
Liu Jicong 已提交
1816 1817 1818 1819 1820
    if (pInfo->blockRecoverContiCnt > 100) {
      pInfo->blockRecoverTotCnt += pInfo->blockRecoverContiCnt;
      pInfo->blockRecoverContiCnt = 0;
      return NULL;
    }
5
54liuyao 已提交
1821 1822 1823 1824 1825 1826 1827

    switch (pInfo->scanMode) {
      case STREAM_SCAN_FROM_RES: {
        pInfo->scanMode = STREAM_SCAN_FROM_READERHANDLE;
        printDataBlock(pInfo->pRecoverRes, "scan recover");
        return pInfo->pRecoverRes;
      } break;
5
54liuyao 已提交
1828 1829 1830 1831
      case STREAM_SCAN_FROM_UPDATERES: {
        generateScanRange(pInfo, pInfo->pUpdateDataRes, pInfo->pUpdateRes);
        prepareRangeScan(pInfo, pInfo->pUpdateRes, &pInfo->updateResIndex);
        pInfo->scanMode = STREAM_SCAN_FROM_DATAREADER_RANGE;
1832
        printDataBlock(pInfo->pUpdateRes, "recover update");
5
54liuyao 已提交
1833 1834
        return pInfo->pUpdateRes;
      } break;
1835 1836 1837 1838 1839 1840 1841 1842 1843
      case STREAM_SCAN_FROM_DELETE_DATA: {
        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;
        printDataBlock(pInfo->pDeleteDataRes, "recover delete");
        return pInfo->pDeleteDataRes;
      } break;
5
54liuyao 已提交
1844 1845 1846 1847 1848 1849
      case STREAM_SCAN_FROM_DATAREADER_RANGE: {
        SSDataBlock* pSDB = doRangeScan(pInfo, pInfo->pUpdateRes, pInfo->primaryTsIndex, &pInfo->updateResIndex);
        if (pSDB) {
          STableScanInfo* pTableScanInfo = pInfo->pTableScanOp->info;
          pSDB->info.type = pInfo->scanMode == STREAM_SCAN_FROM_DATAREADER_RANGE ? STREAM_NORMAL : STREAM_PULL_DATA;
          checkUpdateData(pInfo, true, pSDB, false);
1850
          printDataBlock(pSDB, "scan recover update");
5
54liuyao 已提交
1851 1852 1853 1854 1855 1856
          calBlockTbName(pInfo, pSDB);
          return pSDB;
        }
        blockDataCleanup(pInfo->pUpdateDataRes);
        pInfo->scanMode = STREAM_SCAN_FROM_READERHANDLE;
      } break;
5
54liuyao 已提交
1857 1858 1859 1860 1861 1862
      default:
        break;
    }

    pInfo->pRecoverRes = doTableScan(pInfo->pTableScanOp);
    if (pInfo->pRecoverRes != NULL) {
L
Liu Jicong 已提交
1863
      pInfo->blockRecoverContiCnt++;
5
54liuyao 已提交
1864
      calBlockTbName(pInfo, pInfo->pRecoverRes);
L
liuyao 已提交
1865
      if (!pInfo->igCheckUpdate && pInfo->pUpdateInfo) {
5
54liuyao 已提交
1866
        if (pTaskInfo->streamInfo.recoverStep == STREAM_RECOVER_STEP__SCAN1) {
1867
          TSKEY maxTs = pAPI->stateStore.updateInfoFillBlockData(pInfo->pUpdateInfo, pInfo->pRecoverRes, pInfo->primaryTsIndex);
5
54liuyao 已提交
1868 1869
          pInfo->twAggSup.maxTs = TMAX(pInfo->twAggSup.maxTs, maxTs);
        } else {
L
liuyao 已提交
1870
          pInfo->pUpdateInfo->maxDataVersion = pTaskInfo->streamInfo.fillHistoryVer2;
5
54liuyao 已提交
1871 1872
          doCheckUpdate(pInfo, pInfo->pRecoverRes->info.window.ekey, pInfo->pRecoverRes);
        }
1873
      }
5
54liuyao 已提交
1874 1875
      if (pInfo->pCreateTbRes->info.rows > 0) {
        pInfo->scanMode = STREAM_SCAN_FROM_RES;
1876
        printDataBlock(pInfo->pCreateTbRes, "recover createTbl");
5
54liuyao 已提交
1877 1878
        return pInfo->pCreateTbRes;
      }
1879

X
Xiaoyu Wang 已提交
1880
      qDebug("stream recover scan get block, rows %" PRId64, pInfo->pRecoverRes->info.rows);
5
54liuyao 已提交
1881 1882
      printDataBlock(pInfo->pRecoverRes, "scan recover");
      return pInfo->pRecoverRes;
L
Liu Jicong 已提交
1883 1884
    }
    pTaskInfo->streamInfo.recoverStep = STREAM_RECOVER_STEP__NONE;
L
Liu Jicong 已提交
1885
    STableScanInfo* pTSInfo = pInfo->pTableScanOp->info;
1886
    pAPI->tsdReader.tsdReaderClose(pTSInfo->base.dataReader);
D
dapan1121 已提交
1887

H
Haojun Liao 已提交
1888
    pTSInfo->base.dataReader = NULL;
1889

H
Haojun Liao 已提交
1890 1891
    pTSInfo->base.cond.startVersion = -1;
    pTSInfo->base.cond.endVersion = -1;
L
Liu Jicong 已提交
1892

L
Liu Jicong 已提交
1893
    pTaskInfo->streamInfo.recoverScanFinished = true;
L
Liu Jicong 已提交
1894 1895 1896
    return NULL;
  }

5
54liuyao 已提交
1897
  size_t total = taosArrayGetSize(pInfo->pBlockLists);
5
54liuyao 已提交
1898
// TODO: refactor
L
Liu Jicong 已提交
1899
FETCH_NEXT_BLOCK:
L
Liu Jicong 已提交
1900
  if (pInfo->blockType == STREAM_INPUT__DATA_BLOCK) {
H
Haojun Liao 已提交
1901
    if (pInfo->validBlockIndex >= total) {
L
Liu Jicong 已提交
1902
      doClearBufferedBlocks(pInfo);
H
Haojun Liao 已提交
1903 1904 1905
      return NULL;
    }

1906 1907 1908
    int32_t  current = pInfo->validBlockIndex++;
    qDebug("process %d/%d input data blocks, %s", current, (int32_t) total, id);

L
Liu Jicong 已提交
1909 1910
    SPackedData* pPacked = taosArrayGet(pInfo->pBlockLists, current);
    SSDataBlock* pBlock = pPacked->pDataBlock;
5
54liuyao 已提交
1911
    if (pBlock->info.parTbName[0]) {
1912
      pAPI->stateStore.streamStatePutParName(pTaskInfo->streamInfo.pState, pBlock->info.id.groupId, pBlock->info.parTbName);
1913
    }
1914

1915
    // TODO move into scan
5
54liuyao 已提交
1916 1917
    pBlock->info.calWin.skey = INT64_MIN;
    pBlock->info.calWin.ekey = INT64_MAX;
1918
    pBlock->info.dataLoad = 1;
L
fix bug  
liuyao 已提交
1919
    if (pInfo->pUpdateInfo) {
1920
      pInfo->pUpdateInfo->maxDataVersion = TMAX(pInfo->pUpdateInfo->maxDataVersion, pBlock->info.version);
L
fix bug  
liuyao 已提交
1921
    }
1922
    blockDataUpdateTsWindow(pBlock, 0);
1923
    switch (pBlock->info.type) {
L
Liu Jicong 已提交
1924 1925 1926
      case STREAM_NORMAL:
      case STREAM_GET_ALL:
        return pBlock;
1927 1928 1929
      case STREAM_RETRIEVE: {
        pInfo->blockType = STREAM_INPUT__DATA_SUBMIT;
        pInfo->scanMode = STREAM_SCAN_FROM_DATAREADER_RETRIEVE;
1930
        copyDataBlock(pInfo->pUpdateRes, pBlock);
L
liuyao 已提交
1931
        pInfo->updateResIndex = 0;
1932
        prepareRangeScan(pInfo, pInfo->pUpdateRes, &pInfo->updateResIndex);
1933
        pAPI->stateStore.updateInfoAddCloseWindowSBF(pInfo->pUpdateInfo);
1934 1935
      } break;
      case STREAM_DELETE_DATA: {
1936
        printDataBlock(pBlock, "stream scan delete recv");
L
Liu Jicong 已提交
1937
        SSDataBlock* pDelBlock = NULL;
L
Liu Jicong 已提交
1938
        if (pInfo->tqReader) {
L
Liu Jicong 已提交
1939
          pDelBlock = createSpecialDataBlock(STREAM_DELETE_DATA);
L
Liu Jicong 已提交
1940
          filterDelBlockByUid(pDelBlock, pBlock, pInfo);
L
Liu Jicong 已提交
1941 1942
        } else {
          pDelBlock = pBlock;
L
Liu Jicong 已提交
1943
        }
5
54liuyao 已提交
1944 1945
        setBlockGroupIdByUid(pInfo, pDelBlock);
        printDataBlock(pDelBlock, "stream scan delete recv filtered");
5
54liuyao 已提交
1946 1947 1948 1949 1950 1951
        if (pDelBlock->info.rows == 0) {
          if (pInfo->tqReader) {
            blockDataDestroy(pDelBlock);
          }
          goto FETCH_NEXT_BLOCK;
        }
1952
        if (!isIntervalWindow(pInfo) && !isSessionWindow(pInfo) && !isStateWindow(pInfo)) {
L
Liu Jicong 已提交
1953
          generateDeleteResultBlock(pInfo, pDelBlock, pInfo->pDeleteDataRes);
1954
          pInfo->pDeleteDataRes->info.type = STREAM_DELETE_RESULT;
L
Liu Jicong 已提交
1955
          printDataBlock(pDelBlock, "stream scan delete result");
H
Haojun Liao 已提交
1956 1957
          blockDataDestroy(pDelBlock);

L
Liu Jicong 已提交
1958 1959 1960 1961 1962
          if (pInfo->pDeleteDataRes->info.rows > 0) {
            return pInfo->pDeleteDataRes;
          } else {
            goto FETCH_NEXT_BLOCK;
          }
1963 1964 1965
        } else {
          pInfo->blockType = STREAM_INPUT__DATA_SUBMIT;
          pInfo->updateResIndex = 0;
L
Liu Jicong 已提交
1966
          generateScanRange(pInfo, pDelBlock, pInfo->pUpdateRes);
1967 1968 1969
          prepareRangeScan(pInfo, pInfo->pUpdateRes, &pInfo->updateResIndex);
          copyDataBlock(pInfo->pDeleteDataRes, pInfo->pUpdateRes);
          pInfo->pDeleteDataRes->info.type = STREAM_DELETE_DATA;
L
Liu Jicong 已提交
1970 1971 1972 1973
          printDataBlock(pDelBlock, "stream scan delete data");
          if (pInfo->tqReader) {
            blockDataDestroy(pDelBlock);
          }
L
Liu Jicong 已提交
1974
          if (pInfo->pDeleteDataRes->info.rows > 0) {
5
54liuyao 已提交
1975
            pInfo->scanMode = STREAM_SCAN_FROM_DATAREADER_RANGE;
L
Liu Jicong 已提交
1976 1977 1978 1979
            return pInfo->pDeleteDataRes;
          } else {
            goto FETCH_NEXT_BLOCK;
          }
1980
        }
1981 1982 1983
      } break;
      default:
        break;
5
54liuyao 已提交
1984
    }
1985
    // printDataBlock(pBlock, "stream scan recv");
1986
    return pBlock;
L
Liu Jicong 已提交
1987
  } else if (pInfo->blockType == STREAM_INPUT__DATA_SUBMIT) {
1988
    qDebug("stream scan mode:%d, %s", pInfo->scanMode, id);
5
54liuyao 已提交
1989 1990 1991
    switch (pInfo->scanMode) {
      case STREAM_SCAN_FROM_RES: {
        pInfo->scanMode = STREAM_SCAN_FROM_READERHANDLE;
5
54liuyao 已提交
1992
        doCheckUpdate(pInfo, pInfo->pRes->info.window.ekey, pInfo->pRes);
5
54liuyao 已提交
1993 1994 1995
        doFilter(pInfo->pRes, pOperator->exprSupp.pFilterInfo, NULL);
        pInfo->pRes->info.dataLoad = 1;
        blockDataUpdateTsWindow(pInfo->pRes, pInfo->primaryTsIndex);
5
54liuyao 已提交
1996 1997 1998
        if (pInfo->pRes->info.rows > 0) {
          return pInfo->pRes;
        }
5
54liuyao 已提交
1999
      } break;
2000
      case STREAM_SCAN_FROM_DELETE_DATA: {
2001 2002 2003 2004 2005 2006 2007
        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 已提交
2008 2009 2010 2011 2012 2013 2014 2015 2016 2017
      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) {
2018
          STableScanInfo* pTableScanInfo = pInfo->pTableScanOp->info;
5
54liuyao 已提交
2019 2020
          pSDB->info.type = pInfo->scanMode == STREAM_SCAN_FROM_DATAREADER_RANGE ? STREAM_NORMAL : STREAM_PULL_DATA;
          checkUpdateData(pInfo, true, pSDB, false);
L
liuyao 已提交
2021
          printDataBlock(pSDB, "stream scan update");
L
Liu Jicong 已提交
2022
          calBlockTbName(pInfo, pSDB);
5
54liuyao 已提交
2023 2024
          return pSDB;
        }
2025
        blockDataCleanup(pInfo->pUpdateDataRes);
5
54liuyao 已提交
2026 2027 2028 2029
        pInfo->scanMode = STREAM_SCAN_FROM_READERHANDLE;
      } break;
      default:
        break;
2030
    }
2031

2032
    SStreamAggSupporter* pSup = pInfo->windowSup.pStreamAggSup;
5
54liuyao 已提交
2033
    if (isStateWindow(pInfo) && pSup->pScanBlock->info.rows > 0) {
2034 2035
      pInfo->scanMode = STREAM_SCAN_FROM_DATAREADER_RANGE;
      pInfo->updateResIndex = 0;
5
54liuyao 已提交
2036 2037
      copyDataBlock(pInfo->pUpdateRes, pSup->pScanBlock);
      blockDataCleanup(pSup->pScanBlock);
2038
      prepareRangeScan(pInfo, pInfo->pUpdateRes, &pInfo->updateResIndex);
2039
      pInfo->pUpdateRes->info.type = STREAM_DELETE_DATA;
2040
      return pInfo->pUpdateRes;
5
54liuyao 已提交
2041
    }
5
54liuyao 已提交
2042

2043 2044
    SSDataBlock*    pBlock = pInfo->pRes;
    SDataBlockInfo* pBlockInfo = &pBlock->info;
H
Haojun Liao 已提交
2045
    int32_t         totalBlocks = taosArrayGetSize(pInfo->pBlockLists);
2046

L
Liu Jicong 已提交
2047
  NEXT_SUBMIT_BLK:
2048
    while (1) {
2049
      if (pInfo->readerFn.tqReaderCurrentBlockConsumed(pInfo->tqReader)) {
2050
        if (pInfo->validBlockIndex >= totalBlocks) {
2051
          pAPI->stateStore.updateInfoDestoryColseWinSBF(pInfo->pUpdateInfo);
2052 2053 2054 2055 2056 2057 2058 2059 2060 2061
          doClearBufferedBlocks(pInfo);

          qDebug("stream scan return empty, all %d submit blocks consumed, %s", totalBlocks, id);
          return NULL;
        }

        int32_t      current = pInfo->validBlockIndex++;
        SPackedData* pSubmit = taosArrayGet(pInfo->pBlockLists, current);

        qDebug("set %d/%d as the input submit block, %s", current, totalBlocks, id);
2062
        if (pAPI->tqReaderFn.tqReaderSetSubmitMsg(pInfo->tqReader, pSubmit->msgStr, pSubmit->msgLen, pSubmit->ver) < 0) {
2063 2064 2065 2066
          qError("submit msg messed up when initializing stream submit block %p, current %d/%d, %s", pSubmit, current, totalBlocks, id);
          continue;
        }
      }
2067

2068
      blockDataCleanup(pBlock);
2069

2070 2071
      while (pAPI->tqReaderFn.tqNextBlockImpl(pInfo->tqReader, id)) {
        SSDataBlock* pRes = NULL;
2072

2073
        int32_t code = pAPI->tqReaderFn.tqRetrieveBlock(pInfo->tqReader, &pRes, id);
2074 2075
        qDebug("retrieve data from submit completed code:%s, rows:%" PRId64 " %s", tstrerror(code), pRes->info.rows,
               id);
H
Haojun Liao 已提交
2076

2077
        if (code != TSDB_CODE_SUCCESS || pRes->info.rows == 0) {
2078
          qDebug("retrieve data failed, try next block in submit block, %s", id);
2079 2080 2081
          continue;
        }

2082
        setBlockIntoRes(pInfo, pRes, false);
2083

5
54liuyao 已提交
2084 2085
        if (pInfo->pCreateTbRes->info.rows > 0) {
          pInfo->scanMode = STREAM_SCAN_FROM_RES;
2086
          qDebug("create table res exists, rows:%"PRId64" return from stream scan, %s", pInfo->pCreateTbRes->info.rows, id);
5
54liuyao 已提交
2087
          return pInfo->pCreateTbRes;
2088 2089
        }

2090 2091
        doCheckUpdate(pInfo, pBlockInfo->window.ekey, pBlock);
        doFilter(pBlock, pOperator->exprSupp.pFilterInfo, NULL);
2092

2093 2094 2095
        {  // do additional time window filter
          STimeWindow* pWindow = &pTaskInfo->streamInfo.fillHistoryWindow;

2096
          if (pWindow->skey != INT64_MIN) {
2097
            bool* p = taosMemoryCalloc(pBlock->info.rows, sizeof(bool));
2098
            bool hasUnqualified = false;
2099 2100 2101 2102 2103

            SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, pInfo->primaryTsIndex);
            for(int32_t i = 0; i < pBlock->info.rows; ++i) {
              int64_t* ts = (int64_t*) colDataGetData(pCol, i);
              p[i] = (*ts >= pWindow->skey);
2104 2105 2106 2107 2108 2109 2110 2111

              if (!p[i]) {
                hasUnqualified = true;
              }
            }

            if (hasUnqualified) {
              trimDataBlock(pBlock, pBlock->info.rows, p);
2112 2113 2114 2115 2116 2117
            }

            taosMemoryFree(p);
          }
        }

2118 2119
        pBlock->info.dataLoad = 1;
        blockDataUpdateTsWindow(pBlock, pInfo->primaryTsIndex);
2120

2121 2122
        qDebug("%" PRId64 " rows in datablock, update res:%" PRId64 " %s", pBlockInfo->rows,
               pInfo->pUpdateDataRes->info.rows, id);
2123 2124 2125
        if (pBlockInfo->rows > 0 || pInfo->pUpdateDataRes->info.rows > 0) {
          break;
        }
2126
      }
H
Haojun Liao 已提交
2127

2128
      if (pBlockInfo->rows > 0 || pInfo->pUpdateDataRes->info.rows > 0) {
5
54liuyao 已提交
2129
        break;
2130 2131
      } else {
        continue;
5
54liuyao 已提交
2132
      }
H
Haojun Liao 已提交
2133 2134 2135 2136
    }

    // record the scan action.
    pInfo->numOfExec++;
2137
    pOperator->resultInfo.totalRows += pBlockInfo->rows;
H
Haojun Liao 已提交
2138

2139
    qDebug("stream scan completed, and return source rows:%" PRId64", %s", pBlockInfo->rows, id);
L
Liu Jicong 已提交
2140
    if (pBlockInfo->rows > 0) {
2141
      return pBlock;
L
Liu Jicong 已提交
2142
    }
2143 2144 2145 2146 2147 2148

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

    goto NEXT_SUBMIT_BLK;
H
Haojun Liao 已提交
2149
  }
2150

2151
  return NULL;
H
Haojun Liao 已提交
2152 2153
}

H
Haojun Liao 已提交
2154
static SArray* extractTableIdList(const STableListInfo* pTableListInfo) {
2155 2156 2157
  SArray* tableIdList = taosArrayInit(4, sizeof(uint64_t));

  // Transfer the Array of STableKeyInfo into uid list.
H
Haojun Liao 已提交
2158 2159 2160
  size_t size = tableListGetSize(pTableListInfo);
  for (int32_t i = 0; i < size; ++i) {
    STableKeyInfo* pkeyInfo = tableListGetInfo(pTableListInfo, i);
2161 2162 2163 2164 2165 2166
    taosArrayPush(tableIdList, &pkeyInfo->uid);
  }

  return tableIdList;
}

2167
static SSDataBlock* doRawScan(SOperatorInfo* pOperator) {
L
Liu Jicong 已提交
2168
  // NOTE: this operator does never check if current status is done or not
2169 2170 2171
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
  SStorageAPI*   pAPI = &pTaskInfo->storageAPI;

2172
  SStreamRawScanInfo* pInfo = pOperator->info;
D
dapan1121 已提交
2173
  int32_t             code = TSDB_CODE_SUCCESS;
L
Liu Jicong 已提交
2174
  pTaskInfo->streamInfo.metaRsp.metaRspLen = 0;  // use metaRspLen !=0 to judge if data is meta
wmmhello's avatar
wmmhello 已提交
2175
  pTaskInfo->streamInfo.metaRsp.metaRsp = NULL;
2176

wmmhello's avatar
wmmhello 已提交
2177
  qDebug("tmqsnap doRawScan called");
2178
  if (pTaskInfo->streamInfo.currentOffset.type == TMQ_OFFSET__SNAPSHOT_DATA) {
D
dapan1121 已提交
2179 2180
    bool hasNext = false;
    if (pInfo->dataReader) {
2181
      code = pAPI->tsdReader.tsdNextDataBlock(pInfo->dataReader, &hasNext);
D
dapan1121 已提交
2182
      if (code) {
2183
        pAPI->tsdReader.tsdReaderReleaseDataBlock(pInfo->dataReader);
2184
        T_LONG_JMP(pTaskInfo->env, code);
D
dapan1121 已提交
2185 2186
      }
    }
X
Xiaoyu Wang 已提交
2187

D
dapan1121 已提交
2188
    if (pInfo->dataReader && hasNext) {
wmmhello's avatar
wmmhello 已提交
2189
      if (isTaskKilled(pTaskInfo)) {
2190
        pAPI->tsdReader.tsdReaderReleaseDataBlock(pInfo->dataReader);
2191
        T_LONG_JMP(pTaskInfo->env, pTaskInfo->code);
wmmhello's avatar
wmmhello 已提交
2192
      }
2193

2194
      SSDataBlock* pBlock = pAPI->tsdReader.tsdReaderRetrieveDataBlock(pInfo->dataReader, NULL);
H
Haojun Liao 已提交
2195
      if (pBlock == NULL) {
2196
        T_LONG_JMP(pTaskInfo->env, terrno);
wmmhello's avatar
wmmhello 已提交
2197 2198
      }

H
Haojun Liao 已提交
2199
      qDebug("tmqsnap doRawScan get data uid:%" PRId64 "", pBlock->info.id.uid);
2200
      tqOffsetResetToData(&pTaskInfo->streamInfo.currentOffset, pBlock->info.id.uid, pBlock->info.window.ekey);
wmmhello's avatar
wmmhello 已提交
2201 2202
      return pBlock;
    }
wmmhello's avatar
wmmhello 已提交
2203

H
Haojun Liao 已提交
2204
    SMetaTableInfo mtInfo = pAPI->snapshotFn.getMetaTableInfoFromSnapshot(pInfo->sContext);
X
Xiaoyu Wang 已提交
2205
    STqOffsetVal   offset = {0};
L
Liu Jicong 已提交
2206
    if (mtInfo.uid == 0) {  // read snapshot done, change to get data from wal
wmmhello's avatar
wmmhello 已提交
2207
      qDebug("tmqsnap read snapshot done, change to get data from wal");
2208
      tqOffsetResetToLog(&offset, pInfo->sContext->snapVersion);
L
Liu Jicong 已提交
2209
    } else {
2210
      tqOffsetResetToData(&offset, mtInfo.uid, INT64_MIN);
2211
      qDebug("tmqsnap change get data uid:%" PRId64 "", mtInfo.uid);
wmmhello's avatar
wmmhello 已提交
2212
    }
2213
    qStreamPrepareScan(pTaskInfo, &offset, pInfo->sContext->subType);
2214
    tDeleteSchemaWrapper(mtInfo.schema);
wmmhello's avatar
wmmhello 已提交
2215
    return NULL;
2216
  } else if (pTaskInfo->streamInfo.currentOffset.type == TMQ_OFFSET__SNAPSHOT_META) {
L
Liu Jicong 已提交
2217 2218 2219 2220 2221
    SSnapContext* sContext = pInfo->sContext;
    void*         data = NULL;
    int32_t       dataLen = 0;
    int16_t       type = 0;
    int64_t       uid = 0;
H
Haojun Liao 已提交
2222 2223
    if (pAPI->snapshotFn.getTableInfoFromSnapshot(sContext, &data, &dataLen, &type, &uid) < 0) {
      qError("tmqsnap getTableInfoFromSnapshot error");
wmmhello's avatar
wmmhello 已提交
2224
      taosMemoryFreeClear(data);
2225 2226 2227
      return NULL;
    }

2228
    if (!sContext->queryMeta) {  // change to get data next poll request
2229 2230 2231
      STqOffsetVal offset = {0};
      tqOffsetResetToData(&offset, 0, INT64_MIN);
      qStreamPrepareScan(pTaskInfo, &offset, pInfo->sContext->subType);
L
Liu Jicong 已提交
2232
    } else {
2233
      tqOffsetResetToMeta(&pTaskInfo->streamInfo.currentOffset, uid);
wmmhello's avatar
wmmhello 已提交
2234 2235 2236 2237
      pTaskInfo->streamInfo.metaRsp.resMsgType = type;
      pTaskInfo->streamInfo.metaRsp.metaRspLen = dataLen;
      pTaskInfo->streamInfo.metaRsp.metaRsp = data;
    }
2238

wmmhello's avatar
wmmhello 已提交
2239
    return NULL;
2240 2241 2242 2243
  }
  return NULL;
}

wmmhello's avatar
wmmhello 已提交
2244
static void destroyRawScanOperatorInfo(void* param) {
wmmhello's avatar
wmmhello 已提交
2245
  SStreamRawScanInfo* pRawScan = (SStreamRawScanInfo*)param;
2246
  pRawScan->pAPI->tsdReader.tsdReaderClose(pRawScan->dataReader);
2247
  pRawScan->pAPI->snapshotFn.destroySnapshot(pRawScan->sContext);
2248
  tableListDestroy(pRawScan->pTableListInfo);
wmmhello's avatar
wmmhello 已提交
2249 2250 2251
  taosMemoryFree(pRawScan);
}

L
Liu Jicong 已提交
2252 2253 2254
// for subscribing db or stb (not including column),
// if this scan is used, meta data can be return
// and schemas are decided when scanning
2255
SOperatorInfo* createRawScanOperatorInfo(SReadHandle* pHandle, SExecTaskInfo* pTaskInfo) {
L
Liu Jicong 已提交
2256 2257 2258 2259 2260
  // create operator
  // create tb reader
  // create meta reader
  // create tq reader

H
Haojun Liao 已提交
2261 2262
  int32_t code = TSDB_CODE_SUCCESS;

2263
  SStreamRawScanInfo* pInfo = taosMemoryCalloc(1, sizeof(SStreamRawScanInfo));
L
Liu Jicong 已提交
2264
  SOperatorInfo*      pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
2265
  if (pInfo == NULL || pOperator == NULL) {
H
Haojun Liao 已提交
2266 2267
    code = TSDB_CODE_OUT_OF_MEMORY;
    goto _end;
2268 2269
  }

2270
  pInfo->pTableListInfo = tableListCreate();
wmmhello's avatar
wmmhello 已提交
2271
  pInfo->vnode = pHandle->vnode;
H
Haojun Liao 已提交
2272
  pInfo->pAPI = &pTaskInfo->storageAPI;
wmmhello's avatar
wmmhello 已提交
2273

2274
  pInfo->sContext = pHandle->sContext;
L
Liu Jicong 已提交
2275 2276
  setOperatorInfo(pOperator, "RawScanOperator", QUERY_NODE_PHYSICAL_PLAN_TABLE_SCAN, false, OP_NOT_OPENED, pInfo,
                  pTaskInfo);
2277

2278
  pOperator->fpSet = createOperatorFpSet(NULL, doRawScan, NULL, destroyRawScanOperatorInfo, optrDefaultBufFn, NULL);
2279
  return pOperator;
H
Haojun Liao 已提交
2280

L
Liu Jicong 已提交
2281
_end:
H
Haojun Liao 已提交
2282 2283 2284 2285
  taosMemoryFree(pInfo);
  taosMemoryFree(pOperator);
  pTaskInfo->code = code;
  return NULL;
L
Liu Jicong 已提交
2286 2287
}

2288
static void destroyStreamScanOperatorInfo(void* param) {
2289
  SStreamScanInfo* pStreamScan = (SStreamScanInfo*)param;
2290

2291
  if (pStreamScan->pTableScanOp && pStreamScan->pTableScanOp->info) {
2292
    destroyOperator(pStreamScan->pTableScanOp);
2293
  }
2294

2295
  if (pStreamScan->tqReader) {
2296
    pStreamScan->readerFn.tqReaderClose(pStreamScan->tqReader);
2297
  }
H
Haojun Liao 已提交
2298 2299
  if (pStreamScan->matchInfo.pList) {
    taosArrayDestroy(pStreamScan->matchInfo.pList);
2300
  }
C
Cary Xu 已提交
2301 2302
  if (pStreamScan->pPseudoExpr) {
    destroyExprInfo(pStreamScan->pPseudoExpr, pStreamScan->numOfPseudoExpr);
L
Liu Jicong 已提交
2303
    taosMemoryFree(pStreamScan->pPseudoExpr);
C
Cary Xu 已提交
2304
  }
C
Cary Xu 已提交
2305

L
Liu Jicong 已提交
2306
  cleanupExprSupp(&pStreamScan->tbnameCalSup);
5
54liuyao 已提交
2307
  cleanupExprSupp(&pStreamScan->tagCalSup);
L
Liu Jicong 已提交
2308

2309
  pStreamScan->stateStore.updateInfoDestroy(pStreamScan->pUpdateInfo);
2310 2311 2312 2313
  blockDataDestroy(pStreamScan->pRes);
  blockDataDestroy(pStreamScan->pUpdateRes);
  blockDataDestroy(pStreamScan->pPullDataRes);
  blockDataDestroy(pStreamScan->pDeleteDataRes);
5
54liuyao 已提交
2314
  blockDataDestroy(pStreamScan->pUpdateDataRes);
5
54liuyao 已提交
2315
  blockDataDestroy(pStreamScan->pCreateTbRes);
2316 2317 2318 2319
  taosArrayDestroy(pStreamScan->pBlockLists);
  taosMemoryFree(pStreamScan);
}

2320
SOperatorInfo* createStreamScanOperatorInfo(SReadHandle* pHandle, STableScanPhysiNode* pTableScanNode, SNode* pTagCond,
2321
                                            STableListInfo* pTableListInfo, SExecTaskInfo* pTaskInfo) {
H
Haojun Liao 已提交
2322
  SArray*          pColIds = NULL;
2323 2324
  SStreamScanInfo* pInfo = taosMemoryCalloc(1, sizeof(SStreamScanInfo));
  SOperatorInfo*   pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
2325 2326
  SStorageAPI*     pAPI = &pTaskInfo->storageAPI;
  const char* idstr = pTaskInfo->id.str;
2327

H
Haojun Liao 已提交
2328
  if (pInfo == NULL || pOperator == NULL) {
S
Shengliang Guan 已提交
2329
    terrno = TSDB_CODE_OUT_OF_MEMORY;
2330
    tableListDestroy(pTableListInfo);
2331
    goto _error;
H
Haojun Liao 已提交
2332 2333
  }

2334
  SScanPhysiNode*     pScanPhyNode = &pTableScanNode->scan;
2335
  SDataBlockDescNode* pDescNode = pScanPhyNode->node.pOutputDataBlockDesc;
H
Haojun Liao 已提交
2336

2337
  pInfo->pTagCond = pTagCond;
2338
  pInfo->pGroupTags = pTableScanNode->pGroupTags;
2339

2340
  int32_t numOfCols = 0;
2341 2342
  int32_t code =
      extractColMatchInfo(pScanPhyNode->pScanCols, pDescNode, &numOfCols, COL_MATCH_FROM_COL_ID, &pInfo->matchInfo);
H
Haojun Liao 已提交
2343
  if (code != TSDB_CODE_SUCCESS) {
2344
    tableListDestroy(pTableListInfo);
H
Haojun Liao 已提交
2345 2346
    goto _error;
  }
2347

H
Haojun Liao 已提交
2348
  int32_t numOfOutput = taosArrayGetSize(pInfo->matchInfo.pList);
H
Haojun Liao 已提交
2349
  pColIds = taosArrayInit(numOfOutput, sizeof(int16_t));
2350
  for (int32_t i = 0; i < numOfOutput; ++i) {
H
Haojun Liao 已提交
2351
    SColMatchItem* id = taosArrayGet(pInfo->matchInfo.pList, i);
2352 2353

    int16_t colId = id->colId;
2354
    taosArrayPush(pColIds, &colId);
2355
    if (id->colId == PRIMARYKEY_TIMESTAMP_COL_ID) {
H
Haojun Liao 已提交
2356
      pInfo->primaryTsIndex = id->dstSlotId;
5
54liuyao 已提交
2357
    }
H
Haojun Liao 已提交
2358 2359
  }

L
Liu Jicong 已提交
2360 2361 2362 2363
  if (pTableScanNode->pSubtable != NULL) {
    SExprInfo* pSubTableExpr = taosMemoryCalloc(1, sizeof(SExprInfo));
    if (pSubTableExpr == NULL) {
      terrno = TSDB_CODE_OUT_OF_MEMORY;
2364
      tableListDestroy(pTableListInfo);
L
Liu Jicong 已提交
2365 2366
      goto _error;
    }
2367

L
Liu Jicong 已提交
2368 2369
    pInfo->tbnameCalSup.pExprInfo = pSubTableExpr;
    createExprFromOneNode(pSubTableExpr, pTableScanNode->pSubtable, 0);
2370
    if (initExprSupp(&pInfo->tbnameCalSup, pSubTableExpr, 1, &pTaskInfo->storageAPI.functionStore) != 0) {
2371
      tableListDestroy(pTableListInfo);
L
Liu Jicong 已提交
2372 2373 2374 2375
      goto _error;
    }
  }

2376 2377
  if (pTableScanNode->pTags != NULL) {
    int32_t    numOfTags;
5
54liuyao 已提交
2378
    SExprInfo* pTagExpr = createExpr(pTableScanNode->pTags, &numOfTags);
2379 2380
    if (pTagExpr == NULL) {
      terrno = TSDB_CODE_OUT_OF_MEMORY;
2381
      tableListDestroy(pTableListInfo);
2382 2383
      goto _error;
    }
2384
    if (initExprSupp(&pInfo->tagCalSup, pTagExpr, numOfTags, &pTaskInfo->storageAPI.functionStore) != 0) {
2385
      terrno = TSDB_CODE_OUT_OF_MEMORY;
2386
      tableListDestroy(pTableListInfo);
2387 2388 2389 2390
      goto _error;
    }
  }

L
Liu Jicong 已提交
2391
  pInfo->pBlockLists = taosArrayInit(4, sizeof(SPackedData));
H
Haojun Liao 已提交
2392
  if (pInfo->pBlockLists == NULL) {
2393
    terrno = TSDB_CODE_OUT_OF_MEMORY;
2394
    tableListDestroy(pTableListInfo);
2395
    goto _error;
H
Haojun Liao 已提交
2396 2397
  }

5
54liuyao 已提交
2398
  if (pHandle->vnode) {
2399
    SOperatorInfo*  pTableScanOp = createTableScanOperatorInfo(pTableScanNode, pHandle, pTableListInfo, pTaskInfo);
L
Liu Jicong 已提交
2400
    STableScanInfo* pTSInfo = (STableScanInfo*)pTableScanOp->info;
2401
    if (pHandle->version > 0) {
H
Haojun Liao 已提交
2402
      pTSInfo->base.cond.endVersion = pHandle->version;
2403
    }
L
Liu Jicong 已提交
2404

2405
    STableKeyInfo* pList = NULL;
5
54liuyao 已提交
2406
    int32_t        num = 0;
2407
    tableListGetGroupList(pTableListInfo, 0, &pList, &num);
2408

2409
    if (pHandle->initTableReader) {
L
Liu Jicong 已提交
2410
      pTSInfo->scanMode = TABLE_SCAN__TABLE_ORDER;
H
Haojun Liao 已提交
2411
      pTSInfo->base.dataReader = NULL;
L
Liu Jicong 已提交
2412 2413
    }

L
Liu Jicong 已提交
2414 2415
    if (pHandle->initTqReader) {
      ASSERT(pHandle->tqReader == NULL);
2416
      pInfo->tqReader = pAPI->tqReaderFn.tqReaderOpen(pHandle->vnode);
L
Liu Jicong 已提交
2417
      ASSERT(pInfo->tqReader);
2418
    } else {
L
Liu Jicong 已提交
2419 2420
      ASSERT(pHandle->tqReader);
      pInfo->tqReader = pHandle->tqReader;
2421 2422
    }

2423
    pInfo->pUpdateInfo = NULL;
2424
    pInfo->pTableScanOp = pTableScanOp;
2425
    if (pInfo->pTableScanOp->pTaskInfo->streamInfo.pState) {
2426
      pAPI->stateStore.streamStateSetNumber(pInfo->pTableScanOp->pTaskInfo->streamInfo.pState, -1);
2427
    }
L
Liu Jicong 已提交
2428

L
Liu Jicong 已提交
2429
    pInfo->readHandle = *pHandle;
L
Liu Jicong 已提交
2430
    pTaskInfo->streamInfo.snapshotVer = pHandle->version;
5
54liuyao 已提交
2431 2432
    pInfo->pCreateTbRes = buildCreateTableBlock(&pInfo->tbnameCalSup, &pInfo->tagCalSup);
    blockDataEnsureCapacity(pInfo->pCreateTbRes, 8);
L
Liu Jicong 已提交
2433

L
Liu Jicong 已提交
2434
    // set the extract column id to streamHandle
2435
    pAPI->tqReaderFn.tqReaderSetColIdList(pInfo->tqReader, pColIds);
2436
    SArray* tableIdList = extractTableIdList(((STableScanInfo*)(pInfo->pTableScanOp->info))->base.pTableListInfo);
2437
    code = pAPI->tqReaderFn.tqReaderSetQueryTableList(pInfo->tqReader, tableIdList, idstr);
L
Liu Jicong 已提交
2438 2439 2440 2441
    if (code != 0) {
      taosArrayDestroy(tableIdList);
      goto _error;
    }
2442

L
Liu Jicong 已提交
2443
    taosArrayDestroy(tableIdList);
H
Haojun Liao 已提交
2444
    memcpy(&pTaskInfo->streamInfo.tableCond, &pTSInfo->base.cond, sizeof(SQueryTableDataCond));
L
Liu Jicong 已提交
2445 2446
  } else {
    taosArrayDestroy(pColIds);
2447
    tableListDestroy(pTableListInfo);
H
Haojun Liao 已提交
2448
    pColIds = NULL;
5
54liuyao 已提交
2449 2450
  }

2451 2452 2453 2454 2455
  // create the pseduo columns info
  if (pTableScanNode->scan.pScanPseudoCols != NULL) {
    pInfo->pPseudoExpr = createExprInfo(pTableScanNode->scan.pScanPseudoCols, NULL, &pInfo->numOfPseudoExpr);
  }

H
Haojun Liao 已提交
2456 2457 2458 2459 2460
  code = filterInitFromNode((SNode*)pScanPhyNode->node.pConditions, &pOperator->exprSupp.pFilterInfo, 0);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }

H
Haojun Liao 已提交
2461
  pInfo->pRes = createDataBlockFromDescNode(pDescNode);
2462
  pInfo->pUpdateRes = createSpecialDataBlock(STREAM_CLEAR);
2463
  pInfo->scanMode = STREAM_SCAN_FROM_READERHANDLE;
L
Liu Jicong 已提交
2464
  pInfo->windowSup = (SWindowSupporter){.pStreamAggSup = NULL, .gap = -1, .parentType = QUERY_NODE_PHYSICAL_PLAN};
2465
  pInfo->groupId = 0;
2466
  pInfo->pPullDataRes = createSpecialDataBlock(STREAM_RETRIEVE);
2467
  pInfo->pStreamScanOp = pOperator;
2468
  pInfo->deleteDataIndex = 0;
2469
  pInfo->pDeleteDataRes = createSpecialDataBlock(STREAM_DELETE_DATA);
5
54liuyao 已提交
2470
  pInfo->updateWin = (STimeWindow){.skey = INT64_MAX, .ekey = INT64_MAX};
2471
  pInfo->pUpdateDataRes = createSpecialDataBlock(STREAM_CLEAR);
X
Xiaoyu Wang 已提交
2472
  pInfo->assignBlockUid = pTableScanNode->assignBlockUid;
2473
  pInfo->partitionSup.needCalc = false;
5
54liuyao 已提交
2474 2475
  pInfo->igCheckUpdate = pTableScanNode->igCheckUpdate;
  pInfo->igExpired = pTableScanNode->igExpired;
2476
  pInfo->twAggSup.maxTs = INT64_MIN;
L
liuyao 已提交
2477
  pInfo->pState = NULL;
2478 2479
  pInfo->stateStore = pTaskInfo->storageAPI.stateStore;
  pInfo->readerFn = pTaskInfo->storageAPI.tqReaderFn;
L
Liu Jicong 已提交
2480

L
fix bug  
liuyao 已提交
2481 2482 2483 2484
  // for stream
  if (pTaskInfo->streamInfo.pState) {
    void*   buff = NULL;
    int32_t len = 0;
2485 2486
    pAPI->stateStore.streamStateGetInfo(pTaskInfo->streamInfo.pState, STREAM_SCAN_OP_NAME, strlen(STREAM_SCAN_OP_NAME), &buff, &len);
    streamScanOperatorDecode(buff, len, pInfo);
dengyihao's avatar
dengyihao 已提交
2487
    taosMemoryFree(buff);
L
fix bug  
liuyao 已提交
2488
  }
L
liuyao 已提交
2489

L
fix bug  
liuyao 已提交
2490
  setOperatorInfo(pOperator, STREAM_SCAN_OP_NAME, QUERY_NODE_PHYSICAL_PLAN_STREAM_SCAN, false, OP_NOT_OPENED, pInfo,
L
Liu Jicong 已提交
2491
                  pTaskInfo);
2492
  pOperator->exprSupp.numOfExprs = taosArrayGetSize(pInfo->pRes->pDataBlock);
H
Haojun Liao 已提交
2493

2494
  __optr_fn_t nextFn = (pTaskInfo->execModel == OPTR_EXEC_MODEL_STREAM) ? doStreamScan : doQueueScan;
L
Liu Jicong 已提交
2495 2496
  pOperator->fpSet =
      createOperatorFpSet(optrDummyOpenFn, nextFn, NULL, destroyStreamScanOperatorInfo, optrDefaultBufFn, NULL);
2497

H
Haojun Liao 已提交
2498
  return pOperator;
2499

L
Liu Jicong 已提交
2500
_error:
H
Haojun Liao 已提交
2501 2502 2503 2504 2505 2506 2507 2508
  if (pColIds != NULL) {
    taosArrayDestroy(pColIds);
  }

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

2509 2510
  taosMemoryFreeClear(pOperator);
  return NULL;
H
Haojun Liao 已提交
2511 2512
}

2513
static void doTagScanOneTable(SOperatorInfo* pOperator, const SSDataBlock* pRes, int32_t count, SMetaReader* mr, SStorageAPI* pAPI) {
2514 2515 2516 2517
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
  STagScanInfo* pInfo = pOperator->info;
  SExprInfo*    pExprInfo = &pOperator->exprSupp.pExprInfo[0];

2518
  STableKeyInfo* item = tableListGetInfo(pInfo->pTableListInfo, pInfo->curPos);
2519
  int32_t        code = pAPI->metaReaderFn.getTableEntryByUid(mr, item->uid);
2520 2521 2522 2523
  tDecoderClear(&(*mr).coder);
  if (code != TSDB_CODE_SUCCESS) {
    qError("failed to get table meta, uid:0x%" PRIx64 ", code:%s, %s", item->uid, tstrerror(terrno),
           GET_TASKID(pTaskInfo));
2524
    pAPI->metaReaderFn.clearReader(mr);
2525 2526 2527
    T_LONG_JMP(pTaskInfo->env, terrno);
  }

2528
  char str[512];
2529 2530 2531 2532 2533 2534
  for (int32_t j = 0; j < pOperator->exprSupp.numOfExprs; ++j) {
    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);
2535
      colDataSetVal(pDst, (count), str, false);
2536 2537 2538
    } else {  // it is a tag value
      STagVal val = {0};
      val.cid = pExprInfo[j].base.pParam[0].pCol->colId;
2539
      const char* p = pAPI->metaFn.extractTagVal((*mr).me.ctbEntry.pTags, pDst->info.type, &val);
2540 2541 2542 2543 2544 2545 2546

      char* data = NULL;
      if (pDst->info.type != TSDB_DATA_TYPE_JSON && p != NULL) {
        data = tTagValToData((const STagVal*)p, false);
      } else {
        data = (char*)p;
      }
2547
      colDataSetVal(pDst, (count), data,
2548 2549 2550 2551 2552 2553 2554 2555 2556 2557
                    (data == NULL) || (pDst->info.type == TSDB_DATA_TYPE_JSON && tTagIsJsonNull(data)));

      if (pDst->info.type != TSDB_DATA_TYPE_JSON && p != NULL && IS_VAR_DATA_TYPE(((const STagVal*)p)->type) &&
          data != NULL) {
        taosMemoryFree(data);
      }
    }
  }
}

2558
static SSDataBlock* doTagScan(SOperatorInfo* pOperator) {
H
Haojun Liao 已提交
2559 2560 2561 2562
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

2563
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
2564
  SStorageAPI* pAPI = &pTaskInfo->storageAPI;
2565 2566

  STagScanInfo* pInfo = pOperator->info;
2567
  SExprInfo*    pExprInfo = &pOperator->exprSupp.pExprInfo[0];
2568
  SSDataBlock*  pRes = pInfo->pRes;
2569
  blockDataCleanup(pRes);
H
Haojun Liao 已提交
2570

2571
  int32_t size = tableListGetSize(pInfo->pTableListInfo);
wmmhello's avatar
wmmhello 已提交
2572
  if (size == 0) {
H
Haojun Liao 已提交
2573 2574 2575 2576
    setTaskStatus(pTaskInfo, TASK_COMPLETED);
    return NULL;
  }

2577 2578 2579
  char        str[512] = {0};
  int32_t     count = 0;
  SMetaReader mr = {0};
H
Haojun Liao 已提交
2580
  pAPI->metaReaderFn.initReader(&mr, pInfo->readHandle.vnode, 0, &pAPI->metaFn);
H
Haojun Liao 已提交
2581

wmmhello's avatar
wmmhello 已提交
2582
  while (pInfo->curPos < size && count < pOperator->resultInfo.capacity) {
2583
    doTagScanOneTable(pOperator, pRes, count, &mr, &pTaskInfo->storageAPI);
2584
    ++count;
wmmhello's avatar
wmmhello 已提交
2585
    if (++pInfo->curPos >= size) {
H
Haojun Liao 已提交
2586
      setOperatorCompleted(pOperator);
H
Haojun Liao 已提交
2587
    }
2588
    // each table with tbname is a group, hence its own block, but only group when slimit exists for performance reason.
2589
    if (pInfo->pSlimit != NULL) {
2590 2591 2592
      if (pInfo->curPos < pInfo->pSlimit->offset) {
        continue;
      }
2593
      pInfo->pRes->info.id.groupId = calcGroupId(mr.me.name, strlen(mr.me.name));
2594 2595 2596
      if (pInfo->curPos >= (pInfo->pSlimit->offset + pInfo->pSlimit->limit) - 1) {
        setOperatorCompleted(pOperator);
      }
2597
      break;
H
Haojun Liao 已提交
2598 2599 2600
    }
  }

2601
  pAPI->metaReaderFn.clearReader(&mr);
2602

2603
  // qDebug("QInfo:0x%"PRIx64" create tag values results completed, rows:%d", GET_TASKID(pRuntimeEnv), count);
H
Haojun Liao 已提交
2604
  if (pOperator->status == OP_EXEC_DONE) {
2605
    setTaskStatus(pTaskInfo, TASK_COMPLETED);
H
Haojun Liao 已提交
2606 2607 2608
  }

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

2611
  return (pRes->info.rows == 0) ? NULL : pInfo->pRes;
H
Haojun Liao 已提交
2612 2613
}

2614
static void destroyTagScanOperatorInfo(void* param) {
H
Haojun Liao 已提交
2615 2616
  STagScanInfo* pInfo = (STagScanInfo*)param;
  pInfo->pRes = blockDataDestroy(pInfo->pRes);
H
Haojun Liao 已提交
2617
  taosArrayDestroy(pInfo->matchInfo.pList);
2618
  pInfo->pTableListInfo = tableListDestroy(pInfo->pTableListInfo);
D
dapan1121 已提交
2619
  taosMemoryFreeClear(param);
H
Haojun Liao 已提交
2620 2621
}

S
slzhou 已提交
2622
SOperatorInfo* createTagScanOperatorInfo(SReadHandle* pReadHandle, STagScanPhysiNode* pPhyNode,
X
Xiaoyu Wang 已提交
2623
                                         STableListInfo* pTableListInfo, SExecTaskInfo* pTaskInfo) {
2624
  STagScanInfo*  pInfo = taosMemoryCalloc(1, sizeof(STagScanInfo));
H
Haojun Liao 已提交
2625 2626 2627 2628 2629
  SOperatorInfo* pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }

2630 2631 2632 2633
  SDataBlockDescNode* pDescNode = pPhyNode->node.pOutputDataBlockDesc;

  int32_t    numOfExprs = 0;
  SExprInfo* pExprInfo = createExprInfo(pPhyNode->pScanPseudoCols, NULL, &numOfExprs);
2634
  int32_t    code = initExprSupp(&pOperator->exprSupp, pExprInfo, numOfExprs, &pTaskInfo->storageAPI.functionStore);
2635 2636 2637
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
2638

H
Haojun Liao 已提交
2639 2640
  int32_t num = 0;
  code = extractColMatchInfo(pPhyNode->pScanPseudoCols, pDescNode, &num, COL_MATCH_FROM_COL_ID, &pInfo->matchInfo);
2641 2642 2643
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
2644

2645
  pInfo->pTableListInfo = pTableListInfo;
H
Haojun Liao 已提交
2646
  pInfo->pRes = createDataBlockFromDescNode(pDescNode);
2647 2648
  pInfo->readHandle = *pReadHandle;
  pInfo->curPos = 0;
2649
  pInfo->pSlimit = (SLimitNode*)pPhyNode->node.pSlimit; //TODO: slimit now only indicate group
2650

L
Liu Jicong 已提交
2651 2652
  setOperatorInfo(pOperator, "TagScanOperator", QUERY_NODE_PHYSICAL_PLAN_TAG_SCAN, false, OP_NOT_OPENED, pInfo,
                  pTaskInfo);
2653
  initResultSizeInfo(&pOperator->resultInfo, 4096);
2654 2655
  blockDataEnsureCapacity(pInfo->pRes, pOperator->resultInfo.capacity);

L
Liu Jicong 已提交
2656 2657
  pOperator->fpSet =
      createOperatorFpSet(optrDummyOpenFn, doTagScan, NULL, destroyTagScanOperatorInfo, optrDefaultBufFn, NULL);
H
Haojun Liao 已提交
2658 2659

  return pOperator;
2660

2661
_error:
H
Haojun Liao 已提交
2662 2663 2664 2665 2666
  taosMemoryFree(pInfo);
  taosMemoryFree(pOperator);
  terrno = TSDB_CODE_OUT_OF_MEMORY;
  return NULL;
}
2667

dengyihao's avatar
dengyihao 已提交
2668
static SSDataBlock* getTableDataBlockImpl(void* param) {
dengyihao's avatar
opt mem  
dengyihao 已提交
2669 2670 2671 2672
  STableMergeScanSortSourceParam* source = param;
  SOperatorInfo*                  pOperator = source->pOperator;
  STableMergeScanInfo*            pInfo = pOperator->info;
  SExecTaskInfo*                  pTaskInfo = pOperator->pTaskInfo;
2673 2674
  SStorageAPI* pAPI = &pTaskInfo->storageAPI;

dengyihao's avatar
opt mem  
dengyihao 已提交
2675 2676
  int32_t                         readIdx = source->readerIdx;
  SSDataBlock*                    pBlock = source->inputBlock;
D
dapan1121 已提交
2677
  int32_t                         code = 0;
dengyihao's avatar
opt mem  
dengyihao 已提交
2678

H
Haojun Liao 已提交
2679
  SQueryTableDataCond* pQueryCond = taosArrayGet(pInfo->queryConds, readIdx);
dengyihao's avatar
opt mem  
dengyihao 已提交
2680

L
Liu Jicong 已提交
2681
  int64_t      st = taosGetTimestampUs();
2682
  void*        p = tableListGetInfo(pInfo->base.pTableListInfo, readIdx + pInfo->tableStartIndex);
H
Haojun Liao 已提交
2683
  SReadHandle* pHandle = &pInfo->base.readHandle;
dengyihao's avatar
dengyihao 已提交
2684

D
dapan1121 已提交
2685
  if (NULL == source->dataReader || !source->multiReader) {
2686
    code = pAPI->tsdReader.tsdReaderOpen(pHandle->vnode, pQueryCond, p, 1, pBlock, (void**)&source->dataReader, GET_TASKID(pTaskInfo), false, NULL);
D
dapan1121 已提交
2687 2688 2689
    if (code != 0) {
      T_LONG_JMP(pTaskInfo->env, code);
    }
dengyihao's avatar
dengyihao 已提交
2690
  }
dengyihao's avatar
opt mem  
dengyihao 已提交
2691

D
dapan1121 已提交
2692
  pInfo->base.dataReader = source->dataReader;
H
Haojun Liao 已提交
2693
  STsdbReader* reader = pInfo->base.dataReader;
X
Xiaoyu Wang 已提交
2694
  bool         hasNext = false;
2695
  qTrace("tsdb/read-table-data: %p, enter next reader", reader);
D
dapan1121 已提交
2696 2697

  while (true) {
2698
    code = pAPI->tsdReader.tsdNextDataBlock(reader, &hasNext);
D
dapan1121 已提交
2699
    if (code != 0) {
2700
      pAPI->tsdReader.tsdReaderReleaseDataBlock(reader);
D
dapan1121 已提交
2701 2702 2703 2704 2705 2706 2707
      pInfo->base.dataReader = NULL;
      T_LONG_JMP(pTaskInfo->env, code);
    }

    if (!hasNext) {
      break;
    }
X
Xiaoyu Wang 已提交
2708

H
Haojun Liao 已提交
2709
    if (isTaskKilled(pTaskInfo)) {
2710
      pAPI->tsdReader.tsdReaderReleaseDataBlock(reader);
D
dapan1121 已提交
2711
      pInfo->base.dataReader = NULL;
2712
      T_LONG_JMP(pTaskInfo->env, pTaskInfo->code);
dengyihao's avatar
opt mem  
dengyihao 已提交
2713 2714 2715
    }

    // process this data block based on the probabilities
H
Haojun Liao 已提交
2716
    bool processThisBlock = processBlockWithProbability(&pInfo->sample);
dengyihao's avatar
opt mem  
dengyihao 已提交
2717 2718 2719 2720
    if (!processThisBlock) {
      continue;
    }

H
Haojun Liao 已提交
2721
    if (pQueryCond->order == TSDB_ORDER_ASC) {
dengyihao's avatar
opt mem  
dengyihao 已提交
2722 2723 2724 2725
      pQueryCond->twindows.skey = pBlock->info.window.ekey + 1;
    } else {
      pQueryCond->twindows.ekey = pBlock->info.window.skey - 1;
    }
dengyihao's avatar
opt mem  
dengyihao 已提交
2726 2727

    uint32_t status = 0;
2728
    code = loadDataBlock(pOperator, &pInfo->base, pBlock, &status);
S
slzhou 已提交
2729
    //    code = loadDataBlockFromOneTable(pOperator, pTableScanInfo, pBlock, &status);
dengyihao's avatar
opt mem  
dengyihao 已提交
2730
    if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
2731
      T_LONG_JMP(pTaskInfo->env, code);
dengyihao's avatar
opt mem  
dengyihao 已提交
2732 2733
    }

2734 2735 2736 2737
    if (status == FUNC_DATA_REQUIRED_ALL_FILTEROUT) {
      break;
    }

dengyihao's avatar
opt mem  
dengyihao 已提交
2738 2739 2740 2741 2742
    // 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;
    }

2743
    pBlock->info.id.groupId = getTableGroupId(pInfo->base.pTableListInfo, pBlock->info.id.uid);
dengyihao's avatar
opt mem  
dengyihao 已提交
2744

H
Haojun Liao 已提交
2745
    pOperator->resultInfo.totalRows += pBlock->info.rows;
H
Haojun Liao 已提交
2746
    pInfo->base.readRecorder.elapsedTime += (taosGetTimestampUs() - st) / 1000.0;
dengyihao's avatar
opt mem  
dengyihao 已提交
2747

2748
    qTrace("tsdb/read-table-data: %p, close reader", reader);
D
dapan1121 已提交
2749
    if (!source->multiReader) {
2750
      pAPI->tsdReader.tsdReaderClose(pInfo->base.dataReader);
D
dapan1121 已提交
2751 2752
      source->dataReader = NULL;
    }
H
Haojun Liao 已提交
2753
    pInfo->base.dataReader = NULL;
dengyihao's avatar
opt mem  
dengyihao 已提交
2754 2755
    return pBlock;
  }
H
Haojun Liao 已提交
2756

D
dapan1121 已提交
2757
  if (!source->multiReader) {
2758
    pAPI->tsdReader.tsdReaderClose(pInfo->base.dataReader);
D
dapan1121 已提交
2759 2760
    source->dataReader = NULL;
  }
H
Haojun Liao 已提交
2761
  pInfo->base.dataReader = NULL;
dengyihao's avatar
opt mem  
dengyihao 已提交
2762 2763 2764
  return NULL;
}

2765 2766 2767
SArray* generateSortByTsInfo(SArray* colMatchInfo, int32_t order) {
  int32_t tsTargetSlotId = 0;
  for (int32_t i = 0; i < taosArrayGetSize(colMatchInfo); ++i) {
H
Haojun Liao 已提交
2768
    SColMatchItem* colInfo = taosArrayGet(colMatchInfo, i);
2769
    if (colInfo->colId == PRIMARYKEY_TIMESTAMP_COL_ID) {
H
Haojun Liao 已提交
2770
      tsTargetSlotId = colInfo->dstSlotId;
2771 2772 2773
    }
  }

2774 2775 2776
  SArray*         pList = taosArrayInit(1, sizeof(SBlockOrderInfo));
  SBlockOrderInfo bi = {0};
  bi.order = order;
2777
  bi.slotId = tsTargetSlotId;
2778 2779 2780 2781 2782 2783 2784
  bi.nullFirst = NULL_ORDER_FIRST;

  taosArrayPush(pList, &bi);

  return pList;
}

H
Haojun Liao 已提交
2785
int32_t dumpQueryTableCond(const SQueryTableDataCond* src, SQueryTableDataCond* dst) {
dengyihao's avatar
opt mem  
dengyihao 已提交
2786 2787 2788 2789 2790 2791 2792
  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 已提交
2793

2794
int32_t startGroupTableMergeScan(SOperatorInfo* pOperator) {
2795 2796 2797
  STableMergeScanInfo* pInfo = pOperator->info;
  SExecTaskInfo*       pTaskInfo = pOperator->pTaskInfo;

S
slzhou 已提交
2798
  {
2799
    size_t  numOfTables = tableListGetSize(pInfo->base.pTableListInfo);
S
slzhou 已提交
2800
    int32_t i = pInfo->tableStartIndex + 1;
H
Haojun Liao 已提交
2801
    for (; i < numOfTables; ++i) {
2802
      STableKeyInfo* tableKeyInfo = tableListGetInfo(pInfo->base.pTableListInfo, i);
S
slzhou 已提交
2803 2804 2805 2806 2807 2808
      if (tableKeyInfo->groupId != pInfo->groupId) {
        break;
      }
    }
    pInfo->tableEndIndex = i - 1;
  }
2809

S
slzhou 已提交
2810 2811
  int32_t tableStartIdx = pInfo->tableStartIndex;
  int32_t tableEndIdx = pInfo->tableEndIndex;
2812

H
Haojun Liao 已提交
2813
  pInfo->base.dataReader = NULL;
2814

2815 2816
  // 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 已提交
2817
  pInfo->sortBufSize = pInfo->bufPageSize * (tableEndIdx - tableStartIdx + 1 + 1);
2818
  int32_t numOfBufPage = pInfo->sortBufSize / pInfo->bufPageSize;
L
Liu Jicong 已提交
2819 2820
  pInfo->pSortHandle = tsortCreateSortHandle(pInfo->pSortInfo, SORT_MULTISOURCE_MERGE, pInfo->bufPageSize, numOfBufPage,
                                             pInfo->pSortInputBlock, pTaskInfo->id.str);
2821

dengyihao's avatar
dengyihao 已提交
2822
  tsortSetFetchRawDataFp(pInfo->pSortHandle, getTableDataBlockImpl, NULL, NULL);
dengyihao's avatar
opt mem  
dengyihao 已提交
2823 2824 2825 2826 2827 2828

  // 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) {
2829 2830 2831
    STableMergeScanSortSourceParam param = {0};
    param.readerIdx = i;
    param.pOperator = pOperator;
D
dapan1121 已提交
2832
    param.multiReader = (numOfTable <= MULTI_READER_MAX_TABLE_NUM) ? true : false;
2833
    param.inputBlock = createOneDataBlock(pInfo->pResBlock, false);
H
Haojun Liao 已提交
2834 2835
    blockDataEnsureCapacity(param.inputBlock, pOperator->resultInfo.capacity);

2836
    taosArrayPush(pInfo->sortSourceParams, &param);
dengyihao's avatar
opt mem  
dengyihao 已提交
2837 2838

    SQueryTableDataCond cond;
H
Haojun Liao 已提交
2839
    dumpQueryTableCond(&pInfo->base.cond, &cond);
dengyihao's avatar
opt mem  
dengyihao 已提交
2840
    taosArrayPush(pInfo->queryConds, &cond);
2841 2842
  }

dengyihao's avatar
opt mem  
dengyihao 已提交
2843
  for (int32_t i = 0; i < numOfTable; ++i) {
2844
    SSortSource*                    ps = taosMemoryCalloc(1, sizeof(SSortSource));
2845
    STableMergeScanSortSourceParam* param = taosArrayGet(pInfo->sortSourceParams, i);
2846
    ps->param = param;
2847
    ps->onlyRef = true;
2848 2849 2850 2851 2852 2853
    tsortAddSource(pInfo->pSortHandle, ps);
  }

  int32_t code = tsortOpen(pInfo->pSortHandle);

  if (code != TSDB_CODE_SUCCESS) {
2854
    T_LONG_JMP(pTaskInfo->env, terrno);
2855 2856
  }

2857 2858 2859 2860 2861 2862
  return TSDB_CODE_SUCCESS;
}

int32_t stopGroupTableMergeScan(SOperatorInfo* pOperator) {
  STableMergeScanInfo* pInfo = pOperator->info;
  SExecTaskInfo*       pTaskInfo = pOperator->pTaskInfo;
2863
  SStorageAPI*         pAPI = &pTaskInfo->storageAPI;
2864

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

2867 2868 2869 2870 2871 2872 2873
  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 已提交
2874
  for (int32_t i = 0; i < numOfTable; ++i) {
2875 2876
    STableMergeScanSortSourceParam* param = taosArrayGet(pInfo->sortSourceParams, i);
    blockDataDestroy(param->inputBlock);
2877
    pAPI->tsdReader.tsdReaderClose(param->dataReader);
D
dapan1121 已提交
2878
    param->dataReader = NULL;
2879
  }
2880 2881
  taosArrayClear(pInfo->sortSourceParams);

2882
  tsortDestroySortHandle(pInfo->pSortHandle);
dengyihao's avatar
dengyihao 已提交
2883
  pInfo->pSortHandle = NULL;
2884

dengyihao's avatar
opt mem  
dengyihao 已提交
2885 2886 2887
  for (int32_t i = 0; i < taosArrayGetSize(pInfo->queryConds); i++) {
    SQueryTableDataCond* cond = taosArrayGet(pInfo->queryConds, i);
    taosMemoryFree(cond->colList);
2888
  }
dengyihao's avatar
opt mem  
dengyihao 已提交
2889 2890 2891
  taosArrayDestroy(pInfo->queryConds);
  pInfo->queryConds = NULL;

2892
  resetLimitInfoForNextGroup(&pInfo->limitInfo);
2893 2894 2895
  return TSDB_CODE_SUCCESS;
}

2896 2897
// all data produced by this function only belongs to one group
// slimit/soffset does not need to be concerned here, since this function only deal with data within one group.
L
Liu Jicong 已提交
2898 2899
SSDataBlock* getSortedTableMergeScanBlockData(SSortHandle* pHandle, SSDataBlock* pResBlock, int32_t capacity,
                                              SOperatorInfo* pOperator) {
2900 2901 2902
  STableMergeScanInfo* pInfo = pOperator->info;
  SExecTaskInfo*       pTaskInfo = pOperator->pTaskInfo;

2903
  blockDataCleanup(pResBlock);
2904 2905

  while (1) {
2906
    STupleHandle* pTupleHandle = tsortNextTuple(pHandle);
2907 2908 2909 2910
    if (pTupleHandle == NULL) {
      break;
    }

2911 2912
    appendOneRowToDataBlock(pResBlock, pTupleHandle);
    if (pResBlock->info.rows >= capacity) {
2913 2914 2915 2916
      break;
    }
  }

2917
  bool limitReached = applyLimitOffset(&pInfo->limitInfo, pResBlock, pTaskInfo);
D
dapan1121 已提交
2918
  qDebug("%s get sorted row block, rows:%" PRId64 ", limit:%" PRId64, GET_TASKID(pTaskInfo), pResBlock->info.rows,
2919
         pInfo->limitInfo.numOfOutputRows);
2920

2921
  return (pResBlock->info.rows > 0) ? pResBlock : NULL;
2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933
}

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) {
2934
    T_LONG_JMP(pTaskInfo->env, code);
2935
  }
2936

2937
  size_t tableListSize = tableListGetSize(pInfo->base.pTableListInfo);
S
slzhou 已提交
2938 2939
  if (!pInfo->hasGroupId) {
    pInfo->hasGroupId = true;
2940

S
slzhou 已提交
2941
    if (tableListSize == 0) {
H
Haojun Liao 已提交
2942
      setOperatorCompleted(pOperator);
2943 2944
      return NULL;
    }
S
slzhou 已提交
2945
    pInfo->tableStartIndex = 0;
2946
    pInfo->groupId = ((STableKeyInfo*)tableListGetInfo(pInfo->base.pTableListInfo, pInfo->tableStartIndex))->groupId;
2947 2948
    startGroupTableMergeScan(pOperator);
  }
2949

S
slzhou 已提交
2950 2951
  SSDataBlock* pBlock = NULL;
  while (pInfo->tableStartIndex < tableListSize) {
2952 2953 2954 2955
    if (isTaskKilled(pTaskInfo)) {
      T_LONG_JMP(pTaskInfo->env, pTaskInfo->code);
    }

L
Liu Jicong 已提交
2956 2957
    pBlock = getSortedTableMergeScanBlockData(pInfo->pSortHandle, pInfo->pResBlock, pOperator->resultInfo.capacity,
                                              pOperator);
S
slzhou 已提交
2958
    if (pBlock != NULL) {
H
Haojun Liao 已提交
2959
      pBlock->info.id.groupId = pInfo->groupId;
S
slzhou 已提交
2960 2961 2962
      pOperator->resultInfo.totalRows += pBlock->info.rows;
      return pBlock;
    } else {
2963
      // Data of this group are all dumped, let's try the next group
S
slzhou 已提交
2964 2965
      stopGroupTableMergeScan(pOperator);
      if (pInfo->tableEndIndex >= tableListSize - 1) {
H
Haojun Liao 已提交
2966
        setOperatorCompleted(pOperator);
S
slzhou 已提交
2967 2968
        break;
      }
2969

S
slzhou 已提交
2970
      pInfo->tableStartIndex = pInfo->tableEndIndex + 1;
2971
      pInfo->groupId = tableListGetInfo(pInfo->base.pTableListInfo, pInfo->tableStartIndex)->groupId;
S
slzhou 已提交
2972
      startGroupTableMergeScan(pOperator);
X
Xiaoyu Wang 已提交
2973
      resetLimitInfoForNextGroup(&pInfo->limitInfo);
S
slzhou 已提交
2974
    }
wmmhello's avatar
wmmhello 已提交
2975 2976
  }

2977 2978 2979
  return pBlock;
}

2980
void destroyTableMergeScanOperatorInfo(void* param) {
2981
  STableMergeScanInfo* pTableScanInfo = (STableMergeScanInfo*)param;
H
Haojun Liao 已提交
2982
  cleanupQueryTableDataCond(&pTableScanInfo->base.cond);
2983

dengyihao's avatar
dengyihao 已提交
2984 2985 2986
  int32_t numOfTable = taosArrayGetSize(pTableScanInfo->queryConds);

  for (int32_t i = 0; i < numOfTable; i++) {
H
Haojun Liao 已提交
2987 2988
    STableMergeScanSortSourceParam* p = taosArrayGet(pTableScanInfo->sortSourceParams, i);
    blockDataDestroy(p->inputBlock);
2989
    pTableScanInfo->base.readerAPI.tsdReaderClose(p->dataReader);
D
dapan1121 已提交
2990
    p->dataReader = NULL;
2991
  }
H
Haojun Liao 已提交
2992

2993
  pTableScanInfo->base.readerAPI.tsdReaderClose(pTableScanInfo->base.dataReader);
D
dapan1121 已提交
2994 2995
  pTableScanInfo->base.dataReader = NULL;

2996
  taosArrayDestroy(pTableScanInfo->sortSourceParams);
dengyihao's avatar
dengyihao 已提交
2997 2998
  tsortDestroySortHandle(pTableScanInfo->pSortHandle);
  pTableScanInfo->pSortHandle = NULL;
2999

dengyihao's avatar
opt mem  
dengyihao 已提交
3000 3001 3002
  for (int i = 0; i < taosArrayGetSize(pTableScanInfo->queryConds); i++) {
    SQueryTableDataCond* pCond = taosArrayGet(pTableScanInfo->queryConds, i);
    taosMemoryFree(pCond->colList);
3003 3004
  }

3005
  taosArrayDestroy(pTableScanInfo->queryConds);
3006
  destroyTableScanBase(&pTableScanInfo->base, &pTableScanInfo->base.readerAPI);
3007 3008 3009 3010 3011

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

  taosArrayDestroy(pTableScanInfo->pSortInfo);
D
dapan1121 已提交
3012
  taosMemoryFreeClear(param);
3013 3014 3015 3016
}

int32_t getTableMergeScanExplainExecInfo(SOperatorInfo* pOptr, void** pOptrExplain, uint32_t* len) {
  ASSERT(pOptr != NULL);
3017 3018
  // TODO: merge these two info into one struct
  STableMergeScanExecInfo* execInfo = taosMemoryCalloc(1, sizeof(STableMergeScanExecInfo));
L
Liu Jicong 已提交
3019
  STableMergeScanInfo*     pInfo = pOptr->info;
H
Haojun Liao 已提交
3020
  execInfo->blockRecorder = pInfo->base.readRecorder;
3021
  execInfo->sortExecInfo = pInfo->sortExecInfo;
3022 3023 3024

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

3026 3027 3028
  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
3029
SOperatorInfo* createTableMergeScanOperatorInfo(STableScanPhysiNode* pTableScanNode, SReadHandle* readHandle,
3030
                                                STableListInfo* pTableListInfo, SExecTaskInfo* pTaskInfo) {
3031 3032 3033 3034 3035
  STableMergeScanInfo* pInfo = taosMemoryCalloc(1, sizeof(STableMergeScanInfo));
  SOperatorInfo*       pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }
3036

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

  int32_t numOfCols = 0;
3040
  int32_t code = extractColMatchInfo(pTableScanNode->scan.pScanCols, pDescNode, &numOfCols, COL_MATCH_FROM_COL_ID,
H
Haojun Liao 已提交
3041
                                     &pInfo->base.matchInfo);
H
Haojun Liao 已提交
3042 3043 3044
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
3045

H
Haojun Liao 已提交
3046
  code = initQueryTableDataCond(&pInfo->base.cond, pTableScanNode);
3047
  if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
3048
    taosArrayDestroy(pInfo->base.matchInfo.pList);
3049 3050 3051 3052
    goto _error;
  }

  if (pTableScanNode->scan.pScanPseudoCols != NULL) {
H
Haojun Liao 已提交
3053
    SExprSupp* pSup = &pInfo->base.pseudoSup;
3054
    pSup->pExprInfo = createExprInfo(pTableScanNode->scan.pScanPseudoCols, NULL, &pSup->numOfExprs);
3055
    pSup->pCtx = createSqlFunctionCtx(pSup->pExprInfo, pSup->numOfExprs, &pSup->rowEntryInfoOffset, &pTaskInfo->storageAPI.functionStore);
3056 3057 3058 3059
  }

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

H
Haojun Liao 已提交
3060 3061 3062 3063 3064 3065
  pInfo->base.metaCache.pTableMetaEntryCache = taosLRUCacheInit(1024 * 128, -1, .5);
  if (pInfo->base.metaCache.pTableMetaEntryCache == NULL) {
    code = terrno;
    goto _error;
  }

H
Haojun Liao 已提交
3066
  pInfo->base.readerAPI = pTaskInfo->storageAPI.tsdReader;
H
Haojun Liao 已提交
3067 3068
  pInfo->base.dataBlockLoadFlag = FUNC_DATA_REQUIRED_DATA_LOAD;
  pInfo->base.scanFlag = MAIN_SCAN;
H
Haojun Liao 已提交
3069
  pInfo->base.readHandle = *readHandle;
3070 3071 3072

  pInfo->base.limitInfo.limit.limit = -1;
  pInfo->base.limitInfo.slimit.limit = -1;
3073
  pInfo->base.pTableListInfo = pTableListInfo;
H
Haojun Liao 已提交
3074

3075
  pInfo->sample.sampleRatio = pTableScanNode->ratio;
L
Liu Jicong 已提交
3076
  pInfo->sample.seed = taosGetTimestampSec();
H
Haojun Liao 已提交
3077 3078 3079 3080 3081 3082

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

H
Haojun Liao 已提交
3083
  initResultSizeInfo(&pOperator->resultInfo, 1024);
H
Haojun Liao 已提交
3084
  pInfo->pResBlock = createDataBlockFromDescNode(pDescNode);
H
Haojun Liao 已提交
3085 3086
  blockDataEnsureCapacity(pInfo->pResBlock, pOperator->resultInfo.capacity);

3087
  pInfo->sortSourceParams = taosArrayInit(64, sizeof(STableMergeScanSortSourceParam));
3088

H
Haojun Liao 已提交
3089
  pInfo->pSortInfo = generateSortByTsInfo(pInfo->base.matchInfo.pList, pInfo->base.cond.order);
3090
  pInfo->pSortInputBlock = createOneDataBlock(pInfo->pResBlock, false);
3091
  initLimitInfo(pTableScanNode->scan.node.pLimit, pTableScanNode->scan.node.pSlimit, &pInfo->limitInfo);
3092

dengyihao's avatar
dengyihao 已提交
3093
  int32_t  rowSize = pInfo->pResBlock->info.rowSize;
A
Alex Duan 已提交
3094 3095
  uint32_t nCols = taosArrayGetSize(pInfo->pResBlock->pDataBlock);
  pInfo->bufPageSize = getProperSortPageSize(rowSize, nCols);
3096

L
Liu Jicong 已提交
3097 3098
  setOperatorInfo(pOperator, "TableMergeScanOperator", QUERY_NODE_PHYSICAL_PLAN_TABLE_MERGE_SCAN, false, OP_NOT_OPENED,
                  pInfo, pTaskInfo);
L
Liu Jicong 已提交
3099
  pOperator->exprSupp.numOfExprs = numOfCols;
3100

3101 3102
  pOperator->fpSet = createOperatorFpSet(optrDummyOpenFn, doTableMergeScan, NULL, destroyTableMergeScanOperatorInfo,
                                         optrDefaultBufFn, getTableMergeScanExplainExecInfo);
3103 3104 3105 3106 3107 3108 3109 3110 3111
  pOperator->cost.openCost = 0;
  return pOperator;

_error:
  pTaskInfo->code = TSDB_CODE_OUT_OF_MEMORY;
  taosMemoryFree(pInfo);
  taosMemoryFree(pOperator);
  return NULL;
}
S
shenglian zhou 已提交
3112 3113 3114 3115

// ====================================================================================================================
// TableCountScanOperator
static SSDataBlock* doTableCountScan(SOperatorInfo* pOperator);
S
slzhou 已提交
3116
static void         destoryTableCountScanOperator(void* param);
S
slzhou 已提交
3117
static void         buildVnodeGroupedStbTableCount(STableCountScanOperatorInfo* pInfo, STableCountScanSupp* pSupp,
3118
                                                   SSDataBlock* pRes, char* dbName, tb_uid_t stbUid, SStorageAPI* pAPI);
S
slzhou 已提交
3119
static void         buildVnodeGroupedNtbTableCount(STableCountScanOperatorInfo* pInfo, STableCountScanSupp* pSupp,
3120
                                                   SSDataBlock* pRes, char* dbName, SStorageAPI* pAPI);
S
slzhou 已提交
3121 3122
static void         buildVnodeFilteredTbCount(SOperatorInfo* pOperator, STableCountScanOperatorInfo* pInfo,
                                              STableCountScanSupp* pSupp, SSDataBlock* pRes, char* dbName);
L
Liu Jicong 已提交
3123 3124
static void         buildVnodeGroupedTableCount(SOperatorInfo* pOperator, STableCountScanOperatorInfo* pInfo,
                                                STableCountScanSupp* pSupp, SSDataBlock* pRes, int32_t vgId, char* dbName);
S
slzhou 已提交
3125 3126 3127 3128 3129 3130 3131
static SSDataBlock* buildVnodeDbTableCount(SOperatorInfo* pOperator, STableCountScanOperatorInfo* pInfo,
                                           STableCountScanSupp* pSupp, SSDataBlock* pRes);
static void         buildSysDbGroupedTableCount(SOperatorInfo* pOperator, STableCountScanOperatorInfo* pInfo,
                                                STableCountScanSupp* pSupp, SSDataBlock* pRes, size_t infodbTableNum,
                                                size_t perfdbTableNum);
static void         buildSysDbFilterTableCount(SOperatorInfo* pOperator, STableCountScanSupp* pSupp, SSDataBlock* pRes,
                                               size_t infodbTableNum, size_t perfdbTableNum);
S
slzhou 已提交
3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192
static const char*  GROUP_TAG_DB_NAME = "db_name";
static const char*  GROUP_TAG_STABLE_NAME = "stable_name";

int32_t tblCountScanGetGroupTagsSlotId(const SNodeList* scanCols, STableCountScanSupp* supp) {
  if (scanCols != NULL) {
    SNode* pNode = NULL;
    FOREACH(pNode, scanCols) {
      if (nodeType(pNode) != QUERY_NODE_TARGET) {
        return TSDB_CODE_QRY_SYS_ERROR;
      }
      STargetNode* targetNode = (STargetNode*)pNode;
      if (nodeType(targetNode->pExpr) != QUERY_NODE_COLUMN) {
        return TSDB_CODE_QRY_SYS_ERROR;
      }
      SColumnNode* colNode = (SColumnNode*)(targetNode->pExpr);
      if (strcmp(colNode->colName, GROUP_TAG_DB_NAME) == 0) {
        supp->dbNameSlotId = targetNode->slotId;
      } else if (strcmp(colNode->colName, GROUP_TAG_STABLE_NAME) == 0) {
        supp->stbNameSlotId = targetNode->slotId;
      }
    }
  }
  return TSDB_CODE_SUCCESS;
}

int32_t tblCountScanGetCountSlotId(const SNodeList* pseudoCols, STableCountScanSupp* supp) {
  if (pseudoCols != NULL) {
    SNode* pNode = NULL;
    FOREACH(pNode, pseudoCols) {
      if (nodeType(pNode) != QUERY_NODE_TARGET) {
        return TSDB_CODE_QRY_SYS_ERROR;
      }
      STargetNode* targetNode = (STargetNode*)pNode;
      if (nodeType(targetNode->pExpr) != QUERY_NODE_FUNCTION) {
        return TSDB_CODE_QRY_SYS_ERROR;
      }
      SFunctionNode* funcNode = (SFunctionNode*)(targetNode->pExpr);
      if (funcNode->funcType == FUNCTION_TYPE_TABLE_COUNT) {
        supp->tbCountSlotId = targetNode->slotId;
      }
    }
  }
  return TSDB_CODE_SUCCESS;
}

int32_t tblCountScanGetInputs(SNodeList* groupTags, SName* tableName, STableCountScanSupp* supp) {
  if (groupTags != NULL) {
    SNode* pNode = NULL;
    FOREACH(pNode, groupTags) {
      if (nodeType(pNode) != QUERY_NODE_COLUMN) {
        return TSDB_CODE_QRY_SYS_ERROR;
      }
      SColumnNode* colNode = (SColumnNode*)pNode;
      if (strcmp(colNode->colName, GROUP_TAG_DB_NAME) == 0) {
        supp->groupByDbName = true;
      }
      if (strcmp(colNode->colName, GROUP_TAG_STABLE_NAME) == 0) {
        supp->groupByStbName = true;
      }
    }
  } else {
H
Haojun Liao 已提交
3193 3194
    tstrncpy(supp->dbNameFilter, tNameGetDbNameP(tableName), TSDB_DB_NAME_LEN);
    tstrncpy(supp->stbNameFilter, tNameGetTableName(tableName), TSDB_TABLE_NAME_LEN);
S
slzhou 已提交
3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206
  }
  return TSDB_CODE_SUCCESS;
}

int32_t getTableCountScanSupp(SNodeList* groupTags, SName* tableName, SNodeList* scanCols, SNodeList* pseudoCols,
                              STableCountScanSupp* supp, SExecTaskInfo* taskInfo) {
  int32_t code = 0;
  code = tblCountScanGetInputs(groupTags, tableName, supp);
  if (code != TSDB_CODE_SUCCESS) {
    qError("%s get table count scan supp. get inputs error", GET_TASKID(taskInfo));
    return code;
  }
H
Haojun Liao 已提交
3207

S
slzhou 已提交
3208 3209 3210 3211 3212 3213 3214 3215 3216
  supp->dbNameSlotId = -1;
  supp->stbNameSlotId = -1;
  supp->tbCountSlotId = -1;

  code = tblCountScanGetGroupTagsSlotId(scanCols, supp);
  if (code != TSDB_CODE_SUCCESS) {
    qError("%s get table count scan supp. get group tags slot id error", GET_TASKID(taskInfo));
    return code;
  }
H
Haojun Liao 已提交
3217

S
slzhou 已提交
3218 3219 3220 3221 3222 3223 3224
  code = tblCountScanGetCountSlotId(pseudoCols, supp);
  if (code != TSDB_CODE_SUCCESS) {
    qError("%s get table count scan supp. get count error", GET_TASKID(taskInfo));
    return code;
  }
  return code;
}
S
shenglian zhou 已提交
3225

S
slzhou 已提交
3226
SOperatorInfo* createTableCountScanOperatorInfo(SReadHandle* readHandle, STableCountScanPhysiNode* pTblCountScanNode,
S
shenglian zhou 已提交
3227 3228 3229
                                                SExecTaskInfo* pTaskInfo) {
  int32_t code = TSDB_CODE_SUCCESS;

S
slzhou 已提交
3230
  SScanPhysiNode*              pScanNode = &pTblCountScanNode->scan;
S
slzhou 已提交
3231
  STableCountScanOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(STableCountScanOperatorInfo));
S
slzhou 已提交
3232
  SOperatorInfo*               pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
S
shenglian zhou 已提交
3233 3234 3235 3236 3237 3238 3239 3240 3241

  if (!pInfo || !pOperator) {
    goto _error;
  }

  pInfo->readHandle = *readHandle;

  SDataBlockDescNode* pDescNode = pScanNode->node.pOutputDataBlockDesc;
  initResultSizeInfo(&pOperator->resultInfo, 1);
3242
  pInfo->pRes = createDataBlockFromDescNode(pDescNode);
S
shenglian zhou 已提交
3243 3244
  blockDataEnsureCapacity(pInfo->pRes, pOperator->resultInfo.capacity);

S
slzhou 已提交
3245 3246 3247
  getTableCountScanSupp(pTblCountScanNode->pGroupTags, &pTblCountScanNode->scan.tableName,
                        pTblCountScanNode->scan.pScanCols, pTblCountScanNode->scan.pScanPseudoCols, &pInfo->supp,
                        pTaskInfo);
S
shenglian zhou 已提交
3248 3249 3250

  setOperatorInfo(pOperator, "TableCountScanOperator", QUERY_NODE_PHYSICAL_PLAN_TABLE_COUNT_SCAN, false, OP_NOT_OPENED,
                  pInfo, pTaskInfo);
L
Liu Jicong 已提交
3251 3252
  pOperator->fpSet = createOperatorFpSet(optrDummyOpenFn, doTableCountScan, NULL, destoryTableCountScanOperator,
                                         optrDefaultBufFn, NULL);
S
shenglian zhou 已提交
3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263
  return pOperator;

_error:
  if (pInfo != NULL) {
    destoryTableCountScanOperator(pInfo);
  }
  taosMemoryFreeClear(pOperator);
  pTaskInfo->code = code;
  return NULL;
}

S
slzhou 已提交
3264 3265 3266
void fillTableCountScanDataBlock(STableCountScanSupp* pSupp, char* dbName, char* stbName, int64_t count,
                                 SSDataBlock* pRes) {
  if (pSupp->dbNameSlotId != -1) {
3267
    ASSERT(strlen(dbName));
S
slzhou 已提交
3268
    SColumnInfoData* colInfoData = taosArrayGet(pRes->pDataBlock, pSupp->dbNameSlotId);
H
Haojun Liao 已提交
3269 3270 3271 3272

    char varDbName[TSDB_DB_NAME_LEN + VARSTR_HEADER_SIZE] = {0};
    tstrncpy(varDataVal(varDbName), dbName, TSDB_DB_NAME_LEN);

S
slzhou 已提交
3273
    varDataSetLen(varDbName, strlen(dbName));
3274
    colDataSetVal(colInfoData, 0, varDbName, false);
S
slzhou 已提交
3275 3276 3277 3278
  }

  if (pSupp->stbNameSlotId != -1) {
    SColumnInfoData* colInfoData = taosArrayGet(pRes->pDataBlock, pSupp->stbNameSlotId);
3279
    if (strlen(stbName) != 0) {
S
slzhou 已提交
3280
      char varStbName[TSDB_TABLE_NAME_LEN + VARSTR_HEADER_SIZE] = {0};
H
Haojun Liao 已提交
3281
      strncpy(varDataVal(varStbName), stbName, TSDB_TABLE_NAME_LEN);
3282
      varDataSetLen(varStbName, strlen(stbName));
3283
      colDataSetVal(colInfoData, 0, varStbName, false);
3284
    } else {
3285
      colDataSetNULL(colInfoData, 0);
3286
    }
S
slzhou 已提交
3287 3288 3289
  }

  if (pSupp->tbCountSlotId != -1) {
S
slzhou 已提交
3290
    SColumnInfoData* colInfoData = taosArrayGet(pRes->pDataBlock, pSupp->tbCountSlotId);
3291
    colDataSetVal(colInfoData, 0, (char*)&count, false);
S
slzhou 已提交
3292 3293 3294 3295
  }
  pRes->info.rows = 1;
}

S
slzhou 已提交
3296
static SSDataBlock* buildSysDbTableCount(SOperatorInfo* pOperator, STableCountScanOperatorInfo* pInfo) {
S
slzhou 已提交
3297 3298 3299
  STableCountScanSupp* pSupp = &pInfo->supp;
  SSDataBlock*         pRes = pInfo->pRes;

S
slzhou 已提交
3300
  size_t infodbTableNum;
S
slzhou 已提交
3301
  getInfosDbMeta(NULL, &infodbTableNum);
S
slzhou 已提交
3302
  size_t perfdbTableNum;
S
slzhou 已提交
3303 3304
  getPerfDbMeta(NULL, &perfdbTableNum);

D
dapan1121 已提交
3305
  if (pSupp->groupByDbName || pSupp->groupByStbName) {
S
slzhou 已提交
3306
    buildSysDbGroupedTableCount(pOperator, pInfo, pSupp, pRes, infodbTableNum, perfdbTableNum);
S
slzhou 已提交
3307 3308
    return (pRes->info.rows > 0) ? pRes : NULL;
  } else {
S
slzhou 已提交
3309
    buildSysDbFilterTableCount(pOperator, pSupp, pRes, infodbTableNum, perfdbTableNum);
S
slzhou 已提交
3310 3311 3312 3313
    return (pRes->info.rows > 0) ? pRes : NULL;
  }
}

S
slzhou 已提交
3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329
static void buildSysDbFilterTableCount(SOperatorInfo* pOperator, STableCountScanSupp* pSupp, SSDataBlock* pRes,
                                       size_t infodbTableNum, size_t perfdbTableNum) {
  if (strcmp(pSupp->dbNameFilter, TSDB_INFORMATION_SCHEMA_DB) == 0) {
    fillTableCountScanDataBlock(pSupp, TSDB_INFORMATION_SCHEMA_DB, "", infodbTableNum, pRes);
  } else if (strcmp(pSupp->dbNameFilter, TSDB_PERFORMANCE_SCHEMA_DB) == 0) {
    fillTableCountScanDataBlock(pSupp, TSDB_PERFORMANCE_SCHEMA_DB, "", perfdbTableNum, pRes);
  } else if (strlen(pSupp->dbNameFilter) == 0) {
    fillTableCountScanDataBlock(pSupp, "", "", infodbTableNum + perfdbTableNum, pRes);
  }
  setOperatorCompleted(pOperator);
}

static void buildSysDbGroupedTableCount(SOperatorInfo* pOperator, STableCountScanOperatorInfo* pInfo,
                                        STableCountScanSupp* pSupp, SSDataBlock* pRes, size_t infodbTableNum,
                                        size_t perfdbTableNum) {
  if (pInfo->currGrpIdx == 0) {
D
dapan1121 已提交
3330 3331 3332 3333 3334 3335
    uint64_t groupId = 0;
    if (pSupp->groupByDbName) {
      groupId = calcGroupId(TSDB_INFORMATION_SCHEMA_DB, strlen(TSDB_INFORMATION_SCHEMA_DB));
    } else {
      groupId = calcGroupId("", 0);
    }
X
Xiaoyu Wang 已提交
3336

S
slzhou 已提交
3337 3338 3339
    pRes->info.id.groupId = groupId;
    fillTableCountScanDataBlock(pSupp, TSDB_INFORMATION_SCHEMA_DB, "", infodbTableNum, pRes);
  } else if (pInfo->currGrpIdx == 1) {
D
dapan1121 已提交
3340 3341 3342 3343 3344 3345 3346
    uint64_t groupId = 0;
    if (pSupp->groupByDbName) {
      groupId = calcGroupId(TSDB_PERFORMANCE_SCHEMA_DB, strlen(TSDB_PERFORMANCE_SCHEMA_DB));
    } else {
      groupId = calcGroupId("", 0);
    }

S
slzhou 已提交
3347 3348 3349 3350 3351 3352 3353 3354
    pRes->info.id.groupId = groupId;
    fillTableCountScanDataBlock(pSupp, TSDB_PERFORMANCE_SCHEMA_DB, "", perfdbTableNum, pRes);
  } else {
    setOperatorCompleted(pOperator);
  }
  pInfo->currGrpIdx++;
}

S
shenglian zhou 已提交
3355
static SSDataBlock* doTableCountScan(SOperatorInfo* pOperator) {
S
slzhou 已提交
3356 3357 3358 3359
  SExecTaskInfo*               pTaskInfo = pOperator->pTaskInfo;
  STableCountScanOperatorInfo* pInfo = pOperator->info;
  STableCountScanSupp*         pSupp = &pInfo->supp;
  SSDataBlock*                 pRes = pInfo->pRes;
S
slzhou 已提交
3360
  blockDataCleanup(pRes);
3361

S
slzhou 已提交
3362 3363 3364
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }
S
slzhou 已提交
3365
  if (pInfo->readHandle.mnd != NULL) {
S
slzhou 已提交
3366
    return buildSysDbTableCount(pOperator, pInfo);
S
slzhou 已提交
3367
  }
S
slzhou 已提交
3368

S
slzhou 已提交
3369 3370 3371 3372 3373
  return buildVnodeDbTableCount(pOperator, pInfo, pSupp, pRes);
}

static SSDataBlock* buildVnodeDbTableCount(SOperatorInfo* pOperator, STableCountScanOperatorInfo* pInfo,
                                           STableCountScanSupp* pSupp, SSDataBlock* pRes) {
S
slzhou 已提交
3374 3375
  const char* db = NULL;
  int32_t     vgId = 0;
S
slzhou 已提交
3376
  char        dbName[TSDB_DB_NAME_LEN] = {0};
3377 3378
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
  SStorageAPI* pAPI = &pTaskInfo->storageAPI;
S
slzhou 已提交
3379

S
slzhou 已提交
3380
  // get dbname
3381
  pAPI->metaFn.getBasicInfo(pInfo->readHandle.vnode, &db, &vgId, NULL, NULL);
S
slzhou 已提交
3382 3383 3384 3385
  SName sn = {0};
  tNameFromString(&sn, db, T_NAME_ACCT | T_NAME_DB);
  tNameGetDbName(&sn, dbName);

D
dapan1121 已提交
3386
  if (pSupp->groupByDbName || pSupp->groupByStbName) {
S
slzhou 已提交
3387 3388 3389 3390 3391 3392 3393 3394 3395
    buildVnodeGroupedTableCount(pOperator, pInfo, pSupp, pRes, vgId, dbName);
  } else {
    buildVnodeFilteredTbCount(pOperator, pInfo, pSupp, pRes, dbName);
  }
  return pRes->info.rows > 0 ? pRes : NULL;
}

static void buildVnodeGroupedTableCount(SOperatorInfo* pOperator, STableCountScanOperatorInfo* pInfo,
                                        STableCountScanSupp* pSupp, SSDataBlock* pRes, int32_t vgId, char* dbName) {
3396 3397 3398
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
  SStorageAPI* pAPI = &pTaskInfo->storageAPI;

S
slzhou 已提交
3399 3400 3401
  if (pSupp->groupByStbName) {
    if (pInfo->stbUidList == NULL) {
      pInfo->stbUidList = taosArrayInit(16, sizeof(tb_uid_t));
H
Haojun Liao 已提交
3402
      if (pAPI->metaFn.storeGetTableList(pInfo->readHandle.vnode, TSDB_SUPER_TABLE, pInfo->stbUidList) < 0) {
S
slzhou 已提交
3403
        qError("vgId:%d, failed to get stb id list error: %s", vgId, terrstr());
S
slzhou 已提交
3404
      }
S
slzhou 已提交
3405 3406 3407
    }
    if (pInfo->currGrpIdx < taosArrayGetSize(pInfo->stbUidList)) {
      tb_uid_t stbUid = *(tb_uid_t*)taosArrayGet(pInfo->stbUidList, pInfo->currGrpIdx);
3408
      buildVnodeGroupedStbTableCount(pInfo, pSupp, pRes, dbName, stbUid, pAPI);
S
slzhou 已提交
3409 3410 3411

      pInfo->currGrpIdx++;
    } else if (pInfo->currGrpIdx == taosArrayGetSize(pInfo->stbUidList)) {
3412
      buildVnodeGroupedNtbTableCount(pInfo, pSupp, pRes, dbName, pAPI);
S
slzhou 已提交
3413 3414

      pInfo->currGrpIdx++;
S
slzhou 已提交
3415
    } else {
S
slzhou 已提交
3416
      setOperatorCompleted(pOperator);
S
slzhou 已提交
3417 3418
    }
  } else {
S
slzhou 已提交
3419 3420
    uint64_t groupId = calcGroupId(dbName, strlen(dbName));
    pRes->info.id.groupId = groupId;
3421 3422

    int64_t dbTableCount = 0;
3423
    pAPI->metaFn.getBasicInfo(pInfo->readHandle.vnode, NULL, NULL, &dbTableCount, NULL);
S
slzhou 已提交
3424 3425 3426 3427 3428 3429 3430
    fillTableCountScanDataBlock(pSupp, dbName, "", dbTableCount, pRes);
    setOperatorCompleted(pOperator);
  }
}

static void buildVnodeFilteredTbCount(SOperatorInfo* pOperator, STableCountScanOperatorInfo* pInfo,
                                      STableCountScanSupp* pSupp, SSDataBlock* pRes, char* dbName) {
3431 3432 3433
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
  SStorageAPI* pAPI = &pTaskInfo->storageAPI;

S
slzhou 已提交
3434 3435
  if (strlen(pSupp->dbNameFilter) != 0) {
    if (strlen(pSupp->stbNameFilter) != 0) {
H
Haojun Liao 已提交
3436
      uint64_t uid = 0;
3437
      pAPI->metaFn.getTableUidByName(pInfo->readHandle.vnode, pSupp->stbNameFilter, &uid);
3438 3439 3440 3441 3442

      int64_t numOfChildTables = 0;
      pAPI->metaFn.getNumOfChildTables(pInfo->readHandle.vnode, uid, &numOfChildTables);

      fillTableCountScanDataBlock(pSupp, dbName, pSupp->stbNameFilter, numOfChildTables, pRes);
S
slzhou 已提交
3443
    } else {
H
Haojun Liao 已提交
3444 3445
      int64_t tbNumVnode = 0;
      pAPI->metaFn.getBasicInfo(pInfo->readHandle.vnode, NULL, NULL, &tbNumVnode, NULL);
S
slzhou 已提交
3446
      fillTableCountScanDataBlock(pSupp, dbName, "", tbNumVnode, pRes);
S
slzhou 已提交
3447
    }
S
slzhou 已提交
3448
  } else {
3449 3450
    int64_t tbNumVnode = 0;
    pAPI->metaFn.getBasicInfo(pInfo->readHandle.vnode, NULL, NULL, &tbNumVnode, NULL);
S
slzhou 已提交
3451
    fillTableCountScanDataBlock(pSupp, dbName, "", tbNumVnode, pRes);
S
slzhou 已提交
3452
  }
3453

S
slzhou 已提交
3454 3455 3456 3457
  setOperatorCompleted(pOperator);
}

static void buildVnodeGroupedNtbTableCount(STableCountScanOperatorInfo* pInfo, STableCountScanSupp* pSupp,
3458
                                           SSDataBlock* pRes, char* dbName, SStorageAPI* pAPI) {
S
slzhou 已提交
3459
  char fullStbName[TSDB_TABLE_FNAME_LEN] = {0};
D
dapan1121 已提交
3460 3461 3462
  if (pSupp->groupByDbName) {
    snprintf(fullStbName, TSDB_TABLE_FNAME_LEN, "%s.%s", dbName, "");
  }
X
Xiaoyu Wang 已提交
3463

S
slzhou 已提交
3464 3465
  uint64_t groupId = calcGroupId(fullStbName, strlen(fullStbName));
  pRes->info.id.groupId = groupId;
3466

3467
  int64_t numOfTables = 0;
3468
  pAPI->metaFn.getBasicInfo(pInfo->readHandle.vnode, NULL, NULL, NULL, &numOfTables);
H
Haojun Liao 已提交
3469

3470 3471
  if (numOfTables != 0) {
    fillTableCountScanDataBlock(pSupp, dbName, "", numOfTables, pRes);
3472
  }
S
slzhou 已提交
3473 3474 3475
}

static void buildVnodeGroupedStbTableCount(STableCountScanOperatorInfo* pInfo, STableCountScanSupp* pSupp,
3476
                                           SSDataBlock* pRes, char* dbName, tb_uid_t stbUid, SStorageAPI* pAPI) {
S
slzhou 已提交
3477
  char stbName[TSDB_TABLE_NAME_LEN] = {0};
3478
  pAPI->metaFn.getTableNameByUid(pInfo->readHandle.vnode, stbUid, stbName);
S
slzhou 已提交
3479 3480

  char fullStbName[TSDB_TABLE_FNAME_LEN] = {0};
D
dapan1121 已提交
3481
  if (pSupp->groupByDbName) {
H
Haojun Liao 已提交
3482
    snprintf(fullStbName, TSDB_TABLE_FNAME_LEN, "%s.%s", dbName, varDataVal(stbName));
D
dapan1121 已提交
3483
  } else {
H
Haojun Liao 已提交
3484
    snprintf(fullStbName, TSDB_TABLE_FNAME_LEN, "%s", varDataVal(stbName));
D
dapan1121 已提交
3485
  }
X
Xiaoyu Wang 已提交
3486

S
slzhou 已提交
3487 3488 3489
  uint64_t groupId = calcGroupId(fullStbName, strlen(fullStbName));
  pRes->info.id.groupId = groupId;

H
Haojun Liao 已提交
3490 3491
  int64_t ctbNum = 0;
  int32_t code = pAPI->metaFn.getNumOfChildTables(pInfo->readHandle.vnode, stbUid, &ctbNum);
H
Haojun Liao 已提交
3492
  fillTableCountScanDataBlock(pSupp, dbName, varDataVal(stbName), ctbNum, pRes);
S
shenglian zhou 已提交
3493 3494 3495
}

static void destoryTableCountScanOperator(void* param) {
S
slzhou 已提交
3496
  STableCountScanOperatorInfo* pTableCountScanInfo = param;
S
shenglian zhou 已提交
3497 3498
  blockDataDestroy(pTableCountScanInfo->pRes);

S
slzhou 已提交
3499
  taosArrayDestroy(pTableCountScanInfo->stbUidList);
S
shenglian zhou 已提交
3500 3501
  taosMemoryFreeClear(param);
}
dengyihao's avatar
dengyihao 已提交
3502 3503

// clang-format on