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

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

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

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

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

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

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

dengyihao's avatar
dengyihao 已提交
45 46
static char* SYSTABLE_IDX_EXCEPT[] = {"db_name", "vgroup_id"};

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

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

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

dengyihao's avatar
dengyihao 已提交
61
static int32_t sysChkFilter__Comm(SNode* pNode);
dengyihao's avatar
dengyihao 已提交
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
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);

static int32_t sysFilte__DbName(void* pMeta, SNode* pNode, SArray* result);
static int32_t sysFilte__VgroupId(void* pMeta, SNode* pNode, SArray* result);
static int32_t sysFilte__TableName(void* pMeta, SNode* pNode, SArray* result);
static int32_t sysFilte__CreateTime(void* pMeta, SNode* pNode, SArray* result);
static int32_t sysFilte__Ncolumn(void* pMeta, SNode* pNode, SArray* result);
static int32_t sysFilte__Ttl(void* pMeta, SNode* pNode, SArray* result);
static int32_t sysFilte__STableName(void* pMeta, SNode* pNode, SArray* result);
static int32_t sysFilte__Uid(void* pMeta, SNode* pNode, SArray* result);
static int32_t sysFilte__Type(void* pMeta, SNode* pNode, SArray* result);

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 已提交
92

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

dengyihao's avatar
dengyihao 已提交
95
static int32_t optSysTabFilte(void* arg, SNode* cond, SArray* result);
dengyihao's avatar
dengyihao 已提交
96
static int32_t optSysTabFilteImpl(void* arg, SNode* cond, SArray* result);
dengyihao's avatar
dengyihao 已提交
97
static int32_t optSysCheckOper(SNode* pOpear);
dengyihao's avatar
dengyihao 已提交
98
static int32_t optSysMergeRslt(SArray* multiRslt, SArray* reslt);
dengyihao's avatar
dengyihao 已提交
99

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

102 103 104
static int32_t sysTableUserTagsFillOneTableTags(const SSysTableScanInfo* pInfo, SMetaReader* smrSuperTable,
                                                SMetaReader* smrChildTable, const char* dbname, const char* tableName,
                                                int32_t* pNumOfRows, const SSDataBlock* dataBlock);
105 106 107

static void relocateAndFilterSysTagsScanResult(SSysTableScanInfo* pInfo, int32_t numOfRows, SSDataBlock* dataBlock);
bool        processBlockWithProbability(const SSampleExecInfo* pInfo) {
108 109 110 111 112 113 114 115 116 117 118 119
#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
}

120
static void switchCtxOrder(SqlFunctionCtx* pCtx, int32_t numOfOutput) {
H
Haojun Liao 已提交
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
  for (int32_t i = 0; i < numOfOutput; ++i) {
    SWITCH_ORDER(pCtx[i].order);
  }
}

static void setupQueryRangeForReverseScan(STableScanInfo* pTableScanInfo) {
#if 0
  int32_t numOfGroups = (int32_t)(GET_NUM_OF_TABLEGROUP(pRuntimeEnv));
  for(int32_t i = 0; i < numOfGroups; ++i) {
    SArray *group = GET_TABLEGROUP(pRuntimeEnv, i);
    SArray *tableKeyGroup = taosArrayGetP(pQueryAttr->tableGroupInfo.pGroupList, i);

    size_t t = taosArrayGetSize(group);
    for (int32_t j = 0; j < t; ++j) {
      STableQueryInfo *pCheckInfo = taosArrayGetP(group, j);
      updateTableQueryInfoForReverseScan(pCheckInfo);

      // update the last key in tableKeyInfo list, the tableKeyInfo is used to build the tsdbQueryHandle and decide
      // the start check timestamp of tsdbQueryHandle
//      STableKeyInfo *pTableKeyInfo = taosArrayGet(tableKeyGroup, j);
//      pTableKeyInfo->lastKey = pCheckInfo->lastKey;
//
//      assert(pCheckInfo->pTable == pTableKeyInfo->pTable);
    }
  }
#endif
}

149 150 151 152 153 154 155 156 157
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;
158
  // convert key to second
159 160 161 162 163 164 165
  key = convertTimePrecision(key, pInterval->precision, TSDB_TIME_PRECISION_MILLI) / 1000;

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

  struct tm tm;
166
  time_t    t = (time_t)key;
167 168 169 170 171
  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 已提交
172
  tw->skey = convertTimePrecision((int64_t)taosMktime(&tm) * 1000LL, TSDB_TIME_PRECISION_MILLI, pInterval->precision);
173 174 175 176

  mon = (int)(mon + interval);
  tm.tm_year = mon / 12;
  tm.tm_mon = mon % 12;
wafwerar's avatar
wafwerar 已提交
177
  tw->ekey = convertTimePrecision((int64_t)taosMktime(&tm) * 1000LL, TSDB_TIME_PRECISION_MILLI, pInterval->precision);
178 179 180 181

  tw->ekey -= 1;
}

182
static bool overlapWithTimeWindow(SInterval* pInterval, SDataBlockInfo* pBlockInfo, int32_t order) {
183 184 185 186 187 188 189
  STimeWindow w = {0};

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

190
  if (order == TSDB_ORDER_ASC) {
191
    w = getAlignQueryTimeWindow(pInterval, pInterval->precision, pBlockInfo->window.skey);
192 193
    assert(w.ekey >= pBlockInfo->window.skey);

S
slzhou 已提交
194
    if (TMAX(w.skey, pBlockInfo->window.skey) <= TMIN(w.ekey, pBlockInfo->window.ekey)) {
195 196 197
      return true;
    }

198 199
    while (1) {
      getNextTimeWindow(pInterval, &w, order);
200 201 202 203 204
      if (w.skey > pBlockInfo->window.ekey) {
        break;
      }

      assert(w.ekey > pBlockInfo->window.ekey);
205
      if (TMAX(w.skey, pBlockInfo->window.skey) <= pBlockInfo->window.ekey) {
206 207 208 209
        return true;
      }
    }
  } else {
210
    w = getAlignQueryTimeWindow(pInterval, pInterval->precision, pBlockInfo->window.ekey);
211 212
    assert(w.skey <= pBlockInfo->window.ekey);

213
    if (TMAX(w.skey, pBlockInfo->window.skey) <= TMIN(w.ekey, pBlockInfo->window.ekey)) {
214 215 216
      return true;
    }

217
    while (1) {
218 219 220 221 222 223
      getNextTimeWindow(pInterval, &w, order);
      if (w.ekey < pBlockInfo->window.skey) {
        break;
      }

      assert(w.skey < pBlockInfo->window.skey);
224
      if (pBlockInfo->window.skey <= TMIN(w.ekey, pBlockInfo->window.ekey)) {
225 226 227
        return true;
      }
    }
228 229 230 231 232
  }

  return false;
}

233 234 235 236 237 238 239 240 241 242 243
// 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;

244 245
  SResultRowPosition* p1 = (SResultRowPosition*)tSimpleHashGet(pTableScanInfo->pdInfo.pAggSup->pResultRowHashTable, buf,
                                                               GET_RES_WINDOW_KEY_LEN(sizeof(groupId)));
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293

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

  *pPage = getBufPage(pTableScanInfo->pdInfo.pAggSup->pResultBuf, p1->pageId);
  return (SResultRow*)((char*)(*pPage) + p1->offset);
}

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

  if (pTableScanInfo->pdInfo.pExprSup == NULL) {
    return TSDB_CODE_SUCCESS;
  }

  SExprSupp* pSup1 = pTableScanInfo->pdInfo.pExprSup;

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

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

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

    SResultRowEntryInfo* pEntry = getResultEntryInfo(pRow, i, pTableScanInfo->pdInfo.pExprSup->rowEntryInfoOffset);

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

  // release buffer pages
  releaseBufPage(pTableScanInfo->pdInfo.pAggSup->pResultBuf, pPage);

  if (notLoadBlock) {
    *status = FUNC_DATA_REQUIRED_NOT_LOAD;
  }

  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
294 295 296 297 298 299 300 301 302 303
static FORCE_INLINE bool doFilterByBlockSMA(const SNode* pFilterNode, SColumnDataAgg** pColsAgg, int32_t numOfCols,
                                            int32_t numOfRows) {
  if (pColsAgg == NULL || pFilterNode == NULL) {
    return true;
  }

  SFilterInfo* filter = NULL;

  // todo move to the initialization function
  int32_t code = filterInitFromNode((SNode*)pFilterNode, &filter, 0);
L
Liu Jicong 已提交
304
  bool    keep = filterRangeExecute(filter, pColsAgg, numOfCols, numOfRows);
H
Haojun Liao 已提交
305 306 307 308 309 310 311 312 313 314 315

  filterFreeInfo(filter);
  return keep;
}

static bool doLoadBlockSMA(STableScanInfo* pTableScanInfo, SSDataBlock* pBlock, SExecTaskInfo* pTaskInfo) {
  bool             allColumnsHaveAgg = true;
  SColumnDataAgg** pColAgg = NULL;

  int32_t code = tsdbRetrieveDatablockSMA(pTableScanInfo->dataReader, &pColAgg, &allColumnsHaveAgg);
  if (code != TSDB_CODE_SUCCESS) {
316
    T_LONG_JMP(pTaskInfo->env, code);
H
Haojun Liao 已提交
317 318 319 320 321 322 323 324 325 326 327 328 329
  }

  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) {
330
      T_LONG_JMP(pTaskInfo->env, TSDB_CODE_OUT_OF_MEMORY);
H
Haojun Liao 已提交
331 332 333
    }
  }

H
Haojun Liao 已提交
334 335 336
  for (int32_t i = 0; i < taosArrayGetSize(pTableScanInfo->matchInfo.pList); ++i) {
    SColMatchItem* pColMatchInfo = taosArrayGet(pTableScanInfo->matchInfo.pList, i);
    if (!pColMatchInfo->needOutput) {
H
Haojun Liao 已提交
337 338
      continue;
    }
H
Haojun Liao 已提交
339 340

    pBlock->pBlockAgg[pColMatchInfo->dstSlotId] = pColAgg[i];
H
Haojun Liao 已提交
341 342 343 344 345
  }

  return true;
}

H
Haojun Liao 已提交
346 347 348 349 350 351 352 353 354 355 356 357
static void doSetTagColumnData(STableScanInfo* pTableScanInfo, SSDataBlock* pBlock, SExecTaskInfo* pTaskInfo) {
  if (pTableScanInfo->pseudoSup.numOfExprs > 0) {
    SExprSupp* pSup = &pTableScanInfo->pseudoSup;

    int32_t code = addTagPseudoColumnData(&pTableScanInfo->readHandle, pSup->pExprInfo, pSup->numOfExprs, pBlock,
                                          GET_TASKID(pTaskInfo));
    if (code != TSDB_CODE_SUCCESS) {
      T_LONG_JMP(pTaskInfo->env, code);
    }
  }
}

358 359
// todo handle the slimit info
void applyLimitOffset(SLimitInfo* pLimitInfo, SSDataBlock* pBlock, SExecTaskInfo* pTaskInfo, SOperatorInfo* pOperator) {
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
  SLimit* pLimit = &pLimitInfo->limit;

  if (pLimit->offset > 0 && pLimitInfo->remainOffset > 0) {
    if (pLimitInfo->remainOffset >= pBlock->info.rows) {
      pLimitInfo->remainOffset -= pBlock->info.rows;
      pBlock->info.rows = 0;
      qDebug("current block ignore due to offset, current:%"PRId64", %s", pLimitInfo->remainOffset, GET_TASKID(pTaskInfo));
    } 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);
    qDebug("output limit %"PRId64" has reached, %s", pLimit->limit, GET_TASKID(pTaskInfo));
380 381

//    setTaskStatus(pTaskInfo, TASK_COMPLETED);
382 383 384 385
    pOperator->status = OP_EXEC_DONE;
  }
}

L
Liu Jicong 已提交
386 387
static int32_t loadDataBlock(SOperatorInfo* pOperator, STableScanInfo* pTableScanInfo, SSDataBlock* pBlock,
                             uint32_t* status) {
388
  SExecTaskInfo*  pTaskInfo = pOperator->pTaskInfo;
389 390
  STableScanInfo* pInfo = pOperator->info;

391
  SFileBlockLoadRecorder* pCost = &pTableScanInfo->readRecorder;
H
Haojun Liao 已提交
392 393

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

H
Haojun Liao 已提交
396
  bool loadSMA = false;
H
Haojun Liao 已提交
397

398
  *status = pInfo->dataBlockLoadFlag;
399
  if (pTableScanInfo->pFilterNode != NULL ||
400
      overlapWithTimeWindow(&pTableScanInfo->pdInfo.interval, &pBlock->info, pTableScanInfo->cond.order)) {
401 402 403 404
    (*status) = FUNC_DATA_REQUIRED_DATA_LOAD;
  }

  SDataBlockInfo* pBlockInfo = &pBlock->info;
405
  taosMemoryFreeClear(pBlock->pBlockAgg);
406 407

  if (*status == FUNC_DATA_REQUIRED_FILTEROUT) {
408 409
    qDebug("%s data block filter out, brange:%" PRId64 "-%" PRId64 ", rows:%d", GET_TASKID(pTaskInfo),
           pBlockInfo->window.skey, pBlockInfo->window.ekey, pBlockInfo->rows);
410
    pCost->filterOutBlocks += 1;
411
    pCost->totalRows += pBlock->info.rows;
412 413
    return TSDB_CODE_SUCCESS;
  } else if (*status == FUNC_DATA_REQUIRED_NOT_LOAD) {
414 415
    qDebug("%s data block skipped, brange:%" PRId64 "-%" PRId64 ", rows:%d", GET_TASKID(pTaskInfo),
           pBlockInfo->window.skey, pBlockInfo->window.ekey, pBlockInfo->rows);
H
Haojun Liao 已提交
416 417

    doSetTagColumnData(pTableScanInfo, pBlock, pTaskInfo);
418 419 420 421
    pCost->skipBlocks += 1;
    return TSDB_CODE_SUCCESS;
  } else if (*status == FUNC_DATA_REQUIRED_STATIS_LOAD) {
    pCost->loadBlockStatis += 1;
L
Liu Jicong 已提交
422
    loadSMA = true;  // mark the operation of load sma;
H
Haojun Liao 已提交
423
    bool success = doLoadBlockSMA(pTableScanInfo, pBlock, pTaskInfo);
L
Liu Jicong 已提交
424
    if (success) {  // failed to load the block sma data, data block statistics does not exist, load data block instead
425 426
      qDebug("%s data block SMA loaded, brange:%" PRId64 "-%" PRId64 ", rows:%d", GET_TASKID(pTaskInfo),
             pBlockInfo->window.skey, pBlockInfo->window.ekey, pBlockInfo->rows);
H
Haojun Liao 已提交
427
      doSetTagColumnData(pTableScanInfo, pBlock, pTaskInfo);
428 429
      return TSDB_CODE_SUCCESS;
    } else {
430
      qDebug("%s failed to load SMA, since not all columns have SMA", GET_TASKID(pTaskInfo));
H
Haojun Liao 已提交
431
      *status = FUNC_DATA_REQUIRED_DATA_LOAD;
432
    }
H
Haojun Liao 已提交
433
  }
434

H
Haojun Liao 已提交
435
  ASSERT(*status == FUNC_DATA_REQUIRED_DATA_LOAD);
436

H
Haojun Liao 已提交
437
  // try to filter data block according to sma info
438 439 440 441 442 443 444 445 446 447 448 449 450
  if (pTableScanInfo->pFilterNode != NULL && (!loadSMA)) {
    bool success = doLoadBlockSMA(pTableScanInfo, pBlock, pTaskInfo);
    if (success) {
      size_t size = taosArrayGetSize(pBlock->pDataBlock);
      bool   keep = doFilterByBlockSMA(pTableScanInfo->pFilterNode, pBlock->pBlockAgg, size, pBlockInfo->rows);
      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;
      }
451
    }
H
Haojun Liao 已提交
452
  }
453

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

457
  // try to filter data block according to current results
458 459
  doDynamicPruneDataBlock(pOperator, pBlockInfo, status);
  if (*status == FUNC_DATA_REQUIRED_NOT_LOAD) {
460
    qDebug("%s data block skipped due to dynamic prune, brange:%" PRId64 "-%" PRId64 ", rows:%d", GET_TASKID(pTaskInfo),
461 462 463
           pBlockInfo->window.skey, pBlockInfo->window.ekey, pBlockInfo->rows);
    pCost->skipBlocks += 1;

464
    *status = FUNC_DATA_REQUIRED_FILTEROUT;
465 466 467
    return TSDB_CODE_SUCCESS;
  }

H
Haojun Liao 已提交
468 469
  pCost->totalCheckedRows += pBlock->info.rows;
  pCost->loadBlocks += 1;
470

H
Haojun Liao 已提交
471 472 473
  SArray* pCols = tsdbRetrieveDataBlock(pTableScanInfo->dataReader, NULL);
  if (pCols == NULL) {
    return terrno;
H
Haojun Liao 已提交
474 475
  }

H
Haojun Liao 已提交
476
  relocateColumnData(pBlock, pTableScanInfo->matchInfo.pList, pCols, true);
H
Haojun Liao 已提交
477
  doSetTagColumnData(pTableScanInfo, pBlock, pTaskInfo);
478

H
Haojun Liao 已提交
479 480
  // restore the previous value
  pCost->totalRows -= pBlock->info.rows;
481

482 483
  if (pTableScanInfo->pFilterNode != NULL) {
    int64_t st = taosGetTimestampUs();
H
Haojun Liao 已提交
484
    doFilter(pTableScanInfo->pFilterNode, pBlock, &pTableScanInfo->matchInfo, pOperator->exprSupp.pFilterInfo);
485

486 487
    double el = (taosGetTimestampUs() - st) / 1000.0;
    pTableScanInfo->readRecorder.filterTime += el;
488

489 490 491 492 493 494 495
    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);
    }
496 497
  }

498
  applyLimitOffset(&pInfo->limitInfo, pBlock, pTaskInfo, pOperator);
499

H
Haojun Liao 已提交
500 501
  pCost->totalRows += pBlock->info.rows;
  pInfo->limitInfo.numOfOutputRows = pCost->totalRows;
H
Haojun Liao 已提交
502 503 504
  return TSDB_CODE_SUCCESS;
}

505
static void prepareForDescendingScan(STableScanInfo* pTableScanInfo, SqlFunctionCtx* pCtx, int32_t numOfOutput) {
H
Haojun Liao 已提交
506 507 508
  SET_REVERSE_SCAN_FLAG(pTableScanInfo);

  switchCtxOrder(pCtx, numOfOutput);
509
  //  setupQueryRangeForReverseScan(pTableScanInfo);
H
Haojun Liao 已提交
510

511
  pTableScanInfo->cond.order = TSDB_ORDER_DESC;
H
Haojun Liao 已提交
512 513
  STimeWindow* pTWindow = &pTableScanInfo->cond.twindows;
  TSWAP(pTWindow->skey, pTWindow->ekey);
H
Haojun Liao 已提交
514 515
}

H
Haojun Liao 已提交
516
int32_t addTagPseudoColumnData(SReadHandle* pHandle, SExprInfo* pPseudoExpr, int32_t numOfPseudoExpr,
L
Liu Jicong 已提交
517
                               SSDataBlock* pBlock, const char* idStr) {
518
  // currently only the tbname pseudo column
519
  if (numOfPseudoExpr == 0) {
H
Haojun Liao 已提交
520
    return TSDB_CODE_SUCCESS;
521 522 523
  }

  SMetaReader mr = {0};
524
  metaReaderInit(&mr, pHandle->meta, 0);
H
Haojun Liao 已提交
525 526
  int32_t code = metaGetTableEntryByUid(&mr, pBlock->info.uid);
  if (code != TSDB_CODE_SUCCESS) {
L
Liu Jicong 已提交
527
    qError("failed to get table meta, uid:0x%" PRIx64 ", code:%s, %s", pBlock->info.uid, tstrerror(terrno), idStr);
H
Haojun Liao 已提交
528 529 530
    metaReaderClear(&mr);
    return terrno;
  }
531

532 533
  metaReaderReleaseLock(&mr);

534 535
  for (int32_t j = 0; j < numOfPseudoExpr; ++j) {
    SExprInfo* pExpr = &pPseudoExpr[j];
536 537 538 539

    int32_t dstSlotId = pExpr->base.resSchema.slotId;

    SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, dstSlotId);
D
dapan1121 已提交
540
    colInfoDataCleanup(pColInfoData, pBlock->info.rows);
541 542 543 544 545

    int32_t functionId = pExpr->pExpr->_function.functionId;

    // this is to handle the tbname
    if (fmIsScanPseudoColumnFunc(functionId)) {
546
      setTbNameColData(pHandle->meta, pBlock, pColInfoData, functionId);
547
    } else {  // these are tags
wmmhello's avatar
wmmhello 已提交
548 549
      STagVal tagVal = {0};
      tagVal.cid = pExpr->base.pParam[0].pCol->colId;
550
      const char* p = metaGetTableTagVal(mr.me.ctbEntry.pTags, pColInfoData->info.type, &tagVal);
wmmhello's avatar
wmmhello 已提交
551

552 553 554 555
      char* data = NULL;
      if (pColInfoData->info.type != TSDB_DATA_TYPE_JSON && p != NULL) {
        data = tTagValToData((const STagVal*)p, false);
      } else {
wmmhello's avatar
wmmhello 已提交
556
        data = (char*)p;
wmmhello's avatar
wmmhello 已提交
557
      }
558

H
Haojun Liao 已提交
559 560 561
      bool isNullVal = (data == NULL) || (pColInfoData->info.type == TSDB_DATA_TYPE_JSON && tTagIsJsonNull(data));
      if (isNullVal) {
        colDataAppendNNULL(pColInfoData, 0, pBlock->info.rows);
H
Haojun Liao 已提交
562
      } else if (pColInfoData->info.type != TSDB_DATA_TYPE_JSON) {
H
Haojun Liao 已提交
563
        colDataAppendNItems(pColInfoData, 0, data, pBlock->info.rows);
H
Haojun Liao 已提交
564 565 566
        if (IS_VAR_DATA_TYPE(((const STagVal*)p)->type)) {
          taosMemoryFree(data);
        }
L
Liu Jicong 已提交
567
      } else {  // todo opt for json tag
H
Haojun Liao 已提交
568
        for (int32_t i = 0; i < pBlock->info.rows; ++i) {
H
Haojun Liao 已提交
569
          colDataAppend(pColInfoData, i, data, false);
H
Haojun Liao 已提交
570
        }
571 572 573 574 575
      }
    }
  }

  metaReaderClear(&mr);
H
Haojun Liao 已提交
576
  return TSDB_CODE_SUCCESS;
577 578
}

579 580 581 582
void setTbNameColData(void* pMeta, const SSDataBlock* pBlock, SColumnInfoData* pColInfoData, int32_t functionId) {
  struct SScalarFuncExecFuncs fpSet = {0};
  fmGetScalarFuncExecFuncs(functionId, &fpSet);

583 584
  SColumnInfoData infoData = createColumnInfoData(TSDB_DATA_TYPE_BIGINT, sizeof(uint64_t), 1);
  colInfoDataEnsureCapacity(&infoData, 1);
585

586
  colDataAppendInt64(&infoData, 0, (int64_t*)&pBlock->info.uid);
587
  SScalarParam srcParam = {.numOfRows = pBlock->info.rows, .param = pMeta, .columnData = &infoData};
588 589

  SScalarParam param = {.columnData = pColInfoData};
H
Haojun Liao 已提交
590 591 592 593 594 595 596

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

D
dapan1121 已提交
597
  colDataDestroy(&infoData);
598 599
}

600
static SSDataBlock* doTableScanImpl(SOperatorInfo* pOperator) {
H
Haojun Liao 已提交
601
  STableScanInfo* pTableScanInfo = pOperator->info;
602
  SExecTaskInfo*  pTaskInfo = pOperator->pTaskInfo;
L
Liu Jicong 已提交
603
  SSDataBlock*    pBlock = pTableScanInfo->pResBlock;
H
Haojun Liao 已提交
604

605 606
  int64_t st = taosGetTimestampUs();

607
  while (tsdbNextDataBlock(pTableScanInfo->dataReader)) {
608
    if (isTaskKilled(pTaskInfo)) {
609
      T_LONG_JMP(pTaskInfo->env, TSDB_CODE_TSC_QUERY_CANCELLED);
610
    }
H
Haojun Liao 已提交
611

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

618 619 620 621 622 623 624 625
    blockDataCleanup(pBlock);

    SDataBlockInfo binfo = pBlock->info;
    tsdbRetrieveDataBlockInfo(pTableScanInfo->dataReader, &binfo);

    binfo.capacity = binfo.rows;
    blockDataEnsureCapacity(pBlock, binfo.rows);
    pBlock->info = binfo;
L
Liu Jicong 已提交
626
    ASSERT(binfo.uid != 0);
H
Haojun Liao 已提交
627

628 629 630 631 632
    uint64_t* groupId = taosHashGet(pTaskInfo->tableqinfoList.map, &pBlock->info.uid, sizeof(int64_t));
    if (groupId) {
      pBlock->info.groupId = *groupId;
    }

633 634 635 636
    uint32_t status = 0;
    int32_t  code = loadDataBlock(pOperator, pTableScanInfo, pBlock, &status);
    //    int32_t  code = loadDataBlockOnDemand(pOperator->pRuntimeEnv, pTableScanInfo, pBlock, &status);
    if (code != TSDB_CODE_SUCCESS) {
637
      T_LONG_JMP(pOperator->pTaskInfo->env, code);
638
    }
639

640 641 642
    // 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;
643
    }
644 645 646 647 648

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

    pOperator->cost.totalCost = pTableScanInfo->readRecorder.elapsedTime;
649 650

    // todo refactor
L
Liu Jicong 已提交
651 652 653 654 655
    /*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;
656

L
Liu Jicong 已提交
657
    ASSERT(pBlock->info.uid != 0);
658
    return pBlock;
H
Haojun Liao 已提交
659 660 661 662
  }
  return NULL;
}

wmmhello's avatar
wmmhello 已提交
663
static SSDataBlock* doTableScanGroup(SOperatorInfo* pOperator) {
H
Haojun Liao 已提交
664 665 666 667
  STableScanInfo* pTableScanInfo = pOperator->info;
  SExecTaskInfo*  pTaskInfo = pOperator->pTaskInfo;

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

672 673
  // do the ascending order traverse in the first place.
  while (pTableScanInfo->scanTimes < pTableScanInfo->scanInfo.numOfAsc) {
H
Haojun Liao 已提交
674 675 676 677
    SSDataBlock* p = doTableScanImpl(pOperator);
    if (p != NULL) {
      ASSERT(p->info.uid != 0);
      return p;
H
Haojun Liao 已提交
678 679
    }

680
    pTableScanInfo->scanTimes += 1;
681

682
    if (pTableScanInfo->scanTimes < pTableScanInfo->scanInfo.numOfAsc) {
683 684
      setTaskStatus(pTaskInfo, TASK_NOT_COMPLETED);
      pTableScanInfo->scanFlag = REPEAT_SCAN;
L
Liu Jicong 已提交
685 686 687 688
      qDebug(
          "%s start to repeat ascending order scan data SELECT last_row(*),hostname from cpu group by hostname;blocks "
          "due to query func required",
          GET_TASKID(pTaskInfo));
H
Haojun Liao 已提交
689

690
      // do prepare for the next round table scan operation
H
Haojun Liao 已提交
691
      tsdbReaderReset(pTableScanInfo->dataReader, &pTableScanInfo->cond);
H
Haojun Liao 已提交
692
    }
693
  }
H
Haojun Liao 已提交
694

695
  int32_t total = pTableScanInfo->scanInfo.numOfAsc + pTableScanInfo->scanInfo.numOfDesc;
696
  if (pTableScanInfo->scanTimes < total) {
697
    if (pTableScanInfo->cond.order == TSDB_ORDER_ASC) {
H
Haojun Liao 已提交
698 699
      prepareForDescendingScan(pTableScanInfo, pOperator->exprSupp.pCtx, 0);
      tsdbReaderReset(pTableScanInfo->dataReader, &pTableScanInfo->cond);
700
      qDebug("%s start to descending order scan data blocks due to query func required", GET_TASKID(pTaskInfo));
701
    }
H
Haojun Liao 已提交
702

703
    while (pTableScanInfo->scanTimes < total) {
H
Haojun Liao 已提交
704 705 706
      SSDataBlock* p = doTableScanImpl(pOperator);
      if (p != NULL) {
        return p;
707
      }
H
Haojun Liao 已提交
708

709
      pTableScanInfo->scanTimes += 1;
H
Haojun Liao 已提交
710

711
      if (pTableScanInfo->scanTimes < total) {
712 713
        setTaskStatus(pTaskInfo, TASK_NOT_COMPLETED);
        pTableScanInfo->scanFlag = REPEAT_SCAN;
H
Haojun Liao 已提交
714

715 716
        qDebug("%s start to repeat descending order scan data blocks due to query func required",
               GET_TASKID(pTaskInfo));
H
Haojun Liao 已提交
717
        tsdbReaderReset(pTableScanInfo->dataReader, &pTableScanInfo->cond);
718
      }
H
Haojun Liao 已提交
719 720 721
    }
  }

wmmhello's avatar
wmmhello 已提交
722 723 724 725 726 727 728
  return NULL;
}

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

L
Liu Jicong 已提交
729 730
  // if scan table by table
  if (pInfo->scanMode == TABLE_SCAN__TABLE_ORDER) {
H
Haojun Liao 已提交
731 732
    int32_t numOfTables = taosArrayGetSize(pTaskInfo->tableqinfoList.pTableList);

L
Liu Jicong 已提交
733
    while (1) {
L
Liu Jicong 已提交
734 735 736 737
      SSDataBlock* result = doTableScanGroup(pOperator);
      if (result) {
        return result;
      }
H
Haojun Liao 已提交
738

L
Liu Jicong 已提交
739 740
      // if no data, switch to next table and continue scan
      pInfo->currentTable++;
H
Haojun Liao 已提交
741
      if (pInfo->currentTable >= numOfTables) {
L
Liu Jicong 已提交
742 743
        return NULL;
      }
H
Haojun Liao 已提交
744

L
Liu Jicong 已提交
745 746
      STableKeyInfo* pTableInfo = taosArrayGet(pTaskInfo->tableqinfoList.pTableList, pInfo->currentTable);
      tsdbSetTableId(pInfo->dataReader, pTableInfo->uid);
L
Liu Jicong 已提交
747 748
      qDebug("set uid:%" PRIu64 " into scanner, total tables:%d, index:%d %s", pTableInfo->uid, numOfTables,
             pInfo->currentTable, pTaskInfo->id.str);
H
Haojun Liao 已提交
749

H
Haojun Liao 已提交
750
      tsdbReaderReset(pInfo->dataReader, &pInfo->cond);
L
Liu Jicong 已提交
751 752 753 754
      pInfo->scanTimes = 0;
    }
  }

755
  if (pInfo->currentGroupId == -1) {
wmmhello's avatar
wmmhello 已提交
756
    pInfo->currentGroupId++;
wmmhello's avatar
wmmhello 已提交
757
    if (pInfo->currentGroupId >= taosArrayGetSize(pTaskInfo->tableqinfoList.pGroupList)) {
wmmhello's avatar
wmmhello 已提交
758
      setTaskStatus(pTaskInfo, TASK_COMPLETED);
wmmhello's avatar
wmmhello 已提交
759 760
      return NULL;
    }
H
Haojun Liao 已提交
761

762
    SArray* tableList = taosArrayGetP(pTaskInfo->tableqinfoList.pGroupList, pInfo->currentGroupId);
H
Haojun Liao 已提交
763 764
    tsdbReaderClose(pInfo->dataReader);

765 766
    int32_t code = tsdbReaderOpen(pInfo->readHandle.vnode, &pInfo->cond, tableList, (STsdbReader**)&pInfo->dataReader,
                                  GET_TASKID(pTaskInfo));
767
    if (code != TSDB_CODE_SUCCESS) {
768
      T_LONG_JMP(pTaskInfo->env, code);
769 770
      return NULL;
    }
wmmhello's avatar
wmmhello 已提交
771 772 773
  }

  SSDataBlock* result = doTableScanGroup(pOperator);
774
  if (result) {
wmmhello's avatar
wmmhello 已提交
775 776 777 778 779
    return result;
  }

  pInfo->currentGroupId++;
  if (pInfo->currentGroupId >= taosArrayGetSize(pTaskInfo->tableqinfoList.pGroupList)) {
wmmhello's avatar
wmmhello 已提交
780
    setTaskStatus(pTaskInfo, TASK_COMPLETED);
wmmhello's avatar
wmmhello 已提交
781 782 783
    return NULL;
  }

H
Haojun Liao 已提交
784
  tsdbReaderReset(pInfo->dataReader, &pInfo->cond);
wmmhello's avatar
wmmhello 已提交
785 786 787
  pInfo->scanTimes = 0;

  result = doTableScanGroup(pOperator);
788
  if (result) {
wmmhello's avatar
wmmhello 已提交
789 790 791
    return result;
  }

792 793
  setTaskStatus(pTaskInfo, TASK_COMPLETED);
  return NULL;
H
Haojun Liao 已提交
794 795
}

796 797
static int32_t getTableScannerExecInfo(struct SOperatorInfo* pOptr, void** pOptrExplain, uint32_t* len) {
  SFileBlockLoadRecorder* pRecorder = taosMemoryCalloc(1, sizeof(SFileBlockLoadRecorder));
798
  STableScanInfo*         pTableScanInfo = pOptr->info;
799 800 801 802 803 804
  *pRecorder = pTableScanInfo->readRecorder;
  *pOptrExplain = pRecorder;
  *len = sizeof(SFileBlockLoadRecorder);
  return 0;
}

805
static void destroyTableScanOperatorInfo(void* param) {
806
  STableScanInfo* pTableScanInfo = (STableScanInfo*)param;
H
Haojun Liao 已提交
807
  blockDataDestroy(pTableScanInfo->pResBlock);
808
  cleanupQueryTableDataCond(&pTableScanInfo->cond);
H
Haojun Liao 已提交
809

H
refact  
Hongze Cheng 已提交
810
  tsdbReaderClose(pTableScanInfo->dataReader);
811
  pTableScanInfo->dataReader = NULL;
812

H
Haojun Liao 已提交
813 814
  if (pTableScanInfo->matchInfo.pList != NULL) {
    taosArrayDestroy(pTableScanInfo->matchInfo.pList);
815
  }
L
Liu Jicong 已提交
816

817
  cleanupExprSupp(&pTableScanInfo->pseudoSup);
D
dapan1121 已提交
818
  taosMemoryFreeClear(param);
819 820
}

wmmhello's avatar
wmmhello 已提交
821
SOperatorInfo* createTableScanOperatorInfo(STableScanPhysiNode* pTableScanNode, SReadHandle* readHandle,
822
                                           SExecTaskInfo* pTaskInfo) {
H
Haojun Liao 已提交
823 824 825
  STableScanInfo* pInfo = taosMemoryCalloc(1, sizeof(STableScanInfo));
  SOperatorInfo*  pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
  if (pInfo == NULL || pOperator == NULL) {
826
    goto _error;
H
Haojun Liao 已提交
827 828
  }

829
  SDataBlockDescNode* pDescNode = pTableScanNode->scan.node.pOutputDataBlockDesc;
830 831

  int32_t numOfCols = 0;
H
Haojun Liao 已提交
832 833
  int32_t code = extractColMatchInfo(pTableScanNode->scan.pScanCols, pDescNode, &numOfCols, COL_MATCH_FROM_COL_ID,
                                     &pInfo->matchInfo);
834 835 836 837 838
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }

  initLimitInfo(pTableScanNode->scan.node.pLimit, pTableScanNode->scan.node.pSlimit, &pInfo->limitInfo);
L
Liu Jicong 已提交
839

H
Haojun Liao 已提交
840
  code = initQueryTableDataCond(&pInfo->cond, pTableScanNode);
841
  if (code != TSDB_CODE_SUCCESS) {
842
    goto _error;
843 844 845
  }

  if (pTableScanNode->scan.pScanPseudoCols != NULL) {
846
    SExprSupp* pSup = &pInfo->pseudoSup;
847 848
    pSup->pExprInfo = createExprInfo(pTableScanNode->scan.pScanPseudoCols, NULL, &pSup->numOfExprs);
    pSup->pCtx = createSqlFunctionCtx(pSup->pExprInfo, pSup->numOfExprs, &pSup->rowEntryInfoOffset);
849 850
  }

851
  pInfo->scanInfo = (SScanInfo){.numOfAsc = pTableScanNode->scanSeq[0], .numOfDesc = pTableScanNode->scanSeq[1]};
852
  pInfo->pdInfo.interval = extractIntervalInfo(pTableScanNode);
853 854 855
  pInfo->readHandle = *readHandle;
  pInfo->sample.sampleRatio = pTableScanNode->ratio;
  pInfo->sample.seed = taosGetTimestampSec();
856

857
  pInfo->dataBlockLoadFlag = pTableScanNode->dataRequired;
858 859
  pInfo->pResBlock = createResDataBlock(pDescNode);
  pInfo->pFilterNode = pTableScanNode->scan.node.pConditions;
H
Haojun Liao 已提交
860 861 862

  if (pInfo->pFilterNode != NULL) {
    code = filterInitFromNode((SNode*)pInfo->pFilterNode, &pOperator->exprSupp.pFilterInfo, 0);
863
    if (code != TSDB_CODE_SUCCESS) {
864 865
      goto _error;
    }
H
Haojun Liao 已提交
866 867
  }

868
  pInfo->scanFlag = MAIN_SCAN;
wmmhello's avatar
wmmhello 已提交
869
  pInfo->currentGroupId = -1;
870
  pInfo->assignBlockUid = pTableScanNode->assignBlockUid;
871 872

  pOperator->name = "TableScanOperator";  // for debug purpose
L
Liu Jicong 已提交
873
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_TABLE_SCAN;
874 875 876
  pOperator->blocking = false;
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
877
  pOperator->exprSupp.numOfExprs = numOfCols;
878
  pOperator->pTaskInfo = pTaskInfo;
879

880
  pOperator->fpSet = createOperatorFpSet(operatorDummyOpenFn, doTableScan, NULL, NULL, destroyTableScanOperatorInfo,
881
                                         getTableScannerExecInfo);
882 883 884

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

887
_error:
888 889 890
  if (pInfo != NULL) {
    destroyTableScanOperatorInfo(pInfo);
  }
891

892 893
  taosMemoryFreeClear(pOperator);
  pTaskInfo->code = code;
894
  return NULL;
H
Haojun Liao 已提交
895 896
}

897
SOperatorInfo* createTableSeqScanOperatorInfo(void* pReadHandle, SExecTaskInfo* pTaskInfo) {
H
Haojun Liao 已提交
898
  STableScanInfo* pInfo = taosMemoryCalloc(1, sizeof(STableScanInfo));
L
Liu Jicong 已提交
899
  SOperatorInfo*  pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
900

L
Liu Jicong 已提交
901 902
  pInfo->dataReader = pReadHandle;
  //  pInfo->prevGroupId       = -1;
H
Haojun Liao 已提交
903

904
  pOperator->name = "TableSeqScanOperator";
H
Haojun Liao 已提交
905
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_TABLE_SEQ_SCAN;
906 907 908 909
  pOperator->blocking = false;
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
  pOperator->pTaskInfo = pTaskInfo;
H
Haojun Liao 已提交
910

911
  pOperator->fpSet = createOperatorFpSet(operatorDummyOpenFn, doTableScanImpl, NULL, NULL, NULL, NULL);
H
Haojun Liao 已提交
912 913 914
  return pOperator;
}

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

918
  SMetaReader mr = {0};
919
  metaReaderInit(&mr, pMeta, 0);
H
Haojun Liao 已提交
920 921
  int32_t code = metaGetTableEntryByUid(&mr, uid);
  if (code != TSDB_CODE_SUCCESS) {
L
Liu Jicong 已提交
922
    qError("failed to get table meta, uid:0x%" PRIx64 ", code:%s, %s", uid, tstrerror(terrno), idstr);
H
Haojun Liao 已提交
923 924 925 926
    metaReaderClear(&mr);
    return terrno;
  }

927 928
  if (mr.me.type == TSDB_SUPER_TABLE) {
    int32_t numOfCols = mr.me.stbEntry.schemaRow.nCols;
929
    for (int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
930
      (*rowLen) += mr.me.stbEntry.schemaRow.pSchema[i].bytes;
931 932 933
    }
  } else if (mr.me.type == TSDB_CHILD_TABLE) {
    uint64_t suid = mr.me.ctbEntry.suid;
934
    tDecoderClear(&mr.coder);
H
Haojun Liao 已提交
935 936
    code = metaGetTableEntryByUid(&mr, suid);
    if (code != TSDB_CODE_SUCCESS) {
L
Liu Jicong 已提交
937
      qError("failed to get table meta, uid:0x%" PRIx64 ", code:%s, %s", suid, tstrerror(terrno), idstr);
H
Haojun Liao 已提交
938 939 940 941
      metaReaderClear(&mr);
      return terrno;
    }

942 943
    int32_t numOfCols = mr.me.stbEntry.schemaRow.nCols;

944
    for (int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
945
      (*rowLen) += mr.me.stbEntry.schemaRow.pSchema[i].bytes;
946 947 948
    }
  } else if (mr.me.type == TSDB_NORMAL_TABLE) {
    int32_t numOfCols = mr.me.ntbEntry.schemaRow.nCols;
949
    for (int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
950
      (*rowLen) += mr.me.ntbEntry.schemaRow.pSchema[i].bytes;
951 952 953 954
    }
  }

  metaReaderClear(&mr);
H
Haojun Liao 已提交
955
  return TSDB_CODE_SUCCESS;
956 957 958 959 960 961 962 963
}

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

  SBlockDistInfo* pBlockScanInfo = pOperator->info;
L
Liu Jicong 已提交
964
  SExecTaskInfo*  pTaskInfo = pOperator->pTaskInfo;
965 966

  STableBlockDistInfo blockDistInfo = {.minRows = INT_MAX, .maxRows = INT_MIN};
L
Liu Jicong 已提交
967 968
  int32_t code = doGetTableRowSize(pBlockScanInfo->readHandle.meta, pBlockScanInfo->uid, &blockDistInfo.rowSize,
                                   GET_TASKID(pTaskInfo));
H
Haojun Liao 已提交
969
  if (code != TSDB_CODE_SUCCESS) {
970
    T_LONG_JMP(pTaskInfo->env, code);
H
Haojun Liao 已提交
971
  }
972 973 974

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

976
  SSDataBlock* pBlock = pBlockScanInfo->pResBlock;
H
Haojun Liao 已提交
977

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

981
  int32_t len = tSerializeBlockDistInfo(NULL, 0, &blockDistInfo);
982
  char*   p = taosMemoryCalloc(1, len + VARSTR_HEADER_SIZE);
983 984 985
  tSerializeBlockDistInfo(varDataVal(p), len, &blockDistInfo);
  varDataSetLen(p, len);

986
  blockDataEnsureCapacity(pBlock, 1);
987 988
  colDataAppend(pColInfo, 0, p, false);
  taosMemoryFree(p);
H
Haojun Liao 已提交
989

990 991
  pBlock->info.rows = 1;

H
Haojun Liao 已提交
992 993 994 995
  pOperator->status = OP_EXEC_DONE;
  return pBlock;
}

996
static void destroyBlockDistScanOperatorInfo(void* param) {
997
  SBlockDistInfo* pDistInfo = (SBlockDistInfo*)param;
998
  blockDataDestroy(pDistInfo->pResBlock);
H
Hongze Cheng 已提交
999
  tsdbReaderClose(pDistInfo->pHandle);
D
dapan1121 已提交
1000
  taosMemoryFreeClear(param);
1001 1002
}

1003 1004
SOperatorInfo* createDataBlockInfoScanOperator(void* dataReader, SReadHandle* readHandle, uint64_t uid,
                                               SBlockDistScanPhysiNode* pBlockScanNode, SExecTaskInfo* pTaskInfo) {
1005
  SBlockDistInfo* pInfo = taosMemoryCalloc(1, sizeof(SBlockDistInfo));
1006
  SOperatorInfo*  pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
1007 1008 1009 1010 1011
  if (pInfo == NULL || pOperator == NULL) {
    pTaskInfo->code = TSDB_CODE_OUT_OF_MEMORY;
    goto _error;
  }

1012
  pInfo->pHandle = dataReader;
1013
  pInfo->readHandle = *readHandle;
1014 1015
  pInfo->uid = uid;
  pInfo->pResBlock = createResDataBlock(pBlockScanNode->node.pOutputDataBlockDesc);
1016

1017
  int32_t    numOfCols = 0;
1018
  SExprInfo* pExprInfo = createExprInfo(pBlockScanNode->pScanPseudoCols, NULL, &numOfCols);
1019
  int32_t    code = initExprSupp(&pOperator->exprSupp, pExprInfo, numOfCols);
1020 1021 1022
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
H
Haojun Liao 已提交
1023

1024
  pOperator->name = "DataBlockDistScanOperator";
1025
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_BLOCK_DIST_SCAN;
1026 1027 1028
  pOperator->blocking = false;
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
1029 1030
  pOperator->pTaskInfo = pTaskInfo;

1031 1032
  pOperator->fpSet =
      createOperatorFpSet(operatorDummyOpenFn, doBlockInfoScan, NULL, NULL, destroyBlockDistScanOperatorInfo, NULL);
H
Haojun Liao 已提交
1033 1034
  return pOperator;

1035
_error:
H
Haojun Liao 已提交
1036 1037 1038 1039 1040
  taosMemoryFreeClear(pInfo);
  taosMemoryFreeClear(pOperator);
  return NULL;
}

1041
static FORCE_INLINE void doClearBufferedBlocks(SStreamScanInfo* pInfo) {
L
Liu Jicong 已提交
1042 1043
  taosArrayClear(pInfo->pBlockLists);
  pInfo->validBlockIndex = 0;
H
Haojun Liao 已提交
1044 1045
}

1046
static bool isSessionWindow(SStreamScanInfo* pInfo) {
H
Haojun Liao 已提交
1047
  return pInfo->windowSup.parentType == QUERY_NODE_PHYSICAL_PLAN_STREAM_SESSION;
5
54liuyao 已提交
1048 1049
}

1050
static bool isStateWindow(SStreamScanInfo* pInfo) {
1051
  return pInfo->windowSup.parentType == QUERY_NODE_PHYSICAL_PLAN_STREAM_STATE;
5
54liuyao 已提交
1052
}
5
54liuyao 已提交
1053

L
Liu Jicong 已提交
1054
static bool isIntervalWindow(SStreamScanInfo* pInfo) {
1055 1056 1057
  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 已提交
1058 1059 1060
}

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

1064 1065 1066 1067
static bool isSlidingWindow(SStreamScanInfo* pInfo) {
  return isIntervalWindow(pInfo) && pInfo->interval.interval != pInfo->interval.sliding;
}

1068
static void setGroupId(SStreamScanInfo* pInfo, SSDataBlock* pBlock, int32_t groupColIndex, int32_t rowIndex) {
1069 1070
  SColumnInfoData* pColInfo = taosArrayGet(pBlock->pDataBlock, groupColIndex);
  uint64_t*        groupCol = (uint64_t*)pColInfo->pData;
1071
  ASSERT(rowIndex < pBlock->info.rows);
1072
  pInfo->groupId = groupCol[rowIndex];
1073 1074
}

L
Liu Jicong 已提交
1075
void resetTableScanInfo(STableScanInfo* pTableScanInfo, STimeWindow* pWin) {
H
Haojun Liao 已提交
1076
  pTableScanInfo->cond.twindows = *pWin;
L
Liu Jicong 已提交
1077 1078 1079 1080
  pTableScanInfo->scanTimes = 0;
  pTableScanInfo->currentGroupId = -1;
}

L
Liu Jicong 已提交
1081
static void freeArray(void* array) { taosArrayDestroy(array); }
1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094

static void resetTableScanOperator(SOperatorInfo* pTableScanOp) {
  STableScanInfo* pTableScanInfo = pTableScanOp->info;
  pTableScanInfo->cond.startVersion = -1;
  pTableScanInfo->cond.endVersion = -1;
  SArray* gpTbls = pTableScanOp->pTaskInfo->tableqinfoList.pGroupList;
  SArray* allTbls = pTableScanOp->pTaskInfo->tableqinfoList.pTableList;
  taosArrayClearP(gpTbls, freeArray);
  taosArrayPush(gpTbls, &allTbls);
  STimeWindow win = {.skey = INT64_MIN, .ekey = INT64_MAX};
  resetTableScanInfo(pTableScanOp->info, &win);
}

L
Liu Jicong 已提交
1095 1096
static SSDataBlock* readPreVersionData(SOperatorInfo* pTableScanOp, uint64_t tbUid, TSKEY startTs, TSKEY endTs,
                                       int64_t maxVersion) {
1097 1098 1099
  SArray* gpTbls = pTableScanOp->pTaskInfo->tableqinfoList.pGroupList;
  taosArrayClear(gpTbls);
  STableKeyInfo tblInfo = {.uid = tbUid, .groupId = 0};
L
Liu Jicong 已提交
1100
  SArray*       tbls = taosArrayInit(1, sizeof(STableKeyInfo));
1101 1102 1103
  taosArrayPush(tbls, &tblInfo);
  taosArrayPush(gpTbls, &tbls);

L
Liu Jicong 已提交
1104
  STimeWindow     win = {.skey = startTs, .ekey = endTs};
1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122
  STableScanInfo* pTableScanInfo = pTableScanOp->info;
  pTableScanInfo->cond.startVersion = -1;
  pTableScanInfo->cond.endVersion = maxVersion;
  resetTableScanInfo(pTableScanOp->info, &win);
  SSDataBlock* pRes = doTableScan(pTableScanOp);
  resetTableScanOperator(pTableScanOp);
  return pRes;
}

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 已提交
1123
static uint64_t getGroupIdByUid(SStreamScanInfo* pInfo, uint64_t uid) {
1124 1125 1126 1127 1128 1129 1130 1131
  SHashObj* map = pInfo->pTableScanOp->pTaskInfo->tableqinfoList.map;
  uint64_t* groupId = taosHashGet(map, &uid, sizeof(int64_t));
  if (groupId) {
    return *groupId;
  }
  return 0;
}

5
54liuyao 已提交
1132 1133 1134 1135 1136 1137 1138 1139
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 已提交
1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150
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]};
1151 1152 1153
  SColumnInfoData* pGpCol = taosArrayGet(pBlock->pDataBlock, GROUPID_COLUMN_INDEX);
  uint64_t*        gpData = (uint64_t*)pGpCol->pData;
  uint64_t         groupId = gpData[*pRowIndex];
1154 1155 1156 1157 1158 1159

  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 已提交
1160
  setGroupId(pInfo, pBlock, GROUPID_COLUMN_INDEX, *pRowIndex);
1161 1162 1163 1164
  if (isSlidingWindow(pInfo)) {
    pInfo->updateWin.skey = calStartData[*pRowIndex];
    pInfo->updateWin.ekey = calEndData[*pRowIndex];
  }
L
Liu Jicong 已提交
1165 1166 1167
  (*pRowIndex)++;

  for (; *pRowIndex < pBlock->info.rows; (*pRowIndex)++) {
1168
    if (win.skey == startData[*pRowIndex] && groupId == gpData[*pRowIndex]) {
L
Liu Jicong 已提交
1169 1170 1171
      win.ekey = TMAX(win.ekey, endData[*pRowIndex]);
      continue;
    }
1172
    if (win.skey == endData[*pRowIndex] && groupId == gpData[*pRowIndex]) {
L
Liu Jicong 已提交
1173 1174 1175
      win.skey = TMIN(win.skey, startData[*pRowIndex]);
      continue;
    }
1176 1177
    ASSERT(!(win.skey > startData[*pRowIndex] && win.ekey < endData[*pRowIndex]) ||
           !(isInTimeWindow(&win, startData[*pRowIndex], 0) || isInTimeWindow(&win, endData[*pRowIndex], 0)));
L
Liu Jicong 已提交
1178 1179 1180 1181
    break;
  }

  resetTableScanInfo(pInfo->pTableScanOp->info, &win);
1182
  pInfo->pTableScanOp->status = OP_OPENED;
L
Liu Jicong 已提交
1183 1184 1185
  return true;
}

5
54liuyao 已提交
1186
static STimeWindow getSlidingWindow(TSKEY* startTsCol, TSKEY* endTsCol, uint64_t* gpIdCol, SInterval* pInterval,
1187
                                    SDataBlockInfo* pDataBlockInfo, int32_t* pRowIndex, bool hasGroup) {
H
Haojun Liao 已提交
1188
  SResultRowInfo dumyInfo = {0};
5
54liuyao 已提交
1189
  dumyInfo.cur.pageId = -1;
1190
  STimeWindow win = getActiveTimeWindow(NULL, &dumyInfo, startTsCol[*pRowIndex], pInterval, TSDB_ORDER_ASC);
5
54liuyao 已提交
1191 1192
  STimeWindow endWin = win;
  STimeWindow preWin = win;
5
54liuyao 已提交
1193
  uint64_t    groupId = gpIdCol[*pRowIndex];
H
Haojun Liao 已提交
1194

5
54liuyao 已提交
1195
  while (1) {
1196 1197 1198
    if (hasGroup) {
      (*pRowIndex) += 1;
    } else {
5
54liuyao 已提交
1199 1200 1201 1202 1203 1204
      while ((groupId == gpIdCol[(*pRowIndex)] && startTsCol[*pRowIndex] < endWin.ekey)) {
        (*pRowIndex) += 1;
        if ((*pRowIndex) == pDataBlockInfo->rows) {
          break;
        }
      }
1205
    }
5
54liuyao 已提交
1206

5
54liuyao 已提交
1207 1208 1209
    do {
      preWin = endWin;
      getNextTimeWindow(pInterval, &endWin, TSDB_ORDER_ASC);
1210
    } while (endTsCol[(*pRowIndex) - 1] >= endWin.skey);
5
54liuyao 已提交
1211
    endWin = preWin;
5
54liuyao 已提交
1212
    if (win.ekey == endWin.ekey || (*pRowIndex) == pDataBlockInfo->rows || groupId != gpIdCol[*pRowIndex]) {
5
54liuyao 已提交
1213 1214 1215 1216 1217 1218
      win.ekey = endWin.ekey;
      return win;
    }
    win.ekey = endWin.ekey;
  }
}
5
54liuyao 已提交
1219

L
Liu Jicong 已提交
1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230
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 已提交
1231
      pInfo->updateWin = (STimeWindow){.skey = INT64_MIN, .ekey = INT64_MAX};
H
Hongze Cheng 已提交
1232 1233 1234
      STableScanInfo* pTableScanInfo = pInfo->pTableScanOp->info;
      tsdbReaderClose(pTableScanInfo->dataReader);
      pTableScanInfo->dataReader = NULL;
1235 1236
      return NULL;
    }
L
Liu Jicong 已提交
1237

H
Haojun Liao 已提交
1238
    doFilter(pInfo->pCondition, pResult, NULL, NULL);
1239 1240 1241 1242
    if (pResult->info.rows == 0) {
      continue;
    }

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

      blockDataDestroy(tmpBlock);

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

1272 1273 1274
static int32_t generateSessionScanRange(SStreamScanInfo* pInfo, SSDataBlock* pSrcBlock, SSDataBlock* pDestBlock) {
  if (pSrcBlock->info.rows == 0) {
    return TSDB_CODE_SUCCESS;
1275
  }
1276 1277
  blockDataCleanup(pDestBlock);
  int32_t code = blockDataEnsureCapacity(pDestBlock, pSrcBlock->info.rows);
1278
  if (code != TSDB_CODE_SUCCESS) {
1279
    return code;
L
Liu Jicong 已提交
1280
  }
1281 1282
  ASSERT(taosArrayGetSize(pSrcBlock->pDataBlock) >= 3);
  SColumnInfoData* pStartTsCol = taosArrayGet(pSrcBlock->pDataBlock, START_TS_COLUMN_INDEX);
L
Liu Jicong 已提交
1283
  TSKEY*           startData = (TSKEY*)pStartTsCol->pData;
1284
  SColumnInfoData* pEndTsCol = taosArrayGet(pSrcBlock->pDataBlock, END_TS_COLUMN_INDEX);
L
Liu Jicong 已提交
1285
  TSKEY*           endData = (TSKEY*)pEndTsCol->pData;
1286 1287
  SColumnInfoData* pUidCol = taosArrayGet(pSrcBlock->pDataBlock, UID_COLUMN_INDEX);
  uint64_t*        uidCol = (uint64_t*)pUidCol->pData;
L
Liu Jicong 已提交
1288

1289 1290
  SColumnInfoData* pDestStartCol = taosArrayGet(pDestBlock->pDataBlock, START_TS_COLUMN_INDEX);
  SColumnInfoData* pDestEndCol = taosArrayGet(pDestBlock->pDataBlock, END_TS_COLUMN_INDEX);
5
54liuyao 已提交
1291
  SColumnInfoData* pDestUidCol = taosArrayGet(pDestBlock->pDataBlock, UID_COLUMN_INDEX);
1292
  SColumnInfoData* pDestGpCol = taosArrayGet(pDestBlock->pDataBlock, GROUPID_COLUMN_INDEX);
5
54liuyao 已提交
1293 1294
  SColumnInfoData* pDestCalStartTsCol = taosArrayGet(pDestBlock->pDataBlock, CALCULATE_START_TS_COLUMN_INDEX);
  SColumnInfoData* pDestCalEndTsCol = taosArrayGet(pDestBlock->pDataBlock, CALCULATE_END_TS_COLUMN_INDEX);
L
Liu Jicong 已提交
1295
  int64_t          version = pSrcBlock->info.version - 1;
1296
  for (int32_t i = 0; i < pSrcBlock->info.rows; i++) {
1297
    uint64_t groupId = getGroupIdByData(pInfo, uidCol[i], startData[i], version);
L
Liu Jicong 已提交
1298
    // gap must be 0.
5
54liuyao 已提交
1299 1300 1301
    SSessionKey startWin = {0};
    getCurSessionWindow(pInfo->windowSup.pStreamAggSup, startData[i], endData[i], groupId, &startWin);
    if (IS_INVALID_SESSION_WIN_KEY(startWin)) {
L
Liu Jicong 已提交
1302 1303 1304
      // window has been closed.
      continue;
    }
5
54liuyao 已提交
1305 1306 1307 1308 1309 1310
    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 已提交
1311
    colDataAppendNULL(pDestUidCol, i);
L
Liu Jicong 已提交
1312
    colDataAppend(pDestGpCol, i, (const char*)&groupId, false);
5
54liuyao 已提交
1313 1314
    colDataAppendNULL(pDestCalStartTsCol, i);
    colDataAppendNULL(pDestCalEndTsCol, i);
1315
    pDestBlock->info.rows++;
L
Liu Jicong 已提交
1316
  }
1317
  return TSDB_CODE_SUCCESS;
L
Liu Jicong 已提交
1318
}
1319 1320 1321 1322 1323 1324

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;
1325
  }
1326
  int32_t code = blockDataEnsureCapacity(pDestBlock, rows * 2);
1327 1328 1329 1330
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

1331 1332
  SColumnInfoData* pSrcStartTsCol = (SColumnInfoData*)taosArrayGet(pSrcBlock->pDataBlock, START_TS_COLUMN_INDEX);
  SColumnInfoData* pSrcEndTsCol = (SColumnInfoData*)taosArrayGet(pSrcBlock->pDataBlock, END_TS_COLUMN_INDEX);
1333 1334 1335 1336
  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;
1337 1338 1339
  ASSERT(pSrcStartTsCol->info.type == TSDB_DATA_TYPE_TIMESTAMP);
  TSKEY*           srcStartTsCol = (TSKEY*)pSrcStartTsCol->pData;
  TSKEY*           srcEndTsCol = (TSKEY*)pSrcEndTsCol->pData;
1340 1341
  SColumnInfoData* pStartTsCol = taosArrayGet(pDestBlock->pDataBlock, START_TS_COLUMN_INDEX);
  SColumnInfoData* pEndTsCol = taosArrayGet(pDestBlock->pDataBlock, END_TS_COLUMN_INDEX);
1342
  SColumnInfoData* pDeUidCol = taosArrayGet(pDestBlock->pDataBlock, UID_COLUMN_INDEX);
1343 1344 1345
  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 已提交
1346
  int64_t          version = pSrcBlock->info.version - 1;
1347
  for (int32_t i = 0; i < rows;) {
1348
    uint64_t srcUid = srcUidData[i];
5
54liuyao 已提交
1349 1350 1351 1352 1353
    uint64_t groupId = srcGp[i];
    if (groupId == 0) {
      groupId = getGroupIdByData(pInfo, srcUid, srcStartTsCol[i], version);
    }
    TSKEY calStartTs = srcStartTsCol[i];
1354
    colDataAppend(pCalStartTsCol, pDestBlock->info.rows, (const char*)(&calStartTs), false);
5
54liuyao 已提交
1355
    STimeWindow win = getSlidingWindow(srcStartTsCol, srcEndTsCol, srcGp, &pInfo->interval, &pSrcBlock->info, &i,
1356 1357
                                       pInfo->partitionSup.needCalc);
    TSKEY       calEndTs = srcStartTsCol[i - 1];
1358 1359
    colDataAppend(pCalEndTsCol, pDestBlock->info.rows, (const char*)(&calEndTs), false);
    colDataAppend(pDeUidCol, pDestBlock->info.rows, (const char*)(&srcUid), false);
1360 1361 1362 1363
    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 已提交
1364
  }
1365 1366
  return TSDB_CODE_SUCCESS;
}
1367

1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405
static int32_t generateDeleteResultBlock(SStreamScanInfo* pInfo, SSDataBlock* pSrcBlock, SSDataBlock* pDestBlock) {
  if (pSrcBlock->info.rows == 0) {
    return TSDB_CODE_SUCCESS;
  }
  blockDataCleanup(pDestBlock);
  int32_t code = blockDataEnsureCapacity(pDestBlock, pSrcBlock->info.rows);
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }
  ASSERT(taosArrayGetSize(pSrcBlock->pDataBlock) >= 3);
  SColumnInfoData* pStartTsCol = taosArrayGet(pSrcBlock->pDataBlock, START_TS_COLUMN_INDEX);
  TSKEY*           startData = (TSKEY*)pStartTsCol->pData;
  SColumnInfoData* pEndTsCol = taosArrayGet(pSrcBlock->pDataBlock, END_TS_COLUMN_INDEX);
  TSKEY*           endData = (TSKEY*)pEndTsCol->pData;
  SColumnInfoData* pUidCol = taosArrayGet(pSrcBlock->pDataBlock, UID_COLUMN_INDEX);
  uint64_t*        uidCol = (uint64_t*)pUidCol->pData;

  SColumnInfoData* pDestStartCol = taosArrayGet(pDestBlock->pDataBlock, START_TS_COLUMN_INDEX);
  SColumnInfoData* pDestEndCol = taosArrayGet(pDestBlock->pDataBlock, END_TS_COLUMN_INDEX);
  SColumnInfoData* pDestUidCol = taosArrayGet(pDestBlock->pDataBlock, UID_COLUMN_INDEX);
  SColumnInfoData* pDestGpCol = taosArrayGet(pDestBlock->pDataBlock, GROUPID_COLUMN_INDEX);
  SColumnInfoData* pDestCalStartTsCol = taosArrayGet(pDestBlock->pDataBlock, CALCULATE_START_TS_COLUMN_INDEX);
  SColumnInfoData* pDestCalEndTsCol = taosArrayGet(pDestBlock->pDataBlock, CALCULATE_END_TS_COLUMN_INDEX);
  int32_t          dummy = 0;
  int64_t          version = pSrcBlock->info.version - 1;
  for (int32_t i = 0; i < pSrcBlock->info.rows; i++) {
    uint64_t groupId = getGroupIdByData(pInfo, uidCol[i], startData[i], version);
    colDataAppend(pDestStartCol, i, (const char*)(startData + i), false);
    colDataAppend(pDestEndCol, i, (const char*)(endData + i), false);
    colDataAppendNULL(pDestUidCol, i);
    colDataAppend(pDestGpCol, i, (const char*)&groupId, false);
    colDataAppendNULL(pDestCalStartTsCol, i);
    colDataAppendNULL(pDestCalEndTsCol, i);
    pDestBlock->info.rows++;
  }
  return TSDB_CODE_SUCCESS;
}

1406 1407 1408 1409
static int32_t generateScanRange(SStreamScanInfo* pInfo, SSDataBlock* pSrcBlock, SSDataBlock* pDestBlock) {
  int32_t code = TSDB_CODE_SUCCESS;
  if (isIntervalWindow(pInfo)) {
    code = generateIntervalScanRange(pInfo, pSrcBlock, pDestBlock);
1410
  } else if (isSessionWindow(pInfo) || isStateWindow(pInfo)) {
1411
    code = generateSessionScanRange(pInfo, pSrcBlock, pDestBlock);
1412
  }
1413
  pDestBlock->info.type = STREAM_CLEAR;
1414
  pDestBlock->info.version = pSrcBlock->info.version;
1415 1416 1417 1418
  blockDataUpdateTsWindow(pDestBlock, 0);
  return code;
}

L
Liu Jicong 已提交
1419 1420 1421 1422 1423 1424 1425 1426 1427
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 已提交
1428
  projectApplyFunctions(pTagCalSup->pExprInfo, pResBlock, pSrcBlock, pTagCalSup->pCtx, 1, NULL);
L
Liu Jicong 已提交
1429 1430 1431
  ASSERT(pResBlock->info.rows == 1);

  // build tagArray
1432 1433 1434 1435 1436
  /*SArray* tagArray = taosArrayInit(0, sizeof(void*));*/
  /*STagVal tagVal = {*/
  /*.cid = 0,*/
  /*.type = 0,*/
  /*};*/
L
Liu Jicong 已提交
1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464
  // build STag
  // set STag

  blockDataDestroy(pSrcBlock);
}

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

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

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

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

  void* pData = colDataGetData(pCol, 0);
  // TODO check tbname validation
  if (pData != (void*)-1 && pData != NULL) {
L
Liu Jicong 已提交
1465 1466
    memcpy(pBlock->info.parTbName, varDataVal(pData), TMIN(varDataLen(pData), TSDB_TABLE_NAME_LEN));
    pBlock->info.parTbName[TSDB_TABLE_NAME_LEN - 1] = 0;
L
Liu Jicong 已提交
1467 1468 1469 1470 1471 1472 1473 1474
  } else {
    pBlock->info.parTbName[0] = 0;
  }

  blockDataDestroy(pSrcBlock);
  blockDataDestroy(pResBlock);
}

1475 1476
void appendOneRowToStreamSpecialBlock(SSDataBlock* pBlock, TSKEY* pStartTs, TSKEY* pEndTs, uint64_t* pUid,
                                      uint64_t* pGp, void* pTbName) {
1477 1478
  SColumnInfoData* pStartTsCol = taosArrayGet(pBlock->pDataBlock, START_TS_COLUMN_INDEX);
  SColumnInfoData* pEndTsCol = taosArrayGet(pBlock->pDataBlock, END_TS_COLUMN_INDEX);
1479 1480
  SColumnInfoData* pUidCol = taosArrayGet(pBlock->pDataBlock, UID_COLUMN_INDEX);
  SColumnInfoData* pGpCol = taosArrayGet(pBlock->pDataBlock, GROUPID_COLUMN_INDEX);
1481 1482
  SColumnInfoData* pCalStartCol = taosArrayGet(pBlock->pDataBlock, CALCULATE_START_TS_COLUMN_INDEX);
  SColumnInfoData* pCalEndCol = taosArrayGet(pBlock->pDataBlock, CALCULATE_END_TS_COLUMN_INDEX);
1483
  SColumnInfoData* pTableCol = taosArrayGet(pBlock->pDataBlock, TABLE_NAME_COLUMN_INDEX);
1484 1485
  colDataAppend(pStartTsCol, pBlock->info.rows, (const char*)pStartTs, false);
  colDataAppend(pEndTsCol, pBlock->info.rows, (const char*)pEndTs, false);
1486 1487
  colDataAppend(pUidCol, pBlock->info.rows, (const char*)pUid, false);
  colDataAppend(pGpCol, pBlock->info.rows, (const char*)pGp, false);
1488 1489
  colDataAppend(pCalStartCol, pBlock->info.rows, (const char*)pStartTs, false);
  colDataAppend(pCalEndCol, pBlock->info.rows, (const char*)pEndTs, false);
1490
  colDataAppend(pTableCol, pBlock->info.rows, (const char*)pTbName, pTbName == NULL);
1491
  pBlock->info.rows++;
5
54liuyao 已提交
1492 1493
}

1494
static void checkUpdateData(SStreamScanInfo* pInfo, bool invertible, SSDataBlock* pBlock, bool out) {
1495 1496
  if (out) {
    blockDataCleanup(pInfo->pUpdateDataRes);
5
54liuyao 已提交
1497
    blockDataEnsureCapacity(pInfo->pUpdateDataRes, pBlock->info.rows * 2);
1498
  }
1499 1500
  SColumnInfoData* pColDataInfo = taosArrayGet(pBlock->pDataBlock, pInfo->primaryTsIndex);
  ASSERT(pColDataInfo->info.type == TSDB_DATA_TYPE_TIMESTAMP);
5
54liuyao 已提交
1501
  TSKEY* tsCol = (TSKEY*)pColDataInfo->pData;
L
Liu Jicong 已提交
1502
  bool   tableInserted = updateInfoIsTableInserted(pInfo->pUpdateInfo, pBlock->info.uid);
1503
  for (int32_t rowId = 0; rowId < pBlock->info.rows; rowId++) {
5
54liuyao 已提交
1504 1505
    SResultRowInfo dumyInfo;
    dumyInfo.cur.pageId = -1;
L
Liu Jicong 已提交
1506
    bool        isClosed = false;
5
54liuyao 已提交
1507
    STimeWindow win = {.skey = INT64_MIN, .ekey = INT64_MAX};
L
Liu Jicong 已提交
1508
    if (tableInserted && isOverdue(tsCol[rowId], &pInfo->twAggSup)) {
5
54liuyao 已提交
1509 1510 1511
      win = getActiveTimeWindow(NULL, &dumyInfo, tsCol[rowId], &pInfo->interval, TSDB_ORDER_ASC);
      isClosed = isCloseWindow(&win, &pInfo->twAggSup);
    }
5
54liuyao 已提交
1512 1513
    // must check update info first.
    bool update = updateInfoIsUpdated(pInfo->pUpdateInfo, pBlock->info.uid, tsCol[rowId]);
L
Liu Jicong 已提交
1514
    bool closedWin = isClosed && isSignleIntervalWindow(pInfo) &&
1515 1516
                     isDeletedStreamWindow(&win, pBlock->info.groupId,
                                           pInfo->pTableScanOp->pTaskInfo->streamInfo.pState, &pInfo->twAggSup);
L
Liu Jicong 已提交
1517
    if ((update || closedWin) && out) {
L
Liu Jicong 已提交
1518
      qDebug("stream update check not pass, update %d, closedWin %d", update, closedWin);
5
54liuyao 已提交
1519
      uint64_t gpId = 0;
1520 1521
      appendOneRowToStreamSpecialBlock(pInfo->pUpdateDataRes, tsCol + rowId, tsCol + rowId, &pBlock->info.uid, &gpId,
                                       NULL);
5
54liuyao 已提交
1522 1523
      if (closedWin && pInfo->partitionSup.needCalc) {
        gpId = calGroupIdByData(&pInfo->partitionSup, pInfo->pPartScalarSup, pBlock, rowId);
1524 1525
        appendOneRowToStreamSpecialBlock(pInfo->pUpdateDataRes, tsCol + rowId, tsCol + rowId, &pBlock->info.uid, &gpId,
                                         NULL);
5
54liuyao 已提交
1526
      }
1527 1528
    }
  }
1529 1530
  if (out && pInfo->pUpdateDataRes->info.rows > 0) {
    pInfo->pUpdateDataRes->info.version = pBlock->info.version;
1531
    blockDataUpdateTsWindow(pInfo->pUpdateDataRes, 0);
1532
    pInfo->pUpdateDataRes->info.type = pInfo->partitionSup.needCalc ? STREAM_DELETE_DATA : STREAM_CLEAR;
5
54liuyao 已提交
1533 1534
  }
}
L
Liu Jicong 已提交
1535

1536
static int32_t setBlockIntoRes(SStreamScanInfo* pInfo, const SSDataBlock* pBlock, bool filter) {
L
Liu Jicong 已提交
1537 1538
  SDataBlockInfo* pBlockInfo = &pInfo->pRes->info;
  SOperatorInfo*  pOperator = pInfo->pStreamScanOp;
L
Liu Jicong 已提交
1539
  SExecTaskInfo*  pTaskInfo = pOperator->pTaskInfo;
L
Liu Jicong 已提交
1540

1541 1542
  blockDataEnsureCapacity(pInfo->pRes, pBlock->info.rows);

L
Liu Jicong 已提交
1543 1544 1545
  pInfo->pRes->info.rows = pBlock->info.rows;
  pInfo->pRes->info.uid = pBlock->info.uid;
  pInfo->pRes->info.type = STREAM_NORMAL;
1546
  pInfo->pRes->info.version = pBlock->info.version;
L
Liu Jicong 已提交
1547

L
Liu Jicong 已提交
1548
  uint64_t* groupIdPre = taosHashGet(pTaskInfo->tableqinfoList.map, &pBlock->info.uid, sizeof(int64_t));
L
Liu Jicong 已提交
1549 1550 1551 1552 1553 1554 1555
  if (groupIdPre) {
    pInfo->pRes->info.groupId = *groupIdPre;
  } else {
    pInfo->pRes->info.groupId = 0;
  }

  // todo extract method
H
Haojun Liao 已提交
1556 1557 1558
  for (int32_t i = 0; i < taosArrayGetSize(pInfo->matchInfo.pList); ++i) {
    SColMatchItem* pColMatchInfo = taosArrayGet(pInfo->matchInfo.pList, i);
    if (!pColMatchInfo->needOutput) {
L
Liu Jicong 已提交
1559 1560 1561 1562 1563 1564 1565
      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 已提交
1566
        SColumnInfoData* pDst = taosArrayGet(pInfo->pRes->pDataBlock, pColMatchInfo->dstSlotId);
1567
        colDataAssign(pDst, pResCol, pBlock->info.rows, &pInfo->pRes->info);
L
Liu Jicong 已提交
1568 1569 1570 1571 1572 1573 1574
        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 已提交
1575
      SColumnInfoData* pDst = taosArrayGet(pInfo->pRes->pDataBlock, pColMatchInfo->dstSlotId);
L
Liu Jicong 已提交
1576 1577 1578 1579 1580 1581
      colDataAppendNNULL(pDst, 0, pBlockInfo->rows);
    }
  }

  // currently only the tbname pseudo column
  if (pInfo->numOfPseudoExpr > 0) {
L
Liu Jicong 已提交
1582 1583
    int32_t code = addTagPseudoColumnData(&pInfo->readHandle, pInfo->pPseudoExpr, pInfo->numOfPseudoExpr, pInfo->pRes,
                                          GET_TASKID(pTaskInfo));
H
Haojun Liao 已提交
1584
    if (code != TSDB_CODE_SUCCESS) {
L
Liu Jicong 已提交
1585
      blockDataFreeRes((SSDataBlock*)pBlock);
1586
      T_LONG_JMP(pTaskInfo->env, code);
H
Haojun Liao 已提交
1587
    }
L
Liu Jicong 已提交
1588 1589
  }

1590
  if (filter) {
D
dapan1121 已提交
1591
    doFilter(pInfo->pCondition, pInfo->pRes, NULL, NULL);
1592
  }
L
Liu Jicong 已提交
1593
  blockDataUpdateTsWindow(pInfo->pRes, pInfo->primaryTsIndex);
L
Liu Jicong 已提交
1594
  blockDataFreeRes((SSDataBlock*)pBlock);
L
Liu Jicong 已提交
1595

L
Liu Jicong 已提交
1596
  calBlockTbName(&pInfo->tbnameCalSup, pInfo->pRes);
L
Liu Jicong 已提交
1597

L
Liu Jicong 已提交
1598 1599
  return 0;
}
5
54liuyao 已提交
1600

L
Liu Jicong 已提交
1601
static SSDataBlock* doQueueScan(SOperatorInfo* pOperator) {
1602 1603
  SExecTaskInfo*   pTaskInfo = pOperator->pTaskInfo;
  SStreamScanInfo* pInfo = pOperator->info;
H
Haojun Liao 已提交
1604

L
Liu Jicong 已提交
1605
  qDebug("queue scan called");
L
Liu Jicong 已提交
1606 1607 1608 1609 1610 1611 1612 1613

  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 已提交
1614
        pTaskInfo->streamInfo.pReq = NULL;
L
Liu Jicong 已提交
1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630
        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;
      }

1631
      setBlockIntoRes(pInfo, &block, true);
L
Liu Jicong 已提交
1632 1633 1634 1635 1636 1637 1638 1639

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

    pInfo->tqReader->pMsg = NULL;
    pTaskInfo->streamInfo.pReq = NULL;
L
Liu Jicong 已提交
1640
    return NULL;
L
Liu Jicong 已提交
1641 1642
  }

L
Liu Jicong 已提交
1643 1644 1645
  if (pTaskInfo->streamInfo.prepareStatus.type == TMQ_OFFSET__SNAPSHOT_DATA) {
    SSDataBlock* pResult = doTableScan(pInfo->pTableScanOp);
    if (pResult && pResult->info.rows > 0) {
L
Liu Jicong 已提交
1646
      qDebug("queue scan tsdb return %d rows", pResult->info.rows);
1647
      pTaskInfo->streamInfo.returned = 1;
L
Liu Jicong 已提交
1648 1649
      return pResult;
    } else {
1650 1651 1652 1653 1654
      if (!pTaskInfo->streamInfo.returned) {
        STableScanInfo* pTSInfo = pInfo->pTableScanOp->info;
        tsdbReaderClose(pTSInfo->dataReader);
        pTSInfo->dataReader = NULL;
        tqOffsetResetToLog(&pTaskInfo->streamInfo.prepareStatus, pTaskInfo->streamInfo.snapshotVer);
1655
        qDebug("queue scan tsdb over, switch to wal ver %" PRId64 "", pTaskInfo->streamInfo.snapshotVer + 1);
1656 1657 1658 1659 1660
        if (tqSeekVer(pInfo->tqReader, pTaskInfo->streamInfo.snapshotVer + 1) < 0) {
          return NULL;
        }
        ASSERT(pInfo->tqReader->pWalReader->curVersion == pTaskInfo->streamInfo.snapshotVer + 1);
      } else {
L
Liu Jicong 已提交
1661 1662
        return NULL;
      }
1663 1664 1665
    }
  }

L
Liu Jicong 已提交
1666 1667 1668 1669 1670 1671
  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);
1672
        if (setBlockIntoRes(pInfo, &ret.data, true) < 0) {
L
Liu Jicong 已提交
1673 1674 1675
          ASSERT(0);
        }
        if (pInfo->pRes->info.rows > 0) {
L
Liu Jicong 已提交
1676
          pOperator->status = OP_EXEC_RECV;
L
Liu Jicong 已提交
1677
          qDebug("queue scan log return %d rows", pInfo->pRes->info.rows);
L
Liu Jicong 已提交
1678 1679 1680 1681
          return pInfo->pRes;
        }
      } else if (ret.fetchType == FETCH_TYPE__META) {
        ASSERT(0);
L
Liu Jicong 已提交
1682 1683 1684
        //        pTaskInfo->streamInfo.lastStatus = ret.offset;
        //        pTaskInfo->streamInfo.metaBlk = ret.meta;
        //        return NULL;
L
Liu Jicong 已提交
1685 1686
      } else if (ret.fetchType == FETCH_TYPE__NONE ||
                 (ret.fetchType == FETCH_TYPE__SEP && pOperator->status == OP_EXEC_RECV)) {
L
Liu Jicong 已提交
1687
        pTaskInfo->streamInfo.lastStatus = ret.offset;
1688 1689 1690 1691
        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 已提交
1692
        qDebug("queue scan log return null, offset %s", formatBuf);
L
Liu Jicong 已提交
1693
        pOperator->status = OP_OPENED;
L
Liu Jicong 已提交
1694 1695 1696
        return NULL;
      }
    }
L
Liu Jicong 已提交
1697
#if 0
L
Liu Jicong 已提交
1698 1699
  } else if (pTaskInfo->streamInfo.prepareStatus.type == TMQ_OFFSET__SNAPSHOT_DATA) {
    SSDataBlock* pResult = doTableScan(pInfo->pTableScanOp);
L
Liu Jicong 已提交
1700 1701 1702 1703 1704 1705
    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 已提交
1706
#endif
L
Liu Jicong 已提交
1707 1708 1709
  } else {
    ASSERT(0);
    return NULL;
H
Haojun Liao 已提交
1710
  }
L
Liu Jicong 已提交
1711 1712
}

L
Liu Jicong 已提交
1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740
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 已提交
1741
  uint32_t cap = pDst->info.capacity;
L
Liu Jicong 已提交
1742 1743
  pDst->info = pSrc->info;
  pDst->info.rows = j;
L
Liu Jicong 已提交
1744
  pDst->info.capacity = cap;
L
Liu Jicong 已提交
1745 1746 1747 1748

  return 0;
}

5
54liuyao 已提交
1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772
// 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 已提交
1773 1774 1775 1776 1777
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 已提交
1778
  qDebug("stream scan called");
L
Liu Jicong 已提交
1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811
#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 已提交
1812
  }
L
Liu Jicong 已提交
1813
#endif
H
Haojun Liao 已提交
1814

L
Liu Jicong 已提交
1815
#if 1
1816 1817
  if (pTaskInfo->streamInfo.recoverStep == STREAM_RECOVER_STEP__PREPARE1 ||
      pTaskInfo->streamInfo.recoverStep == STREAM_RECOVER_STEP__PREPARE2) {
L
Liu Jicong 已提交
1818 1819
    STableScanInfo* pTSInfo = pInfo->pTableScanOp->info;
    memcpy(&pTSInfo->cond, &pTaskInfo->streamInfo.tableCond, sizeof(SQueryTableDataCond));
1820 1821 1822 1823 1824 1825 1826
    if (pTaskInfo->streamInfo.recoverStep == STREAM_RECOVER_STEP__PREPARE1) {
      pTSInfo->cond.startVersion = -1;
      pTSInfo->cond.endVersion = pTaskInfo->streamInfo.fillHistoryVer1;
    } else {
      pTSInfo->cond.startVersion = pTaskInfo->streamInfo.fillHistoryVer1 + 1;
      pTSInfo->cond.endVersion = pTaskInfo->streamInfo.fillHistoryVer2;
    }
L
Liu Jicong 已提交
1827 1828 1829 1830 1831 1832 1833 1834
    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 已提交
1835 1836
      calBlockTbName(&pInfo->tbnameCalSup, pBlock);
      updateInfoFillBlockData(pInfo->pUpdateInfo, pBlock, pInfo->primaryTsIndex);
L
Liu Jicong 已提交
1837 1838 1839 1840 1841
      return pBlock;
    }
    pTaskInfo->streamInfo.recoverStep = STREAM_RECOVER_STEP__NONE;
    return NULL;
  }
L
Liu Jicong 已提交
1842
#endif
L
Liu Jicong 已提交
1843

5
54liuyao 已提交
1844
  size_t total = taosArrayGetSize(pInfo->pBlockLists);
1845
  // TODO: refactor
L
Liu Jicong 已提交
1846
FETCH_NEXT_BLOCK:
L
Liu Jicong 已提交
1847
  if (pInfo->blockType == STREAM_INPUT__DATA_BLOCK) {
H
Haojun Liao 已提交
1848
    if (pInfo->validBlockIndex >= total) {
L
Liu Jicong 已提交
1849
      doClearBufferedBlocks(pInfo);
L
Liu Jicong 已提交
1850
      /*pOperator->status = OP_EXEC_DONE;*/
H
Haojun Liao 已提交
1851 1852 1853
      return NULL;
    }

1854
    int32_t      current = pInfo->validBlockIndex++;
1855
    SSDataBlock* pBlock = taosArrayGetP(pInfo->pBlockLists, current);
1856
    // TODO move into scan
5
54liuyao 已提交
1857 1858
    pBlock->info.calWin.skey = INT64_MIN;
    pBlock->info.calWin.ekey = INT64_MAX;
1859
    blockDataUpdateTsWindow(pBlock, 0);
1860
    switch (pBlock->info.type) {
L
Liu Jicong 已提交
1861 1862 1863
      case STREAM_NORMAL:
      case STREAM_GET_ALL:
        return pBlock;
1864 1865 1866
      case STREAM_RETRIEVE: {
        pInfo->blockType = STREAM_INPUT__DATA_SUBMIT;
        pInfo->scanMode = STREAM_SCAN_FROM_DATAREADER_RETRIEVE;
1867 1868
        copyDataBlock(pInfo->pUpdateRes, pBlock);
        prepareRangeScan(pInfo, pInfo->pUpdateRes, &pInfo->updateResIndex);
1869 1870 1871
        updateInfoAddCloseWindowSBF(pInfo->pUpdateInfo);
      } break;
      case STREAM_DELETE_DATA: {
1872
        printDataBlock(pBlock, "stream scan delete recv");
L
Liu Jicong 已提交
1873
        SSDataBlock* pDelBlock = NULL;
L
Liu Jicong 已提交
1874
        if (pInfo->tqReader) {
L
Liu Jicong 已提交
1875
          pDelBlock = createSpecialDataBlock(STREAM_DELETE_DATA);
L
Liu Jicong 已提交
1876
          filterDelBlockByUid(pDelBlock, pBlock, pInfo);
L
Liu Jicong 已提交
1877 1878
        } else {
          pDelBlock = pBlock;
L
Liu Jicong 已提交
1879
        }
5
54liuyao 已提交
1880 1881
        setBlockGroupIdByUid(pInfo, pDelBlock);
        printDataBlock(pDelBlock, "stream scan delete recv filtered");
1882
        if (!isIntervalWindow(pInfo) && !isSessionWindow(pInfo) && !isStateWindow(pInfo)) {
L
Liu Jicong 已提交
1883
          generateDeleteResultBlock(pInfo, pDelBlock, pInfo->pDeleteDataRes);
1884
          pInfo->pDeleteDataRes->info.type = STREAM_DELETE_RESULT;
L
Liu Jicong 已提交
1885
          printDataBlock(pDelBlock, "stream scan delete result");
H
Haojun Liao 已提交
1886 1887
          blockDataDestroy(pDelBlock);

L
Liu Jicong 已提交
1888 1889 1890 1891 1892
          if (pInfo->pDeleteDataRes->info.rows > 0) {
            return pInfo->pDeleteDataRes;
          } else {
            goto FETCH_NEXT_BLOCK;
          }
1893 1894 1895
        } else {
          pInfo->blockType = STREAM_INPUT__DATA_SUBMIT;
          pInfo->updateResIndex = 0;
L
Liu Jicong 已提交
1896
          generateScanRange(pInfo, pDelBlock, pInfo->pUpdateRes);
1897 1898 1899 1900
          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 已提交
1901 1902 1903 1904
          printDataBlock(pDelBlock, "stream scan delete data");
          if (pInfo->tqReader) {
            blockDataDestroy(pDelBlock);
          }
L
Liu Jicong 已提交
1905 1906 1907 1908 1909
          if (pInfo->pDeleteDataRes->info.rows > 0) {
            return pInfo->pDeleteDataRes;
          } else {
            goto FETCH_NEXT_BLOCK;
          }
1910
        }
1911 1912 1913
      } break;
      default:
        break;
5
54liuyao 已提交
1914
    }
1915
    // printDataBlock(pBlock, "stream scan recv");
1916
    return pBlock;
L
Liu Jicong 已提交
1917
  } else if (pInfo->blockType == STREAM_INPUT__DATA_SUBMIT) {
L
Liu Jicong 已提交
1918
    qDebug("scan mode %d", pInfo->scanMode);
5
54liuyao 已提交
1919 1920 1921 1922 1923 1924
    switch (pInfo->scanMode) {
      case STREAM_SCAN_FROM_RES: {
        blockDataDestroy(pInfo->pUpdateRes);
        pInfo->scanMode = STREAM_SCAN_FROM_READERHANDLE;
        return pInfo->pRes;
      } break;
1925
      case STREAM_SCAN_FROM_DELETE_DATA: {
1926 1927 1928 1929 1930 1931 1932
        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 已提交
1933 1934 1935 1936 1937 1938 1939 1940 1941 1942
      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) {
1943
          STableScanInfo* pTableScanInfo = pInfo->pTableScanOp->info;
L
Liu Jicong 已提交
1944 1945
          uint64_t        version = getReaderMaxVersion(pTableScanInfo->dataReader);
          updateInfoSetScanRange(pInfo->pUpdateInfo, &pTableScanInfo->cond.twindows, pInfo->groupId, version);
5
54liuyao 已提交
1946 1947
          pSDB->info.type = pInfo->scanMode == STREAM_SCAN_FROM_DATAREADER_RANGE ? STREAM_NORMAL : STREAM_PULL_DATA;
          checkUpdateData(pInfo, true, pSDB, false);
1948
          // printDataBlock(pSDB, "stream scan update");
L
Liu Jicong 已提交
1949
          calBlockTbName(&pInfo->tbnameCalSup, pSDB);
5
54liuyao 已提交
1950 1951
          return pSDB;
        }
1952
        blockDataCleanup(pInfo->pUpdateDataRes);
5
54liuyao 已提交
1953 1954 1955 1956
        pInfo->scanMode = STREAM_SCAN_FROM_READERHANDLE;
      } break;
      default:
        break;
1957
    }
1958

1959
    SStreamAggSupporter* pSup = pInfo->windowSup.pStreamAggSup;
5
54liuyao 已提交
1960
    if (isStateWindow(pInfo) && pSup->pScanBlock->info.rows > 0) {
1961 1962
      pInfo->scanMode = STREAM_SCAN_FROM_DATAREADER_RANGE;
      pInfo->updateResIndex = 0;
5
54liuyao 已提交
1963 1964
      copyDataBlock(pInfo->pUpdateRes, pSup->pScanBlock);
      blockDataCleanup(pSup->pScanBlock);
1965 1966
      prepareRangeScan(pInfo, pInfo->pUpdateRes, &pInfo->updateResIndex);
      return pInfo->pUpdateRes;
5
54liuyao 已提交
1967
    }
5
54liuyao 已提交
1968

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

1971
    int32_t totBlockNum = taosArrayGetSize(pInfo->pBlockLists);
1972

L
Liu Jicong 已提交
1973
  NEXT_SUBMIT_BLK:
1974 1975 1976
    while (1) {
      if (pInfo->tqReader->pMsg == NULL) {
        if (pInfo->validBlockIndex >= totBlockNum) {
5
54liuyao 已提交
1977
          updateInfoDestoryColseWinSBF(pInfo->pUpdateInfo);
L
Liu Jicong 已提交
1978
          doClearBufferedBlocks(pInfo);
1979 1980
          return NULL;
        }
1981

1982 1983 1984 1985 1986 1987 1988 1989
        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 已提交
1990 1991
      }

1992 1993 1994 1995
      blockDataCleanup(pInfo->pRes);

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

1997 1998 1999 2000 2001 2002
        int32_t code = tqRetrieveDataBlock(&block, pInfo->tqReader);

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

2003
        setBlockIntoRes(pInfo, &block, false);
2004

L
Liu Jicong 已提交
2005 2006
        if (updateInfoIgnore(pInfo->pUpdateInfo, &pInfo->pRes->info.window, pInfo->pRes->info.groupId,
                             pInfo->pRes->info.version)) {
2007 2008 2009 2010 2011
          printDataBlock(pInfo->pRes, "stream scan ignore");
          blockDataCleanup(pInfo->pRes);
          continue;
        }

2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027
        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 已提交
2028
        doFilter(pInfo->pCondition, pInfo->pRes, NULL, NULL);
2029 2030 2031
        blockDataUpdateTsWindow(pInfo->pRes, pInfo->primaryTsIndex);

        if (pBlockInfo->rows > 0 || pInfo->pUpdateDataRes->info.rows > 0) {
2032 2033 2034
          break;
        }
      }
2035
      if (pBlockInfo->rows > 0 || pInfo->pUpdateDataRes->info.rows > 0) {
5
54liuyao 已提交
2036
        break;
J
jiacy-jcy 已提交
2037 2038
      } else {
        pInfo->tqReader->pMsg = NULL;
2039
        continue;
5
54liuyao 已提交
2040
      }
2041
      /*blockDataCleanup(pInfo->pRes);*/
H
Haojun Liao 已提交
2042 2043 2044 2045
    }

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

L
Liu Jicong 已提交
2049
    qDebug("scan rows: %d", pBlockInfo->rows);
L
Liu Jicong 已提交
2050 2051 2052
    if (pBlockInfo->rows > 0) {
      return pInfo->pRes;
    }
2053 2054 2055 2056 2057 2058

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

    goto NEXT_SUBMIT_BLK;
L
Liu Jicong 已提交
2059 2060 2061
  } else {
    ASSERT(0);
    return NULL;
H
Haojun Liao 已提交
2062 2063 2064
  }
}

2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076
static SArray* extractTableIdList(const STableListInfo* pTableGroupInfo) {
  SArray* tableIdList = taosArrayInit(4, sizeof(uint64_t));

  // Transfer the Array of STableKeyInfo into uid list.
  for (int32_t i = 0; i < taosArrayGetSize(pTableGroupInfo->pTableList); ++i) {
    STableKeyInfo* pkeyInfo = taosArrayGet(pTableGroupInfo->pTableList, i);
    taosArrayPush(tableIdList, &pkeyInfo->uid);
  }

  return tableIdList;
}

2077
static SSDataBlock* doRawScan(SOperatorInfo* pOperator) {
L
Liu Jicong 已提交
2078 2079
  // NOTE: this operator does never check if current status is done or not
  SExecTaskInfo*      pTaskInfo = pOperator->pTaskInfo;
2080
  SStreamRawScanInfo* pInfo = pOperator->info;
L
Liu Jicong 已提交
2081
  pTaskInfo->streamInfo.metaRsp.metaRspLen = 0;  // use metaRspLen !=0 to judge if data is meta
wmmhello's avatar
wmmhello 已提交
2082
  pTaskInfo->streamInfo.metaRsp.metaRsp = NULL;
2083

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

2088
    if (pInfo->dataReader && tsdbNextDataBlock(pInfo->dataReader)) {
wmmhello's avatar
wmmhello 已提交
2089 2090 2091
      if (isTaskKilled(pTaskInfo)) {
        longjmp(pTaskInfo->env, TSDB_CODE_TSC_QUERY_CANCELLED);
      }
2092

wmmhello's avatar
wmmhello 已提交
2093
      tsdbRetrieveDataBlockInfo(pInfo->dataReader, &pBlock->info);
2094

wmmhello's avatar
wmmhello 已提交
2095 2096 2097
      SArray* pCols = tsdbRetrieveDataBlock(pInfo->dataReader, NULL);
      pBlock->pDataBlock = pCols;
      if (pCols == NULL) {
wmmhello's avatar
wmmhello 已提交
2098
        longjmp(pTaskInfo->env, terrno);
wmmhello's avatar
wmmhello 已提交
2099 2100
      }

2101
      qDebug("tmqsnap doRawScan get data uid:%" PRId64 "", pBlock->info.uid);
wmmhello's avatar
wmmhello 已提交
2102 2103 2104 2105 2106
      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 已提交
2107 2108

    SMetaTableInfo mtInfo = getUidfromSnapShot(pInfo->sContext);
L
Liu Jicong 已提交
2109
    if (mtInfo.uid == 0) {  // read snapshot done, change to get data from wal
wmmhello's avatar
wmmhello 已提交
2110 2111
      qDebug("tmqsnap read snapshot done, change to get data from wal");
      pTaskInfo->streamInfo.prepareStatus.uid = mtInfo.uid;
wmmhello's avatar
wmmhello 已提交
2112 2113
      pTaskInfo->streamInfo.lastStatus.type = TMQ_OFFSET__LOG;
      pTaskInfo->streamInfo.lastStatus.version = pInfo->sContext->snapVersion;
L
Liu Jicong 已提交
2114
    } else {
wmmhello's avatar
wmmhello 已提交
2115 2116
      pTaskInfo->streamInfo.prepareStatus.uid = mtInfo.uid;
      pTaskInfo->streamInfo.prepareStatus.ts = INT64_MIN;
2117
      qDebug("tmqsnap change get data uid:%" PRId64 "", mtInfo.uid);
wmmhello's avatar
wmmhello 已提交
2118 2119
      qStreamPrepareScan(pTaskInfo, &pTaskInfo->streamInfo.prepareStatus, pInfo->sContext->subType);
    }
2120
    tDeleteSSchemaWrapper(mtInfo.schema);
wmmhello's avatar
wmmhello 已提交
2121
    qDebug("tmqsnap stream scan tsdb return null");
wmmhello's avatar
wmmhello 已提交
2122
    return NULL;
L
Liu Jicong 已提交
2123 2124 2125 2126 2127 2128 2129
  } 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 已提交
2130
      qError("tmqsnap getMetafromSnapShot error");
wmmhello's avatar
wmmhello 已提交
2131
      taosMemoryFreeClear(data);
2132 2133 2134
      return NULL;
    }

L
Liu Jicong 已提交
2135
    if (!sContext->queryMetaOrData) {  // change to get data next poll request
wmmhello's avatar
wmmhello 已提交
2136 2137 2138 2139
      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 已提交
2140
      pTaskInfo->streamInfo.metaRsp.rspOffset.ts = INT64_MIN;
L
Liu Jicong 已提交
2141
    } else {
wmmhello's avatar
wmmhello 已提交
2142 2143 2144 2145 2146 2147 2148
      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;
    }
2149

wmmhello's avatar
wmmhello 已提交
2150
    return NULL;
2151
  }
L
Liu Jicong 已提交
2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189
  //  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;
  //      }
  //    }
2190 2191 2192
  return NULL;
}

wmmhello's avatar
wmmhello 已提交
2193
static void destroyRawScanOperatorInfo(void* param) {
wmmhello's avatar
wmmhello 已提交
2194 2195 2196 2197 2198 2199
  SStreamRawScanInfo* pRawScan = (SStreamRawScanInfo*)param;
  tsdbReaderClose(pRawScan->dataReader);
  destroySnapContext(pRawScan->sContext);
  taosMemoryFree(pRawScan);
}

L
Liu Jicong 已提交
2200 2201 2202
// for subscribing db or stb (not including column),
// if this scan is used, meta data can be return
// and schemas are decided when scanning
2203
SOperatorInfo* createRawScanOperatorInfo(SReadHandle* pHandle, SExecTaskInfo* pTaskInfo) {
L
Liu Jicong 已提交
2204 2205 2206 2207 2208
  // create operator
  // create tb reader
  // create meta reader
  // create tq reader

H
Haojun Liao 已提交
2209 2210
  int32_t code = TSDB_CODE_SUCCESS;

2211
  SStreamRawScanInfo* pInfo = taosMemoryCalloc(1, sizeof(SStreamRawScanInfo));
L
Liu Jicong 已提交
2212
  SOperatorInfo*      pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
2213
  if (pInfo == NULL || pOperator == NULL) {
H
Haojun Liao 已提交
2214 2215
    code = TSDB_CODE_OUT_OF_MEMORY;
    goto _end;
2216 2217
  }

wmmhello's avatar
wmmhello 已提交
2218 2219
  pInfo->vnode = pHandle->vnode;

2220 2221 2222 2223 2224
  pInfo->sContext = pHandle->sContext;
  pOperator->name = "RawStreamScanOperator";
  pOperator->info = pInfo;
  pOperator->pTaskInfo = pTaskInfo;

2225
  pOperator->fpSet = createOperatorFpSet(NULL, doRawScan, NULL, NULL, destroyRawScanOperatorInfo, NULL);
2226
  return pOperator;
H
Haojun Liao 已提交
2227

L
Liu Jicong 已提交
2228
_end:
H
Haojun Liao 已提交
2229 2230 2231 2232
  taosMemoryFree(pInfo);
  taosMemoryFree(pOperator);
  pTaskInfo->code = code;
  return NULL;
L
Liu Jicong 已提交
2233 2234
}

2235
static void destroyStreamScanOperatorInfo(void* param) {
2236 2237 2238
  SStreamScanInfo* pStreamScan = (SStreamScanInfo*)param;
  if (pStreamScan->pTableScanOp && pStreamScan->pTableScanOp->info) {
    STableScanInfo* pTableScanInfo = pStreamScan->pTableScanOp->info;
2239
    destroyTableScanOperatorInfo(pTableScanInfo);
5
54liuyao 已提交
2240
    taosMemoryFreeClear(pStreamScan->pTableScanOp);
2241 2242 2243 2244
  }
  if (pStreamScan->tqReader) {
    tqCloseReader(pStreamScan->tqReader);
  }
H
Haojun Liao 已提交
2245 2246
  if (pStreamScan->matchInfo.pList) {
    taosArrayDestroy(pStreamScan->matchInfo.pList);
2247
  }
C
Cary Xu 已提交
2248 2249
  if (pStreamScan->pPseudoExpr) {
    destroyExprInfo(pStreamScan->pPseudoExpr, pStreamScan->numOfPseudoExpr);
L
Liu Jicong 已提交
2250
    taosMemoryFree(pStreamScan->pPseudoExpr);
C
Cary Xu 已提交
2251
  }
C
Cary Xu 已提交
2252

L
Liu Jicong 已提交
2253
  updateInfoDestroy(pStreamScan->pUpdateInfo);
2254 2255 2256 2257
  blockDataDestroy(pStreamScan->pRes);
  blockDataDestroy(pStreamScan->pUpdateRes);
  blockDataDestroy(pStreamScan->pPullDataRes);
  blockDataDestroy(pStreamScan->pDeleteDataRes);
5
54liuyao 已提交
2258
  blockDataDestroy(pStreamScan->pUpdateDataRes);
2259 2260 2261 2262
  taosArrayDestroy(pStreamScan->pBlockLists);
  taosMemoryFree(pStreamScan);
}

2263
SOperatorInfo* createStreamScanOperatorInfo(SReadHandle* pHandle, STableScanPhysiNode* pTableScanNode, SNode* pTagCond,
2264
                                            SExecTaskInfo* pTaskInfo) {
2265 2266
  SStreamScanInfo* pInfo = taosMemoryCalloc(1, sizeof(SStreamScanInfo));
  SOperatorInfo*   pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
2267

H
Haojun Liao 已提交
2268 2269
  if (pInfo == NULL || pOperator == NULL) {
    terrno = TSDB_CODE_QRY_OUT_OF_MEMORY;
2270
    goto _error;
H
Haojun Liao 已提交
2271 2272
  }

2273
  SScanPhysiNode*     pScanPhyNode = &pTableScanNode->scan;
2274
  SDataBlockDescNode* pDescNode = pScanPhyNode->node.pOutputDataBlockDesc;
H
Haojun Liao 已提交
2275

2276
  pInfo->pTagCond = pTagCond;
2277
  pInfo->pGroupTags = pTableScanNode->pGroupTags;
2278

2279
  int32_t numOfCols = 0;
2280 2281
  int32_t code =
      extractColMatchInfo(pScanPhyNode->pScanCols, pDescNode, &numOfCols, COL_MATCH_FROM_COL_ID, &pInfo->matchInfo);
2282

H
Haojun Liao 已提交
2283
  int32_t numOfOutput = taosArrayGetSize(pInfo->matchInfo.pList);
2284
  SArray* pColIds = taosArrayInit(numOfOutput, sizeof(int16_t));
2285
  for (int32_t i = 0; i < numOfOutput; ++i) {
H
Haojun Liao 已提交
2286
    SColMatchItem* id = taosArrayGet(pInfo->matchInfo.pList, i);
2287 2288

    int16_t colId = id->colId;
2289
    taosArrayPush(pColIds, &colId);
2290
    if (id->colId == PRIMARYKEY_TIMESTAMP_COL_ID) {
H
Haojun Liao 已提交
2291
      pInfo->primaryTsIndex = id->dstSlotId;
5
54liuyao 已提交
2292
    }
H
Haojun Liao 已提交
2293 2294
  }

L
Liu Jicong 已提交
2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307
  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;
    }
  }

2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320
  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 已提交
2321 2322
  pInfo->pBlockLists = taosArrayInit(4, POINTER_BYTES);
  if (pInfo->pBlockLists == NULL) {
2323 2324
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    goto _error;
H
Haojun Liao 已提交
2325 2326
  }

5
54liuyao 已提交
2327
  if (pHandle->vnode) {
L
Liu Jicong 已提交
2328
    SOperatorInfo*  pTableScanOp = createTableScanOperatorInfo(pTableScanNode, pHandle, pTaskInfo);
L
Liu Jicong 已提交
2329
    STableScanInfo* pTSInfo = (STableScanInfo*)pTableScanOp->info;
2330
    if (pHandle->version > 0) {
L
Liu Jicong 已提交
2331
      pTSInfo->cond.endVersion = pHandle->version;
2332
    }
L
Liu Jicong 已提交
2333 2334

    SArray* tableList = taosArrayGetP(pTaskInfo->tableqinfoList.pGroupList, 0);
2335
    if (pHandle->initTableReader) {
L
Liu Jicong 已提交
2336 2337 2338
      pTSInfo->scanMode = TABLE_SCAN__TABLE_ORDER;
      pTSInfo->dataReader = NULL;
      if (tsdbReaderOpen(pHandle->vnode, &pTSInfo->cond, tableList, &pTSInfo->dataReader, NULL) < 0) {
2339 2340
        terrno = TSDB_CODE_OUT_OF_MEMORY;
        goto _error;
L
Liu Jicong 已提交
2341
      }
L
Liu Jicong 已提交
2342 2343
    }

L
Liu Jicong 已提交
2344 2345 2346 2347
    if (pHandle->initTqReader) {
      ASSERT(pHandle->tqReader == NULL);
      pInfo->tqReader = tqOpenReader(pHandle->vnode);
      ASSERT(pInfo->tqReader);
2348
    } else {
L
Liu Jicong 已提交
2349 2350
      ASSERT(pHandle->tqReader);
      pInfo->tqReader = pHandle->tqReader;
2351 2352
    }

2353
    pInfo->pUpdateInfo = NULL;
2354
    pInfo->pTableScanOp = pTableScanOp;
2355 2356 2357
    if (pInfo->pTableScanOp->pTaskInfo->streamInfo.pState) {
      streamStateSetNumber(pInfo->pTableScanOp->pTaskInfo->streamInfo.pState, -1);
    }
L
Liu Jicong 已提交
2358

L
Liu Jicong 已提交
2359 2360
    pInfo->readHandle = *pHandle;
    pInfo->tableUid = pScanPhyNode->uid;
L
Liu Jicong 已提交
2361
    pTaskInfo->streamInfo.snapshotVer = pHandle->version;
L
Liu Jicong 已提交
2362

L
Liu Jicong 已提交
2363
    // set the extract column id to streamHandle
L
Liu Jicong 已提交
2364
    tqReaderSetColIdList(pInfo->tqReader, pColIds);
L
Liu Jicong 已提交
2365
    SArray* tableIdList = extractTableIdList(&pTaskInfo->tableqinfoList);
L
Liu Jicong 已提交
2366
    int32_t code = tqReaderSetTbUidList(pInfo->tqReader, tableIdList);
L
Liu Jicong 已提交
2367 2368 2369 2370 2371
    if (code != 0) {
      taosArrayDestroy(tableIdList);
      goto _error;
    }
    taosArrayDestroy(tableIdList);
L
Liu Jicong 已提交
2372
    memcpy(&pTaskInfo->streamInfo.tableCond, &pTSInfo->cond, sizeof(SQueryTableDataCond));
L
Liu Jicong 已提交
2373 2374
  } else {
    taosArrayDestroy(pColIds);
5
54liuyao 已提交
2375 2376
  }

2377 2378 2379 2380 2381
  // create the pseduo columns info
  if (pTableScanNode->scan.pScanPseudoCols != NULL) {
    pInfo->pPseudoExpr = createExprInfo(pTableScanNode->scan.pScanPseudoCols, NULL, &pInfo->numOfPseudoExpr);
  }

2382
  pInfo->pRes = createResDataBlock(pDescNode);
2383
  pInfo->pUpdateRes = createSpecialDataBlock(STREAM_CLEAR);
2384 2385
  pInfo->pCondition = pScanPhyNode->node.pConditions;
  pInfo->scanMode = STREAM_SCAN_FROM_READERHANDLE;
L
Liu Jicong 已提交
2386
  pInfo->windowSup = (SWindowSupporter){.pStreamAggSup = NULL, .gap = -1, .parentType = QUERY_NODE_PHYSICAL_PLAN};
2387
  pInfo->groupId = 0;
2388
  pInfo->pPullDataRes = createSpecialDataBlock(STREAM_RETRIEVE);
2389
  pInfo->pStreamScanOp = pOperator;
2390
  pInfo->deleteDataIndex = 0;
2391
  pInfo->pDeleteDataRes = createSpecialDataBlock(STREAM_DELETE_DATA);
5
54liuyao 已提交
2392
  pInfo->updateWin = (STimeWindow){.skey = INT64_MAX, .ekey = INT64_MAX};
2393
  pInfo->pUpdateDataRes = createSpecialDataBlock(STREAM_CLEAR);
X
Xiaoyu Wang 已提交
2394
  pInfo->assignBlockUid = pTableScanNode->assignBlockUid;
2395
  pInfo->partitionSup.needCalc = false;
L
Liu Jicong 已提交
2396

2397
  pOperator->name = "StreamScanOperator";
L
Liu Jicong 已提交
2398
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_STREAM_SCAN;
2399 2400 2401
  pOperator->blocking = false;
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
2402
  pOperator->exprSupp.numOfExprs = taosArrayGetSize(pInfo->pRes->pDataBlock);
2403
  pOperator->pTaskInfo = pTaskInfo;
H
Haojun Liao 已提交
2404

L
Liu Jicong 已提交
2405
  __optr_fn_t nextFn = pTaskInfo->execModel == OPTR_EXEC_MODEL_STREAM ? doStreamScan : doQueueScan;
2406
  pOperator->fpSet = createOperatorFpSet(operatorDummyOpenFn, nextFn, NULL, NULL, destroyStreamScanOperatorInfo, NULL);
2407

H
Haojun Liao 已提交
2408
  return pOperator;
2409

L
Liu Jicong 已提交
2410
_error:
H
Haojun Liao 已提交
2411 2412 2413 2414 2415 2416 2417 2418
  if (pColIds != NULL) {
    taosArrayDestroy(pColIds);
  }

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

2419 2420
  taosMemoryFreeClear(pOperator);
  return NULL;
H
Haojun Liao 已提交
2421 2422
}

2423
static void destroySysScanOperator(void* param) {
H
Haojun Liao 已提交
2424 2425 2426 2427
  SSysTableScanInfo* pInfo = (SSysTableScanInfo*)param;
  tsem_destroy(&pInfo->ready);
  blockDataDestroy(pInfo->pRes);

2428
  const char* name = tNameGetTableName(&pInfo->name);
D
dapan1121 已提交
2429 2430
  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 已提交
2431
    metaCloseTbCursor(pInfo->pCur);
2432
    pInfo->pCur = NULL;
H
Haojun Liao 已提交
2433
  }
dengyihao's avatar
dengyihao 已提交
2434 2435 2436 2437 2438
  if (pInfo->pIdx) {
    taosArrayDestroy(pInfo->pIdx->uids);
    taosMemoryFree(pInfo->pIdx);
    pInfo->pIdx = NULL;
  }
H
Haojun Liao 已提交
2439

H
Haojun Liao 已提交
2440
  taosArrayDestroy(pInfo->matchInfo.pList);
2441
  taosMemoryFreeClear(pInfo->pUser);
D
dapan1121 已提交
2442 2443

  taosMemoryFreeClear(param);
H
Haojun Liao 已提交
2444 2445
}

X
Xiaoyu Wang 已提交
2446
static int32_t getSysTableDbNameColId(const char* pTable) {
D
dapan1121 已提交
2447
  // if (0 == strcmp(TSDB_INS_TABLE_INDEXES, pTable)) {
X
Xiaoyu Wang 已提交
2448 2449
  //   return 1;
  // }
X
Xiaoyu Wang 已提交
2450 2451 2452
  return TSDB_INS_USER_STABLES_DBNAME_COLID;
}

H
Haojun Liao 已提交
2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473
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 已提交
2474
      if (getSysTableDbNameColId(node->tableName) == node->colId) {
H
Haojun Liao 已提交
2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490
        *(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;
2491
      return DEAL_RES_END;  // stop walk
H
Haojun Liao 已提交
2492 2493 2494 2495 2496 2497 2498
    }
    default:
      break;
  }
  return DEAL_RES_CONTINUE;
}

2499
static void getDBNameFromCondition(SNode* pCondition, const char* dbName) {
H
Haojun Liao 已提交
2500 2501 2502
  if (NULL == pCondition) {
    return;
  }
L
Liu Jicong 已提交
2503
  nodesWalkExpr(pCondition, getDBNameFromConditionWalker, (char*)dbName);
H
Haojun Liao 已提交
2504 2505
}

D
dapan1121 已提交
2506
static int32_t loadSysTableCallback(void* param, SDataBuf* pMsg, int32_t code) {
H
Haojun Liao 已提交
2507 2508 2509 2510 2511 2512 2513
  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);
2514 2515 2516
    pRsp->useconds = htobe64(pRsp->useconds);
    pRsp->handle = htobe64(pRsp->handle);
    pRsp->compLen = htonl(pRsp->compLen);
H
Haojun Liao 已提交
2517 2518 2519 2520 2521
  } else {
    operator->pTaskInfo->code = code;
  }

  tsem_post(&pScanResInfo->ready);
wmmhello's avatar
wmmhello 已提交
2522
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
2523 2524 2525 2526 2527 2528 2529
}

static SSDataBlock* doFilterResult(SSysTableScanInfo* pInfo) {
  if (pInfo->pCondition == NULL) {
    return pInfo->pRes->info.rows == 0 ? NULL : pInfo->pRes;
  }

H
Haojun Liao 已提交
2530
  doFilter(pInfo->pCondition, pInfo->pRes, NULL, NULL);
H
Haojun Liao 已提交
2531 2532 2533
  return pInfo->pRes->info.rows == 0 ? NULL : pInfo->pRes;
}

2534
static SSDataBlock* buildInfoSchemaTableMetaBlock(char* tableName) {
L
Liu Jicong 已提交
2535 2536
  size_t               size = 0;
  const SSysTableMeta* pMeta = NULL;
2537 2538 2539
  getInfosDbMeta(&pMeta, &size);

  int32_t index = 0;
L
Liu Jicong 已提交
2540
  for (int32_t i = 0; i < size; ++i) {
2541
    if (strcmp(pMeta[i].name, tableName) == 0) {
2542 2543 2544 2545
      index = i;
      break;
    }
  }
2546

2547
  SSDataBlock* pBlock = createDataBlock();
L
Liu Jicong 已提交
2548
  for (int32_t i = 0; i < pMeta[index].colNum; ++i) {
L
Liu Jicong 已提交
2549 2550
    SColumnInfoData colInfoData =
        createColumnInfoData(pMeta[index].schema[i].type, pMeta[index].schema[i].bytes, i + 1);
2551
    blockDataAppendColInfo(pBlock, &colInfoData);
2552 2553
  }

2554 2555 2556
  return pBlock;
}

2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637
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;
}

2638 2639 2640 2641 2642 2643 2644
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;
2645 2646 2647 2648
      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);
2649 2650 2651 2652 2653 2654 2655 2656
        return true;
      }
    }
  }
  return false;
}

static bool sysTableIsCondOnOneTable(SNode* pCond, char* condTable) {
S
slzhou 已提交
2657 2658 2659
  if (pCond == NULL) {
    return false;
  }
2660 2661 2662
  if (nodeType(pCond) == QUERY_NODE_LOGIC_CONDITION) {
    SLogicConditionNode* node = (SLogicConditionNode*)pCond;
    if (LOGIC_COND_TYPE_AND == node->condType) {
S
slzhou 已提交
2663 2664 2665 2666
      SNode* pChild = NULL;
      FOREACH(pChild, node->pParameterList) {
        if (QUERY_NODE_OPERATOR == nodeType(pChild) && sysTableIsOperatorCondOnOneTable(pChild, condTable)) {
          return true;
2667 2668 2669 2670
        }
      }
    }
  }
S
slzhou 已提交
2671

2672 2673 2674
  if (QUERY_NODE_OPERATOR == nodeType(pCond)) {
    return sysTableIsOperatorCondOnOneTable(pCond, condTable);
  }
S
slzhou 已提交
2675

2676 2677 2678
  return false;
}

S
shenglian zhou 已提交
2679 2680 2681 2682 2683 2684 2685 2686 2687 2688
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;

2689 2690 2691
  SSDataBlock* dataBlock = buildInfoSchemaTableMetaBlock(TSDB_INS_TABLE_TAGS);
  blockDataEnsureCapacity(dataBlock, pOperator->resultInfo.capacity);

S
shenglian zhou 已提交
2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702
  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)));

2703
  char condTableName[TSDB_TABLE_NAME_LEN] = {0};
S
slzhou 已提交
2704 2705
  // optimize when sql like where table_name='tablename' and xxx.
  if (pInfo->pCondition && sysTableIsCondOnOneTable(pInfo->pCondition, condTableName)) {
2706 2707 2708
    char tableName[TSDB_TABLE_NAME_LEN + VARSTR_HEADER_SIZE] = {0};
    STR_TO_VARSTR(tableName, condTableName);

2709 2710
    SMetaReader smrChildTable = {0};
    metaReaderInit(&smrChildTable, pInfo->readHandle.meta, 0);
H
Haojun Liao 已提交
2711 2712 2713 2714 2715 2716
    int32_t code = metaGetTableEntryByName(&smrChildTable, condTableName);
    if (code != TSDB_CODE_SUCCESS) {
      // terrno has been set by metaGetTableEntryByName, therefore, return directly
      return NULL;
    }

2717 2718 2719 2720 2721 2722
    if (smrChildTable.me.type != TSDB_CHILD_TABLE) {
      metaReaderClear(&smrChildTable);
      blockDataDestroy(dataBlock);
      pInfo->loadInfo.totalRows = 0;
      return NULL;
    }
H
Haojun Liao 已提交
2723

2724
    SMetaReader smrSuperTable = {0};
2725
    metaReaderInit(&smrSuperTable, pInfo->readHandle.meta, META_READER_NOLOCK);
H
Haojun Liao 已提交
2726 2727 2728 2729 2730 2731
    code = metaGetTableEntryByUid(&smrSuperTable, smrChildTable.me.ctbEntry.suid);
    if (code != TSDB_CODE_SUCCESS) {
      // terrno has been set by metaGetTableEntryByUid
      return NULL;
    }

2732 2733 2734
    sysTableUserTagsFillOneTableTags(pInfo, &smrSuperTable, &smrChildTable, dbname, tableName, &numOfRows, dataBlock);
    metaReaderClear(&smrSuperTable);
    metaReaderClear(&smrChildTable);
2735 2736 2737 2738 2739 2740
    if (numOfRows > 0) {
      relocateAndFilterSysTagsScanResult(pInfo, numOfRows, dataBlock);
      numOfRows = 0;
    }
    blockDataDestroy(dataBlock);
    pInfo->loadInfo.totalRows += pInfo->pRes->info.rows;
2741
    doSetOperatorCompleted(pOperator);
2742 2743
    return (pInfo->pRes->info.rows == 0) ? NULL : pInfo->pRes;
  }
S
shenglian zhou 已提交
2744 2745

  int32_t ret = 0;
2746 2747 2748 2749
  if (pInfo->pCur == NULL) {
    pInfo->pCur = metaOpenTbCursor(pInfo->readHandle.meta);
  }

S
shenglian zhou 已提交
2750
  while ((ret = metaTbCursorNext(pInfo->pCur)) == 0) {
2751 2752 2753
    if (pInfo->pCur->mr.me.type != TSDB_CHILD_TABLE) {
      continue;
    }
S
shenglian zhou 已提交
2754

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

2758 2759
    SMetaReader smrSuperTable = {0};
    metaReaderInit(&smrSuperTable, pInfo->readHandle.meta, 0);
2760
    uint64_t suid = pInfo->pCur->mr.me.ctbEntry.suid;
2761
    int32_t  code = metaGetTableEntryByUid(&smrSuperTable, suid);
2762 2763 2764
    if (code != TSDB_CODE_SUCCESS) {
      qError("failed to get super table meta, uid:0x%" PRIx64 ", code:%s, %s", suid, tstrerror(terrno),
             GET_TASKID(pTaskInfo));
2765
      metaReaderClear(&smrSuperTable);
2766 2767
      metaCloseTbCursor(pInfo->pCur);
      pInfo->pCur = NULL;
2768
      T_LONG_JMP(pTaskInfo->env, terrno);
2769
    }
S
shenglian zhou 已提交
2770

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

2773
    metaReaderClear(&smrSuperTable);
S
shenglian zhou 已提交
2774

2775
    if (numOfRows >= pOperator->resultInfo.capacity) {
2776
      relocateAndFilterSysTagsScanResult(pInfo, numOfRows, dataBlock);
2777 2778 2779 2780 2781
      numOfRows = 0;

      if (pInfo->pRes->info.rows > 0) {
        break;
      }
S
shenglian zhou 已提交
2782 2783 2784
    }
  }

2785
  if (numOfRows > 0) {
2786
    relocateAndFilterSysTagsScanResult(pInfo, numOfRows, dataBlock);
2787 2788 2789
    numOfRows = 0;
  }

2790
  blockDataDestroy(dataBlock);
S
shenglian zhou 已提交
2791 2792 2793 2794 2795 2796 2797 2798 2799 2800
  if (ret != 0) {
    metaCloseTbCursor(pInfo->pCur);
    pInfo->pCur = NULL;
    doSetOperatorCompleted(pOperator);
  }

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

2801 2802 2803 2804
static void relocateAndFilterSysTagsScanResult(SSysTableScanInfo* pInfo, int32_t numOfRows, SSDataBlock* dataBlock) {
  dataBlock->info.rows = numOfRows;
  pInfo->pRes->info.rows = numOfRows;

H
Haojun Liao 已提交
2805
  relocateColumnData(pInfo->pRes, pInfo->matchInfo.pList, dataBlock->pDataBlock, false);
2806 2807 2808 2809 2810
  doFilterResult(pInfo);

  blockDataCleanup(dataBlock);
}

2811 2812 2813
static int32_t sysTableUserTagsFillOneTableTags(const SSysTableScanInfo* pInfo, SMetaReader* smrSuperTable,
                                                SMetaReader* smrChildTable, const char* dbname, const char* tableName,
                                                int32_t* pNumOfRows, const SSDataBlock* dataBlock) {
2814
  char stableName[TSDB_TABLE_NAME_LEN + VARSTR_HEADER_SIZE] = {0};
2815
  STR_TO_VARSTR(stableName, (*smrSuperTable).me.name);
2816 2817 2818

  int32_t numOfRows = *pNumOfRows;

2819
  int32_t numOfTags = (*smrSuperTable).me.stbEntry.schemaTag.nCols;
2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836
  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};
2837
    STR_TO_VARSTR(tagName, (*smrSuperTable).me.stbEntry.schemaTag.pSchema[i].name);
2838 2839 2840 2841
    pColInfoData = taosArrayGet(dataBlock->pDataBlock, 3);
    colDataAppend(pColInfoData, numOfRows, tagName, false);

    // tag type
2842
    int8_t tagType = (*smrSuperTable).me.stbEntry.schemaTag.pSchema[i].type;
2843 2844 2845 2846 2847
    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)",
2848
                            (int32_t)((*smrSuperTable).me.stbEntry.schemaTag.pSchema[i].bytes - VARSTR_HEADER_SIZE));
2849
    } else if (tagType == TSDB_DATA_TYPE_NCHAR) {
2850 2851 2852
      tagTypeLen += sprintf(
          varDataVal(tagTypeStr) + tagTypeLen, "(%d)",
          (int32_t)(((*smrSuperTable).me.stbEntry.schemaTag.pSchema[i].bytes - VARSTR_HEADER_SIZE) / TSDB_NCHAR_SIZE));
2853 2854 2855 2856 2857
    }
    varDataSetLen(tagTypeStr, tagTypeLen);
    colDataAppend(pColInfoData, numOfRows, (char*)tagTypeStr, false);

    STagVal tagVal = {0};
2858
    tagVal.cid = (*smrSuperTable).me.stbEntry.schemaTag.pSchema[i].colId;
2859 2860 2861 2862
    char*    tagData = NULL;
    uint32_t tagLen = 0;

    if (tagType == TSDB_DATA_TYPE_JSON) {
2863
      tagData = (char*)smrChildTable->me.ctbEntry.pTags;
2864
    } else {
2865
      bool exist = tTagGet((STag*)smrChildTable->me.ctbEntry.pTags, &tagVal);
2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905
      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 已提交
2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931
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;
2932
  }
dengyihao's avatar
dengyihao 已提交
2933
  return cmp;
dengyihao's avatar
dengyihao 已提交
2934
}
H
Haojun Liao 已提交
2935

dengyihao's avatar
dengyihao 已提交
2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955
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);
}
2956

dengyihao's avatar
dengyihao 已提交
2957 2958 2959 2960
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 已提交
2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974
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 已提交
2975 2976
  else if (ctype == OP_TYPE_NOT_EQUAL)
    return optSysFilterFuncImpl__NoEqual;
dengyihao's avatar
dengyihao 已提交
2977 2978
  return NULL;
}
dengyihao's avatar
dengyihao 已提交
2979 2980
static int32_t sysFilte__DbName(void* arg, SNode* pNode, SArray* result) {
  void* pVnode = ((SSTabFltArg*)arg)->pVnode;
2981

dengyihao's avatar
dengyihao 已提交
2982 2983
  const char* db = NULL;
  vnodeGetInfo(pVnode, &db, NULL);
dengyihao's avatar
dengyihao 已提交
2984

dengyihao's avatar
dengyihao 已提交
2985 2986 2987 2988 2989 2990
  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 已提交
2991

dengyihao's avatar
dengyihao 已提交
2992
  SOperatorNode* pOper = (SOperatorNode*)pNode;
dengyihao's avatar
dengyihao 已提交
2993
  SValueNode*    pVal = (SValueNode*)pOper->pRight;
dengyihao's avatar
dengyihao 已提交
2994

dengyihao's avatar
dengyihao 已提交
2995 2996
  bool           reverse = false;
  __optSysFilter func = optSysGetFilterFunc(pOper->opType, &reverse);
dengyihao's avatar
dengyihao 已提交
2997 2998 2999 3000 3001
  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 已提交
3002
  return -2;
dengyihao's avatar
dengyihao 已提交
3003
}
dengyihao's avatar
dengyihao 已提交
3004 3005
static int32_t sysFilte__VgroupId(void* arg, SNode* pNode, SArray* result) {
  void* pVnode = ((SSTabFltArg*)arg)->pVnode;
dengyihao's avatar
dengyihao 已提交
3006

dengyihao's avatar
dengyihao 已提交
3007 3008
  int64_t vgId = 0;
  vnodeGetInfo(pVnode, NULL, (int32_t*)&vgId);
dengyihao's avatar
dengyihao 已提交
3009

dengyihao's avatar
dengyihao 已提交
3010
  SOperatorNode* pOper = (SOperatorNode*)pNode;
dengyihao's avatar
dengyihao 已提交
3011 3012
  SValueNode*    pVal = (SValueNode*)pOper->pRight;

dengyihao's avatar
dengyihao 已提交
3013 3014 3015
  bool reverse = false;

  __optSysFilter func = optSysGetFilterFunc(pOper->opType, &reverse);
dengyihao's avatar
dengyihao 已提交
3016 3017 3018 3019
  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 已提交
3020

dengyihao's avatar
dengyihao 已提交
3021
  return -1;
dengyihao's avatar
dengyihao 已提交
3022
}
dengyihao's avatar
dengyihao 已提交
3023 3024
static int32_t sysFilte__TableName(void* arg, SNode* pNode, SArray* result) {
  void* pMeta = ((SSTabFltArg*)arg)->pMeta;
dengyihao's avatar
dengyihao 已提交
3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038

  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 已提交
3039
  return -1;
dengyihao's avatar
dengyihao 已提交
3040 3041
}

dengyihao's avatar
dengyihao 已提交
3042 3043
static int32_t sysFilte__CreateTime(void* arg, SNode* pNode, SArray* result) {
  void* pMeta = ((SSTabFltArg*)arg)->pMeta;
dengyihao's avatar
dengyihao 已提交
3044 3045 3046 3047 3048 3049 3050

  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 已提交
3051 3052 3053 3054 3055 3056 3057 3058 3059 3060

  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 已提交
3061
}
dengyihao's avatar
dengyihao 已提交
3062 3063
static int32_t sysFilte__Ncolumn(void* arg, SNode* pNode, SArray* result) {
  void* pMeta = ((SSTabFltArg*)arg)->pMeta;
dengyihao's avatar
dengyihao 已提交
3064 3065 3066 3067 3068 3069

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

  __optSysFilter func = optSysGetFilterFunc(pOper->opType, &reverse);
dengyihao's avatar
dengyihao 已提交
3070 3071
  if (func == NULL) return -1;
  return -1;
dengyihao's avatar
dengyihao 已提交
3072 3073
}

dengyihao's avatar
dengyihao 已提交
3074 3075
static int32_t sysFilte__Ttl(void* arg, SNode* pNode, SArray* result) {
  void* pMeta = ((SSTabFltArg*)arg)->pMeta;
dengyihao's avatar
dengyihao 已提交
3076 3077 3078 3079 3080 3081

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

  __optSysFilter func = optSysGetFilterFunc(pOper->opType, &reverse);
dengyihao's avatar
dengyihao 已提交
3082 3083
  if (func == NULL) return -1;
  return -1;
dengyihao's avatar
dengyihao 已提交
3084
}
dengyihao's avatar
dengyihao 已提交
3085 3086
static int32_t sysFilte__STableName(void* arg, SNode* pNode, SArray* result) {
  void* pMeta = ((SSTabFltArg*)arg)->pMeta;
dengyihao's avatar
dengyihao 已提交
3087 3088 3089 3090 3091 3092

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

  __optSysFilter func = optSysGetFilterFunc(pOper->opType, &reverse);
dengyihao's avatar
dengyihao 已提交
3093 3094
  if (func == NULL) return -1;
  return -1;
dengyihao's avatar
dengyihao 已提交
3095
}
dengyihao's avatar
dengyihao 已提交
3096 3097
static int32_t sysFilte__Uid(void* arg, SNode* pNode, SArray* result) {
  void* pMeta = ((SSTabFltArg*)arg)->pMeta;
dengyihao's avatar
dengyihao 已提交
3098 3099 3100 3101 3102 3103

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

  __optSysFilter func = optSysGetFilterFunc(pOper->opType, &reverse);
dengyihao's avatar
dengyihao 已提交
3104 3105
  if (func == NULL) return -1;
  return -1;
dengyihao's avatar
dengyihao 已提交
3106
}
dengyihao's avatar
dengyihao 已提交
3107 3108
static int32_t sysFilte__Type(void* arg, SNode* pNode, SArray* result) {
  void* pMeta = ((SSTabFltArg*)arg)->pMeta;
dengyihao's avatar
dengyihao 已提交
3109 3110 3111 3112 3113 3114

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

  __optSysFilter func = optSysGetFilterFunc(pOper->opType, &reverse);
dengyihao's avatar
dengyihao 已提交
3115
  if (func == NULL) return -1;
dengyihao's avatar
dengyihao 已提交
3116
  return -1;
dengyihao's avatar
dengyihao 已提交
3117
}
dengyihao's avatar
dengyihao 已提交
3118 3119 3120 3121 3122
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 已提交
3123
      opType != OP_TYPE_GREATER_EQUAL && opType != OP_TYPE_GREATER_THAN) {
dengyihao's avatar
dengyihao 已提交
3124
    return -1;
dengyihao's avatar
dengyihao 已提交
3125 3126 3127 3128
  }
  return 0;
}

dengyihao's avatar
dengyihao 已提交
3129 3130
static int32_t sysChkFilter__DBName(SNode* pNode) {
  SOperatorNode* pOper = (SOperatorNode*)pNode;
dengyihao's avatar
dengyihao 已提交
3131 3132 3133 3134 3135 3136

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

  SValueNode* pVal = (SValueNode*)pOper->pRight;
dengyihao's avatar
dengyihao 已提交
3137
  if (!IS_STR_DATA_TYPE(pVal->node.resType.type)) {
dengyihao's avatar
dengyihao 已提交
3138 3139
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
3140

dengyihao's avatar
dengyihao 已提交
3141 3142 3143 3144 3145
  return 0;
}
static int32_t sysChkFilter__VgroupId(SNode* pNode) {
  SOperatorNode* pOper = (SOperatorNode*)pNode;
  SValueNode*    pVal = (SValueNode*)pOper->pRight;
dengyihao's avatar
dengyihao 已提交
3146
  if (!IS_INTEGER_TYPE(pVal->node.resType.type)) {
dengyihao's avatar
dengyihao 已提交
3147 3148
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
3149
  return sysChkFilter__Comm(pNode);
dengyihao's avatar
dengyihao 已提交
3150 3151 3152 3153
}
static int32_t sysChkFilter__TableName(SNode* pNode) {
  SOperatorNode* pOper = (SOperatorNode*)pNode;
  SValueNode*    pVal = (SValueNode*)pOper->pRight;
dengyihao's avatar
dengyihao 已提交
3154
  if (!IS_STR_DATA_TYPE(pVal->node.resType.type)) {
dengyihao's avatar
dengyihao 已提交
3155 3156
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
3157
  return sysChkFilter__Comm(pNode);
dengyihao's avatar
dengyihao 已提交
3158 3159 3160 3161 3162
}
static int32_t sysChkFilter__CreateTime(SNode* pNode) {
  SOperatorNode* pOper = (SOperatorNode*)pNode;
  SValueNode*    pVal = (SValueNode*)pOper->pRight;

dengyihao's avatar
dengyihao 已提交
3163
  if (!IS_TIMESTAMP_TYPE(pVal->node.resType.type)) {
dengyihao's avatar
dengyihao 已提交
3164 3165
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
3166
  return sysChkFilter__Comm(pNode);
dengyihao's avatar
dengyihao 已提交
3167 3168 3169 3170 3171 3172
}

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

dengyihao's avatar
dengyihao 已提交
3173
  if (!IS_INTEGER_TYPE(pVal->node.resType.type)) {
dengyihao's avatar
dengyihao 已提交
3174 3175
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
3176
  return sysChkFilter__Comm(pNode);
dengyihao's avatar
dengyihao 已提交
3177 3178 3179 3180 3181
}
static int32_t sysChkFilter__Ttl(SNode* pNode) {
  SOperatorNode* pOper = (SOperatorNode*)pNode;
  SValueNode*    pVal = (SValueNode*)pOper->pRight;

dengyihao's avatar
dengyihao 已提交
3182
  if (!IS_INTEGER_TYPE(pVal->node.resType.type)) {
dengyihao's avatar
dengyihao 已提交
3183 3184
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
3185
  return sysChkFilter__Comm(pNode);
dengyihao's avatar
dengyihao 已提交
3186 3187 3188 3189
}
static int32_t sysChkFilter__STableName(SNode* pNode) {
  SOperatorNode* pOper = (SOperatorNode*)pNode;
  SValueNode*    pVal = (SValueNode*)pOper->pRight;
dengyihao's avatar
dengyihao 已提交
3190
  if (!IS_STR_DATA_TYPE(pVal->node.resType.type)) {
dengyihao's avatar
dengyihao 已提交
3191 3192
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
3193
  return sysChkFilter__Comm(pNode);
dengyihao's avatar
dengyihao 已提交
3194 3195 3196 3197
}
static int32_t sysChkFilter__Uid(SNode* pNode) {
  SOperatorNode* pOper = (SOperatorNode*)pNode;
  SValueNode*    pVal = (SValueNode*)pOper->pRight;
dengyihao's avatar
dengyihao 已提交
3198
  if (!IS_INTEGER_TYPE(pVal->node.resType.type)) {
dengyihao's avatar
dengyihao 已提交
3199 3200
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
3201
  return sysChkFilter__Comm(pNode);
dengyihao's avatar
dengyihao 已提交
3202 3203 3204 3205
}
static int32_t sysChkFilter__Type(SNode* pNode) {
  SOperatorNode* pOper = (SOperatorNode*)pNode;
  SValueNode*    pVal = (SValueNode*)pOper->pRight;
dengyihao's avatar
dengyihao 已提交
3206
  if (!IS_INTEGER_TYPE(pVal->node.resType.type)) {
dengyihao's avatar
dengyihao 已提交
3207 3208
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
3209
  return sysChkFilter__Comm(pNode);
dengyihao's avatar
dengyihao 已提交
3210
}
dengyihao's avatar
dengyihao 已提交
3211
static int32_t optSysTabFilteImpl(void* arg, SNode* cond, SArray* result) {
dengyihao's avatar
dengyihao 已提交
3212
  if (optSysCheckOper(cond) != 0) return -1;
dengyihao's avatar
dengyihao 已提交
3213 3214 3215

  SOperatorNode* pNode = (SOperatorNode*)cond;

dengyihao's avatar
dengyihao 已提交
3216 3217
  int8_t i = 0;
  for (; i < SYSTAB_FILTER_DICT_SIZE; i++) {
dengyihao's avatar
dengyihao 已提交
3218 3219
    if (strcmp(filterDict[i].name, ((SColumnNode*)(pNode->pLeft))->colName) == 0) {
      break;
3220
    }
dengyihao's avatar
dengyihao 已提交
3221 3222
  }
  if (i >= SYSTAB_FILTER_DICT_SIZE) return -1;
3223

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

dengyihao's avatar
dengyihao 已提交
3226 3227
  return filterDict[i].fltFunc(arg, cond, result);
}
3228

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

dengyihao's avatar
dengyihao 已提交
3232
  SOperatorNode* pOper = (SOperatorNode*)pOpear;
dengyihao's avatar
dengyihao 已提交
3233 3234 3235
  if (pOper->opType < OP_TYPE_GREATER_THAN || pOper->opType > OP_TYPE_NOT_EQUAL) {
    return -1;
  }
3236

dengyihao's avatar
dengyihao 已提交
3237 3238 3239 3240
  if (nodeType(pOper->pLeft) != QUERY_NODE_COLUMN || nodeType(pOper->pRight) != QUERY_NODE_VALUE) {
    return -1;
  }
  return 0;
dengyihao's avatar
dengyihao 已提交
3241
}
3242

dengyihao's avatar
dengyihao 已提交
3243 3244 3245 3246 3247 3248 3249 3250
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
dengyihao 已提交
3251 3252 3253 3254 3255 3256
static int32_t optSysMergeRslt(SArray* mRslt, SArray* rslt) {
  // TODO, find comm mem from mRslt
  for (int i = 0; i < taosArrayGetSize(mRslt); i++) {
    SArray* aRslt = taosArrayGetP(mRslt, i);
    taosArrayAddAll(rslt, aRslt);
  }
dengyihao's avatar
dengyihao 已提交
3257 3258
  taosArraySort(rslt, tableUidCompare);
  taosArrayRemoveDuplicate(rslt, tableUidCompare, NULL);
3259

dengyihao's avatar
dengyihao 已提交
3260 3261
  return 0;
}
3262

dengyihao's avatar
dengyihao 已提交
3263 3264 3265 3266
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 已提交
3267 3268 3269
    if (ret == 0) {
      SOperatorNode* pOper = (SOperatorNode*)cond;
      SColumnNode*   pCol = (SColumnNode*)pOper->pLeft;
dengyihao's avatar
dengyihao 已提交
3270
      if (0 == strcmp(pCol->colName, "create_time")) {
dengyihao's avatar
dengyihao 已提交
3271 3272 3273 3274
        return 0;
      }
      return -1;
    }
dengyihao's avatar
dengyihao 已提交
3275 3276
    return ret;
  }
3277

dengyihao's avatar
dengyihao 已提交
3278 3279 3280
  if (nodeType(cond) != QUERY_NODE_LOGIC_CONDITION || ((SLogicConditionNode*)cond)->condType != LOGIC_COND_TYPE_AND) {
    return ret;
  }
3281

dengyihao's avatar
dengyihao 已提交
3282 3283
  SLogicConditionNode* pNode = (SLogicConditionNode*)cond;
  SNodeList*           pList = (SNodeList*)pNode->pParameterList;
3284

dengyihao's avatar
dengyihao 已提交
3285 3286
  int32_t len = LIST_LENGTH(pList);
  if (len <= 0) return ret;
3287

dengyihao's avatar
dengyihao 已提交
3288
  bool    hasIdx = false;
dengyihao's avatar
dengyihao 已提交
3289
  bool    hasRslt = true;
dengyihao's avatar
dengyihao 已提交
3290
  SArray* mRslt = taosArrayInit(len, POINTER_BYTES);
3291

dengyihao's avatar
dengyihao 已提交
3292 3293 3294
  SListCell* cell = pList->pHead;
  for (int i = 0; i < len; i++) {
    if (cell == NULL) break;
3295

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

dengyihao's avatar
dengyihao 已提交
3298 3299
    ret = optSysTabFilteImpl(arg, cell->pNode, aRslt);
    if (ret == 0) {
dengyihao's avatar
dengyihao 已提交
3300
      // has index
dengyihao's avatar
dengyihao 已提交
3301 3302 3303
      hasIdx = true;
      taosArrayPush(mRslt, &aRslt);
    } else if (ret == -2) {
dengyihao's avatar
dengyihao 已提交
3304
      // current vg
dengyihao's avatar
dengyihao 已提交
3305 3306 3307 3308 3309 3310
      hasIdx = true;
      hasRslt = false;
      taosArrayDestroy(aRslt);
      break;
    } else {
      taosArrayDestroy(aRslt);
dengyihao's avatar
dengyihao 已提交
3311 3312 3313
    }
    cell = cell->pNext;
  }
dengyihao's avatar
dengyihao 已提交
3314 3315 3316
  if (hasRslt && hasIdx) {
    optSysMergeRslt(mRslt, result);
  }
3317

dengyihao's avatar
dengyihao 已提交
3318 3319 3320
  for (int i = 0; i < taosArrayGetSize(mRslt); i++) {
    SArray* aRslt = taosArrayGetP(mRslt, i);
    taosArrayDestroy(aRslt);
dengyihao's avatar
dengyihao 已提交
3321
  }
dengyihao's avatar
dengyihao 已提交
3322
  taosArrayDestroy(mRslt);
dengyihao's avatar
dengyihao 已提交
3323 3324 3325 3326
  if (hasRslt == false) {
    return -2;
  }
  if (hasRslt && hasIdx) {
dengyihao's avatar
dengyihao 已提交
3327 3328 3329 3330 3331
    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 已提交
3332
      if (0 == strcmp(pCol->colName, "create_time")) {
dengyihao's avatar
dengyihao 已提交
3333 3334 3335 3336 3337
        return 0;
      }
      cell = cell->pNext;
    }
    return -1;
dengyihao's avatar
dengyihao 已提交
3338 3339
  }
  return -1;
dengyihao's avatar
dengyihao 已提交
3340
}
3341

dengyihao's avatar
dengyihao 已提交
3342
static SSDataBlock* sysTableBuildUserTablesByUids(SOperatorInfo* pOperator) {
dengyihao's avatar
dengyihao 已提交
3343 3344
  SExecTaskInfo*     pTaskInfo = pOperator->pTaskInfo;
  SSysTableScanInfo* pInfo = pOperator->info;
3345

dengyihao's avatar
dengyihao 已提交
3346
  SSysTableIndex* pIdx = pInfo->pIdx;
dengyihao's avatar
dengyihao 已提交
3347 3348
  blockDataCleanup(pInfo->pRes);
  int32_t numOfRows = 0;
3349

dengyihao's avatar
dengyihao 已提交
3350
  int ret = 0;
3351

dengyihao's avatar
dengyihao 已提交
3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365
  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 已提交
3366 3367 3368 3369
  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);
3370

dengyihao's avatar
dengyihao 已提交
3371
    SMetaReader mr = {0};
dengyihao's avatar
dengyihao 已提交
3372
    metaReaderInit(&mr, pInfo->readHandle.meta, 0);
dengyihao's avatar
dengyihao 已提交
3373 3374 3375 3376 3377 3378 3379 3380 3381 3382
    int32_t ret = metaGetTableEntryByUid(&mr, *uid);
    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);
3383

dengyihao's avatar
dengyihao 已提交
3384 3385 3386
    // database name
    pColInfoData = taosArrayGet(p->pDataBlock, 1);
    colDataAppend(pColInfoData, numOfRows, dbname, false);
3387

dengyihao's avatar
dengyihao 已提交
3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401
    // 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 已提交
3402 3403
      int64_t suid = mr.me.ctbEntry.suid;
      int32_t code = metaGetTableEntryByUid(&mr1, suid);
dengyihao's avatar
dengyihao 已提交
3404 3405 3406 3407
      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 已提交
3408
        metaReaderClear(&mr);
dengyihao's avatar
dengyihao 已提交
3409
        T_LONG_JMP(pTaskInfo->env, terrno);
H
Haojun Liao 已提交
3410
      }
dengyihao's avatar
dengyihao 已提交
3411
      pColInfoData = taosArrayGet(p->pDataBlock, 3);
dengyihao's avatar
dengyihao 已提交
3412
      colDataAppend(pColInfoData, numOfRows, (char*)&mr1.me.stbEntry.schemaRow.nCols, false);
H
Haojun Liao 已提交
3413

dengyihao's avatar
dengyihao 已提交
3414 3415 3416
      // super table name
      STR_TO_VARSTR(n, mr1.me.name);
      pColInfoData = taosArrayGet(p->pDataBlock, 4);
3417
      colDataAppend(pColInfoData, numOfRows, n, false);
dengyihao's avatar
dengyihao 已提交
3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432
      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);
      }
3433

dengyihao's avatar
dengyihao 已提交
3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458
      // 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 已提交
3459
      if (mr.me.ntbEntry.commentLen > 0) {
dengyihao's avatar
dengyihao 已提交
3460
        char comment[TSDB_TB_COMMENT_LEN + VARSTR_HEADER_SIZE] = {0};
dengyihao's avatar
dengyihao 已提交
3461
        STR_TO_VARSTR(comment, mr.me.ntbEntry.comment);
dengyihao's avatar
dengyihao 已提交
3462
        colDataAppend(pColInfoData, numOfRows, comment, false);
dengyihao's avatar
dengyihao 已提交
3463
      } else if (mr.me.ntbEntry.commentLen == 0) {
dengyihao's avatar
dengyihao 已提交
3464 3465 3466 3467 3468 3469
        char comment[VARSTR_HEADER_SIZE + VARSTR_HEADER_SIZE] = {0};
        STR_TO_VARSTR(comment, "");
        colDataAppend(pColInfoData, numOfRows, comment, false);
      } else {
        colDataAppendNULL(pColInfoData, numOfRows);
      }
3470

dengyihao's avatar
dengyihao 已提交
3471 3472
      // uid
      pColInfoData = taosArrayGet(p->pDataBlock, 5);
dengyihao's avatar
dengyihao 已提交
3473
      colDataAppend(pColInfoData, numOfRows, (char*)&mr.me.uid, false);
3474

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

dengyihao's avatar
dengyihao 已提交
3479 3480
      STR_TO_VARSTR(n, "NORMAL_TABLE");
      // impl later
3481
    }
3482

dengyihao's avatar
dengyihao 已提交
3483 3484
    metaReaderClear(&mr);

dengyihao's avatar
dengyihao 已提交
3485 3486 3487 3488
    pColInfoData = taosArrayGet(p->pDataBlock, 9);
    colDataAppend(pColInfoData, numOfRows, n, false);

    if (++numOfRows >= pOperator->resultInfo.capacity) {
3489 3490 3491
      p->info.rows = numOfRows;
      pInfo->pRes->info.rows = numOfRows;

H
Haojun Liao 已提交
3492
      relocateColumnData(pInfo->pRes, pInfo->matchInfo.pList, p->pDataBlock, false);
3493 3494 3495 3496
      doFilterResult(pInfo);

      blockDataCleanup(p);
      numOfRows = 0;
dengyihao's avatar
dengyihao 已提交
3497 3498 3499 3500

      if (pInfo->pRes->info.rows > 0) {
        break;
      }
3501
    }
dengyihao's avatar
dengyihao 已提交
3502
  }
3503

dengyihao's avatar
dengyihao 已提交
3504 3505 3506
  if (numOfRows > 0) {
    p->info.rows = numOfRows;
    pInfo->pRes->info.rows = numOfRows;
3507

H
Haojun Liao 已提交
3508
    relocateColumnData(pInfo->pRes, pInfo->matchInfo.pList, p->pDataBlock, false);
dengyihao's avatar
dengyihao 已提交
3509 3510 3511 3512 3513 3514
    doFilterResult(pInfo);

    blockDataCleanup(p);
    numOfRows = 0;
  }

dengyihao's avatar
dengyihao 已提交
3515 3516 3517
  if (i >= taosArrayGetSize(pIdx->uids)) {
    doSetOperatorCompleted(pOperator);
  } else {
dengyihao's avatar
dengyihao 已提交
3518
    pIdx->lastIdx = i + 1;
dengyihao's avatar
dengyihao 已提交
3519
  }
dengyihao's avatar
dengyihao 已提交
3520

dengyihao's avatar
dengyihao 已提交
3521
  blockDataDestroy(p);
dengyihao's avatar
dengyihao 已提交
3522 3523 3524 3525

  pInfo->loadInfo.totalRows += pInfo->pRes->info.rows;
  return (pInfo->pRes->info.rows == 0) ? NULL : pInfo->pRes;
}
dengyihao's avatar
dengyihao 已提交
3526
static SSDataBlock* sysTableBuildUserTables(SOperatorInfo* pOperator) {
dengyihao's avatar
dengyihao 已提交
3527 3528
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;

H
Haojun Liao 已提交
3529
  SSysTableScanInfo* pInfo = pOperator->info;
dengyihao's avatar
dengyihao 已提交
3530 3531
  if (pInfo->pCur == NULL) {
    pInfo->pCur = metaOpenTbCursor(pInfo->readHandle.meta);
3532
  }
H
Haojun Liao 已提交
3533

dengyihao's avatar
dengyihao 已提交
3534 3535
  blockDataCleanup(pInfo->pRes);
  int32_t numOfRows = 0;
3536

dengyihao's avatar
dengyihao 已提交
3537 3538 3539
  const char* db = NULL;
  int32_t     vgId = 0;
  vnodeGetInfo(pInfo->readHandle.vnode, &db, &vgId);
3540

dengyihao's avatar
dengyihao 已提交
3541 3542 3543
  SName sn = {0};
  char  dbname[TSDB_DB_FNAME_LEN + VARSTR_HEADER_SIZE] = {0};
  tNameFromString(&sn, db, T_NAME_ACCT | T_NAME_DB);
3544

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

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

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

dengyihao's avatar
dengyihao 已提交
3553 3554 3555
  int32_t ret = 0;
  while ((ret = metaTbCursorNext(pInfo->pCur)) == 0) {
    STR_TO_VARSTR(n, pInfo->pCur->mr.me.name);
3556

dengyihao's avatar
dengyihao 已提交
3557 3558 3559
    // table name
    SColumnInfoData* pColInfoData = taosArrayGet(p->pDataBlock, 0);
    colDataAppend(pColInfoData, numOfRows, n, false);
3560

dengyihao's avatar
dengyihao 已提交
3561 3562 3563
    // database name
    pColInfoData = taosArrayGet(p->pDataBlock, 1);
    colDataAppend(pColInfoData, numOfRows, dbname, false);
3564

dengyihao's avatar
dengyihao 已提交
3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583
    // 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));
3584
        metaReaderClear(&mr);
dengyihao's avatar
dengyihao 已提交
3585 3586 3587 3588
        metaCloseTbCursor(pInfo->pCur);
        pInfo->pCur = NULL;
        T_LONG_JMP(pTaskInfo->env, terrno);
      }
3589

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

dengyihao's avatar
dengyihao 已提交
3594 3595 3596 3597 3598
      // super table name
      STR_TO_VARSTR(n, mr.me.name);
      pColInfoData = taosArrayGet(p->pDataBlock, 4);
      colDataAppend(pColInfoData, numOfRows, n, false);
      metaReaderClear(&mr);
3599

dengyihao's avatar
dengyihao 已提交
3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610
      // 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 {
3611
        colDataAppendNULL(pColInfoData, numOfRows);
H
Haojun Liao 已提交
3612 3613
      }

dengyihao's avatar
dengyihao 已提交
3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648
      // 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);
      }
3649

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

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

dengyihao's avatar
dengyihao 已提交
3658
      STR_TO_VARSTR(n, "NORMAL_TABLE");
3659
    }
H
Haojun Liao 已提交
3660

dengyihao's avatar
dengyihao 已提交
3661 3662 3663 3664
    pColInfoData = taosArrayGet(p->pDataBlock, 9);
    colDataAppend(pColInfoData, numOfRows, n, false);

    if (++numOfRows >= pOperator->resultInfo.capacity) {
3665 3666 3667
      p->info.rows = numOfRows;
      pInfo->pRes->info.rows = numOfRows;

H
Haojun Liao 已提交
3668
      relocateColumnData(pInfo->pRes, pInfo->matchInfo.pList, p->pDataBlock, false);
3669 3670 3671 3672
      doFilterResult(pInfo);

      blockDataCleanup(p);
      numOfRows = 0;
dengyihao's avatar
dengyihao 已提交
3673 3674 3675 3676

      if (pInfo->pRes->info.rows > 0) {
        break;
      }
3677
    }
dengyihao's avatar
dengyihao 已提交
3678
  }
3679

dengyihao's avatar
dengyihao 已提交
3680 3681 3682
  if (numOfRows > 0) {
    p->info.rows = numOfRows;
    pInfo->pRes->info.rows = numOfRows;
3683

H
Haojun Liao 已提交
3684
    relocateColumnData(pInfo->pRes, pInfo->matchInfo.pList, p->pDataBlock, false);
dengyihao's avatar
dengyihao 已提交
3685
    doFilterResult(pInfo);
H
Haojun Liao 已提交
3686

dengyihao's avatar
dengyihao 已提交
3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702
    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;
    doSetOperatorCompleted(pOperator);
  }

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

dengyihao's avatar
dengyihao 已提交
3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717
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);

    doFilterResult(pInfo);
3718
    pInfo->loadInfo.totalRows += pInfo->pRes->info.rows;
dengyihao's avatar
dengyihao 已提交
3719 3720

    doSetOperatorCompleted(pOperator);
3721
    return (pInfo->pRes->info.rows == 0) ? NULL : pInfo->pRes;
dengyihao's avatar
dengyihao 已提交
3722
  } else {
dengyihao's avatar
dengyihao 已提交
3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746
    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 已提交
3747
        SSDataBlock* blk = sysTableBuildUserTablesByUids(pOperator);
dengyihao's avatar
dengyihao 已提交
3748 3749
        return blk;
      }
dengyihao's avatar
dengyihao 已提交
3750
    }
dengyihao's avatar
dengyihao 已提交
3751

dengyihao's avatar
dengyihao 已提交
3752
    return sysTableBuildUserTables(pOperator);
3753
  }
dengyihao's avatar
dengyihao 已提交
3754
  return NULL;
3755 3756
}

3757 3758 3759 3760 3761 3762 3763 3764
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 已提交
3765
  pOperator->status = OP_EXEC_DONE;
3766 3767 3768 3769 3770

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

3771 3772 3773 3774
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 已提交
3775
  char               dbName[TSDB_DB_NAME_LEN] = {0};
3776 3777

  const char* name = tNameGetTableName(&pInfo->name);
D
dapan1121 已提交
3778 3779 3780 3781
  if (pInfo->showRewrite) {
    getDBNameFromCondition(pInfo->pCondition, dbName);
    sprintf(pInfo->req.db, "%d.%s", pInfo->accountId, dbName);
  }
H
Hongze Cheng 已提交
3782

D
dapan1121 已提交
3783
  if (strncasecmp(name, TSDB_INS_TABLE_TABLES, TSDB_TABLE_FNAME_LEN) == 0) {
3784
    return sysTableScanUserTables(pOperator);
D
dapan1121 已提交
3785
  } else if (strncasecmp(name, TSDB_INS_TABLE_TAGS, TSDB_TABLE_FNAME_LEN) == 0) {
3786
    return sysTableScanUserTags(pOperator);
L
Liu Jicong 已提交
3787 3788
  } else if (strncasecmp(name, TSDB_INS_TABLE_STABLES, TSDB_TABLE_FNAME_LEN) == 0 && pInfo->showRewrite &&
             IS_SYS_DBNAME(dbName)) {
3789
    return sysTableScanUserSTables(pOperator);
H
Haojun Liao 已提交
3790 3791 3792 3793 3794
  } else {  // load the meta from mnode of the given epset
    if (pOperator->status == OP_EXEC_DONE) {
      return NULL;
    }

3795 3796
    while (1) {
      int64_t startTs = taosGetTimestampUs();
H
Haojun Liao 已提交
3797
      tstrncpy(pInfo->req.tb, tNameGetTableName(&pInfo->name), tListLen(pInfo->req.tb));
H
Haojun Liao 已提交
3798
      tstrncpy(pInfo->req.user, pInfo->pUser, tListLen(pInfo->req.user));
H
Haojun Liao 已提交
3799

3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810
      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 已提交
3811

L
Liu Jicong 已提交
3812 3813
      int32_t msgType = (strcasecmp(name, TSDB_INS_TABLE_DNODE_VARIABLES) == 0) ? TDMT_DND_SYSTABLE_RETRIEVE
                                                                                : TDMT_MND_SYSTABLE_RETRIEVE;
D
dapan1121 已提交
3814

3815 3816 3817
      pMsgSendInfo->param = pOperator;
      pMsgSendInfo->msgInfo.pData = buf1;
      pMsgSendInfo->msgInfo.len = contLen;
D
dapan1121 已提交
3818
      pMsgSendInfo->msgType = msgType;
3819
      pMsgSendInfo->fp = loadSysTableCallback;
D
dapan1121 已提交
3820
      pMsgSendInfo->requestId = pTaskInfo->id.queryId;
H
Haojun Liao 已提交
3821

3822
      int64_t transporterId = 0;
3823 3824
      int32_t code =
          asyncSendMsgToServer(pInfo->readHandle.pMsgCb->clientRpc, &pInfo->epSet, &transporterId, pMsgSendInfo);
3825
      tsem_wait(&pInfo->ready);
H
Haojun Liao 已提交
3826

3827 3828 3829 3830 3831
      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 已提交
3832

3833 3834
      SRetrieveMetaTableRsp* pRsp = pInfo->pRsp;
      pInfo->req.showId = pRsp->handle;
H
Haojun Liao 已提交
3835

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

3841
        if (pRsp->numOfRows == 0) {
H
Haojun Liao 已提交
3842
          taosMemoryFree(pRsp);
3843 3844 3845
          return NULL;
        }
      }
H
Haojun Liao 已提交
3846

3847
      char* pStart = pRsp->data;
H
Haojun Liao 已提交
3848
      extractDataBlockFromFetchRsp(pInfo->pRes, pRsp->data, pInfo->matchInfo.pList, &pStart);
3849
      updateLoadRemoteInfo(&pInfo->loadInfo, pRsp->numOfRows, pRsp->compLen, startTs, pOperator);
H
Haojun Liao 已提交
3850

3851 3852
      // todo log the filter info
      doFilterResult(pInfo);
H
Haojun Liao 已提交
3853
      taosMemoryFree(pRsp);
3854 3855
      if (pInfo->pRes->info.rows > 0) {
        return pInfo->pRes;
D
dapan1121 已提交
3856 3857
      } else if (pOperator->status == OP_EXEC_DONE) {
        return NULL;
3858
      }
3859
    }
H
Haojun Liao 已提交
3860 3861 3862
  }
}

3863
int32_t buildSysDbTableInfo(const SSysTableScanInfo* pInfo, int32_t capacity) {
D
dapan1121 已提交
3864
  SSDataBlock* p = buildInfoSchemaTableMetaBlock(TSDB_INS_TABLE_TABLES);
3865
  blockDataEnsureCapacity(p, capacity);
3866

L
Liu Jicong 已提交
3867
  size_t               size = 0;
3868 3869 3870
  const SSysTableMeta* pSysDbTableMeta = NULL;

  getInfosDbMeta(&pSysDbTableMeta, &size);
3871
  p->info.rows = buildDbTableInfoBlock(pInfo->sysInfo, p, pSysDbTableMeta, size, TSDB_INFORMATION_SCHEMA_DB);
3872 3873

  getPerfDbMeta(&pSysDbTableMeta, &size);
3874
  p->info.rows = buildDbTableInfoBlock(pInfo->sysInfo, p, pSysDbTableMeta, size, TSDB_PERFORMANCE_SCHEMA_DB);
3875 3876

  pInfo->pRes->info.rows = p->info.rows;
H
Haojun Liao 已提交
3877
  relocateColumnData(pInfo->pRes, pInfo->matchInfo.pList, p->pDataBlock, false);
3878 3879 3880
  blockDataDestroy(p);

  return pInfo->pRes->info.rows;
3881 3882
}

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

L
Liu Jicong 已提交
3888
  for (int32_t i = 0; i < size; ++i) {
3889
    const SSysTableMeta* pm = &pSysDbTableMeta[i];
3890 3891 3892
    if (!sysInfo && pm->sysInfo) {
      continue;
    }
3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911

    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 已提交
3912
    for (int32_t j = 4; j <= 8; ++j) {
3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927
      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;
}

3928
SOperatorInfo* createSysTableScanOperatorInfo(void* readHandle, SSystemTableScanPhysiNode* pScanPhyNode,
3929
                                              const char* pUser, SExecTaskInfo* pTaskInfo) {
H
Haojun Liao 已提交
3930 3931 3932
  SSysTableScanInfo* pInfo = taosMemoryCalloc(1, sizeof(SSysTableScanInfo));
  SOperatorInfo*     pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
  if (pInfo == NULL || pOperator == NULL) {
3933
    goto _error;
H
Haojun Liao 已提交
3934 3935
  }

3936 3937 3938 3939 3940
  SScanPhysiNode* pScanNode = &pScanPhyNode->scan;

  SDataBlockDescNode* pDescNode = pScanNode->node.pOutputDataBlockDesc;

  int32_t num = 0;
H
Haojun Liao 已提交
3941
  int32_t code = extractColMatchInfo(pScanNode->pScanCols, pDescNode, &num, COL_MATCH_FROM_COL_ID, &pInfo->matchInfo);
3942

3943 3944
  pInfo->accountId = pScanPhyNode->accountId;
  pInfo->pUser = taosMemoryStrDup((void*)pUser);
3945
  pInfo->sysInfo = pScanPhyNode->sysInfo;
3946
  pInfo->showRewrite = pScanPhyNode->showRewrite;
H
Haojun Liao 已提交
3947
  pInfo->pRes = createResDataBlock(pDescNode);
3948
  pInfo->pCondition = pScanNode->node.pConditions;
3949

3950
  initResultSizeInfo(&pOperator->resultInfo, 4096);
H
Haojun Liao 已提交
3951

3952
  tNameAssign(&pInfo->name, &pScanNode->tableName);
3953
  const char* name = tNameGetTableName(&pInfo->name);
3954

D
dapan1121 已提交
3955 3956
  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 已提交
3957
    pInfo->readHandle = *(SReadHandle*)readHandle;
3958
    blockDataEnsureCapacity(pInfo->pRes, pOperator->resultInfo.capacity);
H
Haojun Liao 已提交
3959 3960
  } else {
    tsem_init(&pInfo->ready, 0, 0);
3961
    pInfo->epSet = pScanPhyNode->mgmtEpSet;
3962
    pInfo->readHandle = *(SReadHandle*)readHandle;
H
Haojun Liao 已提交
3963 3964
  }

3965
  pOperator->name = "SysTableScanOperator";
H
Haojun Liao 已提交
3966
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_SYSTABLE_SCAN;
3967 3968 3969
  pOperator->blocking = false;
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
H
Haojun Liao 已提交
3970
  pOperator->exprSupp.numOfExprs = taosArrayGetSize(pInfo->pRes->pDataBlock);
3971
  pOperator->pTaskInfo = pTaskInfo;
3972

3973
  pOperator->fpSet = createOperatorFpSet(operatorDummyOpenFn, doSysTableScan, NULL, NULL, destroySysScanOperator, NULL);
H
Haojun Liao 已提交
3974 3975

  return pOperator;
3976

3977
_error:
3978 3979 3980 3981
  taosMemoryFreeClear(pInfo);
  taosMemoryFreeClear(pOperator);
  terrno = TSDB_CODE_QRY_OUT_OF_MEMORY;
  return NULL;
H
Haojun Liao 已提交
3982
}
H
Haojun Liao 已提交
3983

3984
static SSDataBlock* doTagScan(SOperatorInfo* pOperator) {
H
Haojun Liao 已提交
3985 3986 3987 3988
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

3989 3990 3991
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;

  STagScanInfo* pInfo = pOperator->info;
3992
  SExprInfo*    pExprInfo = &pOperator->exprSupp.pExprInfo[0];
3993
  SSDataBlock*  pRes = pInfo->pRes;
3994
  blockDataCleanup(pRes);
H
Haojun Liao 已提交
3995

wmmhello's avatar
wmmhello 已提交
3996 3997
  int32_t size = taosArrayGetSize(pInfo->pTableList->pTableList);
  if (size == 0) {
H
Haojun Liao 已提交
3998 3999 4000 4001
    setTaskStatus(pTaskInfo, TASK_COMPLETED);
    return NULL;
  }

4002 4003 4004
  char        str[512] = {0};
  int32_t     count = 0;
  SMetaReader mr = {0};
4005
  metaReaderInit(&mr, pInfo->readHandle.meta, 0);
H
Haojun Liao 已提交
4006

wmmhello's avatar
wmmhello 已提交
4007 4008
  while (pInfo->curPos < size && count < pOperator->resultInfo.capacity) {
    STableKeyInfo* item = taosArrayGet(pInfo->pTableList->pTableList, pInfo->curPos);
L
Liu Jicong 已提交
4009
    int32_t        code = metaGetTableEntryByUid(&mr, item->uid);
4010
    tDecoderClear(&mr.coder);
H
Haojun Liao 已提交
4011
    if (code != TSDB_CODE_SUCCESS) {
L
Liu Jicong 已提交
4012 4013
      qError("failed to get table meta, uid:0x%" PRIx64 ", code:%s, %s", item->uid, tstrerror(terrno),
             GET_TASKID(pTaskInfo));
H
Haojun Liao 已提交
4014
      metaReaderClear(&mr);
4015
      T_LONG_JMP(pTaskInfo->env, terrno);
H
Haojun Liao 已提交
4016
    }
H
Haojun Liao 已提交
4017

4018
    for (int32_t j = 0; j < pOperator->exprSupp.numOfExprs; ++j) {
4019 4020 4021 4022 4023 4024
      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);
4025
      } else {  // it is a tag value
wmmhello's avatar
wmmhello 已提交
4026 4027
        STagVal val = {0};
        val.cid = pExprInfo[j].base.pParam[0].pCol->colId;
4028
        const char* p = metaGetTableTagVal(mr.me.ctbEntry.pTags, pDst->info.type, &val);
wmmhello's avatar
wmmhello 已提交
4029

4030 4031 4032 4033
        char* data = NULL;
        if (pDst->info.type != TSDB_DATA_TYPE_JSON && p != NULL) {
          data = tTagValToData((const STagVal*)p, false);
        } else {
wmmhello's avatar
wmmhello 已提交
4034 4035
          data = (char*)p;
        }
L
Liu Jicong 已提交
4036 4037
        colDataAppend(pDst, count, data,
                      (data == NULL) || (pDst->info.type == TSDB_DATA_TYPE_JSON && tTagIsJsonNull(data)));
4038

4039 4040
        if (pDst->info.type != TSDB_DATA_TYPE_JSON && p != NULL && IS_VAR_DATA_TYPE(((const STagVal*)p)->type) &&
            data != NULL) {
wmmhello's avatar
wmmhello 已提交
4041
          taosMemoryFree(data);
wmmhello's avatar
wmmhello 已提交
4042
        }
H
Haojun Liao 已提交
4043 4044 4045
      }
    }

4046
    count += 1;
wmmhello's avatar
wmmhello 已提交
4047
    if (++pInfo->curPos >= size) {
4048
      doSetOperatorCompleted(pOperator);
H
Haojun Liao 已提交
4049 4050 4051
    }
  }

4052 4053
  metaReaderClear(&mr);

4054
  // qDebug("QInfo:0x%"PRIx64" create tag values results completed, rows:%d", GET_TASKID(pRuntimeEnv), count);
H
Haojun Liao 已提交
4055
  if (pOperator->status == OP_EXEC_DONE) {
4056
    setTaskStatus(pTaskInfo, TASK_COMPLETED);
H
Haojun Liao 已提交
4057 4058 4059
  }

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

4062
  return (pRes->info.rows == 0) ? NULL : pInfo->pRes;
H
Haojun Liao 已提交
4063 4064
}

4065
static void destroyTagScanOperatorInfo(void* param) {
H
Haojun Liao 已提交
4066 4067
  STagScanInfo* pInfo = (STagScanInfo*)param;
  pInfo->pRes = blockDataDestroy(pInfo->pRes);
H
Haojun Liao 已提交
4068
  taosArrayDestroy(pInfo->matchInfo.pList);
D
dapan1121 已提交
4069
  taosMemoryFreeClear(param);
H
Haojun Liao 已提交
4070 4071
}

4072 4073
SOperatorInfo* createTagScanOperatorInfo(SReadHandle* pReadHandle, STagScanPhysiNode* pPhyNode,
                                         STableListInfo* pTableListInfo, SExecTaskInfo* pTaskInfo) {
4074
  STagScanInfo*  pInfo = taosMemoryCalloc(1, sizeof(STagScanInfo));
H
Haojun Liao 已提交
4075 4076 4077 4078 4079
  SOperatorInfo* pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }

4080 4081
  SDataBlockDescNode* pDescNode = pPhyNode->node.pOutputDataBlockDesc;

4082
  int32_t    num = 0;
4083 4084
  int32_t    numOfExprs = 0;
  SExprInfo* pExprInfo = createExprInfo(pPhyNode->pScanPseudoCols, NULL, &numOfExprs);
4085 4086
  int32_t    code =
      extractColMatchInfo(pPhyNode->pScanPseudoCols, pDescNode, &num, COL_MATCH_FROM_COL_ID, &pInfo->matchInfo);
4087

H
Haojun Liao 已提交
4088
  code = initExprSupp(&pOperator->exprSupp, pExprInfo, numOfExprs);
4089 4090 4091
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
4092

4093 4094 4095 4096
  pInfo->pTableList = pTableListInfo;
  pInfo->pRes = createResDataBlock(pDescNode);
  pInfo->readHandle = *pReadHandle;
  pInfo->curPos = 0;
4097

4098
  pOperator->name = "TagScanOperator";
4099
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_TAG_SCAN;
4100

4101 4102 4103 4104
  pOperator->blocking = false;
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
  pOperator->pTaskInfo = pTaskInfo;
4105

4106
  initResultSizeInfo(&pOperator->resultInfo, 4096);
4107 4108
  blockDataEnsureCapacity(pInfo->pRes, pOperator->resultInfo.capacity);

4109
  pOperator->fpSet = createOperatorFpSet(operatorDummyOpenFn, doTagScan, NULL, NULL, destroyTagScanOperatorInfo, NULL);
H
Haojun Liao 已提交
4110 4111

  return pOperator;
4112

4113
_error:
H
Haojun Liao 已提交
4114 4115 4116 4117 4118
  taosMemoryFree(pInfo);
  taosMemoryFree(pOperator);
  terrno = TSDB_CODE_OUT_OF_MEMORY;
  return NULL;
}
4119

H
Haojun Liao 已提交
4120
int32_t createScanTableListInfo(SScanPhysiNode* pScanNode, SNodeList* pGroupTags, bool groupSort, SReadHandle* pHandle,
4121 4122
                                STableListInfo* pTableListInfo, SNode* pTagCond, SNode* pTagIndexCond,
                                const char* idStr) {
H
Haojun Liao 已提交
4123 4124
  int64_t st = taosGetTimestampUs();

H
Haojun Liao 已提交
4125
  if (pHandle == NULL) {
H
Haojun Liao 已提交
4126
    qError("invalid handle, in creating operator tree, %s", idStr);
H
Haojun Liao 已提交
4127 4128 4129
    return TSDB_CODE_INVALID_PARA;
  }

4130
  int32_t code = getTableList(pHandle->meta, pHandle->vnode, pScanNode, pTagCond, pTagIndexCond, pTableListInfo);
4131
  if (code != TSDB_CODE_SUCCESS) {
4132
    qError("failed to getTableList, code: %s", tstrerror(code));
4133
    return code;
4134 4135
  }

H
Haojun Liao 已提交
4136
  int64_t st1 = taosGetTimestampUs();
L
Liu Jicong 已提交
4137
  qDebug("generate queried table list completed, elapsed time:%.2f ms %s", (st1 - st) / 1000.0, idStr);
H
Haojun Liao 已提交
4138

4139
  if (taosArrayGetSize(pTableListInfo->pTableList) == 0) {
4140
    qDebug("no table qualified for query, %s" PRIx64, idStr);
4141 4142
    return TSDB_CODE_SUCCESS;
  }
4143

H
Haojun Liao 已提交
4144 4145
  pTableListInfo->needSortTableByGroupId = groupSort;
  code = generateGroupIdMap(pTableListInfo, pHandle, pGroupTags);
4146
  if (code != TSDB_CODE_SUCCESS) {
wmmhello's avatar
wmmhello 已提交
4147
    return code;
4148 4149
  }

H
Haojun Liao 已提交
4150
  int64_t st2 = taosGetTimestampUs();
L
Liu Jicong 已提交
4151
  qDebug("generate group id map completed, elapsed time:%.2f ms %s", (st2 - st1) / 1000.0, idStr);
H
Haojun Liao 已提交
4152

4153 4154 4155
  return TSDB_CODE_SUCCESS;
}

S
slzhou 已提交
4156
int32_t createMultipleDataReaders(SQueryTableDataCond* pQueryCond, SReadHandle* pHandle, STableListInfo* pTableListInfo,
H
Haojun Liao 已提交
4157
                                  int32_t tableStartIdx, int32_t tableEndIdx, SArray* arrayReader, const char* idstr) {
S
slzhou 已提交
4158 4159 4160 4161
  for (int32_t i = tableStartIdx; i <= tableEndIdx; ++i) {
    SArray* subTableList = taosArrayInit(1, sizeof(STableKeyInfo));
    taosArrayPush(subTableList, taosArrayGet(pTableListInfo->pTableList, i));

H
Haojun Liao 已提交
4162 4163
    STsdbReader* pReader = NULL;
    tsdbReaderOpen(pHandle->vnode, pQueryCond, subTableList, &pReader, idstr);
S
slzhou 已提交
4164 4165 4166 4167 4168 4169 4170 4171
    taosArrayPush(arrayReader, &pReader);

    taosArrayDestroy(subTableList);
  }

  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
4172
// todo refactor
4173 4174
static int32_t loadDataBlockFromOneTable(SOperatorInfo* pOperator, STableMergeScanInfo* pTableScanInfo,
                                         int32_t readerIdx, SSDataBlock* pBlock, uint32_t* status) {
L
Liu Jicong 已提交
4175
  SExecTaskInfo*       pTaskInfo = pOperator->pTaskInfo;
S
shenglian zhou 已提交
4176
  STableMergeScanInfo* pInfo = pOperator->info;
4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202

  SFileBlockLoadRecorder* pCost = &pTableScanInfo->readRecorder;

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

  *status = pInfo->dataBlockLoadFlag;
  if (pTableScanInfo->pFilterNode != NULL ||
      overlapWithTimeWindow(&pTableScanInfo->interval, &pBlock->info, pTableScanInfo->cond.order)) {
    (*status) = FUNC_DATA_REQUIRED_DATA_LOAD;
  }

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

  if (*status == FUNC_DATA_REQUIRED_FILTEROUT) {
    qDebug("%s data block filter out, brange:%" PRId64 "-%" PRId64 ", rows:%d", GET_TASKID(pTaskInfo),
           pBlockInfo->window.skey, pBlockInfo->window.ekey, pBlockInfo->rows);
    pCost->filterOutBlocks += 1;
    return TSDB_CODE_SUCCESS;
  } else if (*status == FUNC_DATA_REQUIRED_NOT_LOAD) {
    qDebug("%s data block skipped, brange:%" PRId64 "-%" PRId64 ", rows:%d", GET_TASKID(pTaskInfo),
           pBlockInfo->window.skey, pBlockInfo->window.ekey, pBlockInfo->rows);
    pCost->skipBlocks += 1;

    // clear all data in pBlock that are set when handing the previous block
4203
    for (int32_t i = 0; i < taosArrayGetSize(pBlock->pDataBlock); ++i) {
4204 4205 4206 4207 4208 4209 4210 4211 4212 4213
      SColumnInfoData* pcol = taosArrayGet(pBlock->pDataBlock, i);
      pcol->pData = NULL;
    }

    return TSDB_CODE_SUCCESS;
  } else if (*status == FUNC_DATA_REQUIRED_STATIS_LOAD) {
    pCost->loadBlockStatis += 1;

    bool             allColumnsHaveAgg = true;
    SColumnDataAgg** pColAgg = NULL;
H
Hongze Cheng 已提交
4214
    STsdbReader*     reader = taosArrayGetP(pTableScanInfo->dataReaders, readerIdx);
4215
    tsdbRetrieveDatablockSMA(reader, &pColAgg, &allColumnsHaveAgg);
4216 4217

    if (allColumnsHaveAgg == true) {
4218
      int32_t numOfCols = taosArrayGetSize(pBlock->pDataBlock);
4219 4220 4221 4222 4223 4224 4225

      // todo create this buffer during creating operator
      if (pBlock->pBlockAgg == NULL) {
        pBlock->pBlockAgg = taosMemoryCalloc(numOfCols, POINTER_BYTES);
      }

      for (int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
4226 4227
        SColMatchItem* pColMatchInfo = taosArrayGet(pTableScanInfo->matchInfo.pList, i);
        if (!pColMatchInfo->needOutput) {
4228 4229
          continue;
        }
H
Haojun Liao 已提交
4230
        pBlock->pBlockAgg[pColMatchInfo->dstSlotId] = pColAgg[i];
4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242
      }

      return TSDB_CODE_SUCCESS;
    } else {  // failed to load the block sma data, data block statistics does not exist, load data block instead
      *status = FUNC_DATA_REQUIRED_DATA_LOAD;
    }
  }

  ASSERT(*status == FUNC_DATA_REQUIRED_DATA_LOAD);

  // todo filter data block according to the block sma data firstly
#if 0
H
Haojun Liao 已提交
4243
  if (!doFilterByBlockSMA(pBlock->pBlockStatis, pTableScanInfo->pCtx, pBlockInfo->rows)) {
4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254
    pCost->filterOutBlocks += 1;
    qDebug("%s data block filter out, brange:%" PRId64 "-%" PRId64 ", rows:%d", GET_TASKID(pTaskInfo), pBlockInfo->window.skey,
           pBlockInfo->window.ekey, pBlockInfo->rows);
    (*status) = FUNC_DATA_REQUIRED_FILTEROUT;
    return TSDB_CODE_SUCCESS;
  }
#endif

  pCost->totalCheckedRows += pBlock->info.rows;
  pCost->loadBlocks += 1;

H
Hongze Cheng 已提交
4255
  STsdbReader* reader = taosArrayGetP(pTableScanInfo->dataReaders, readerIdx);
4256 4257 4258 4259 4260
  SArray*      pCols = tsdbRetrieveDataBlock(reader, NULL);
  if (pCols == NULL) {
    return terrno;
  }

H
Haojun Liao 已提交
4261
  relocateColumnData(pBlock, pTableScanInfo->matchInfo.pList, pCols, true);
4262 4263

  // currently only the tbname pseudo column
S
shenglian zhou 已提交
4264 4265 4266
  if (pTableScanInfo->pseudoSup.numOfExprs > 0) {
    int32_t code = addTagPseudoColumnData(&pTableScanInfo->readHandle, pTableScanInfo->pseudoSup.pExprInfo,
                                          pTableScanInfo->pseudoSup.numOfExprs, pBlock, GET_TASKID(pTaskInfo));
H
Haojun Liao 已提交
4267
    if (code != TSDB_CODE_SUCCESS) {
4268
      T_LONG_JMP(pTaskInfo->env, code);
H
Haojun Liao 已提交
4269
    }
4270 4271
  }

4272 4273
  if (pTableScanInfo->pFilterNode != NULL) {
    int64_t st = taosGetTimestampMs();
H
Haojun Liao 已提交
4274
    doFilter(pTableScanInfo->pFilterNode, pBlock, &pTableScanInfo->matchInfo, NULL);
4275

4276 4277
    double el = (taosGetTimestampUs() - st) / 1000.0;
    pTableScanInfo->readRecorder.filterTime += el;
4278

4279 4280 4281 4282 4283 4284 4285
    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);
    }
4286 4287 4288 4289 4290 4291 4292 4293
  }

  return TSDB_CODE_SUCCESS;
}

typedef struct STableMergeScanSortSourceParam {
  SOperatorInfo* pOperator;
  int32_t        readerIdx;
4294
  SSDataBlock*   inputBlock;
4295 4296 4297 4298 4299 4300
} STableMergeScanSortSourceParam;

static SSDataBlock* getTableDataBlock(void* param) {
  STableMergeScanSortSourceParam* source = param;
  SOperatorInfo*                  pOperator = source->pOperator;
  int32_t                         readerIdx = source->readerIdx;
4301
  SSDataBlock*                    pBlock = source->inputBlock;
4302 4303 4304 4305
  STableMergeScanInfo*            pTableScanInfo = pOperator->info;

  int64_t st = taosGetTimestampUs();

4306 4307
  blockDataCleanup(pBlock);

H
Hongze Cheng 已提交
4308
  STsdbReader* reader = taosArrayGetP(pTableScanInfo->dataReaders, readerIdx);
4309 4310
  while (tsdbNextDataBlock(reader)) {
    if (isTaskKilled(pOperator->pTaskInfo)) {
4311
      T_LONG_JMP(pOperator->pTaskInfo->env, TSDB_CODE_TSC_QUERY_CANCELLED);
4312 4313 4314 4315 4316 4317 4318 4319
    }

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

4320 4321 4322 4323
    blockDataCleanup(pBlock);
    SDataBlockInfo binfo = pBlock->info;
    tsdbRetrieveDataBlockInfo(reader, &binfo);

4324
    blockDataEnsureCapacity(pBlock, binfo.rows);
4325 4326 4327 4328
    pBlock->info.type = binfo.type;
    pBlock->info.uid = binfo.uid;
    pBlock->info.window = binfo.window;
    pBlock->info.rows = binfo.rows;
4329 4330 4331 4332 4333

    uint32_t status = 0;
    int32_t  code = loadDataBlockFromOneTable(pOperator, pTableScanInfo, readerIdx, pBlock, &status);
    //    int32_t  code = loadDataBlockOnDemand(pOperator->pRuntimeEnv, pTableScanInfo, pBlock, &status);
    if (code != TSDB_CODE_SUCCESS) {
4334
      T_LONG_JMP(pOperator->pTaskInfo->env, code);
4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354
    }

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

    uint64_t* groupId = taosHashGet(pOperator->pTaskInfo->tableqinfoList.map, &pBlock->info.uid, sizeof(int64_t));
    if (groupId) {
      pBlock->info.groupId = *groupId;
    }

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

    return pBlock;
  }
  return NULL;
}

4355 4356 4357
SArray* generateSortByTsInfo(SArray* colMatchInfo, int32_t order) {
  int32_t tsTargetSlotId = 0;
  for (int32_t i = 0; i < taosArrayGetSize(colMatchInfo); ++i) {
H
Haojun Liao 已提交
4358
    SColMatchItem* colInfo = taosArrayGet(colMatchInfo, i);
4359
    if (colInfo->colId == PRIMARYKEY_TIMESTAMP_COL_ID) {
H
Haojun Liao 已提交
4360
      tsTargetSlotId = colInfo->dstSlotId;
4361 4362 4363
    }
  }

4364 4365 4366
  SArray*         pList = taosArrayInit(1, sizeof(SBlockOrderInfo));
  SBlockOrderInfo bi = {0};
  bi.order = order;
4367
  bi.slotId = tsTargetSlotId;
4368 4369 4370 4371 4372 4373 4374
  bi.nullFirst = NULL_ORDER_FIRST;

  taosArrayPush(pList, &bi);

  return pList;
}

4375
int32_t startGroupTableMergeScan(SOperatorInfo* pOperator) {
4376 4377 4378
  STableMergeScanInfo* pInfo = pOperator->info;
  SExecTaskInfo*       pTaskInfo = pOperator->pTaskInfo;

S
slzhou 已提交
4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389
  {
    size_t  tableListSize = taosArrayGetSize(pInfo->tableListInfo->pTableList);
    int32_t i = pInfo->tableStartIndex + 1;
    for (; i < tableListSize; ++i) {
      STableKeyInfo* tableKeyInfo = taosArrayGet(pInfo->tableListInfo->pTableList, i);
      if (tableKeyInfo->groupId != pInfo->groupId) {
        break;
      }
    }
    pInfo->tableEndIndex = i - 1;
  }
4390

S
slzhou 已提交
4391 4392
  int32_t tableStartIdx = pInfo->tableStartIndex;
  int32_t tableEndIdx = pInfo->tableEndIndex;
4393

S
slzhou 已提交
4394
  STableListInfo* tableListInfo = pInfo->tableListInfo;
4395
  pInfo->dataReaders = taosArrayInit(64, POINTER_BYTES);
S
slzhou 已提交
4396
  createMultipleDataReaders(&pInfo->cond, &pInfo->readHandle, tableListInfo, tableStartIdx, tableEndIdx,
4397
                            pInfo->dataReaders, GET_TASKID(pTaskInfo));
4398

4399 4400
  // 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 已提交
4401
  pInfo->sortBufSize = pInfo->bufPageSize * (tableEndIdx - tableStartIdx + 1 + 1);
4402
  int32_t numOfBufPage = pInfo->sortBufSize / pInfo->bufPageSize;
L
Liu Jicong 已提交
4403 4404
  pInfo->pSortHandle = tsortCreateSortHandle(pInfo->pSortInfo, SORT_MULTISOURCE_MERGE, pInfo->bufPageSize, numOfBufPage,
                                             pInfo->pSortInputBlock, pTaskInfo->id.str);
4405 4406 4407 4408

  tsortSetFetchRawDataFp(pInfo->pSortHandle, getTableDataBlock, NULL, NULL);

  size_t numReaders = taosArrayGetSize(pInfo->dataReaders);
4409 4410 4411 4412 4413 4414 4415 4416
  for (int32_t i = 0; i < numReaders; ++i) {
    STableMergeScanSortSourceParam param = {0};
    param.readerIdx = i;
    param.pOperator = pOperator;
    param.inputBlock = createOneDataBlock(pInfo->pResBlock, false);
    taosArrayPush(pInfo->sortSourceParams, &param);
  }

4417 4418
  for (int32_t i = 0; i < numReaders; ++i) {
    SSortSource*                    ps = taosMemoryCalloc(1, sizeof(SSortSource));
4419
    STableMergeScanSortSourceParam* param = taosArrayGet(pInfo->sortSourceParams, i);
4420 4421 4422 4423 4424 4425 4426
    ps->param = param;
    tsortAddSource(pInfo->pSortHandle, ps);
  }

  int32_t code = tsortOpen(pInfo->pSortHandle);

  if (code != TSDB_CODE_SUCCESS) {
4427
    T_LONG_JMP(pTaskInfo->env, terrno);
4428 4429
  }

4430 4431 4432 4433 4434 4435 4436
  return TSDB_CODE_SUCCESS;
}

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

4437 4438
  size_t numReaders = taosArrayGetSize(pInfo->dataReaders);

4439 4440 4441 4442 4443 4444 4445
  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;

4446 4447 4448 4449
  for (int32_t i = 0; i < numReaders; ++i) {
    STableMergeScanSortSourceParam* param = taosArrayGet(pInfo->sortSourceParams, i);
    blockDataDestroy(param->inputBlock);
  }
4450 4451
  taosArrayClear(pInfo->sortSourceParams);

4452 4453 4454
  tsortDestroySortHandle(pInfo->pSortHandle);

  for (int32_t i = 0; i < numReaders; ++i) {
H
Haojun Liao 已提交
4455 4456
    STsdbReader* reader = taosArrayGetP(pInfo->dataReaders, i);
    tsdbReaderClose(reader);
4457
  }
4458 4459
  taosArrayDestroy(pInfo->dataReaders);
  pInfo->dataReaders = NULL;
4460 4461 4462
  return TSDB_CODE_SUCCESS;
}

L
Liu Jicong 已提交
4463 4464
SSDataBlock* getSortedTableMergeScanBlockData(SSortHandle* pHandle, SSDataBlock* pResBlock, int32_t capacity,
                                              SOperatorInfo* pOperator) {
4465 4466 4467
  STableMergeScanInfo* pInfo = pOperator->info;
  SExecTaskInfo*       pTaskInfo = pOperator->pTaskInfo;

4468 4469
  blockDataCleanup(pResBlock);
  blockDataEnsureCapacity(pResBlock, capacity);
4470 4471

  while (1) {
4472
    STupleHandle* pTupleHandle = tsortNextTuple(pHandle);
4473 4474 4475 4476
    if (pTupleHandle == NULL) {
      break;
    }

4477 4478
    appendOneRowToDataBlock(pResBlock, pTupleHandle);
    if (pResBlock->info.rows >= capacity) {
4479 4480 4481 4482
      break;
    }
  }

4483
  qDebug("%s get sorted row blocks, rows:%d", GET_TASKID(pTaskInfo), pResBlock->info.rows);
4484 4485 4486
  applyLimitOffset(&pInfo->limitInfo, pResBlock, pTaskInfo, pOperator);
  pInfo->limitInfo.numOfOutputRows += pResBlock->info.rows;

4487
  return (pResBlock->info.rows > 0) ? pResBlock : NULL;
4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499
}

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) {
4500
    T_LONG_JMP(pTaskInfo->env, code);
4501
  }
4502

S
slzhou 已提交
4503 4504 4505
  size_t tableListSize = taosArrayGetSize(pInfo->tableListInfo->pTableList);
  if (!pInfo->hasGroupId) {
    pInfo->hasGroupId = true;
4506

S
slzhou 已提交
4507
    if (tableListSize == 0) {
4508 4509 4510
      doSetOperatorCompleted(pOperator);
      return NULL;
    }
S
slzhou 已提交
4511 4512
    pInfo->tableStartIndex = 0;
    pInfo->groupId = ((STableKeyInfo*)taosArrayGet(pInfo->tableListInfo->pTableList, pInfo->tableStartIndex))->groupId;
4513 4514
    startGroupTableMergeScan(pOperator);
  }
4515

S
slzhou 已提交
4516 4517
  SSDataBlock* pBlock = NULL;
  while (pInfo->tableStartIndex < tableListSize) {
L
Liu Jicong 已提交
4518 4519
    pBlock = getSortedTableMergeScanBlockData(pInfo->pSortHandle, pInfo->pResBlock, pOperator->resultInfo.capacity,
                                              pOperator);
S
slzhou 已提交
4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534
    if (pBlock != NULL) {
      pBlock->info.groupId = pInfo->groupId;
      pOperator->resultInfo.totalRows += pBlock->info.rows;
      return pBlock;
    } else {
      stopGroupTableMergeScan(pOperator);
      if (pInfo->tableEndIndex >= tableListSize - 1) {
        doSetOperatorCompleted(pOperator);
        break;
      }
      pInfo->tableStartIndex = pInfo->tableEndIndex + 1;
      pInfo->groupId =
          ((STableKeyInfo*)taosArrayGet(pInfo->tableListInfo->pTableList, pInfo->tableStartIndex))->groupId;
      startGroupTableMergeScan(pOperator);
    }
wmmhello's avatar
wmmhello 已提交
4535 4536
  }

4537 4538 4539
  return pBlock;
}

4540
void destroyTableMergeScanOperatorInfo(void* param) {
4541
  STableMergeScanInfo* pTableScanInfo = (STableMergeScanInfo*)param;
4542
  cleanupQueryTableDataCond(&pTableScanInfo->cond);
4543
  taosArrayDestroy(pTableScanInfo->sortSourceParams);
4544 4545

  for (int32_t i = 0; i < taosArrayGetSize(pTableScanInfo->dataReaders); ++i) {
H
Hongze Cheng 已提交
4546
    STsdbReader* reader = taosArrayGetP(pTableScanInfo->dataReaders, i);
H
refact  
Hongze Cheng 已提交
4547
    tsdbReaderClose(reader);
4548 4549 4550
  }
  taosArrayDestroy(pTableScanInfo->dataReaders);

H
Haojun Liao 已提交
4551 4552
  if (pTableScanInfo->matchInfo.pList != NULL) {
    taosArrayDestroy(pTableScanInfo->matchInfo.pList);
4553 4554 4555 4556 4557 4558
  }

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

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

4561
  taosMemoryFreeClear(pTableScanInfo->rowEntryInfoOffset);
D
dapan1121 已提交
4562
  taosMemoryFreeClear(param);
4563 4564
}

4565 4566
typedef struct STableMergeScanExecInfo {
  SFileBlockLoadRecorder blockRecorder;
L
Liu Jicong 已提交
4567
  SSortExecInfo          sortExecInfo;
4568 4569
} STableMergeScanExecInfo;

4570 4571
int32_t getTableMergeScanExplainExecInfo(SOperatorInfo* pOptr, void** pOptrExplain, uint32_t* len) {
  ASSERT(pOptr != NULL);
4572 4573
  // TODO: merge these two info into one struct
  STableMergeScanExecInfo* execInfo = taosMemoryCalloc(1, sizeof(STableMergeScanExecInfo));
L
Liu Jicong 已提交
4574
  STableMergeScanInfo*     pInfo = pOptr->info;
4575
  execInfo->blockRecorder = pInfo->readRecorder;
4576
  execInfo->sortExecInfo = pInfo->sortExecInfo;
4577 4578 4579

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

4581 4582 4583
  return TSDB_CODE_SUCCESS;
}

S
slzhou 已提交
4584 4585 4586
int32_t compareTableKeyInfoByGid(const void* p1, const void* p2) {
  const STableKeyInfo* info1 = p1;
  const STableKeyInfo* info2 = p2;
4587 4588 4589 4590 4591 4592 4593
  if (info1->groupId < info2->groupId) {
    return -1;
  } else if (info1->groupId > info2->groupId) {
    return 1;
  } else {
    return 0;
  }
S
slzhou 已提交
4594 4595
}

4596
SOperatorInfo* createTableMergeScanOperatorInfo(STableScanPhysiNode* pTableScanNode, STableListInfo* pTableListInfo,
4597
                                                SReadHandle* readHandle, SExecTaskInfo* pTaskInfo) {
4598 4599 4600 4601 4602
  STableMergeScanInfo* pInfo = taosMemoryCalloc(1, sizeof(STableMergeScanInfo));
  SOperatorInfo*       pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }
4603

4604
  if (pTableScanNode->pGroupTags) {
S
slzhou 已提交
4605 4606
    taosArraySort(pTableListInfo->pTableList, compareTableKeyInfoByGid);
  }
4607 4608 4609 4610

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

  int32_t numOfCols = 0;
4611 4612
  int32_t code = extractColMatchInfo(pTableScanNode->scan.pScanCols, pDescNode, &numOfCols, COL_MATCH_FROM_COL_ID,
                                     &pInfo->matchInfo);
4613

H
Haojun Liao 已提交
4614
  code = initQueryTableDataCond(&pInfo->cond, pTableScanNode);
4615
  if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
4616
    taosArrayDestroy(pInfo->matchInfo.pList);
4617 4618 4619 4620
    goto _error;
  }

  if (pTableScanNode->scan.pScanPseudoCols != NULL) {
4621 4622 4623
    SExprSupp* pSup = &pInfo->pseudoSup;
    pSup->pExprInfo = createExprInfo(pTableScanNode->scan.pScanPseudoCols, NULL, &pSup->numOfExprs);
    pSup->pCtx = createSqlFunctionCtx(pSup->pExprInfo, pSup->numOfExprs, &pSup->rowEntryInfoOffset);
4624 4625 4626 4627
  }

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

L
Liu Jicong 已提交
4628 4629
  pInfo->readHandle = *readHandle;
  pInfo->interval = extractIntervalInfo(pTableScanNode);
4630
  pInfo->sample.sampleRatio = pTableScanNode->ratio;
L
Liu Jicong 已提交
4631 4632 4633
  pInfo->sample.seed = taosGetTimestampSec();
  pInfo->dataBlockLoadFlag = pTableScanNode->dataRequired;
  pInfo->pFilterNode = pTableScanNode->scan.node.pConditions;
4634
  pInfo->tableListInfo = pTableListInfo;
L
Liu Jicong 已提交
4635
  pInfo->scanFlag = MAIN_SCAN;
4636 4637

  pInfo->pResBlock = createResDataBlock(pDescNode);
4638
  pInfo->sortSourceParams = taosArrayInit(64, sizeof(STableMergeScanSortSourceParam));
4639

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

4644
  int32_t rowSize = pInfo->pResBlock->info.rowSize;
L
Liu Jicong 已提交
4645
  pInfo->bufPageSize = getProperSortPageSize(rowSize);
4646

L
Liu Jicong 已提交
4647
  pOperator->name = "TableMergeScanOperator";
4648
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_TABLE_MERGE_SCAN;
L
Liu Jicong 已提交
4649 4650 4651
  pOperator->blocking = false;
  pOperator->status = OP_NOT_OPENED;
  pOperator->info = pInfo;
L
Liu Jicong 已提交
4652
  pOperator->exprSupp.numOfExprs = numOfCols;
L
Liu Jicong 已提交
4653
  pOperator->pTaskInfo = pTaskInfo;
4654
  initResultSizeInfo(&pOperator->resultInfo, 1024);
4655

4656 4657
  pOperator->fpSet = createOperatorFpSet(operatorDummyOpenFn, doTableMergeScan, NULL, NULL,
                                         destroyTableMergeScanOperatorInfo, getTableMergeScanExplainExecInfo);
4658 4659 4660 4661 4662 4663 4664 4665 4666
  pOperator->cost.openCost = 0;
  return pOperator;

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