scanoperator.c 135.8 KB
Newer Older
H
Haojun Liao 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/*
 * Copyright (c) 2019 TAOS Data, Inc. <jhtao@taosdata.com>
 *
 * This program is free software: you can use, redistribute, and/or modify
 * it under the terms of the GNU Affero General Public License, version 3
 * or later ("AGPL"), as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

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

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

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

36 37 38
#include "storageapi.h"
#include "wal.h"

D
dapan1121 已提交
39 40
int32_t scanDebug = 0;

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

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

typedef struct STableMergeScanSortSourceParam {
  SOperatorInfo* pOperator;
  int32_t        readerIdx;
  uint64_t       uid;
56
  STsdbReader*   reader;
H
Haojun Liao 已提交
57 58
} STableMergeScanSortSourceParam;

59 60 61 62 63 64 65 66 67 68
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 已提交
69
static bool processBlockWithProbability(const SSampleExecInfo* pInfo);
70

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

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

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

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

98
  if (order == TSDB_ORDER_ASC) {
99
    w = getAlignQueryTimeWindow(pInterval, pBlockInfo->window.skey);
100
    ASSERT(w.ekey >= pBlockInfo->window.skey);
101

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

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

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

121
    if (w.skey > pBlockInfo->window.skey) {
122 123 124
      return true;
    }

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

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

  return false;
}

141 142 143 144 145 146 147 148 149 150 151
// 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 已提交
152 153
  SResultRowPosition* p1 = (SResultRowPosition*)tSimpleHashGet(pTableScanInfo->base.pdInfo.pAggSup->pResultRowHashTable,
                                                               buf, GET_RES_WINDOW_KEY_LEN(sizeof(groupId)));
154 155 156 157 158

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

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

164 165 166
  return (SResultRow*)((char*)(*pPage) + p1->offset);
}

167 168 169 170 171 172 173 174
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 已提交
175

176 177 178 179 180
  taosHashPut(pTableScanInfo->pIgnoreTables, &uid, sizeof(uid), &pTableScanInfo->scanTimes, sizeof(pTableScanInfo->scanTimes));

  return TSDB_CODE_SUCCESS;
}

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

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

H
Haojun Liao 已提交
189
  SExprSupp* pSup1 = pTableScanInfo->base.pdInfo.pExprSup;
190 191

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

  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 已提交
202
    SResultRowEntryInfo* pEntry = getResultEntryInfo(pRow, i, pTableScanInfo->base.pdInfo.pExprSup->rowEntryInfoOffset);
203 204 205 206 207 208 209 210 211

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

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

  if (notLoadBlock) {
    *status = FUNC_DATA_REQUIRED_NOT_LOAD;
216
    code = insertTableToScanIgnoreList(pTableScanInfo, pBlockInfo->id.uid);
217 218
  }

219
  return code;
220 221
}

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

H
Haojun Liao 已提交
228
  bool keep = filterRangeExecute(pFilterInfo, pColsAgg, numOfCols, numOfRows);
H
Haojun Liao 已提交
229 230 231
  return keep;
}

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

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

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

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

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

    // reset the error code.
    terrno = 0;
H
Haojun Liao 已提交
262 263 264
  }
}

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

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

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

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

291
  pLimitInfo->numOfOutputRows += pBlock->info.rows;
292
  return false;
293 294
}

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

300
  SFileBlockLoadRecorder* pCost = &pTableScanInfo->readRecorder;
H
Haojun Liao 已提交
301 302

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

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

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

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

H
Haojun Liao 已提交
346
  ASSERT(*status == FUNC_DATA_REQUIRED_DATA_LOAD);
347

H
Haojun Liao 已提交
348
  // try to filter data block according to sma info
H
Haojun Liao 已提交
349
  if (pOperator->exprSupp.pFilterInfo != NULL && (!loadSMA)) {
350 351 352
    bool success = doLoadBlockSMA(pTableScanInfo, pBlock, pTaskInfo);
    if (success) {
      size_t size = taosArrayGetSize(pBlock->pDataBlock);
H
Haojun Liao 已提交
353
      bool   keep = doFilterByBlockSMA(pOperator->exprSupp.pFilterInfo, pBlock->pBlockAgg, size, pBlockInfo->rows);
354
      if (!keep) {
X
Xiaoyu Wang 已提交
355 356
        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);
357 358 359
        pCost->filterOutBlocks += 1;
        (*status) = FUNC_DATA_REQUIRED_FILTEROUT;

360
        pAPI->tsdReader.tsdReaderReleaseDataBlock(pTableScanInfo->dataReader);
361 362
        return TSDB_CODE_SUCCESS;
      }
363
    }
H
Haojun Liao 已提交
364
  }
365

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

369
  // try to filter data block according to current results
370 371
  doDynamicPruneDataBlock(pOperator, pBlockInfo, status);
  if (*status == FUNC_DATA_REQUIRED_NOT_LOAD) {
X
Xiaoyu Wang 已提交
372 373
    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);
374
    pCost->skipBlocks += 1;
375
    pAPI->tsdReader.tsdReaderReleaseDataBlock(pTableScanInfo->dataReader);
376

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

H
Haojun Liao 已提交
386 387
  pCost->totalCheckedRows += pBlock->info.rows;
  pCost->loadBlocks += 1;
388

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

H
Haojun Liao 已提交
394
  ASSERT(p == pBlock);
395
  doSetTagColumnData(pTableScanInfo, pBlock, pTaskInfo, pBlock->info.rows);
396

H
Haojun Liao 已提交
397 398
  // restore the previous value
  pCost->totalRows -= pBlock->info.rows;
399

H
Haojun Liao 已提交
400
  if (pOperator->exprSupp.pFilterInfo != NULL) {
401 402
    int32_t code = doFilter(pBlock, pOperator->exprSupp.pFilterInfo, &pTableScanInfo->matchInfo);
    if (code != TSDB_CODE_SUCCESS) return code;
403

404
    int64_t st = taosGetTimestampUs();
405 406
    double el = (taosGetTimestampUs() - st) / 1000.0;
    pTableScanInfo->readRecorder.filterTime += el;
407

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

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

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

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

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

435 436
typedef struct STableCachedVal {
  const char* pName;
437
  STag*       pTags;
438 439
} STableCachedVal;

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

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

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

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

  return pVal;
}

466
// const void *key, size_t keyLen, void *value
D
dapan1121 已提交
467 468 469 470 471 472
static void freeCachedMetaItem(const void* key, size_t keyLen, void* value, void* ud) {
  (void)key;
  (void)keyLen;
  (void)ud;
  freeTableCachedVal(value);
}
473

474 475 476 477 478
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);
479
    colDataSetNNULL(pColInfoData, 0, pBlock->info.rows);
480 481 482
  }
}

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

490
  int32_t code = 0;
491
  bool    freeReader = false;
492

493 494 495 496
  // backup the rows
  int32_t backupRows = pBlock->info.rows;
  pBlock->info.rows = rows;

497
  STableCachedVal val = {0};
498 499

  SMetaReader mr = {0};
500
  LRUHandle*  h = NULL;
501

502 503 504
  // todo refactor: extract method
  // the handling of the null data should be packed in the extracted method

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

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

525
    pHandle->api.metaReaderFn.readerReleaseLock(&mr);
526

527 528
    val.pName = mr.me.name;
    val.pTags = (STag*)mr.me.ctbEntry.pTags;
529 530

    freeReader = true;
531
  } else {
532 533
    pCache->metaFetch += 1;

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

552
      pHandle->api.metaReaderFn.readerReleaseLock(&mr);
553

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

H
Haojun Liao 已提交
556
      val = *pVal;
557
      freeReader = true;
H
Haojun Liao 已提交
558

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

H
Haojun Liao 已提交
570
      taosLRUCacheRelease(pCache->pTableMetaEntryCache, h, false);
571
    }
H
Haojun Liao 已提交
572

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

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

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

584
    int32_t functionId = pExpr1->pExpr->_function.functionId;
585 586 587

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

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

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

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

H
Haojun Liao 已提交
629
  return TSDB_CODE_SUCCESS;
630 631
}

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

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

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

H
Haojun Liao 已提交
642
  colInfoDataEnsureCapacity(&infoData, 1, false);
643
  colDataSetVal(&infoData, 0, buf, false);
644

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

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

D
dapan1121 已提交
654
  colDataDestroy(&infoData);
655 656
}

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

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

666 667
  int64_t st = taosGetTimestampUs();

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

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

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

684
    if (pOperator->status == OP_EXEC_DONE) {
685
      pAPI->tsdReader.tsdReaderReleaseDataBlock(pTableScanInfo->base.dataReader);
686 687 688
      break;
    }

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

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

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

705 706 707 708
    if (status == FUNC_DATA_REQUIRED_ALL_FILTEROUT) {
      break;
    }

709 710 711
    // 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;
712
    }
713

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

H
Haojun Liao 已提交
717
    pOperator->cost.totalCost = pTableScanInfo->base.readRecorder.elapsedTime;
718
    pBlock->info.scanFlag = pTableScanInfo->base.scanFlag;
719
    return pBlock;
H
Haojun Liao 已提交
720 721 722 723
  }
  return NULL;
}

H
Haojun Liao 已提交
724
static SSDataBlock* doGroupedTableScan(SOperatorInfo* pOperator) {
H
Haojun Liao 已提交
725 726
  STableScanInfo* pTableScanInfo = pOperator->info;
  SExecTaskInfo*  pTaskInfo = pOperator->pTaskInfo;
727
  SStorageAPI* pAPI = &pTaskInfo->storageAPI;
H
Haojun Liao 已提交
728 729

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

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

741
    pTableScanInfo->scanTimes += 1;
742
    taosHashClear(pTableScanInfo->pIgnoreTables);
743

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

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

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

763
    while (pTableScanInfo->scanTimes < total) {
H
Haojun Liao 已提交
764 765 766
      SSDataBlock* p = doTableScanImpl(pOperator);
      if (p != NULL) {
        return p;
767
      }
H
Haojun Liao 已提交
768

769
      pTableScanInfo->scanTimes += 1;
770
      taosHashClear(pTableScanInfo->pIgnoreTables);
H
Haojun Liao 已提交
771

772
      if (pTableScanInfo->scanTimes < total) {
773
        setTaskStatus(pTaskInfo, TASK_NOT_COMPLETED);
G
Ganlin Zhao 已提交
774
        pTableScanInfo->base.scanFlag = MAIN_SCAN;
H
Haojun Liao 已提交
775

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

wmmhello's avatar
wmmhello 已提交
782 783 784 785 786 787
  return NULL;
}

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

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

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

L
Liu Jicong 已提交
801 802
      // if no data, switch to next table and continue scan
      pInfo->currentTable++;
803 804

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

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

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

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

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

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

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

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

H
Haojun Liao 已提交
846
    SSDataBlock* result = doGroupedTableScan(pOperator);
847 848 849
    if (result != NULL) {
      return result;
    }
H
Haojun Liao 已提交
850

851
    if ((++pInfo->currentGroupId) >= tableListGetOutputGroups(pInfo->base.pTableListInfo)) {
H
Haojun Liao 已提交
852
      setOperatorCompleted(pOperator);
853 854
      return NULL;
    }
wmmhello's avatar
wmmhello 已提交
855

856 857
    // reset value for the next group data output
    pOperator->status = OP_OPENED;
858
    resetLimitInfoForNextGroup(&pInfo->base.limitInfo);
wmmhello's avatar
wmmhello 已提交
859

5
54liuyao 已提交
860
    int32_t        num = 0;
861
    STableKeyInfo* pList = NULL;
862
    tableListGetGroupList(pInfo->base.pTableListInfo, pInfo->currentGroupId, &pList, &num);
wmmhello's avatar
wmmhello 已提交
863

864 865
    pAPI->tsdReader.tsdSetQueryTableList(pInfo->base.dataReader, pList, num);
    pAPI->tsdReader.tsdReaderResetStatus(pInfo->base.dataReader, &pInfo->base.cond);
866
    pInfo->scanTimes = 0;
wmmhello's avatar
wmmhello 已提交
867

H
Haojun Liao 已提交
868
    result = doGroupedTableScan(pOperator);
869 870 871
    if (result != NULL) {
      return result;
    }
872

H
Haojun Liao 已提交
873
    setOperatorCompleted(pOperator);
874 875
    return NULL;
  }
H
Haojun Liao 已提交
876 877
}

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

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

890
  pAPI->tsdReaderClose(pBase->dataReader);
891
  pBase->dataReader = NULL;
892

893 894
  if (pBase->matchInfo.pList != NULL) {
    taosArrayDestroy(pBase->matchInfo.pList);
895
  }
L
Liu Jicong 已提交
896

897
  tableListDestroy(pBase->pTableListInfo);
898 899 900 901 902 903 904
  taosLRUCacheCleanup(pBase->metaCache.pTableMetaEntryCache);
  cleanupExprSupp(&pBase->pseudoSup);
}

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

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

920
  SScanPhysiNode*     pScanNode = &pTableScanNode->scan;
H
Haojun Liao 已提交
921
  SDataBlockDescNode* pDescNode = pScanNode->node.pOutputDataBlockDesc;
922 923

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

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

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

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

H
Haojun Liao 已提交
945 946
  pInfo->base.pdInfo.interval = extractIntervalInfo(pTableScanNode);
  pInfo->base.readHandle = *readHandle;
H
Haojun Liao 已提交
947 948
  pInfo->base.dataBlockLoadFlag = pTableScanNode->dataRequired;

949 950
  pInfo->sample.sampleRatio = pTableScanNode->ratio;
  pInfo->sample.seed = taosGetTimestampSec();
951

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

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

wmmhello's avatar
wmmhello 已提交
962
  pInfo->currentGroupId = -1;
963
  pInfo->assignBlockUid = pTableScanNode->assignBlockUid;
964
  pInfo->hasGroupByTag = pTableScanNode->pGroupTags ? true : false;
965

L
Liu Jicong 已提交
966 967
  setOperatorInfo(pOperator, "TableScanOperator", QUERY_NODE_PHYSICAL_PLAN_TABLE_SCAN, false, OP_NOT_OPENED, pInfo,
                  pTaskInfo);
968
  pOperator->exprSupp.numOfExprs = numOfCols;
969

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

D
dapan1121 已提交
977 978 979 980
  if (scanDebug) {
    pInfo->countOnly = true;
  }

H
Haojun Liao 已提交
981
  taosLRUCacheSetStrictCapacity(pInfo->base.metaCache.pTableMetaEntryCache, false);
982 983
  pOperator->fpSet = createOperatorFpSet(optrDummyOpenFn, doTableScan, NULL, destroyTableScanOperatorInfo,
                                         optrDefaultBufFn, getTableScannerExecInfo);
984 985 986

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

989
_error:
990 991 992
  if (pInfo != NULL) {
    destroyTableScanOperatorInfo(pInfo);
  }
993

994 995
  taosMemoryFreeClear(pOperator);
  pTaskInfo->code = code;
996
  return NULL;
H
Haojun Liao 已提交
997 998
}

999
SOperatorInfo* createTableSeqScanOperatorInfo(void* pReadHandle, SExecTaskInfo* pTaskInfo) {
H
Haojun Liao 已提交
1000
  STableScanInfo* pInfo = taosMemoryCalloc(1, sizeof(STableScanInfo));
L
Liu Jicong 已提交
1001
  SOperatorInfo*  pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
1002

H
Haojun Liao 已提交
1003
  pInfo->base.dataReader = pReadHandle;
L
Liu Jicong 已提交
1004
  //  pInfo->prevGroupId       = -1;
H
Haojun Liao 已提交
1005

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

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

1018
static bool isSessionWindow(SStreamScanInfo* pInfo) {
H
Haojun Liao 已提交
1019
  return pInfo->windowSup.parentType == QUERY_NODE_PHYSICAL_PLAN_STREAM_SESSION;
5
54liuyao 已提交
1020 1021
}

1022
static bool isStateWindow(SStreamScanInfo* pInfo) {
1023
  return pInfo->windowSup.parentType == QUERY_NODE_PHYSICAL_PLAN_STREAM_STATE;
5
54liuyao 已提交
1024
}
5
54liuyao 已提交
1025

L
Liu Jicong 已提交
1026
static bool isIntervalWindow(SStreamScanInfo* pInfo) {
1027 1028 1029
  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 已提交
1030 1031 1032
}

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

1036 1037 1038 1039
static bool isSlidingWindow(SStreamScanInfo* pInfo) {
  return isIntervalWindow(pInfo) && pInfo->interval.interval != pInfo->interval.sliding;
}

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

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

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

1061
  STableScanInfo*     pTableScanInfo = pTableScanOp->info;
H
Haojun Liao 已提交
1062
  SQueryTableDataCond cond = pTableScanInfo->base.cond;
1063 1064 1065 1066 1067 1068

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

  SExecTaskInfo* pTaskInfo = pTableScanOp->pTaskInfo;
1069
  SStorageAPI*   pAPI = &pTaskInfo->storageAPI;
1070 1071 1072

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

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

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

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

  return pBlock->info.rows > 0 ? pBlock : NULL;
1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111
}

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

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

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

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

1161
    if (win.skey == endData[*pRowIndex] && groupId == gpData[*pRowIndex]) {
L
Liu Jicong 已提交
1162 1163 1164
      win.skey = TMIN(win.skey, startData[*pRowIndex]);
      continue;
    }
1165

1166 1167
    ASSERT(!(win.skey > startData[*pRowIndex] && win.ekey < endData[*pRowIndex]) ||
           !(isInTimeWindow(&win, startData[*pRowIndex], 0) || isInTimeWindow(&win, endData[*pRowIndex], 0)));
L
Liu Jicong 已提交
1168 1169 1170
    break;
  }

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

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

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

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

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

H
Haojun Liao 已提交
1236
    doFilter(pResult, pInfo->pTableScanOp->exprSupp.pFilterInfo, NULL);
1237 1238 1239 1240
    if (pResult->info.rows == 0) {
      continue;
    }

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

      blockDataDestroy(tmpBlock);

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

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

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

  taosMemoryFree(pCur);
1283 1284 1285
  return code;
}

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

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

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

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

1348 1349
  SColumnInfoData* pSrcStartTsCol = (SColumnInfoData*)taosArrayGet(pSrcBlock->pDataBlock, START_TS_COLUMN_INDEX);
  SColumnInfoData* pSrcEndTsCol = (SColumnInfoData*)taosArrayGet(pSrcBlock->pDataBlock, END_TS_COLUMN_INDEX);
1350 1351
  SColumnInfoData* pSrcUidCol = taosArrayGet(pSrcBlock->pDataBlock, UID_COLUMN_INDEX);
  SColumnInfoData* pSrcGpCol = taosArrayGet(pSrcBlock->pDataBlock, GROUPID_COLUMN_INDEX);
5
54liuyao 已提交
1352

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

  if (pInfo->partitionSup.needCalc && srcStartTsCol[0] != srcEndTsCol[0]) {
    uint64_t     srcUid = srcUidData[0];
    TSKEY        startTs = srcStartTsCol[0];
    TSKEY        endTs = srcEndTsCol[0];
H
Haojun Liao 已提交
1363
    SSDataBlock* pPreRes = readPreVersionData(pInfo->pTableScanOp, srcUid, startTs, endTs, ver);
5
54liuyao 已提交
1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390
    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;
  }

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

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

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

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

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

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

1487 1488
void appendOneRowToStreamSpecialBlock(SSDataBlock* pBlock, TSKEY* pStartTs, TSKEY* pEndTs, uint64_t* pUid,
                                      uint64_t* pGp, void* pTbName) {
1489 1490
  SColumnInfoData* pStartTsCol = taosArrayGet(pBlock->pDataBlock, START_TS_COLUMN_INDEX);
  SColumnInfoData* pEndTsCol = taosArrayGet(pBlock->pDataBlock, END_TS_COLUMN_INDEX);
1491 1492
  SColumnInfoData* pUidCol = taosArrayGet(pBlock->pDataBlock, UID_COLUMN_INDEX);
  SColumnInfoData* pGpCol = taosArrayGet(pBlock->pDataBlock, GROUPID_COLUMN_INDEX);
1493 1494
  SColumnInfoData* pCalStartCol = taosArrayGet(pBlock->pDataBlock, CALCULATE_START_TS_COLUMN_INDEX);
  SColumnInfoData* pCalEndCol = taosArrayGet(pBlock->pDataBlock, CALCULATE_END_TS_COLUMN_INDEX);
1495
  SColumnInfoData* pTableCol = taosArrayGet(pBlock->pDataBlock, TABLE_NAME_COLUMN_INDEX);
1496 1497 1498 1499 1500 1501 1502
  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);
1503
  pBlock->info.rows++;
5
54liuyao 已提交
1504 1505
}

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

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

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

1558 1559
  blockDataEnsureCapacity(pInfo->pRes, pBlock->info.rows);

1560 1561 1562 1563
  pBlockInfo->rows = pBlock->info.rows;
  pBlockInfo->id.uid = pBlock->info.id.uid;
  pBlockInfo->type = STREAM_NORMAL;
  pBlockInfo->version = pBlock->info.version;
L
Liu Jicong 已提交
1564

1565
  STableScanInfo* pTableScanInfo = pInfo->pTableScanOp->info;
1566
  pBlockInfo->id.groupId = getTableGroupId(pTableScanInfo->base.pTableListInfo, pBlock->info.id.uid);
L
Liu Jicong 已提交
1567 1568

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

  // currently only the tbname pseudo column
  if (pInfo->numOfPseudoExpr > 0) {
L
Liu Jicong 已提交
1595
    int32_t code = addTagPseudoColumnData(&pInfo->readHandle, pInfo->pPseudoExpr, pInfo->numOfPseudoExpr, pInfo->pRes,
1596
                                          pBlockInfo->rows, GET_TASKID(pTaskInfo), &pTableScanInfo->base.metaCache);
K
kailixu 已提交
1597 1598
    // 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 已提交
1599
      blockDataFreeRes((SSDataBlock*)pBlock);
1600
      T_LONG_JMP(pTaskInfo->env, code);
H
Haojun Liao 已提交
1601
    }
K
kailixu 已提交
1602 1603 1604

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

1607
  if (filter) {
H
Haojun Liao 已提交
1608
    doFilter(pInfo->pRes, pOperator->exprSupp.pFilterInfo, NULL);
1609
  }
1610

1611
  pInfo->pRes->info.dataLoad = 1;
L
Liu Jicong 已提交
1612
  blockDataUpdateTsWindow(pInfo->pRes, pInfo->primaryTsIndex);
L
Liu Jicong 已提交
1613

L
Liu Jicong 已提交
1614
  calBlockTbName(pInfo, pInfo->pRes);
L
Liu Jicong 已提交
1615 1616
  return 0;
}
5
54liuyao 已提交
1617

L
Liu Jicong 已提交
1618
static SSDataBlock* doQueueScan(SOperatorInfo* pOperator) {
1619 1620 1621
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
  SStorageAPI*   pAPI = &pTaskInfo->storageAPI;

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

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

1627
  if (isTaskKilled(pTaskInfo)) {
L
Liu Jicong 已提交
1628
    return NULL;
L
Liu Jicong 已提交
1629 1630
  }

1631
  if (pTaskInfo->streamInfo.currentOffset.type == TMQ_OFFSET__SNAPSHOT_DATA) {
L
Liu Jicong 已提交
1632 1633
    SSDataBlock* pResult = doTableScan(pInfo->pTableScanOp);
    if (pResult && pResult->info.rows > 0) {
1634 1635 1636
//      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);
1637
      tqOffsetResetToData(&pTaskInfo->streamInfo.currentOffset, pResult->info.id.uid, pResult->info.window.ekey);
L
Liu Jicong 已提交
1638
      return pResult;
1639
    }
1640

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

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

wmmhello's avatar
wmmhello 已提交
1650
    tqOffsetResetToLog(&pTaskInfo->streamInfo.currentOffset, pTaskInfo->streamInfo.snapshotVer);
1651 1652
  }

1653
  if (pTaskInfo->streamInfo.currentOffset.type == TMQ_OFFSET__LOG) {
1654

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

H
Haojun Liao 已提交
1658
      SSDataBlock* pRes = pAPI->tqReaderFn.tqGetResultBlock(pInfo->tqReader);
1659
      struct SWalReader* pWalReader = pAPI->tqReaderFn.tqReaderGetWalReader(pInfo->tqReader);
1660 1661

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

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

L
Liu Jicong 已提交
1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697
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);
1698 1699

  int32_t j = 0;
L
Liu Jicong 已提交
1700
  for (int32_t i = 0; i < rows; i++) {
1701
    if (pInfo->readerFn.tqReaderIsQueriedTable(pReader, uidCol[i])) {
1702 1703 1704
      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 已提交
1705

1706 1707 1708
      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 已提交
1709 1710 1711
      j++;
    }
  }
1712

L
Liu Jicong 已提交
1713
  uint32_t cap = pDst->info.capacity;
L
Liu Jicong 已提交
1714 1715
  pDst->info = pSrc->info;
  pDst->info.rows = j;
L
Liu Jicong 已提交
1716
  pDst->info.capacity = cap;
L
Liu Jicong 已提交
1717 1718 1719 1720

  return 0;
}

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

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

1757 1758 1759 1760 1761 1762
//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 已提交
1763 1764

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

L
liuyao 已提交
1770
  void* pUpInfo = taosMemoryCalloc(1, sizeof(SUpdateInfo));
1771
  int32_t      code = pInfo->stateStore.updateInfoDeserialize(pBuff, len, pUpInfo);
L
liuyao 已提交
1772 1773 1774 1775 1776
  if (code == TSDB_CODE_SUCCESS) {
    pInfo->pUpdateInfo = pUpInfo;
  }
}

1777
static void doBlockDataWindowFilter(SSDataBlock* pBlock, int32_t tsIndex, STimeWindow* pWindow, const char* id) {
1778
  if (pWindow->skey != INT64_MIN || pWindow->ekey != INT64_MAX) {
1779
    bool* p = taosMemoryCalloc(pBlock->info.rows, sizeof(bool));
1780
    bool  hasUnqualified = false;
1781 1782 1783

    SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, tsIndex);

1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795
    if (pWindow->skey != INT64_MIN) {
      qDebug("%s filter for additional history window, skey:%" PRId64, id, pWindow->skey);

      for (int32_t i = 0; i < pBlock->info.rows; ++i) {
        int64_t* ts = (int64_t*)colDataGetData(pCol, i);
        p[i] = (*ts >= pWindow->skey);

        if (!p[i]) {
          hasUnqualified = true;
        }
      }
    } else if (pWindow->ekey != INT64_MAX) {
1796
      qDebug("%s filter for additional history window, ekey:%" PRId64, id, pWindow->ekey);
1797 1798 1799 1800 1801 1802 1803
      for (int32_t i = 0; i < pBlock->info.rows; ++i) {
        int64_t* ts = (int64_t*)colDataGetData(pCol, i);
        p[i] = (*ts <= pWindow->ekey);

        if (!p[i]) {
          hasUnqualified = true;
        }
1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850
      }
    }

    if (hasUnqualified) {
      trimDataBlock(pBlock, pBlock->info.rows, p);
    }

    taosMemoryFree(p);
  }
}

// re-build the delete block, ONLY according to the split timestamp
static void rebuildDeleteBlockData(SSDataBlock* pBlock, int64_t skey, const char* id) {
  if (skey == INT64_MIN) {
    return;
  }

  int32_t numOfRows = pBlock->info.rows;

  bool* p = taosMemoryCalloc(numOfRows, sizeof(bool));
  bool  hasUnqualified = false;

  SColumnInfoData* pSrcStartCol = taosArrayGet(pBlock->pDataBlock, START_TS_COLUMN_INDEX);
  uint64_t*        tsStartCol = (uint64_t*)pSrcStartCol->pData;
  SColumnInfoData* pSrcEndCol = taosArrayGet(pBlock->pDataBlock, END_TS_COLUMN_INDEX);
  uint64_t*        tsEndCol = (uint64_t*)pSrcEndCol->pData;

  for (int32_t i = 0; i < numOfRows; i++) {
    if (tsStartCol[i] < skey) {
      tsStartCol[i] = skey;
    }

    if (tsEndCol[i] >= skey) {
      p[i] = true;
    } else { // this row should be removed, since it is not in this query time window, which is [skey, INT64_MAX]
      hasUnqualified = true;
    }
  }

  if (hasUnqualified) {
    trimDataBlock(pBlock, pBlock->info.rows, p);
  }

  qDebug("%s re-build delete datablock, start key revised to:%"PRId64", rows:%"PRId64, id, skey, pBlock->info.rows);
  taosMemoryFree(p);
}

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

1856
  SStorageAPI*     pAPI = &pTaskInfo->storageAPI;
L
Liu Jicong 已提交
1857
  SStreamScanInfo* pInfo = pOperator->info;
1858
  SStreamTaskInfo* pStreamInfo = &pTaskInfo->streamInfo;
L
Liu Jicong 已提交
1859

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

1862
  if (pStreamInfo->recoverStep == STREAM_RECOVER_STEP__PREPARE1 || pStreamInfo->recoverStep == STREAM_RECOVER_STEP__PREPARE2) {
L
Liu Jicong 已提交
1863
    STableScanInfo* pTSInfo = pInfo->pTableScanOp->info;
1864
    memcpy(&pTSInfo->base.cond, &pStreamInfo->tableCond, sizeof(SQueryTableDataCond));
1865

1866 1867 1868
    if (pStreamInfo->recoverStep == STREAM_RECOVER_STEP__PREPARE1) {
      pTSInfo->base.cond.startVersion = pStreamInfo->fillHistoryVer.minVer;
      pTSInfo->base.cond.endVersion = pStreamInfo->fillHistoryVer.maxVer;
1869

1870
      pTSInfo->base.cond.twindows = pStreamInfo->fillHistoryWindow;
1871 1872
      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);
1873
      pStreamInfo->recoverStep = STREAM_RECOVER_STEP__SCAN1;
L
liuyao 已提交
1874
      pStreamInfo->recoverScanFinished = false;
1875
    } else {
1876 1877
      pTSInfo->base.cond.startVersion = pStreamInfo->fillHistoryVer.minVer;
      pTSInfo->base.cond.endVersion = pStreamInfo->fillHistoryVer.maxVer;
1878 1879 1880 1881
      pTSInfo->base.cond.twindows = pStreamInfo->fillHistoryWindow;
      qDebug("stream recover step2, 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);
L
liuyao 已提交
1882
      pStreamInfo->recoverStep = STREAM_RECOVER_STEP__NONE;
1883
    }
L
Liu Jicong 已提交
1884

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

H
Haojun Liao 已提交
1887
    pTSInfo->base.dataReader = NULL;
L
Liu Jicong 已提交
1888
    pInfo->pTableScanOp->status = OP_OPENED;
L
Liu Jicong 已提交
1889

L
Liu Jicong 已提交
1890 1891 1892 1893
    pTSInfo->scanTimes = 0;
    pTSInfo->currentGroupId = -1;
  }

L
liuyao 已提交
1894
  if (pStreamInfo->recoverStep == STREAM_RECOVER_STEP__SCAN1) {
L
liuyao 已提交
1895 1896 1897
    if (isTaskKilled(pTaskInfo)) {
      return NULL;
    }
5
54liuyao 已提交
1898 1899 1900 1901 1902 1903 1904

    switch (pInfo->scanMode) {
      case STREAM_SCAN_FROM_RES: {
        pInfo->scanMode = STREAM_SCAN_FROM_READERHANDLE;
        printDataBlock(pInfo->pRecoverRes, "scan recover");
        return pInfo->pRecoverRes;
      } break;
L
liuyao 已提交
1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933
      // case STREAM_SCAN_FROM_UPDATERES: {
      //   generateScanRange(pInfo, pInfo->pUpdateDataRes, pInfo->pUpdateRes);
      //   prepareRangeScan(pInfo, pInfo->pUpdateRes, &pInfo->updateResIndex);
      //   pInfo->scanMode = STREAM_SCAN_FROM_DATAREADER_RANGE;
      //   printDataBlock(pInfo->pUpdateRes, "recover update");
      //   return pInfo->pUpdateRes;
      // } break;
      // 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;
      // 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);
      //     printDataBlock(pSDB, "scan recover update");
      //     calBlockTbName(pInfo, pSDB);
      //     return pSDB;
      //   }
      //   blockDataCleanup(pInfo->pUpdateDataRes);
      //   pInfo->scanMode = STREAM_SCAN_FROM_READERHANDLE;
      // } break;
5
54liuyao 已提交
1934 1935 1936 1937 1938 1939 1940
      default:
        break;
    }

    pInfo->pRecoverRes = doTableScan(pInfo->pTableScanOp);
    if (pInfo->pRecoverRes != NULL) {
      calBlockTbName(pInfo, pInfo->pRecoverRes);
L
liuyao 已提交
1941
      if (!pInfo->igCheckUpdate && pInfo->pUpdateInfo) {
L
liuyao 已提交
1942 1943 1944 1945 1946 1947 1948
        // if (pStreamInfo->recoverStep == STREAM_RECOVER_STEP__SCAN1) {
        TSKEY maxTs = pAPI->stateStore.updateInfoFillBlockData(pInfo->pUpdateInfo, pInfo->pRecoverRes, pInfo->primaryTsIndex);
        pInfo->twAggSup.maxTs = TMAX(pInfo->twAggSup.maxTs, maxTs);
        // } else {
        //   pInfo->pUpdateInfo->maxDataVersion = TMAX(pInfo->pUpdateInfo->maxDataVersion, pStreamInfo->fillHistoryVer.maxVer);
        //   doCheckUpdate(pInfo, pInfo->pRecoverRes->info.window.ekey, pInfo->pRecoverRes);
        // }
1949
      }
5
54liuyao 已提交
1950 1951
      if (pInfo->pCreateTbRes->info.rows > 0) {
        pInfo->scanMode = STREAM_SCAN_FROM_RES;
1952
        printDataBlock(pInfo->pCreateTbRes, "recover createTbl");
5
54liuyao 已提交
1953 1954
        return pInfo->pCreateTbRes;
      }
1955

X
Xiaoyu Wang 已提交
1956
      qDebug("stream recover scan get block, rows %" PRId64, pInfo->pRecoverRes->info.rows);
5
54liuyao 已提交
1957 1958
      printDataBlock(pInfo->pRecoverRes, "scan recover");
      return pInfo->pRecoverRes;
L
Liu Jicong 已提交
1959
    }
1960
    pStreamInfo->recoverStep = STREAM_RECOVER_STEP__NONE;
L
Liu Jicong 已提交
1961
    STableScanInfo* pTSInfo = pInfo->pTableScanOp->info;
1962
    pAPI->tsdReader.tsdReaderClose(pTSInfo->base.dataReader);
D
dapan1121 已提交
1963

H
Haojun Liao 已提交
1964
    pTSInfo->base.dataReader = NULL;
1965

H
Haojun Liao 已提交
1966 1967
    pTSInfo->base.cond.startVersion = -1;
    pTSInfo->base.cond.endVersion = -1;
L
Liu Jicong 已提交
1968

1969
    pStreamInfo->recoverScanFinished = true;
L
Liu Jicong 已提交
1970 1971 1972
    return NULL;
  }

5
54liuyao 已提交
1973
  size_t total = taosArrayGetSize(pInfo->pBlockLists);
5
54liuyao 已提交
1974
// TODO: refactor
L
Liu Jicong 已提交
1975
FETCH_NEXT_BLOCK:
L
Liu Jicong 已提交
1976
  if (pInfo->blockType == STREAM_INPUT__DATA_BLOCK) {
H
Haojun Liao 已提交
1977
    if (pInfo->validBlockIndex >= total) {
L
Liu Jicong 已提交
1978
      doClearBufferedBlocks(pInfo);
H
Haojun Liao 已提交
1979 1980 1981
      return NULL;
    }

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

L
Liu Jicong 已提交
1985 1986
    SPackedData* pPacked = taosArrayGet(pInfo->pBlockLists, current);
    SSDataBlock* pBlock = pPacked->pDataBlock;
5
54liuyao 已提交
1987
    if (pBlock->info.parTbName[0]) {
1988
      pAPI->stateStore.streamStatePutParName(pStreamInfo->pState, pBlock->info.id.groupId, pBlock->info.parTbName);
1989
    }
1990

1991
    // TODO move into scan
5
54liuyao 已提交
1992 1993
    pBlock->info.calWin.skey = INT64_MIN;
    pBlock->info.calWin.ekey = INT64_MAX;
1994
    pBlock->info.dataLoad = 1;
L
fix bug  
liuyao 已提交
1995
    if (pInfo->pUpdateInfo) {
1996
      pInfo->pUpdateInfo->maxDataVersion = TMAX(pInfo->pUpdateInfo->maxDataVersion, pBlock->info.version);
L
fix bug  
liuyao 已提交
1997
    }
1998

1999
    blockDataUpdateTsWindow(pBlock, 0);
2000
    switch (pBlock->info.type) {
L
Liu Jicong 已提交
2001 2002 2003
      case STREAM_NORMAL:
      case STREAM_GET_ALL:
        return pBlock;
2004 2005 2006
      case STREAM_RETRIEVE: {
        pInfo->blockType = STREAM_INPUT__DATA_SUBMIT;
        pInfo->scanMode = STREAM_SCAN_FROM_DATAREADER_RETRIEVE;
2007
        copyDataBlock(pInfo->pUpdateRes, pBlock);
L
liuyao 已提交
2008
        pInfo->updateResIndex = 0;
2009
        prepareRangeScan(pInfo, pInfo->pUpdateRes, &pInfo->updateResIndex);
2010
        pAPI->stateStore.updateInfoAddCloseWindowSBF(pInfo->pUpdateInfo);
2011 2012
      } break;
      case STREAM_DELETE_DATA: {
2013
        printDataBlock(pBlock, "stream scan delete recv");
L
Liu Jicong 已提交
2014
        SSDataBlock* pDelBlock = NULL;
L
Liu Jicong 已提交
2015
        if (pInfo->tqReader) {
L
Liu Jicong 已提交
2016
          pDelBlock = createSpecialDataBlock(STREAM_DELETE_DATA);
L
Liu Jicong 已提交
2017
          filterDelBlockByUid(pDelBlock, pBlock, pInfo);
L
Liu Jicong 已提交
2018 2019
        } else {
          pDelBlock = pBlock;
L
Liu Jicong 已提交
2020
        }
2021

5
54liuyao 已提交
2022
        setBlockGroupIdByUid(pInfo, pDelBlock);
2023
        rebuildDeleteBlockData(pDelBlock, pStreamInfo->fillHistoryWindow.skey, id);
5
54liuyao 已提交
2024
        printDataBlock(pDelBlock, "stream scan delete recv filtered");
5
54liuyao 已提交
2025 2026 2027 2028 2029 2030
        if (pDelBlock->info.rows == 0) {
          if (pInfo->tqReader) {
            blockDataDestroy(pDelBlock);
          }
          goto FETCH_NEXT_BLOCK;
        }
2031

2032
        if (!isIntervalWindow(pInfo) && !isSessionWindow(pInfo) && !isStateWindow(pInfo)) {
L
Liu Jicong 已提交
2033
          generateDeleteResultBlock(pInfo, pDelBlock, pInfo->pDeleteDataRes);
2034
          pInfo->pDeleteDataRes->info.type = STREAM_DELETE_RESULT;
L
Liu Jicong 已提交
2035
          printDataBlock(pDelBlock, "stream scan delete result");
H
Haojun Liao 已提交
2036 2037
          blockDataDestroy(pDelBlock);

L
Liu Jicong 已提交
2038 2039 2040 2041 2042
          if (pInfo->pDeleteDataRes->info.rows > 0) {
            return pInfo->pDeleteDataRes;
          } else {
            goto FETCH_NEXT_BLOCK;
          }
2043 2044 2045
        } else {
          pInfo->blockType = STREAM_INPUT__DATA_SUBMIT;
          pInfo->updateResIndex = 0;
L
Liu Jicong 已提交
2046
          generateScanRange(pInfo, pDelBlock, pInfo->pUpdateRes);
2047 2048 2049
          prepareRangeScan(pInfo, pInfo->pUpdateRes, &pInfo->updateResIndex);
          copyDataBlock(pInfo->pDeleteDataRes, pInfo->pUpdateRes);
          pInfo->pDeleteDataRes->info.type = STREAM_DELETE_DATA;
L
Liu Jicong 已提交
2050 2051 2052 2053
          printDataBlock(pDelBlock, "stream scan delete data");
          if (pInfo->tqReader) {
            blockDataDestroy(pDelBlock);
          }
L
Liu Jicong 已提交
2054
          if (pInfo->pDeleteDataRes->info.rows > 0) {
5
54liuyao 已提交
2055
            pInfo->scanMode = STREAM_SCAN_FROM_DATAREADER_RANGE;
L
Liu Jicong 已提交
2056 2057 2058 2059
            return pInfo->pDeleteDataRes;
          } else {
            goto FETCH_NEXT_BLOCK;
          }
2060
        }
2061 2062 2063
      } break;
      default:
        break;
5
54liuyao 已提交
2064
    }
2065
    // printDataBlock(pBlock, "stream scan recv");
2066
    return pBlock;
L
Liu Jicong 已提交
2067
  } else if (pInfo->blockType == STREAM_INPUT__DATA_SUBMIT) {
2068
    qDebug("stream scan mode:%d, %s", pInfo->scanMode, id);
5
54liuyao 已提交
2069 2070 2071
    switch (pInfo->scanMode) {
      case STREAM_SCAN_FROM_RES: {
        pInfo->scanMode = STREAM_SCAN_FROM_READERHANDLE;
5
54liuyao 已提交
2072
        doCheckUpdate(pInfo, pInfo->pRes->info.window.ekey, pInfo->pRes);
5
54liuyao 已提交
2073 2074 2075
        doFilter(pInfo->pRes, pOperator->exprSupp.pFilterInfo, NULL);
        pInfo->pRes->info.dataLoad = 1;
        blockDataUpdateTsWindow(pInfo->pRes, pInfo->primaryTsIndex);
5
54liuyao 已提交
2076 2077 2078
        if (pInfo->pRes->info.rows > 0) {
          return pInfo->pRes;
        }
5
54liuyao 已提交
2079
      } break;
2080
      case STREAM_SCAN_FROM_DELETE_DATA: {
2081 2082 2083 2084 2085 2086 2087
        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 已提交
2088 2089 2090 2091 2092 2093 2094 2095 2096 2097
      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) {
2098
          STableScanInfo* pTableScanInfo = pInfo->pTableScanOp->info;
5
54liuyao 已提交
2099 2100
          pSDB->info.type = pInfo->scanMode == STREAM_SCAN_FROM_DATAREADER_RANGE ? STREAM_NORMAL : STREAM_PULL_DATA;
          checkUpdateData(pInfo, true, pSDB, false);
L
liuyao 已提交
2101
          printDataBlock(pSDB, "stream scan update");
L
Liu Jicong 已提交
2102
          calBlockTbName(pInfo, pSDB);
5
54liuyao 已提交
2103 2104
          return pSDB;
        }
2105
        blockDataCleanup(pInfo->pUpdateDataRes);
5
54liuyao 已提交
2106 2107 2108 2109
        pInfo->scanMode = STREAM_SCAN_FROM_READERHANDLE;
      } break;
      default:
        break;
2110
    }
2111

2112
    SStreamAggSupporter* pSup = pInfo->windowSup.pStreamAggSup;
5
54liuyao 已提交
2113
    if (isStateWindow(pInfo) && pSup->pScanBlock->info.rows > 0) {
2114 2115
      pInfo->scanMode = STREAM_SCAN_FROM_DATAREADER_RANGE;
      pInfo->updateResIndex = 0;
5
54liuyao 已提交
2116 2117
      copyDataBlock(pInfo->pUpdateRes, pSup->pScanBlock);
      blockDataCleanup(pSup->pScanBlock);
2118
      prepareRangeScan(pInfo, pInfo->pUpdateRes, &pInfo->updateResIndex);
2119
      pInfo->pUpdateRes->info.type = STREAM_DELETE_DATA;
2120
      return pInfo->pUpdateRes;
5
54liuyao 已提交
2121
    }
5
54liuyao 已提交
2122

2123 2124
    SSDataBlock*    pBlock = pInfo->pRes;
    SDataBlockInfo* pBlockInfo = &pBlock->info;
H
Haojun Liao 已提交
2125
    int32_t         totalBlocks = taosArrayGetSize(pInfo->pBlockLists);
2126

L
Liu Jicong 已提交
2127
  NEXT_SUBMIT_BLK:
2128
    while (1) {
2129
      if (pInfo->readerFn.tqReaderCurrentBlockConsumed(pInfo->tqReader)) {
2130
        if (pInfo->validBlockIndex >= totalBlocks) {
2131
          pAPI->stateStore.updateInfoDestoryColseWinSBF(pInfo->pUpdateInfo);
2132 2133 2134 2135 2136 2137 2138 2139 2140 2141
          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);
2142
        if (pAPI->tqReaderFn.tqReaderSetSubmitMsg(pInfo->tqReader, pSubmit->msgStr, pSubmit->msgLen, pSubmit->ver) < 0) {
2143 2144 2145 2146
          qError("submit msg messed up when initializing stream submit block %p, current %d/%d, %s", pSubmit, current, totalBlocks, id);
          continue;
        }
      }
2147

2148
      blockDataCleanup(pBlock);
2149

2150 2151
      while (pAPI->tqReaderFn.tqNextBlockImpl(pInfo->tqReader, id)) {
        SSDataBlock* pRes = NULL;
2152

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

2157
        if (code != TSDB_CODE_SUCCESS || pRes->info.rows == 0) {
2158
          qDebug("retrieve data failed, try next block in submit block, %s", id);
2159 2160 2161
          continue;
        }

2162
        setBlockIntoRes(pInfo, pRes, false);
2163

5
54liuyao 已提交
2164 2165
        if (pInfo->pCreateTbRes->info.rows > 0) {
          pInfo->scanMode = STREAM_SCAN_FROM_RES;
2166
          qDebug("create table res exists, rows:%"PRId64" return from stream scan, %s", pInfo->pCreateTbRes->info.rows, id);
5
54liuyao 已提交
2167
          return pInfo->pCreateTbRes;
2168 2169
        }

2170 2171
        // apply additional time window filter
        doBlockDataWindowFilter(pBlock, pInfo->primaryTsIndex, &pStreamInfo->fillHistoryWindow, id);
2172 2173
        pBlock->info.dataLoad = 1;
        blockDataUpdateTsWindow(pBlock, pInfo->primaryTsIndex);
2174

2175 2176 2177
        doCheckUpdate(pInfo, pBlockInfo->window.ekey, pBlock);
        doFilter(pBlock, pOperator->exprSupp.pFilterInfo, NULL);

2178 2179 2180
        int64_t numOfUpdateRes = pInfo->pUpdateDataRes->info.rows;
        qDebug("%s %" PRId64 " rows in datablock, update res:%" PRId64, id, pBlockInfo->rows, numOfUpdateRes);
        if (pBlockInfo->rows > 0 || numOfUpdateRes > 0) {
2181 2182
          break;
        }
2183
      }
H
Haojun Liao 已提交
2184

2185
      if (pBlockInfo->rows > 0 || pInfo->pUpdateDataRes->info.rows > 0) {
5
54liuyao 已提交
2186
        break;
2187 2188
      } else {
        continue;
5
54liuyao 已提交
2189
      }
H
Haojun Liao 已提交
2190 2191 2192 2193
    }

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

2196
    qDebug("stream scan completed, and return source rows:%" PRId64", %s", pBlockInfo->rows, id);
L
Liu Jicong 已提交
2197
    if (pBlockInfo->rows > 0) {
2198
      return pBlock;
L
Liu Jicong 已提交
2199
    }
2200 2201 2202 2203 2204 2205

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

    goto NEXT_SUBMIT_BLK;
H
Haojun Liao 已提交
2206
  }
2207

2208
  return NULL;
H
Haojun Liao 已提交
2209 2210
}

H
Haojun Liao 已提交
2211
static SArray* extractTableIdList(const STableListInfo* pTableListInfo) {
2212 2213 2214
  SArray* tableIdList = taosArrayInit(4, sizeof(uint64_t));

  // Transfer the Array of STableKeyInfo into uid list.
H
Haojun Liao 已提交
2215 2216 2217
  size_t size = tableListGetSize(pTableListInfo);
  for (int32_t i = 0; i < size; ++i) {
    STableKeyInfo* pkeyInfo = tableListGetInfo(pTableListInfo, i);
2218 2219 2220 2221 2222 2223
    taosArrayPush(tableIdList, &pkeyInfo->uid);
  }

  return tableIdList;
}

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

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

wmmhello's avatar
wmmhello 已提交
2234
  qDebug("tmqsnap doRawScan called");
2235
  if (pTaskInfo->streamInfo.currentOffset.type == TMQ_OFFSET__SNAPSHOT_DATA) {
D
dapan1121 已提交
2236
    bool hasNext = false;
2237
    if (pInfo->dataReader && pInfo->sContext->withMeta != ONLY_META) {
2238
      code = pAPI->tsdReader.tsdNextDataBlock(pInfo->dataReader, &hasNext);
D
dapan1121 已提交
2239
      if (code) {
2240
        pAPI->tsdReader.tsdReaderReleaseDataBlock(pInfo->dataReader);
2241
        T_LONG_JMP(pTaskInfo->env, code);
D
dapan1121 已提交
2242 2243
      }
    }
X
Xiaoyu Wang 已提交
2244

D
dapan1121 已提交
2245
    if (pInfo->dataReader && hasNext) {
wmmhello's avatar
wmmhello 已提交
2246
      if (isTaskKilled(pTaskInfo)) {
2247
        pAPI->tsdReader.tsdReaderReleaseDataBlock(pInfo->dataReader);
2248
        T_LONG_JMP(pTaskInfo->env, pTaskInfo->code);
wmmhello's avatar
wmmhello 已提交
2249
      }
2250

2251
      SSDataBlock* pBlock = pAPI->tsdReader.tsdReaderRetrieveDataBlock(pInfo->dataReader, NULL);
H
Haojun Liao 已提交
2252
      if (pBlock == NULL) {
2253
        T_LONG_JMP(pTaskInfo->env, terrno);
wmmhello's avatar
wmmhello 已提交
2254 2255
      }

H
Haojun Liao 已提交
2256
      qDebug("tmqsnap doRawScan get data uid:%" PRId64 "", pBlock->info.id.uid);
2257
      tqOffsetResetToData(&pTaskInfo->streamInfo.currentOffset, pBlock->info.id.uid, pBlock->info.window.ekey);
wmmhello's avatar
wmmhello 已提交
2258 2259
      return pBlock;
    }
wmmhello's avatar
wmmhello 已提交
2260

H
Haojun Liao 已提交
2261
    SMetaTableInfo mtInfo = pAPI->snapshotFn.getMetaTableInfoFromSnapshot(pInfo->sContext);
X
Xiaoyu Wang 已提交
2262
    STqOffsetVal   offset = {0};
2263
    if (mtInfo.uid == 0 || pInfo->sContext->withMeta == ONLY_META) {  // read snapshot done, change to get data from wal
wmmhello's avatar
wmmhello 已提交
2264
      qDebug("tmqsnap read snapshot done, change to get data from wal");
2265
      tqOffsetResetToLog(&offset, pInfo->sContext->snapVersion);
L
Liu Jicong 已提交
2266
    } else {
2267
      tqOffsetResetToData(&offset, mtInfo.uid, INT64_MIN);
2268
      qDebug("tmqsnap change get data uid:%" PRId64 "", mtInfo.uid);
wmmhello's avatar
wmmhello 已提交
2269
    }
2270
    qStreamPrepareScan(pTaskInfo, &offset, pInfo->sContext->subType);
2271
    tDeleteSchemaWrapper(mtInfo.schema);
wmmhello's avatar
wmmhello 已提交
2272
    return NULL;
2273
  } else if (pTaskInfo->streamInfo.currentOffset.type == TMQ_OFFSET__SNAPSHOT_META) {
L
Liu Jicong 已提交
2274 2275 2276 2277 2278
    SSnapContext* sContext = pInfo->sContext;
    void*         data = NULL;
    int32_t       dataLen = 0;
    int16_t       type = 0;
    int64_t       uid = 0;
H
Haojun Liao 已提交
2279 2280
    if (pAPI->snapshotFn.getTableInfoFromSnapshot(sContext, &data, &dataLen, &type, &uid) < 0) {
      qError("tmqsnap getTableInfoFromSnapshot error");
wmmhello's avatar
wmmhello 已提交
2281
      taosMemoryFreeClear(data);
2282 2283 2284
      return NULL;
    }

2285
    if (!sContext->queryMeta) {  // change to get data next poll request
2286 2287 2288
      STqOffsetVal offset = {0};
      tqOffsetResetToData(&offset, 0, INT64_MIN);
      qStreamPrepareScan(pTaskInfo, &offset, pInfo->sContext->subType);
L
Liu Jicong 已提交
2289
    } else {
2290
      tqOffsetResetToMeta(&pTaskInfo->streamInfo.currentOffset, uid);
wmmhello's avatar
wmmhello 已提交
2291 2292 2293 2294
      pTaskInfo->streamInfo.metaRsp.resMsgType = type;
      pTaskInfo->streamInfo.metaRsp.metaRspLen = dataLen;
      pTaskInfo->streamInfo.metaRsp.metaRsp = data;
    }
2295

wmmhello's avatar
wmmhello 已提交
2296
    return NULL;
2297 2298 2299 2300
  }
  return NULL;
}

wmmhello's avatar
wmmhello 已提交
2301
static void destroyRawScanOperatorInfo(void* param) {
wmmhello's avatar
wmmhello 已提交
2302
  SStreamRawScanInfo* pRawScan = (SStreamRawScanInfo*)param;
2303
  pRawScan->pAPI->tsdReader.tsdReaderClose(pRawScan->dataReader);
2304
  pRawScan->pAPI->snapshotFn.destroySnapshot(pRawScan->sContext);
2305
  tableListDestroy(pRawScan->pTableListInfo);
wmmhello's avatar
wmmhello 已提交
2306 2307 2308
  taosMemoryFree(pRawScan);
}

L
Liu Jicong 已提交
2309 2310 2311
// for subscribing db or stb (not including column),
// if this scan is used, meta data can be return
// and schemas are decided when scanning
2312
SOperatorInfo* createRawScanOperatorInfo(SReadHandle* pHandle, SExecTaskInfo* pTaskInfo) {
L
Liu Jicong 已提交
2313 2314 2315 2316 2317
  // create operator
  // create tb reader
  // create meta reader
  // create tq reader

H
Haojun Liao 已提交
2318 2319
  int32_t code = TSDB_CODE_SUCCESS;

2320
  SStreamRawScanInfo* pInfo = taosMemoryCalloc(1, sizeof(SStreamRawScanInfo));
L
Liu Jicong 已提交
2321
  SOperatorInfo*      pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
2322
  if (pInfo == NULL || pOperator == NULL) {
H
Haojun Liao 已提交
2323 2324
    code = TSDB_CODE_OUT_OF_MEMORY;
    goto _end;
2325 2326
  }

2327
  pInfo->pTableListInfo = tableListCreate();
wmmhello's avatar
wmmhello 已提交
2328
  pInfo->vnode = pHandle->vnode;
H
Haojun Liao 已提交
2329
  pInfo->pAPI = &pTaskInfo->storageAPI;
wmmhello's avatar
wmmhello 已提交
2330

2331
  pInfo->sContext = pHandle->sContext;
L
Liu Jicong 已提交
2332 2333
  setOperatorInfo(pOperator, "RawScanOperator", QUERY_NODE_PHYSICAL_PLAN_TABLE_SCAN, false, OP_NOT_OPENED, pInfo,
                  pTaskInfo);
2334

2335
  pOperator->fpSet = createOperatorFpSet(NULL, doRawScan, NULL, destroyRawScanOperatorInfo, optrDefaultBufFn, NULL);
2336
  return pOperator;
H
Haojun Liao 已提交
2337

L
Liu Jicong 已提交
2338
_end:
H
Haojun Liao 已提交
2339 2340 2341 2342
  taosMemoryFree(pInfo);
  taosMemoryFree(pOperator);
  pTaskInfo->code = code;
  return NULL;
L
Liu Jicong 已提交
2343 2344
}

2345
static void destroyStreamScanOperatorInfo(void* param) {
2346
  SStreamScanInfo* pStreamScan = (SStreamScanInfo*)param;
2347

2348
  if (pStreamScan->pTableScanOp && pStreamScan->pTableScanOp->info) {
2349
    destroyOperator(pStreamScan->pTableScanOp);
2350
  }
2351

2352
  if (pStreamScan->tqReader) {
2353
    pStreamScan->readerFn.tqReaderClose(pStreamScan->tqReader);
2354
  }
H
Haojun Liao 已提交
2355 2356
  if (pStreamScan->matchInfo.pList) {
    taosArrayDestroy(pStreamScan->matchInfo.pList);
2357
  }
C
Cary Xu 已提交
2358 2359
  if (pStreamScan->pPseudoExpr) {
    destroyExprInfo(pStreamScan->pPseudoExpr, pStreamScan->numOfPseudoExpr);
L
Liu Jicong 已提交
2360
    taosMemoryFree(pStreamScan->pPseudoExpr);
C
Cary Xu 已提交
2361
  }
C
Cary Xu 已提交
2362

L
Liu Jicong 已提交
2363
  cleanupExprSupp(&pStreamScan->tbnameCalSup);
5
54liuyao 已提交
2364
  cleanupExprSupp(&pStreamScan->tagCalSup);
L
Liu Jicong 已提交
2365

2366
  pStreamScan->stateStore.updateInfoDestroy(pStreamScan->pUpdateInfo);
2367 2368 2369 2370
  blockDataDestroy(pStreamScan->pRes);
  blockDataDestroy(pStreamScan->pUpdateRes);
  blockDataDestroy(pStreamScan->pPullDataRes);
  blockDataDestroy(pStreamScan->pDeleteDataRes);
5
54liuyao 已提交
2371
  blockDataDestroy(pStreamScan->pUpdateDataRes);
5
54liuyao 已提交
2372
  blockDataDestroy(pStreamScan->pCreateTbRes);
2373 2374 2375 2376
  taosArrayDestroy(pStreamScan->pBlockLists);
  taosMemoryFree(pStreamScan);
}

L
liuyao 已提交
2377 2378
void streamScanReleaseState(SOperatorInfo* pOperator) {
  SStreamScanInfo* pInfo = pOperator->info;
L
liuyao 已提交
2379 2380 2381
  if (!pInfo->pState) {
    return;
  }
L
liuyao 已提交
2382 2383 2384 2385 2386 2387 2388
  if (!pInfo->pUpdateInfo) {
    return;
  }
  int32_t len = pInfo->stateStore.updateInfoSerialize(NULL, 0, pInfo->pUpdateInfo);
  void* pBuff = taosMemoryCalloc(1, len);
  pInfo->stateStore.updateInfoSerialize(pBuff, len, pInfo->pUpdateInfo);
  pInfo->stateStore.streamStateSaveInfo(pInfo->pState, STREAM_SCAN_OP_STATE_NAME, strlen(STREAM_SCAN_OP_STATE_NAME), pBuff, len);
L
liuyao 已提交
2389
  taosMemoryFree(pBuff);
L
liuyao 已提交
2390 2391 2392 2393
}

void streamScanReloadState(SOperatorInfo* pOperator) {
  SStreamScanInfo* pInfo = pOperator->info;
L
liuyao 已提交
2394 2395 2396
  if (!pInfo->pState) {
    return;
  }
L
liuyao 已提交
2397 2398 2399
  void*   pBuff = NULL;
  int32_t len = 0;
  pInfo->stateStore.streamStateGetInfo(pInfo->pState, STREAM_SCAN_OP_STATE_NAME, strlen(STREAM_SCAN_OP_STATE_NAME), &pBuff, &len);
L
liuyao 已提交
2400
  SUpdateInfo* pUpInfo = taosMemoryCalloc(1, sizeof(SUpdateInfo));
L
liuyao 已提交
2401
  int32_t      code = pInfo->stateStore.updateInfoDeserialize(pBuff, len, pUpInfo);
L
liuyao 已提交
2402
  taosMemoryFree(pBuff);
L
liuyao 已提交
2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422
  if (code == TSDB_CODE_SUCCESS && pInfo->pUpdateInfo) {
    if (pInfo->pUpdateInfo->minTS < 0) {
      pInfo->stateStore.updateInfoDestroy(pInfo->pUpdateInfo);
      pInfo->pUpdateInfo = pUpInfo;
    } else {
      pInfo->pUpdateInfo->minTS = TMAX(pInfo->pUpdateInfo->minTS, pUpInfo->minTS);
      pInfo->pUpdateInfo->maxDataVersion = TMAX(pInfo->pUpdateInfo->maxDataVersion, pUpInfo->maxDataVersion);
      SHashObj* curMap = pInfo->pUpdateInfo->pMap;
      void *pIte = taosHashIterate(curMap, NULL);
      while (pIte != NULL) {
        size_t keySize = 0;
        int64_t* pUid = taosHashGetKey(pIte, &keySize);
        taosHashPut(pUpInfo->pMap, pUid, sizeof(int64_t), pIte, sizeof(TSKEY));
        pIte = taosHashIterate(curMap, pIte);
      }
      taosHashCleanup(curMap);
      pInfo->pUpdateInfo->pMap = pUpInfo->pMap;
      pUpInfo->pMap = NULL;
      pInfo->stateStore.updateInfoDestroy(pUpInfo);
    }
L
liuyao 已提交
2423 2424
  } else {
    pInfo->stateStore.updateInfoDestroy(pUpInfo);
L
liuyao 已提交
2425 2426 2427
  }
}

2428
SOperatorInfo* createStreamScanOperatorInfo(SReadHandle* pHandle, STableScanPhysiNode* pTableScanNode, SNode* pTagCond,
2429
                                            STableListInfo* pTableListInfo, SExecTaskInfo* pTaskInfo) {
H
Haojun Liao 已提交
2430
  SArray*          pColIds = NULL;
2431 2432
  SStreamScanInfo* pInfo = taosMemoryCalloc(1, sizeof(SStreamScanInfo));
  SOperatorInfo*   pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
2433 2434
  SStorageAPI*     pAPI = &pTaskInfo->storageAPI;
  const char* idstr = pTaskInfo->id.str;
2435

H
Haojun Liao 已提交
2436
  if (pInfo == NULL || pOperator == NULL) {
S
Shengliang Guan 已提交
2437
    terrno = TSDB_CODE_OUT_OF_MEMORY;
2438
    tableListDestroy(pTableListInfo);
2439
    goto _error;
H
Haojun Liao 已提交
2440 2441
  }

2442
  SScanPhysiNode*     pScanPhyNode = &pTableScanNode->scan;
2443
  SDataBlockDescNode* pDescNode = pScanPhyNode->node.pOutputDataBlockDesc;
H
Haojun Liao 已提交
2444

2445
  pInfo->pTagCond = pTagCond;
2446
  pInfo->pGroupTags = pTableScanNode->pGroupTags;
2447

2448
  int32_t numOfCols = 0;
2449 2450
  int32_t code =
      extractColMatchInfo(pScanPhyNode->pScanCols, pDescNode, &numOfCols, COL_MATCH_FROM_COL_ID, &pInfo->matchInfo);
H
Haojun Liao 已提交
2451
  if (code != TSDB_CODE_SUCCESS) {
2452
    tableListDestroy(pTableListInfo);
H
Haojun Liao 已提交
2453 2454
    goto _error;
  }
2455

H
Haojun Liao 已提交
2456
  int32_t numOfOutput = taosArrayGetSize(pInfo->matchInfo.pList);
H
Haojun Liao 已提交
2457
  pColIds = taosArrayInit(numOfOutput, sizeof(int16_t));
2458
  for (int32_t i = 0; i < numOfOutput; ++i) {
H
Haojun Liao 已提交
2459
    SColMatchItem* id = taosArrayGet(pInfo->matchInfo.pList, i);
2460 2461

    int16_t colId = id->colId;
2462
    taosArrayPush(pColIds, &colId);
2463
    if (id->colId == PRIMARYKEY_TIMESTAMP_COL_ID) {
H
Haojun Liao 已提交
2464
      pInfo->primaryTsIndex = id->dstSlotId;
5
54liuyao 已提交
2465
    }
H
Haojun Liao 已提交
2466 2467
  }

L
Liu Jicong 已提交
2468 2469 2470 2471
  if (pTableScanNode->pSubtable != NULL) {
    SExprInfo* pSubTableExpr = taosMemoryCalloc(1, sizeof(SExprInfo));
    if (pSubTableExpr == NULL) {
      terrno = TSDB_CODE_OUT_OF_MEMORY;
2472
      tableListDestroy(pTableListInfo);
L
Liu Jicong 已提交
2473 2474
      goto _error;
    }
2475

L
Liu Jicong 已提交
2476 2477
    pInfo->tbnameCalSup.pExprInfo = pSubTableExpr;
    createExprFromOneNode(pSubTableExpr, pTableScanNode->pSubtable, 0);
2478
    if (initExprSupp(&pInfo->tbnameCalSup, pSubTableExpr, 1, &pTaskInfo->storageAPI.functionStore) != 0) {
2479
      tableListDestroy(pTableListInfo);
L
Liu Jicong 已提交
2480 2481 2482 2483
      goto _error;
    }
  }

2484 2485
  if (pTableScanNode->pTags != NULL) {
    int32_t    numOfTags;
5
54liuyao 已提交
2486
    SExprInfo* pTagExpr = createExpr(pTableScanNode->pTags, &numOfTags);
2487 2488
    if (pTagExpr == NULL) {
      terrno = TSDB_CODE_OUT_OF_MEMORY;
2489
      tableListDestroy(pTableListInfo);
2490 2491
      goto _error;
    }
2492
    if (initExprSupp(&pInfo->tagCalSup, pTagExpr, numOfTags, &pTaskInfo->storageAPI.functionStore) != 0) {
2493
      terrno = TSDB_CODE_OUT_OF_MEMORY;
2494
      tableListDestroy(pTableListInfo);
2495 2496 2497 2498
      goto _error;
    }
  }

L
Liu Jicong 已提交
2499
  pInfo->pBlockLists = taosArrayInit(4, sizeof(SPackedData));
H
Haojun Liao 已提交
2500
  if (pInfo->pBlockLists == NULL) {
2501
    terrno = TSDB_CODE_OUT_OF_MEMORY;
2502
    tableListDestroy(pTableListInfo);
2503
    goto _error;
H
Haojun Liao 已提交
2504 2505
  }

5
54liuyao 已提交
2506
  if (pHandle->vnode) {
2507
    SOperatorInfo*  pTableScanOp = createTableScanOperatorInfo(pTableScanNode, pHandle, pTableListInfo, pTaskInfo);
2508 2509 2510 2511
    if (pTableScanOp == NULL) {
      qError("createTableScanOperatorInfo error, errorcode: %d", pTaskInfo->code);
      goto _error;
    }
L
Liu Jicong 已提交
2512
    STableScanInfo* pTSInfo = (STableScanInfo*)pTableScanOp->info;
2513
    if (pHandle->version > 0) {
H
Haojun Liao 已提交
2514
      pTSInfo->base.cond.endVersion = pHandle->version;
2515
    }
L
Liu Jicong 已提交
2516

2517
    STableKeyInfo* pList = NULL;
5
54liuyao 已提交
2518
    int32_t        num = 0;
2519
    tableListGetGroupList(pTableListInfo, 0, &pList, &num);
2520

2521
    if (pHandle->initTableReader) {
L
Liu Jicong 已提交
2522
      pTSInfo->scanMode = TABLE_SCAN__TABLE_ORDER;
H
Haojun Liao 已提交
2523
      pTSInfo->base.dataReader = NULL;
L
Liu Jicong 已提交
2524 2525
    }

L
Liu Jicong 已提交
2526 2527
    if (pHandle->initTqReader) {
      ASSERT(pHandle->tqReader == NULL);
2528
      pInfo->tqReader = pAPI->tqReaderFn.tqReaderOpen(pHandle->vnode);
L
Liu Jicong 已提交
2529
      ASSERT(pInfo->tqReader);
2530
    } else {
L
Liu Jicong 已提交
2531 2532
      ASSERT(pHandle->tqReader);
      pInfo->tqReader = pHandle->tqReader;
2533 2534
    }

2535
    pInfo->pUpdateInfo = NULL;
2536
    pInfo->pTableScanOp = pTableScanOp;
2537
    if (pInfo->pTableScanOp->pTaskInfo->streamInfo.pState) {
2538
      pAPI->stateStore.streamStateSetNumber(pInfo->pTableScanOp->pTaskInfo->streamInfo.pState, -1);
2539
    }
L
Liu Jicong 已提交
2540

L
Liu Jicong 已提交
2541
    pInfo->readHandle = *pHandle;
L
Liu Jicong 已提交
2542
    pTaskInfo->streamInfo.snapshotVer = pHandle->version;
5
54liuyao 已提交
2543 2544
    pInfo->pCreateTbRes = buildCreateTableBlock(&pInfo->tbnameCalSup, &pInfo->tagCalSup);
    blockDataEnsureCapacity(pInfo->pCreateTbRes, 8);
L
Liu Jicong 已提交
2545

L
Liu Jicong 已提交
2546
    // set the extract column id to streamHandle
2547
    pAPI->tqReaderFn.tqReaderSetColIdList(pInfo->tqReader, pColIds);
2548
    SArray* tableIdList = extractTableIdList(((STableScanInfo*)(pInfo->pTableScanOp->info))->base.pTableListInfo);
2549
    code = pAPI->tqReaderFn.tqReaderSetQueryTableList(pInfo->tqReader, tableIdList, idstr);
L
Liu Jicong 已提交
2550 2551 2552 2553
    if (code != 0) {
      taosArrayDestroy(tableIdList);
      goto _error;
    }
2554

L
Liu Jicong 已提交
2555
    taosArrayDestroy(tableIdList);
H
Haojun Liao 已提交
2556
    memcpy(&pTaskInfo->streamInfo.tableCond, &pTSInfo->base.cond, sizeof(SQueryTableDataCond));
L
Liu Jicong 已提交
2557 2558
  } else {
    taosArrayDestroy(pColIds);
2559
    tableListDestroy(pTableListInfo);
H
Haojun Liao 已提交
2560
    pColIds = NULL;
5
54liuyao 已提交
2561 2562
  }

2563 2564 2565 2566 2567
  // create the pseduo columns info
  if (pTableScanNode->scan.pScanPseudoCols != NULL) {
    pInfo->pPseudoExpr = createExprInfo(pTableScanNode->scan.pScanPseudoCols, NULL, &pInfo->numOfPseudoExpr);
  }

H
Haojun Liao 已提交
2568 2569 2570 2571 2572
  code = filterInitFromNode((SNode*)pScanPhyNode->node.pConditions, &pOperator->exprSupp.pFilterInfo, 0);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }

H
Haojun Liao 已提交
2573
  pInfo->pRes = createDataBlockFromDescNode(pDescNode);
2574
  pInfo->pUpdateRes = createSpecialDataBlock(STREAM_CLEAR);
2575
  pInfo->scanMode = STREAM_SCAN_FROM_READERHANDLE;
L
Liu Jicong 已提交
2576
  pInfo->windowSup = (SWindowSupporter){.pStreamAggSup = NULL, .gap = -1, .parentType = QUERY_NODE_PHYSICAL_PLAN};
2577
  pInfo->groupId = 0;
2578
  pInfo->pPullDataRes = createSpecialDataBlock(STREAM_RETRIEVE);
2579
  pInfo->pStreamScanOp = pOperator;
2580
  pInfo->deleteDataIndex = 0;
2581
  pInfo->pDeleteDataRes = createSpecialDataBlock(STREAM_DELETE_DATA);
5
54liuyao 已提交
2582
  pInfo->updateWin = (STimeWindow){.skey = INT64_MAX, .ekey = INT64_MAX};
2583
  pInfo->pUpdateDataRes = createSpecialDataBlock(STREAM_CLEAR);
X
Xiaoyu Wang 已提交
2584
  pInfo->assignBlockUid = pTableScanNode->assignBlockUid;
2585
  pInfo->partitionSup.needCalc = false;
5
54liuyao 已提交
2586 2587
  pInfo->igCheckUpdate = pTableScanNode->igCheckUpdate;
  pInfo->igExpired = pTableScanNode->igExpired;
2588
  pInfo->twAggSup.maxTs = INT64_MIN;
L
liuyao 已提交
2589
  pInfo->pState = NULL;
2590 2591
  pInfo->stateStore = pTaskInfo->storageAPI.stateStore;
  pInfo->readerFn = pTaskInfo->storageAPI.tqReaderFn;
L
Liu Jicong 已提交
2592

L
fix bug  
liuyao 已提交
2593 2594 2595 2596
  // for stream
  if (pTaskInfo->streamInfo.pState) {
    void*   buff = NULL;
    int32_t len = 0;
2597 2598
    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 已提交
2599
    taosMemoryFree(buff);
L
fix bug  
liuyao 已提交
2600
  }
L
liuyao 已提交
2601

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

2606
  __optr_fn_t nextFn = (pTaskInfo->execModel == OPTR_EXEC_MODEL_STREAM) ? doStreamScan : doQueueScan;
L
Liu Jicong 已提交
2607 2608
  pOperator->fpSet =
      createOperatorFpSet(optrDummyOpenFn, nextFn, NULL, destroyStreamScanOperatorInfo, optrDefaultBufFn, NULL);
L
liuyao 已提交
2609
  setOperatorStreamStateFn(pOperator, streamScanReleaseState, streamScanReloadState);
2610

H
Haojun Liao 已提交
2611
  return pOperator;
2612

L
Liu Jicong 已提交
2613
_error:
H
Haojun Liao 已提交
2614 2615 2616 2617 2618 2619 2620 2621
  if (pColIds != NULL) {
    taosArrayDestroy(pColIds);
  }

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

2622 2623
  taosMemoryFreeClear(pOperator);
  return NULL;
H
Haojun Liao 已提交
2624 2625
}

2626
static void doTagScanOneTable(SOperatorInfo* pOperator, const SSDataBlock* pRes, int32_t count, SMetaReader* mr, SStorageAPI* pAPI) {
2627 2628 2629 2630
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
  STagScanInfo* pInfo = pOperator->info;
  SExprInfo*    pExprInfo = &pOperator->exprSupp.pExprInfo[0];

2631
  STableKeyInfo* item = tableListGetInfo(pInfo->pTableListInfo, pInfo->curPos);
2632
  int32_t        code = pAPI->metaReaderFn.getTableEntryByUid(mr, item->uid);
2633 2634 2635 2636
  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));
2637
    pAPI->metaReaderFn.clearReader(mr);
2638 2639 2640
    T_LONG_JMP(pTaskInfo->env, terrno);
  }

2641
  char str[512];
2642 2643 2644 2645 2646 2647
  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);
2648
      colDataSetVal(pDst, (count), str, false);
2649 2650 2651
    } else {  // it is a tag value
      STagVal val = {0};
      val.cid = pExprInfo[j].base.pParam[0].pCol->colId;
2652
      const char* p = pAPI->metaFn.extractTagVal((*mr).me.ctbEntry.pTags, pDst->info.type, &val);
2653 2654 2655 2656 2657 2658 2659

      char* data = NULL;
      if (pDst->info.type != TSDB_DATA_TYPE_JSON && p != NULL) {
        data = tTagValToData((const STagVal*)p, false);
      } else {
        data = (char*)p;
      }
2660
      colDataSetVal(pDst, (count), data,
2661 2662 2663 2664 2665 2666 2667 2668 2669 2670
                    (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);
      }
    }
  }
}

2671
static SSDataBlock* doTagScan(SOperatorInfo* pOperator) {
H
Haojun Liao 已提交
2672 2673 2674 2675
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

2676
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
2677
  SStorageAPI* pAPI = &pTaskInfo->storageAPI;
2678 2679

  STagScanInfo* pInfo = pOperator->info;
2680
  SExprInfo*    pExprInfo = &pOperator->exprSupp.pExprInfo[0];
2681
  SSDataBlock*  pRes = pInfo->pRes;
2682
  blockDataCleanup(pRes);
H
Haojun Liao 已提交
2683

2684
  int32_t size = tableListGetSize(pInfo->pTableListInfo);
wmmhello's avatar
wmmhello 已提交
2685
  if (size == 0) {
H
Haojun Liao 已提交
2686 2687 2688 2689
    setTaskStatus(pTaskInfo, TASK_COMPLETED);
    return NULL;
  }

2690 2691 2692
  char        str[512] = {0};
  int32_t     count = 0;
  SMetaReader mr = {0};
H
Haojun Liao 已提交
2693
  pAPI->metaReaderFn.initReader(&mr, pInfo->readHandle.vnode, 0, &pAPI->metaFn);
H
Haojun Liao 已提交
2694

wmmhello's avatar
wmmhello 已提交
2695
  while (pInfo->curPos < size && count < pOperator->resultInfo.capacity) {
2696
    doTagScanOneTable(pOperator, pRes, count, &mr, &pTaskInfo->storageAPI);
2697
    ++count;
wmmhello's avatar
wmmhello 已提交
2698
    if (++pInfo->curPos >= size) {
H
Haojun Liao 已提交
2699
      setOperatorCompleted(pOperator);
H
Haojun Liao 已提交
2700
    }
2701
    // each table with tbname is a group, hence its own block, but only group when slimit exists for performance reason.
2702
    if (pInfo->pSlimit != NULL) {
2703 2704 2705
      if (pInfo->curPos < pInfo->pSlimit->offset) {
        continue;
      }
2706
      pInfo->pRes->info.id.groupId = calcGroupId(mr.me.name, strlen(mr.me.name));
2707 2708 2709
      if (pInfo->curPos >= (pInfo->pSlimit->offset + pInfo->pSlimit->limit) - 1) {
        setOperatorCompleted(pOperator);
      }
2710
      break;
H
Haojun Liao 已提交
2711 2712 2713
    }
  }

2714
  pAPI->metaReaderFn.clearReader(&mr);
2715

2716
  // qDebug("QInfo:0x%"PRIx64" create tag values results completed, rows:%d", GET_TASKID(pRuntimeEnv), count);
H
Haojun Liao 已提交
2717
  if (pOperator->status == OP_EXEC_DONE) {
2718
    setTaskStatus(pTaskInfo, TASK_COMPLETED);
H
Haojun Liao 已提交
2719 2720 2721
  }

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

2724
  return (pRes->info.rows == 0) ? NULL : pInfo->pRes;
H
Haojun Liao 已提交
2725 2726
}

2727
static void destroyTagScanOperatorInfo(void* param) {
H
Haojun Liao 已提交
2728 2729
  STagScanInfo* pInfo = (STagScanInfo*)param;
  pInfo->pRes = blockDataDestroy(pInfo->pRes);
H
Haojun Liao 已提交
2730
  taosArrayDestroy(pInfo->matchInfo.pList);
2731
  pInfo->pTableListInfo = tableListDestroy(pInfo->pTableListInfo);
D
dapan1121 已提交
2732
  taosMemoryFreeClear(param);
H
Haojun Liao 已提交
2733 2734
}

S
slzhou 已提交
2735
SOperatorInfo* createTagScanOperatorInfo(SReadHandle* pReadHandle, STagScanPhysiNode* pPhyNode,
X
Xiaoyu Wang 已提交
2736
                                         STableListInfo* pTableListInfo, SExecTaskInfo* pTaskInfo) {
2737
  STagScanInfo*  pInfo = taosMemoryCalloc(1, sizeof(STagScanInfo));
H
Haojun Liao 已提交
2738 2739 2740 2741 2742
  SOperatorInfo* pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }

2743 2744 2745 2746
  SDataBlockDescNode* pDescNode = pPhyNode->node.pOutputDataBlockDesc;

  int32_t    numOfExprs = 0;
  SExprInfo* pExprInfo = createExprInfo(pPhyNode->pScanPseudoCols, NULL, &numOfExprs);
2747
  int32_t    code = initExprSupp(&pOperator->exprSupp, pExprInfo, numOfExprs, &pTaskInfo->storageAPI.functionStore);
2748 2749 2750
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
2751

H
Haojun Liao 已提交
2752 2753
  int32_t num = 0;
  code = extractColMatchInfo(pPhyNode->pScanPseudoCols, pDescNode, &num, COL_MATCH_FROM_COL_ID, &pInfo->matchInfo);
2754 2755 2756
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
2757

2758
  pInfo->pTableListInfo = pTableListInfo;
H
Haojun Liao 已提交
2759
  pInfo->pRes = createDataBlockFromDescNode(pDescNode);
2760 2761
  pInfo->readHandle = *pReadHandle;
  pInfo->curPos = 0;
2762
  pInfo->pSlimit = (SLimitNode*)pPhyNode->node.pSlimit; //TODO: slimit now only indicate group
2763

L
Liu Jicong 已提交
2764 2765
  setOperatorInfo(pOperator, "TagScanOperator", QUERY_NODE_PHYSICAL_PLAN_TAG_SCAN, false, OP_NOT_OPENED, pInfo,
                  pTaskInfo);
2766
  initResultSizeInfo(&pOperator->resultInfo, 4096);
2767 2768
  blockDataEnsureCapacity(pInfo->pRes, pOperator->resultInfo.capacity);

L
Liu Jicong 已提交
2769 2770
  pOperator->fpSet =
      createOperatorFpSet(optrDummyOpenFn, doTagScan, NULL, destroyTagScanOperatorInfo, optrDefaultBufFn, NULL);
H
Haojun Liao 已提交
2771 2772

  return pOperator;
2773

2774
_error:
H
Haojun Liao 已提交
2775 2776 2777 2778 2779
  taosMemoryFree(pInfo);
  taosMemoryFree(pOperator);
  terrno = TSDB_CODE_OUT_OF_MEMORY;
  return NULL;
}
2780

dengyihao's avatar
dengyihao 已提交
2781
static SSDataBlock* getTableDataBlockImpl(void* param) {
dengyihao's avatar
opt mem  
dengyihao 已提交
2782 2783 2784 2785
  STableMergeScanSortSourceParam* source = param;
  SOperatorInfo*                  pOperator = source->pOperator;
  STableMergeScanInfo*            pInfo = pOperator->info;
  SExecTaskInfo*                  pTaskInfo = pOperator->pTaskInfo;
2786 2787
  SStorageAPI* pAPI = &pTaskInfo->storageAPI;

S
slzhou 已提交
2788
  SSDataBlock*                    pBlock = pInfo->pReaderBlock;
D
dapan1121 已提交
2789
  int32_t                         code = 0;
dengyihao's avatar
opt mem  
dengyihao 已提交
2790

L
Liu Jicong 已提交
2791
  int64_t      st = taosGetTimestampUs();
X
Xiaoyu Wang 已提交
2792
  bool         hasNext = false;
D
dapan1121 已提交
2793

H
Haojun Liao 已提交
2794
  STsdbReader* reader = pInfo->base.dataReader;
D
dapan1121 已提交
2795
  while (true) {
2796
    code = pAPI->tsdReader.tsdNextDataBlock(reader, &hasNext);
D
dapan1121 已提交
2797
    if (code != 0) {
2798
      pAPI->tsdReader.tsdReaderReleaseDataBlock(reader);
D
dapan1121 已提交
2799 2800 2801 2802 2803 2804
      T_LONG_JMP(pTaskInfo->env, code);
    }

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

H
Haojun Liao 已提交
2806
    if (isTaskKilled(pTaskInfo)) {
2807
      pAPI->tsdReader.tsdReaderReleaseDataBlock(reader);
2808
      T_LONG_JMP(pTaskInfo->env, pTaskInfo->code);
dengyihao's avatar
opt mem  
dengyihao 已提交
2809 2810 2811
    }

    // process this data block based on the probabilities
H
Haojun Liao 已提交
2812
    bool processThisBlock = processBlockWithProbability(&pInfo->sample);
dengyihao's avatar
opt mem  
dengyihao 已提交
2813 2814 2815 2816 2817
    if (!processThisBlock) {
      continue;
    }

    uint32_t status = 0;
2818
    code = loadDataBlock(pOperator, &pInfo->base, pBlock, &status);
S
slzhou 已提交
2819
    //    code = loadDataBlockFromOneTable(pOperator, pTableScanInfo, pBlock, &status);
dengyihao's avatar
opt mem  
dengyihao 已提交
2820
    if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
2821
      T_LONG_JMP(pTaskInfo->env, code);
dengyihao's avatar
opt mem  
dengyihao 已提交
2822 2823
    }

2824 2825 2826 2827
    if (status == FUNC_DATA_REQUIRED_ALL_FILTEROUT) {
      break;
    }

dengyihao's avatar
opt mem  
dengyihao 已提交
2828 2829 2830 2831 2832
    // 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;
    }

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

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

    return pBlock;
  }
H
Haojun Liao 已提交
2840

dengyihao's avatar
opt mem  
dengyihao 已提交
2841 2842 2843
  return NULL;
}

2844 2845 2846
SArray* generateSortByTsInfo(SArray* colMatchInfo, int32_t order) {
  int32_t tsTargetSlotId = 0;
  for (int32_t i = 0; i < taosArrayGetSize(colMatchInfo); ++i) {
H
Haojun Liao 已提交
2847
    SColMatchItem* colInfo = taosArrayGet(colMatchInfo, i);
2848
    if (colInfo->colId == PRIMARYKEY_TIMESTAMP_COL_ID) {
H
Haojun Liao 已提交
2849
      tsTargetSlotId = colInfo->dstSlotId;
2850 2851 2852
    }
  }

2853 2854 2855
  SArray*         pList = taosArrayInit(1, sizeof(SBlockOrderInfo));
  SBlockOrderInfo bi = {0};
  bi.order = order;
2856
  bi.slotId = tsTargetSlotId;
2857 2858 2859 2860 2861 2862 2863
  bi.nullFirst = NULL_ORDER_FIRST;

  taosArrayPush(pList, &bi);

  return pList;
}

H
Haojun Liao 已提交
2864
int32_t dumpQueryTableCond(const SQueryTableDataCond* src, SQueryTableDataCond* dst) {
dengyihao's avatar
opt mem  
dengyihao 已提交
2865 2866 2867 2868 2869 2870 2871
  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 已提交
2872

2873
int32_t startGroupTableMergeScan(SOperatorInfo* pOperator) {
2874 2875
  STableMergeScanInfo* pInfo = pOperator->info;
  SExecTaskInfo*       pTaskInfo = pOperator->pTaskInfo;
2876 2877
  SReadHandle* pHandle = &pInfo->base.readHandle;
  SStorageAPI* pAPI = &pTaskInfo->storageAPI;
2878

S
slzhou 已提交
2879
  {
2880
    size_t  numOfTables = tableListGetSize(pInfo->base.pTableListInfo);
S
slzhou 已提交
2881
    int32_t i = pInfo->tableStartIndex + 1;
H
Haojun Liao 已提交
2882
    for (; i < numOfTables; ++i) {
2883
      STableKeyInfo* tableKeyInfo = tableListGetInfo(pInfo->base.pTableListInfo, i);
S
slzhou 已提交
2884 2885 2886 2887 2888 2889
      if (tableKeyInfo->groupId != pInfo->groupId) {
        break;
      }
    }
    pInfo->tableEndIndex = i - 1;
  }
2890

S
slzhou 已提交
2891 2892
  int32_t tableStartIdx = pInfo->tableStartIndex;
  int32_t tableEndIdx = pInfo->tableEndIndex;
2893

2894
  bool hasLimit = pInfo->limitInfo.limit.limit != -1 || pInfo->limitInfo.limit.offset != -1;
S
slzhou 已提交
2895
  int64_t mergeLimit = -1;
2896 2897 2898 2899
  if (hasLimit) {
      mergeLimit = pInfo->limitInfo.limit.limit + pInfo->limitInfo.limit.offset;
  }
  size_t szRow = blockDataGetRowSize(pInfo->pResBlock);   
2900
  if (hasLimit) {
2901 2902 2903 2904 2905 2906 2907 2908 2909 2910
    pInfo->pSortHandle = tsortCreateSortHandle(pInfo->pSortInfo, SORT_SINGLESOURCE_SORT, -1, -1,
                                              NULL, pTaskInfo->id.str, mergeLimit, szRow+8, tsPQSortMemThreshold * 1024* 1024);
  } else {
    pInfo->sortBufSize = 2048 * pInfo->bufPageSize;
    int32_t numOfBufPage = pInfo->sortBufSize / pInfo->bufPageSize;
    pInfo->pSortHandle = tsortCreateSortHandle(pInfo->pSortInfo, SORT_BLOCK_TS_MERGE, pInfo->bufPageSize, numOfBufPage,
                                              pInfo->pSortInputBlock, pTaskInfo->id.str, 0, 0, 0);
                                          
    tsortSetMergeLimit(pInfo->pSortHandle, mergeLimit);
  }
dengyihao's avatar
dengyihao 已提交
2911
  tsortSetFetchRawDataFp(pInfo->pSortHandle, getTableDataBlockImpl, NULL, NULL);
dengyihao's avatar
opt mem  
dengyihao 已提交
2912 2913 2914

  // one table has one data block
  int32_t numOfTable = tableEndIdx - tableStartIdx + 1;
H
Haojun Liao 已提交
2915

2916 2917 2918 2919
  STableMergeScanSortSourceParam param = {0};
  param.pOperator = pOperator;
  STableKeyInfo* startKeyInfo = tableListGetInfo(pInfo->base.pTableListInfo, tableStartIdx);
  pAPI->tsdReader.tsdReaderOpen(pHandle->vnode, &pInfo->base.cond, startKeyInfo, numOfTable, pInfo->pReaderBlock, (void**)&pInfo->base.dataReader, GET_TASKID(pTaskInfo), false, NULL);
dengyihao's avatar
opt mem  
dengyihao 已提交
2920

2921 2922 2923 2924
  SSortSource* ps = taosMemoryCalloc(1, sizeof(SSortSource));
  ps->param = &param;
  ps->onlyRef = true;
  tsortAddSource(pInfo->pSortHandle, ps);
2925 2926 2927 2928

  int32_t code = tsortOpen(pInfo->pSortHandle);

  if (code != TSDB_CODE_SUCCESS) {
2929
    T_LONG_JMP(pTaskInfo->env, terrno);
2930 2931
  }

2932 2933 2934 2935 2936 2937
  return TSDB_CODE_SUCCESS;
}

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

2940 2941 2942 2943 2944 2945 2946
  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;

2947 2948 2949
  if (pInfo->base.dataReader != NULL) {
    pAPI->tsdReader.tsdReaderClose(pInfo->base.dataReader);
    pInfo->base.dataReader = NULL;
2950
  }
2951

2952
  tsortDestroySortHandle(pInfo->pSortHandle);
dengyihao's avatar
dengyihao 已提交
2953
  pInfo->pSortHandle = NULL;
2954

2955
  resetLimitInfoForNextGroup(&pInfo->limitInfo);
2956 2957 2958
  return TSDB_CODE_SUCCESS;
}

2959 2960
// 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 已提交
2961 2962
SSDataBlock* getSortedTableMergeScanBlockData(SSortHandle* pHandle, SSDataBlock* pResBlock, int32_t capacity,
                                              SOperatorInfo* pOperator) {
2963 2964 2965
  STableMergeScanInfo* pInfo = pOperator->info;
  SExecTaskInfo*       pTaskInfo = pOperator->pTaskInfo;

2966
  blockDataCleanup(pResBlock);
S
slzhou 已提交
2967
  STupleHandle* pTupleHandle = NULL;
2968
  while (1) {
S
slzhou 已提交
2969 2970 2971 2972 2973 2974 2975 2976 2977 2978
    while (1) {
      pTupleHandle = tsortNextTuple(pHandle);
      if (pTupleHandle == NULL) {
        break;
      }

      appendOneRowToDataBlock(pResBlock, pTupleHandle);
      if (pResBlock->info.rows >= capacity) {
        break;
      }
2979 2980
    }

S
slzhou 已提交
2981 2982 2983
    if (tsortIsClosed(pHandle)) {
      terrno = TSDB_CODE_TSC_QUERY_CANCELLED;
      T_LONG_JMP(pOperator->pTaskInfo->env, terrno);
2984 2985
    }

S
slzhou 已提交
2986 2987 2988 2989 2990 2991
    bool limitReached = applyLimitOffset(&pInfo->limitInfo, pResBlock, pTaskInfo);
    qDebug("%s get sorted row block, rows:%" PRId64 ", limit:%" PRId64, GET_TASKID(pTaskInfo), pResBlock->info.rows,
          pInfo->limitInfo.numOfOutputRows);
    if (pTupleHandle == NULL || limitReached || pResBlock->info.rows > 0) {
      break;
    }  
D
dapan1121 已提交
2992
  }
2993
  return (pResBlock->info.rows > 0) ? pResBlock : NULL;
2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005
}

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) {
3006
    T_LONG_JMP(pTaskInfo->env, code);
3007
  }
3008

3009
  size_t tableListSize = tableListGetSize(pInfo->base.pTableListInfo);
S
slzhou 已提交
3010 3011
  if (!pInfo->hasGroupId) {
    pInfo->hasGroupId = true;
3012

S
slzhou 已提交
3013
    if (tableListSize == 0) {
H
Haojun Liao 已提交
3014
      setOperatorCompleted(pOperator);
3015 3016
      return NULL;
    }
S
slzhou 已提交
3017
    pInfo->tableStartIndex = 0;
3018
    pInfo->groupId = ((STableKeyInfo*)tableListGetInfo(pInfo->base.pTableListInfo, pInfo->tableStartIndex))->groupId;
3019 3020
    startGroupTableMergeScan(pOperator);
  }
3021

S
slzhou 已提交
3022 3023
  SSDataBlock* pBlock = NULL;
  while (pInfo->tableStartIndex < tableListSize) {
3024 3025 3026 3027
    if (isTaskKilled(pTaskInfo)) {
      T_LONG_JMP(pTaskInfo->env, pTaskInfo->code);
    }

L
Liu Jicong 已提交
3028 3029
    pBlock = getSortedTableMergeScanBlockData(pInfo->pSortHandle, pInfo->pResBlock, pOperator->resultInfo.capacity,
                                              pOperator);
S
slzhou 已提交
3030
    if (pBlock != NULL) {
H
Haojun Liao 已提交
3031
      pBlock->info.id.groupId = pInfo->groupId;
S
slzhou 已提交
3032 3033 3034
      pOperator->resultInfo.totalRows += pBlock->info.rows;
      return pBlock;
    } else {
3035
      // Data of this group are all dumped, let's try the next group
S
slzhou 已提交
3036 3037
      stopGroupTableMergeScan(pOperator);
      if (pInfo->tableEndIndex >= tableListSize - 1) {
H
Haojun Liao 已提交
3038
        setOperatorCompleted(pOperator);
S
slzhou 已提交
3039 3040
        break;
      }
3041

S
slzhou 已提交
3042
      pInfo->tableStartIndex = pInfo->tableEndIndex + 1;
3043
      pInfo->groupId = tableListGetInfo(pInfo->base.pTableListInfo, pInfo->tableStartIndex)->groupId;
S
slzhou 已提交
3044
      startGroupTableMergeScan(pOperator);
X
Xiaoyu Wang 已提交
3045
      resetLimitInfoForNextGroup(&pInfo->limitInfo);
S
slzhou 已提交
3046
    }
wmmhello's avatar
wmmhello 已提交
3047 3048
  }

3049 3050 3051
  return pBlock;
}

3052
void destroyTableMergeScanOperatorInfo(void* param) {
3053
  STableMergeScanInfo* pTableScanInfo = (STableMergeScanInfo*)param;
H
Haojun Liao 已提交
3054
  cleanupQueryTableDataCond(&pTableScanInfo->base.cond);
3055

3056
  int32_t numOfTable = taosArrayGetSize(pTableScanInfo->sortSourceParams);
H
Haojun Liao 已提交
3057

3058
  pTableScanInfo->base.readerAPI.tsdReaderClose(pTableScanInfo->base.dataReader);
D
dapan1121 已提交
3059 3060
  pTableScanInfo->base.dataReader = NULL;

3061
  taosArrayDestroy(pTableScanInfo->sortSourceParams);
dengyihao's avatar
dengyihao 已提交
3062 3063
  tsortDestroySortHandle(pTableScanInfo->pSortHandle);
  pTableScanInfo->pSortHandle = NULL;
3064

3065
  destroyTableScanBase(&pTableScanInfo->base, &pTableScanInfo->base.readerAPI);
3066 3067 3068

  pTableScanInfo->pResBlock = blockDataDestroy(pTableScanInfo->pResBlock);
  pTableScanInfo->pSortInputBlock = blockDataDestroy(pTableScanInfo->pSortInputBlock);
S
slzhou 已提交
3069
  pTableScanInfo->pReaderBlock = blockDataDestroy(pTableScanInfo->pReaderBlock);
3070 3071

  taosArrayDestroy(pTableScanInfo->pSortInfo);
D
dapan1121 已提交
3072
  taosMemoryFreeClear(param);
3073 3074 3075 3076
}

int32_t getTableMergeScanExplainExecInfo(SOperatorInfo* pOptr, void** pOptrExplain, uint32_t* len) {
  ASSERT(pOptr != NULL);
3077 3078
  // TODO: merge these two info into one struct
  STableMergeScanExecInfo* execInfo = taosMemoryCalloc(1, sizeof(STableMergeScanExecInfo));
L
Liu Jicong 已提交
3079
  STableMergeScanInfo*     pInfo = pOptr->info;
H
Haojun Liao 已提交
3080
  execInfo->blockRecorder = pInfo->base.readRecorder;
3081
  execInfo->sortExecInfo = pInfo->sortExecInfo;
3082 3083 3084

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

3086 3087 3088
  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
3089
SOperatorInfo* createTableMergeScanOperatorInfo(STableScanPhysiNode* pTableScanNode, SReadHandle* readHandle,
3090
                                                STableListInfo* pTableListInfo, SExecTaskInfo* pTaskInfo) {
3091 3092 3093 3094 3095
  STableMergeScanInfo* pInfo = taosMemoryCalloc(1, sizeof(STableMergeScanInfo));
  SOperatorInfo*       pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }
3096

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

  int32_t numOfCols = 0;
3100
  int32_t code = extractColMatchInfo(pTableScanNode->scan.pScanCols, pDescNode, &numOfCols, COL_MATCH_FROM_COL_ID,
H
Haojun Liao 已提交
3101
                                     &pInfo->base.matchInfo);
H
Haojun Liao 已提交
3102 3103 3104
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
3105

H
Haojun Liao 已提交
3106
  code = initQueryTableDataCond(&pInfo->base.cond, pTableScanNode);
3107
  if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
3108
    taosArrayDestroy(pInfo->base.matchInfo.pList);
3109 3110 3111 3112
    goto _error;
  }

  if (pTableScanNode->scan.pScanPseudoCols != NULL) {
H
Haojun Liao 已提交
3113
    SExprSupp* pSup = &pInfo->base.pseudoSup;
3114
    pSup->pExprInfo = createExprInfo(pTableScanNode->scan.pScanPseudoCols, NULL, &pSup->numOfExprs);
3115
    pSup->pCtx = createSqlFunctionCtx(pSup->pExprInfo, pSup->numOfExprs, &pSup->rowEntryInfoOffset, &pTaskInfo->storageAPI.functionStore);
3116 3117 3118 3119
  }

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

H
Haojun Liao 已提交
3120 3121 3122 3123 3124 3125
  pInfo->base.metaCache.pTableMetaEntryCache = taosLRUCacheInit(1024 * 128, -1, .5);
  if (pInfo->base.metaCache.pTableMetaEntryCache == NULL) {
    code = terrno;
    goto _error;
  }

H
Haojun Liao 已提交
3126
  pInfo->base.readerAPI = pTaskInfo->storageAPI.tsdReader;
H
Haojun Liao 已提交
3127 3128
  pInfo->base.dataBlockLoadFlag = FUNC_DATA_REQUIRED_DATA_LOAD;
  pInfo->base.scanFlag = MAIN_SCAN;
H
Haojun Liao 已提交
3129
  pInfo->base.readHandle = *readHandle;
3130

3131 3132
  pInfo->readIdx = -1;

3133 3134
  pInfo->base.limitInfo.limit.limit = -1;
  pInfo->base.limitInfo.slimit.limit = -1;
3135
  pInfo->base.pTableListInfo = pTableListInfo;
H
Haojun Liao 已提交
3136

3137
  pInfo->sample.sampleRatio = pTableScanNode->ratio;
L
Liu Jicong 已提交
3138
  pInfo->sample.seed = taosGetTimestampSec();
H
Haojun Liao 已提交
3139 3140 3141 3142 3143 3144

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

H
Haojun Liao 已提交
3145
  initResultSizeInfo(&pOperator->resultInfo, 1024);
H
Haojun Liao 已提交
3146
  pInfo->pResBlock = createDataBlockFromDescNode(pDescNode);
H
Haojun Liao 已提交
3147 3148
  blockDataEnsureCapacity(pInfo->pResBlock, pOperator->resultInfo.capacity);

3149
  pInfo->sortSourceParams = taosArrayInit(64, sizeof(STableMergeScanSortSourceParam));
3150

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

S
slzhou 已提交
3155 3156
  pInfo->pReaderBlock = createOneDataBlock(pInfo->pResBlock, false);

dengyihao's avatar
dengyihao 已提交
3157
  int32_t  rowSize = pInfo->pResBlock->info.rowSize;
A
Alex Duan 已提交
3158 3159
  uint32_t nCols = taosArrayGetSize(pInfo->pResBlock->pDataBlock);
  pInfo->bufPageSize = getProperSortPageSize(rowSize, nCols);
3160

L
Liu Jicong 已提交
3161 3162
  setOperatorInfo(pOperator, "TableMergeScanOperator", QUERY_NODE_PHYSICAL_PLAN_TABLE_MERGE_SCAN, false, OP_NOT_OPENED,
                  pInfo, pTaskInfo);
L
Liu Jicong 已提交
3163
  pOperator->exprSupp.numOfExprs = numOfCols;
3164

3165 3166
  pOperator->fpSet = createOperatorFpSet(optrDummyOpenFn, doTableMergeScan, NULL, destroyTableMergeScanOperatorInfo,
                                         optrDefaultBufFn, getTableMergeScanExplainExecInfo);
3167 3168 3169 3170 3171 3172 3173 3174 3175
  pOperator->cost.openCost = 0;
  return pOperator;

_error:
  pTaskInfo->code = TSDB_CODE_OUT_OF_MEMORY;
  taosMemoryFree(pInfo);
  taosMemoryFree(pOperator);
  return NULL;
}
S
shenglian zhou 已提交
3176 3177 3178 3179

// ====================================================================================================================
// TableCountScanOperator
static SSDataBlock* doTableCountScan(SOperatorInfo* pOperator);
S
slzhou 已提交
3180
static void         destoryTableCountScanOperator(void* param);
S
slzhou 已提交
3181
static void         buildVnodeGroupedStbTableCount(STableCountScanOperatorInfo* pInfo, STableCountScanSupp* pSupp,
3182
                                                   SSDataBlock* pRes, char* dbName, tb_uid_t stbUid, SStorageAPI* pAPI);
S
slzhou 已提交
3183
static void         buildVnodeGroupedNtbTableCount(STableCountScanOperatorInfo* pInfo, STableCountScanSupp* pSupp,
3184
                                                   SSDataBlock* pRes, char* dbName, SStorageAPI* pAPI);
S
slzhou 已提交
3185 3186
static void         buildVnodeFilteredTbCount(SOperatorInfo* pOperator, STableCountScanOperatorInfo* pInfo,
                                              STableCountScanSupp* pSupp, SSDataBlock* pRes, char* dbName);
L
Liu Jicong 已提交
3187 3188
static void         buildVnodeGroupedTableCount(SOperatorInfo* pOperator, STableCountScanOperatorInfo* pInfo,
                                                STableCountScanSupp* pSupp, SSDataBlock* pRes, int32_t vgId, char* dbName);
S
slzhou 已提交
3189 3190 3191 3192 3193 3194 3195
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 已提交
3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256
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 已提交
3257 3258
    tstrncpy(supp->dbNameFilter, tNameGetDbNameP(tableName), TSDB_DB_NAME_LEN);
    tstrncpy(supp->stbNameFilter, tNameGetTableName(tableName), TSDB_TABLE_NAME_LEN);
S
slzhou 已提交
3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270
  }
  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 已提交
3271

S
slzhou 已提交
3272 3273 3274 3275 3276 3277 3278 3279 3280
  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 已提交
3281

S
slzhou 已提交
3282 3283 3284 3285 3286 3287 3288
  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 已提交
3289

S
slzhou 已提交
3290
SOperatorInfo* createTableCountScanOperatorInfo(SReadHandle* readHandle, STableCountScanPhysiNode* pTblCountScanNode,
S
shenglian zhou 已提交
3291 3292 3293
                                                SExecTaskInfo* pTaskInfo) {
  int32_t code = TSDB_CODE_SUCCESS;

S
slzhou 已提交
3294
  SScanPhysiNode*              pScanNode = &pTblCountScanNode->scan;
S
slzhou 已提交
3295
  STableCountScanOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(STableCountScanOperatorInfo));
S
slzhou 已提交
3296
  SOperatorInfo*               pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
S
shenglian zhou 已提交
3297 3298 3299 3300 3301 3302 3303 3304 3305

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

  pInfo->readHandle = *readHandle;

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

S
slzhou 已提交
3309 3310 3311
  getTableCountScanSupp(pTblCountScanNode->pGroupTags, &pTblCountScanNode->scan.tableName,
                        pTblCountScanNode->scan.pScanCols, pTblCountScanNode->scan.pScanPseudoCols, &pInfo->supp,
                        pTaskInfo);
S
shenglian zhou 已提交
3312 3313 3314

  setOperatorInfo(pOperator, "TableCountScanOperator", QUERY_NODE_PHYSICAL_PLAN_TABLE_COUNT_SCAN, false, OP_NOT_OPENED,
                  pInfo, pTaskInfo);
L
Liu Jicong 已提交
3315 3316
  pOperator->fpSet = createOperatorFpSet(optrDummyOpenFn, doTableCountScan, NULL, destoryTableCountScanOperator,
                                         optrDefaultBufFn, NULL);
S
shenglian zhou 已提交
3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327
  return pOperator;

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

S
slzhou 已提交
3328 3329 3330
void fillTableCountScanDataBlock(STableCountScanSupp* pSupp, char* dbName, char* stbName, int64_t count,
                                 SSDataBlock* pRes) {
  if (pSupp->dbNameSlotId != -1) {
3331
    ASSERT(strlen(dbName));
S
slzhou 已提交
3332
    SColumnInfoData* colInfoData = taosArrayGet(pRes->pDataBlock, pSupp->dbNameSlotId);
H
Haojun Liao 已提交
3333 3334 3335 3336

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

S
slzhou 已提交
3337
    varDataSetLen(varDbName, strlen(dbName));
3338
    colDataSetVal(colInfoData, 0, varDbName, false);
S
slzhou 已提交
3339 3340 3341 3342
  }

  if (pSupp->stbNameSlotId != -1) {
    SColumnInfoData* colInfoData = taosArrayGet(pRes->pDataBlock, pSupp->stbNameSlotId);
3343
    if (strlen(stbName) != 0) {
S
slzhou 已提交
3344
      char varStbName[TSDB_TABLE_NAME_LEN + VARSTR_HEADER_SIZE] = {0};
H
Haojun Liao 已提交
3345
      strncpy(varDataVal(varStbName), stbName, TSDB_TABLE_NAME_LEN);
3346
      varDataSetLen(varStbName, strlen(stbName));
3347
      colDataSetVal(colInfoData, 0, varStbName, false);
3348
    } else {
3349
      colDataSetNULL(colInfoData, 0);
3350
    }
S
slzhou 已提交
3351 3352 3353
  }

  if (pSupp->tbCountSlotId != -1) {
S
slzhou 已提交
3354
    SColumnInfoData* colInfoData = taosArrayGet(pRes->pDataBlock, pSupp->tbCountSlotId);
3355
    colDataSetVal(colInfoData, 0, (char*)&count, false);
S
slzhou 已提交
3356 3357 3358 3359
  }
  pRes->info.rows = 1;
}

S
slzhou 已提交
3360
static SSDataBlock* buildSysDbTableCount(SOperatorInfo* pOperator, STableCountScanOperatorInfo* pInfo) {
S
slzhou 已提交
3361 3362 3363
  STableCountScanSupp* pSupp = &pInfo->supp;
  SSDataBlock*         pRes = pInfo->pRes;

S
slzhou 已提交
3364
  size_t infodbTableNum;
S
slzhou 已提交
3365
  getInfosDbMeta(NULL, &infodbTableNum);
S
slzhou 已提交
3366
  size_t perfdbTableNum;
S
slzhou 已提交
3367 3368
  getPerfDbMeta(NULL, &perfdbTableNum);

D
dapan1121 已提交
3369
  if (pSupp->groupByDbName || pSupp->groupByStbName) {
S
slzhou 已提交
3370
    buildSysDbGroupedTableCount(pOperator, pInfo, pSupp, pRes, infodbTableNum, perfdbTableNum);
S
slzhou 已提交
3371 3372
    return (pRes->info.rows > 0) ? pRes : NULL;
  } else {
S
slzhou 已提交
3373
    buildSysDbFilterTableCount(pOperator, pSupp, pRes, infodbTableNum, perfdbTableNum);
S
slzhou 已提交
3374 3375 3376 3377
    return (pRes->info.rows > 0) ? pRes : NULL;
  }
}

S
slzhou 已提交
3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393
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 已提交
3394 3395 3396 3397 3398 3399
    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 已提交
3400

S
slzhou 已提交
3401 3402 3403
    pRes->info.id.groupId = groupId;
    fillTableCountScanDataBlock(pSupp, TSDB_INFORMATION_SCHEMA_DB, "", infodbTableNum, pRes);
  } else if (pInfo->currGrpIdx == 1) {
D
dapan1121 已提交
3404 3405 3406 3407 3408 3409 3410
    uint64_t groupId = 0;
    if (pSupp->groupByDbName) {
      groupId = calcGroupId(TSDB_PERFORMANCE_SCHEMA_DB, strlen(TSDB_PERFORMANCE_SCHEMA_DB));
    } else {
      groupId = calcGroupId("", 0);
    }

S
slzhou 已提交
3411 3412 3413 3414 3415 3416 3417 3418
    pRes->info.id.groupId = groupId;
    fillTableCountScanDataBlock(pSupp, TSDB_PERFORMANCE_SCHEMA_DB, "", perfdbTableNum, pRes);
  } else {
    setOperatorCompleted(pOperator);
  }
  pInfo->currGrpIdx++;
}

S
shenglian zhou 已提交
3419
static SSDataBlock* doTableCountScan(SOperatorInfo* pOperator) {
S
slzhou 已提交
3420 3421 3422 3423
  SExecTaskInfo*               pTaskInfo = pOperator->pTaskInfo;
  STableCountScanOperatorInfo* pInfo = pOperator->info;
  STableCountScanSupp*         pSupp = &pInfo->supp;
  SSDataBlock*                 pRes = pInfo->pRes;
S
slzhou 已提交
3424
  blockDataCleanup(pRes);
3425

S
slzhou 已提交
3426 3427 3428
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }
S
slzhou 已提交
3429
  if (pInfo->readHandle.mnd != NULL) {
S
slzhou 已提交
3430
    return buildSysDbTableCount(pOperator, pInfo);
S
slzhou 已提交
3431
  }
S
slzhou 已提交
3432

S
slzhou 已提交
3433 3434 3435 3436 3437
  return buildVnodeDbTableCount(pOperator, pInfo, pSupp, pRes);
}

static SSDataBlock* buildVnodeDbTableCount(SOperatorInfo* pOperator, STableCountScanOperatorInfo* pInfo,
                                           STableCountScanSupp* pSupp, SSDataBlock* pRes) {
S
slzhou 已提交
3438 3439
  const char* db = NULL;
  int32_t     vgId = 0;
S
slzhou 已提交
3440
  char        dbName[TSDB_DB_NAME_LEN] = {0};
3441 3442
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
  SStorageAPI* pAPI = &pTaskInfo->storageAPI;
S
slzhou 已提交
3443

S
slzhou 已提交
3444
  // get dbname
3445
  pAPI->metaFn.getBasicInfo(pInfo->readHandle.vnode, &db, &vgId, NULL, NULL);
S
slzhou 已提交
3446 3447 3448 3449
  SName sn = {0};
  tNameFromString(&sn, db, T_NAME_ACCT | T_NAME_DB);
  tNameGetDbName(&sn, dbName);

D
dapan1121 已提交
3450
  if (pSupp->groupByDbName || pSupp->groupByStbName) {
S
slzhou 已提交
3451 3452 3453 3454 3455 3456 3457 3458 3459
    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) {
3460 3461 3462
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
  SStorageAPI* pAPI = &pTaskInfo->storageAPI;

S
slzhou 已提交
3463 3464 3465
  if (pSupp->groupByStbName) {
    if (pInfo->stbUidList == NULL) {
      pInfo->stbUidList = taosArrayInit(16, sizeof(tb_uid_t));
H
Haojun Liao 已提交
3466
      if (pAPI->metaFn.storeGetTableList(pInfo->readHandle.vnode, TSDB_SUPER_TABLE, pInfo->stbUidList) < 0) {
S
slzhou 已提交
3467
        qError("vgId:%d, failed to get stb id list error: %s", vgId, terrstr());
S
slzhou 已提交
3468
      }
S
slzhou 已提交
3469 3470 3471
    }
    if (pInfo->currGrpIdx < taosArrayGetSize(pInfo->stbUidList)) {
      tb_uid_t stbUid = *(tb_uid_t*)taosArrayGet(pInfo->stbUidList, pInfo->currGrpIdx);
3472
      buildVnodeGroupedStbTableCount(pInfo, pSupp, pRes, dbName, stbUid, pAPI);
S
slzhou 已提交
3473 3474 3475

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

      pInfo->currGrpIdx++;
S
slzhou 已提交
3479
    } else {
S
slzhou 已提交
3480
      setOperatorCompleted(pOperator);
S
slzhou 已提交
3481 3482
    }
  } else {
S
slzhou 已提交
3483 3484
    uint64_t groupId = calcGroupId(dbName, strlen(dbName));
    pRes->info.id.groupId = groupId;
3485 3486

    int64_t dbTableCount = 0;
3487
    pAPI->metaFn.getBasicInfo(pInfo->readHandle.vnode, NULL, NULL, &dbTableCount, NULL);
S
slzhou 已提交
3488 3489 3490 3491 3492 3493 3494
    fillTableCountScanDataBlock(pSupp, dbName, "", dbTableCount, pRes);
    setOperatorCompleted(pOperator);
  }
}

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

S
slzhou 已提交
3498 3499
  if (strlen(pSupp->dbNameFilter) != 0) {
    if (strlen(pSupp->stbNameFilter) != 0) {
H
Haojun Liao 已提交
3500
      uint64_t uid = 0;
3501
      pAPI->metaFn.getTableUidByName(pInfo->readHandle.vnode, pSupp->stbNameFilter, &uid);
3502 3503 3504 3505 3506

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

      fillTableCountScanDataBlock(pSupp, dbName, pSupp->stbNameFilter, numOfChildTables, pRes);
S
slzhou 已提交
3507
    } else {
H
Haojun Liao 已提交
3508 3509
      int64_t tbNumVnode = 0;
      pAPI->metaFn.getBasicInfo(pInfo->readHandle.vnode, NULL, NULL, &tbNumVnode, NULL);
S
slzhou 已提交
3510
      fillTableCountScanDataBlock(pSupp, dbName, "", tbNumVnode, pRes);
S
slzhou 已提交
3511
    }
S
slzhou 已提交
3512
  } else {
3513 3514
    int64_t tbNumVnode = 0;
    pAPI->metaFn.getBasicInfo(pInfo->readHandle.vnode, NULL, NULL, &tbNumVnode, NULL);
S
slzhou 已提交
3515
    fillTableCountScanDataBlock(pSupp, dbName, "", tbNumVnode, pRes);
S
slzhou 已提交
3516
  }
3517

S
slzhou 已提交
3518 3519 3520 3521
  setOperatorCompleted(pOperator);
}

static void buildVnodeGroupedNtbTableCount(STableCountScanOperatorInfo* pInfo, STableCountScanSupp* pSupp,
3522
                                           SSDataBlock* pRes, char* dbName, SStorageAPI* pAPI) {
S
slzhou 已提交
3523
  char fullStbName[TSDB_TABLE_FNAME_LEN] = {0};
D
dapan1121 已提交
3524 3525 3526
  if (pSupp->groupByDbName) {
    snprintf(fullStbName, TSDB_TABLE_FNAME_LEN, "%s.%s", dbName, "");
  }
X
Xiaoyu Wang 已提交
3527

S
slzhou 已提交
3528 3529
  uint64_t groupId = calcGroupId(fullStbName, strlen(fullStbName));
  pRes->info.id.groupId = groupId;
3530

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

3534 3535
  if (numOfTables != 0) {
    fillTableCountScanDataBlock(pSupp, dbName, "", numOfTables, pRes);
3536
  }
S
slzhou 已提交
3537 3538 3539
}

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

  char fullStbName[TSDB_TABLE_FNAME_LEN] = {0};
D
dapan1121 已提交
3545
  if (pSupp->groupByDbName) {
H
Haojun Liao 已提交
3546
    snprintf(fullStbName, TSDB_TABLE_FNAME_LEN, "%s.%s", dbName, varDataVal(stbName));
D
dapan1121 已提交
3547
  } else {
H
Haojun Liao 已提交
3548
    snprintf(fullStbName, TSDB_TABLE_FNAME_LEN, "%s", varDataVal(stbName));
D
dapan1121 已提交
3549
  }
X
Xiaoyu Wang 已提交
3550

S
slzhou 已提交
3551 3552 3553
  uint64_t groupId = calcGroupId(fullStbName, strlen(fullStbName));
  pRes->info.id.groupId = groupId;

H
Haojun Liao 已提交
3554 3555
  int64_t ctbNum = 0;
  int32_t code = pAPI->metaFn.getNumOfChildTables(pInfo->readHandle.vnode, stbUid, &ctbNum);
H
Haojun Liao 已提交
3556
  fillTableCountScanDataBlock(pSupp, dbName, varDataVal(stbName), ctbNum, pRes);
S
shenglian zhou 已提交
3557 3558 3559
}

static void destoryTableCountScanOperator(void* param) {
S
slzhou 已提交
3560
  STableCountScanOperatorInfo* pTableCountScanInfo = param;
S
shenglian zhou 已提交
3561 3562
  blockDataDestroy(pTableCountScanInfo->pRes);

S
slzhou 已提交
3563
  taosArrayDestroy(pTableCountScanInfo->stbUidList);
S
shenglian zhou 已提交
3564
  taosMemoryFreeClear(param);
3565
}