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

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

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

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

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

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

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

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

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

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

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

  STableCountScanSupp supp;

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

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

H
Haojun Liao 已提交
74
bool processBlockWithProbability(const SSampleExecInfo* pInfo) {
75 76 77 78 79 80 81 82 83 84 85 86
#if 0
  if (pInfo->sampleRatio == 1) {
    return true;
  }

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

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

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

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

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

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

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

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

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

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

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

  return false;
}

144 145 146 147 148 149 150 151 152 153 154
// this function is for table scanner to extract temporary results of upstream aggregate results.
static SResultRow* getTableGroupOutputBuf(SOperatorInfo* pOperator, uint64_t groupId, SFilePage** pPage) {
  if (pOperator->operatorType != QUERY_NODE_PHYSICAL_PLAN_TABLE_SCAN) {
    return NULL;
  }

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

  STableScanInfo* pTableScanInfo = pOperator->info;

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

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

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

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

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

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

  return TSDB_CODE_SUCCESS;
}

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

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

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

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

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

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

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

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

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

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

222
  return code;
223 224
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

410 411
    if (pBlock->info.rows == 0) {
      pCost->filterOutBlocks += 1;
D
dapan1121 已提交
412
      qDebug("%s data block filter out, brange:%" PRId64 "-%" PRId64 ", rows:%" PRId64 ", elapsed time:%.2f ms",
413 414 415 416
             GET_TASKID(pTaskInfo), pBlockInfo->window.skey, pBlockInfo->window.ekey, pBlockInfo->rows, el);
    } else {
      qDebug("%s data block filter applied, elapsed time:%.2f ms", GET_TASKID(pTaskInfo), el);
    }
417 418
  }

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

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

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

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

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

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

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

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

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

  return pVal;
}

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

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

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

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

487 488
  int32_t code = 0;

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

493
  bool            freeReader = false;
494
  STableCachedVal val = {0};
495 496

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

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

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

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

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

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

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

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

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

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

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

H
Haojun Liao 已提交
556
      int32_t ret = taosLRUCacheInsert(pCache->pTableMetaEntryCache, &pBlock->info.id.uid, sizeof(uint64_t), pVal,
557
                                       sizeof(STableCachedVal), freeCachedMetaItem, NULL, TAOS_LRU_PRIORITY_LOW);
558 559 560 561 562 563 564 565
      if (ret != TAOS_LRU_STATUS_OK) {
        qError("failed to put meta into lru cache, code:%d, %s", ret, idStr);
        freeTableCachedVal(pVal);
      }
    } else {
      pCache->cacheHit += 1;
      STableCachedVal* pVal = taosLRUCacheValue(pCache->pTableMetaEntryCache, h);
      val = *pVal;
H
Haojun Liao 已提交
566

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

663 664
  int64_t st = taosGetTimestampUs();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

L
Liu Jicong 已提交
1022
static bool isIntervalWindow(SStreamScanInfo* pInfo) {
1023 1024 1025
  return pInfo->windowSup.parentType == QUERY_NODE_PHYSICAL_PLAN_STREAM_INTERVAL ||
         pInfo->windowSup.parentType == QUERY_NODE_PHYSICAL_PLAN_STREAM_SEMI_INTERVAL ||
         pInfo->windowSup.parentType == QUERY_NODE_PHYSICAL_PLAN_STREAM_FINAL_INTERVAL;
5
54liuyao 已提交
1026 1027 1028
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

5
54liuyao 已提交
1108
static uint64_t getGroupIdByUid(SStreamScanInfo* pInfo, uint64_t uid) {
1109
  STableScanInfo* pTableScanInfo = pInfo->pTableScanOp->info;
1110
  return getTableGroupId(pTableScanInfo->base.pTableListInfo, uid);
1111 1112
}

5
54liuyao 已提交
1113 1114 1115 1116 1117 1118 1119 1120
static uint64_t getGroupIdByData(SStreamScanInfo* pInfo, uint64_t uid, TSKEY ts, int64_t maxVersion) {
  if (pInfo->partitionSup.needCalc) {
    return getGroupIdByCol(pInfo, uid, ts, maxVersion);
  }

  return getGroupIdByUid(pInfo, uid);
}

L
Liu Jicong 已提交
1121
static bool prepareRangeScan(SStreamScanInfo* pInfo, SSDataBlock* pBlock, int32_t* pRowIndex) {
5
54liuyao 已提交
1122 1123 1124
  if (pBlock->info.rows == 0) {
    return false;
  }
L
Liu Jicong 已提交
1125 1126 1127 1128 1129 1130 1131 1132 1133 1134
  if ((*pRowIndex) == pBlock->info.rows) {
    return false;
  }

  ASSERT(taosArrayGetSize(pBlock->pDataBlock) >= 3);
  SColumnInfoData* pStartTsCol = taosArrayGet(pBlock->pDataBlock, START_TS_COLUMN_INDEX);
  TSKEY*           startData = (TSKEY*)pStartTsCol->pData;
  SColumnInfoData* pEndTsCol = taosArrayGet(pBlock->pDataBlock, END_TS_COLUMN_INDEX);
  TSKEY*           endData = (TSKEY*)pEndTsCol->pData;
  STimeWindow      win = {.skey = startData[*pRowIndex], .ekey = endData[*pRowIndex]};
1135 1136 1137
  SColumnInfoData* pGpCol = taosArrayGet(pBlock->pDataBlock, GROUPID_COLUMN_INDEX);
  uint64_t*        gpData = (uint64_t*)pGpCol->pData;
  uint64_t         groupId = gpData[*pRowIndex];
1138 1139 1140 1141 1142 1143

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

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

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

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

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

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

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

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

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

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

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

1237 1238 1239 1240 1241 1242 1243 1244
    if (pInfo->partitionSup.needCalc) {
      SSDataBlock* tmpBlock = createOneDataBlock(pResult, true);
      blockDataCleanup(pResult);
      for (int32_t i = 0; i < tmpBlock->info.rows; i++) {
        if (calGroupIdByData(&pInfo->partitionSup, pInfo->pPartScalarSup, tmpBlock, i) == pInfo->groupId) {
          for (int32_t j = 0; j < pInfo->pTableScanOp->exprSupp.numOfExprs; j++) {
            SColumnInfoData* pSrcCol = taosArrayGet(tmpBlock->pDataBlock, j);
            SColumnInfoData* pDestCol = taosArrayGet(pResult->pDataBlock, j);
L
Liu Jicong 已提交
1245 1246
            bool             isNull = colDataIsNull(pSrcCol, tmpBlock->info.rows, i, NULL);
            char*            pSrcData = colDataGetData(pSrcCol, i);
1247
            colDataSetVal(pDestCol, pResult->info.rows, pSrcData, isNull);
1248 1249 1250 1251
          }
          pResult->info.rows++;
        }
      }
H
Haojun Liao 已提交
1252 1253 1254

      blockDataDestroy(tmpBlock);

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

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

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

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

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

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

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

static int32_t generateIntervalScanRange(SStreamScanInfo* pInfo, SSDataBlock* pSrcBlock, SSDataBlock* pDestBlock) {
  blockDataCleanup(pDestBlock);
  int32_t rows = pSrcBlock->info.rows;
  if (rows == 0) {
    return TSDB_CODE_SUCCESS;
1342
  }
1343

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

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

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

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

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

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

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

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

5
54liuyao 已提交
1425 1426 1427 1428 1429 1430 1431 1432 1433
  SColumnInfoData* pSrcStartTsCol = (SColumnInfoData*)taosArrayGet(pSrcBlock->pDataBlock, START_TS_COLUMN_INDEX);
  SColumnInfoData* pSrcEndTsCol = (SColumnInfoData*)taosArrayGet(pSrcBlock->pDataBlock, END_TS_COLUMN_INDEX);
  SColumnInfoData* pSrcUidCol = taosArrayGet(pSrcBlock->pDataBlock, UID_COLUMN_INDEX);
  uint64_t*        srcUidData = (uint64_t*)pSrcUidCol->pData;
  SColumnInfoData* pSrcGpCol = taosArrayGet(pSrcBlock->pDataBlock, GROUPID_COLUMN_INDEX);
  uint64_t*        srcGp = (uint64_t*)pSrcGpCol->pData;
  ASSERT(pSrcStartTsCol->info.type == TSDB_DATA_TYPE_TIMESTAMP);
  TSKEY*  srcStartTsCol = (TSKEY*)pSrcStartTsCol->pData;
  TSKEY*  srcEndTsCol = (TSKEY*)pSrcEndTsCol->pData;
H
Haojun Liao 已提交
1434
  int64_t ver = pSrcBlock->info.version - 1;
1435
  for (int32_t i = 0; i < pSrcBlock->info.rows; i++) {
5
54liuyao 已提交
1436 1437
    uint64_t srcUid = srcUidData[i];
    uint64_t groupId = srcGp[i];
L
Liu Jicong 已提交
1438
    char*    tbname[VARSTR_HEADER_SIZE + TSDB_TABLE_NAME_LEN] = {0};
5
54liuyao 已提交
1439
    if (groupId == 0) {
H
Haojun Liao 已提交
1440
      groupId = getGroupIdByData(pInfo, srcUid, srcStartTsCol[i], ver);
5
54liuyao 已提交
1441
    }
L
Liu Jicong 已提交
1442
    if (pInfo->tbnameCalSup.pExprInfo) {
1443
      void* parTbname = NULL;
1444
      pInfo->stateStore.streamStateGetParName(pInfo->pStreamScanOp->pTaskInfo->streamInfo.pState, groupId, &parTbname);
1445

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

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

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

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

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

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

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

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

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

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

  // todo extract method
H
Haojun Liao 已提交
1565 1566 1567
  for (int32_t i = 0; i < taosArrayGetSize(pInfo->matchInfo.pList); ++i) {
    SColMatchItem* pColMatchInfo = taosArrayGet(pInfo->matchInfo.pList, i);
    if (!pColMatchInfo->needOutput) {
L
Liu Jicong 已提交
1568 1569 1570 1571 1572 1573 1574
      continue;
    }

    bool colExists = false;
    for (int32_t j = 0; j < blockDataGetNumOfCols(pBlock); ++j) {
      SColumnInfoData* pResCol = bdGetColumnInfoData(pBlock, j);
      if (pResCol->info.colId == pColMatchInfo->colId) {
H
Haojun Liao 已提交
1575
        SColumnInfoData* pDst = taosArrayGet(pInfo->pRes->pDataBlock, pColMatchInfo->dstSlotId);
1576
        colDataAssign(pDst, pResCol, pBlock->info.rows, &pInfo->pRes->info);
L
Liu Jicong 已提交
1577 1578 1579 1580 1581 1582 1583
        colExists = true;
        break;
      }
    }

    // the required column does not exists in submit block, let's set it to be all null value
    if (!colExists) {
H
Haojun Liao 已提交
1584
      SColumnInfoData* pDst = taosArrayGet(pInfo->pRes->pDataBlock, pColMatchInfo->dstSlotId);
1585
      colDataSetNNULL(pDst, 0, pBlockInfo->rows);
L
Liu Jicong 已提交
1586 1587 1588 1589 1590
    }
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1703 1704 1705
      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 已提交
1706 1707 1708
      j++;
    }
  }
1709

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

  return 0;
}

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

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

1754 1755 1756 1757 1758 1759
//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 已提交
1760 1761

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

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

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

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

1782
  qDebug("stream scan started, %s", GET_TASKID(pTaskInfo));
H
Haojun Liao 已提交
1783

1784 1785
  if (pTaskInfo->streamInfo.recoverStep == STREAM_RECOVER_STEP__PREPARE1 ||
      pTaskInfo->streamInfo.recoverStep == STREAM_RECOVER_STEP__PREPARE2) {
L
Liu Jicong 已提交
1786
    STableScanInfo* pTSInfo = pInfo->pTableScanOp->info;
H
Haojun Liao 已提交
1787
    memcpy(&pTSInfo->base.cond, &pTaskInfo->streamInfo.tableCond, sizeof(SQueryTableDataCond));
1788
    if (pTaskInfo->streamInfo.recoverStep == STREAM_RECOVER_STEP__PREPARE1) {
H
Haojun Liao 已提交
1789 1790
      pTSInfo->base.cond.startVersion = 0;
      pTSInfo->base.cond.endVersion = pTaskInfo->streamInfo.fillHistoryVer1;
1791
      qDebug("stream recover step1, verRange:%" PRId64 " - %" PRId64, pTSInfo->base.cond.startVersion,
H
Haojun Liao 已提交
1792
             pTSInfo->base.cond.endVersion);
5
54liuyao 已提交
1793
      pTaskInfo->streamInfo.recoverStep = STREAM_RECOVER_STEP__SCAN1;
1794
    } else {
H
Haojun Liao 已提交
1795 1796
      pTSInfo->base.cond.startVersion = pTaskInfo->streamInfo.fillHistoryVer1 + 1;
      pTSInfo->base.cond.endVersion = pTaskInfo->streamInfo.fillHistoryVer2;
1797
      qDebug("stream recover step2, verRange:%" PRId64 " - %" PRId64, pTSInfo->base.cond.startVersion,
H
Haojun Liao 已提交
1798
             pTSInfo->base.cond.endVersion);
5
54liuyao 已提交
1799
      pTaskInfo->streamInfo.recoverStep = STREAM_RECOVER_STEP__SCAN2;
1800
    }
L
Liu Jicong 已提交
1801

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

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

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

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

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

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

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

H
Haojun Liao 已提交
1886
    pTSInfo->base.dataReader = NULL;
1887

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

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

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

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

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

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

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

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

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

L
Liu Jicong 已提交
2045
  NEXT_SUBMIT_BLK:
2046
    while (1) {
2047
      if (pInfo->readerFn.tqReaderCurrentBlockConsumed(pInfo->tqReader)) {
2048
        if (pInfo->validBlockIndex >= totalBlocks) {
2049
          pAPI->stateStore.updateInfoDestoryColseWinSBF(pInfo->pUpdateInfo);
2050 2051 2052 2053 2054 2055 2056 2057 2058 2059
          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);
2060
        if (pAPI->tqReaderFn.tqReaderSetSubmitMsg(pInfo->tqReader, pSubmit->msgStr, pSubmit->msgLen, pSubmit->ver) < 0) {
2061 2062 2063 2064
          qError("submit msg messed up when initializing stream submit block %p, current %d/%d, %s", pSubmit, current, totalBlocks, id);
          continue;
        }
      }
2065

2066
      blockDataCleanup(pBlock);
2067

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

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

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

2080
        setBlockIntoRes(pInfo, pRes, false);
2081

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

2088 2089 2090 2091
        doCheckUpdate(pInfo, pBlockInfo->window.ekey, pBlock);
        doFilter(pBlock, pOperator->exprSupp.pFilterInfo, NULL);
        pBlock->info.dataLoad = 1;
        blockDataUpdateTsWindow(pBlock, pInfo->primaryTsIndex);
2092

2093 2094
        qDebug("%" PRId64 " rows in datablock, update res:%" PRId64 " %s", pBlockInfo->rows,
               pInfo->pUpdateDataRes->info.rows, id);
2095 2096 2097
        if (pBlockInfo->rows > 0 || pInfo->pUpdateDataRes->info.rows > 0) {
          break;
        }
2098
      }
H
Haojun Liao 已提交
2099

2100
      if (pBlockInfo->rows > 0 || pInfo->pUpdateDataRes->info.rows > 0) {
5
54liuyao 已提交
2101
        break;
2102 2103
      } else {
        continue;
5
54liuyao 已提交
2104
      }
H
Haojun Liao 已提交
2105 2106 2107 2108
    }

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

2111
    qDebug("stream scan completed, and return source rows:%" PRId64", %s", pBlockInfo->rows, id);
L
Liu Jicong 已提交
2112
    if (pBlockInfo->rows > 0) {
2113
      return pBlock;
L
Liu Jicong 已提交
2114
    }
2115 2116 2117 2118 2119 2120

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

    goto NEXT_SUBMIT_BLK;
H
Haojun Liao 已提交
2121
  }
2122

2123
  return NULL;
H
Haojun Liao 已提交
2124 2125
}

H
Haojun Liao 已提交
2126
static SArray* extractTableIdList(const STableListInfo* pTableListInfo) {
2127 2128 2129
  SArray* tableIdList = taosArrayInit(4, sizeof(uint64_t));

  // Transfer the Array of STableKeyInfo into uid list.
H
Haojun Liao 已提交
2130 2131 2132
  size_t size = tableListGetSize(pTableListInfo);
  for (int32_t i = 0; i < size; ++i) {
    STableKeyInfo* pkeyInfo = tableListGetInfo(pTableListInfo, i);
2133 2134 2135 2136 2137 2138
    taosArrayPush(tableIdList, &pkeyInfo->uid);
  }

  return tableIdList;
}

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

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

wmmhello's avatar
wmmhello 已提交
2149
  qDebug("tmqsnap doRawScan called");
2150
  if (pTaskInfo->streamInfo.currentOffset.type == TMQ_OFFSET__SNAPSHOT_DATA) {
D
dapan1121 已提交
2151 2152
    bool hasNext = false;
    if (pInfo->dataReader) {
2153
      code = pAPI->tsdReader.tsdNextDataBlock(pInfo->dataReader, &hasNext);
D
dapan1121 已提交
2154
      if (code) {
2155
        pAPI->tsdReader.tsdReaderReleaseDataBlock(pInfo->dataReader);
2156
        T_LONG_JMP(pTaskInfo->env, code);
D
dapan1121 已提交
2157 2158
      }
    }
X
Xiaoyu Wang 已提交
2159

D
dapan1121 已提交
2160
    if (pInfo->dataReader && hasNext) {
wmmhello's avatar
wmmhello 已提交
2161
      if (isTaskKilled(pTaskInfo)) {
2162
        pAPI->tsdReader.tsdReaderReleaseDataBlock(pInfo->dataReader);
2163
        T_LONG_JMP(pTaskInfo->env, pTaskInfo->code);
wmmhello's avatar
wmmhello 已提交
2164
      }
2165

2166
      SSDataBlock* pBlock = pAPI->tsdReader.tsdReaderRetrieveDataBlock(pInfo->dataReader, NULL);
H
Haojun Liao 已提交
2167
      if (pBlock == NULL) {
2168
        T_LONG_JMP(pTaskInfo->env, terrno);
wmmhello's avatar
wmmhello 已提交
2169 2170
      }

H
Haojun Liao 已提交
2171
      qDebug("tmqsnap doRawScan get data uid:%" PRId64 "", pBlock->info.id.uid);
2172
      tqOffsetResetToData(&pTaskInfo->streamInfo.currentOffset, pBlock->info.id.uid, pBlock->info.window.ekey);
wmmhello's avatar
wmmhello 已提交
2173 2174
      return pBlock;
    }
wmmhello's avatar
wmmhello 已提交
2175

H
Haojun Liao 已提交
2176
    SMetaTableInfo mtInfo = pAPI->snapshotFn.getMetaTableInfoFromSnapshot(pInfo->sContext);
X
Xiaoyu Wang 已提交
2177
    STqOffsetVal   offset = {0};
L
Liu Jicong 已提交
2178
    if (mtInfo.uid == 0) {  // read snapshot done, change to get data from wal
wmmhello's avatar
wmmhello 已提交
2179
      qDebug("tmqsnap read snapshot done, change to get data from wal");
2180
      tqOffsetResetToLog(&offset, pInfo->sContext->snapVersion);
L
Liu Jicong 已提交
2181
    } else {
2182
      tqOffsetResetToData(&offset, mtInfo.uid, INT64_MIN);
2183
      qDebug("tmqsnap change get data uid:%" PRId64 "", mtInfo.uid);
wmmhello's avatar
wmmhello 已提交
2184
    }
2185
    qStreamPrepareScan(pTaskInfo, &offset, pInfo->sContext->subType);
2186
    tDeleteSchemaWrapper(mtInfo.schema);
wmmhello's avatar
wmmhello 已提交
2187
    return NULL;
2188
  } else if (pTaskInfo->streamInfo.currentOffset.type == TMQ_OFFSET__SNAPSHOT_META) {
L
Liu Jicong 已提交
2189 2190 2191 2192 2193
    SSnapContext* sContext = pInfo->sContext;
    void*         data = NULL;
    int32_t       dataLen = 0;
    int16_t       type = 0;
    int64_t       uid = 0;
H
Haojun Liao 已提交
2194 2195
    if (pAPI->snapshotFn.getTableInfoFromSnapshot(sContext, &data, &dataLen, &type, &uid) < 0) {
      qError("tmqsnap getTableInfoFromSnapshot error");
wmmhello's avatar
wmmhello 已提交
2196
      taosMemoryFreeClear(data);
2197 2198 2199
      return NULL;
    }

2200
    if (!sContext->queryMeta) {  // change to get data next poll request
2201 2202 2203
      STqOffsetVal offset = {0};
      tqOffsetResetToData(&offset, 0, INT64_MIN);
      qStreamPrepareScan(pTaskInfo, &offset, pInfo->sContext->subType);
L
Liu Jicong 已提交
2204
    } else {
2205
      tqOffsetResetToMeta(&pTaskInfo->streamInfo.currentOffset, uid);
wmmhello's avatar
wmmhello 已提交
2206 2207 2208 2209
      pTaskInfo->streamInfo.metaRsp.resMsgType = type;
      pTaskInfo->streamInfo.metaRsp.metaRspLen = dataLen;
      pTaskInfo->streamInfo.metaRsp.metaRsp = data;
    }
2210

wmmhello's avatar
wmmhello 已提交
2211
    return NULL;
2212 2213 2214 2215
  }
  return NULL;
}

wmmhello's avatar
wmmhello 已提交
2216
static void destroyRawScanOperatorInfo(void* param) {
wmmhello's avatar
wmmhello 已提交
2217
  SStreamRawScanInfo* pRawScan = (SStreamRawScanInfo*)param;
2218
  pRawScan->pAPI->tsdReader.tsdReaderClose(pRawScan->dataReader);
2219
  pRawScan->pAPI->snapshotFn.destroySnapshot(pRawScan->sContext);
2220
  tableListDestroy(pRawScan->pTableListInfo);
wmmhello's avatar
wmmhello 已提交
2221 2222 2223
  taosMemoryFree(pRawScan);
}

L
Liu Jicong 已提交
2224 2225 2226
// for subscribing db or stb (not including column),
// if this scan is used, meta data can be return
// and schemas are decided when scanning
2227
SOperatorInfo* createRawScanOperatorInfo(SReadHandle* pHandle, SExecTaskInfo* pTaskInfo) {
L
Liu Jicong 已提交
2228 2229 2230 2231 2232
  // create operator
  // create tb reader
  // create meta reader
  // create tq reader

H
Haojun Liao 已提交
2233 2234
  int32_t code = TSDB_CODE_SUCCESS;

2235
  SStreamRawScanInfo* pInfo = taosMemoryCalloc(1, sizeof(SStreamRawScanInfo));
L
Liu Jicong 已提交
2236
  SOperatorInfo*      pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
2237
  if (pInfo == NULL || pOperator == NULL) {
H
Haojun Liao 已提交
2238 2239
    code = TSDB_CODE_OUT_OF_MEMORY;
    goto _end;
2240 2241
  }

2242
  pInfo->pTableListInfo = tableListCreate();
wmmhello's avatar
wmmhello 已提交
2243
  pInfo->vnode = pHandle->vnode;
H
Haojun Liao 已提交
2244
  pInfo->pAPI = &pTaskInfo->storageAPI;
wmmhello's avatar
wmmhello 已提交
2245

2246
  pInfo->sContext = pHandle->sContext;
L
Liu Jicong 已提交
2247 2248
  setOperatorInfo(pOperator, "RawScanOperator", QUERY_NODE_PHYSICAL_PLAN_TABLE_SCAN, false, OP_NOT_OPENED, pInfo,
                  pTaskInfo);
2249

2250
  pOperator->fpSet = createOperatorFpSet(NULL, doRawScan, NULL, destroyRawScanOperatorInfo, optrDefaultBufFn, NULL);
2251
  return pOperator;
H
Haojun Liao 已提交
2252

L
Liu Jicong 已提交
2253
_end:
H
Haojun Liao 已提交
2254 2255 2256 2257
  taosMemoryFree(pInfo);
  taosMemoryFree(pOperator);
  pTaskInfo->code = code;
  return NULL;
L
Liu Jicong 已提交
2258 2259
}

2260
static void destroyStreamScanOperatorInfo(void* param) {
2261
  SStreamScanInfo* pStreamScan = (SStreamScanInfo*)param;
2262

2263
  if (pStreamScan->pTableScanOp && pStreamScan->pTableScanOp->info) {
2264
    destroyOperator(pStreamScan->pTableScanOp);
2265
  }
2266

2267
  if (pStreamScan->tqReader) {
2268
    pStreamScan->readerFn.tqReaderClose(pStreamScan->tqReader);
2269
  }
H
Haojun Liao 已提交
2270 2271
  if (pStreamScan->matchInfo.pList) {
    taosArrayDestroy(pStreamScan->matchInfo.pList);
2272
  }
C
Cary Xu 已提交
2273 2274
  if (pStreamScan->pPseudoExpr) {
    destroyExprInfo(pStreamScan->pPseudoExpr, pStreamScan->numOfPseudoExpr);
L
Liu Jicong 已提交
2275
    taosMemoryFree(pStreamScan->pPseudoExpr);
C
Cary Xu 已提交
2276
  }
C
Cary Xu 已提交
2277

L
Liu Jicong 已提交
2278
  cleanupExprSupp(&pStreamScan->tbnameCalSup);
5
54liuyao 已提交
2279
  cleanupExprSupp(&pStreamScan->tagCalSup);
L
Liu Jicong 已提交
2280

2281
  pStreamScan->stateStore.updateInfoDestroy(pStreamScan->pUpdateInfo);
2282 2283 2284 2285
  blockDataDestroy(pStreamScan->pRes);
  blockDataDestroy(pStreamScan->pUpdateRes);
  blockDataDestroy(pStreamScan->pPullDataRes);
  blockDataDestroy(pStreamScan->pDeleteDataRes);
5
54liuyao 已提交
2286
  blockDataDestroy(pStreamScan->pUpdateDataRes);
5
54liuyao 已提交
2287
  blockDataDestroy(pStreamScan->pCreateTbRes);
2288 2289 2290 2291
  taosArrayDestroy(pStreamScan->pBlockLists);
  taosMemoryFree(pStreamScan);
}

2292
SOperatorInfo* createStreamScanOperatorInfo(SReadHandle* pHandle, STableScanPhysiNode* pTableScanNode, SNode* pTagCond,
2293
                                            STableListInfo* pTableListInfo, SExecTaskInfo* pTaskInfo) {
H
Haojun Liao 已提交
2294
  SArray*          pColIds = NULL;
2295 2296
  SStreamScanInfo* pInfo = taosMemoryCalloc(1, sizeof(SStreamScanInfo));
  SOperatorInfo*   pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
2297 2298
  SStorageAPI*     pAPI = &pTaskInfo->storageAPI;
  const char* idstr = pTaskInfo->id.str;
2299

H
Haojun Liao 已提交
2300
  if (pInfo == NULL || pOperator == NULL) {
S
Shengliang Guan 已提交
2301
    terrno = TSDB_CODE_OUT_OF_MEMORY;
2302
    tableListDestroy(pTableListInfo);
2303
    goto _error;
H
Haojun Liao 已提交
2304 2305
  }

2306
  SScanPhysiNode*     pScanPhyNode = &pTableScanNode->scan;
2307
  SDataBlockDescNode* pDescNode = pScanPhyNode->node.pOutputDataBlockDesc;
H
Haojun Liao 已提交
2308

2309
  pInfo->pTagCond = pTagCond;
2310
  pInfo->pGroupTags = pTableScanNode->pGroupTags;
2311

2312
  int32_t numOfCols = 0;
2313 2314
  int32_t code =
      extractColMatchInfo(pScanPhyNode->pScanCols, pDescNode, &numOfCols, COL_MATCH_FROM_COL_ID, &pInfo->matchInfo);
H
Haojun Liao 已提交
2315
  if (code != TSDB_CODE_SUCCESS) {
2316
    tableListDestroy(pTableListInfo);
H
Haojun Liao 已提交
2317 2318
    goto _error;
  }
2319

H
Haojun Liao 已提交
2320
  int32_t numOfOutput = taosArrayGetSize(pInfo->matchInfo.pList);
H
Haojun Liao 已提交
2321
  pColIds = taosArrayInit(numOfOutput, sizeof(int16_t));
2322
  for (int32_t i = 0; i < numOfOutput; ++i) {
H
Haojun Liao 已提交
2323
    SColMatchItem* id = taosArrayGet(pInfo->matchInfo.pList, i);
2324 2325

    int16_t colId = id->colId;
2326
    taosArrayPush(pColIds, &colId);
2327
    if (id->colId == PRIMARYKEY_TIMESTAMP_COL_ID) {
H
Haojun Liao 已提交
2328
      pInfo->primaryTsIndex = id->dstSlotId;
5
54liuyao 已提交
2329
    }
H
Haojun Liao 已提交
2330 2331
  }

L
Liu Jicong 已提交
2332 2333 2334 2335
  if (pTableScanNode->pSubtable != NULL) {
    SExprInfo* pSubTableExpr = taosMemoryCalloc(1, sizeof(SExprInfo));
    if (pSubTableExpr == NULL) {
      terrno = TSDB_CODE_OUT_OF_MEMORY;
2336
      tableListDestroy(pTableListInfo);
L
Liu Jicong 已提交
2337 2338
      goto _error;
    }
2339

L
Liu Jicong 已提交
2340 2341
    pInfo->tbnameCalSup.pExprInfo = pSubTableExpr;
    createExprFromOneNode(pSubTableExpr, pTableScanNode->pSubtable, 0);
2342
    if (initExprSupp(&pInfo->tbnameCalSup, pSubTableExpr, 1, &pTaskInfo->storageAPI.functionStore) != 0) {
2343
      tableListDestroy(pTableListInfo);
L
Liu Jicong 已提交
2344 2345 2346 2347
      goto _error;
    }
  }

2348 2349
  if (pTableScanNode->pTags != NULL) {
    int32_t    numOfTags;
5
54liuyao 已提交
2350
    SExprInfo* pTagExpr = createExpr(pTableScanNode->pTags, &numOfTags);
2351 2352
    if (pTagExpr == NULL) {
      terrno = TSDB_CODE_OUT_OF_MEMORY;
2353
      tableListDestroy(pTableListInfo);
2354 2355
      goto _error;
    }
2356
    if (initExprSupp(&pInfo->tagCalSup, pTagExpr, numOfTags, &pTaskInfo->storageAPI.functionStore) != 0) {
2357
      terrno = TSDB_CODE_OUT_OF_MEMORY;
2358
      tableListDestroy(pTableListInfo);
2359 2360 2361 2362
      goto _error;
    }
  }

L
Liu Jicong 已提交
2363
  pInfo->pBlockLists = taosArrayInit(4, sizeof(SPackedData));
H
Haojun Liao 已提交
2364
  if (pInfo->pBlockLists == NULL) {
2365
    terrno = TSDB_CODE_OUT_OF_MEMORY;
2366
    tableListDestroy(pTableListInfo);
2367
    goto _error;
H
Haojun Liao 已提交
2368 2369
  }

5
54liuyao 已提交
2370
  if (pHandle->vnode) {
2371
    SOperatorInfo*  pTableScanOp = createTableScanOperatorInfo(pTableScanNode, pHandle, pTableListInfo, pTaskInfo);
L
Liu Jicong 已提交
2372
    STableScanInfo* pTSInfo = (STableScanInfo*)pTableScanOp->info;
2373
    if (pHandle->version > 0) {
H
Haojun Liao 已提交
2374
      pTSInfo->base.cond.endVersion = pHandle->version;
2375
    }
L
Liu Jicong 已提交
2376

2377
    STableKeyInfo* pList = NULL;
5
54liuyao 已提交
2378
    int32_t        num = 0;
2379
    tableListGetGroupList(pTableListInfo, 0, &pList, &num);
2380

2381
    if (pHandle->initTableReader) {
L
Liu Jicong 已提交
2382
      pTSInfo->scanMode = TABLE_SCAN__TABLE_ORDER;
H
Haojun Liao 已提交
2383
      pTSInfo->base.dataReader = NULL;
L
Liu Jicong 已提交
2384 2385
    }

L
Liu Jicong 已提交
2386 2387
    if (pHandle->initTqReader) {
      ASSERT(pHandle->tqReader == NULL);
2388
      pInfo->tqReader = pAPI->tqReaderFn.tqReaderOpen(pHandle->vnode);
L
Liu Jicong 已提交
2389
      ASSERT(pInfo->tqReader);
2390
    } else {
L
Liu Jicong 已提交
2391 2392
      ASSERT(pHandle->tqReader);
      pInfo->tqReader = pHandle->tqReader;
2393 2394
    }

2395
    pInfo->pUpdateInfo = NULL;
2396
    pInfo->pTableScanOp = pTableScanOp;
2397
    if (pInfo->pTableScanOp->pTaskInfo->streamInfo.pState) {
2398
      pAPI->stateStore.streamStateSetNumber(pInfo->pTableScanOp->pTaskInfo->streamInfo.pState, -1);
2399
    }
L
Liu Jicong 已提交
2400

L
Liu Jicong 已提交
2401
    pInfo->readHandle = *pHandle;
L
Liu Jicong 已提交
2402
    pTaskInfo->streamInfo.snapshotVer = pHandle->version;
5
54liuyao 已提交
2403 2404
    pInfo->pCreateTbRes = buildCreateTableBlock(&pInfo->tbnameCalSup, &pInfo->tagCalSup);
    blockDataEnsureCapacity(pInfo->pCreateTbRes, 8);
L
Liu Jicong 已提交
2405

L
Liu Jicong 已提交
2406
    // set the extract column id to streamHandle
2407
    pAPI->tqReaderFn.tqReaderSetColIdList(pInfo->tqReader, pColIds);
2408
    SArray* tableIdList = extractTableIdList(((STableScanInfo*)(pInfo->pTableScanOp->info))->base.pTableListInfo);
2409
    code = pAPI->tqReaderFn.tqReaderSetQueryTableList(pInfo->tqReader, tableIdList, idstr);
L
Liu Jicong 已提交
2410 2411 2412 2413
    if (code != 0) {
      taosArrayDestroy(tableIdList);
      goto _error;
    }
2414

L
Liu Jicong 已提交
2415
    taosArrayDestroy(tableIdList);
H
Haojun Liao 已提交
2416
    memcpy(&pTaskInfo->streamInfo.tableCond, &pTSInfo->base.cond, sizeof(SQueryTableDataCond));
L
Liu Jicong 已提交
2417 2418
  } else {
    taosArrayDestroy(pColIds);
2419
    tableListDestroy(pTableListInfo);
H
Haojun Liao 已提交
2420
    pColIds = NULL;
5
54liuyao 已提交
2421 2422
  }

2423 2424 2425 2426 2427
  // create the pseduo columns info
  if (pTableScanNode->scan.pScanPseudoCols != NULL) {
    pInfo->pPseudoExpr = createExprInfo(pTableScanNode->scan.pScanPseudoCols, NULL, &pInfo->numOfPseudoExpr);
  }

H
Haojun Liao 已提交
2428 2429 2430 2431 2432
  code = filterInitFromNode((SNode*)pScanPhyNode->node.pConditions, &pOperator->exprSupp.pFilterInfo, 0);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }

H
Haojun Liao 已提交
2433
  pInfo->pRes = createDataBlockFromDescNode(pDescNode);
2434
  pInfo->pUpdateRes = createSpecialDataBlock(STREAM_CLEAR);
2435
  pInfo->scanMode = STREAM_SCAN_FROM_READERHANDLE;
L
Liu Jicong 已提交
2436
  pInfo->windowSup = (SWindowSupporter){.pStreamAggSup = NULL, .gap = -1, .parentType = QUERY_NODE_PHYSICAL_PLAN};
2437
  pInfo->groupId = 0;
2438
  pInfo->pPullDataRes = createSpecialDataBlock(STREAM_RETRIEVE);
2439
  pInfo->pStreamScanOp = pOperator;
2440
  pInfo->deleteDataIndex = 0;
2441
  pInfo->pDeleteDataRes = createSpecialDataBlock(STREAM_DELETE_DATA);
5
54liuyao 已提交
2442
  pInfo->updateWin = (STimeWindow){.skey = INT64_MAX, .ekey = INT64_MAX};
2443
  pInfo->pUpdateDataRes = createSpecialDataBlock(STREAM_CLEAR);
X
Xiaoyu Wang 已提交
2444
  pInfo->assignBlockUid = pTableScanNode->assignBlockUid;
2445
  pInfo->partitionSup.needCalc = false;
5
54liuyao 已提交
2446 2447
  pInfo->igCheckUpdate = pTableScanNode->igCheckUpdate;
  pInfo->igExpired = pTableScanNode->igExpired;
2448
  pInfo->twAggSup.maxTs = INT64_MIN;
L
liuyao 已提交
2449
  pInfo->pState = NULL;
2450 2451
  pInfo->stateStore = pTaskInfo->storageAPI.stateStore;
  pInfo->readerFn = pTaskInfo->storageAPI.tqReaderFn;
L
Liu Jicong 已提交
2452

L
fix bug  
liuyao 已提交
2453 2454 2455 2456
  // for stream
  if (pTaskInfo->streamInfo.pState) {
    void*   buff = NULL;
    int32_t len = 0;
2457 2458
    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 已提交
2459
    taosMemoryFree(buff);
L
fix bug  
liuyao 已提交
2460
  }
L
liuyao 已提交
2461

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

2466
  __optr_fn_t nextFn = (pTaskInfo->execModel == OPTR_EXEC_MODEL_STREAM) ? doStreamScan : doQueueScan;
L
Liu Jicong 已提交
2467 2468
  pOperator->fpSet =
      createOperatorFpSet(optrDummyOpenFn, nextFn, NULL, destroyStreamScanOperatorInfo, optrDefaultBufFn, NULL);
2469

H
Haojun Liao 已提交
2470
  return pOperator;
2471

L
Liu Jicong 已提交
2472
_error:
H
Haojun Liao 已提交
2473 2474 2475 2476 2477 2478 2479 2480
  if (pColIds != NULL) {
    taosArrayDestroy(pColIds);
  }

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

2481 2482
  taosMemoryFreeClear(pOperator);
  return NULL;
H
Haojun Liao 已提交
2483 2484
}

2485
static void doTagScanOneTable(SOperatorInfo* pOperator, const SSDataBlock* pRes, int32_t count, SMetaReader* mr, SStorageAPI* pAPI) {
2486 2487 2488 2489
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
  STagScanInfo* pInfo = pOperator->info;
  SExprInfo*    pExprInfo = &pOperator->exprSupp.pExprInfo[0];

2490
  STableKeyInfo* item = tableListGetInfo(pInfo->pTableListInfo, pInfo->curPos);
2491
  int32_t        code = pAPI->metaReaderFn.getTableEntryByUid(mr, item->uid);
2492 2493 2494 2495
  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));
2496
    pAPI->metaReaderFn.clearReader(mr);
2497 2498 2499
    T_LONG_JMP(pTaskInfo->env, terrno);
  }

2500
  char str[512];
2501 2502 2503 2504 2505 2506
  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);
2507
      colDataSetVal(pDst, (count), str, false);
2508 2509 2510
    } else {  // it is a tag value
      STagVal val = {0};
      val.cid = pExprInfo[j].base.pParam[0].pCol->colId;
2511
      const char* p = pAPI->metaFn.extractTagVal((*mr).me.ctbEntry.pTags, pDst->info.type, &val);
2512 2513 2514 2515 2516 2517 2518

      char* data = NULL;
      if (pDst->info.type != TSDB_DATA_TYPE_JSON && p != NULL) {
        data = tTagValToData((const STagVal*)p, false);
      } else {
        data = (char*)p;
      }
2519
      colDataSetVal(pDst, (count), data,
2520 2521 2522 2523 2524 2525 2526 2527 2528 2529
                    (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);
      }
    }
  }
}

2530
static SSDataBlock* doTagScan(SOperatorInfo* pOperator) {
H
Haojun Liao 已提交
2531 2532 2533 2534
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

2535
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
2536
  SStorageAPI* pAPI = &pTaskInfo->storageAPI;
2537 2538

  STagScanInfo* pInfo = pOperator->info;
2539
  SExprInfo*    pExprInfo = &pOperator->exprSupp.pExprInfo[0];
2540
  SSDataBlock*  pRes = pInfo->pRes;
2541
  blockDataCleanup(pRes);
H
Haojun Liao 已提交
2542

2543
  int32_t size = tableListGetSize(pInfo->pTableListInfo);
wmmhello's avatar
wmmhello 已提交
2544
  if (size == 0) {
H
Haojun Liao 已提交
2545 2546 2547 2548
    setTaskStatus(pTaskInfo, TASK_COMPLETED);
    return NULL;
  }

2549 2550 2551
  char        str[512] = {0};
  int32_t     count = 0;
  SMetaReader mr = {0};
H
Haojun Liao 已提交
2552
  pAPI->metaReaderFn.initReader(&mr, pInfo->readHandle.vnode, 0, &pAPI->metaFn);
H
Haojun Liao 已提交
2553

wmmhello's avatar
wmmhello 已提交
2554
  while (pInfo->curPos < size && count < pOperator->resultInfo.capacity) {
2555
    doTagScanOneTable(pOperator, pRes, count, &mr, &pTaskInfo->storageAPI);
2556
    ++count;
wmmhello's avatar
wmmhello 已提交
2557
    if (++pInfo->curPos >= size) {
H
Haojun Liao 已提交
2558
      setOperatorCompleted(pOperator);
H
Haojun Liao 已提交
2559
    }
2560
    // each table with tbname is a group, hence its own block, but only group when slimit exists for performance reason.
2561
    if (pInfo->pSlimit != NULL) {
2562 2563 2564
      if (pInfo->curPos < pInfo->pSlimit->offset) {
        continue;
      }
2565
      pInfo->pRes->info.id.groupId = calcGroupId(mr.me.name, strlen(mr.me.name));
2566 2567 2568
      if (pInfo->curPos >= (pInfo->pSlimit->offset + pInfo->pSlimit->limit) - 1) {
        setOperatorCompleted(pOperator);
      }
2569
      break;
H
Haojun Liao 已提交
2570 2571 2572
    }
  }

2573
  pAPI->metaReaderFn.clearReader(&mr);
2574

2575
  // qDebug("QInfo:0x%"PRIx64" create tag values results completed, rows:%d", GET_TASKID(pRuntimeEnv), count);
H
Haojun Liao 已提交
2576
  if (pOperator->status == OP_EXEC_DONE) {
2577
    setTaskStatus(pTaskInfo, TASK_COMPLETED);
H
Haojun Liao 已提交
2578 2579 2580
  }

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

2583
  return (pRes->info.rows == 0) ? NULL : pInfo->pRes;
H
Haojun Liao 已提交
2584 2585
}

2586
static void destroyTagScanOperatorInfo(void* param) {
H
Haojun Liao 已提交
2587 2588
  STagScanInfo* pInfo = (STagScanInfo*)param;
  pInfo->pRes = blockDataDestroy(pInfo->pRes);
H
Haojun Liao 已提交
2589
  taosArrayDestroy(pInfo->matchInfo.pList);
2590
  pInfo->pTableListInfo = tableListDestroy(pInfo->pTableListInfo);
D
dapan1121 已提交
2591
  taosMemoryFreeClear(param);
H
Haojun Liao 已提交
2592 2593
}

S
slzhou 已提交
2594
SOperatorInfo* createTagScanOperatorInfo(SReadHandle* pReadHandle, STagScanPhysiNode* pPhyNode,
X
Xiaoyu Wang 已提交
2595
                                         STableListInfo* pTableListInfo, SExecTaskInfo* pTaskInfo) {
2596
  STagScanInfo*  pInfo = taosMemoryCalloc(1, sizeof(STagScanInfo));
H
Haojun Liao 已提交
2597 2598 2599 2600 2601
  SOperatorInfo* pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }

2602 2603 2604 2605
  SDataBlockDescNode* pDescNode = pPhyNode->node.pOutputDataBlockDesc;

  int32_t    numOfExprs = 0;
  SExprInfo* pExprInfo = createExprInfo(pPhyNode->pScanPseudoCols, NULL, &numOfExprs);
2606
  int32_t    code = initExprSupp(&pOperator->exprSupp, pExprInfo, numOfExprs, &pTaskInfo->storageAPI.functionStore);
2607 2608 2609
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
2610

H
Haojun Liao 已提交
2611 2612
  int32_t num = 0;
  code = extractColMatchInfo(pPhyNode->pScanPseudoCols, pDescNode, &num, COL_MATCH_FROM_COL_ID, &pInfo->matchInfo);
2613 2614 2615
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
2616

2617
  pInfo->pTableListInfo = pTableListInfo;
H
Haojun Liao 已提交
2618
  pInfo->pRes = createDataBlockFromDescNode(pDescNode);
2619 2620
  pInfo->readHandle = *pReadHandle;
  pInfo->curPos = 0;
2621
  pInfo->pSlimit = (SLimitNode*)pPhyNode->node.pSlimit; //TODO: slimit now only indicate group
2622

L
Liu Jicong 已提交
2623 2624
  setOperatorInfo(pOperator, "TagScanOperator", QUERY_NODE_PHYSICAL_PLAN_TAG_SCAN, false, OP_NOT_OPENED, pInfo,
                  pTaskInfo);
2625
  initResultSizeInfo(&pOperator->resultInfo, 4096);
2626 2627
  blockDataEnsureCapacity(pInfo->pRes, pOperator->resultInfo.capacity);

L
Liu Jicong 已提交
2628 2629
  pOperator->fpSet =
      createOperatorFpSet(optrDummyOpenFn, doTagScan, NULL, destroyTagScanOperatorInfo, optrDefaultBufFn, NULL);
H
Haojun Liao 已提交
2630 2631

  return pOperator;
2632

2633
_error:
H
Haojun Liao 已提交
2634 2635 2636 2637 2638
  taosMemoryFree(pInfo);
  taosMemoryFree(pOperator);
  terrno = TSDB_CODE_OUT_OF_MEMORY;
  return NULL;
}
2639

dengyihao's avatar
dengyihao 已提交
2640
static SSDataBlock* getTableDataBlockImpl(void* param) {
dengyihao's avatar
opt mem  
dengyihao 已提交
2641 2642 2643 2644
  STableMergeScanSortSourceParam* source = param;
  SOperatorInfo*                  pOperator = source->pOperator;
  STableMergeScanInfo*            pInfo = pOperator->info;
  SExecTaskInfo*                  pTaskInfo = pOperator->pTaskInfo;
2645 2646
  SStorageAPI* pAPI = &pTaskInfo->storageAPI;

dengyihao's avatar
opt mem  
dengyihao 已提交
2647 2648
  int32_t                         readIdx = source->readerIdx;
  SSDataBlock*                    pBlock = source->inputBlock;
D
dapan1121 已提交
2649
  int32_t                         code = 0;
dengyihao's avatar
opt mem  
dengyihao 已提交
2650

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

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

D
dapan1121 已提交
2657
  if (NULL == source->dataReader || !source->multiReader) {
2658
    code = pAPI->tsdReader.tsdReaderOpen(pHandle->vnode, pQueryCond, p, 1, pBlock, (void**)&source->dataReader, GET_TASKID(pTaskInfo), false, NULL);
D
dapan1121 已提交
2659 2660 2661
    if (code != 0) {
      T_LONG_JMP(pTaskInfo->env, code);
    }
dengyihao's avatar
dengyihao 已提交
2662
  }
dengyihao's avatar
opt mem  
dengyihao 已提交
2663

D
dapan1121 已提交
2664
  pInfo->base.dataReader = source->dataReader;
H
Haojun Liao 已提交
2665
  STsdbReader* reader = pInfo->base.dataReader;
X
Xiaoyu Wang 已提交
2666
  bool         hasNext = false;
2667
  qTrace("tsdb/read-table-data: %p, enter next reader", reader);
D
dapan1121 已提交
2668 2669

  while (true) {
2670
    code = pAPI->tsdReader.tsdNextDataBlock(reader, &hasNext);
D
dapan1121 已提交
2671
    if (code != 0) {
2672
      pAPI->tsdReader.tsdReaderReleaseDataBlock(reader);
D
dapan1121 已提交
2673 2674 2675 2676 2677 2678 2679
      pInfo->base.dataReader = NULL;
      T_LONG_JMP(pTaskInfo->env, code);
    }

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

H
Haojun Liao 已提交
2681
    if (isTaskKilled(pTaskInfo)) {
2682
      pAPI->tsdReader.tsdReaderReleaseDataBlock(reader);
D
dapan1121 已提交
2683
      pInfo->base.dataReader = NULL;
2684
      T_LONG_JMP(pTaskInfo->env, pTaskInfo->code);
dengyihao's avatar
opt mem  
dengyihao 已提交
2685 2686 2687
    }

    // process this data block based on the probabilities
H
Haojun Liao 已提交
2688
    bool processThisBlock = processBlockWithProbability(&pInfo->sample);
dengyihao's avatar
opt mem  
dengyihao 已提交
2689 2690 2691 2692
    if (!processThisBlock) {
      continue;
    }

H
Haojun Liao 已提交
2693
    if (pQueryCond->order == TSDB_ORDER_ASC) {
dengyihao's avatar
opt mem  
dengyihao 已提交
2694 2695 2696 2697
      pQueryCond->twindows.skey = pBlock->info.window.ekey + 1;
    } else {
      pQueryCond->twindows.ekey = pBlock->info.window.skey - 1;
    }
dengyihao's avatar
opt mem  
dengyihao 已提交
2698 2699

    uint32_t status = 0;
2700
    code = loadDataBlock(pOperator, &pInfo->base, pBlock, &status);
S
slzhou 已提交
2701
    //    code = loadDataBlockFromOneTable(pOperator, pTableScanInfo, pBlock, &status);
dengyihao's avatar
opt mem  
dengyihao 已提交
2702
    if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
2703
      T_LONG_JMP(pTaskInfo->env, code);
dengyihao's avatar
opt mem  
dengyihao 已提交
2704 2705
    }

2706 2707 2708 2709
    if (status == FUNC_DATA_REQUIRED_ALL_FILTEROUT) {
      break;
    }

dengyihao's avatar
opt mem  
dengyihao 已提交
2710 2711 2712 2713 2714
    // 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;
    }

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

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

2720
    qTrace("tsdb/read-table-data: %p, close reader", reader);
D
dapan1121 已提交
2721
    if (!source->multiReader) {
2722
      pAPI->tsdReader.tsdReaderClose(pInfo->base.dataReader);
D
dapan1121 已提交
2723 2724
      source->dataReader = NULL;
    }
H
Haojun Liao 已提交
2725
    pInfo->base.dataReader = NULL;
dengyihao's avatar
opt mem  
dengyihao 已提交
2726 2727
    return pBlock;
  }
H
Haojun Liao 已提交
2728

D
dapan1121 已提交
2729
  if (!source->multiReader) {
2730
    pAPI->tsdReader.tsdReaderClose(pInfo->base.dataReader);
D
dapan1121 已提交
2731 2732
    source->dataReader = NULL;
  }
H
Haojun Liao 已提交
2733
  pInfo->base.dataReader = NULL;
dengyihao's avatar
opt mem  
dengyihao 已提交
2734 2735 2736
  return NULL;
}

2737 2738 2739
SArray* generateSortByTsInfo(SArray* colMatchInfo, int32_t order) {
  int32_t tsTargetSlotId = 0;
  for (int32_t i = 0; i < taosArrayGetSize(colMatchInfo); ++i) {
H
Haojun Liao 已提交
2740
    SColMatchItem* colInfo = taosArrayGet(colMatchInfo, i);
2741
    if (colInfo->colId == PRIMARYKEY_TIMESTAMP_COL_ID) {
H
Haojun Liao 已提交
2742
      tsTargetSlotId = colInfo->dstSlotId;
2743 2744 2745
    }
  }

2746 2747 2748
  SArray*         pList = taosArrayInit(1, sizeof(SBlockOrderInfo));
  SBlockOrderInfo bi = {0};
  bi.order = order;
2749
  bi.slotId = tsTargetSlotId;
2750 2751 2752 2753 2754 2755 2756
  bi.nullFirst = NULL_ORDER_FIRST;

  taosArrayPush(pList, &bi);

  return pList;
}

H
Haojun Liao 已提交
2757
int32_t dumpQueryTableCond(const SQueryTableDataCond* src, SQueryTableDataCond* dst) {
dengyihao's avatar
opt mem  
dengyihao 已提交
2758 2759 2760 2761 2762 2763 2764
  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 已提交
2765

2766
int32_t startGroupTableMergeScan(SOperatorInfo* pOperator) {
2767 2768 2769
  STableMergeScanInfo* pInfo = pOperator->info;
  SExecTaskInfo*       pTaskInfo = pOperator->pTaskInfo;

S
slzhou 已提交
2770
  {
2771
    size_t  numOfTables = tableListGetSize(pInfo->base.pTableListInfo);
S
slzhou 已提交
2772
    int32_t i = pInfo->tableStartIndex + 1;
H
Haojun Liao 已提交
2773
    for (; i < numOfTables; ++i) {
2774
      STableKeyInfo* tableKeyInfo = tableListGetInfo(pInfo->base.pTableListInfo, i);
S
slzhou 已提交
2775 2776 2777 2778 2779 2780
      if (tableKeyInfo->groupId != pInfo->groupId) {
        break;
      }
    }
    pInfo->tableEndIndex = i - 1;
  }
2781

S
slzhou 已提交
2782 2783
  int32_t tableStartIdx = pInfo->tableStartIndex;
  int32_t tableEndIdx = pInfo->tableEndIndex;
2784

H
Haojun Liao 已提交
2785
  pInfo->base.dataReader = NULL;
2786

2787 2788
  // todo the total available buffer should be determined by total capacity of buffer of this task.
  // the additional one is reserved for merge result
S
slzhou 已提交
2789
  pInfo->sortBufSize = pInfo->bufPageSize * (tableEndIdx - tableStartIdx + 1 + 1);
2790
  int32_t numOfBufPage = pInfo->sortBufSize / pInfo->bufPageSize;
L
Liu Jicong 已提交
2791 2792
  pInfo->pSortHandle = tsortCreateSortHandle(pInfo->pSortInfo, SORT_MULTISOURCE_MERGE, pInfo->bufPageSize, numOfBufPage,
                                             pInfo->pSortInputBlock, pTaskInfo->id.str);
2793

dengyihao's avatar
dengyihao 已提交
2794
  tsortSetFetchRawDataFp(pInfo->pSortHandle, getTableDataBlockImpl, NULL, NULL);
dengyihao's avatar
opt mem  
dengyihao 已提交
2795 2796 2797 2798 2799 2800

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

  for (int32_t i = 0; i < numOfTable; ++i) {
2801 2802 2803
    STableMergeScanSortSourceParam param = {0};
    param.readerIdx = i;
    param.pOperator = pOperator;
D
dapan1121 已提交
2804
    param.multiReader = (numOfTable <= MULTI_READER_MAX_TABLE_NUM) ? true : false;
2805
    param.inputBlock = createOneDataBlock(pInfo->pResBlock, false);
H
Haojun Liao 已提交
2806 2807
    blockDataEnsureCapacity(param.inputBlock, pOperator->resultInfo.capacity);

2808
    taosArrayPush(pInfo->sortSourceParams, &param);
dengyihao's avatar
opt mem  
dengyihao 已提交
2809 2810

    SQueryTableDataCond cond;
H
Haojun Liao 已提交
2811
    dumpQueryTableCond(&pInfo->base.cond, &cond);
dengyihao's avatar
opt mem  
dengyihao 已提交
2812
    taosArrayPush(pInfo->queryConds, &cond);
2813 2814
  }

dengyihao's avatar
opt mem  
dengyihao 已提交
2815
  for (int32_t i = 0; i < numOfTable; ++i) {
2816
    SSortSource*                    ps = taosMemoryCalloc(1, sizeof(SSortSource));
2817
    STableMergeScanSortSourceParam* param = taosArrayGet(pInfo->sortSourceParams, i);
2818
    ps->param = param;
2819
    ps->onlyRef = true;
2820 2821 2822 2823 2824 2825
    tsortAddSource(pInfo->pSortHandle, ps);
  }

  int32_t code = tsortOpen(pInfo->pSortHandle);

  if (code != TSDB_CODE_SUCCESS) {
2826
    T_LONG_JMP(pTaskInfo->env, terrno);
2827 2828
  }

2829 2830 2831 2832 2833 2834
  return TSDB_CODE_SUCCESS;
}

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

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

2839 2840 2841 2842 2843 2844 2845
  SSortExecInfo sortExecInfo = tsortGetSortExecInfo(pInfo->pSortHandle);
  pInfo->sortExecInfo.sortMethod = sortExecInfo.sortMethod;
  pInfo->sortExecInfo.sortBuffer = sortExecInfo.sortBuffer;
  pInfo->sortExecInfo.loops += sortExecInfo.loops;
  pInfo->sortExecInfo.readBytes += sortExecInfo.readBytes;
  pInfo->sortExecInfo.writeBytes += sortExecInfo.writeBytes;

dengyihao's avatar
dengyihao 已提交
2846
  for (int32_t i = 0; i < numOfTable; ++i) {
2847 2848
    STableMergeScanSortSourceParam* param = taosArrayGet(pInfo->sortSourceParams, i);
    blockDataDestroy(param->inputBlock);
2849
    pAPI->tsdReader.tsdReaderClose(param->dataReader);
D
dapan1121 已提交
2850
    param->dataReader = NULL;
2851
  }
2852 2853
  taosArrayClear(pInfo->sortSourceParams);

2854
  tsortDestroySortHandle(pInfo->pSortHandle);
dengyihao's avatar
dengyihao 已提交
2855
  pInfo->pSortHandle = NULL;
2856

dengyihao's avatar
opt mem  
dengyihao 已提交
2857 2858 2859
  for (int32_t i = 0; i < taosArrayGetSize(pInfo->queryConds); i++) {
    SQueryTableDataCond* cond = taosArrayGet(pInfo->queryConds, i);
    taosMemoryFree(cond->colList);
2860
  }
dengyihao's avatar
opt mem  
dengyihao 已提交
2861 2862 2863
  taosArrayDestroy(pInfo->queryConds);
  pInfo->queryConds = NULL;

2864
  resetLimitInfoForNextGroup(&pInfo->limitInfo);
2865 2866 2867
  return TSDB_CODE_SUCCESS;
}

2868 2869
// 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 已提交
2870 2871
SSDataBlock* getSortedTableMergeScanBlockData(SSortHandle* pHandle, SSDataBlock* pResBlock, int32_t capacity,
                                              SOperatorInfo* pOperator) {
2872 2873 2874
  STableMergeScanInfo* pInfo = pOperator->info;
  SExecTaskInfo*       pTaskInfo = pOperator->pTaskInfo;

2875
  blockDataCleanup(pResBlock);
2876 2877

  while (1) {
2878
    STupleHandle* pTupleHandle = tsortNextTuple(pHandle);
2879 2880 2881 2882
    if (pTupleHandle == NULL) {
      break;
    }

2883 2884
    appendOneRowToDataBlock(pResBlock, pTupleHandle);
    if (pResBlock->info.rows >= capacity) {
2885 2886 2887 2888
      break;
    }
  }

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

2893
  return (pResBlock->info.rows > 0) ? pResBlock : NULL;
2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905
}

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) {
2906
    T_LONG_JMP(pTaskInfo->env, code);
2907
  }
2908

2909
  size_t tableListSize = tableListGetSize(pInfo->base.pTableListInfo);
S
slzhou 已提交
2910 2911
  if (!pInfo->hasGroupId) {
    pInfo->hasGroupId = true;
2912

S
slzhou 已提交
2913
    if (tableListSize == 0) {
H
Haojun Liao 已提交
2914
      setOperatorCompleted(pOperator);
2915 2916
      return NULL;
    }
S
slzhou 已提交
2917
    pInfo->tableStartIndex = 0;
2918
    pInfo->groupId = ((STableKeyInfo*)tableListGetInfo(pInfo->base.pTableListInfo, pInfo->tableStartIndex))->groupId;
2919 2920
    startGroupTableMergeScan(pOperator);
  }
2921

S
slzhou 已提交
2922 2923
  SSDataBlock* pBlock = NULL;
  while (pInfo->tableStartIndex < tableListSize) {
2924 2925 2926 2927
    if (isTaskKilled(pTaskInfo)) {
      T_LONG_JMP(pTaskInfo->env, pTaskInfo->code);
    }

L
Liu Jicong 已提交
2928 2929
    pBlock = getSortedTableMergeScanBlockData(pInfo->pSortHandle, pInfo->pResBlock, pOperator->resultInfo.capacity,
                                              pOperator);
S
slzhou 已提交
2930
    if (pBlock != NULL) {
H
Haojun Liao 已提交
2931
      pBlock->info.id.groupId = pInfo->groupId;
S
slzhou 已提交
2932 2933 2934
      pOperator->resultInfo.totalRows += pBlock->info.rows;
      return pBlock;
    } else {
2935
      // Data of this group are all dumped, let's try the next group
S
slzhou 已提交
2936 2937
      stopGroupTableMergeScan(pOperator);
      if (pInfo->tableEndIndex >= tableListSize - 1) {
H
Haojun Liao 已提交
2938
        setOperatorCompleted(pOperator);
S
slzhou 已提交
2939 2940
        break;
      }
2941

S
slzhou 已提交
2942
      pInfo->tableStartIndex = pInfo->tableEndIndex + 1;
2943
      pInfo->groupId = tableListGetInfo(pInfo->base.pTableListInfo, pInfo->tableStartIndex)->groupId;
S
slzhou 已提交
2944
      startGroupTableMergeScan(pOperator);
X
Xiaoyu Wang 已提交
2945
      resetLimitInfoForNextGroup(&pInfo->limitInfo);
S
slzhou 已提交
2946
    }
wmmhello's avatar
wmmhello 已提交
2947 2948
  }

2949 2950 2951
  return pBlock;
}

2952
void destroyTableMergeScanOperatorInfo(void* param) {
2953
  STableMergeScanInfo* pTableScanInfo = (STableMergeScanInfo*)param;
H
Haojun Liao 已提交
2954
  cleanupQueryTableDataCond(&pTableScanInfo->base.cond);
2955

dengyihao's avatar
dengyihao 已提交
2956 2957 2958
  int32_t numOfTable = taosArrayGetSize(pTableScanInfo->queryConds);

  for (int32_t i = 0; i < numOfTable; i++) {
H
Haojun Liao 已提交
2959 2960
    STableMergeScanSortSourceParam* p = taosArrayGet(pTableScanInfo->sortSourceParams, i);
    blockDataDestroy(p->inputBlock);
2961
    pTableScanInfo->base.readerAPI.tsdReaderClose(p->dataReader);
D
dapan1121 已提交
2962
    p->dataReader = NULL;
2963
  }
H
Haojun Liao 已提交
2964

2965
  pTableScanInfo->base.readerAPI.tsdReaderClose(pTableScanInfo->base.dataReader);
D
dapan1121 已提交
2966 2967
  pTableScanInfo->base.dataReader = NULL;

2968
  taosArrayDestroy(pTableScanInfo->sortSourceParams);
dengyihao's avatar
dengyihao 已提交
2969 2970
  tsortDestroySortHandle(pTableScanInfo->pSortHandle);
  pTableScanInfo->pSortHandle = NULL;
2971

dengyihao's avatar
opt mem  
dengyihao 已提交
2972 2973 2974
  for (int i = 0; i < taosArrayGetSize(pTableScanInfo->queryConds); i++) {
    SQueryTableDataCond* pCond = taosArrayGet(pTableScanInfo->queryConds, i);
    taosMemoryFree(pCond->colList);
2975 2976
  }

2977
  taosArrayDestroy(pTableScanInfo->queryConds);
2978
  destroyTableScanBase(&pTableScanInfo->base, &pTableScanInfo->base.readerAPI);
2979 2980 2981 2982 2983

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

  taosArrayDestroy(pTableScanInfo->pSortInfo);
D
dapan1121 已提交
2984
  taosMemoryFreeClear(param);
2985 2986 2987 2988
}

int32_t getTableMergeScanExplainExecInfo(SOperatorInfo* pOptr, void** pOptrExplain, uint32_t* len) {
  ASSERT(pOptr != NULL);
2989 2990
  // TODO: merge these two info into one struct
  STableMergeScanExecInfo* execInfo = taosMemoryCalloc(1, sizeof(STableMergeScanExecInfo));
L
Liu Jicong 已提交
2991
  STableMergeScanInfo*     pInfo = pOptr->info;
H
Haojun Liao 已提交
2992
  execInfo->blockRecorder = pInfo->base.readRecorder;
2993
  execInfo->sortExecInfo = pInfo->sortExecInfo;
2994 2995 2996

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

2998 2999 3000
  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
3001
SOperatorInfo* createTableMergeScanOperatorInfo(STableScanPhysiNode* pTableScanNode, SReadHandle* readHandle,
3002
                                                STableListInfo* pTableListInfo, SExecTaskInfo* pTaskInfo) {
3003 3004 3005 3006 3007
  STableMergeScanInfo* pInfo = taosMemoryCalloc(1, sizeof(STableMergeScanInfo));
  SOperatorInfo*       pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }
3008

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

  int32_t numOfCols = 0;
3012
  int32_t code = extractColMatchInfo(pTableScanNode->scan.pScanCols, pDescNode, &numOfCols, COL_MATCH_FROM_COL_ID,
H
Haojun Liao 已提交
3013
                                     &pInfo->base.matchInfo);
H
Haojun Liao 已提交
3014 3015 3016
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
3017

H
Haojun Liao 已提交
3018
  code = initQueryTableDataCond(&pInfo->base.cond, pTableScanNode);
3019
  if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
3020
    taosArrayDestroy(pInfo->base.matchInfo.pList);
3021 3022 3023 3024
    goto _error;
  }

  if (pTableScanNode->scan.pScanPseudoCols != NULL) {
H
Haojun Liao 已提交
3025
    SExprSupp* pSup = &pInfo->base.pseudoSup;
3026
    pSup->pExprInfo = createExprInfo(pTableScanNode->scan.pScanPseudoCols, NULL, &pSup->numOfExprs);
3027
    pSup->pCtx = createSqlFunctionCtx(pSup->pExprInfo, pSup->numOfExprs, &pSup->rowEntryInfoOffset, &pTaskInfo->storageAPI.functionStore);
3028 3029 3030 3031
  }

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

H
Haojun Liao 已提交
3032 3033 3034 3035 3036 3037
  pInfo->base.metaCache.pTableMetaEntryCache = taosLRUCacheInit(1024 * 128, -1, .5);
  if (pInfo->base.metaCache.pTableMetaEntryCache == NULL) {
    code = terrno;
    goto _error;
  }

H
Haojun Liao 已提交
3038
  pInfo->base.readerAPI = pTaskInfo->storageAPI.tsdReader;
H
Haojun Liao 已提交
3039 3040
  pInfo->base.dataBlockLoadFlag = FUNC_DATA_REQUIRED_DATA_LOAD;
  pInfo->base.scanFlag = MAIN_SCAN;
H
Haojun Liao 已提交
3041
  pInfo->base.readHandle = *readHandle;
3042 3043 3044

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

3047
  pInfo->sample.sampleRatio = pTableScanNode->ratio;
L
Liu Jicong 已提交
3048
  pInfo->sample.seed = taosGetTimestampSec();
H
Haojun Liao 已提交
3049 3050 3051 3052 3053 3054

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

H
Haojun Liao 已提交
3055
  initResultSizeInfo(&pOperator->resultInfo, 1024);
H
Haojun Liao 已提交
3056
  pInfo->pResBlock = createDataBlockFromDescNode(pDescNode);
H
Haojun Liao 已提交
3057 3058
  blockDataEnsureCapacity(pInfo->pResBlock, pOperator->resultInfo.capacity);

3059
  pInfo->sortSourceParams = taosArrayInit(64, sizeof(STableMergeScanSortSourceParam));
3060

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

dengyihao's avatar
dengyihao 已提交
3065
  int32_t  rowSize = pInfo->pResBlock->info.rowSize;
A
Alex Duan 已提交
3066 3067
  uint32_t nCols = taosArrayGetSize(pInfo->pResBlock->pDataBlock);
  pInfo->bufPageSize = getProperSortPageSize(rowSize, nCols);
3068

L
Liu Jicong 已提交
3069 3070
  setOperatorInfo(pOperator, "TableMergeScanOperator", QUERY_NODE_PHYSICAL_PLAN_TABLE_MERGE_SCAN, false, OP_NOT_OPENED,
                  pInfo, pTaskInfo);
L
Liu Jicong 已提交
3071
  pOperator->exprSupp.numOfExprs = numOfCols;
3072

3073 3074
  pOperator->fpSet = createOperatorFpSet(optrDummyOpenFn, doTableMergeScan, NULL, destroyTableMergeScanOperatorInfo,
                                         optrDefaultBufFn, getTableMergeScanExplainExecInfo);
3075 3076 3077 3078 3079 3080 3081 3082 3083
  pOperator->cost.openCost = 0;
  return pOperator;

_error:
  pTaskInfo->code = TSDB_CODE_OUT_OF_MEMORY;
  taosMemoryFree(pInfo);
  taosMemoryFree(pOperator);
  return NULL;
}
S
shenglian zhou 已提交
3084 3085 3086 3087

// ====================================================================================================================
// TableCountScanOperator
static SSDataBlock* doTableCountScan(SOperatorInfo* pOperator);
S
slzhou 已提交
3088
static void         destoryTableCountScanOperator(void* param);
S
slzhou 已提交
3089
static void         buildVnodeGroupedStbTableCount(STableCountScanOperatorInfo* pInfo, STableCountScanSupp* pSupp,
3090
                                                   SSDataBlock* pRes, char* dbName, tb_uid_t stbUid, SStorageAPI* pAPI);
S
slzhou 已提交
3091
static void         buildVnodeGroupedNtbTableCount(STableCountScanOperatorInfo* pInfo, STableCountScanSupp* pSupp,
3092
                                                   SSDataBlock* pRes, char* dbName, SStorageAPI* pAPI);
S
slzhou 已提交
3093 3094
static void         buildVnodeFilteredTbCount(SOperatorInfo* pOperator, STableCountScanOperatorInfo* pInfo,
                                              STableCountScanSupp* pSupp, SSDataBlock* pRes, char* dbName);
L
Liu Jicong 已提交
3095 3096
static void         buildVnodeGroupedTableCount(SOperatorInfo* pOperator, STableCountScanOperatorInfo* pInfo,
                                                STableCountScanSupp* pSupp, SSDataBlock* pRes, int32_t vgId, char* dbName);
S
slzhou 已提交
3097 3098 3099 3100 3101 3102 3103
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 已提交
3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164
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 已提交
3165 3166
    tstrncpy(supp->dbNameFilter, tNameGetDbNameP(tableName), TSDB_DB_NAME_LEN);
    tstrncpy(supp->stbNameFilter, tNameGetTableName(tableName), TSDB_TABLE_NAME_LEN);
S
slzhou 已提交
3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178
  }
  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 已提交
3179

S
slzhou 已提交
3180 3181 3182 3183 3184 3185 3186 3187 3188
  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 已提交
3189

S
slzhou 已提交
3190 3191 3192 3193 3194 3195 3196
  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 已提交
3197

S
slzhou 已提交
3198
SOperatorInfo* createTableCountScanOperatorInfo(SReadHandle* readHandle, STableCountScanPhysiNode* pTblCountScanNode,
S
shenglian zhou 已提交
3199 3200 3201
                                                SExecTaskInfo* pTaskInfo) {
  int32_t code = TSDB_CODE_SUCCESS;

S
slzhou 已提交
3202
  SScanPhysiNode*              pScanNode = &pTblCountScanNode->scan;
S
slzhou 已提交
3203
  STableCountScanOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(STableCountScanOperatorInfo));
S
slzhou 已提交
3204
  SOperatorInfo*               pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
S
shenglian zhou 已提交
3205 3206 3207 3208 3209 3210 3211 3212 3213

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

  pInfo->readHandle = *readHandle;

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

S
slzhou 已提交
3217 3218 3219
  getTableCountScanSupp(pTblCountScanNode->pGroupTags, &pTblCountScanNode->scan.tableName,
                        pTblCountScanNode->scan.pScanCols, pTblCountScanNode->scan.pScanPseudoCols, &pInfo->supp,
                        pTaskInfo);
S
shenglian zhou 已提交
3220 3221 3222

  setOperatorInfo(pOperator, "TableCountScanOperator", QUERY_NODE_PHYSICAL_PLAN_TABLE_COUNT_SCAN, false, OP_NOT_OPENED,
                  pInfo, pTaskInfo);
L
Liu Jicong 已提交
3223 3224
  pOperator->fpSet = createOperatorFpSet(optrDummyOpenFn, doTableCountScan, NULL, destoryTableCountScanOperator,
                                         optrDefaultBufFn, NULL);
S
shenglian zhou 已提交
3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235
  return pOperator;

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

S
slzhou 已提交
3236 3237 3238
void fillTableCountScanDataBlock(STableCountScanSupp* pSupp, char* dbName, char* stbName, int64_t count,
                                 SSDataBlock* pRes) {
  if (pSupp->dbNameSlotId != -1) {
3239
    ASSERT(strlen(dbName));
S
slzhou 已提交
3240
    SColumnInfoData* colInfoData = taosArrayGet(pRes->pDataBlock, pSupp->dbNameSlotId);
H
Haojun Liao 已提交
3241 3242 3243 3244

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

S
slzhou 已提交
3245
    varDataSetLen(varDbName, strlen(dbName));
3246
    colDataSetVal(colInfoData, 0, varDbName, false);
S
slzhou 已提交
3247 3248 3249 3250
  }

  if (pSupp->stbNameSlotId != -1) {
    SColumnInfoData* colInfoData = taosArrayGet(pRes->pDataBlock, pSupp->stbNameSlotId);
3251
    if (strlen(stbName) != 0) {
S
slzhou 已提交
3252
      char varStbName[TSDB_TABLE_NAME_LEN + VARSTR_HEADER_SIZE] = {0};
H
Haojun Liao 已提交
3253
      strncpy(varDataVal(varStbName), stbName, TSDB_TABLE_NAME_LEN);
3254
      varDataSetLen(varStbName, strlen(stbName));
3255
      colDataSetVal(colInfoData, 0, varStbName, false);
3256
    } else {
3257
      colDataSetNULL(colInfoData, 0);
3258
    }
S
slzhou 已提交
3259 3260 3261
  }

  if (pSupp->tbCountSlotId != -1) {
S
slzhou 已提交
3262
    SColumnInfoData* colInfoData = taosArrayGet(pRes->pDataBlock, pSupp->tbCountSlotId);
3263
    colDataSetVal(colInfoData, 0, (char*)&count, false);
S
slzhou 已提交
3264 3265 3266 3267
  }
  pRes->info.rows = 1;
}

S
slzhou 已提交
3268
static SSDataBlock* buildSysDbTableCount(SOperatorInfo* pOperator, STableCountScanOperatorInfo* pInfo) {
S
slzhou 已提交
3269 3270 3271
  STableCountScanSupp* pSupp = &pInfo->supp;
  SSDataBlock*         pRes = pInfo->pRes;

S
slzhou 已提交
3272
  size_t infodbTableNum;
S
slzhou 已提交
3273
  getInfosDbMeta(NULL, &infodbTableNum);
S
slzhou 已提交
3274
  size_t perfdbTableNum;
S
slzhou 已提交
3275 3276
  getPerfDbMeta(NULL, &perfdbTableNum);

D
dapan1121 已提交
3277
  if (pSupp->groupByDbName || pSupp->groupByStbName) {
S
slzhou 已提交
3278
    buildSysDbGroupedTableCount(pOperator, pInfo, pSupp, pRes, infodbTableNum, perfdbTableNum);
S
slzhou 已提交
3279 3280
    return (pRes->info.rows > 0) ? pRes : NULL;
  } else {
S
slzhou 已提交
3281
    buildSysDbFilterTableCount(pOperator, pSupp, pRes, infodbTableNum, perfdbTableNum);
S
slzhou 已提交
3282 3283 3284 3285
    return (pRes->info.rows > 0) ? pRes : NULL;
  }
}

S
slzhou 已提交
3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301
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 已提交
3302 3303 3304 3305 3306 3307
    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 已提交
3308

S
slzhou 已提交
3309 3310 3311
    pRes->info.id.groupId = groupId;
    fillTableCountScanDataBlock(pSupp, TSDB_INFORMATION_SCHEMA_DB, "", infodbTableNum, pRes);
  } else if (pInfo->currGrpIdx == 1) {
D
dapan1121 已提交
3312 3313 3314 3315 3316 3317 3318
    uint64_t groupId = 0;
    if (pSupp->groupByDbName) {
      groupId = calcGroupId(TSDB_PERFORMANCE_SCHEMA_DB, strlen(TSDB_PERFORMANCE_SCHEMA_DB));
    } else {
      groupId = calcGroupId("", 0);
    }

S
slzhou 已提交
3319 3320 3321 3322 3323 3324 3325 3326
    pRes->info.id.groupId = groupId;
    fillTableCountScanDataBlock(pSupp, TSDB_PERFORMANCE_SCHEMA_DB, "", perfdbTableNum, pRes);
  } else {
    setOperatorCompleted(pOperator);
  }
  pInfo->currGrpIdx++;
}

S
shenglian zhou 已提交
3327
static SSDataBlock* doTableCountScan(SOperatorInfo* pOperator) {
S
slzhou 已提交
3328 3329 3330 3331
  SExecTaskInfo*               pTaskInfo = pOperator->pTaskInfo;
  STableCountScanOperatorInfo* pInfo = pOperator->info;
  STableCountScanSupp*         pSupp = &pInfo->supp;
  SSDataBlock*                 pRes = pInfo->pRes;
S
slzhou 已提交
3332
  blockDataCleanup(pRes);
3333

S
slzhou 已提交
3334 3335 3336
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }
S
slzhou 已提交
3337
  if (pInfo->readHandle.mnd != NULL) {
S
slzhou 已提交
3338
    return buildSysDbTableCount(pOperator, pInfo);
S
slzhou 已提交
3339
  }
S
slzhou 已提交
3340

S
slzhou 已提交
3341 3342 3343 3344 3345
  return buildVnodeDbTableCount(pOperator, pInfo, pSupp, pRes);
}

static SSDataBlock* buildVnodeDbTableCount(SOperatorInfo* pOperator, STableCountScanOperatorInfo* pInfo,
                                           STableCountScanSupp* pSupp, SSDataBlock* pRes) {
S
slzhou 已提交
3346 3347
  const char* db = NULL;
  int32_t     vgId = 0;
S
slzhou 已提交
3348
  char        dbName[TSDB_DB_NAME_LEN] = {0};
3349 3350
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
  SStorageAPI* pAPI = &pTaskInfo->storageAPI;
S
slzhou 已提交
3351

S
slzhou 已提交
3352
  // get dbname
3353
  pAPI->metaFn.getBasicInfo(pInfo->readHandle.vnode, &db, &vgId, NULL, NULL);
S
slzhou 已提交
3354 3355 3356 3357
  SName sn = {0};
  tNameFromString(&sn, db, T_NAME_ACCT | T_NAME_DB);
  tNameGetDbName(&sn, dbName);

D
dapan1121 已提交
3358
  if (pSupp->groupByDbName || pSupp->groupByStbName) {
S
slzhou 已提交
3359 3360 3361 3362 3363 3364 3365 3366 3367
    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) {
3368 3369 3370
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
  SStorageAPI* pAPI = &pTaskInfo->storageAPI;

S
slzhou 已提交
3371 3372 3373
  if (pSupp->groupByStbName) {
    if (pInfo->stbUidList == NULL) {
      pInfo->stbUidList = taosArrayInit(16, sizeof(tb_uid_t));
H
Haojun Liao 已提交
3374
      if (pAPI->metaFn.storeGetTableList(pInfo->readHandle.vnode, TSDB_SUPER_TABLE, pInfo->stbUidList) < 0) {
S
slzhou 已提交
3375
        qError("vgId:%d, failed to get stb id list error: %s", vgId, terrstr());
S
slzhou 已提交
3376
      }
S
slzhou 已提交
3377 3378 3379
    }
    if (pInfo->currGrpIdx < taosArrayGetSize(pInfo->stbUidList)) {
      tb_uid_t stbUid = *(tb_uid_t*)taosArrayGet(pInfo->stbUidList, pInfo->currGrpIdx);
3380
      buildVnodeGroupedStbTableCount(pInfo, pSupp, pRes, dbName, stbUid, pAPI);
S
slzhou 已提交
3381 3382 3383

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

      pInfo->currGrpIdx++;
S
slzhou 已提交
3387
    } else {
S
slzhou 已提交
3388
      setOperatorCompleted(pOperator);
S
slzhou 已提交
3389 3390
    }
  } else {
S
slzhou 已提交
3391 3392
    uint64_t groupId = calcGroupId(dbName, strlen(dbName));
    pRes->info.id.groupId = groupId;
3393 3394

    int64_t dbTableCount = 0;
3395
    pAPI->metaFn.getBasicInfo(pInfo->readHandle.vnode, NULL, NULL, &dbTableCount, NULL);
S
slzhou 已提交
3396 3397 3398 3399 3400 3401 3402
    fillTableCountScanDataBlock(pSupp, dbName, "", dbTableCount, pRes);
    setOperatorCompleted(pOperator);
  }
}

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

S
slzhou 已提交
3406 3407
  if (strlen(pSupp->dbNameFilter) != 0) {
    if (strlen(pSupp->stbNameFilter) != 0) {
H
Haojun Liao 已提交
3408
      uint64_t uid = 0;
3409
      pAPI->metaFn.getTableUidByName(pInfo->readHandle.vnode, pSupp->stbNameFilter, &uid);
3410 3411 3412 3413 3414

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

      fillTableCountScanDataBlock(pSupp, dbName, pSupp->stbNameFilter, numOfChildTables, pRes);
S
slzhou 已提交
3415
    } else {
H
Haojun Liao 已提交
3416 3417
      int64_t tbNumVnode = 0;
      pAPI->metaFn.getBasicInfo(pInfo->readHandle.vnode, NULL, NULL, &tbNumVnode, NULL);
S
slzhou 已提交
3418
      fillTableCountScanDataBlock(pSupp, dbName, "", tbNumVnode, pRes);
S
slzhou 已提交
3419
    }
S
slzhou 已提交
3420
  } else {
3421 3422
    int64_t tbNumVnode = 0;
    pAPI->metaFn.getBasicInfo(pInfo->readHandle.vnode, NULL, NULL, &tbNumVnode, NULL);
S
slzhou 已提交
3423
    fillTableCountScanDataBlock(pSupp, dbName, "", tbNumVnode, pRes);
S
slzhou 已提交
3424
  }
3425

S
slzhou 已提交
3426 3427 3428 3429
  setOperatorCompleted(pOperator);
}

static void buildVnodeGroupedNtbTableCount(STableCountScanOperatorInfo* pInfo, STableCountScanSupp* pSupp,
3430
                                           SSDataBlock* pRes, char* dbName, SStorageAPI* pAPI) {
S
slzhou 已提交
3431
  char fullStbName[TSDB_TABLE_FNAME_LEN] = {0};
D
dapan1121 已提交
3432 3433 3434
  if (pSupp->groupByDbName) {
    snprintf(fullStbName, TSDB_TABLE_FNAME_LEN, "%s.%s", dbName, "");
  }
X
Xiaoyu Wang 已提交
3435

S
slzhou 已提交
3436 3437
  uint64_t groupId = calcGroupId(fullStbName, strlen(fullStbName));
  pRes->info.id.groupId = groupId;
3438

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

3442 3443
  if (numOfTables != 0) {
    fillTableCountScanDataBlock(pSupp, dbName, "", numOfTables, pRes);
3444
  }
S
slzhou 已提交
3445 3446 3447
}

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

  char fullStbName[TSDB_TABLE_FNAME_LEN] = {0};
D
dapan1121 已提交
3453
  if (pSupp->groupByDbName) {
H
Haojun Liao 已提交
3454
    snprintf(fullStbName, TSDB_TABLE_FNAME_LEN, "%s.%s", dbName, varDataVal(stbName));
D
dapan1121 已提交
3455
  } else {
H
Haojun Liao 已提交
3456
    snprintf(fullStbName, TSDB_TABLE_FNAME_LEN, "%s", varDataVal(stbName));
D
dapan1121 已提交
3457
  }
X
Xiaoyu Wang 已提交
3458

S
slzhou 已提交
3459 3460 3461
  uint64_t groupId = calcGroupId(fullStbName, strlen(fullStbName));
  pRes->info.id.groupId = groupId;

H
Haojun Liao 已提交
3462 3463
  int64_t ctbNum = 0;
  int32_t code = pAPI->metaFn.getNumOfChildTables(pInfo->readHandle.vnode, stbUid, &ctbNum);
H
Haojun Liao 已提交
3464
  fillTableCountScanDataBlock(pSupp, dbName, varDataVal(stbName), ctbNum, pRes);
S
shenglian zhou 已提交
3465 3466 3467
}

static void destoryTableCountScanOperator(void* param) {
S
slzhou 已提交
3468
  STableCountScanOperatorInfo* pTableCountScanInfo = param;
S
shenglian zhou 已提交
3469 3470
  blockDataDestroy(pTableCountScanInfo->pRes);

S
slzhou 已提交
3471
  taosArrayDestroy(pTableCountScanInfo->stbUidList);
S
shenglian zhou 已提交
3472 3473
  taosMemoryFreeClear(param);
}
dengyihao's avatar
dengyihao 已提交
3474 3475

// clang-format on