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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

bool processBlockWithProbability(const SSampleExecInfo* pInfo) {
123 124 125 126 127 128 129 130 131 132 133 134
#if 0
  if (pInfo->sampleRatio == 1) {
    return true;
  }

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

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

141 142 143 144 145 146 147 148 149
static void getNextTimeWindow(SInterval* pInterval, STimeWindow* tw, int32_t order) {
  int32_t factor = GET_FORWARD_DIRECTION_FACTOR(order);
  if (pInterval->intervalUnit != 'n' && pInterval->intervalUnit != 'y') {
    tw->skey += pInterval->sliding * factor;
    tw->ekey = tw->skey + pInterval->interval - 1;
    return;
  }

  int64_t key = tw->skey, interval = pInterval->interval;
150
  // convert key to second
151 152 153 154 155 156 157
  key = convertTimePrecision(key, pInterval->precision, TSDB_TIME_PRECISION_MILLI) / 1000;

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

  struct tm tm;
158
  time_t    t = (time_t)key;
159 160 161 162 163
  taosLocalTime(&t, &tm);

  int mon = (int)(tm.tm_year * 12 + tm.tm_mon + interval * factor);
  tm.tm_year = mon / 12;
  tm.tm_mon = mon % 12;
wafwerar's avatar
wafwerar 已提交
164
  tw->skey = convertTimePrecision((int64_t)taosMktime(&tm) * 1000LL, TSDB_TIME_PRECISION_MILLI, pInterval->precision);
165 166 167 168

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

  tw->ekey -= 1;
}

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

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

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

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

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

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

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

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

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

  return false;
}

225 226 227 228 229 230 231 232 233 234 235
// this function is for table scanner to extract temporary results of upstream aggregate results.
static SResultRow* getTableGroupOutputBuf(SOperatorInfo* pOperator, uint64_t groupId, SFilePage** pPage) {
  if (pOperator->operatorType != QUERY_NODE_PHYSICAL_PLAN_TABLE_SCAN) {
    return NULL;
  }

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

  STableScanInfo* pTableScanInfo = pOperator->info;

H
Haojun Liao 已提交
236
  SResultRowPosition* p1 = (SResultRowPosition*)tSimpleHashGet(pTableScanInfo->base.pdInfo.pAggSup->pResultRowHashTable, buf,
237
                                                               GET_RES_WINDOW_KEY_LEN(sizeof(groupId)));
238 239 240 241 242

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

H
Haojun Liao 已提交
243
  *pPage = getBufPage(pTableScanInfo->base.pdInfo.pAggSup->pResultBuf, p1->pageId);
244 245 246 247 248 249
  return (SResultRow*)((char*)(*pPage) + p1->offset);
}

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

H
Haojun Liao 已提交
250
  if (pTableScanInfo->base.pdInfo.pExprSup == NULL) {
251 252 253
    return TSDB_CODE_SUCCESS;
  }

H
Haojun Liao 已提交
254
  SExprSupp* pSup1 = pTableScanInfo->base.pdInfo.pExprSup;
255 256 257 258 259 260 261 262 263 264 265 266

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

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

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

H
Haojun Liao 已提交
267
    SResultRowEntryInfo* pEntry = getResultEntryInfo(pRow, i, pTableScanInfo->base.pdInfo.pExprSup->rowEntryInfoOffset);
268 269 270 271 272 273 274 275 276

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

  // release buffer pages
H
Haojun Liao 已提交
277
  releaseBufPage(pTableScanInfo->base.pdInfo.pAggSup->pResultBuf, pPage);
278 279 280 281 282 283 284 285

  if (notLoadBlock) {
    *status = FUNC_DATA_REQUIRED_NOT_LOAD;
  }

  return TSDB_CODE_SUCCESS;
}

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

H
Haojun Liao 已提交
292
  bool keep = filterRangeExecute(pFilterInfo, pColsAgg, numOfCols, numOfRows);
H
Haojun Liao 已提交
293 294 295
  return keep;
}

H
Haojun Liao 已提交
296
static bool doLoadBlockSMA(STableScanBase* pTableScanInfo, SSDataBlock* pBlock, SExecTaskInfo* pTaskInfo) {
H
Haojun Liao 已提交
297 298 299 300 301
  bool             allColumnsHaveAgg = true;
  SColumnDataAgg** pColAgg = NULL;

  int32_t code = tsdbRetrieveDatablockSMA(pTableScanInfo->dataReader, &pColAgg, &allColumnsHaveAgg);
  if (code != TSDB_CODE_SUCCESS) {
302
    T_LONG_JMP(pTaskInfo->env, code);
H
Haojun Liao 已提交
303 304 305 306 307 308 309 310 311 312 313 314 315
  }

  if (!allColumnsHaveAgg) {
    return false;
  }

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

  // todo create this buffer during creating operator
  if (pBlock->pBlockAgg == NULL) {
    pBlock->pBlockAgg = taosMemoryCalloc(numOfCols, POINTER_BYTES);
    if (pBlock->pBlockAgg == NULL) {
316
      T_LONG_JMP(pTaskInfo->env, TSDB_CODE_OUT_OF_MEMORY);
H
Haojun Liao 已提交
317 318 319
    }
  }

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

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

  return true;
}

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

338
    int32_t code = addTagPseudoColumnData(&pTableScanInfo->readHandle, pSup->pExprInfo, pSup->numOfExprs, pBlock, rows,
339
                                          GET_TASKID(pTaskInfo), &pTableScanInfo->metaCache);
H
Haojun Liao 已提交
340
    // ignore the table not exists error, since this table may have been dropped during the scan procedure.
H
Haojun Liao 已提交
341
    if (code != TSDB_CODE_SUCCESS && code != TSDB_CODE_PAR_TABLE_NOT_EXIST) {
H
Haojun Liao 已提交
342 343
      T_LONG_JMP(pTaskInfo->env, code);
    }
H
Haojun Liao 已提交
344 345 346

    // reset the error code.
    terrno = 0;
H
Haojun Liao 已提交
347 348 349
  }
}

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

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

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

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

H
Haojun Liao 已提交
377
static int32_t loadDataBlock(SOperatorInfo* pOperator, STableScanBase* pTableScanInfo, SSDataBlock* pBlock,
L
Liu Jicong 已提交
378
                             uint32_t* status) {
379
  SExecTaskInfo*  pTaskInfo = pOperator->pTaskInfo;
380
  SFileBlockLoadRecorder* pCost = &pTableScanInfo->readRecorder;
H
Haojun Liao 已提交
381 382

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

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

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

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

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

H
Haojun Liao 已提交
424
  // try to filter data block according to sma info
H
Haojun Liao 已提交
425
  if (pOperator->exprSupp.pFilterInfo != NULL && (!loadSMA)) {
426 427 428
    bool success = doLoadBlockSMA(pTableScanInfo, pBlock, pTaskInfo);
    if (success) {
      size_t size = taosArrayGetSize(pBlock->pDataBlock);
H
Haojun Liao 已提交
429
      bool   keep = doFilterByBlockSMA(pOperator->exprSupp.pFilterInfo, pBlock->pBlockAgg, size, pBlockInfo->rows);
430 431 432 433 434 435 436 437
      if (!keep) {
        qDebug("%s data block filter out by block SMA, brange:%" PRId64 "-%" PRId64 ", rows:%d", GET_TASKID(pTaskInfo),
               pBlockInfo->window.skey, pBlockInfo->window.ekey, pBlockInfo->rows);
        pCost->filterOutBlocks += 1;
        (*status) = FUNC_DATA_REQUIRED_FILTEROUT;

        return TSDB_CODE_SUCCESS;
      }
438
    }
H
Haojun Liao 已提交
439
  }
440

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

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

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

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

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

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

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

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

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

476 477 478 479 480 481 482
    if (pBlock->info.rows == 0) {
      pCost->filterOutBlocks += 1;
      qDebug("%s data block filter out, brange:%" PRId64 "-%" PRId64 ", rows:%d, elapsed time:%.2f ms",
             GET_TASKID(pTaskInfo), pBlockInfo->window.skey, pBlockInfo->window.ekey, pBlockInfo->rows, el);
    } else {
      qDebug("%s data block filter applied, elapsed time:%.2f ms", GET_TASKID(pTaskInfo), el);
    }
483 484
  }

H
Haojun Liao 已提交
485
  applyLimitOffset(&pTableScanInfo->limitInfo, pBlock, pTaskInfo, pOperator);
486

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

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

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

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

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

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

H
Haojun Liao 已提交
517 518 519 520 521 522 523
static STableCachedVal* createTableCacheVal(const SMetaReader* pMetaReader) {
  STableCachedVal* pVal = taosMemoryMalloc(sizeof(STableCachedVal));
  pVal->pName = strdup(pMetaReader->me.name);
  pVal->pTags = NULL;

  // only child table has tag value
  if (pMetaReader->me.type == TSDB_CHILD_TABLE) {
524
    STag* pTag = (STag*)pMetaReader->me.ctbEntry.pTags;
H
Haojun Liao 已提交
525 526 527 528 529 530 531
    pVal->pTags = taosMemoryMalloc(pTag->len);
    memcpy(pVal->pTags, pTag, pTag->len);
  }

  return pVal;
}

532 533
// const void *key, size_t keyLen, void *value
static void freeCachedMetaItem(const void* key, size_t keyLen, void* value) { freeTableCachedVal(value); }
534

535 536
int32_t addTagPseudoColumnData(SReadHandle* pHandle, const SExprInfo* pExpr, int32_t numOfExpr, SSDataBlock* pBlock,
                               int32_t rows, const char* idStr, STableMetaCacheInfo* pCache) {
537
  // currently only the tbname pseudo column
538
  if (numOfExpr <= 0) {
H
Haojun Liao 已提交
539
    return TSDB_CODE_SUCCESS;
540 541
  }

542 543
  int32_t code = 0;

544 545 546 547
  // backup the rows
  int32_t backupRows = pBlock->info.rows;
  pBlock->info.rows = rows;

548
  bool            freeReader = false;
549
  STableCachedVal val = {0};
550 551

  SMetaReader mr = {0};
552
  LRUHandle*  h = NULL;
553

554
  // 1. check if it is existed in meta cache
555
  if (pCache == NULL) {
556 557 558
    metaReaderInit(&mr, pHandle->meta, 0);
    code = metaGetTableEntryByUid(&mr, pBlock->info.uid);
    if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
559
      if (terrno == TSDB_CODE_PAR_TABLE_NOT_EXIST) {
560 561
        qWarn("failed to get table meta, table may have been dropped, uid:0x%" PRIx64 ", code:%s, %s", pBlock->info.uid,
              tstrerror(terrno), idStr);
H
Haojun Liao 已提交
562 563 564
      } else {
        qError("failed to get table meta, uid:0x%" PRIx64 ", code:%s, %s", pBlock->info.uid, tstrerror(terrno), idStr);
      }
565 566 567 568 569
      metaReaderClear(&mr);
      return terrno;
    }

    metaReaderReleaseLock(&mr);
570

571 572
    val.pName = mr.me.name;
    val.pTags = (STag*)mr.me.ctbEntry.pTags;
573 574

    freeReader = true;
575
  } else {
576 577
    pCache->metaFetch += 1;

H
Haojun Liao 已提交
578
    h = taosLRUCacheLookup(pCache->pTableMetaEntryCache, &pBlock->info.uid, sizeof(pBlock->info.uid));
579 580 581 582
    if (h == NULL) {
      metaReaderInit(&mr, pHandle->meta, 0);
      code = metaGetTableEntryByUid(&mr, pBlock->info.uid);
      if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
583
        if (terrno == TSDB_CODE_PAR_TABLE_NOT_EXIST) {
584 585
          qWarn("failed to get table meta, table may have been dropped, uid:0x%" PRIx64 ", code:%s, %s",
                pBlock->info.uid, tstrerror(terrno), idStr);
H
Haojun Liao 已提交
586
        } else {
587 588
          qError("failed to get table meta, uid:0x%" PRIx64 ", code:%s, %s", pBlock->info.uid, tstrerror(terrno),
                 idStr);
H
Haojun Liao 已提交
589
        }
590 591 592 593 594 595
        metaReaderClear(&mr);
        return terrno;
      }

      metaReaderReleaseLock(&mr);

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

H
Haojun Liao 已提交
598
      val = *pVal;
599
      freeReader = true;
H
Haojun Liao 已提交
600

601 602
      int32_t ret = taosLRUCacheInsert(pCache->pTableMetaEntryCache, &pBlock->info.uid, sizeof(uint64_t), pVal,
                                       sizeof(STableCachedVal), freeCachedMetaItem, NULL, TAOS_LRU_PRIORITY_LOW);
603 604 605 606 607 608 609 610
      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 已提交
611

H
Haojun Liao 已提交
612
      taosLRUCacheRelease(pCache->pTableMetaEntryCache, h, false);
613
    }
H
Haojun Liao 已提交
614

615 616
    qDebug("retrieve table meta from cache:%" PRIu64 ", hit:%" PRIu64 " miss:%" PRIu64 ", %s", pCache->metaFetch,
           pCache->cacheHit, (pCache->metaFetch - pCache->cacheHit), idStr);
H
Haojun Liao 已提交
617
  }
618

619 620
  for (int32_t j = 0; j < numOfExpr; ++j) {
    const SExprInfo* pExpr1 = &pExpr[j];
621
    int32_t          dstSlotId = pExpr1->base.resSchema.slotId;
622 623

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

626
    int32_t functionId = pExpr1->pExpr->_function.functionId;
627 628 629

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

636 637 638 639
      char* data = NULL;
      if (pColInfoData->info.type != TSDB_DATA_TYPE_JSON && p != NULL) {
        data = tTagValToData((const STagVal*)p, false);
      } else {
wmmhello's avatar
wmmhello 已提交
640
        data = (char*)p;
wmmhello's avatar
wmmhello 已提交
641
      }
642

H
Haojun Liao 已提交
643 644 645
      bool isNullVal = (data == NULL) || (pColInfoData->info.type == TSDB_DATA_TYPE_JSON && tTagIsJsonNull(data));
      if (isNullVal) {
        colDataAppendNNULL(pColInfoData, 0, pBlock->info.rows);
H
Haojun Liao 已提交
646
      } else if (pColInfoData->info.type != TSDB_DATA_TYPE_JSON) {
H
Haojun Liao 已提交
647
        colDataAppendNItems(pColInfoData, 0, data, pBlock->info.rows);
H
Haojun Liao 已提交
648 649 650
        if (IS_VAR_DATA_TYPE(((const STagVal*)p)->type)) {
          taosMemoryFree(data);
        }
L
Liu Jicong 已提交
651
      } else {  // todo opt for json tag
H
Haojun Liao 已提交
652
        for (int32_t i = 0; i < pBlock->info.rows; ++i) {
H
Haojun Liao 已提交
653
          colDataAppend(pColInfoData, i, data, false);
H
Haojun Liao 已提交
654
        }
655 656 657 658
      }
    }
  }

659 660
  // restore the rows
  pBlock->info.rows = backupRows;
661 662 663 664
  if (freeReader) {
    metaReaderClear(&mr);
  }

H
Haojun Liao 已提交
665
  return TSDB_CODE_SUCCESS;
666 667
}

H
Haojun Liao 已提交
668
void setTbNameColData(const SSDataBlock* pBlock, SColumnInfoData* pColInfoData, int32_t functionId, const char* name) {
669 670 671
  struct SScalarFuncExecFuncs fpSet = {0};
  fmGetScalarFuncExecFuncs(functionId, &fpSet);

H
Haojun Liao 已提交
672
  size_t len = TSDB_TABLE_FNAME_LEN + VARSTR_HEADER_SIZE;
673
  char   buf[TSDB_TABLE_FNAME_LEN + VARSTR_HEADER_SIZE] = {0};
H
Haojun Liao 已提交
674 675 676
  STR_TO_VARSTR(buf, name)

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

H
Haojun Liao 已提交
678 679
  colInfoDataEnsureCapacity(&infoData, 1, false);
  colDataAppend(&infoData, 0, buf, false);
680

H
Haojun Liao 已提交
681
  SScalarParam srcParam = {.numOfRows = pBlock->info.rows, .columnData = &infoData};
682
  SScalarParam param = {.columnData = pColInfoData};
H
Haojun Liao 已提交
683 684 685 686 687 688 689

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

D
dapan1121 已提交
690
  colDataDestroy(&infoData);
691 692
}

693
static SSDataBlock* doTableScanImpl(SOperatorInfo* pOperator) {
H
Haojun Liao 已提交
694
  STableScanInfo* pTableScanInfo = pOperator->info;
695
  SExecTaskInfo*  pTaskInfo = pOperator->pTaskInfo;
L
Liu Jicong 已提交
696
  SSDataBlock*    pBlock = pTableScanInfo->pResBlock;
H
Haojun Liao 已提交
697

698 699
  int64_t st = taosGetTimestampUs();

H
Haojun Liao 已提交
700
  while (tsdbNextDataBlock(pTableScanInfo->base.dataReader)) {
701
    if (isTaskKilled(pTaskInfo)) {
702
      T_LONG_JMP(pTaskInfo->env, TSDB_CODE_TSC_QUERY_CANCELLED);
703
    }
H
Haojun Liao 已提交
704

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

711
    blockDataCleanup(pBlock);
H
Haojun Liao 已提交
712
    SDataBlockInfo* pBInfo = &pBlock->info;
H
Haojun Liao 已提交
713 714

    int32_t rows = 0;
H
Haojun Liao 已提交
715
    tsdbRetrieveDataBlockInfo(pTableScanInfo->base.dataReader, &rows, &pBInfo->uid, &pBInfo->window);
H
Haojun Liao 已提交
716

717
    blockDataEnsureCapacity(pBlock, rows);  // todo remove it latter
H
Haojun Liao 已提交
718
    pBInfo->rows = rows;
719

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

723
    uint32_t status = 0;
H
Haojun Liao 已提交
724
    int32_t  code = loadDataBlock(pOperator, &pTableScanInfo->base, pBlock, &status);
725 726
    //    int32_t  code = loadDataBlockOnDemand(pOperator->pRuntimeEnv, pTableScanInfo, pBlock, &status);
    if (code != TSDB_CODE_SUCCESS) {
727
      T_LONG_JMP(pOperator->pTaskInfo->env, code);
728
    }
729

730 731 732
    // 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;
733
    }
734

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

H
Haojun Liao 已提交
738
    pOperator->cost.totalCost = pTableScanInfo->base.readRecorder.elapsedTime;
739 740

    // todo refactor
L
Liu Jicong 已提交
741 742 743 744 745
    /*pTableScanInfo->lastStatus.uid = pBlock->info.uid;*/
    /*pTableScanInfo->lastStatus.ts = pBlock->info.window.ekey;*/
    pTaskInfo->streamInfo.lastStatus.type = TMQ_OFFSET__SNAPSHOT_DATA;
    pTaskInfo->streamInfo.lastStatus.uid = pBlock->info.uid;
    pTaskInfo->streamInfo.lastStatus.ts = pBlock->info.window.ekey;
746

L
Liu Jicong 已提交
747
    ASSERT(pBlock->info.uid != 0);
748
    return pBlock;
H
Haojun Liao 已提交
749 750 751 752
  }
  return NULL;
}

H
Haojun Liao 已提交
753
static SSDataBlock* doGroupedTableScan(SOperatorInfo* pOperator) {
H
Haojun Liao 已提交
754 755 756 757
  STableScanInfo* pTableScanInfo = pOperator->info;
  SExecTaskInfo*  pTaskInfo = pOperator->pTaskInfo;

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

762 763
  // do the ascending order traverse in the first place.
  while (pTableScanInfo->scanTimes < pTableScanInfo->scanInfo.numOfAsc) {
H
Haojun Liao 已提交
764 765 766
    SSDataBlock* p = doTableScanImpl(pOperator);
    if (p != NULL) {
      return p;
H
Haojun Liao 已提交
767 768
    }

769
    pTableScanInfo->scanTimes += 1;
770

771
    if (pTableScanInfo->scanTimes < pTableScanInfo->scanInfo.numOfAsc) {
772
      setTaskStatus(pTaskInfo, TASK_NOT_COMPLETED);
H
Haojun Liao 已提交
773
      pTableScanInfo->base.scanFlag = REPEAT_SCAN;
774
      qDebug("start to repeat ascending order scan data blocks due to query func required, %s", GET_TASKID(pTaskInfo));
H
Haojun Liao 已提交
775

776
      // do prepare for the next round table scan operation
H
Haojun Liao 已提交
777
      tsdbReaderReset(pTableScanInfo->base.dataReader, &pTableScanInfo->base.cond);
H
Haojun Liao 已提交
778
    }
779
  }
H
Haojun Liao 已提交
780

781
  int32_t total = pTableScanInfo->scanInfo.numOfAsc + pTableScanInfo->scanInfo.numOfDesc;
782
  if (pTableScanInfo->scanTimes < total) {
H
Haojun Liao 已提交
783 784 785
    if (pTableScanInfo->base.cond.order == TSDB_ORDER_ASC) {
      prepareForDescendingScan(&pTableScanInfo->base, pOperator->exprSupp.pCtx, 0);
      tsdbReaderReset(pTableScanInfo->base.dataReader, &pTableScanInfo->base.cond);
786
      qDebug("%s start to descending order scan data blocks due to query func required", GET_TASKID(pTaskInfo));
787
    }
H
Haojun Liao 已提交
788

789
    while (pTableScanInfo->scanTimes < total) {
H
Haojun Liao 已提交
790 791 792
      SSDataBlock* p = doTableScanImpl(pOperator);
      if (p != NULL) {
        return p;
793
      }
H
Haojun Liao 已提交
794

795
      pTableScanInfo->scanTimes += 1;
H
Haojun Liao 已提交
796

797
      if (pTableScanInfo->scanTimes < total) {
798
        setTaskStatus(pTaskInfo, TASK_NOT_COMPLETED);
H
Haojun Liao 已提交
799
        pTableScanInfo->base.scanFlag = REPEAT_SCAN;
H
Haojun Liao 已提交
800

801
        qDebug("%s start to repeat descending order scan data blocks", GET_TASKID(pTaskInfo));
H
Haojun Liao 已提交
802
        tsdbReaderReset(pTableScanInfo->base.dataReader, &pTableScanInfo->base.cond);
803
      }
H
Haojun Liao 已提交
804 805 806
    }
  }

wmmhello's avatar
wmmhello 已提交
807 808 809 810 811 812 813
  return NULL;
}

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

814
  // scan table one by one sequentially
L
Liu Jicong 已提交
815
  if (pInfo->scanMode == TABLE_SCAN__TABLE_ORDER) {
H
Haojun Liao 已提交
816
    int32_t numOfTables = tableListGetSize(pTaskInfo->pTableInfoList);
H
Haojun Liao 已提交
817

L
Liu Jicong 已提交
818
    while (1) {
H
Haojun Liao 已提交
819
      SSDataBlock* result = doGroupedTableScan(pOperator);
L
Liu Jicong 已提交
820 821 822
      if (result) {
        return result;
      }
H
Haojun Liao 已提交
823

L
Liu Jicong 已提交
824 825
      // if no data, switch to next table and continue scan
      pInfo->currentTable++;
H
Haojun Liao 已提交
826
      if (pInfo->currentTable >= numOfTables) {
L
Liu Jicong 已提交
827 828
        return NULL;
      }
H
Haojun Liao 已提交
829

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

H
Haojun Liao 已提交
835
      tsdbReaderReset(pInfo->base.dataReader, &pInfo->base.cond);
L
Liu Jicong 已提交
836 837
      pInfo->scanTimes = 0;
    }
838 839
  } else {  // scan table group by group sequentially
    if (pInfo->currentGroupId == -1) {
H
Haojun Liao 已提交
840
      if ((++pInfo->currentGroupId) >= tableListGetOutputGroups(pTaskInfo->pTableInfoList)) {
H
Haojun Liao 已提交
841
        setOperatorCompleted(pOperator);
842 843
        return NULL;
      }
844

5
54liuyao 已提交
845
      int32_t        num = 0;
846
      STableKeyInfo* pList = NULL;
H
Haojun Liao 已提交
847
      tableListGetGroupList(pTaskInfo->pTableInfoList, pInfo->currentGroupId, &pList, &num);
H
Haojun Liao 已提交
848
      ASSERT(pInfo->base.dataReader == NULL);
849

H
Haojun Liao 已提交
850 851
      int32_t code = tsdbReaderOpen(pInfo->base.readHandle.vnode, &pInfo->base.cond, pList, num,
                                    (STsdbReader**)&pInfo->base.dataReader, GET_TASKID(pTaskInfo));
852 853 854
      if (code != TSDB_CODE_SUCCESS) {
        T_LONG_JMP(pTaskInfo->env, code);
      }
wmmhello's avatar
wmmhello 已提交
855
    }
H
Haojun Liao 已提交
856

H
Haojun Liao 已提交
857
    SSDataBlock* result = doGroupedTableScan(pOperator);
858
    if (result != NULL) {
H
Haojun Liao 已提交
859
      ASSERT(result->info.uid != 0);
860 861
      return result;
    }
H
Haojun Liao 已提交
862

H
Haojun Liao 已提交
863
    if ((++pInfo->currentGroupId) >= tableListGetOutputGroups(pTaskInfo->pTableInfoList)) {
H
Haojun Liao 已提交
864
      setOperatorCompleted(pOperator);
865 866
      return NULL;
    }
wmmhello's avatar
wmmhello 已提交
867

868 869
    // reset value for the next group data output
    pOperator->status = OP_OPENED;
H
Haojun Liao 已提交
870 871
    pInfo->base.limitInfo.numOfOutputRows = 0;
    pInfo->base.limitInfo.remainOffset = pInfo->base.limitInfo.limit.offset;
wmmhello's avatar
wmmhello 已提交
872

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

H
Haojun Liao 已提交
877 878
    tsdbSetTableList(pInfo->base.dataReader, pList, num);
    tsdbReaderReset(pInfo->base.dataReader, &pInfo->base.cond);
879
    pInfo->scanTimes = 0;
wmmhello's avatar
wmmhello 已提交
880

H
Haojun Liao 已提交
881
    result = doGroupedTableScan(pOperator);
882 883 884
    if (result != NULL) {
      return result;
    }
885

H
Haojun Liao 已提交
886
    setOperatorCompleted(pOperator);
887 888
    return NULL;
  }
H
Haojun Liao 已提交
889 890
}

891 892
static int32_t getTableScannerExecInfo(struct SOperatorInfo* pOptr, void** pOptrExplain, uint32_t* len) {
  SFileBlockLoadRecorder* pRecorder = taosMemoryCalloc(1, sizeof(SFileBlockLoadRecorder));
893
  STableScanInfo*         pTableScanInfo = pOptr->info;
H
Haojun Liao 已提交
894
  *pRecorder = pTableScanInfo->base.readRecorder;
895 896 897 898 899
  *pOptrExplain = pRecorder;
  *len = sizeof(SFileBlockLoadRecorder);
  return 0;
}

900
static void destroyTableScanOperatorInfo(void* param) {
901
  STableScanInfo* pTableScanInfo = (STableScanInfo*)param;
H
Haojun Liao 已提交
902
  blockDataDestroy(pTableScanInfo->pResBlock);
H
Haojun Liao 已提交
903
  cleanupQueryTableDataCond(&pTableScanInfo->base.cond);
H
Haojun Liao 已提交
904

H
Haojun Liao 已提交
905 906
  tsdbReaderClose(pTableScanInfo->base.dataReader);
  pTableScanInfo->base.dataReader = NULL;
907

H
Haojun Liao 已提交
908 909
  if (pTableScanInfo->base.matchInfo.pList != NULL) {
    taosArrayDestroy(pTableScanInfo->base.matchInfo.pList);
910
  }
L
Liu Jicong 已提交
911

H
Haojun Liao 已提交
912 913
  taosLRUCacheCleanup(pTableScanInfo->base.metaCache.pTableMetaEntryCache);
  cleanupExprSupp(&pTableScanInfo->base.pseudoSup);
D
dapan1121 已提交
914
  taosMemoryFreeClear(param);
915 916
}

917
SOperatorInfo* createTableScanOperatorInfo(STableScanPhysiNode* pTableScanNode, SReadHandle* readHandle,
918
                                           SExecTaskInfo* pTaskInfo) {
H
Haojun Liao 已提交
919 920 921
  STableScanInfo* pInfo = taosMemoryCalloc(1, sizeof(STableScanInfo));
  SOperatorInfo*  pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
  if (pInfo == NULL || pOperator == NULL) {
922
    goto _error;
H
Haojun Liao 已提交
923 924
  }

925
  SScanPhysiNode*     pScanNode = &pTableScanNode->scan;
H
Haojun Liao 已提交
926
  SDataBlockDescNode* pDescNode = pScanNode->node.pOutputDataBlockDesc;
927 928

  int32_t numOfCols = 0;
929
  int32_t code =
H
Haojun Liao 已提交
930
      extractColMatchInfo(pScanNode->pScanCols, pDescNode, &numOfCols, COL_MATCH_FROM_COL_ID, &pInfo->base.matchInfo);
931 932 933 934
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }

H
Haojun Liao 已提交
935
  initLimitInfo(pScanNode->node.pLimit, pScanNode->node.pSlimit, &pInfo->base.limitInfo);
H
Haojun Liao 已提交
936
  code = initQueryTableDataCond(&pInfo->base.cond, pTableScanNode);
937
  if (code != TSDB_CODE_SUCCESS) {
938
    goto _error;
939 940
  }

H
Haojun Liao 已提交
941
  if (pScanNode->pScanPseudoCols != NULL) {
H
Haojun Liao 已提交
942
    SExprSupp* pSup = &pInfo->base.pseudoSup;
H
Haojun Liao 已提交
943
    pSup->pExprInfo = createExprInfo(pScanNode->pScanPseudoCols, NULL, &pSup->numOfExprs);
944
    pSup->pCtx = createSqlFunctionCtx(pSup->pExprInfo, pSup->numOfExprs, &pSup->rowEntryInfoOffset);
945 946
  }

947
  pInfo->scanInfo = (SScanInfo){.numOfAsc = pTableScanNode->scanSeq[0], .numOfDesc = pTableScanNode->scanSeq[1]};
H
Haojun Liao 已提交
948 949

  pInfo->base.scanFlag = MAIN_SCAN;
H
Haojun Liao 已提交
950 951
  pInfo->base.pdInfo.interval = extractIntervalInfo(pTableScanNode);
  pInfo->base.readHandle = *readHandle;
952 953
  pInfo->sample.sampleRatio = pTableScanNode->ratio;
  pInfo->sample.seed = taosGetTimestampSec();
954

H
Haojun Liao 已提交
955
  pInfo->base.dataBlockLoadFlag = pTableScanNode->dataRequired;
H
Haojun Liao 已提交
956 957

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

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

wmmhello's avatar
wmmhello 已提交
966
  pInfo->currentGroupId = -1;
967
  pInfo->assignBlockUid = pTableScanNode->assignBlockUid;
968

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

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

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

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

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

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

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

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

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

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

1013
  SMetaReader mr = {0};
1014
  metaReaderInit(&mr, pMeta, 0);
H
Haojun Liao 已提交
1015 1016
  int32_t code = metaGetTableEntryByUid(&mr, uid);
  if (code != TSDB_CODE_SUCCESS) {
L
Liu Jicong 已提交
1017
    qError("failed to get table meta, uid:0x%" PRIx64 ", code:%s, %s", uid, tstrerror(terrno), idstr);
H
Haojun Liao 已提交
1018 1019 1020 1021
    metaReaderClear(&mr);
    return terrno;
  }

1022 1023
  if (mr.me.type == TSDB_SUPER_TABLE) {
    int32_t numOfCols = mr.me.stbEntry.schemaRow.nCols;
1024
    for (int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
1025
      (*rowLen) += mr.me.stbEntry.schemaRow.pSchema[i].bytes;
1026 1027 1028
    }
  } else if (mr.me.type == TSDB_CHILD_TABLE) {
    uint64_t suid = mr.me.ctbEntry.suid;
1029
    tDecoderClear(&mr.coder);
H
Haojun Liao 已提交
1030 1031
    code = metaGetTableEntryByUid(&mr, suid);
    if (code != TSDB_CODE_SUCCESS) {
L
Liu Jicong 已提交
1032
      qError("failed to get table meta, uid:0x%" PRIx64 ", code:%s, %s", suid, tstrerror(terrno), idstr);
H
Haojun Liao 已提交
1033 1034 1035 1036
      metaReaderClear(&mr);
      return terrno;
    }

1037 1038
    int32_t numOfCols = mr.me.stbEntry.schemaRow.nCols;

1039
    for (int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
1040
      (*rowLen) += mr.me.stbEntry.schemaRow.pSchema[i].bytes;
1041 1042 1043
    }
  } else if (mr.me.type == TSDB_NORMAL_TABLE) {
    int32_t numOfCols = mr.me.ntbEntry.schemaRow.nCols;
1044
    for (int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
1045
      (*rowLen) += mr.me.ntbEntry.schemaRow.pSchema[i].bytes;
1046 1047 1048 1049
    }
  }

  metaReaderClear(&mr);
H
Haojun Liao 已提交
1050
  return TSDB_CODE_SUCCESS;
1051 1052 1053 1054 1055 1056 1057 1058
}

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

  SBlockDistInfo* pBlockScanInfo = pOperator->info;
L
Liu Jicong 已提交
1059
  SExecTaskInfo*  pTaskInfo = pOperator->pTaskInfo;
1060 1061

  STableBlockDistInfo blockDistInfo = {.minRows = INT_MAX, .maxRows = INT_MIN};
1062 1063
  int32_t             code = doGetTableRowSize(pBlockScanInfo->readHandle.meta, pBlockScanInfo->uid,
                                               (int32_t*)&blockDistInfo.rowSize, GET_TASKID(pTaskInfo));
H
Haojun Liao 已提交
1064
  if (code != TSDB_CODE_SUCCESS) {
1065
    T_LONG_JMP(pTaskInfo->env, code);
H
Haojun Liao 已提交
1066
  }
1067 1068 1069

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

1071
  SSDataBlock* pBlock = pBlockScanInfo->pResBlock;
H
Haojun Liao 已提交
1072

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

1076
  int32_t len = tSerializeBlockDistInfo(NULL, 0, &blockDistInfo);
1077
  char*   p = taosMemoryCalloc(1, len + VARSTR_HEADER_SIZE);
1078 1079 1080 1081 1082
  tSerializeBlockDistInfo(varDataVal(p), len, &blockDistInfo);
  varDataSetLen(p, len);

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

1084
  pBlock->info.rows = 1;
H
Haojun Liao 已提交
1085 1086 1087 1088
  pOperator->status = OP_EXEC_DONE;
  return pBlock;
}

1089
static void destroyBlockDistScanOperatorInfo(void* param) {
1090
  SBlockDistInfo* pDistInfo = (SBlockDistInfo*)param;
1091
  blockDataDestroy(pDistInfo->pResBlock);
H
Hongze Cheng 已提交
1092
  tsdbReaderClose(pDistInfo->pHandle);
D
dapan1121 已提交
1093
  taosMemoryFreeClear(param);
1094 1095
}

1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119
static int32_t initTableblockDistQueryCond(uint64_t uid, SQueryTableDataCond* pCond) {
  memset(pCond, 0, sizeof(SQueryTableDataCond));

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

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

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

  return TSDB_CODE_SUCCESS;
}

5
54liuyao 已提交
1120 1121
SOperatorInfo* createDataBlockInfoScanOperator(SReadHandle* readHandle, SBlockDistScanPhysiNode* pBlockScanNode,
                                               SExecTaskInfo* pTaskInfo) {
1122
  SBlockDistInfo* pInfo = taosMemoryCalloc(1, sizeof(SBlockDistInfo));
1123
  SOperatorInfo*  pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
1124 1125 1126 1127 1128
  if (pInfo == NULL || pOperator == NULL) {
    pTaskInfo->code = TSDB_CODE_OUT_OF_MEMORY;
    goto _error;
  }

1129 1130 1131 1132 1133
  {
    SQueryTableDataCond cond = {0};

    int32_t code = initTableblockDistQueryCond(pBlockScanNode->suid, &cond);
    if (code != TSDB_CODE_SUCCESS) {
dengyihao's avatar
merge  
dengyihao 已提交
1134
      goto _error;
1135 1136 1137
    }

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

dengyihao's avatar
dengyihao 已提交
1141
    code = tsdbReaderOpen(readHandle->vnode, &cond, pList, num, &pInfo->pHandle, pTaskInfo->id.str);
1142
    cleanupQueryTableDataCond(&cond);
dengyihao's avatar
dengyihao 已提交
1143 1144 1145
    if (code != 0) {
      goto _error;
    }
1146 1147
  }

1148
  pInfo->readHandle = *readHandle;
1149
  pInfo->uid = pBlockScanNode->suid;
H
Haojun Liao 已提交
1150

1151
  pInfo->pResBlock = createResDataBlock(pBlockScanNode->node.pOutputDataBlockDesc);
H
Haojun Liao 已提交
1152
  blockDataEnsureCapacity(pInfo->pResBlock, 1);
1153

1154
  int32_t    numOfCols = 0;
1155
  SExprInfo* pExprInfo = createExprInfo(pBlockScanNode->pScanPseudoCols, NULL, &numOfCols);
1156
  int32_t    code = initExprSupp(&pOperator->exprSupp, pExprInfo, numOfCols);
1157 1158 1159
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
H
Haojun Liao 已提交
1160

L
Liu Jicong 已提交
1161 1162 1163 1164
  setOperatorInfo(pOperator, "DataBlockDistScanOperator", QUERY_NODE_PHYSICAL_PLAN_BLOCK_DIST_SCAN, false,
                  OP_NOT_OPENED, pInfo, pTaskInfo);
  pOperator->fpSet =
      createOperatorFpSet(operatorDummyOpenFn, doBlockInfoScan, NULL, destroyBlockDistScanOperatorInfo, NULL);
H
Haojun Liao 已提交
1165 1166
  return pOperator;

1167
_error:
H
Haojun Liao 已提交
1168 1169 1170 1171 1172
  taosMemoryFreeClear(pInfo);
  taosMemoryFreeClear(pOperator);
  return NULL;
}

1173
static FORCE_INLINE void doClearBufferedBlocks(SStreamScanInfo* pInfo) {
L
Liu Jicong 已提交
1174 1175
  taosArrayClear(pInfo->pBlockLists);
  pInfo->validBlockIndex = 0;
H
Haojun Liao 已提交
1176 1177
}

1178
static bool isSessionWindow(SStreamScanInfo* pInfo) {
H
Haojun Liao 已提交
1179
  return pInfo->windowSup.parentType == QUERY_NODE_PHYSICAL_PLAN_STREAM_SESSION;
5
54liuyao 已提交
1180 1181
}

1182
static bool isStateWindow(SStreamScanInfo* pInfo) {
1183
  return pInfo->windowSup.parentType == QUERY_NODE_PHYSICAL_PLAN_STREAM_STATE;
5
54liuyao 已提交
1184
}
5
54liuyao 已提交
1185

L
Liu Jicong 已提交
1186
static bool isIntervalWindow(SStreamScanInfo* pInfo) {
1187 1188 1189
  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 已提交
1190 1191 1192
}

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

1196 1197 1198 1199
static bool isSlidingWindow(SStreamScanInfo* pInfo) {
  return isIntervalWindow(pInfo) && pInfo->interval.interval != pInfo->interval.sliding;
}

1200
static void setGroupId(SStreamScanInfo* pInfo, SSDataBlock* pBlock, int32_t groupColIndex, int32_t rowIndex) {
1201 1202
  SColumnInfoData* pColInfo = taosArrayGet(pBlock->pDataBlock, groupColIndex);
  uint64_t*        groupCol = (uint64_t*)pColInfo->pData;
1203
  ASSERT(rowIndex < pBlock->info.rows);
1204
  pInfo->groupId = groupCol[rowIndex];
1205 1206
}

L
Liu Jicong 已提交
1207
void resetTableScanInfo(STableScanInfo* pTableScanInfo, STimeWindow* pWin) {
H
Haojun Liao 已提交
1208
  pTableScanInfo->base.cond.twindows = *pWin;
L
Liu Jicong 已提交
1209 1210
  pTableScanInfo->scanTimes = 0;
  pTableScanInfo->currentGroupId = -1;
H
Haojun Liao 已提交
1211 1212
  tsdbReaderClose(pTableScanInfo->base.dataReader);
  pTableScanInfo->base.dataReader = NULL;
1213 1214
}

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

1219
  STableScanInfo*     pTableScanInfo = pTableScanOp->info;
H
Haojun Liao 已提交
1220
  SQueryTableDataCond cond = pTableScanInfo->base.cond;
1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231

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

  SExecTaskInfo* pTaskInfo = pTableScanOp->pTaskInfo;

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

  STsdbReader* pReader = NULL;
H
Haojun Liao 已提交
1232
  int32_t      code = tsdbReaderOpen(pTableScanInfo->base.readHandle.vnode, &cond, &tblInfo, 1, (STsdbReader**)&pReader,
5
54liuyao 已提交
1233
                                     GET_TASKID(pTaskInfo));
1234 1235
  if (code != TSDB_CODE_SUCCESS) {
    terrno = code;
dengyihao's avatar
dengyihao 已提交
1236
    T_LONG_JMP(pTaskInfo->env, code);
1237 1238 1239 1240 1241
    return NULL;
  }

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

H
Haojun Liao 已提交
1244 1245
    int32_t rows = 0;
    tsdbRetrieveDataBlockInfo(pReader, &rows, &pBInfo->uid, &pBInfo->window);
1246

H
Haojun Liao 已提交
1247
    SArray* pCols = tsdbRetrieveDataBlock(pReader, NULL);
H
Haojun Liao 已提交
1248 1249
    blockDataEnsureCapacity(pBlock, rows);
    pBlock->info.rows = rows;
1250

H
Haojun Liao 已提交
1251 1252
    relocateColumnData(pBlock, pTableScanInfo->base.matchInfo.pList, pCols, true);
    doSetTagColumnData(&pTableScanInfo->base, pBlock, pTaskInfo, rows);
H
Haojun Liao 已提交
1253

H
Haojun Liao 已提交
1254
    pBlock->info.groupId = getTableGroupId(pTaskInfo->pTableInfoList, pBInfo->uid);
1255 1256 1257 1258
  }

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

  return pBlock->info.rows > 0 ? pBlock : NULL;
1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273
}

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 已提交
1274
static uint64_t getGroupIdByUid(SStreamScanInfo* pInfo, uint64_t uid) {
H
Haojun Liao 已提交
1275
  return getTableGroupId(pInfo->pTableScanOp->pTaskInfo->pTableInfoList, uid);
1276 1277
}

5
54liuyao 已提交
1278 1279 1280 1281 1282 1283 1284 1285
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 已提交
1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296
static bool prepareRangeScan(SStreamScanInfo* pInfo, SSDataBlock* pBlock, int32_t* pRowIndex) {
  if ((*pRowIndex) == pBlock->info.rows) {
    return false;
  }

  ASSERT(taosArrayGetSize(pBlock->pDataBlock) >= 3);
  SColumnInfoData* pStartTsCol = taosArrayGet(pBlock->pDataBlock, START_TS_COLUMN_INDEX);
  TSKEY*           startData = (TSKEY*)pStartTsCol->pData;
  SColumnInfoData* pEndTsCol = taosArrayGet(pBlock->pDataBlock, END_TS_COLUMN_INDEX);
  TSKEY*           endData = (TSKEY*)pEndTsCol->pData;
  STimeWindow      win = {.skey = startData[*pRowIndex], .ekey = endData[*pRowIndex]};
1297 1298 1299
  SColumnInfoData* pGpCol = taosArrayGet(pBlock->pDataBlock, GROUPID_COLUMN_INDEX);
  uint64_t*        gpData = (uint64_t*)pGpCol->pData;
  uint64_t         groupId = gpData[*pRowIndex];
1300 1301 1302 1303 1304 1305

  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 已提交
1306
  setGroupId(pInfo, pBlock, GROUPID_COLUMN_INDEX, *pRowIndex);
1307 1308 1309 1310
  if (isSlidingWindow(pInfo)) {
    pInfo->updateWin.skey = calStartData[*pRowIndex];
    pInfo->updateWin.ekey = calEndData[*pRowIndex];
  }
L
Liu Jicong 已提交
1311 1312 1313
  (*pRowIndex)++;

  for (; *pRowIndex < pBlock->info.rows; (*pRowIndex)++) {
1314
    if (win.skey == startData[*pRowIndex] && groupId == gpData[*pRowIndex]) {
L
Liu Jicong 已提交
1315 1316 1317
      win.ekey = TMAX(win.ekey, endData[*pRowIndex]);
      continue;
    }
1318
    if (win.skey == endData[*pRowIndex] && groupId == gpData[*pRowIndex]) {
L
Liu Jicong 已提交
1319 1320 1321
      win.skey = TMIN(win.skey, startData[*pRowIndex]);
      continue;
    }
1322 1323
    ASSERT(!(win.skey > startData[*pRowIndex] && win.ekey < endData[*pRowIndex]) ||
           !(isInTimeWindow(&win, startData[*pRowIndex], 0) || isInTimeWindow(&win, endData[*pRowIndex], 0)));
L
Liu Jicong 已提交
1324 1325 1326 1327
    break;
  }

  resetTableScanInfo(pInfo->pTableScanOp->info, &win);
1328
  pInfo->pTableScanOp->status = OP_OPENED;
L
Liu Jicong 已提交
1329 1330 1331
  return true;
}

5
54liuyao 已提交
1332
static STimeWindow getSlidingWindow(TSKEY* startTsCol, TSKEY* endTsCol, uint64_t* gpIdCol, SInterval* pInterval,
1333
                                    SDataBlockInfo* pDataBlockInfo, int32_t* pRowIndex, bool hasGroup) {
H
Haojun Liao 已提交
1334
  SResultRowInfo dumyInfo = {0};
5
54liuyao 已提交
1335
  dumyInfo.cur.pageId = -1;
1336
  STimeWindow win = getActiveTimeWindow(NULL, &dumyInfo, startTsCol[*pRowIndex], pInterval, TSDB_ORDER_ASC);
5
54liuyao 已提交
1337 1338
  STimeWindow endWin = win;
  STimeWindow preWin = win;
5
54liuyao 已提交
1339
  uint64_t    groupId = gpIdCol[*pRowIndex];
H
Haojun Liao 已提交
1340

5
54liuyao 已提交
1341
  while (1) {
1342 1343 1344
    if (hasGroup) {
      (*pRowIndex) += 1;
    } else {
5
54liuyao 已提交
1345 1346 1347 1348 1349 1350
      while ((groupId == gpIdCol[(*pRowIndex)] && startTsCol[*pRowIndex] < endWin.ekey)) {
        (*pRowIndex) += 1;
        if ((*pRowIndex) == pDataBlockInfo->rows) {
          break;
        }
      }
1351
    }
5
54liuyao 已提交
1352

5
54liuyao 已提交
1353 1354 1355
    do {
      preWin = endWin;
      getNextTimeWindow(pInterval, &endWin, TSDB_ORDER_ASC);
1356
    } while (endTsCol[(*pRowIndex) - 1] >= endWin.skey);
5
54liuyao 已提交
1357
    endWin = preWin;
5
54liuyao 已提交
1358
    if (win.ekey == endWin.ekey || (*pRowIndex) == pDataBlockInfo->rows || groupId != gpIdCol[*pRowIndex]) {
5
54liuyao 已提交
1359 1360 1361 1362 1363 1364
      win.ekey = endWin.ekey;
      return win;
    }
    win.ekey = endWin.ekey;
  }
}
5
54liuyao 已提交
1365

L
Liu Jicong 已提交
1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376
static SSDataBlock* doRangeScan(SStreamScanInfo* pInfo, SSDataBlock* pSDB, int32_t tsColIndex, int32_t* pRowIndex) {
  while (1) {
    SSDataBlock* pResult = NULL;
    pResult = doTableScan(pInfo->pTableScanOp);
    if (!pResult && prepareRangeScan(pInfo, pSDB, pRowIndex)) {
      // scan next window data
      pResult = doTableScan(pInfo->pTableScanOp);
    }
    if (!pResult) {
      blockDataCleanup(pSDB);
      *pRowIndex = 0;
5
54liuyao 已提交
1377
      pInfo->updateWin = (STimeWindow){.skey = INT64_MIN, .ekey = INT64_MAX};
H
Hongze Cheng 已提交
1378
      STableScanInfo* pTableScanInfo = pInfo->pTableScanOp->info;
H
Haojun Liao 已提交
1379 1380
      tsdbReaderClose(pTableScanInfo->base.dataReader);
      pTableScanInfo->base.dataReader = NULL;
1381 1382
      return NULL;
    }
L
Liu Jicong 已提交
1383

H
Haojun Liao 已提交
1384
    doFilter(pResult, pInfo->pTableScanOp->exprSupp.pFilterInfo, NULL);
1385 1386 1387 1388
    if (pResult->info.rows == 0) {
      continue;
    }

1389 1390 1391 1392 1393 1394 1395 1396
    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 已提交
1397 1398
            bool             isNull = colDataIsNull(pSrcCol, tmpBlock->info.rows, i, NULL);
            char*            pSrcData = colDataGetData(pSrcCol, i);
1399 1400 1401 1402 1403
            colDataAppend(pDestCol, pResult->info.rows, pSrcData, isNull);
          }
          pResult->info.rows++;
        }
      }
H
Haojun Liao 已提交
1404 1405 1406

      blockDataDestroy(tmpBlock);

1407 1408 1409 1410 1411
      if (pResult->info.rows > 0) {
        pResult->info.calWin = pInfo->updateWin;
        return pResult;
      }
    } else if (pResult->info.groupId == pInfo->groupId) {
5
54liuyao 已提交
1412
      pResult->info.calWin = pInfo->updateWin;
1413
      return pResult;
5
54liuyao 已提交
1414 1415
    }
  }
1416
}
1417

1418 1419 1420
static int32_t generateSessionScanRange(SStreamScanInfo* pInfo, SSDataBlock* pSrcBlock, SSDataBlock* pDestBlock) {
  if (pSrcBlock->info.rows == 0) {
    return TSDB_CODE_SUCCESS;
1421
  }
1422 1423
  blockDataCleanup(pDestBlock);
  int32_t code = blockDataEnsureCapacity(pDestBlock, pSrcBlock->info.rows);
1424
  if (code != TSDB_CODE_SUCCESS) {
1425
    return code;
L
Liu Jicong 已提交
1426
  }
1427 1428
  ASSERT(taosArrayGetSize(pSrcBlock->pDataBlock) >= 3);
  SColumnInfoData* pStartTsCol = taosArrayGet(pSrcBlock->pDataBlock, START_TS_COLUMN_INDEX);
L
Liu Jicong 已提交
1429
  TSKEY*           startData = (TSKEY*)pStartTsCol->pData;
1430
  SColumnInfoData* pEndTsCol = taosArrayGet(pSrcBlock->pDataBlock, END_TS_COLUMN_INDEX);
L
Liu Jicong 已提交
1431
  TSKEY*           endData = (TSKEY*)pEndTsCol->pData;
1432 1433
  SColumnInfoData* pUidCol = taosArrayGet(pSrcBlock->pDataBlock, UID_COLUMN_INDEX);
  uint64_t*        uidCol = (uint64_t*)pUidCol->pData;
L
Liu Jicong 已提交
1434

1435 1436
  SColumnInfoData* pDestStartCol = taosArrayGet(pDestBlock->pDataBlock, START_TS_COLUMN_INDEX);
  SColumnInfoData* pDestEndCol = taosArrayGet(pDestBlock->pDataBlock, END_TS_COLUMN_INDEX);
5
54liuyao 已提交
1437
  SColumnInfoData* pDestUidCol = taosArrayGet(pDestBlock->pDataBlock, UID_COLUMN_INDEX);
1438
  SColumnInfoData* pDestGpCol = taosArrayGet(pDestBlock->pDataBlock, GROUPID_COLUMN_INDEX);
5
54liuyao 已提交
1439 1440
  SColumnInfoData* pDestCalStartTsCol = taosArrayGet(pDestBlock->pDataBlock, CALCULATE_START_TS_COLUMN_INDEX);
  SColumnInfoData* pDestCalEndTsCol = taosArrayGet(pDestBlock->pDataBlock, CALCULATE_END_TS_COLUMN_INDEX);
L
Liu Jicong 已提交
1441
  int64_t          version = pSrcBlock->info.version - 1;
1442
  for (int32_t i = 0; i < pSrcBlock->info.rows; i++) {
1443
    uint64_t groupId = getGroupIdByData(pInfo, uidCol[i], startData[i], version);
L
Liu Jicong 已提交
1444
    // gap must be 0.
5
54liuyao 已提交
1445
    SSessionKey startWin = {0};
1446
    getCurSessionWindow(pInfo->windowSup.pStreamAggSup, startData[i], startData[i], groupId, &startWin);
5
54liuyao 已提交
1447
    if (IS_INVALID_SESSION_WIN_KEY(startWin)) {
L
Liu Jicong 已提交
1448 1449 1450
      // window has been closed.
      continue;
    }
5
54liuyao 已提交
1451 1452 1453 1454 1455 1456
    SSessionKey endWin = {0};
    getCurSessionWindow(pInfo->windowSup.pStreamAggSup, endData[i], endData[i], groupId, &endWin);
    ASSERT(!IS_INVALID_SESSION_WIN_KEY(endWin));
    colDataAppend(pDestStartCol, i, (const char*)&startWin.win.skey, false);
    colDataAppend(pDestEndCol, i, (const char*)&endWin.win.ekey, false);

5
54liuyao 已提交
1457
    colDataAppendNULL(pDestUidCol, i);
L
Liu Jicong 已提交
1458
    colDataAppend(pDestGpCol, i, (const char*)&groupId, false);
5
54liuyao 已提交
1459 1460
    colDataAppendNULL(pDestCalStartTsCol, i);
    colDataAppendNULL(pDestCalEndTsCol, i);
1461
    pDestBlock->info.rows++;
L
Liu Jicong 已提交
1462
  }
1463
  return TSDB_CODE_SUCCESS;
L
Liu Jicong 已提交
1464
}
1465 1466 1467 1468 1469 1470

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;
1471
  }
5
54liuyao 已提交
1472
  int32_t code = blockDataEnsureCapacity(pDestBlock, rows);
1473 1474 1475 1476
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

1477 1478
  SColumnInfoData* pSrcStartTsCol = (SColumnInfoData*)taosArrayGet(pSrcBlock->pDataBlock, START_TS_COLUMN_INDEX);
  SColumnInfoData* pSrcEndTsCol = (SColumnInfoData*)taosArrayGet(pSrcBlock->pDataBlock, END_TS_COLUMN_INDEX);
1479 1480 1481 1482
  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;
1483 1484 1485
  ASSERT(pSrcStartTsCol->info.type == TSDB_DATA_TYPE_TIMESTAMP);
  TSKEY*           srcStartTsCol = (TSKEY*)pSrcStartTsCol->pData;
  TSKEY*           srcEndTsCol = (TSKEY*)pSrcEndTsCol->pData;
1486 1487
  SColumnInfoData* pStartTsCol = taosArrayGet(pDestBlock->pDataBlock, START_TS_COLUMN_INDEX);
  SColumnInfoData* pEndTsCol = taosArrayGet(pDestBlock->pDataBlock, END_TS_COLUMN_INDEX);
1488
  SColumnInfoData* pDeUidCol = taosArrayGet(pDestBlock->pDataBlock, UID_COLUMN_INDEX);
1489 1490 1491
  SColumnInfoData* pGpCol = taosArrayGet(pDestBlock->pDataBlock, GROUPID_COLUMN_INDEX);
  SColumnInfoData* pCalStartTsCol = taosArrayGet(pDestBlock->pDataBlock, CALCULATE_START_TS_COLUMN_INDEX);
  SColumnInfoData* pCalEndTsCol = taosArrayGet(pDestBlock->pDataBlock, CALCULATE_END_TS_COLUMN_INDEX);
L
Liu Jicong 已提交
1492
  int64_t          version = pSrcBlock->info.version - 1;
1493
  for (int32_t i = 0; i < rows;) {
1494
    uint64_t srcUid = srcUidData[i];
5
54liuyao 已提交
1495 1496 1497 1498 1499
    uint64_t groupId = srcGp[i];
    if (groupId == 0) {
      groupId = getGroupIdByData(pInfo, srcUid, srcStartTsCol[i], version);
    }
    TSKEY calStartTs = srcStartTsCol[i];
1500
    colDataAppend(pCalStartTsCol, pDestBlock->info.rows, (const char*)(&calStartTs), false);
5
54liuyao 已提交
1501
    STimeWindow win = getSlidingWindow(srcStartTsCol, srcEndTsCol, srcGp, &pInfo->interval, &pSrcBlock->info, &i,
1502 1503
                                       pInfo->partitionSup.needCalc);
    TSKEY       calEndTs = srcStartTsCol[i - 1];
1504 1505
    colDataAppend(pCalEndTsCol, pDestBlock->info.rows, (const char*)(&calEndTs), false);
    colDataAppend(pDeUidCol, pDestBlock->info.rows, (const char*)(&srcUid), false);
1506 1507 1508 1509
    colDataAppend(pStartTsCol, pDestBlock->info.rows, (const char*)(&win.skey), false);
    colDataAppend(pEndTsCol, pDestBlock->info.rows, (const char*)(&win.ekey), false);
    colDataAppend(pGpCol, pDestBlock->info.rows, (const char*)(&groupId), false);
    pDestBlock->info.rows++;
5
54liuyao 已提交
1510
  }
1511 1512
  return TSDB_CODE_SUCCESS;
}
1513

1514
static int32_t generateDeleteResultBlock(SStreamScanInfo* pInfo, SSDataBlock* pSrcBlock, SSDataBlock* pDestBlock) {
5
54liuyao 已提交
1515 1516 1517
  blockDataCleanup(pDestBlock);
  int32_t rows = pSrcBlock->info.rows;
  if (rows == 0) {
1518 1519
    return TSDB_CODE_SUCCESS;
  }
5
54liuyao 已提交
1520
  int32_t code = blockDataEnsureCapacity(pDestBlock, rows);
1521 1522 1523 1524
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

5
54liuyao 已提交
1525 1526 1527 1528 1529 1530 1531 1532 1533 1534
  SColumnInfoData* pSrcStartTsCol = (SColumnInfoData*)taosArrayGet(pSrcBlock->pDataBlock, START_TS_COLUMN_INDEX);
  SColumnInfoData* pSrcEndTsCol = (SColumnInfoData*)taosArrayGet(pSrcBlock->pDataBlock, END_TS_COLUMN_INDEX);
  SColumnInfoData* pSrcUidCol = taosArrayGet(pSrcBlock->pDataBlock, UID_COLUMN_INDEX);
  uint64_t*        srcUidData = (uint64_t*)pSrcUidCol->pData;
  SColumnInfoData* pSrcGpCol = taosArrayGet(pSrcBlock->pDataBlock, GROUPID_COLUMN_INDEX);
  uint64_t*        srcGp = (uint64_t*)pSrcGpCol->pData;
  ASSERT(pSrcStartTsCol->info.type == TSDB_DATA_TYPE_TIMESTAMP);
  TSKEY*  srcStartTsCol = (TSKEY*)pSrcStartTsCol->pData;
  TSKEY*  srcEndTsCol = (TSKEY*)pSrcEndTsCol->pData;
  int64_t version = pSrcBlock->info.version - 1;
1535
  for (int32_t i = 0; i < pSrcBlock->info.rows; i++) {
5
54liuyao 已提交
1536 1537
    uint64_t srcUid = srcUidData[i];
    uint64_t groupId = srcGp[i];
L
Liu Jicong 已提交
1538
    char*    tbname[VARSTR_HEADER_SIZE + TSDB_TABLE_NAME_LEN] = {0};
5
54liuyao 已提交
1539 1540 1541
    if (groupId == 0) {
      groupId = getGroupIdByData(pInfo, srcUid, srcStartTsCol[i], version);
    }
L
Liu Jicong 已提交
1542
    if (pInfo->tbnameCalSup.pExprInfo) {
1543 1544 1545
      void* parTbname = NULL;
      streamStateGetParName(pInfo->pStreamScanOp->pTaskInfo->streamInfo.pState, groupId, &parTbname);

L
Liu Jicong 已提交
1546 1547 1548 1549 1550
      memcpy(varDataVal(tbname), parTbname, TSDB_TABLE_NAME_LEN);
      varDataSetLen(tbname, strlen(varDataVal(tbname)));
    }
    appendOneRowToStreamSpecialBlock(pDestBlock, srcStartTsCol + i, srcEndTsCol + i, srcUidData + i, &groupId,
                                     tbname[0] == 0 ? NULL : tbname);
1551 1552 1553 1554
  }
  return TSDB_CODE_SUCCESS;
}

1555 1556 1557 1558
static int32_t generateScanRange(SStreamScanInfo* pInfo, SSDataBlock* pSrcBlock, SSDataBlock* pDestBlock) {
  int32_t code = TSDB_CODE_SUCCESS;
  if (isIntervalWindow(pInfo)) {
    code = generateIntervalScanRange(pInfo, pSrcBlock, pDestBlock);
1559
  } else if (isSessionWindow(pInfo) || isStateWindow(pInfo)) {
1560
    code = generateSessionScanRange(pInfo, pSrcBlock, pDestBlock);
5
54liuyao 已提交
1561 1562
  } else {
    code = generateDeleteResultBlock(pInfo, pSrcBlock, pDestBlock);
1563
  }
1564
  pDestBlock->info.type = STREAM_CLEAR;
1565
  pDestBlock->info.version = pSrcBlock->info.version;
1566 1567 1568 1569
  blockDataUpdateTsWindow(pDestBlock, 0);
  return code;
}

L
Liu Jicong 已提交
1570 1571 1572 1573 1574 1575 1576 1577 1578
static void calBlockTag(SExprSupp* pTagCalSup, SSDataBlock* pBlock, SSDataBlock* pResBlock) {
  if (pTagCalSup == NULL || pTagCalSup->numOfExprs == 0) return;
  if (pBlock == NULL || pBlock->info.rows == 0) return;

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

  blockDataEnsureCapacity(pResBlock, 1);

H
Haojun Liao 已提交
1579
  projectApplyFunctions(pTagCalSup->pExprInfo, pResBlock, pSrcBlock, pTagCalSup->pCtx, 1, NULL);
L
Liu Jicong 已提交
1580 1581 1582
  ASSERT(pResBlock->info.rows == 1);

  // build tagArray
1583 1584 1585 1586 1587
  /*SArray* tagArray = taosArrayInit(0, sizeof(void*));*/
  /*STagVal tagVal = {*/
  /*.cid = 0,*/
  /*.type = 0,*/
  /*};*/
L
Liu Jicong 已提交
1588 1589 1590 1591 1592 1593
  // build STag
  // set STag

  blockDataDestroy(pSrcBlock);
}

L
Liu Jicong 已提交
1594
void calBlockTbName(SStreamScanInfo* pInfo, SSDataBlock* pBlock) {
1595 1596
  SExprSupp*    pTbNameCalSup = &pInfo->tbnameCalSup;
  SStreamState* pState = pInfo->pStreamScanOp->pTaskInfo->streamInfo.pState;
L
Liu Jicong 已提交
1597 1598
  if (pTbNameCalSup == NULL || pTbNameCalSup->numOfExprs == 0) return;
  if (pBlock == NULL || pBlock->info.rows == 0) return;
1599 1600 1601 1602 1603 1604

  void* tbname = NULL;
  if (streamStateGetParName(pInfo->pStreamScanOp->pTaskInfo->streamInfo.pState, pBlock->info.groupId, &tbname) < 0) {
    pBlock->info.parTbName[0] = 0;
  } else {
    memcpy(pBlock->info.parTbName, tbname, TSDB_TABLE_NAME_LEN);
L
Liu Jicong 已提交
1605
  }
1606
  tdbFree(tbname);
L
Liu Jicong 已提交
1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625

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

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

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

  void* pData = colDataGetData(pCol, 0);
  // TODO check tbname validation
  if (pData != (void*)-1 && pData != NULL) {
1626
    memset(pBlock->info.parTbName, 0, TSDB_TABLE_NAME_LEN);
L
Liu Jicong 已提交
1627
    int32_t len = TMIN(varDataLen(pData), TSDB_TABLE_NAME_LEN - 1);
1628 1629
    memcpy(pBlock->info.parTbName, varDataVal(pData), len);
    /*pBlock->info.parTbName[len + 1] = 0;*/
L
Liu Jicong 已提交
1630 1631 1632 1633
  } else {
    pBlock->info.parTbName[0] = 0;
  }

1634 1635
  if (pBlock->info.groupId && pBlock->info.parTbName[0]) {
    streamStatePutParName(pState, pBlock->info.groupId, pBlock->info.parTbName);
L
Liu Jicong 已提交
1636 1637
  }

L
Liu Jicong 已提交
1638 1639 1640 1641
  blockDataDestroy(pSrcBlock);
  blockDataDestroy(pResBlock);
}

1642 1643
void appendOneRowToStreamSpecialBlock(SSDataBlock* pBlock, TSKEY* pStartTs, TSKEY* pEndTs, uint64_t* pUid,
                                      uint64_t* pGp, void* pTbName) {
1644 1645
  SColumnInfoData* pStartTsCol = taosArrayGet(pBlock->pDataBlock, START_TS_COLUMN_INDEX);
  SColumnInfoData* pEndTsCol = taosArrayGet(pBlock->pDataBlock, END_TS_COLUMN_INDEX);
1646 1647
  SColumnInfoData* pUidCol = taosArrayGet(pBlock->pDataBlock, UID_COLUMN_INDEX);
  SColumnInfoData* pGpCol = taosArrayGet(pBlock->pDataBlock, GROUPID_COLUMN_INDEX);
1648 1649
  SColumnInfoData* pCalStartCol = taosArrayGet(pBlock->pDataBlock, CALCULATE_START_TS_COLUMN_INDEX);
  SColumnInfoData* pCalEndCol = taosArrayGet(pBlock->pDataBlock, CALCULATE_END_TS_COLUMN_INDEX);
1650
  SColumnInfoData* pTableCol = taosArrayGet(pBlock->pDataBlock, TABLE_NAME_COLUMN_INDEX);
1651 1652
  colDataAppend(pStartTsCol, pBlock->info.rows, (const char*)pStartTs, false);
  colDataAppend(pEndTsCol, pBlock->info.rows, (const char*)pEndTs, false);
1653 1654
  colDataAppend(pUidCol, pBlock->info.rows, (const char*)pUid, false);
  colDataAppend(pGpCol, pBlock->info.rows, (const char*)pGp, false);
1655 1656
  colDataAppend(pCalStartCol, pBlock->info.rows, (const char*)pStartTs, false);
  colDataAppend(pCalEndCol, pBlock->info.rows, (const char*)pEndTs, false);
1657
  colDataAppend(pTableCol, pBlock->info.rows, (const char*)pTbName, pTbName == NULL);
1658
  pBlock->info.rows++;
5
54liuyao 已提交
1659 1660
}

1661
static void checkUpdateData(SStreamScanInfo* pInfo, bool invertible, SSDataBlock* pBlock, bool out) {
1662 1663
  if (out) {
    blockDataCleanup(pInfo->pUpdateDataRes);
5
54liuyao 已提交
1664
    blockDataEnsureCapacity(pInfo->pUpdateDataRes, pBlock->info.rows * 2);
1665
  }
1666 1667
  SColumnInfoData* pColDataInfo = taosArrayGet(pBlock->pDataBlock, pInfo->primaryTsIndex);
  ASSERT(pColDataInfo->info.type == TSDB_DATA_TYPE_TIMESTAMP);
5
54liuyao 已提交
1668
  TSKEY* tsCol = (TSKEY*)pColDataInfo->pData;
L
Liu Jicong 已提交
1669
  bool   tableInserted = updateInfoIsTableInserted(pInfo->pUpdateInfo, pBlock->info.uid);
1670
  for (int32_t rowId = 0; rowId < pBlock->info.rows; rowId++) {
5
54liuyao 已提交
1671 1672
    SResultRowInfo dumyInfo;
    dumyInfo.cur.pageId = -1;
L
Liu Jicong 已提交
1673
    bool        isClosed = false;
5
54liuyao 已提交
1674
    STimeWindow win = {.skey = INT64_MIN, .ekey = INT64_MAX};
L
Liu Jicong 已提交
1675
    if (tableInserted && isOverdue(tsCol[rowId], &pInfo->twAggSup)) {
5
54liuyao 已提交
1676 1677 1678
      win = getActiveTimeWindow(NULL, &dumyInfo, tsCol[rowId], &pInfo->interval, TSDB_ORDER_ASC);
      isClosed = isCloseWindow(&win, &pInfo->twAggSup);
    }
5
54liuyao 已提交
1679 1680
    // must check update info first.
    bool update = updateInfoIsUpdated(pInfo->pUpdateInfo, pBlock->info.uid, tsCol[rowId]);
L
Liu Jicong 已提交
1681
    bool closedWin = isClosed && isSignleIntervalWindow(pInfo) &&
1682 1683
                     isDeletedStreamWindow(&win, pBlock->info.groupId,
                                           pInfo->pTableScanOp->pTaskInfo->streamInfo.pState, &pInfo->twAggSup);
L
Liu Jicong 已提交
1684
    if ((update || closedWin) && out) {
L
Liu Jicong 已提交
1685
      qDebug("stream update check not pass, update %d, closedWin %d", update, closedWin);
5
54liuyao 已提交
1686
      uint64_t gpId = 0;
1687 1688
      appendOneRowToStreamSpecialBlock(pInfo->pUpdateDataRes, tsCol + rowId, tsCol + rowId, &pBlock->info.uid, &gpId,
                                       NULL);
5
54liuyao 已提交
1689 1690
      if (closedWin && pInfo->partitionSup.needCalc) {
        gpId = calGroupIdByData(&pInfo->partitionSup, pInfo->pPartScalarSup, pBlock, rowId);
1691 1692
        appendOneRowToStreamSpecialBlock(pInfo->pUpdateDataRes, tsCol + rowId, tsCol + rowId, &pBlock->info.uid, &gpId,
                                         NULL);
5
54liuyao 已提交
1693
      }
1694 1695
    }
  }
1696 1697
  if (out && pInfo->pUpdateDataRes->info.rows > 0) {
    pInfo->pUpdateDataRes->info.version = pBlock->info.version;
1698
    blockDataUpdateTsWindow(pInfo->pUpdateDataRes, 0);
1699
    pInfo->pUpdateDataRes->info.type = pInfo->partitionSup.needCalc ? STREAM_DELETE_DATA : STREAM_CLEAR;
5
54liuyao 已提交
1700 1701
  }
}
L
Liu Jicong 已提交
1702

1703
static int32_t setBlockIntoRes(SStreamScanInfo* pInfo, const SSDataBlock* pBlock, bool filter) {
L
Liu Jicong 已提交
1704 1705
  SDataBlockInfo* pBlockInfo = &pInfo->pRes->info;
  SOperatorInfo*  pOperator = pInfo->pStreamScanOp;
L
Liu Jicong 已提交
1706
  SExecTaskInfo*  pTaskInfo = pOperator->pTaskInfo;
L
Liu Jicong 已提交
1707

1708 1709
  blockDataEnsureCapacity(pInfo->pRes, pBlock->info.rows);

L
Liu Jicong 已提交
1710 1711 1712
  pInfo->pRes->info.rows = pBlock->info.rows;
  pInfo->pRes->info.uid = pBlock->info.uid;
  pInfo->pRes->info.type = STREAM_NORMAL;
1713
  pInfo->pRes->info.version = pBlock->info.version;
L
Liu Jicong 已提交
1714

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

  // todo extract method
H
Haojun Liao 已提交
1718 1719 1720
  for (int32_t i = 0; i < taosArrayGetSize(pInfo->matchInfo.pList); ++i) {
    SColMatchItem* pColMatchInfo = taosArrayGet(pInfo->matchInfo.pList, i);
    if (!pColMatchInfo->needOutput) {
L
Liu Jicong 已提交
1721 1722 1723 1724 1725 1726 1727
      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 已提交
1728
        SColumnInfoData* pDst = taosArrayGet(pInfo->pRes->pDataBlock, pColMatchInfo->dstSlotId);
1729
        colDataAssign(pDst, pResCol, pBlock->info.rows, &pInfo->pRes->info);
L
Liu Jicong 已提交
1730 1731 1732 1733 1734 1735 1736
        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 已提交
1737
      SColumnInfoData* pDst = taosArrayGet(pInfo->pRes->pDataBlock, pColMatchInfo->dstSlotId);
L
Liu Jicong 已提交
1738 1739 1740 1741 1742 1743
      colDataAppendNNULL(pDst, 0, pBlockInfo->rows);
    }
  }

  // currently only the tbname pseudo column
  if (pInfo->numOfPseudoExpr > 0) {
L
Liu Jicong 已提交
1744
    int32_t code = addTagPseudoColumnData(&pInfo->readHandle, pInfo->pPseudoExpr, pInfo->numOfPseudoExpr, pInfo->pRes,
1745
                                          pInfo->pRes->info.rows, GET_TASKID(pTaskInfo), NULL);
H
Haojun Liao 已提交
1746
    if (code != TSDB_CODE_SUCCESS) {
L
Liu Jicong 已提交
1747
      blockDataFreeRes((SSDataBlock*)pBlock);
1748
      T_LONG_JMP(pTaskInfo->env, code);
H
Haojun Liao 已提交
1749
    }
L
Liu Jicong 已提交
1750 1751
  }

1752
  if (filter) {
H
Haojun Liao 已提交
1753
    doFilter(pInfo->pRes, pOperator->exprSupp.pFilterInfo, NULL);
1754
  }
1755

L
Liu Jicong 已提交
1756
  blockDataUpdateTsWindow(pInfo->pRes, pInfo->primaryTsIndex);
L
Liu Jicong 已提交
1757
  blockDataFreeRes((SSDataBlock*)pBlock);
L
Liu Jicong 已提交
1758

L
Liu Jicong 已提交
1759
  calBlockTbName(pInfo, pInfo->pRes);
L
Liu Jicong 已提交
1760 1761
  return 0;
}
5
54liuyao 已提交
1762

L
Liu Jicong 已提交
1763
static SSDataBlock* doQueueScan(SOperatorInfo* pOperator) {
1764 1765
  SExecTaskInfo*   pTaskInfo = pOperator->pTaskInfo;
  SStreamScanInfo* pInfo = pOperator->info;
H
Haojun Liao 已提交
1766

L
Liu Jicong 已提交
1767
  qDebug("queue scan called");
L
Liu Jicong 已提交
1768 1769 1770 1771 1772 1773 1774 1775

  if (pTaskInfo->streamInfo.pReq != NULL) {
    if (pInfo->tqReader->pMsg == NULL) {
      pInfo->tqReader->pMsg = pTaskInfo->streamInfo.pReq;
      const SSubmitReq* pSubmit = pInfo->tqReader->pMsg;
      if (tqReaderSetDataMsg(pInfo->tqReader, pSubmit, 0) < 0) {
        qError("submit msg messed up when initing stream submit block %p", pSubmit);
        pInfo->tqReader->pMsg = NULL;
L
Liu Jicong 已提交
1776
        pTaskInfo->streamInfo.pReq = NULL;
L
Liu Jicong 已提交
1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792
        ASSERT(0);
      }
    }

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

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

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

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

1793
      setBlockIntoRes(pInfo, &block, true);
L
Liu Jicong 已提交
1794 1795 1796 1797 1798 1799 1800 1801

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

    pInfo->tqReader->pMsg = NULL;
    pTaskInfo->streamInfo.pReq = NULL;
L
Liu Jicong 已提交
1802
    return NULL;
L
Liu Jicong 已提交
1803 1804
  }

L
Liu Jicong 已提交
1805 1806 1807
  if (pTaskInfo->streamInfo.prepareStatus.type == TMQ_OFFSET__SNAPSHOT_DATA) {
    SSDataBlock* pResult = doTableScan(pInfo->pTableScanOp);
    if (pResult && pResult->info.rows > 0) {
L
Liu Jicong 已提交
1808
      qDebug("queue scan tsdb return %d rows", pResult->info.rows);
1809
      pTaskInfo->streamInfo.returned = 1;
L
Liu Jicong 已提交
1810 1811
      return pResult;
    } else {
1812 1813
      if (!pTaskInfo->streamInfo.returned) {
        STableScanInfo* pTSInfo = pInfo->pTableScanOp->info;
H
Haojun Liao 已提交
1814 1815
        tsdbReaderClose(pTSInfo->base.dataReader);
        pTSInfo->base.dataReader = NULL;
1816
        tqOffsetResetToLog(&pTaskInfo->streamInfo.prepareStatus, pTaskInfo->streamInfo.snapshotVer);
1817
        qDebug("queue scan tsdb over, switch to wal ver %" PRId64 "", pTaskInfo->streamInfo.snapshotVer + 1);
1818
        if (tqSeekVer(pInfo->tqReader, pTaskInfo->streamInfo.snapshotVer + 1) < 0) {
1819
          tqOffsetResetToLog(&pTaskInfo->streamInfo.lastStatus, pTaskInfo->streamInfo.snapshotVer);
1820 1821 1822 1823
          return NULL;
        }
        ASSERT(pInfo->tqReader->pWalReader->curVersion == pTaskInfo->streamInfo.snapshotVer + 1);
      } else {
L
Liu Jicong 已提交
1824 1825
        return NULL;
      }
1826 1827 1828
    }
  }

L
Liu Jicong 已提交
1829 1830 1831 1832 1833 1834
  if (pTaskInfo->streamInfo.prepareStatus.type == TMQ_OFFSET__LOG) {
    while (1) {
      SFetchRet ret = {0};
      tqNextBlock(pInfo->tqReader, &ret);
      if (ret.fetchType == FETCH_TYPE__DATA) {
        blockDataCleanup(pInfo->pRes);
1835
        if (setBlockIntoRes(pInfo, &ret.data, true) < 0) {
L
Liu Jicong 已提交
1836 1837 1838
          ASSERT(0);
        }
        if (pInfo->pRes->info.rows > 0) {
L
Liu Jicong 已提交
1839
          pOperator->status = OP_EXEC_RECV;
L
Liu Jicong 已提交
1840
          qDebug("queue scan log return %d rows", pInfo->pRes->info.rows);
L
Liu Jicong 已提交
1841 1842 1843 1844
          return pInfo->pRes;
        }
      } else if (ret.fetchType == FETCH_TYPE__META) {
        ASSERT(0);
L
Liu Jicong 已提交
1845 1846 1847
        //        pTaskInfo->streamInfo.lastStatus = ret.offset;
        //        pTaskInfo->streamInfo.metaBlk = ret.meta;
        //        return NULL;
L
Liu Jicong 已提交
1848 1849
      } else if (ret.fetchType == FETCH_TYPE__NONE ||
                 (ret.fetchType == FETCH_TYPE__SEP && pOperator->status == OP_EXEC_RECV)) {
L
Liu Jicong 已提交
1850
        pTaskInfo->streamInfo.lastStatus = ret.offset;
1851 1852 1853 1854
        ASSERT(pTaskInfo->streamInfo.lastStatus.version >= pTaskInfo->streamInfo.prepareStatus.version);
        ASSERT(pTaskInfo->streamInfo.lastStatus.version + 1 == pInfo->tqReader->pWalReader->curVersion);
        char formatBuf[80];
        tFormatOffset(formatBuf, 80, &ret.offset);
L
Liu Jicong 已提交
1855
        qDebug("queue scan log return null, offset %s", formatBuf);
L
Liu Jicong 已提交
1856
        pOperator->status = OP_OPENED;
L
Liu Jicong 已提交
1857 1858 1859
        return NULL;
      }
    }
L
Liu Jicong 已提交
1860
#if 0
1861
    } else if (pTaskInfo->streamInfo.prepareStatus.type == TMQ_OFFSET__SNAPSHOT_DATA) {
L
Liu Jicong 已提交
1862
    SSDataBlock* pResult = doTableScan(pInfo->pTableScanOp);
L
Liu Jicong 已提交
1863 1864 1865 1866 1867 1868
    if (pResult && pResult->info.rows > 0) {
      qDebug("stream scan tsdb return %d rows", pResult->info.rows);
      return pResult;
    }
    qDebug("stream scan tsdb return null");
    return NULL;
L
Liu Jicong 已提交
1869
#endif
L
Liu Jicong 已提交
1870 1871 1872
  } else {
    ASSERT(0);
    return NULL;
H
Haojun Liao 已提交
1873
  }
L
Liu Jicong 已提交
1874 1875
}

L
Liu Jicong 已提交
1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903
static int32_t filterDelBlockByUid(SSDataBlock* pDst, const SSDataBlock* pSrc, SStreamScanInfo* pInfo) {
  STqReader* pReader = pInfo->tqReader;
  int32_t    rows = pSrc->info.rows;
  blockDataEnsureCapacity(pDst, rows);

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

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

      colDataAppendNULL(taosArrayGet(pDst->pDataBlock, GROUPID_COLUMN_INDEX), j);
      colDataAppendNULL(taosArrayGet(pDst->pDataBlock, CALCULATE_START_TS_COLUMN_INDEX), j);
      colDataAppendNULL(taosArrayGet(pDst->pDataBlock, CALCULATE_END_TS_COLUMN_INDEX), j);
      j++;
    }
  }
L
Liu Jicong 已提交
1904
  uint32_t cap = pDst->info.capacity;
L
Liu Jicong 已提交
1905 1906
  pDst->info = pSrc->info;
  pDst->info.rows = j;
L
Liu Jicong 已提交
1907
  pDst->info.capacity = cap;
L
Liu Jicong 已提交
1908 1909 1910 1911

  return 0;
}

5
54liuyao 已提交
1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935
// for partition by tag
static void setBlockGroupIdByUid(SStreamScanInfo* pInfo, SSDataBlock* pBlock) {
  SColumnInfoData* pStartTsCol = taosArrayGet(pBlock->pDataBlock, START_TS_COLUMN_INDEX);
  TSKEY*           startTsCol = (TSKEY*)pStartTsCol->pData;
  SColumnInfoData* pGpCol = taosArrayGet(pBlock->pDataBlock, GROUPID_COLUMN_INDEX);
  uint64_t*        gpCol = (uint64_t*)pGpCol->pData;
  SColumnInfoData* pUidCol = taosArrayGet(pBlock->pDataBlock, UID_COLUMN_INDEX);
  uint64_t*        uidCol = (uint64_t*)pUidCol->pData;
  int32_t          rows = pBlock->info.rows;
  if (!pInfo->partitionSup.needCalc) {
    for (int32_t i = 0; i < rows; i++) {
      uint64_t groupId = getGroupIdByUid(pInfo, uidCol[i]);
      colDataAppend(pGpCol, i, (const char*)&groupId, false);
    }
  } else {
    // SSDataBlock* pPreRes = readPreVersionData(pInfo->pTableScanOp, uidCol[i], startTsCol, ts, maxVersion);
    // if (!pPreRes || pPreRes->info.rows == 0) {
    //   return 0;
    // }
    // ASSERT(pPreRes->info.rows == 1);
    // return calGroupIdByData(&pInfo->partitionSup, pInfo->pPartScalarSup, pPreRes, 0);
  }
}

L
Liu Jicong 已提交
1936 1937 1938 1939 1940
static SSDataBlock* doStreamScan(SOperatorInfo* pOperator) {
  // NOTE: this operator does never check if current status is done or not
  SExecTaskInfo*   pTaskInfo = pOperator->pTaskInfo;
  SStreamScanInfo* pInfo = pOperator->info;

L
Liu Jicong 已提交
1941
  qDebug("stream scan called");
L
Liu Jicong 已提交
1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974
#if 0
  SStreamState* pState = pTaskInfo->streamInfo.pState;
  if (pState) {
    printf(">>>>>>>> stream write backend\n");
    SWinKey key = {
        .ts = 1,
        .groupId = 2,
    };
    char tmp[100] = "abcdefg1";
    if (streamStatePut(pState, &key, &tmp, strlen(tmp) + 1) < 0) {
      ASSERT(0);
    }

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

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

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

1978 1979
  if (pTaskInfo->streamInfo.recoverStep == STREAM_RECOVER_STEP__PREPARE1 ||
      pTaskInfo->streamInfo.recoverStep == STREAM_RECOVER_STEP__PREPARE2) {
L
Liu Jicong 已提交
1980
    STableScanInfo* pTSInfo = pInfo->pTableScanOp->info;
H
Haojun Liao 已提交
1981
    memcpy(&pTSInfo->base.cond, &pTaskInfo->streamInfo.tableCond, sizeof(SQueryTableDataCond));
1982
    if (pTaskInfo->streamInfo.recoverStep == STREAM_RECOVER_STEP__PREPARE1) {
H
Haojun Liao 已提交
1983 1984 1985 1986
      pTSInfo->base.cond.startVersion = 0;
      pTSInfo->base.cond.endVersion = pTaskInfo->streamInfo.fillHistoryVer1;
      qDebug("stream recover step 1, from %" PRId64 " to %" PRId64, pTSInfo->base.cond.startVersion,
             pTSInfo->base.cond.endVersion);
1987
    } else {
H
Haojun Liao 已提交
1988 1989 1990 1991
      pTSInfo->base.cond.startVersion = pTaskInfo->streamInfo.fillHistoryVer1 + 1;
      pTSInfo->base.cond.endVersion = pTaskInfo->streamInfo.fillHistoryVer2;
      qDebug("stream recover step 2, from %" PRId64 " to %" PRId64, pTSInfo->base.cond.startVersion,
             pTSInfo->base.cond.endVersion);
1992
    }
L
Liu Jicong 已提交
1993 1994

    /*resetTableScanInfo(pTSInfo, pWin);*/
H
Haojun Liao 已提交
1995 1996
    tsdbReaderClose(pTSInfo->base.dataReader);
    pTSInfo->base.dataReader = NULL;
L
Liu Jicong 已提交
1997

L
Liu Jicong 已提交
1998 1999 2000 2001 2002 2003 2004 2005
    pTSInfo->scanTimes = 0;
    pTSInfo->currentGroupId = -1;
    pTaskInfo->streamInfo.recoverStep = STREAM_RECOVER_STEP__SCAN;
  }

  if (pTaskInfo->streamInfo.recoverStep == STREAM_RECOVER_STEP__SCAN) {
    SSDataBlock* pBlock = doTableScan(pInfo->pTableScanOp);
    if (pBlock != NULL) {
L
Liu Jicong 已提交
2006
      calBlockTbName(pInfo, pBlock);
2007
      if (pInfo->pUpdateInfo) {
L
Liu Jicong 已提交
2008 2009
        TSKEY maxTs = updateInfoFillBlockData(pInfo->pUpdateInfo, pBlock, pInfo->primaryTsIndex);
        pInfo->twAggSup.maxTs = TMAX(pInfo->twAggSup.maxTs, maxTs);
2010
      }
2011
      qDebug("stream recover scan get block, rows %d", pBlock->info.rows);
L
Liu Jicong 已提交
2012
      printDataBlock(pBlock, "scan recover");
L
Liu Jicong 已提交
2013 2014 2015
      return pBlock;
    }
    pTaskInfo->streamInfo.recoverStep = STREAM_RECOVER_STEP__NONE;
L
Liu Jicong 已提交
2016
    STableScanInfo* pTSInfo = pInfo->pTableScanOp->info;
H
Haojun Liao 已提交
2017 2018
    tsdbReaderClose(pTSInfo->base.dataReader);
    pTSInfo->base.dataReader = NULL;
2019

H
Haojun Liao 已提交
2020 2021
    pTSInfo->base.cond.startVersion = -1;
    pTSInfo->base.cond.endVersion = -1;
L
Liu Jicong 已提交
2022

L
Liu Jicong 已提交
2023 2024 2025
    return NULL;
  }

5
54liuyao 已提交
2026
  size_t total = taosArrayGetSize(pInfo->pBlockLists);
5
54liuyao 已提交
2027
// TODO: refactor
L
Liu Jicong 已提交
2028
FETCH_NEXT_BLOCK:
L
Liu Jicong 已提交
2029
  if (pInfo->blockType == STREAM_INPUT__DATA_BLOCK) {
H
Haojun Liao 已提交
2030
    if (pInfo->validBlockIndex >= total) {
L
Liu Jicong 已提交
2031
      doClearBufferedBlocks(pInfo);
L
Liu Jicong 已提交
2032
      /*pOperator->status = OP_EXEC_DONE;*/
H
Haojun Liao 已提交
2033 2034 2035
      return NULL;
    }

2036
    int32_t      current = pInfo->validBlockIndex++;
2037
    SSDataBlock* pBlock = taosArrayGetP(pInfo->pBlockLists, current);
2038 2039 2040
    if (pBlock->info.groupId && pBlock->info.parTbName[0]) {
      streamStatePutParName(pTaskInfo->streamInfo.pState, pBlock->info.groupId, pBlock->info.parTbName);
    }
2041
    // TODO move into scan
5
54liuyao 已提交
2042 2043
    pBlock->info.calWin.skey = INT64_MIN;
    pBlock->info.calWin.ekey = INT64_MAX;
2044
    blockDataUpdateTsWindow(pBlock, 0);
2045
    switch (pBlock->info.type) {
L
Liu Jicong 已提交
2046 2047 2048
      case STREAM_NORMAL:
      case STREAM_GET_ALL:
        return pBlock;
2049 2050 2051
      case STREAM_RETRIEVE: {
        pInfo->blockType = STREAM_INPUT__DATA_SUBMIT;
        pInfo->scanMode = STREAM_SCAN_FROM_DATAREADER_RETRIEVE;
2052 2053
        copyDataBlock(pInfo->pUpdateRes, pBlock);
        prepareRangeScan(pInfo, pInfo->pUpdateRes, &pInfo->updateResIndex);
2054 2055 2056
        updateInfoAddCloseWindowSBF(pInfo->pUpdateInfo);
      } break;
      case STREAM_DELETE_DATA: {
2057
        printDataBlock(pBlock, "stream scan delete recv");
L
Liu Jicong 已提交
2058
        SSDataBlock* pDelBlock = NULL;
L
Liu Jicong 已提交
2059
        if (pInfo->tqReader) {
L
Liu Jicong 已提交
2060
          pDelBlock = createSpecialDataBlock(STREAM_DELETE_DATA);
L
Liu Jicong 已提交
2061
          filterDelBlockByUid(pDelBlock, pBlock, pInfo);
L
Liu Jicong 已提交
2062 2063
        } else {
          pDelBlock = pBlock;
L
Liu Jicong 已提交
2064
        }
5
54liuyao 已提交
2065 2066
        setBlockGroupIdByUid(pInfo, pDelBlock);
        printDataBlock(pDelBlock, "stream scan delete recv filtered");
2067
        if (!isIntervalWindow(pInfo) && !isSessionWindow(pInfo) && !isStateWindow(pInfo)) {
L
Liu Jicong 已提交
2068
          generateDeleteResultBlock(pInfo, pDelBlock, pInfo->pDeleteDataRes);
2069
          pInfo->pDeleteDataRes->info.type = STREAM_DELETE_RESULT;
L
Liu Jicong 已提交
2070
          printDataBlock(pDelBlock, "stream scan delete result");
H
Haojun Liao 已提交
2071 2072
          blockDataDestroy(pDelBlock);

L
Liu Jicong 已提交
2073 2074 2075 2076 2077
          if (pInfo->pDeleteDataRes->info.rows > 0) {
            return pInfo->pDeleteDataRes;
          } else {
            goto FETCH_NEXT_BLOCK;
          }
2078 2079 2080
        } else {
          pInfo->blockType = STREAM_INPUT__DATA_SUBMIT;
          pInfo->updateResIndex = 0;
L
Liu Jicong 已提交
2081
          generateScanRange(pInfo, pDelBlock, pInfo->pUpdateRes);
2082 2083 2084 2085
          prepareRangeScan(pInfo, pInfo->pUpdateRes, &pInfo->updateResIndex);
          copyDataBlock(pInfo->pDeleteDataRes, pInfo->pUpdateRes);
          pInfo->pDeleteDataRes->info.type = STREAM_DELETE_DATA;
          pInfo->scanMode = STREAM_SCAN_FROM_DATAREADER_RANGE;
L
Liu Jicong 已提交
2086 2087 2088 2089
          printDataBlock(pDelBlock, "stream scan delete data");
          if (pInfo->tqReader) {
            blockDataDestroy(pDelBlock);
          }
L
Liu Jicong 已提交
2090 2091 2092 2093 2094
          if (pInfo->pDeleteDataRes->info.rows > 0) {
            return pInfo->pDeleteDataRes;
          } else {
            goto FETCH_NEXT_BLOCK;
          }
2095
        }
2096 2097 2098
      } break;
      default:
        break;
5
54liuyao 已提交
2099
    }
2100
    // printDataBlock(pBlock, "stream scan recv");
2101
    return pBlock;
L
Liu Jicong 已提交
2102
  } else if (pInfo->blockType == STREAM_INPUT__DATA_SUBMIT) {
L
Liu Jicong 已提交
2103
    qDebug("scan mode %d", pInfo->scanMode);
5
54liuyao 已提交
2104 2105 2106 2107 2108 2109
    switch (pInfo->scanMode) {
      case STREAM_SCAN_FROM_RES: {
        blockDataDestroy(pInfo->pUpdateRes);
        pInfo->scanMode = STREAM_SCAN_FROM_READERHANDLE;
        return pInfo->pRes;
      } break;
2110
      case STREAM_SCAN_FROM_DELETE_DATA: {
2111 2112 2113 2114 2115 2116 2117
        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 已提交
2118 2119 2120 2121 2122 2123 2124 2125 2126 2127
      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) {
2128
          STableScanInfo* pTableScanInfo = pInfo->pTableScanOp->info;
H
Haojun Liao 已提交
2129 2130
          uint64_t        version = getReaderMaxVersion(pTableScanInfo->base.dataReader);
          updateInfoSetScanRange(pInfo->pUpdateInfo, &pTableScanInfo->base.cond.twindows, pInfo->groupId, version);
5
54liuyao 已提交
2131 2132
          pSDB->info.type = pInfo->scanMode == STREAM_SCAN_FROM_DATAREADER_RANGE ? STREAM_NORMAL : STREAM_PULL_DATA;
          checkUpdateData(pInfo, true, pSDB, false);
2133
          // printDataBlock(pSDB, "stream scan update");
L
Liu Jicong 已提交
2134
          calBlockTbName(pInfo, pSDB);
5
54liuyao 已提交
2135 2136
          return pSDB;
        }
2137
        blockDataCleanup(pInfo->pUpdateDataRes);
5
54liuyao 已提交
2138 2139 2140 2141
        pInfo->scanMode = STREAM_SCAN_FROM_READERHANDLE;
      } break;
      default:
        break;
2142
    }
2143

2144
    SStreamAggSupporter* pSup = pInfo->windowSup.pStreamAggSup;
5
54liuyao 已提交
2145
    if (isStateWindow(pInfo) && pSup->pScanBlock->info.rows > 0) {
2146 2147
      pInfo->scanMode = STREAM_SCAN_FROM_DATAREADER_RANGE;
      pInfo->updateResIndex = 0;
5
54liuyao 已提交
2148 2149
      copyDataBlock(pInfo->pUpdateRes, pSup->pScanBlock);
      blockDataCleanup(pSup->pScanBlock);
2150 2151
      prepareRangeScan(pInfo, pInfo->pUpdateRes, &pInfo->updateResIndex);
      return pInfo->pUpdateRes;
5
54liuyao 已提交
2152
    }
5
54liuyao 已提交
2153

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

2156
    int32_t totBlockNum = taosArrayGetSize(pInfo->pBlockLists);
2157

L
Liu Jicong 已提交
2158
  NEXT_SUBMIT_BLK:
2159 2160 2161
    while (1) {
      if (pInfo->tqReader->pMsg == NULL) {
        if (pInfo->validBlockIndex >= totBlockNum) {
5
54liuyao 已提交
2162
          updateInfoDestoryColseWinSBF(pInfo->pUpdateInfo);
L
Liu Jicong 已提交
2163
          doClearBufferedBlocks(pInfo);
2164 2165
          return NULL;
        }
2166

2167 2168 2169 2170 2171 2172 2173 2174
        int32_t     current = pInfo->validBlockIndex++;
        SSubmitReq* pSubmit = taosArrayGetP(pInfo->pBlockLists, current);
        if (tqReaderSetDataMsg(pInfo->tqReader, pSubmit, 0) < 0) {
          qError("submit msg messed up when initing stream submit block %p, current %d, total %d", pSubmit, current,
                 totBlockNum);
          pInfo->tqReader->pMsg = NULL;
          continue;
        }
H
Haojun Liao 已提交
2175 2176
      }

2177 2178 2179 2180
      blockDataCleanup(pInfo->pRes);

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

2182 2183 2184 2185 2186 2187
        int32_t code = tqRetrieveDataBlock(&block, pInfo->tqReader);

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

2188
        setBlockIntoRes(pInfo, &block, false);
2189

L
Liu Jicong 已提交
2190 2191
        if (updateInfoIgnore(pInfo->pUpdateInfo, &pInfo->pRes->info.window, pInfo->pRes->info.groupId,
                             pInfo->pRes->info.version)) {
2192 2193 2194 2195 2196
          printDataBlock(pInfo->pRes, "stream scan ignore");
          blockDataCleanup(pInfo->pRes);
          continue;
        }

2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212
        if (pInfo->pUpdateInfo) {
          checkUpdateData(pInfo, true, pInfo->pRes, true);
          pInfo->twAggSup.maxTs = TMAX(pInfo->twAggSup.maxTs, pBlockInfo->window.ekey);
          if (pInfo->pUpdateDataRes->info.rows > 0) {
            pInfo->updateResIndex = 0;
            if (pInfo->pUpdateDataRes->info.type == STREAM_CLEAR) {
              pInfo->scanMode = STREAM_SCAN_FROM_UPDATERES;
            } else if (pInfo->pUpdateDataRes->info.type == STREAM_INVERT) {
              pInfo->scanMode = STREAM_SCAN_FROM_RES;
              return pInfo->pUpdateDataRes;
            } else if (pInfo->pUpdateDataRes->info.type == STREAM_DELETE_DATA) {
              pInfo->scanMode = STREAM_SCAN_FROM_DELETE_DATA;
            }
          }
        }

H
Haojun Liao 已提交
2213
        doFilter(pInfo->pRes, pOperator->exprSupp.pFilterInfo, NULL);
2214 2215 2216
        blockDataUpdateTsWindow(pInfo->pRes, pInfo->primaryTsIndex);

        if (pBlockInfo->rows > 0 || pInfo->pUpdateDataRes->info.rows > 0) {
2217 2218 2219
          break;
        }
      }
2220
      if (pBlockInfo->rows > 0 || pInfo->pUpdateDataRes->info.rows > 0) {
5
54liuyao 已提交
2221
        break;
J
jiacy-jcy 已提交
2222 2223
      } else {
        pInfo->tqReader->pMsg = NULL;
2224
        continue;
5
54liuyao 已提交
2225
      }
2226
      /*blockDataCleanup(pInfo->pRes);*/
H
Haojun Liao 已提交
2227 2228 2229 2230
    }

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

L
Liu Jicong 已提交
2234
    qDebug("scan rows: %d", pBlockInfo->rows);
L
Liu Jicong 已提交
2235 2236 2237
    if (pBlockInfo->rows > 0) {
      return pInfo->pRes;
    }
2238 2239 2240 2241 2242 2243

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

    goto NEXT_SUBMIT_BLK;
L
Liu Jicong 已提交
2244 2245 2246
  } else {
    ASSERT(0);
    return NULL;
H
Haojun Liao 已提交
2247 2248 2249
  }
}

H
Haojun Liao 已提交
2250
static SArray* extractTableIdList(const STableListInfo* pTableListInfo) {
2251 2252 2253
  SArray* tableIdList = taosArrayInit(4, sizeof(uint64_t));

  // Transfer the Array of STableKeyInfo into uid list.
H
Haojun Liao 已提交
2254 2255 2256
  size_t size = tableListGetSize(pTableListInfo);
  for (int32_t i = 0; i < size; ++i) {
    STableKeyInfo* pkeyInfo = tableListGetInfo(pTableListInfo, i);
2257 2258 2259 2260 2261 2262
    taosArrayPush(tableIdList, &pkeyInfo->uid);
  }

  return tableIdList;
}

2263
static SSDataBlock* doRawScan(SOperatorInfo* pOperator) {
L
Liu Jicong 已提交
2264 2265
  // NOTE: this operator does never check if current status is done or not
  SExecTaskInfo*      pTaskInfo = pOperator->pTaskInfo;
2266
  SStreamRawScanInfo* pInfo = pOperator->info;
L
Liu Jicong 已提交
2267
  pTaskInfo->streamInfo.metaRsp.metaRspLen = 0;  // use metaRspLen !=0 to judge if data is meta
wmmhello's avatar
wmmhello 已提交
2268
  pTaskInfo->streamInfo.metaRsp.metaRsp = NULL;
2269

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

2274
    if (pInfo->dataReader && tsdbNextDataBlock(pInfo->dataReader)) {
wmmhello's avatar
wmmhello 已提交
2275 2276 2277
      if (isTaskKilled(pTaskInfo)) {
        longjmp(pTaskInfo->env, TSDB_CODE_TSC_QUERY_CANCELLED);
      }
2278

H
Haojun Liao 已提交
2279 2280 2281
      int32_t rows = 0;
      tsdbRetrieveDataBlockInfo(pInfo->dataReader, &rows, &pBlock->info.uid, &pBlock->info.window);
      pBlock->info.rows = rows;
2282

wmmhello's avatar
wmmhello 已提交
2283 2284 2285
      SArray* pCols = tsdbRetrieveDataBlock(pInfo->dataReader, NULL);
      pBlock->pDataBlock = pCols;
      if (pCols == NULL) {
wmmhello's avatar
wmmhello 已提交
2286
        longjmp(pTaskInfo->env, terrno);
wmmhello's avatar
wmmhello 已提交
2287 2288
      }

2289
      qDebug("tmqsnap doRawScan get data uid:%" PRId64 "", pBlock->info.uid);
wmmhello's avatar
wmmhello 已提交
2290 2291 2292 2293 2294
      pTaskInfo->streamInfo.lastStatus.type = TMQ_OFFSET__SNAPSHOT_DATA;
      pTaskInfo->streamInfo.lastStatus.uid = pBlock->info.uid;
      pTaskInfo->streamInfo.lastStatus.ts = pBlock->info.window.ekey;
      return pBlock;
    }
wmmhello's avatar
wmmhello 已提交
2295 2296

    SMetaTableInfo mtInfo = getUidfromSnapShot(pInfo->sContext);
L
Liu Jicong 已提交
2297
    if (mtInfo.uid == 0) {  // read snapshot done, change to get data from wal
wmmhello's avatar
wmmhello 已提交
2298 2299
      qDebug("tmqsnap read snapshot done, change to get data from wal");
      pTaskInfo->streamInfo.prepareStatus.uid = mtInfo.uid;
wmmhello's avatar
wmmhello 已提交
2300 2301
      pTaskInfo->streamInfo.lastStatus.type = TMQ_OFFSET__LOG;
      pTaskInfo->streamInfo.lastStatus.version = pInfo->sContext->snapVersion;
L
Liu Jicong 已提交
2302
    } else {
wmmhello's avatar
wmmhello 已提交
2303 2304
      pTaskInfo->streamInfo.prepareStatus.uid = mtInfo.uid;
      pTaskInfo->streamInfo.prepareStatus.ts = INT64_MIN;
2305
      qDebug("tmqsnap change get data uid:%" PRId64 "", mtInfo.uid);
wmmhello's avatar
wmmhello 已提交
2306 2307
      qStreamPrepareScan(pTaskInfo, &pTaskInfo->streamInfo.prepareStatus, pInfo->sContext->subType);
    }
2308
    tDeleteSSchemaWrapper(mtInfo.schema);
wmmhello's avatar
wmmhello 已提交
2309
    qDebug("tmqsnap stream scan tsdb return null");
wmmhello's avatar
wmmhello 已提交
2310
    return NULL;
L
Liu Jicong 已提交
2311 2312 2313 2314 2315 2316 2317
  } else if (pTaskInfo->streamInfo.prepareStatus.type == TMQ_OFFSET__SNAPSHOT_META) {
    SSnapContext* sContext = pInfo->sContext;
    void*         data = NULL;
    int32_t       dataLen = 0;
    int16_t       type = 0;
    int64_t       uid = 0;
    if (getMetafromSnapShot(sContext, &data, &dataLen, &type, &uid) < 0) {
wmmhello's avatar
wmmhello 已提交
2318
      qError("tmqsnap getMetafromSnapShot error");
wmmhello's avatar
wmmhello 已提交
2319
      taosMemoryFreeClear(data);
2320 2321 2322
      return NULL;
    }

L
Liu Jicong 已提交
2323
    if (!sContext->queryMetaOrData) {  // change to get data next poll request
wmmhello's avatar
wmmhello 已提交
2324 2325 2326 2327
      pTaskInfo->streamInfo.lastStatus.type = TMQ_OFFSET__SNAPSHOT_META;
      pTaskInfo->streamInfo.lastStatus.uid = uid;
      pTaskInfo->streamInfo.metaRsp.rspOffset.type = TMQ_OFFSET__SNAPSHOT_DATA;
      pTaskInfo->streamInfo.metaRsp.rspOffset.uid = 0;
wmmhello's avatar
wmmhello 已提交
2328
      pTaskInfo->streamInfo.metaRsp.rspOffset.ts = INT64_MIN;
L
Liu Jicong 已提交
2329
    } else {
wmmhello's avatar
wmmhello 已提交
2330 2331 2332 2333 2334 2335 2336
      pTaskInfo->streamInfo.lastStatus.type = TMQ_OFFSET__SNAPSHOT_META;
      pTaskInfo->streamInfo.lastStatus.uid = uid;
      pTaskInfo->streamInfo.metaRsp.rspOffset = pTaskInfo->streamInfo.lastStatus;
      pTaskInfo->streamInfo.metaRsp.resMsgType = type;
      pTaskInfo->streamInfo.metaRsp.metaRspLen = dataLen;
      pTaskInfo->streamInfo.metaRsp.metaRsp = data;
    }
2337

wmmhello's avatar
wmmhello 已提交
2338
    return NULL;
2339
  }
L
Liu Jicong 已提交
2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377
  //  else if (pTaskInfo->streamInfo.prepareStatus.type == TMQ_OFFSET__LOG) {
  //    int64_t fetchVer = pTaskInfo->streamInfo.prepareStatus.version + 1;
  //
  //    while(1){
  //      if (tqFetchLog(pInfo->tqReader->pWalReader, pInfo->sContext->withMeta, &fetchVer, &pInfo->pCkHead) < 0) {
  //        qDebug("tmqsnap tmq poll: consumer log end. offset %" PRId64, fetchVer);
  //        pTaskInfo->streamInfo.lastStatus.version = fetchVer;
  //        pTaskInfo->streamInfo.lastStatus.type = TMQ_OFFSET__LOG;
  //        return NULL;
  //      }
  //      SWalCont* pHead = &pInfo->pCkHead->head;
  //      qDebug("tmqsnap tmq poll: consumer log offset %" PRId64 " msgType %d", fetchVer, pHead->msgType);
  //
  //      if (pHead->msgType == TDMT_VND_SUBMIT) {
  //        SSubmitReq* pCont = (SSubmitReq*)&pHead->body;
  //        tqReaderSetDataMsg(pInfo->tqReader, pCont, 0);
  //        SSDataBlock* block = tqLogScanExec(pInfo->sContext->subType, pInfo->tqReader, pInfo->pFilterOutTbUid,
  //        &pInfo->pRes); if(block){
  //          pTaskInfo->streamInfo.lastStatus.type = TMQ_OFFSET__LOG;
  //          pTaskInfo->streamInfo.lastStatus.version = fetchVer;
  //          qDebug("tmqsnap fetch data msg, ver:%" PRId64 ", type:%d", pHead->version, pHead->msgType);
  //          return block;
  //        }else{
  //          fetchVer++;
  //        }
  //      } else{
  //        ASSERT(pInfo->sContext->withMeta);
  //        ASSERT(IS_META_MSG(pHead->msgType));
  //        qDebug("tmqsnap fetch meta msg, ver:%" PRId64 ", type:%d", pHead->version, pHead->msgType);
  //        pTaskInfo->streamInfo.metaRsp.rspOffset.version = fetchVer;
  //        pTaskInfo->streamInfo.metaRsp.rspOffset.type = TMQ_OFFSET__LOG;
  //        pTaskInfo->streamInfo.metaRsp.resMsgType = pHead->msgType;
  //        pTaskInfo->streamInfo.metaRsp.metaRspLen = pHead->bodyLen;
  //        pTaskInfo->streamInfo.metaRsp.metaRsp = taosMemoryMalloc(pHead->bodyLen);
  //        memcpy(pTaskInfo->streamInfo.metaRsp.metaRsp, pHead->body, pHead->bodyLen);
  //        return NULL;
  //      }
  //    }
2378 2379 2380
  return NULL;
}

wmmhello's avatar
wmmhello 已提交
2381
static void destroyRawScanOperatorInfo(void* param) {
wmmhello's avatar
wmmhello 已提交
2382 2383 2384 2385 2386 2387
  SStreamRawScanInfo* pRawScan = (SStreamRawScanInfo*)param;
  tsdbReaderClose(pRawScan->dataReader);
  destroySnapContext(pRawScan->sContext);
  taosMemoryFree(pRawScan);
}

L
Liu Jicong 已提交
2388 2389 2390
// for subscribing db or stb (not including column),
// if this scan is used, meta data can be return
// and schemas are decided when scanning
2391
SOperatorInfo* createRawScanOperatorInfo(SReadHandle* pHandle, SExecTaskInfo* pTaskInfo) {
L
Liu Jicong 已提交
2392 2393 2394 2395 2396
  // create operator
  // create tb reader
  // create meta reader
  // create tq reader

H
Haojun Liao 已提交
2397 2398
  int32_t code = TSDB_CODE_SUCCESS;

2399
  SStreamRawScanInfo* pInfo = taosMemoryCalloc(1, sizeof(SStreamRawScanInfo));
L
Liu Jicong 已提交
2400
  SOperatorInfo*      pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
2401
  if (pInfo == NULL || pOperator == NULL) {
H
Haojun Liao 已提交
2402 2403
    code = TSDB_CODE_OUT_OF_MEMORY;
    goto _end;
2404 2405
  }

wmmhello's avatar
wmmhello 已提交
2406 2407
  pInfo->vnode = pHandle->vnode;

2408
  pInfo->sContext = pHandle->sContext;
L
Liu Jicong 已提交
2409 2410
  setOperatorInfo(pOperator, "RawScanOperator", QUERY_NODE_PHYSICAL_PLAN_TABLE_SCAN, false, OP_NOT_OPENED, pInfo,
                  pTaskInfo);
2411

H
Haojun Liao 已提交
2412
  pOperator->fpSet = createOperatorFpSet(NULL, doRawScan, NULL, destroyRawScanOperatorInfo, NULL);
2413
  return pOperator;
H
Haojun Liao 已提交
2414

L
Liu Jicong 已提交
2415
_end:
H
Haojun Liao 已提交
2416 2417 2418 2419
  taosMemoryFree(pInfo);
  taosMemoryFree(pOperator);
  pTaskInfo->code = code;
  return NULL;
L
Liu Jicong 已提交
2420 2421
}

2422
static void destroyStreamScanOperatorInfo(void* param) {
2423 2424
  SStreamScanInfo* pStreamScan = (SStreamScanInfo*)param;
  if (pStreamScan->pTableScanOp && pStreamScan->pTableScanOp->info) {
5
54liuyao 已提交
2425
    destroyOperatorInfo(pStreamScan->pTableScanOp);
2426 2427 2428 2429
  }
  if (pStreamScan->tqReader) {
    tqCloseReader(pStreamScan->tqReader);
  }
H
Haojun Liao 已提交
2430 2431
  if (pStreamScan->matchInfo.pList) {
    taosArrayDestroy(pStreamScan->matchInfo.pList);
2432
  }
C
Cary Xu 已提交
2433 2434
  if (pStreamScan->pPseudoExpr) {
    destroyExprInfo(pStreamScan->pPseudoExpr, pStreamScan->numOfPseudoExpr);
L
Liu Jicong 已提交
2435
    taosMemoryFree(pStreamScan->pPseudoExpr);
C
Cary Xu 已提交
2436
  }
C
Cary Xu 已提交
2437

L
Liu Jicong 已提交
2438 2439
  cleanupExprSupp(&pStreamScan->tbnameCalSup);

L
Liu Jicong 已提交
2440
  updateInfoDestroy(pStreamScan->pUpdateInfo);
2441 2442 2443 2444
  blockDataDestroy(pStreamScan->pRes);
  blockDataDestroy(pStreamScan->pUpdateRes);
  blockDataDestroy(pStreamScan->pPullDataRes);
  blockDataDestroy(pStreamScan->pDeleteDataRes);
5
54liuyao 已提交
2445
  blockDataDestroy(pStreamScan->pUpdateDataRes);
2446 2447 2448 2449
  taosArrayDestroy(pStreamScan->pBlockLists);
  taosMemoryFree(pStreamScan);
}

2450
SOperatorInfo* createStreamScanOperatorInfo(SReadHandle* pHandle, STableScanPhysiNode* pTableScanNode, SNode* pTagCond,
2451
                                            SExecTaskInfo* pTaskInfo) {
2452 2453
  SStreamScanInfo* pInfo = taosMemoryCalloc(1, sizeof(SStreamScanInfo));
  SOperatorInfo*   pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
2454

H
Haojun Liao 已提交
2455 2456
  if (pInfo == NULL || pOperator == NULL) {
    terrno = TSDB_CODE_QRY_OUT_OF_MEMORY;
2457
    goto _error;
H
Haojun Liao 已提交
2458 2459
  }

2460
  SScanPhysiNode*     pScanPhyNode = &pTableScanNode->scan;
2461
  SDataBlockDescNode* pDescNode = pScanPhyNode->node.pOutputDataBlockDesc;
H
Haojun Liao 已提交
2462

2463
  pInfo->pTagCond = pTagCond;
2464
  pInfo->pGroupTags = pTableScanNode->pGroupTags;
2465

2466
  int32_t numOfCols = 0;
2467 2468
  int32_t code =
      extractColMatchInfo(pScanPhyNode->pScanCols, pDescNode, &numOfCols, COL_MATCH_FROM_COL_ID, &pInfo->matchInfo);
H
Haojun Liao 已提交
2469 2470 2471
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
2472

H
Haojun Liao 已提交
2473
  int32_t numOfOutput = taosArrayGetSize(pInfo->matchInfo.pList);
2474
  SArray* pColIds = taosArrayInit(numOfOutput, sizeof(int16_t));
2475
  for (int32_t i = 0; i < numOfOutput; ++i) {
H
Haojun Liao 已提交
2476
    SColMatchItem* id = taosArrayGet(pInfo->matchInfo.pList, i);
2477 2478

    int16_t colId = id->colId;
2479
    taosArrayPush(pColIds, &colId);
2480
    if (id->colId == PRIMARYKEY_TIMESTAMP_COL_ID) {
H
Haojun Liao 已提交
2481
      pInfo->primaryTsIndex = id->dstSlotId;
5
54liuyao 已提交
2482
    }
H
Haojun Liao 已提交
2483 2484
  }

L
Liu Jicong 已提交
2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497
  if (pTableScanNode->pSubtable != NULL) {
    SExprInfo* pSubTableExpr = taosMemoryCalloc(1, sizeof(SExprInfo));
    if (pSubTableExpr == NULL) {
      terrno = TSDB_CODE_OUT_OF_MEMORY;
      goto _error;
    }
    pInfo->tbnameCalSup.pExprInfo = pSubTableExpr;
    createExprFromOneNode(pSubTableExpr, pTableScanNode->pSubtable, 0);
    if (initExprSupp(&pInfo->tbnameCalSup, pSubTableExpr, 1) != 0) {
      goto _error;
    }
  }

2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510
  if (pTableScanNode->pTags != NULL) {
    int32_t    numOfTags;
    SExprInfo* pTagExpr = createExprInfo(pTableScanNode->pTags, NULL, &numOfTags);
    if (pTagExpr == NULL) {
      terrno = TSDB_CODE_OUT_OF_MEMORY;
      goto _error;
    }
    if (initExprSupp(&pInfo->tagCalSup, pTagExpr, numOfTags) != 0) {
      terrno = TSDB_CODE_OUT_OF_MEMORY;
      goto _error;
    }
  }

H
Haojun Liao 已提交
2511 2512
  pInfo->pBlockLists = taosArrayInit(4, POINTER_BYTES);
  if (pInfo->pBlockLists == NULL) {
2513 2514
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    goto _error;
H
Haojun Liao 已提交
2515 2516
  }

5
54liuyao 已提交
2517
  if (pHandle->vnode) {
L
Liu Jicong 已提交
2518
    SOperatorInfo*  pTableScanOp = createTableScanOperatorInfo(pTableScanNode, pHandle, pTaskInfo);
L
Liu Jicong 已提交
2519
    STableScanInfo* pTSInfo = (STableScanInfo*)pTableScanOp->info;
2520
    if (pHandle->version > 0) {
H
Haojun Liao 已提交
2521
      pTSInfo->base.cond.endVersion = pHandle->version;
2522
    }
L
Liu Jicong 已提交
2523

2524
    STableKeyInfo* pList = NULL;
5
54liuyao 已提交
2525
    int32_t        num = 0;
H
Haojun Liao 已提交
2526
    tableListGetGroupList(pTaskInfo->pTableInfoList, 0, &pList, &num);
2527

2528
    if (pHandle->initTableReader) {
L
Liu Jicong 已提交
2529
      pTSInfo->scanMode = TABLE_SCAN__TABLE_ORDER;
H
Haojun Liao 已提交
2530 2531
      pTSInfo->base.dataReader = NULL;
      code = tsdbReaderOpen(pHandle->vnode, &pTSInfo->base.cond, pList, num, &pTSInfo->base.dataReader, NULL);
dengyihao's avatar
dengyihao 已提交
2532 2533
      if (code != 0) {
        terrno = code;
H
Haojun Liao 已提交
2534
        destroyTableScanOperatorInfo(pTableScanOp);
2535
        goto _error;
L
Liu Jicong 已提交
2536
      }
L
Liu Jicong 已提交
2537 2538
    }

L
Liu Jicong 已提交
2539 2540 2541 2542
    if (pHandle->initTqReader) {
      ASSERT(pHandle->tqReader == NULL);
      pInfo->tqReader = tqOpenReader(pHandle->vnode);
      ASSERT(pInfo->tqReader);
2543
    } else {
L
Liu Jicong 已提交
2544 2545
      ASSERT(pHandle->tqReader);
      pInfo->tqReader = pHandle->tqReader;
2546 2547
    }

2548
    pInfo->pUpdateInfo = NULL;
2549
    pInfo->pTableScanOp = pTableScanOp;
2550 2551 2552
    if (pInfo->pTableScanOp->pTaskInfo->streamInfo.pState) {
      streamStateSetNumber(pInfo->pTableScanOp->pTaskInfo->streamInfo.pState, -1);
    }
L
Liu Jicong 已提交
2553

L
Liu Jicong 已提交
2554 2555
    pInfo->readHandle = *pHandle;
    pInfo->tableUid = pScanPhyNode->uid;
L
Liu Jicong 已提交
2556
    pTaskInfo->streamInfo.snapshotVer = pHandle->version;
L
Liu Jicong 已提交
2557

L
Liu Jicong 已提交
2558
    // set the extract column id to streamHandle
L
Liu Jicong 已提交
2559
    tqReaderSetColIdList(pInfo->tqReader, pColIds);
H
Haojun Liao 已提交
2560
    SArray* tableIdList = extractTableIdList(pTaskInfo->pTableInfoList);
2561
    code = tqReaderSetTbUidList(pInfo->tqReader, tableIdList);
L
Liu Jicong 已提交
2562 2563 2564 2565 2566
    if (code != 0) {
      taosArrayDestroy(tableIdList);
      goto _error;
    }
    taosArrayDestroy(tableIdList);
H
Haojun Liao 已提交
2567
    memcpy(&pTaskInfo->streamInfo.tableCond, &pTSInfo->base.cond, sizeof(SQueryTableDataCond));
L
Liu Jicong 已提交
2568 2569
  } else {
    taosArrayDestroy(pColIds);
5
54liuyao 已提交
2570 2571
  }

2572 2573 2574 2575 2576
  // create the pseduo columns info
  if (pTableScanNode->scan.pScanPseudoCols != NULL) {
    pInfo->pPseudoExpr = createExprInfo(pTableScanNode->scan.pScanPseudoCols, NULL, &pInfo->numOfPseudoExpr);
  }

H
Haojun Liao 已提交
2577 2578 2579 2580 2581
  code = filterInitFromNode((SNode*)pScanPhyNode->node.pConditions, &pOperator->exprSupp.pFilterInfo, 0);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }

2582
  pInfo->pRes = createResDataBlock(pDescNode);
2583
  pInfo->pUpdateRes = createSpecialDataBlock(STREAM_CLEAR);
2584
  pInfo->scanMode = STREAM_SCAN_FROM_READERHANDLE;
L
Liu Jicong 已提交
2585
  pInfo->windowSup = (SWindowSupporter){.pStreamAggSup = NULL, .gap = -1, .parentType = QUERY_NODE_PHYSICAL_PLAN};
2586
  pInfo->groupId = 0;
2587
  pInfo->pPullDataRes = createSpecialDataBlock(STREAM_RETRIEVE);
2588
  pInfo->pStreamScanOp = pOperator;
2589
  pInfo->deleteDataIndex = 0;
2590
  pInfo->pDeleteDataRes = createSpecialDataBlock(STREAM_DELETE_DATA);
5
54liuyao 已提交
2591
  pInfo->updateWin = (STimeWindow){.skey = INT64_MAX, .ekey = INT64_MAX};
2592
  pInfo->pUpdateDataRes = createSpecialDataBlock(STREAM_CLEAR);
X
Xiaoyu Wang 已提交
2593
  pInfo->assignBlockUid = pTableScanNode->assignBlockUid;
2594
  pInfo->partitionSup.needCalc = false;
L
Liu Jicong 已提交
2595

L
Liu Jicong 已提交
2596 2597
  setOperatorInfo(pOperator, "StreamScanOperator", QUERY_NODE_PHYSICAL_PLAN_STREAM_SCAN, false, OP_NOT_OPENED, pInfo,
                  pTaskInfo);
2598
  pOperator->exprSupp.numOfExprs = taosArrayGetSize(pInfo->pRes->pDataBlock);
H
Haojun Liao 已提交
2599

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

H
Haojun Liao 已提交
2603
  return pOperator;
2604

L
Liu Jicong 已提交
2605
_error:
H
Haojun Liao 已提交
2606 2607 2608 2609 2610 2611 2612 2613
  if (pColIds != NULL) {
    taosArrayDestroy(pColIds);
  }

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

2614 2615
  taosMemoryFreeClear(pOperator);
  return NULL;
H
Haojun Liao 已提交
2616 2617
}

2618
static void destroySysScanOperator(void* param) {
H
Haojun Liao 已提交
2619 2620 2621 2622
  SSysTableScanInfo* pInfo = (SSysTableScanInfo*)param;
  tsem_destroy(&pInfo->ready);
  blockDataDestroy(pInfo->pRes);

2623
  const char* name = tNameGetTableName(&pInfo->name);
D
dapan1121 已提交
2624 2625
  if (strncasecmp(name, TSDB_INS_TABLE_TABLES, TSDB_TABLE_FNAME_LEN) == 0 ||
      strncasecmp(name, TSDB_INS_TABLE_TAGS, TSDB_TABLE_FNAME_LEN) == 0 || pInfo->pCur != NULL) {
H
Haojun Liao 已提交
2626
    metaCloseTbCursor(pInfo->pCur);
2627
    pInfo->pCur = NULL;
H
Haojun Liao 已提交
2628
  }
dengyihao's avatar
dengyihao 已提交
2629 2630 2631 2632 2633
  if (pInfo->pIdx) {
    taosArrayDestroy(pInfo->pIdx->uids);
    taosMemoryFree(pInfo->pIdx);
    pInfo->pIdx = NULL;
  }
H
Haojun Liao 已提交
2634

H
Haojun Liao 已提交
2635
  taosArrayDestroy(pInfo->matchInfo.pList);
2636
  taosMemoryFreeClear(pInfo->pUser);
D
dapan1121 已提交
2637 2638

  taosMemoryFreeClear(param);
H
Haojun Liao 已提交
2639 2640
}

X
Xiaoyu Wang 已提交
2641
static int32_t getSysTableDbNameColId(const char* pTable) {
D
dapan1121 已提交
2642
  // if (0 == strcmp(TSDB_INS_TABLE_INDEXES, pTable)) {
X
Xiaoyu Wang 已提交
2643 2644
  //   return 1;
  // }
X
Xiaoyu Wang 已提交
2645 2646 2647
  return TSDB_INS_USER_STABLES_DBNAME_COLID;
}

H
Haojun Liao 已提交
2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668
EDealRes getDBNameFromConditionWalker(SNode* pNode, void* pContext) {
  int32_t   code = TSDB_CODE_SUCCESS;
  ENodeType nType = nodeType(pNode);

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

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

      SColumnNode* node = (SColumnNode*)pNode;
X
Xiaoyu Wang 已提交
2669
      if (getSysTableDbNameColId(node->tableName) == node->colId) {
H
Haojun Liao 已提交
2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685
        *(int32_t*)pContext = 2;
        return DEAL_RES_CONTINUE;
      }

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

      SValueNode* node = (SValueNode*)pNode;
      char*       dbName = nodesGetValueFromNode(node);
      strncpy(pContext, varDataVal(dbName), varDataLen(dbName));
      *((char*)pContext + varDataLen(dbName)) = 0;
2686
      return DEAL_RES_END;  // stop walk
H
Haojun Liao 已提交
2687 2688 2689 2690 2691 2692 2693
    }
    default:
      break;
  }
  return DEAL_RES_CONTINUE;
}

2694
static void getDBNameFromCondition(SNode* pCondition, const char* dbName) {
H
Haojun Liao 已提交
2695 2696 2697
  if (NULL == pCondition) {
    return;
  }
L
Liu Jicong 已提交
2698
  nodesWalkExpr(pCondition, getDBNameFromConditionWalker, (char*)dbName);
H
Haojun Liao 已提交
2699 2700
}

D
dapan1121 已提交
2701
static int32_t loadSysTableCallback(void* param, SDataBuf* pMsg, int32_t code) {
H
Haojun Liao 已提交
2702 2703 2704 2705 2706 2707 2708
  SOperatorInfo*     operator=(SOperatorInfo*) param;
  SSysTableScanInfo* pScanResInfo = (SSysTableScanInfo*)operator->info;
  if (TSDB_CODE_SUCCESS == code) {
    pScanResInfo->pRsp = pMsg->pData;

    SRetrieveMetaTableRsp* pRsp = pScanResInfo->pRsp;
    pRsp->numOfRows = htonl(pRsp->numOfRows);
2709 2710 2711
    pRsp->useconds = htobe64(pRsp->useconds);
    pRsp->handle = htobe64(pRsp->handle);
    pRsp->compLen = htonl(pRsp->compLen);
H
Haojun Liao 已提交
2712 2713 2714 2715 2716
  } else {
    operator->pTaskInfo->code = code;
  }

  tsem_post(&pScanResInfo->ready);
wmmhello's avatar
wmmhello 已提交
2717
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
2718 2719
}

H
Haojun Liao 已提交
2720 2721 2722
static SSDataBlock* doFilterResult(SSDataBlock* pDataBlock, SFilterInfo* pFilterInfo) {
  if (pFilterInfo == NULL) {
    return pDataBlock->info.rows == 0 ? NULL : pDataBlock;
H
Haojun Liao 已提交
2723 2724
  }

H
Haojun Liao 已提交
2725 2726
  doFilter(pDataBlock, pFilterInfo, NULL);
  return pDataBlock->info.rows == 0 ? NULL : pDataBlock;
H
Haojun Liao 已提交
2727 2728
}

2729
static SSDataBlock* buildInfoSchemaTableMetaBlock(char* tableName) {
L
Liu Jicong 已提交
2730 2731
  size_t               size = 0;
  const SSysTableMeta* pMeta = NULL;
2732 2733 2734
  getInfosDbMeta(&pMeta, &size);

  int32_t index = 0;
L
Liu Jicong 已提交
2735
  for (int32_t i = 0; i < size; ++i) {
2736
    if (strcmp(pMeta[i].name, tableName) == 0) {
2737 2738 2739 2740
      index = i;
      break;
    }
  }
2741

2742
  SSDataBlock* pBlock = createDataBlock();
L
Liu Jicong 已提交
2743
  for (int32_t i = 0; i < pMeta[index].colNum; ++i) {
L
Liu Jicong 已提交
2744 2745
    SColumnInfoData colInfoData =
        createColumnInfoData(pMeta[index].schema[i].type, pMeta[index].schema[i].bytes, i + 1);
2746
    blockDataAppendColInfo(pBlock, &colInfoData);
2747 2748
  }

2749 2750 2751
  return pBlock;
}

2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832
int32_t convertTagDataToStr(char* str, int type, void* buf, int32_t bufSize, int32_t* len) {
  int32_t n = 0;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    default:
      return TSDB_CODE_TSC_INVALID_VALUE;
  }

  if (len) *len = n;

  return TSDB_CODE_SUCCESS;
}

2833 2834 2835 2836 2837 2838 2839
static bool sysTableIsOperatorCondOnOneTable(SNode* pCond, char* condTable) {
  SOperatorNode* node = (SOperatorNode*)pCond;
  if (node->opType == OP_TYPE_EQUAL) {
    if (nodeType(node->pLeft) == QUERY_NODE_COLUMN &&
        strcasecmp(nodesGetNameFromColumnNode(node->pLeft), "table_name") == 0 &&
        nodeType(node->pRight) == QUERY_NODE_VALUE) {
      SValueNode* pValue = (SValueNode*)node->pRight;
2840 2841 2842 2843
      if (pValue->node.resType.type == TSDB_DATA_TYPE_NCHAR || pValue->node.resType.type == TSDB_DATA_TYPE_VARCHAR ||
          pValue->node.resType.type == TSDB_DATA_TYPE_BINARY) {
        char* value = nodesGetValueFromNode(pValue);
        strncpy(condTable, varDataVal(value), TSDB_TABLE_NAME_LEN);
2844 2845 2846 2847 2848 2849 2850 2851
        return true;
      }
    }
  }
  return false;
}

static bool sysTableIsCondOnOneTable(SNode* pCond, char* condTable) {
S
slzhou 已提交
2852 2853 2854
  if (pCond == NULL) {
    return false;
  }
2855 2856 2857
  if (nodeType(pCond) == QUERY_NODE_LOGIC_CONDITION) {
    SLogicConditionNode* node = (SLogicConditionNode*)pCond;
    if (LOGIC_COND_TYPE_AND == node->condType) {
S
slzhou 已提交
2858 2859 2860 2861
      SNode* pChild = NULL;
      FOREACH(pChild, node->pParameterList) {
        if (QUERY_NODE_OPERATOR == nodeType(pChild) && sysTableIsOperatorCondOnOneTable(pChild, condTable)) {
          return true;
2862 2863 2864 2865
        }
      }
    }
  }
S
slzhou 已提交
2866

2867 2868 2869
  if (QUERY_NODE_OPERATOR == nodeType(pCond)) {
    return sysTableIsOperatorCondOnOneTable(pCond, condTable);
  }
S
slzhou 已提交
2870

2871 2872 2873
  return false;
}

S
shenglian zhou 已提交
2874 2875 2876 2877 2878 2879 2880 2881 2882 2883
static SSDataBlock* sysTableScanUserTags(SOperatorInfo* pOperator) {
  SExecTaskInfo*     pTaskInfo = pOperator->pTaskInfo;
  SSysTableScanInfo* pInfo = pOperator->info;
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

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

2884 2885 2886
  SSDataBlock* dataBlock = buildInfoSchemaTableMetaBlock(TSDB_INS_TABLE_TAGS);
  blockDataEnsureCapacity(dataBlock, pOperator->resultInfo.capacity);

S
shenglian zhou 已提交
2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897
  const char* db = NULL;
  int32_t     vgId = 0;
  vnodeGetInfo(pInfo->readHandle.vnode, &db, &vgId);

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

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

2898
  char condTableName[TSDB_TABLE_NAME_LEN] = {0};
S
slzhou 已提交
2899 2900
  // optimize when sql like where table_name='tablename' and xxx.
  if (pInfo->pCondition && sysTableIsCondOnOneTable(pInfo->pCondition, condTableName)) {
2901 2902 2903
    char tableName[TSDB_TABLE_NAME_LEN + VARSTR_HEADER_SIZE] = {0};
    STR_TO_VARSTR(tableName, condTableName);

2904 2905
    SMetaReader smrChildTable = {0};
    metaReaderInit(&smrChildTable, pInfo->readHandle.meta, 0);
H
Haojun Liao 已提交
2906 2907 2908 2909 2910 2911
    int32_t code = metaGetTableEntryByName(&smrChildTable, condTableName);
    if (code != TSDB_CODE_SUCCESS) {
      // terrno has been set by metaGetTableEntryByName, therefore, return directly
      return NULL;
    }

2912 2913 2914 2915 2916 2917
    if (smrChildTable.me.type != TSDB_CHILD_TABLE) {
      metaReaderClear(&smrChildTable);
      blockDataDestroy(dataBlock);
      pInfo->loadInfo.totalRows = 0;
      return NULL;
    }
H
Haojun Liao 已提交
2918

2919
    SMetaReader smrSuperTable = {0};
2920
    metaReaderInit(&smrSuperTable, pInfo->readHandle.meta, META_READER_NOLOCK);
H
Haojun Liao 已提交
2921 2922 2923 2924 2925 2926
    code = metaGetTableEntryByUid(&smrSuperTable, smrChildTable.me.ctbEntry.suid);
    if (code != TSDB_CODE_SUCCESS) {
      // terrno has been set by metaGetTableEntryByUid
      return NULL;
    }

2927 2928 2929
    sysTableUserTagsFillOneTableTags(pInfo, &smrSuperTable, &smrChildTable, dbname, tableName, &numOfRows, dataBlock);
    metaReaderClear(&smrSuperTable);
    metaReaderClear(&smrChildTable);
2930
    if (numOfRows > 0) {
H
Haojun Liao 已提交
2931
      relocateAndFilterSysTagsScanResult(pInfo, numOfRows, dataBlock, pOperator->exprSupp.pFilterInfo);
2932 2933 2934 2935
      numOfRows = 0;
    }
    blockDataDestroy(dataBlock);
    pInfo->loadInfo.totalRows += pInfo->pRes->info.rows;
H
Haojun Liao 已提交
2936
    setOperatorCompleted(pOperator);
2937 2938
    return (pInfo->pRes->info.rows == 0) ? NULL : pInfo->pRes;
  }
S
shenglian zhou 已提交
2939 2940

  int32_t ret = 0;
2941 2942 2943 2944
  if (pInfo->pCur == NULL) {
    pInfo->pCur = metaOpenTbCursor(pInfo->readHandle.meta);
  }

S
shenglian zhou 已提交
2945
  while ((ret = metaTbCursorNext(pInfo->pCur)) == 0) {
2946 2947 2948
    if (pInfo->pCur->mr.me.type != TSDB_CHILD_TABLE) {
      continue;
    }
S
shenglian zhou 已提交
2949

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

2953 2954
    SMetaReader smrSuperTable = {0};
    metaReaderInit(&smrSuperTable, pInfo->readHandle.meta, 0);
2955
    uint64_t suid = pInfo->pCur->mr.me.ctbEntry.suid;
2956
    int32_t  code = metaGetTableEntryByUid(&smrSuperTable, suid);
2957 2958 2959
    if (code != TSDB_CODE_SUCCESS) {
      qError("failed to get super table meta, uid:0x%" PRIx64 ", code:%s, %s", suid, tstrerror(terrno),
             GET_TASKID(pTaskInfo));
2960
      metaReaderClear(&smrSuperTable);
2961 2962
      metaCloseTbCursor(pInfo->pCur);
      pInfo->pCur = NULL;
2963
      T_LONG_JMP(pTaskInfo->env, terrno);
2964
    }
S
shenglian zhou 已提交
2965

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

2968
    metaReaderClear(&smrSuperTable);
S
shenglian zhou 已提交
2969

2970
    if (numOfRows >= pOperator->resultInfo.capacity) {
H
Haojun Liao 已提交
2971
      relocateAndFilterSysTagsScanResult(pInfo, numOfRows, dataBlock, pOperator->exprSupp.pFilterInfo);
2972 2973 2974 2975 2976
      numOfRows = 0;

      if (pInfo->pRes->info.rows > 0) {
        break;
      }
S
shenglian zhou 已提交
2977 2978 2979
    }
  }

2980
  if (numOfRows > 0) {
H
Haojun Liao 已提交
2981
    relocateAndFilterSysTagsScanResult(pInfo, numOfRows, dataBlock, pOperator->exprSupp.pFilterInfo);
2982 2983 2984
    numOfRows = 0;
  }

2985
  blockDataDestroy(dataBlock);
S
shenglian zhou 已提交
2986 2987 2988
  if (ret != 0) {
    metaCloseTbCursor(pInfo->pCur);
    pInfo->pCur = NULL;
H
Haojun Liao 已提交
2989
    setOperatorCompleted(pOperator);
S
shenglian zhou 已提交
2990 2991 2992 2993 2994 2995
  }

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

H
Haojun Liao 已提交
2996 2997
void relocateAndFilterSysTagsScanResult(SSysTableScanInfo* pInfo, int32_t numOfRows, SSDataBlock* dataBlock,
                                        SFilterInfo* pFilterInfo) {
2998 2999 3000
  dataBlock->info.rows = numOfRows;
  pInfo->pRes->info.rows = numOfRows;

H
Haojun Liao 已提交
3001
  relocateColumnData(pInfo->pRes, pInfo->matchInfo.pList, dataBlock->pDataBlock, false);
H
Haojun Liao 已提交
3002
  doFilterResult(pInfo->pRes, pFilterInfo);
3003 3004 3005
  blockDataCleanup(dataBlock);
}

3006 3007 3008
static int32_t sysTableUserTagsFillOneTableTags(const SSysTableScanInfo* pInfo, SMetaReader* smrSuperTable,
                                                SMetaReader* smrChildTable, const char* dbname, const char* tableName,
                                                int32_t* pNumOfRows, const SSDataBlock* dataBlock) {
3009
  char stableName[TSDB_TABLE_NAME_LEN + VARSTR_HEADER_SIZE] = {0};
3010
  STR_TO_VARSTR(stableName, (*smrSuperTable).me.name);
3011 3012 3013

  int32_t numOfRows = *pNumOfRows;

3014
  int32_t numOfTags = (*smrSuperTable).me.stbEntry.schemaTag.nCols;
3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031
  for (int32_t i = 0; i < numOfTags; ++i) {
    SColumnInfoData* pColInfoData = NULL;

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

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

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

    // tag name
    char tagName[TSDB_COL_NAME_LEN + VARSTR_HEADER_SIZE] = {0};
3032
    STR_TO_VARSTR(tagName, (*smrSuperTable).me.stbEntry.schemaTag.pSchema[i].name);
3033 3034 3035 3036
    pColInfoData = taosArrayGet(dataBlock->pDataBlock, 3);
    colDataAppend(pColInfoData, numOfRows, tagName, false);

    // tag type
3037
    int8_t tagType = (*smrSuperTable).me.stbEntry.schemaTag.pSchema[i].type;
3038 3039 3040 3041 3042
    pColInfoData = taosArrayGet(dataBlock->pDataBlock, 4);
    char tagTypeStr[VARSTR_HEADER_SIZE + 32];
    int  tagTypeLen = sprintf(varDataVal(tagTypeStr), "%s", tDataTypes[tagType].name);
    if (tagType == TSDB_DATA_TYPE_VARCHAR) {
      tagTypeLen += sprintf(varDataVal(tagTypeStr) + tagTypeLen, "(%d)",
3043
                            (int32_t)((*smrSuperTable).me.stbEntry.schemaTag.pSchema[i].bytes - VARSTR_HEADER_SIZE));
3044
    } else if (tagType == TSDB_DATA_TYPE_NCHAR) {
3045 3046 3047
      tagTypeLen += sprintf(
          varDataVal(tagTypeStr) + tagTypeLen, "(%d)",
          (int32_t)(((*smrSuperTable).me.stbEntry.schemaTag.pSchema[i].bytes - VARSTR_HEADER_SIZE) / TSDB_NCHAR_SIZE));
3048 3049 3050 3051 3052
    }
    varDataSetLen(tagTypeStr, tagTypeLen);
    colDataAppend(pColInfoData, numOfRows, (char*)tagTypeStr, false);

    STagVal tagVal = {0};
3053
    tagVal.cid = (*smrSuperTable).me.stbEntry.schemaTag.pSchema[i].colId;
3054 3055 3056 3057
    char*    tagData = NULL;
    uint32_t tagLen = 0;

    if (tagType == TSDB_DATA_TYPE_JSON) {
3058
      tagData = (char*)smrChildTable->me.ctbEntry.pTags;
3059
    } else {
3060
      bool exist = tTagGet((STag*)smrChildTable->me.ctbEntry.pTags, &tagVal);
3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100
      if (exist) {
        if (IS_VAR_DATA_TYPE(tagType)) {
          tagData = (char*)tagVal.pData;
          tagLen = tagVal.nData;
        } else {
          tagData = (char*)&tagVal.i64;
          tagLen = tDataTypes[tagType].bytes;
        }
      }
    }

    char* tagVarChar = NULL;
    if (tagData != NULL) {
      if (tagType == TSDB_DATA_TYPE_JSON) {
        char* tagJson = parseTagDatatoJson(tagData);
        tagVarChar = taosMemoryMalloc(strlen(tagJson) + VARSTR_HEADER_SIZE);
        memcpy(varDataVal(tagVarChar), tagJson, strlen(tagJson));
        varDataSetLen(tagVarChar, strlen(tagJson));
        taosMemoryFree(tagJson);
      } else {
        int32_t bufSize = IS_VAR_DATA_TYPE(tagType) ? (tagLen + VARSTR_HEADER_SIZE)
                                                    : (3 + DBL_MANT_DIG - DBL_MIN_EXP + VARSTR_HEADER_SIZE);
        tagVarChar = taosMemoryMalloc(bufSize);
        int32_t len = -1;
        convertTagDataToStr(varDataVal(tagVarChar), tagType, tagData, tagLen, &len);
        varDataSetLen(tagVarChar, len);
      }
    }
    pColInfoData = taosArrayGet(dataBlock->pDataBlock, 5);
    colDataAppend(pColInfoData, numOfRows, tagVarChar,
                  (tagData == NULL) || (tagType == TSDB_DATA_TYPE_JSON && tTagIsJsonNull(tagData)));
    taosMemoryFree(tagVarChar);
    ++numOfRows;
  }

  *pNumOfRows = numOfRows;

  return TSDB_CODE_SUCCESS;
}

dengyihao's avatar
dengyihao 已提交
3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126
typedef int (*__optSysFilter)(void* a, void* b, int16_t dtype);

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

dengyihao's avatar
dengyihao 已提交
3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150
static int optSysFilterFuncImpl__LowerThan(void* a, void* b, int16_t dtype) {
  __compar_fn_t func = getComparFunc(dtype, 0);
  return optSysDoCompare(func, OP_TYPE_LOWER_THAN, a, b);
}
static int optSysFilterFuncImpl__LowerEqual(void* a, void* b, int16_t dtype) {
  __compar_fn_t func = getComparFunc(dtype, 0);
  return optSysDoCompare(func, OP_TYPE_LOWER_EQUAL, a, b);
}
static int optSysFilterFuncImpl__GreaterThan(void* a, void* b, int16_t dtype) {
  __compar_fn_t func = getComparFunc(dtype, 0);
  return optSysDoCompare(func, OP_TYPE_GREATER_THAN, a, b);
}
static int optSysFilterFuncImpl__GreaterEqual(void* a, void* b, int16_t dtype) {
  __compar_fn_t func = getComparFunc(dtype, 0);
  return optSysDoCompare(func, OP_TYPE_GREATER_EQUAL, a, b);
}
static int optSysFilterFuncImpl__Equal(void* a, void* b, int16_t dtype) {
  __compar_fn_t func = getComparFunc(dtype, 0);
  return optSysDoCompare(func, OP_TYPE_EQUAL, a, b);
}
3151

dengyihao's avatar
dengyihao 已提交
3152 3153 3154 3155
static int optSysFilterFuncImpl__NoEqual(void* a, void* b, int16_t dtype) {
  __compar_fn_t func = getComparFunc(dtype, 0);
  return optSysDoCompare(func, OP_TYPE_NOT_EQUAL, a, b);
}
dengyihao's avatar
dengyihao 已提交
3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169
static __optSysFilter optSysGetFilterFunc(int32_t ctype, bool* reverse) {
  if (ctype == OP_TYPE_LOWER_EQUAL || ctype == OP_TYPE_LOWER_THAN) {
    *reverse = true;
  }
  if (ctype == OP_TYPE_LOWER_THAN)
    return optSysFilterFuncImpl__LowerThan;
  else if (ctype == OP_TYPE_LOWER_EQUAL)
    return optSysFilterFuncImpl__LowerEqual;
  else if (ctype == OP_TYPE_GREATER_THAN)
    return optSysFilterFuncImpl__GreaterThan;
  else if (ctype == OP_TYPE_GREATER_EQUAL)
    return optSysFilterFuncImpl__GreaterEqual;
  else if (ctype == OP_TYPE_EQUAL)
    return optSysFilterFuncImpl__Equal;
dengyihao's avatar
dengyihao 已提交
3170 3171
  else if (ctype == OP_TYPE_NOT_EQUAL)
    return optSysFilterFuncImpl__NoEqual;
dengyihao's avatar
dengyihao 已提交
3172 3173
  return NULL;
}
dengyihao's avatar
dengyihao 已提交
3174 3175
static int32_t sysFilte__DbName(void* arg, SNode* pNode, SArray* result) {
  void* pVnode = ((SSTabFltArg*)arg)->pVnode;
3176

dengyihao's avatar
dengyihao 已提交
3177 3178
  const char* db = NULL;
  vnodeGetInfo(pVnode, &db, NULL);
dengyihao's avatar
dengyihao 已提交
3179

dengyihao's avatar
dengyihao 已提交
3180 3181 3182 3183 3184 3185
  SName sn = {0};
  char  dbname[TSDB_DB_FNAME_LEN + VARSTR_HEADER_SIZE] = {0};
  tNameFromString(&sn, db, T_NAME_ACCT | T_NAME_DB);

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

dengyihao's avatar
dengyihao 已提交
3187
  SOperatorNode* pOper = (SOperatorNode*)pNode;
dengyihao's avatar
dengyihao 已提交
3188
  SValueNode*    pVal = (SValueNode*)pOper->pRight;
dengyihao's avatar
dengyihao 已提交
3189

dengyihao's avatar
dengyihao 已提交
3190 3191
  bool           reverse = false;
  __optSysFilter func = optSysGetFilterFunc(pOper->opType, &reverse);
dengyihao's avatar
dengyihao 已提交
3192 3193 3194 3195 3196
  if (func == NULL) return -1;

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

dengyihao's avatar
dengyihao 已提交
3197
  return -2;
dengyihao's avatar
dengyihao 已提交
3198
}
dengyihao's avatar
dengyihao 已提交
3199 3200
static int32_t sysFilte__VgroupId(void* arg, SNode* pNode, SArray* result) {
  void* pVnode = ((SSTabFltArg*)arg)->pVnode;
dengyihao's avatar
dengyihao 已提交
3201

dengyihao's avatar
dengyihao 已提交
3202 3203
  int64_t vgId = 0;
  vnodeGetInfo(pVnode, NULL, (int32_t*)&vgId);
dengyihao's avatar
dengyihao 已提交
3204

dengyihao's avatar
dengyihao 已提交
3205
  SOperatorNode* pOper = (SOperatorNode*)pNode;
dengyihao's avatar
dengyihao 已提交
3206 3207
  SValueNode*    pVal = (SValueNode*)pOper->pRight;

dengyihao's avatar
dengyihao 已提交
3208 3209 3210
  bool reverse = false;

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

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

dengyihao's avatar
dengyihao 已提交
3216
  return -1;
dengyihao's avatar
dengyihao 已提交
3217
}
dengyihao's avatar
dengyihao 已提交
3218 3219
static int32_t sysFilte__TableName(void* arg, SNode* pNode, SArray* result) {
  void* pMeta = ((SSTabFltArg*)arg)->pMeta;
dengyihao's avatar
dengyihao 已提交
3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233

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

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

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

dengyihao's avatar
dengyihao 已提交
3237 3238
static int32_t sysFilte__CreateTime(void* arg, SNode* pNode, SArray* result) {
  void* pMeta = ((SSTabFltArg*)arg)->pMeta;
dengyihao's avatar
dengyihao 已提交
3239 3240 3241 3242 3243 3244 3245

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

  __optSysFilter func = optSysGetFilterFunc(pOper->opType, &reverse);
  if (func == NULL) return -1;
dengyihao's avatar
dengyihao 已提交
3246 3247 3248 3249 3250 3251 3252 3253 3254 3255

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

  int32_t ret = metaFilterCreateTime(pMeta, &param, result);
  return ret;
dengyihao's avatar
dengyihao 已提交
3256
}
dengyihao's avatar
dengyihao 已提交
3257 3258
static int32_t sysFilte__Ncolumn(void* arg, SNode* pNode, SArray* result) {
  void* pMeta = ((SSTabFltArg*)arg)->pMeta;
dengyihao's avatar
dengyihao 已提交
3259 3260 3261 3262 3263 3264

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

  __optSysFilter func = optSysGetFilterFunc(pOper->opType, &reverse);
dengyihao's avatar
dengyihao 已提交
3265 3266
  if (func == NULL) return -1;
  return -1;
dengyihao's avatar
dengyihao 已提交
3267 3268
}

dengyihao's avatar
dengyihao 已提交
3269 3270
static int32_t sysFilte__Ttl(void* arg, SNode* pNode, SArray* result) {
  void* pMeta = ((SSTabFltArg*)arg)->pMeta;
dengyihao's avatar
dengyihao 已提交
3271 3272 3273 3274 3275 3276

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

  __optSysFilter func = optSysGetFilterFunc(pOper->opType, &reverse);
dengyihao's avatar
dengyihao 已提交
3277 3278
  if (func == NULL) return -1;
  return -1;
dengyihao's avatar
dengyihao 已提交
3279
}
dengyihao's avatar
dengyihao 已提交
3280 3281
static int32_t sysFilte__STableName(void* arg, SNode* pNode, SArray* result) {
  void* pMeta = ((SSTabFltArg*)arg)->pMeta;
dengyihao's avatar
dengyihao 已提交
3282 3283 3284 3285 3286 3287

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

  __optSysFilter func = optSysGetFilterFunc(pOper->opType, &reverse);
dengyihao's avatar
dengyihao 已提交
3288 3289
  if (func == NULL) return -1;
  return -1;
dengyihao's avatar
dengyihao 已提交
3290
}
dengyihao's avatar
dengyihao 已提交
3291 3292
static int32_t sysFilte__Uid(void* arg, SNode* pNode, SArray* result) {
  void* pMeta = ((SSTabFltArg*)arg)->pMeta;
dengyihao's avatar
dengyihao 已提交
3293 3294 3295 3296 3297 3298

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

  __optSysFilter func = optSysGetFilterFunc(pOper->opType, &reverse);
dengyihao's avatar
dengyihao 已提交
3299 3300
  if (func == NULL) return -1;
  return -1;
dengyihao's avatar
dengyihao 已提交
3301
}
dengyihao's avatar
dengyihao 已提交
3302 3303
static int32_t sysFilte__Type(void* arg, SNode* pNode, SArray* result) {
  void* pMeta = ((SSTabFltArg*)arg)->pMeta;
dengyihao's avatar
dengyihao 已提交
3304 3305 3306 3307 3308 3309

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

  __optSysFilter func = optSysGetFilterFunc(pOper->opType, &reverse);
dengyihao's avatar
dengyihao 已提交
3310
  if (func == NULL) return -1;
dengyihao's avatar
dengyihao 已提交
3311
  return -1;
dengyihao's avatar
dengyihao 已提交
3312
}
dengyihao's avatar
dengyihao 已提交
3313 3314 3315 3316 3317
static int32_t sysChkFilter__Comm(SNode* pNode) {
  // impl
  SOperatorNode* pOper = (SOperatorNode*)pNode;
  EOperatorType  opType = pOper->opType;
  if (opType != OP_TYPE_EQUAL && opType != OP_TYPE_LOWER_EQUAL && opType != OP_TYPE_LOWER_THAN &&
dengyihao's avatar
dengyihao 已提交
3318
      opType != OP_TYPE_GREATER_EQUAL && opType != OP_TYPE_GREATER_THAN) {
dengyihao's avatar
dengyihao 已提交
3319
    return -1;
dengyihao's avatar
dengyihao 已提交
3320 3321 3322 3323
  }
  return 0;
}

dengyihao's avatar
dengyihao 已提交
3324 3325
static int32_t sysChkFilter__DBName(SNode* pNode) {
  SOperatorNode* pOper = (SOperatorNode*)pNode;
dengyihao's avatar
dengyihao 已提交
3326 3327 3328 3329 3330 3331

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

  SValueNode* pVal = (SValueNode*)pOper->pRight;
dengyihao's avatar
dengyihao 已提交
3332
  if (!IS_STR_DATA_TYPE(pVal->node.resType.type)) {
dengyihao's avatar
dengyihao 已提交
3333 3334
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
3335

dengyihao's avatar
dengyihao 已提交
3336 3337 3338 3339 3340
  return 0;
}
static int32_t sysChkFilter__VgroupId(SNode* pNode) {
  SOperatorNode* pOper = (SOperatorNode*)pNode;
  SValueNode*    pVal = (SValueNode*)pOper->pRight;
dengyihao's avatar
dengyihao 已提交
3341
  if (!IS_INTEGER_TYPE(pVal->node.resType.type)) {
dengyihao's avatar
dengyihao 已提交
3342 3343
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
3344
  return sysChkFilter__Comm(pNode);
dengyihao's avatar
dengyihao 已提交
3345 3346 3347 3348
}
static int32_t sysChkFilter__TableName(SNode* pNode) {
  SOperatorNode* pOper = (SOperatorNode*)pNode;
  SValueNode*    pVal = (SValueNode*)pOper->pRight;
dengyihao's avatar
dengyihao 已提交
3349
  if (!IS_STR_DATA_TYPE(pVal->node.resType.type)) {
dengyihao's avatar
dengyihao 已提交
3350 3351
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
3352
  return sysChkFilter__Comm(pNode);
dengyihao's avatar
dengyihao 已提交
3353 3354 3355 3356 3357
}
static int32_t sysChkFilter__CreateTime(SNode* pNode) {
  SOperatorNode* pOper = (SOperatorNode*)pNode;
  SValueNode*    pVal = (SValueNode*)pOper->pRight;

dengyihao's avatar
dengyihao 已提交
3358
  if (!IS_TIMESTAMP_TYPE(pVal->node.resType.type)) {
dengyihao's avatar
dengyihao 已提交
3359 3360
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
3361
  return sysChkFilter__Comm(pNode);
dengyihao's avatar
dengyihao 已提交
3362 3363 3364 3365 3366 3367
}

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

dengyihao's avatar
dengyihao 已提交
3368
  if (!IS_INTEGER_TYPE(pVal->node.resType.type)) {
dengyihao's avatar
dengyihao 已提交
3369 3370
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
3371
  return sysChkFilter__Comm(pNode);
dengyihao's avatar
dengyihao 已提交
3372 3373 3374 3375 3376
}
static int32_t sysChkFilter__Ttl(SNode* pNode) {
  SOperatorNode* pOper = (SOperatorNode*)pNode;
  SValueNode*    pVal = (SValueNode*)pOper->pRight;

dengyihao's avatar
dengyihao 已提交
3377
  if (!IS_INTEGER_TYPE(pVal->node.resType.type)) {
dengyihao's avatar
dengyihao 已提交
3378 3379
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
3380
  return sysChkFilter__Comm(pNode);
dengyihao's avatar
dengyihao 已提交
3381 3382 3383 3384
}
static int32_t sysChkFilter__STableName(SNode* pNode) {
  SOperatorNode* pOper = (SOperatorNode*)pNode;
  SValueNode*    pVal = (SValueNode*)pOper->pRight;
dengyihao's avatar
dengyihao 已提交
3385
  if (!IS_STR_DATA_TYPE(pVal->node.resType.type)) {
dengyihao's avatar
dengyihao 已提交
3386 3387
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
3388
  return sysChkFilter__Comm(pNode);
dengyihao's avatar
dengyihao 已提交
3389 3390 3391 3392
}
static int32_t sysChkFilter__Uid(SNode* pNode) {
  SOperatorNode* pOper = (SOperatorNode*)pNode;
  SValueNode*    pVal = (SValueNode*)pOper->pRight;
dengyihao's avatar
dengyihao 已提交
3393
  if (!IS_INTEGER_TYPE(pVal->node.resType.type)) {
dengyihao's avatar
dengyihao 已提交
3394 3395
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
3396
  return sysChkFilter__Comm(pNode);
dengyihao's avatar
dengyihao 已提交
3397 3398 3399 3400
}
static int32_t sysChkFilter__Type(SNode* pNode) {
  SOperatorNode* pOper = (SOperatorNode*)pNode;
  SValueNode*    pVal = (SValueNode*)pOper->pRight;
dengyihao's avatar
dengyihao 已提交
3401
  if (!IS_INTEGER_TYPE(pVal->node.resType.type)) {
dengyihao's avatar
dengyihao 已提交
3402 3403
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
3404
  return sysChkFilter__Comm(pNode);
dengyihao's avatar
dengyihao 已提交
3405
}
dengyihao's avatar
dengyihao 已提交
3406
static int32_t optSysTabFilteImpl(void* arg, SNode* cond, SArray* result) {
dengyihao's avatar
dengyihao 已提交
3407
  if (optSysCheckOper(cond) != 0) return -1;
dengyihao's avatar
dengyihao 已提交
3408 3409 3410

  SOperatorNode* pNode = (SOperatorNode*)cond;

dengyihao's avatar
dengyihao 已提交
3411 3412
  int8_t i = 0;
  for (; i < SYSTAB_FILTER_DICT_SIZE; i++) {
dengyihao's avatar
dengyihao 已提交
3413 3414
    if (strcmp(filterDict[i].name, ((SColumnNode*)(pNode->pLeft))->colName) == 0) {
      break;
3415
    }
dengyihao's avatar
dengyihao 已提交
3416 3417
  }
  if (i >= SYSTAB_FILTER_DICT_SIZE) return -1;
3418

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

dengyihao's avatar
dengyihao 已提交
3421 3422
  return filterDict[i].fltFunc(arg, cond, result);
}
3423

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

dengyihao's avatar
dengyihao 已提交
3427
  SOperatorNode* pOper = (SOperatorNode*)pOpear;
dengyihao's avatar
dengyihao 已提交
3428 3429 3430
  if (pOper->opType < OP_TYPE_GREATER_THAN || pOper->opType > OP_TYPE_NOT_EQUAL) {
    return -1;
  }
3431

dengyihao's avatar
dengyihao 已提交
3432 3433 3434 3435
  if (nodeType(pOper->pLeft) != QUERY_NODE_COLUMN || nodeType(pOper->pRight) != QUERY_NODE_VALUE) {
    return -1;
  }
  return 0;
dengyihao's avatar
dengyihao 已提交
3436
}
3437

dengyihao's avatar
dengyihao 已提交
3438 3439 3440 3441 3442 3443 3444 3445
static int tableUidCompare(const void* a, const void* b) {
  int64_t u1 = *(int64_t*)a;
  int64_t u2 = *(int64_t*)b;
  if (u1 == u2) {
    return 0;
  }
  return u1 < u2 ? -1 : 1;
}
dengyihao's avatar
opt mem  
dengyihao 已提交
3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500

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

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

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

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

dengyihao's avatar
dengyihao 已提交
3501 3502 3503
static int32_t optSysMergeRslt(SArray* mRslt, SArray* rslt) {
  // TODO, find comm mem from mRslt
  for (int i = 0; i < taosArrayGetSize(mRslt); i++) {
dengyihao's avatar
opt mem  
dengyihao 已提交
3504 3505 3506 3507 3508 3509
    SArray* arslt = taosArrayGetP(mRslt, i);
    taosArraySort(arslt, tableUidCompare);
  }
  optSysIntersection(mRslt, rslt);
  return 0;
}
3510

dengyihao's avatar
opt mem  
dengyihao 已提交
3511 3512 3513 3514 3515 3516 3517
static int32_t optSysSpecialColumn(SNode* cond) {
  SOperatorNode* pOper = (SOperatorNode*)cond;
  SColumnNode*   pCol = (SColumnNode*)pOper->pLeft;
  for (int i = 0; i < sizeof(SYSTABLE_SPECIAL_COL) / sizeof(SYSTABLE_SPECIAL_COL[0]); i++) {
    if (0 == strcmp(pCol->colName, SYSTABLE_SPECIAL_COL[i])) {
      return 1;
    }
dengyihao's avatar
dengyihao 已提交
3518 3519 3520
  }
  return 0;
}
3521

dengyihao's avatar
dengyihao 已提交
3522 3523 3524 3525
static int32_t optSysTabFilte(void* arg, SNode* cond, SArray* result) {
  int ret = -1;
  if (nodeType(cond) == QUERY_NODE_OPERATOR) {
    ret = optSysTabFilteImpl(arg, cond, result);
dengyihao's avatar
dengyihao 已提交
3526 3527 3528
    if (ret == 0) {
      SOperatorNode* pOper = (SOperatorNode*)cond;
      SColumnNode*   pCol = (SColumnNode*)pOper->pLeft;
dengyihao's avatar
dengyihao 已提交
3529
      if (0 == strcmp(pCol->colName, "create_time")) {
dengyihao's avatar
dengyihao 已提交
3530 3531 3532 3533
        return 0;
      }
      return -1;
    }
dengyihao's avatar
dengyihao 已提交
3534 3535
    return ret;
  }
3536

dengyihao's avatar
dengyihao 已提交
3537 3538 3539
  if (nodeType(cond) != QUERY_NODE_LOGIC_CONDITION || ((SLogicConditionNode*)cond)->condType != LOGIC_COND_TYPE_AND) {
    return ret;
  }
3540

dengyihao's avatar
dengyihao 已提交
3541 3542
  SLogicConditionNode* pNode = (SLogicConditionNode*)cond;
  SNodeList*           pList = (SNodeList*)pNode->pParameterList;
3543

dengyihao's avatar
dengyihao 已提交
3544
  int32_t len = LIST_LENGTH(pList);
3545

dengyihao's avatar
dengyihao 已提交
3546
  bool    hasIdx = false;
dengyihao's avatar
dengyihao 已提交
3547
  bool    hasRslt = true;
dengyihao's avatar
dengyihao 已提交
3548
  SArray* mRslt = taosArrayInit(len, POINTER_BYTES);
3549

dengyihao's avatar
dengyihao 已提交
3550 3551 3552
  SListCell* cell = pList->pHead;
  for (int i = 0; i < len; i++) {
    if (cell == NULL) break;
3553

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

dengyihao's avatar
dengyihao 已提交
3556 3557
    ret = optSysTabFilteImpl(arg, cell->pNode, aRslt);
    if (ret == 0) {
dengyihao's avatar
dengyihao 已提交
3558
      // has index
dengyihao's avatar
dengyihao 已提交
3559
      hasIdx = true;
dengyihao's avatar
opt mem  
dengyihao 已提交
3560 3561 3562 3563 3564 3565
      if (optSysSpecialColumn(cell->pNode) == 0) {
        taosArrayPush(mRslt, &aRslt);
      } else {
        // db_name/vgroup not result
        taosArrayDestroy(aRslt);
      }
dengyihao's avatar
dengyihao 已提交
3566
    } else if (ret == -2) {
dengyihao's avatar
dengyihao 已提交
3567
      // current vg
dengyihao's avatar
dengyihao 已提交
3568 3569 3570 3571 3572 3573
      hasIdx = true;
      hasRslt = false;
      taosArrayDestroy(aRslt);
      break;
    } else {
      taosArrayDestroy(aRslt);
dengyihao's avatar
dengyihao 已提交
3574 3575 3576
    }
    cell = cell->pNext;
  }
dengyihao's avatar
dengyihao 已提交
3577 3578 3579
  if (hasRslt && hasIdx) {
    optSysMergeRslt(mRslt, result);
  }
3580

dengyihao's avatar
dengyihao 已提交
3581 3582 3583
  for (int i = 0; i < taosArrayGetSize(mRslt); i++) {
    SArray* aRslt = taosArrayGetP(mRslt, i);
    taosArrayDestroy(aRslt);
dengyihao's avatar
dengyihao 已提交
3584
  }
dengyihao's avatar
dengyihao 已提交
3585
  taosArrayDestroy(mRslt);
dengyihao's avatar
dengyihao 已提交
3586 3587 3588 3589
  if (hasRslt == false) {
    return -2;
  }
  if (hasRslt && hasIdx) {
dengyihao's avatar
dengyihao 已提交
3590 3591 3592 3593 3594
    cell = pList->pHead;
    for (int i = 0; i < len; i++) {
      if (cell == NULL) break;
      SOperatorNode* pOper = (SOperatorNode*)cell->pNode;
      SColumnNode*   pCol = (SColumnNode*)pOper->pLeft;
dengyihao's avatar
dengyihao 已提交
3595
      if (0 == strcmp(pCol->colName, "create_time")) {
dengyihao's avatar
dengyihao 已提交
3596 3597 3598 3599 3600
        return 0;
      }
      cell = cell->pNext;
    }
    return -1;
dengyihao's avatar
dengyihao 已提交
3601 3602
  }
  return -1;
dengyihao's avatar
dengyihao 已提交
3603
}
3604

dengyihao's avatar
dengyihao 已提交
3605
static SSDataBlock* sysTableBuildUserTablesByUids(SOperatorInfo* pOperator) {
dengyihao's avatar
dengyihao 已提交
3606 3607
  SExecTaskInfo*     pTaskInfo = pOperator->pTaskInfo;
  SSysTableScanInfo* pInfo = pOperator->info;
3608

dengyihao's avatar
dengyihao 已提交
3609
  SSysTableIndex* pIdx = pInfo->pIdx;
dengyihao's avatar
dengyihao 已提交
3610 3611
  blockDataCleanup(pInfo->pRes);
  int32_t numOfRows = 0;
3612

dengyihao's avatar
dengyihao 已提交
3613
  int ret = 0;
3614

dengyihao's avatar
dengyihao 已提交
3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628
  const char* db = NULL;
  int32_t     vgId = 0;
  vnodeGetInfo(pInfo->readHandle.vnode, &db, &vgId);

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

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

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

dengyihao's avatar
dengyihao 已提交
3629 3630 3631 3632
  char    n[TSDB_TABLE_NAME_LEN + VARSTR_HEADER_SIZE] = {0};
  int32_t i = pIdx->lastIdx;
  for (; i < taosArrayGetSize(pIdx->uids); i++) {
    tb_uid_t* uid = taosArrayGet(pIdx->uids, i);
3633

dengyihao's avatar
dengyihao 已提交
3634
    SMetaReader mr = {0};
dengyihao's avatar
dengyihao 已提交
3635
    metaReaderInit(&mr, pInfo->readHandle.meta, 0);
H
Haojun Liao 已提交
3636
    ret = metaGetTableEntryByUid(&mr, *uid);
dengyihao's avatar
dengyihao 已提交
3637 3638 3639 3640 3641 3642 3643 3644 3645
    if (ret < 0) {
      metaReaderClear(&mr);
      continue;
    }
    STR_TO_VARSTR(n, mr.me.name);

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

dengyihao's avatar
dengyihao 已提交
3647 3648 3649
    // database name
    pColInfoData = taosArrayGet(p->pDataBlock, 1);
    colDataAppend(pColInfoData, numOfRows, dbname, false);
3650

dengyihao's avatar
dengyihao 已提交
3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664
    // vgId
    pColInfoData = taosArrayGet(p->pDataBlock, 6);
    colDataAppend(pColInfoData, numOfRows, (char*)&vgId, false);

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

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

dengyihao's avatar
dengyihao 已提交
3665 3666
      int64_t suid = mr.me.ctbEntry.suid;
      int32_t code = metaGetTableEntryByUid(&mr1, suid);
dengyihao's avatar
dengyihao 已提交
3667 3668 3669 3670
      if (code != TSDB_CODE_SUCCESS) {
        qError("failed to get super table meta, cname:%s, suid:0x%" PRIx64 ", code:%s, %s", pInfo->pCur->mr.me.name,
               suid, tstrerror(terrno), GET_TASKID(pTaskInfo));
        metaReaderClear(&mr1);
dengyihao's avatar
dengyihao 已提交
3671
        metaReaderClear(&mr);
dengyihao's avatar
dengyihao 已提交
3672
        T_LONG_JMP(pTaskInfo->env, terrno);
H
Haojun Liao 已提交
3673
      }
dengyihao's avatar
dengyihao 已提交
3674
      pColInfoData = taosArrayGet(p->pDataBlock, 3);
dengyihao's avatar
dengyihao 已提交
3675
      colDataAppend(pColInfoData, numOfRows, (char*)&mr1.me.stbEntry.schemaRow.nCols, false);
H
Haojun Liao 已提交
3676

dengyihao's avatar
dengyihao 已提交
3677 3678 3679
      // super table name
      STR_TO_VARSTR(n, mr1.me.name);
      pColInfoData = taosArrayGet(p->pDataBlock, 4);
3680
      colDataAppend(pColInfoData, numOfRows, n, false);
dengyihao's avatar
dengyihao 已提交
3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695
      metaReaderClear(&mr1);

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

dengyihao's avatar
dengyihao 已提交
3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721
      // uid
      pColInfoData = taosArrayGet(p->pDataBlock, 5);
      colDataAppend(pColInfoData, numOfRows, (char*)&mr.me.uid, false);

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

      STR_TO_VARSTR(n, "CHILD_TABLE");

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

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

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

      // table comment
      pColInfoData = taosArrayGet(p->pDataBlock, 8);
dengyihao's avatar
dengyihao 已提交
3722
      if (mr.me.ntbEntry.commentLen > 0) {
dengyihao's avatar
dengyihao 已提交
3723
        char comment[TSDB_TB_COMMENT_LEN + VARSTR_HEADER_SIZE] = {0};
dengyihao's avatar
dengyihao 已提交
3724
        STR_TO_VARSTR(comment, mr.me.ntbEntry.comment);
dengyihao's avatar
dengyihao 已提交
3725
        colDataAppend(pColInfoData, numOfRows, comment, false);
dengyihao's avatar
dengyihao 已提交
3726
      } else if (mr.me.ntbEntry.commentLen == 0) {
dengyihao's avatar
dengyihao 已提交
3727 3728 3729 3730 3731 3732
        char comment[VARSTR_HEADER_SIZE + VARSTR_HEADER_SIZE] = {0};
        STR_TO_VARSTR(comment, "");
        colDataAppend(pColInfoData, numOfRows, comment, false);
      } else {
        colDataAppendNULL(pColInfoData, numOfRows);
      }
3733

dengyihao's avatar
dengyihao 已提交
3734 3735
      // uid
      pColInfoData = taosArrayGet(p->pDataBlock, 5);
dengyihao's avatar
dengyihao 已提交
3736
      colDataAppend(pColInfoData, numOfRows, (char*)&mr.me.uid, false);
3737

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

dengyihao's avatar
dengyihao 已提交
3742 3743
      STR_TO_VARSTR(n, "NORMAL_TABLE");
      // impl later
3744
    }
3745

dengyihao's avatar
dengyihao 已提交
3746 3747
    metaReaderClear(&mr);

dengyihao's avatar
dengyihao 已提交
3748 3749 3750 3751
    pColInfoData = taosArrayGet(p->pDataBlock, 9);
    colDataAppend(pColInfoData, numOfRows, n, false);

    if (++numOfRows >= pOperator->resultInfo.capacity) {
3752 3753 3754
      p->info.rows = numOfRows;
      pInfo->pRes->info.rows = numOfRows;

H
Haojun Liao 已提交
3755
      relocateColumnData(pInfo->pRes, pInfo->matchInfo.pList, p->pDataBlock, false);
H
Haojun Liao 已提交
3756
      doFilterResult(pInfo->pRes, pOperator->exprSupp.pFilterInfo);
3757 3758 3759

      blockDataCleanup(p);
      numOfRows = 0;
dengyihao's avatar
dengyihao 已提交
3760 3761 3762 3763

      if (pInfo->pRes->info.rows > 0) {
        break;
      }
3764
    }
dengyihao's avatar
dengyihao 已提交
3765
  }
3766

dengyihao's avatar
dengyihao 已提交
3767 3768 3769
  if (numOfRows > 0) {
    p->info.rows = numOfRows;
    pInfo->pRes->info.rows = numOfRows;
3770

H
Haojun Liao 已提交
3771
    relocateColumnData(pInfo->pRes, pInfo->matchInfo.pList, p->pDataBlock, false);
H
Haojun Liao 已提交
3772
    doFilterResult(pInfo->pRes, pOperator->exprSupp.pFilterInfo);
dengyihao's avatar
dengyihao 已提交
3773 3774 3775 3776 3777

    blockDataCleanup(p);
    numOfRows = 0;
  }

dengyihao's avatar
dengyihao 已提交
3778
  if (i >= taosArrayGetSize(pIdx->uids)) {
H
Haojun Liao 已提交
3779
    setOperatorCompleted(pOperator);
dengyihao's avatar
dengyihao 已提交
3780
  } else {
dengyihao's avatar
dengyihao 已提交
3781
    pIdx->lastIdx = i + 1;
dengyihao's avatar
dengyihao 已提交
3782
  }
dengyihao's avatar
dengyihao 已提交
3783

dengyihao's avatar
dengyihao 已提交
3784
  blockDataDestroy(p);
dengyihao's avatar
dengyihao 已提交
3785 3786 3787 3788

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

dengyihao's avatar
dengyihao 已提交
3790
static SSDataBlock* sysTableBuildUserTables(SOperatorInfo* pOperator) {
dengyihao's avatar
dengyihao 已提交
3791 3792
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;

H
Haojun Liao 已提交
3793
  SSysTableScanInfo* pInfo = pOperator->info;
dengyihao's avatar
dengyihao 已提交
3794 3795
  if (pInfo->pCur == NULL) {
    pInfo->pCur = metaOpenTbCursor(pInfo->readHandle.meta);
3796
  }
H
Haojun Liao 已提交
3797

dengyihao's avatar
dengyihao 已提交
3798 3799
  blockDataCleanup(pInfo->pRes);
  int32_t numOfRows = 0;
3800

dengyihao's avatar
dengyihao 已提交
3801 3802 3803
  const char* db = NULL;
  int32_t     vgId = 0;
  vnodeGetInfo(pInfo->readHandle.vnode, &db, &vgId);
3804

dengyihao's avatar
dengyihao 已提交
3805 3806 3807
  SName sn = {0};
  char  dbname[TSDB_DB_FNAME_LEN + VARSTR_HEADER_SIZE] = {0};
  tNameFromString(&sn, db, T_NAME_ACCT | T_NAME_DB);
3808

dengyihao's avatar
dengyihao 已提交
3809 3810
  tNameGetDbName(&sn, varDataVal(dbname));
  varDataSetLen(dbname, strlen(varDataVal(dbname)));
3811

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

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

dengyihao's avatar
dengyihao 已提交
3817 3818 3819
  int32_t ret = 0;
  while ((ret = metaTbCursorNext(pInfo->pCur)) == 0) {
    STR_TO_VARSTR(n, pInfo->pCur->mr.me.name);
3820

dengyihao's avatar
dengyihao 已提交
3821 3822 3823
    // table name
    SColumnInfoData* pColInfoData = taosArrayGet(p->pDataBlock, 0);
    colDataAppend(pColInfoData, numOfRows, n, false);
3824

dengyihao's avatar
dengyihao 已提交
3825 3826 3827
    // database name
    pColInfoData = taosArrayGet(p->pDataBlock, 1);
    colDataAppend(pColInfoData, numOfRows, dbname, false);
3828

dengyihao's avatar
dengyihao 已提交
3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847
    // vgId
    pColInfoData = taosArrayGet(p->pDataBlock, 6);
    colDataAppend(pColInfoData, numOfRows, (char*)&vgId, false);

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

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

      uint64_t suid = pInfo->pCur->mr.me.ctbEntry.suid;
      int32_t  code = metaGetTableEntryByUid(&mr, suid);
      if (code != TSDB_CODE_SUCCESS) {
        qError("failed to get super table meta, cname:%s, suid:0x%" PRIx64 ", code:%s, %s", pInfo->pCur->mr.me.name,
               suid, tstrerror(terrno), GET_TASKID(pTaskInfo));
3848
        metaReaderClear(&mr);
dengyihao's avatar
dengyihao 已提交
3849 3850 3851 3852
        metaCloseTbCursor(pInfo->pCur);
        pInfo->pCur = NULL;
        T_LONG_JMP(pTaskInfo->env, terrno);
      }
3853

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

dengyihao's avatar
dengyihao 已提交
3858 3859 3860 3861 3862
      // super table name
      STR_TO_VARSTR(n, mr.me.name);
      pColInfoData = taosArrayGet(p->pDataBlock, 4);
      colDataAppend(pColInfoData, numOfRows, n, false);
      metaReaderClear(&mr);
3863

dengyihao's avatar
dengyihao 已提交
3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874
      // table comment
      pColInfoData = taosArrayGet(p->pDataBlock, 8);
      if (pInfo->pCur->mr.me.ctbEntry.commentLen > 0) {
        char comment[TSDB_TB_COMMENT_LEN + VARSTR_HEADER_SIZE] = {0};
        STR_TO_VARSTR(comment, pInfo->pCur->mr.me.ctbEntry.comment);
        colDataAppend(pColInfoData, numOfRows, comment, false);
      } else if (pInfo->pCur->mr.me.ctbEntry.commentLen == 0) {
        char comment[VARSTR_HEADER_SIZE + VARSTR_HEADER_SIZE] = {0};
        STR_TO_VARSTR(comment, "");
        colDataAppend(pColInfoData, numOfRows, comment, false);
      } else {
3875
        colDataAppendNULL(pColInfoData, numOfRows);
H
Haojun Liao 已提交
3876 3877
      }

dengyihao's avatar
dengyihao 已提交
3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912
      // uid
      pColInfoData = taosArrayGet(p->pDataBlock, 5);
      colDataAppend(pColInfoData, numOfRows, (char*)&pInfo->pCur->mr.me.uid, false);

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

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

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

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

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

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

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

dengyihao's avatar
dengyihao 已提交
3922
      STR_TO_VARSTR(n, "NORMAL_TABLE");
3923
    }
H
Haojun Liao 已提交
3924

dengyihao's avatar
dengyihao 已提交
3925 3926 3927 3928
    pColInfoData = taosArrayGet(p->pDataBlock, 9);
    colDataAppend(pColInfoData, numOfRows, n, false);

    if (++numOfRows >= pOperator->resultInfo.capacity) {
3929 3930 3931
      p->info.rows = numOfRows;
      pInfo->pRes->info.rows = numOfRows;

H
Haojun Liao 已提交
3932
      relocateColumnData(pInfo->pRes, pInfo->matchInfo.pList, p->pDataBlock, false);
H
Haojun Liao 已提交
3933
      doFilterResult(pInfo->pRes, pOperator->exprSupp.pFilterInfo);
3934 3935 3936

      blockDataCleanup(p);
      numOfRows = 0;
dengyihao's avatar
dengyihao 已提交
3937 3938 3939 3940

      if (pInfo->pRes->info.rows > 0) {
        break;
      }
3941
    }
dengyihao's avatar
dengyihao 已提交
3942
  }
3943

dengyihao's avatar
dengyihao 已提交
3944 3945 3946
  if (numOfRows > 0) {
    p->info.rows = numOfRows;
    pInfo->pRes->info.rows = numOfRows;
3947

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

dengyihao's avatar
dengyihao 已提交
3951 3952 3953 3954 3955 3956 3957 3958 3959 3960
    blockDataCleanup(p);
    numOfRows = 0;
  }

  blockDataDestroy(p);

  // todo temporarily free the cursor here, the true reason why the free is not valid needs to be found
  if (ret != 0) {
    metaCloseTbCursor(pInfo->pCur);
    pInfo->pCur = NULL;
H
Haojun Liao 已提交
3961
    setOperatorCompleted(pOperator);
dengyihao's avatar
dengyihao 已提交
3962 3963 3964 3965 3966
  }

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

dengyihao's avatar
dengyihao 已提交
3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979
static SSDataBlock* sysTableScanUserTables(SOperatorInfo* pOperator) {
  SExecTaskInfo*     pTaskInfo = pOperator->pTaskInfo;
  SSysTableScanInfo* pInfo = pOperator->info;

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

  // the retrieve is executed on the mnode, so return tables that belongs to the information schema database.
  if (pInfo->readHandle.mnd != NULL) {
    buildSysDbTableInfo(pInfo, pOperator->resultInfo.capacity);
H
Haojun Liao 已提交
3980
    doFilterResult(pInfo->pRes, pOperator->exprSupp.pFilterInfo);
3981
    pInfo->loadInfo.totalRows += pInfo->pRes->info.rows;
dengyihao's avatar
dengyihao 已提交
3982

H
Haojun Liao 已提交
3983
    setOperatorCompleted(pOperator);
3984
    return (pInfo->pRes->info.rows == 0) ? NULL : pInfo->pRes;
dengyihao's avatar
dengyihao 已提交
3985
  } else {
dengyihao's avatar
dengyihao 已提交
3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009
    if (pInfo->showRewrite == false) {
      if (pCondition != NULL && pInfo->pIdx == NULL) {
        SSTabFltArg arg = {.pMeta = pInfo->readHandle.meta, .pVnode = pInfo->readHandle.vnode};

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

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

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

dengyihao's avatar
dengyihao 已提交
4015
    return sysTableBuildUserTables(pOperator);
4016
  }
dengyihao's avatar
dengyihao 已提交
4017
  return NULL;
4018 4019
}

4020 4021 4022 4023 4024 4025 4026 4027
static SSDataBlock* sysTableScanUserSTables(SOperatorInfo* pOperator) {
  SExecTaskInfo*     pTaskInfo = pOperator->pTaskInfo;
  SSysTableScanInfo* pInfo = pOperator->info;
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

  pInfo->pRes->info.rows = 0;
D
dapan1121 已提交
4028
  pOperator->status = OP_EXEC_DONE;
4029 4030 4031 4032 4033

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

4034 4035 4036 4037
static SSDataBlock* doSysTableScan(SOperatorInfo* pOperator) {
  // build message and send to mnode to fetch the content of system tables.
  SExecTaskInfo*     pTaskInfo = pOperator->pTaskInfo;
  SSysTableScanInfo* pInfo = pOperator->info;
L
Liu Jicong 已提交
4038
  char               dbName[TSDB_DB_NAME_LEN] = {0};
4039 4040

  const char* name = tNameGetTableName(&pInfo->name);
D
dapan1121 已提交
4041 4042 4043 4044
  if (pInfo->showRewrite) {
    getDBNameFromCondition(pInfo->pCondition, dbName);
    sprintf(pInfo->req.db, "%d.%s", pInfo->accountId, dbName);
  }
H
Hongze Cheng 已提交
4045

D
dapan1121 已提交
4046
  if (strncasecmp(name, TSDB_INS_TABLE_TABLES, TSDB_TABLE_FNAME_LEN) == 0) {
4047
    return sysTableScanUserTables(pOperator);
D
dapan1121 已提交
4048
  } else if (strncasecmp(name, TSDB_INS_TABLE_TAGS, TSDB_TABLE_FNAME_LEN) == 0) {
4049
    return sysTableScanUserTags(pOperator);
L
Liu Jicong 已提交
4050 4051
  } else if (strncasecmp(name, TSDB_INS_TABLE_STABLES, TSDB_TABLE_FNAME_LEN) == 0 && pInfo->showRewrite &&
             IS_SYS_DBNAME(dbName)) {
4052
    return sysTableScanUserSTables(pOperator);
H
Haojun Liao 已提交
4053 4054 4055 4056 4057
  } else {  // load the meta from mnode of the given epset
    if (pOperator->status == OP_EXEC_DONE) {
      return NULL;
    }

4058 4059
    while (1) {
      int64_t startTs = taosGetTimestampUs();
H
Haojun Liao 已提交
4060
      tstrncpy(pInfo->req.tb, tNameGetTableName(&pInfo->name), tListLen(pInfo->req.tb));
H
Haojun Liao 已提交
4061
      tstrncpy(pInfo->req.user, pInfo->pUser, tListLen(pInfo->req.user));
H
Haojun Liao 已提交
4062

4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073
      int32_t contLen = tSerializeSRetrieveTableReq(NULL, 0, &pInfo->req);
      char*   buf1 = taosMemoryCalloc(1, contLen);
      tSerializeSRetrieveTableReq(buf1, contLen, &pInfo->req);

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

L
Liu Jicong 已提交
4075 4076
      int32_t msgType = (strcasecmp(name, TSDB_INS_TABLE_DNODE_VARIABLES) == 0) ? TDMT_DND_SYSTABLE_RETRIEVE
                                                                                : TDMT_MND_SYSTABLE_RETRIEVE;
D
dapan1121 已提交
4077

4078 4079 4080
      pMsgSendInfo->param = pOperator;
      pMsgSendInfo->msgInfo.pData = buf1;
      pMsgSendInfo->msgInfo.len = contLen;
D
dapan1121 已提交
4081
      pMsgSendInfo->msgType = msgType;
4082
      pMsgSendInfo->fp = loadSysTableCallback;
D
dapan1121 已提交
4083
      pMsgSendInfo->requestId = pTaskInfo->id.queryId;
H
Haojun Liao 已提交
4084

4085
      int64_t transporterId = 0;
4086 4087
      int32_t code =
          asyncSendMsgToServer(pInfo->readHandle.pMsgCb->clientRpc, &pInfo->epSet, &transporterId, pMsgSendInfo);
4088
      tsem_wait(&pInfo->ready);
H
Haojun Liao 已提交
4089

4090 4091 4092 4093 4094
      if (pTaskInfo->code) {
        qDebug("%s load meta data from mnode failed, totalRows:%" PRIu64 ", code:%s", GET_TASKID(pTaskInfo),
               pInfo->loadInfo.totalRows, tstrerror(pTaskInfo->code));
        return NULL;
      }
H
Haojun Liao 已提交
4095

4096 4097
      SRetrieveMetaTableRsp* pRsp = pInfo->pRsp;
      pInfo->req.showId = pRsp->handle;
H
Haojun Liao 已提交
4098

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

4104
        if (pRsp->numOfRows == 0) {
H
Haojun Liao 已提交
4105
          taosMemoryFree(pRsp);
4106 4107 4108
          return NULL;
        }
      }
H
Haojun Liao 已提交
4109

4110
      char* pStart = pRsp->data;
H
Haojun Liao 已提交
4111
      extractDataBlockFromFetchRsp(pInfo->pRes, pRsp->data, pInfo->matchInfo.pList, &pStart);
4112
      updateLoadRemoteInfo(&pInfo->loadInfo, pRsp->numOfRows, pRsp->compLen, startTs, pOperator);
H
Haojun Liao 已提交
4113

4114
      // todo log the filter info
H
Haojun Liao 已提交
4115
      doFilterResult(pInfo->pRes, pOperator->exprSupp.pFilterInfo);
H
Haojun Liao 已提交
4116
      taosMemoryFree(pRsp);
4117 4118
      if (pInfo->pRes->info.rows > 0) {
        return pInfo->pRes;
D
dapan1121 已提交
4119 4120
      } else if (pOperator->status == OP_EXEC_DONE) {
        return NULL;
4121
      }
4122
    }
H
Haojun Liao 已提交
4123 4124 4125
  }
}

4126
int32_t buildSysDbTableInfo(const SSysTableScanInfo* pInfo, int32_t capacity) {
D
dapan1121 已提交
4127
  SSDataBlock* p = buildInfoSchemaTableMetaBlock(TSDB_INS_TABLE_TABLES);
4128
  blockDataEnsureCapacity(p, capacity);
4129

L
Liu Jicong 已提交
4130
  size_t               size = 0;
4131 4132 4133
  const SSysTableMeta* pSysDbTableMeta = NULL;

  getInfosDbMeta(&pSysDbTableMeta, &size);
4134
  p->info.rows = buildDbTableInfoBlock(pInfo->sysInfo, p, pSysDbTableMeta, size, TSDB_INFORMATION_SCHEMA_DB);
4135 4136

  getPerfDbMeta(&pSysDbTableMeta, &size);
4137
  p->info.rows = buildDbTableInfoBlock(pInfo->sysInfo, p, pSysDbTableMeta, size, TSDB_PERFORMANCE_SCHEMA_DB);
4138 4139

  pInfo->pRes->info.rows = p->info.rows;
H
Haojun Liao 已提交
4140
  relocateColumnData(pInfo->pRes, pInfo->matchInfo.pList, p->pDataBlock, false);
4141 4142 4143
  blockDataDestroy(p);

  return pInfo->pRes->info.rows;
4144 4145
}

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

L
Liu Jicong 已提交
4151
  for (int32_t i = 0; i < size; ++i) {
4152
    const SSysTableMeta* pm = &pSysDbTableMeta[i];
4153 4154 4155
    if (!sysInfo && pm->sysInfo) {
      continue;
    }
4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174

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

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

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

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

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

L
Liu Jicong 已提交
4175
    for (int32_t j = 4; j <= 8; ++j) {
4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190
      pColInfoData = taosArrayGet(p->pDataBlock, j);
      colDataAppendNULL(pColInfoData, numOfRows);
    }

    STR_TO_VARSTR(n, "SYSTEM_TABLE");

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

    numOfRows += 1;
  }

  return numOfRows;
}

4191
SOperatorInfo* createSysTableScanOperatorInfo(void* readHandle, SSystemTableScanPhysiNode* pScanPhyNode,
4192
                                              const char* pUser, SExecTaskInfo* pTaskInfo) {
H
Haojun Liao 已提交
4193 4194 4195
  SSysTableScanInfo* pInfo = taosMemoryCalloc(1, sizeof(SSysTableScanInfo));
  SOperatorInfo*     pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
  if (pInfo == NULL || pOperator == NULL) {
4196
    goto _error;
H
Haojun Liao 已提交
4197 4198
  }

H
Haojun Liao 已提交
4199
  SScanPhysiNode*     pScanNode = &pScanPhyNode->scan;
4200 4201 4202
  SDataBlockDescNode* pDescNode = pScanNode->node.pOutputDataBlockDesc;

  int32_t num = 0;
H
Haojun Liao 已提交
4203
  int32_t code = extractColMatchInfo(pScanNode->pScanCols, pDescNode, &num, COL_MATCH_FROM_COL_ID, &pInfo->matchInfo);
H
Haojun Liao 已提交
4204 4205 4206
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
4207

4208 4209
  pInfo->accountId = pScanPhyNode->accountId;
  pInfo->pUser = taosMemoryStrDup((void*)pUser);
4210
  pInfo->sysInfo = pScanPhyNode->sysInfo;
4211
  pInfo->showRewrite = pScanPhyNode->showRewrite;
H
Haojun Liao 已提交
4212
  pInfo->pRes = createResDataBlock(pDescNode);
4213

4214
  pInfo->pCondition = pScanNode->node.pConditions;
4215 4216 4217 4218
  code = filterInitFromNode(pScanNode->node.pConditions, &pOperator->exprSupp.pFilterInfo, 0);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
4219

4220
  initResultSizeInfo(&pOperator->resultInfo, 4096);
4221
  blockDataEnsureCapacity(pInfo->pRes, pOperator->resultInfo.capacity);
H
Haojun Liao 已提交
4222

4223
  tNameAssign(&pInfo->name, &pScanNode->tableName);
4224
  const char* name = tNameGetTableName(&pInfo->name);
4225

D
dapan1121 已提交
4226 4227
  if (strncasecmp(name, TSDB_INS_TABLE_TABLES, TSDB_TABLE_FNAME_LEN) == 0 ||
      strncasecmp(name, TSDB_INS_TABLE_TAGS, TSDB_TABLE_FNAME_LEN) == 0) {
L
Liu Jicong 已提交
4228
    pInfo->readHandle = *(SReadHandle*)readHandle;
H
Haojun Liao 已提交
4229 4230
  } else {
    tsem_init(&pInfo->ready, 0, 0);
4231
    pInfo->epSet = pScanPhyNode->mgmtEpSet;
4232
    pInfo->readHandle = *(SReadHandle*)readHandle;
H
Haojun Liao 已提交
4233 4234
  }

L
Liu Jicong 已提交
4235 4236
  setOperatorInfo(pOperator, "SysTableScanOperator", QUERY_NODE_PHYSICAL_PLAN_SYSTABLE_SCAN, false, OP_NOT_OPENED,
                  pInfo, pTaskInfo);
H
Haojun Liao 已提交
4237
  pOperator->exprSupp.numOfExprs = taosArrayGetSize(pInfo->pRes->pDataBlock);
H
Haojun Liao 已提交
4238
  pOperator->fpSet = createOperatorFpSet(operatorDummyOpenFn, doSysTableScan, NULL, destroySysScanOperator, NULL);
H
Haojun Liao 已提交
4239
  return pOperator;
4240

4241
_error:
H
Haojun Liao 已提交
4242 4243 4244
  if (pInfo != NULL) {
    destroySysScanOperator(pInfo);
  }
4245
  taosMemoryFreeClear(pOperator);
4246
  pTaskInfo->code = code;
4247
  return NULL;
H
Haojun Liao 已提交
4248
}
H
Haojun Liao 已提交
4249

4250
static SSDataBlock* doTagScan(SOperatorInfo* pOperator) {
H
Haojun Liao 已提交
4251 4252 4253 4254
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

4255 4256 4257
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;

  STagScanInfo* pInfo = pOperator->info;
4258
  SExprInfo*    pExprInfo = &pOperator->exprSupp.pExprInfo[0];
4259
  SSDataBlock*  pRes = pInfo->pRes;
4260
  blockDataCleanup(pRes);
H
Haojun Liao 已提交
4261

H
Haojun Liao 已提交
4262
  int32_t size = tableListGetSize(pTaskInfo->pTableInfoList);
wmmhello's avatar
wmmhello 已提交
4263
  if (size == 0) {
H
Haojun Liao 已提交
4264 4265 4266 4267
    setTaskStatus(pTaskInfo, TASK_COMPLETED);
    return NULL;
  }

4268 4269 4270
  char        str[512] = {0};
  int32_t     count = 0;
  SMetaReader mr = {0};
4271
  metaReaderInit(&mr, pInfo->readHandle.meta, 0);
H
Haojun Liao 已提交
4272

wmmhello's avatar
wmmhello 已提交
4273
  while (pInfo->curPos < size && count < pOperator->resultInfo.capacity) {
H
Haojun Liao 已提交
4274
    STableKeyInfo* item = tableListGetInfo(pInfo->pTableList, pInfo->curPos);
L
Liu Jicong 已提交
4275
    int32_t        code = metaGetTableEntryByUid(&mr, item->uid);
4276
    tDecoderClear(&mr.coder);
H
Haojun Liao 已提交
4277
    if (code != TSDB_CODE_SUCCESS) {
L
Liu Jicong 已提交
4278 4279
      qError("failed to get table meta, uid:0x%" PRIx64 ", code:%s, %s", item->uid, tstrerror(terrno),
             GET_TASKID(pTaskInfo));
H
Haojun Liao 已提交
4280
      metaReaderClear(&mr);
4281
      T_LONG_JMP(pTaskInfo->env, terrno);
H
Haojun Liao 已提交
4282
    }
H
Haojun Liao 已提交
4283

4284
    for (int32_t j = 0; j < pOperator->exprSupp.numOfExprs; ++j) {
4285 4286 4287 4288 4289 4290
      SColumnInfoData* pDst = taosArrayGet(pRes->pDataBlock, pExprInfo[j].base.resSchema.slotId);

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

4296 4297 4298 4299
        char* data = NULL;
        if (pDst->info.type != TSDB_DATA_TYPE_JSON && p != NULL) {
          data = tTagValToData((const STagVal*)p, false);
        } else {
wmmhello's avatar
wmmhello 已提交
4300 4301
          data = (char*)p;
        }
L
Liu Jicong 已提交
4302 4303
        colDataAppend(pDst, count, data,
                      (data == NULL) || (pDst->info.type == TSDB_DATA_TYPE_JSON && tTagIsJsonNull(data)));
4304

4305 4306
        if (pDst->info.type != TSDB_DATA_TYPE_JSON && p != NULL && IS_VAR_DATA_TYPE(((const STagVal*)p)->type) &&
            data != NULL) {
wmmhello's avatar
wmmhello 已提交
4307
          taosMemoryFree(data);
wmmhello's avatar
wmmhello 已提交
4308
        }
H
Haojun Liao 已提交
4309 4310 4311
      }
    }

4312
    count += 1;
wmmhello's avatar
wmmhello 已提交
4313
    if (++pInfo->curPos >= size) {
H
Haojun Liao 已提交
4314
      setOperatorCompleted(pOperator);
H
Haojun Liao 已提交
4315 4316 4317
    }
  }

4318 4319
  metaReaderClear(&mr);

4320
  // qDebug("QInfo:0x%"PRIx64" create tag values results completed, rows:%d", GET_TASKID(pRuntimeEnv), count);
H
Haojun Liao 已提交
4321
  if (pOperator->status == OP_EXEC_DONE) {
4322
    setTaskStatus(pTaskInfo, TASK_COMPLETED);
H
Haojun Liao 已提交
4323 4324 4325
  }

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

4328
  return (pRes->info.rows == 0) ? NULL : pInfo->pRes;
H
Haojun Liao 已提交
4329 4330
}

4331
static void destroyTagScanOperatorInfo(void* param) {
H
Haojun Liao 已提交
4332 4333
  STagScanInfo* pInfo = (STagScanInfo*)param;
  pInfo->pRes = blockDataDestroy(pInfo->pRes);
H
Haojun Liao 已提交
4334
  taosArrayDestroy(pInfo->matchInfo.pList);
D
dapan1121 已提交
4335
  taosMemoryFreeClear(param);
H
Haojun Liao 已提交
4336 4337
}

4338 4339
SOperatorInfo* createTagScanOperatorInfo(SReadHandle* pReadHandle, STagScanPhysiNode* pPhyNode,
                                         STableListInfo* pTableListInfo, SExecTaskInfo* pTaskInfo) {
4340
  STagScanInfo*  pInfo = taosMemoryCalloc(1, sizeof(STagScanInfo));
H
Haojun Liao 已提交
4341 4342 4343 4344 4345
  SOperatorInfo* pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }

4346 4347 4348 4349
  SDataBlockDescNode* pDescNode = pPhyNode->node.pOutputDataBlockDesc;

  int32_t    numOfExprs = 0;
  SExprInfo* pExprInfo = createExprInfo(pPhyNode->pScanPseudoCols, NULL, &numOfExprs);
4350
  int32_t    code = initExprSupp(&pOperator->exprSupp, pExprInfo, numOfExprs);
4351 4352 4353
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
4354

H
Haojun Liao 已提交
4355 4356
  int32_t num = 0;
  code = extractColMatchInfo(pPhyNode->pScanPseudoCols, pDescNode, &num, COL_MATCH_FROM_COL_ID, &pInfo->matchInfo);
4357 4358 4359
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
4360

4361 4362 4363 4364
  pInfo->pTableList = pTableListInfo;
  pInfo->pRes = createResDataBlock(pDescNode);
  pInfo->readHandle = *pReadHandle;
  pInfo->curPos = 0;
4365

L
Liu Jicong 已提交
4366 4367
  setOperatorInfo(pOperator, "TagScanOperator", QUERY_NODE_PHYSICAL_PLAN_TAG_SCAN, false, OP_NOT_OPENED, pInfo,
                  pTaskInfo);
4368
  initResultSizeInfo(&pOperator->resultInfo, 4096);
4369 4370
  blockDataEnsureCapacity(pInfo->pRes, pOperator->resultInfo.capacity);

H
Haojun Liao 已提交
4371
  pOperator->fpSet = createOperatorFpSet(operatorDummyOpenFn, doTagScan, NULL, destroyTagScanOperatorInfo, NULL);
H
Haojun Liao 已提交
4372 4373

  return pOperator;
4374

4375
_error:
H
Haojun Liao 已提交
4376 4377 4378 4379 4380
  taosMemoryFree(pInfo);
  taosMemoryFree(pOperator);
  terrno = TSDB_CODE_OUT_OF_MEMORY;
  return NULL;
}
4381

dengyihao's avatar
dengyihao 已提交
4382
static SSDataBlock* getTableDataBlockImpl(void* param) {
dengyihao's avatar
opt mem  
dengyihao 已提交
4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395
  STableMergeScanSortSourceParam* source = param;
  SOperatorInfo*                  pOperator = source->pOperator;
  STableMergeScanInfo*            pInfo = pOperator->info;
  SExecTaskInfo*                  pTaskInfo = pOperator->pTaskInfo;
  int32_t                         readIdx = source->readerIdx;
  SSDataBlock*                    pBlock = source->inputBlock;
  STableMergeScanInfo*            pTableScanInfo = pOperator->info;

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

  int64_t st = taosGetTimestampUs();

H
Haojun Liao 已提交
4396
  void*        p = tableListGetInfo(pTaskInfo->pTableInfoList, readIdx + pInfo->tableStartIndex);
H
Haojun Liao 已提交
4397
  SReadHandle* pHandle = &pInfo->base.readHandle;
dengyihao's avatar
dengyihao 已提交
4398

H
Haojun Liao 已提交
4399
  int32_t code = tsdbReaderOpen(pHandle->vnode, pQueryCond, p, 1, &pInfo->base.dataReader, GET_TASKID(pTaskInfo));
dengyihao's avatar
dengyihao 已提交
4400
  if (code != 0) {
H
Haojun Liao 已提交
4401
    T_LONG_JMP(pTaskInfo->env, code);
dengyihao's avatar
dengyihao 已提交
4402
  }
dengyihao's avatar
opt mem  
dengyihao 已提交
4403

H
Haojun Liao 已提交
4404
  STsdbReader* reader = pInfo->base.dataReader;
dengyihao's avatar
opt mem  
dengyihao 已提交
4405
  while (tsdbNextDataBlock(reader)) {
H
Haojun Liao 已提交
4406 4407
    if (isTaskKilled(pTaskInfo)) {
      T_LONG_JMP(pTaskInfo->env, TSDB_CODE_TSC_QUERY_CANCELLED);
dengyihao's avatar
opt mem  
dengyihao 已提交
4408 4409 4410 4411 4412 4413 4414 4415 4416 4417
    }

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

    blockDataCleanup(pBlock);

H
Haojun Liao 已提交
4418 4419 4420 4421
    int32_t rows = 0;
    tsdbRetrieveDataBlockInfo(reader, &rows, &pBlock->info.uid, &pBlock->info.window);
    blockDataEnsureCapacity(pBlock, rows);
    pBlock->info.rows = rows;
dengyihao's avatar
opt mem  
dengyihao 已提交
4422

H
Haojun Liao 已提交
4423
    if (pQueryCond->order == TSDB_ORDER_ASC) {
dengyihao's avatar
opt mem  
dengyihao 已提交
4424 4425 4426 4427
      pQueryCond->twindows.skey = pBlock->info.window.ekey + 1;
    } else {
      pQueryCond->twindows.ekey = pBlock->info.window.skey - 1;
    }
dengyihao's avatar
opt mem  
dengyihao 已提交
4428 4429

    uint32_t status = 0;
H
Haojun Liao 已提交
4430 4431
    loadDataBlock(pOperator, &pTableScanInfo->base, pBlock, &status);
//    code = loadDataBlockFromOneTable(pOperator, pTableScanInfo, pBlock, &status);
dengyihao's avatar
opt mem  
dengyihao 已提交
4432
    if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
4433
      T_LONG_JMP(pTaskInfo->env, code);
dengyihao's avatar
opt mem  
dengyihao 已提交
4434 4435 4436 4437 4438 4439 4440
    }

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

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

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

H
Haojun Liao 已提交
4446 4447
    tsdbReaderClose(pInfo->base.dataReader);
    pInfo->base.dataReader = NULL;
dengyihao's avatar
opt mem  
dengyihao 已提交
4448 4449
    return pBlock;
  }
H
Haojun Liao 已提交
4450

H
Haojun Liao 已提交
4451 4452
  tsdbReaderClose(pInfo->base.dataReader);
  pInfo->base.dataReader = NULL;
dengyihao's avatar
opt mem  
dengyihao 已提交
4453 4454 4455
  return NULL;
}

4456 4457 4458
SArray* generateSortByTsInfo(SArray* colMatchInfo, int32_t order) {
  int32_t tsTargetSlotId = 0;
  for (int32_t i = 0; i < taosArrayGetSize(colMatchInfo); ++i) {
H
Haojun Liao 已提交
4459
    SColMatchItem* colInfo = taosArrayGet(colMatchInfo, i);
4460
    if (colInfo->colId == PRIMARYKEY_TIMESTAMP_COL_ID) {
H
Haojun Liao 已提交
4461
      tsTargetSlotId = colInfo->dstSlotId;
4462 4463 4464
    }
  }

4465 4466 4467
  SArray*         pList = taosArrayInit(1, sizeof(SBlockOrderInfo));
  SBlockOrderInfo bi = {0};
  bi.order = order;
4468
  bi.slotId = tsTargetSlotId;
4469 4470 4471 4472 4473 4474 4475
  bi.nullFirst = NULL_ORDER_FIRST;

  taosArrayPush(pList, &bi);

  return pList;
}

dengyihao's avatar
opt mem  
dengyihao 已提交
4476 4477 4478 4479 4480 4481 4482 4483
int32_t dumpSQueryTableCond(const SQueryTableDataCond* src, SQueryTableDataCond* dst) {
  memcpy((void*)dst, (void*)src, sizeof(SQueryTableDataCond));
  dst->colList = taosMemoryCalloc(src->numOfCols, sizeof(SColumnInfo));
  for (int i = 0; i < src->numOfCols; i++) {
    dst->colList[i] = src->colList[i];
  }
  return 0;
}
H
Haojun Liao 已提交
4484

4485
int32_t startGroupTableMergeScan(SOperatorInfo* pOperator) {
4486 4487 4488
  STableMergeScanInfo* pInfo = pOperator->info;
  SExecTaskInfo*       pTaskInfo = pOperator->pTaskInfo;

S
slzhou 已提交
4489
  {
H
Haojun Liao 已提交
4490
    size_t  numOfTables = tableListGetSize(pTaskInfo->pTableInfoList);
S
slzhou 已提交
4491
    int32_t i = pInfo->tableStartIndex + 1;
H
Haojun Liao 已提交
4492
    for (; i < numOfTables; ++i) {
H
Haojun Liao 已提交
4493
      STableKeyInfo* tableKeyInfo = tableListGetInfo(pTaskInfo->pTableInfoList, i);
S
slzhou 已提交
4494 4495 4496 4497 4498 4499
      if (tableKeyInfo->groupId != pInfo->groupId) {
        break;
      }
    }
    pInfo->tableEndIndex = i - 1;
  }
4500

S
slzhou 已提交
4501 4502
  int32_t tableStartIdx = pInfo->tableStartIndex;
  int32_t tableEndIdx = pInfo->tableEndIndex;
4503

H
Haojun Liao 已提交
4504
  pInfo->base.dataReader = NULL;
4505

4506 4507
  // 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 已提交
4508
  pInfo->sortBufSize = pInfo->bufPageSize * (tableEndIdx - tableStartIdx + 1 + 1);
4509
  int32_t numOfBufPage = pInfo->sortBufSize / pInfo->bufPageSize;
L
Liu Jicong 已提交
4510 4511
  pInfo->pSortHandle = tsortCreateSortHandle(pInfo->pSortInfo, SORT_MULTISOURCE_MERGE, pInfo->bufPageSize, numOfBufPage,
                                             pInfo->pSortInputBlock, pTaskInfo->id.str);
4512

dengyihao's avatar
dengyihao 已提交
4513
  tsortSetFetchRawDataFp(pInfo->pSortHandle, getTableDataBlockImpl, NULL, NULL);
dengyihao's avatar
opt mem  
dengyihao 已提交
4514 4515 4516 4517 4518 4519

  // 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) {
4520 4521 4522 4523 4524
    STableMergeScanSortSourceParam param = {0};
    param.readerIdx = i;
    param.pOperator = pOperator;
    param.inputBlock = createOneDataBlock(pInfo->pResBlock, false);
    taosArrayPush(pInfo->sortSourceParams, &param);
dengyihao's avatar
opt mem  
dengyihao 已提交
4525 4526

    SQueryTableDataCond cond;
H
Haojun Liao 已提交
4527
    dumpSQueryTableCond(&pInfo->base.cond, &cond);
dengyihao's avatar
opt mem  
dengyihao 已提交
4528
    taosArrayPush(pInfo->queryConds, &cond);
4529 4530
  }

dengyihao's avatar
opt mem  
dengyihao 已提交
4531
  for (int32_t i = 0; i < numOfTable; ++i) {
4532
    SSortSource*                    ps = taosMemoryCalloc(1, sizeof(SSortSource));
4533
    STableMergeScanSortSourceParam* param = taosArrayGet(pInfo->sortSourceParams, i);
4534 4535 4536 4537 4538 4539 4540
    ps->param = param;
    tsortAddSource(pInfo->pSortHandle, ps);
  }

  int32_t code = tsortOpen(pInfo->pSortHandle);

  if (code != TSDB_CODE_SUCCESS) {
4541
    T_LONG_JMP(pTaskInfo->env, terrno);
4542 4543
  }

4544 4545 4546 4547 4548 4549 4550
  return TSDB_CODE_SUCCESS;
}

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

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

4553 4554 4555 4556 4557 4558 4559
  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 已提交
4560
  for (int32_t i = 0; i < numOfTable; ++i) {
4561 4562 4563
    STableMergeScanSortSourceParam* param = taosArrayGet(pInfo->sortSourceParams, i);
    blockDataDestroy(param->inputBlock);
  }
4564 4565
  taosArrayClear(pInfo->sortSourceParams);

4566
  tsortDestroySortHandle(pInfo->pSortHandle);
dengyihao's avatar
dengyihao 已提交
4567
  pInfo->pSortHandle = NULL;
4568

dengyihao's avatar
opt mem  
dengyihao 已提交
4569 4570 4571
  for (int32_t i = 0; i < taosArrayGetSize(pInfo->queryConds); i++) {
    SQueryTableDataCond* cond = taosArrayGet(pInfo->queryConds, i);
    taosMemoryFree(cond->colList);
4572
  }
dengyihao's avatar
opt mem  
dengyihao 已提交
4573 4574 4575
  taosArrayDestroy(pInfo->queryConds);
  pInfo->queryConds = NULL;

4576 4577 4578
  return TSDB_CODE_SUCCESS;
}

L
Liu Jicong 已提交
4579 4580
SSDataBlock* getSortedTableMergeScanBlockData(SSortHandle* pHandle, SSDataBlock* pResBlock, int32_t capacity,
                                              SOperatorInfo* pOperator) {
4581 4582 4583
  STableMergeScanInfo* pInfo = pOperator->info;
  SExecTaskInfo*       pTaskInfo = pOperator->pTaskInfo;

4584
  blockDataCleanup(pResBlock);
4585 4586

  while (1) {
4587
    STupleHandle* pTupleHandle = tsortNextTuple(pHandle);
4588 4589 4590 4591
    if (pTupleHandle == NULL) {
      break;
    }

4592 4593
    appendOneRowToDataBlock(pResBlock, pTupleHandle);
    if (pResBlock->info.rows >= capacity) {
4594 4595 4596 4597
      break;
    }
  }

4598
  qDebug("%s get sorted row blocks, rows:%d", GET_TASKID(pTaskInfo), pResBlock->info.rows);
4599 4600 4601
  applyLimitOffset(&pInfo->limitInfo, pResBlock, pTaskInfo, pOperator);
  pInfo->limitInfo.numOfOutputRows += pResBlock->info.rows;

4602
  return (pResBlock->info.rows > 0) ? pResBlock : NULL;
4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614
}

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) {
4615
    T_LONG_JMP(pTaskInfo->env, code);
4616
  }
4617

H
Haojun Liao 已提交
4618
  size_t tableListSize = tableListGetSize(pTaskInfo->pTableInfoList);
S
slzhou 已提交
4619 4620
  if (!pInfo->hasGroupId) {
    pInfo->hasGroupId = true;
4621

S
slzhou 已提交
4622
    if (tableListSize == 0) {
H
Haojun Liao 已提交
4623
      setOperatorCompleted(pOperator);
4624 4625
      return NULL;
    }
S
slzhou 已提交
4626
    pInfo->tableStartIndex = 0;
H
Haojun Liao 已提交
4627
    pInfo->groupId = ((STableKeyInfo*)tableListGetInfo(pTaskInfo->pTableInfoList, pInfo->tableStartIndex))->groupId;
4628 4629
    startGroupTableMergeScan(pOperator);
  }
4630

S
slzhou 已提交
4631 4632
  SSDataBlock* pBlock = NULL;
  while (pInfo->tableStartIndex < tableListSize) {
L
Liu Jicong 已提交
4633 4634
    pBlock = getSortedTableMergeScanBlockData(pInfo->pSortHandle, pInfo->pResBlock, pOperator->resultInfo.capacity,
                                              pOperator);
S
slzhou 已提交
4635 4636 4637 4638 4639 4640 4641
    if (pBlock != NULL) {
      pBlock->info.groupId = pInfo->groupId;
      pOperator->resultInfo.totalRows += pBlock->info.rows;
      return pBlock;
    } else {
      stopGroupTableMergeScan(pOperator);
      if (pInfo->tableEndIndex >= tableListSize - 1) {
H
Haojun Liao 已提交
4642
        setOperatorCompleted(pOperator);
S
slzhou 已提交
4643 4644 4645
        break;
      }
      pInfo->tableStartIndex = pInfo->tableEndIndex + 1;
H
Haojun Liao 已提交
4646
      pInfo->groupId = tableListGetInfo(pTaskInfo->pTableInfoList, pInfo->tableStartIndex)->groupId;
S
slzhou 已提交
4647 4648
      startGroupTableMergeScan(pOperator);
    }
wmmhello's avatar
wmmhello 已提交
4649 4650
  }

4651 4652 4653
  return pBlock;
}

4654
void destroyTableMergeScanOperatorInfo(void* param) {
4655
  STableMergeScanInfo* pTableScanInfo = (STableMergeScanInfo*)param;
H
Haojun Liao 已提交
4656
  cleanupQueryTableDataCond(&pTableScanInfo->base.cond);
4657

dengyihao's avatar
dengyihao 已提交
4658 4659 4660
  int32_t numOfTable = taosArrayGetSize(pTableScanInfo->queryConds);

  for (int32_t i = 0; i < numOfTable; i++) {
H
Haojun Liao 已提交
4661 4662
    STableMergeScanSortSourceParam* p = taosArrayGet(pTableScanInfo->sortSourceParams, i);
    blockDataDestroy(p->inputBlock);
4663
  }
H
Haojun Liao 已提交
4664

4665
  taosArrayDestroy(pTableScanInfo->sortSourceParams);
dengyihao's avatar
dengyihao 已提交
4666 4667
  tsortDestroySortHandle(pTableScanInfo->pSortHandle);
  pTableScanInfo->pSortHandle = NULL;
4668

H
Haojun Liao 已提交
4669 4670
  tsdbReaderClose(pTableScanInfo->base.dataReader);
  pTableScanInfo->base.dataReader = NULL;
dengyihao's avatar
opt mem  
dengyihao 已提交
4671

dengyihao's avatar
opt mem  
dengyihao 已提交
4672 4673 4674
  for (int i = 0; i < taosArrayGetSize(pTableScanInfo->queryConds); i++) {
    SQueryTableDataCond* pCond = taosArrayGet(pTableScanInfo->queryConds, i);
    taosMemoryFree(pCond->colList);
4675
  }
dengyihao's avatar
opt mem  
dengyihao 已提交
4676
  taosArrayDestroy(pTableScanInfo->queryConds);
4677

H
Haojun Liao 已提交
4678 4679
  if (pTableScanInfo->base.matchInfo.pList != NULL) {
    taosArrayDestroy(pTableScanInfo->base.matchInfo.pList);
4680 4681 4682 4683 4684 4685
  }

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

  taosArrayDestroy(pTableScanInfo->pSortInfo);
H
Haojun Liao 已提交
4686
  cleanupExprSupp(&pTableScanInfo->base.pseudoSup);
L
Liu Jicong 已提交
4687

H
Haojun Liao 已提交
4688 4689 4690 4691
  tsdbReaderClose(pTableScanInfo->base.dataReader);
  pTableScanInfo->base.dataReader = NULL;
  taosLRUCacheCleanup(pTableScanInfo->base.metaCache.pTableMetaEntryCache);

D
dapan1121 已提交
4692
  taosMemoryFreeClear(param);
4693 4694 4695 4696
}

int32_t getTableMergeScanExplainExecInfo(SOperatorInfo* pOptr, void** pOptrExplain, uint32_t* len) {
  ASSERT(pOptr != NULL);
4697 4698
  // TODO: merge these two info into one struct
  STableMergeScanExecInfo* execInfo = taosMemoryCalloc(1, sizeof(STableMergeScanExecInfo));
L
Liu Jicong 已提交
4699
  STableMergeScanInfo*     pInfo = pOptr->info;
H
Haojun Liao 已提交
4700
  execInfo->blockRecorder = pInfo->base.readRecorder;
4701
  execInfo->sortExecInfo = pInfo->sortExecInfo;
4702 4703 4704

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

4706 4707 4708
  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
4709 4710
SOperatorInfo* createTableMergeScanOperatorInfo(STableScanPhysiNode* pTableScanNode, SReadHandle* readHandle,
                                                SExecTaskInfo* pTaskInfo) {
4711 4712 4713 4714 4715
  STableMergeScanInfo* pInfo = taosMemoryCalloc(1, sizeof(STableMergeScanInfo));
  SOperatorInfo*       pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }
4716

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

  int32_t numOfCols = 0;
4720
  int32_t code = extractColMatchInfo(pTableScanNode->scan.pScanCols, pDescNode, &numOfCols, COL_MATCH_FROM_COL_ID,
H
Haojun Liao 已提交
4721
                                     &pInfo->base.matchInfo);
H
Haojun Liao 已提交
4722 4723 4724
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
4725

H
Haojun Liao 已提交
4726
  code = initQueryTableDataCond(&pInfo->base.cond, pTableScanNode);
4727
  if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
4728
    taosArrayDestroy(pInfo->base.matchInfo.pList);
4729 4730 4731 4732
    goto _error;
  }

  if (pTableScanNode->scan.pScanPseudoCols != NULL) {
H
Haojun Liao 已提交
4733
    SExprSupp* pSup = &pInfo->base.pseudoSup;
4734 4735
    pSup->pExprInfo = createExprInfo(pTableScanNode->scan.pScanPseudoCols, NULL, &pSup->numOfExprs);
    pSup->pCtx = createSqlFunctionCtx(pSup->pExprInfo, pSup->numOfExprs, &pSup->rowEntryInfoOffset);
4736 4737 4738 4739
  }

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

H
Haojun Liao 已提交
4740 4741 4742 4743 4744 4745
  pInfo->base.metaCache.pTableMetaEntryCache = taosLRUCacheInit(1024 * 128, -1, .5);
  if (pInfo->base.metaCache.pTableMetaEntryCache == NULL) {
    code = terrno;
    goto _error;
  }

H
Haojun Liao 已提交
4746 4747
  pInfo->base.dataBlockLoadFlag = FUNC_DATA_REQUIRED_DATA_LOAD;
  pInfo->base.scanFlag = MAIN_SCAN;
H
Haojun Liao 已提交
4748
  pInfo->base.readHandle = *readHandle;
4749 4750 4751

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

4753
  pInfo->sample.sampleRatio = pTableScanNode->ratio;
L
Liu Jicong 已提交
4754
  pInfo->sample.seed = taosGetTimestampSec();
H
Haojun Liao 已提交
4755 4756 4757 4758 4759 4760

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

4761

H
Haojun Liao 已提交
4762
  initResultSizeInfo(&pOperator->resultInfo, 1024);
4763
  pInfo->pResBlock = createResDataBlock(pDescNode);
H
Haojun Liao 已提交
4764 4765
  blockDataEnsureCapacity(pInfo->pResBlock, pOperator->resultInfo.capacity);

4766
  pInfo->sortSourceParams = taosArrayInit(64, sizeof(STableMergeScanSortSourceParam));
4767

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

dengyihao's avatar
dengyihao 已提交
4772
  int32_t  rowSize = pInfo->pResBlock->info.rowSize;
A
Alex Duan 已提交
4773 4774
  uint32_t nCols = taosArrayGetSize(pInfo->pResBlock->pDataBlock);
  pInfo->bufPageSize = getProperSortPageSize(rowSize, nCols);
4775

L
Liu Jicong 已提交
4776 4777
  setOperatorInfo(pOperator, "TableMergeScanOperator", QUERY_NODE_PHYSICAL_PLAN_TABLE_MERGE_SCAN, false, OP_NOT_OPENED,
                  pInfo, pTaskInfo);
L
Liu Jicong 已提交
4778
  pOperator->exprSupp.numOfExprs = numOfCols;
4779

L
Liu Jicong 已提交
4780 4781
  pOperator->fpSet = createOperatorFpSet(operatorDummyOpenFn, doTableMergeScan, NULL, destroyTableMergeScanOperatorInfo,
                                         getTableMergeScanExplainExecInfo);
4782 4783 4784 4785 4786 4787 4788 4789 4790
  pOperator->cost.openCost = 0;
  return pOperator;

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