tsdbRead.c 130.6 KB
Newer Older
H
hjxilinx 已提交
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/>.
 */

H
Haojun Liao 已提交
16
#include "osDef.h"
H
Hongze Cheng 已提交
17
#include "tsdb.h"
18

19
#define ASCENDING_TRAVERSE(o)  (o == TSDB_ORDER_ASC)
20
#define ALL_ROWS_CHECKED_INDEX (INT16_MIN)
21
#define INITIAL_ROW_INDEX_VAL  (-1)
H
Hongze Cheng 已提交
22

23 24 25 26 27 28
typedef enum {
  EXTERNAL_ROWS_PREV = 0x1,
  EXTERNAL_ROWS_MAIN = 0x2,
  EXTERNAL_ROWS_NEXT = 0x3,
} EContentData;

29
typedef struct {
dengyihao's avatar
dengyihao 已提交
30
  STbDataIter* iter;
31 32 33 34
  int32_t      index;
  bool         hasVal;
} SIterInfo;

35 36 37 38 39
typedef struct {
  int32_t numOfBlocks;
  int32_t numOfLastBlocks;
} SBlockNumber;

H
Haojun Liao 已提交
40
typedef struct STableBlockScanInfo {
dengyihao's avatar
dengyihao 已提交
41 42
  uint64_t  uid;
  TSKEY     lastKey;
43 44 45 46 47
  SMapData  mapData;      // block info (compressed)
  SArray*   pBlockList;   // block data index list
  SIterInfo iter;         // mem buffer skip list iterator
  SIterInfo iiter;        // imem buffer skip list iterator
  SArray*   delSkyline;   // delete info for this table
48 49
  int32_t   fileDelIndex; // file block delete index
  int32_t   lastBlockDelIndex;// delete index for last block
50 51
  bool      iterInit;     // whether to initialize the in-memory skip list iterator or not
  int16_t   indexInBlockL;// row position in last block
H
Haojun Liao 已提交
52 53 54
} STableBlockScanInfo;

typedef struct SBlockOrderWrapper {
dengyihao's avatar
dengyihao 已提交
55
  int64_t uid;
56
  int64_t offset;
H
Haojun Liao 已提交
57
} SBlockOrderWrapper;
H
Hongze Cheng 已提交
58 59

typedef struct SBlockOrderSupporter {
60 61 62 63
  SBlockOrderWrapper** pDataBlockInfo;
  int32_t*             indexPerTable;
  int32_t*             numOfBlocksPerTable;
  int32_t              numOfTables;
H
Hongze Cheng 已提交
64 65 66
} SBlockOrderSupporter;

typedef struct SIOCostSummary {
67 68 69
  int64_t numOfBlocks;
  double  blockLoadTime;
  double  buildmemBlock;
70
  int64_t headFileLoad;
71
  double  headFileLoadTime;
72
  int64_t smaDataLoad;
73
  double  smaLoadTime;
74 75
  int64_t lastBlockLoad;
  double  lastBlockLoadTime;
H
Hongze Cheng 已提交
76 77 78
} SIOCostSummary;

typedef struct SBlockLoadSuppInfo {
79
  SArray*          pColAgg;
80
  SColumnDataAgg   tsColAgg;
C
Cary Xu 已提交
81
  SColumnDataAgg** plist;
82 83
  int16_t*         colIds;    // column ids for loading file block data
  char**           buildBuf;  // build string tmp buffer, todo remove it later after all string format being updated.
H
Hongze Cheng 已提交
84 85
} SBlockLoadSuppInfo;

86 87 88 89 90 91 92 93 94 95 96
typedef struct SVersionRange {
  uint64_t minVer;
  uint64_t maxVer;
} SVersionRange;

typedef struct SLastBlockReader {
  SArray*       pBlockL;
  int32_t       currentBlockIndex;
  SBlockData    lastBlockData;
  STimeWindow   window;
  SVersionRange verRange;
97
  int32_t       order;
98
  uint64_t      uid;
99
  int16_t*      rowIndex;         // row index ptr, usually from the STableBlockScanInfo->indexInBlockL
100 101
} SLastBlockReader;

102
typedef struct SFilesetIter {
103 104 105 106
  int32_t           numOfFiles;    // number of total files
  int32_t           index;         // current accessed index in the list
  SArray*           pFileList;     // data file list
  int32_t           order;
107
  SLastBlockReader* pLastBlockReader; // last file block reader
108
} SFilesetIter;
H
Haojun Liao 已提交
109 110

typedef struct SFileDataBlockInfo {
111
  // index position in STableBlockScanInfo in order to check whether neighbor block overlaps with it
dengyihao's avatar
dengyihao 已提交
112
  uint64_t uid;
113
  int32_t  tbBlockIdx;
H
Haojun Liao 已提交
114 115 116
} SFileDataBlockInfo;

typedef struct SDataBlockIter {
117
  int32_t   numOfBlocks;
118
  int32_t   index;
119
  SArray*   blockList;      // SArray<SFileDataBlockInfo>
120
  int32_t   order;
121
  SBlock    block;          // current SBlock data
122
  SHashObj* pTableMap;
H
Haojun Liao 已提交
123 124 125
} SDataBlockIter;

typedef struct SFileBlockDumpInfo {
dengyihao's avatar
dengyihao 已提交
126 127 128 129
  int32_t totalRows;
  int32_t rowIndex;
  int64_t lastKey;
  bool    allDumped;
H
Haojun Liao 已提交
130 131
} SFileBlockDumpInfo;

132 133 134 135 136
typedef struct SUidOrderCheckInfo {
  uint64_t*            tableUidList;  // access table uid list in uid ascending order list
  int32_t              currentIndex;  // index in table uid list
} SUidOrderCheckInfo;

H
Haojun Liao 已提交
137
typedef struct SReaderStatus {
138
  bool                 loadFromFile;       // check file stage
139
  bool                 composedDataBlock;  // the returned data block is a composed block or not
140 141 142
  SHashObj*            pTableMap;          // SHash<STableBlockScanInfo>
  STableBlockScanInfo* pTableIter;         // table iterator used in building in-memory buffer data blocks.
  SUidOrderCheckInfo   uidCheckInfo;      // check all table in uid order
143
  SFileBlockDumpInfo   fBlockDumpInfo;
144
  SDFileSet*           pCurrentFileset;    // current opened file set
145 146 147
  SBlockData           fileBlockData;
  SFilesetIter         fileIter;
  SDataBlockIter       blockIter;
H
Haojun Liao 已提交
148 149
} SReaderStatus;

H
Hongze Cheng 已提交
150
struct STsdbReader {
H
Haojun Liao 已提交
151 152 153 154 155 156 157
  STsdb*             pTsdb;
  uint64_t           suid;
  int16_t            order;
  STimeWindow        window;  // the primary query time window that applies to all queries
  SSDataBlock*       pResBlock;
  int32_t            capacity;
  SReaderStatus      status;
158 159
  char*              idStr;  // query info handle, for debug purpose
  int32_t            type;   // query type: 1. retrieve all data blocks, 2. retrieve direct prev|next rows
H
Hongze Cheng 已提交
160
  SBlockLoadSuppInfo suppInfo;
H
Hongze Cheng 已提交
161
  STsdbReadSnap*     pReadSnap;
162
  SIOCostSummary     cost;
163 164
  STSchema*          pSchema;     // the newest version schema
  STSchema*          pMemSchema;  // the previous schema for in-memory data, to avoid load schema too many times
165 166
  SDataFReader*      pFileReader;
  SVersionRange      verRange;
167

168 169
  int32_t      step;
  STsdbReader* innerReader[2];
H
Hongze Cheng 已提交
170
};
H
Hongze Cheng 已提交
171

H
Haojun Liao 已提交
172
static SFileDataBlockInfo* getCurrentBlockInfo(SDataBlockIter* pBlockIter);
173 174
static int      buildDataBlockFromBufImpl(STableBlockScanInfo* pBlockScanInfo, int64_t endKey, int32_t capacity,
                                          STsdbReader* pReader);
175
static TSDBROW* getValidMemRow(SIterInfo* pIter, const SArray* pDelList, STsdbReader* pReader);
176 177
static int32_t  doMergeRowsInFileBlocks(SBlockData* pBlockData, STableBlockScanInfo* pScanInfo, STsdbReader* pReader,
                                        SRowMerger* pMerger);
H
Haojun Liao 已提交
178
static int32_t  doMergeRowsInLastBlock(SLastBlockReader* pLastBlockReader, STableBlockScanInfo* pScanInfo, int64_t ts, SRowMerger* pMerger);
179
static int32_t  doMergeRowsInBuf(SIterInfo* pIter, uint64_t uid, int64_t ts, SArray* pDelList, SRowMerger* pMerger,
dengyihao's avatar
dengyihao 已提交
180
                                 STsdbReader* pReader);
H
Haojun Liao 已提交
181
static int32_t  doAppendRowFromTSRow(SSDataBlock* pBlock, STsdbReader* pReader, STSRow* pTSRow, uint64_t uid);
182
static int32_t  doAppendRowFromFileBlock(SSDataBlock* pResBlock, STsdbReader* pReader, SBlockData* pBlockData,
183
                                     int32_t rowIndex);
184
static void     setComposedBlockFlag(STsdbReader* pReader, bool composed);
185
static bool     hasBeenDropped(const SArray* pDelList, int32_t* index, TSDBKEY* pKey, int32_t order);
186

187
static void doMergeMemTableMultiRows(TSDBROW* pRow, uint64_t uid, SIterInfo* pIter, SArray* pDelList, STSRow** pTSRow,
188
                             STsdbReader* pReader, bool* freeTSRow);
189 190
static void doMergeMemIMemRows(TSDBROW* pRow, TSDBROW* piRow, STableBlockScanInfo* pBlockScanInfo, STsdbReader* pReader,
                               STSRow** pTSRow);
191 192
static int32_t mergeRowsInFileBlocks(SBlockData* pBlockData, STableBlockScanInfo* pBlockScanInfo, int64_t key, STsdbReader* pReader);

dengyihao's avatar
dengyihao 已提交
193 194 195 196
static int32_t initDelSkylineIterator(STableBlockScanInfo* pBlockScanInfo, STsdbReader* pReader, STbData* pMemTbData,
                                      STbData* piMemTbData);
static STsdb*  getTsdbByRetentions(SVnode* pVnode, TSKEY winSKey, SRetention* retentions, const char* idstr,
                                   int8_t* pLevel);
197
static SVersionRange getQueryVerRange(SVnode* pVnode, SQueryTableDataCond* pCond, int8_t level);
198
static int64_t getCurrentKeyInLastBlock(SLastBlockReader* pLastBlockReader);
199 200
static bool    hasDataInLastBlock(SLastBlockReader* pLastBlockReader);
static int32_t doBuildDataBlock(STsdbReader* pReader);
H
Haojun Liao 已提交
201

202 203 204
static int32_t setColumnIdSlotList(STsdbReader* pReader, SSDataBlock* pBlock) {
  SBlockLoadSuppInfo* pSupInfo = &pReader->suppInfo;

205
  size_t numOfCols = blockDataGetNumOfCols(pBlock);
206

207
  pSupInfo->colIds = taosMemoryMalloc(numOfCols * sizeof(int16_t));
208
  pSupInfo->buildBuf = taosMemoryCalloc(numOfCols, POINTER_BYTES);
209 210 211
  if (pSupInfo->buildBuf == NULL || pSupInfo->colIds == NULL) {
    taosMemoryFree(pSupInfo->colIds);
    taosMemoryFree(pSupInfo->buildBuf);
H
Haojun Liao 已提交
212 213
    return TSDB_CODE_OUT_OF_MEMORY;
  }
H
Hongze Cheng 已提交
214

H
Haojun Liao 已提交
215 216
  for (int32_t i = 0; i < numOfCols; ++i) {
    SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, i);
217
    pSupInfo->colIds[i] = pCol->info.colId;
218 219 220 221

    if (IS_VAR_DATA_TYPE(pCol->info.type)) {
      pSupInfo->buildBuf[i] = taosMemoryMalloc(pCol->info.bytes);
    }
H
Haojun Liao 已提交
222
  }
H
Hongze Cheng 已提交
223

H
Haojun Liao 已提交
224 225
  return TSDB_CODE_SUCCESS;
}
H
Hongze Cheng 已提交
226

227
static SHashObj* createDataBlockScanInfo(STsdbReader* pTsdbReader, const STableKeyInfo* idList, int32_t numOfTables) {
H
Haojun Liao 已提交
228
  // allocate buffer in order to load data blocks from file
229
  // todo use simple hash instead, optimize the memory consumption
230 231 232
  SHashObj* pTableMap =
      taosHashInit(numOfTables, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT), false, HASH_NO_LOCK);
  if (pTableMap == NULL) {
H
Haojun Liao 已提交
233 234 235
    return NULL;
  }

236
  for (int32_t j = 0; j < numOfTables; ++j) {
237
    STableBlockScanInfo info = {.lastKey = 0, .uid = idList[j].uid, .indexInBlockL = INITIAL_ROW_INDEX_VAL};
238 239 240
    if (ASCENDING_TRAVERSE(pTsdbReader->order)) {
      if (info.lastKey == INT64_MIN || info.lastKey < pTsdbReader->window.skey) {
        info.lastKey = pTsdbReader->window.skey;
H
Haojun Liao 已提交
241 242
      }

243
      ASSERT(info.lastKey >= pTsdbReader->window.skey && info.lastKey <= pTsdbReader->window.ekey);
wmmhello's avatar
wmmhello 已提交
244
    } else {
245
      info.lastKey = pTsdbReader->window.skey;
H
Haojun Liao 已提交
246
    }
wmmhello's avatar
wmmhello 已提交
247

248 249 250
    taosHashPut(pTableMap, &info.uid, sizeof(uint64_t), &info, sizeof(info));
    tsdbDebug("%p check table uid:%" PRId64 " from lastKey:%" PRId64 " %s", pTsdbReader, info.uid, info.lastKey,
              pTsdbReader->idStr);
H
Haojun Liao 已提交
251 252
  }

253 254
  tsdbDebug("%p create %d tables scan-info, size:%.2f Kb, %s", pTsdbReader, numOfTables,
            (sizeof(STableBlockScanInfo) * numOfTables) / 1024.0, pTsdbReader->idStr);
255

256
  return pTableMap;
H
Hongze Cheng 已提交
257
}
H
Hongze Cheng 已提交
258

259 260 261
static void resetDataBlockScanInfo(SHashObj* pTableMap) {
  STableBlockScanInfo* p = NULL;

dengyihao's avatar
dengyihao 已提交
262
  while ((p = taosHashIterate(pTableMap, p)) != NULL) {
263 264
    p->iterInit = false;
    p->iiter.hasVal = false;
dengyihao's avatar
dengyihao 已提交
265
    if (p->iter.iter != NULL) {
266
      p->iter.iter = tsdbTbDataIterDestroy(p->iter.iter);
267 268
    }

269 270 271
    p->fileDelIndex = -1;
    p->delSkyline   = taosArrayDestroy(p->delSkyline);
    p->lastBlockDelIndex = INITIAL_ROW_INDEX_VAL;
272 273 274
  }
}

275 276 277 278 279 280 281 282
static void destroyBlockScanInfo(SHashObj* pTableMap) {
  STableBlockScanInfo* p = NULL;

  while ((p = taosHashIterate(pTableMap, p)) != NULL) {
    p->iterInit = false;
    p->iiter.hasVal = false;

    if (p->iter.iter != NULL) {
283
      p->iter.iter = tsdbTbDataIterDestroy(p->iter.iter);
284 285 286
    }

    if (p->iiter.iter != NULL) {
287
      p->iiter.iter = tsdbTbDataIterDestroy(p->iiter.iter);
288 289
    }

290 291
    p->delSkyline = taosArrayDestroy(p->delSkyline);
    p->pBlockList = taosArrayDestroy(p->pBlockList);
292
    tMapDataClear(&p->mapData);
293 294 295 296 297
  }

  taosHashCleanup(pTableMap);
}

298
static bool isEmptyQueryTimeWindow(STimeWindow* pWindow) {
299 300
  ASSERT(pWindow != NULL);
  return pWindow->skey > pWindow->ekey;
H
Haojun Liao 已提交
301
}
H
Hongze Cheng 已提交
302

303 304 305
// Update the query time window according to the data time to live(TTL) information, in order to avoid to return
// the expired data to client, even it is queried already.
static STimeWindow updateQueryTimeWindow(STsdb* pTsdb, STimeWindow* pWindow) {
dengyihao's avatar
dengyihao 已提交
306
  STsdbKeepCfg* pCfg = &pTsdb->keepCfg;
H
Hongze Cheng 已提交
307

308
  int64_t now = taosGetTimestamp(pCfg->precision);
dengyihao's avatar
dengyihao 已提交
309
  int64_t earilyTs = now - (tsTickPerMin[pCfg->precision] * pCfg->keep2) + 1;  // needs to add one tick
310

dengyihao's avatar
dengyihao 已提交
311
  STimeWindow win = *pWindow;
312 313 314 315 316 317
  if (win.skey < earilyTs) {
    win.skey = earilyTs;
  }

  return win;
}
H
Hongze Cheng 已提交
318

H
Haojun Liao 已提交
319
static void limitOutputBufferSize(const SQueryTableDataCond* pCond, int32_t* capacity) {
H
Haojun Liao 已提交
320 321 322 323 324 325
  int32_t rowLen = 0;
  for (int32_t i = 0; i < pCond->numOfCols; ++i) {
    rowLen += pCond->colList[i].bytes;
  }

  // make sure the output SSDataBlock size be less than 2MB.
H
Haojun Liao 已提交
326 327 328
  const int32_t TWOMB = 2 * 1024 * 1024;
  if ((*capacity) * rowLen > TWOMB) {
    (*capacity) = TWOMB / rowLen;
H
Haojun Liao 已提交
329 330 331 332
  }
}

// init file iterator
333
static int32_t initFilesetIterator(SFilesetIter* pIter, SArray* aDFileSet, STsdbReader* pReader/*int32_t order, const char* idstr*/) {
H
Hongze Cheng 已提交
334
  size_t numOfFileset = taosArrayGetSize(aDFileSet);
335

336 337
  pIter->index = ASCENDING_TRAVERSE(pReader->order) ? -1 : numOfFileset;
  pIter->order = pReader->order;
H
Hongze Cheng 已提交
338
  pIter->pFileList = aDFileSet;
339
  pIter->numOfFiles = numOfFileset;
H
Haojun Liao 已提交
340

341 342 343 344
  if (pIter->pLastBlockReader == NULL) {
    pIter->pLastBlockReader = taosMemoryCalloc(1, sizeof(struct SLastBlockReader));
    if (pIter->pLastBlockReader == NULL) {
      int32_t code = TSDB_CODE_OUT_OF_MEMORY;
345
      tsdbError("failed to prepare the last block iterator, code:%d %s", tstrerror(code), pReader->idStr);
346 347 348
      return code;
    }

349 350 351 352 353
    SLastBlockReader* pLReader = pIter->pLastBlockReader;
    pLReader->pBlockL = taosArrayInit(4, sizeof(SBlockL));
    pLReader->order   = pReader->order;
    pLReader->window  = pReader->window;
    pLReader->verRange = pReader->verRange;
354
    pLReader->currentBlockIndex = -1;
H
Haojun Liao 已提交
355 356 357 358 359

    int32_t code = tBlockDataCreate(&pLReader->lastBlockData);
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }
360 361
  }

362
  tsdbDebug("init fileset iterator, total files:%d %s", pIter->numOfFiles, pReader->idStr);
H
Haojun Liao 已提交
363 364 365
  return TSDB_CODE_SUCCESS;
}

366
static bool filesetIteratorNext(SFilesetIter* pIter, STsdbReader* pReader) {
367 368
  bool    asc = ASCENDING_TRAVERSE(pIter->order);
  int32_t step = asc ? 1 : -1;
369 370 371
  pIter->index += step;

  if ((asc && pIter->index >= pIter->numOfFiles) || ((!asc) && pIter->index < 0)) {
H
Haojun Liao 已提交
372 373 374 375 376
    return false;
  }

  // check file the time range of coverage
  STimeWindow win = {0};
H
Hongze Cheng 已提交
377

378
  while (1) {
H
Haojun Liao 已提交
379 380 381
    if (pReader->pFileReader != NULL) {
      tsdbDataFReaderClose(&pReader->pFileReader);
    }
382

383
    pReader->status.pCurrentFileset = (SDFileSet*)taosArrayGet(pIter->pFileList, pIter->index);
H
Haojun Liao 已提交
384

385 386 387 388
    int32_t code = tsdbDataFReaderOpen(&pReader->pFileReader, pReader->pTsdb, pReader->status.pCurrentFileset);
    if (code != TSDB_CODE_SUCCESS) {
      goto _err;
    }
H
Haojun Liao 已提交
389

390 391
    pReader->cost.headFileLoad += 1;

392 393 394 395 396 397 398 399 400 401 402 403
    int32_t fid = pReader->status.pCurrentFileset->fid;
    tsdbFidKeyRange(fid, pReader->pTsdb->keepCfg.days, pReader->pTsdb->keepCfg.precision, &win.skey, &win.ekey);

    // current file are no longer overlapped with query time window, ignore remain files
    if ((asc && win.skey > pReader->window.ekey) || (!asc && win.ekey < pReader->window.skey)) {
      tsdbDebug("%p remain files are not qualified for qrange:%" PRId64 "-%" PRId64 ", ignore, %s", pReader,
                pReader->window.skey, pReader->window.ekey, pReader->idStr);
      return false;
    }

    if ((asc && (win.ekey < pReader->window.skey)) || ((!asc) && (win.skey > pReader->window.ekey))) {
      pIter->index += step;
404 405 406
      if ((asc && pIter->index >= pIter->numOfFiles) || ((!asc) && pIter->index < 0)) {
        return false;
      }
407 408
      continue;
    }
C
Cary Xu 已提交
409

410
    tsdbDebug("%p file found fid:%d for qrange:%" PRId64 "-%" PRId64 ", %s", pReader, fid, pReader->window.skey,
411
              pReader->window.ekey, pReader->idStr);
412 413
    return true;
  }
414

415
_err:
H
Haojun Liao 已提交
416 417 418
  return false;
}

419
static void resetDataBlockIterator(SDataBlockIter* pIter, int32_t order) {
420 421
  pIter->order = order;
  pIter->index = -1;
422
  pIter->numOfBlocks = 0;
423 424 425 426 427 428 429
  if (pIter->blockList == NULL) {
    pIter->blockList = taosArrayInit(4, sizeof(SFileDataBlockInfo));
  } else {
    taosArrayClear(pIter->blockList);
  }
}

L
Liu Jicong 已提交
430
static void cleanupDataBlockIterator(SDataBlockIter* pIter) { taosArrayDestroy(pIter->blockList); }
H
Haojun Liao 已提交
431

H
Haojun Liao 已提交
432
static void initReaderStatus(SReaderStatus* pStatus) {
dengyihao's avatar
dengyihao 已提交
433 434
  pStatus->pTableIter = NULL;
  pStatus->loadFromFile = true;
H
Haojun Liao 已提交
435 436
}

437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
static SSDataBlock* createResBlock(SQueryTableDataCond* pCond, int32_t capacity) {
  SSDataBlock* pResBlock = createDataBlock();
  if (pResBlock == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

  for (int32_t i = 0; i < pCond->numOfCols; ++i) {
    SColumnInfoData colInfo = {{0}, 0};
    colInfo.info = pCond->colList[i];
    blockDataAppendColInfo(pResBlock, &colInfo);
  }

  int32_t code = blockDataEnsureCapacity(pResBlock, capacity);
  if (code != TSDB_CODE_SUCCESS) {
    terrno = code;
    taosMemoryFree(pResBlock);
    return NULL;
  }

  return pResBlock;
}

460 461
static int32_t tsdbReaderCreate(SVnode* pVnode, SQueryTableDataCond* pCond, STsdbReader** ppReader, int32_t capacity,
                                const char* idstr) {
H
Haojun Liao 已提交
462
  int32_t      code = 0;
463
  int8_t       level = 0;
H
Haojun Liao 已提交
464
  STsdbReader* pReader = (STsdbReader*)taosMemoryCalloc(1, sizeof(*pReader));
H
Hongze Cheng 已提交
465 466
  if (pReader == NULL) {
    code = TSDB_CODE_OUT_OF_MEMORY;
H
Haojun Liao 已提交
467
    goto _end;
H
Hongze Cheng 已提交
468 469
  }

C
Cary Xu 已提交
470 471 472 473
  if (VND_IS_TSMA(pVnode)) {
    tsdbDebug("vgId:%d, tsma is selected to query", TD_VID(pVnode));
  }

H
Haojun Liao 已提交
474
  initReaderStatus(&pReader->status);
475

L
Liu Jicong 已提交
476
  pReader->pTsdb = getTsdbByRetentions(pVnode, pCond->twindows.skey, pVnode->config.tsdbCfg.retentions, idstr, &level);
dengyihao's avatar
dengyihao 已提交
477 478
  pReader->suid = pCond->suid;
  pReader->order = pCond->order;
479
  pReader->capacity = 4096;
dengyihao's avatar
dengyihao 已提交
480 481
  pReader->idStr = (idstr != NULL) ? strdup(idstr) : NULL;
  pReader->verRange = getQueryVerRange(pVnode, pCond, level);
482
  pReader->type = pCond->type;
483
  pReader->window = updateQueryTimeWindow(pReader->pTsdb, &pCond->twindows);
484

485
  ASSERT(pCond->numOfCols > 0);
H
Hongze Cheng 已提交
486

487
  limitOutputBufferSize(pCond, &pReader->capacity);
488

489 490
  // allocate buffer in order to load data blocks from file
  SBlockLoadSuppInfo* pSup = &pReader->suppInfo;
491
  pSup->pColAgg = taosArrayInit(4, sizeof(SColumnDataAgg));
492
  pSup->plist = taosMemoryCalloc(pCond->numOfCols, POINTER_BYTES);
493
  if (pSup->pColAgg == NULL || pSup->plist == NULL) {
494 495 496
    code = TSDB_CODE_OUT_OF_MEMORY;
    goto _end;
  }
H
Haojun Liao 已提交
497

498 499
  pSup->tsColAgg.colId = PRIMARYKEY_TIMESTAMP_COL_ID;

H
Hongze Cheng 已提交
500
  code = tBlockDataCreate(&pReader->status.fileBlockData);
H
Haojun Liao 已提交
501 502 503 504 505
  if (code != TSDB_CODE_SUCCESS) {
    terrno = code;
    goto _end;
  }

506 507 508 509
  pReader->pResBlock = createResBlock(pCond, pReader->capacity);
  if (pReader->pResBlock == NULL) {
    code = terrno;
    goto _end;
H
Hongze Cheng 已提交
510
  }
H
Hongze Cheng 已提交
511

512 513
  setColumnIdSlotList(pReader, pReader->pResBlock);

H
Hongze Cheng 已提交
514 515
  *ppReader = pReader;
  return code;
H
Hongze Cheng 已提交
516

H
Haojun Liao 已提交
517 518
_end:
  tsdbReaderClose(pReader);
H
Hongze Cheng 已提交
519 520 521
  *ppReader = NULL;
  return code;
}
H
Hongze Cheng 已提交
522

H
Haojun Liao 已提交
523
static int32_t doLoadBlockIndex(STsdbReader* pReader, SDataFReader* pFileReader, SArray* pIndexList) {
524
  SArray* aBlockIdx = taosArrayInit(8, sizeof(SBlockIdx));
H
Hongze Cheng 已提交
525

526
  int64_t st = taosGetTimestampUs();
H
Hongze Cheng 已提交
527
  int32_t code = tsdbReadBlockIdx(pFileReader, aBlockIdx);
H
Haojun Liao 已提交
528
  if (code != TSDB_CODE_SUCCESS) {
529
    goto _end;
H
Haojun Liao 已提交
530
  }
H
Hongze Cheng 已提交
531

532 533
  size_t num = taosArrayGetSize(aBlockIdx);
  if (num == 0) {
H
Haojun Liao 已提交
534
    taosArrayDestroy(aBlockIdx);
H
Haojun Liao 已提交
535 536
    return TSDB_CODE_SUCCESS;
  }
H
Hongze Cheng 已提交
537

538 539 540 541
  int64_t et1 = taosGetTimestampUs();

  SBlockIdx* pBlockIdx = NULL;
  for (int32_t i = 0; i < num; ++i) {
542
    pBlockIdx = (SBlockIdx*)taosArrayGet(aBlockIdx, i);
H
Haojun Liao 已提交
543

544
    // uid check
H
Hongze Cheng 已提交
545
    if (pBlockIdx->suid != pReader->suid) {
H
Haojun Liao 已提交
546 547 548 549
      continue;
    }

    // this block belongs to a table that is not queried.
H
Hongze Cheng 已提交
550
    void* p = taosHashGet(pReader->status.pTableMap, &pBlockIdx->uid, sizeof(uint64_t));
H
Haojun Liao 已提交
551 552 553 554 555 556
    if (p == NULL) {
      continue;
    }

    STableBlockScanInfo* pScanInfo = p;
    if (pScanInfo->pBlockList == NULL) {
557
      pScanInfo->pBlockList = taosArrayInit(4, sizeof(int32_t));
H
Haojun Liao 已提交
558 559
    }

H
Hongze Cheng 已提交
560
    taosArrayPush(pIndexList, pBlockIdx);
H
Haojun Liao 已提交
561
  }
H
Hongze Cheng 已提交
562

563
  int64_t et2 = taosGetTimestampUs();
564
  tsdbDebug("load block index for %d tables completed, elapsed time:%.2f ms, set blockIdx:%.2f ms, size:%.2f Kb %s",
565
            (int32_t)num, (et1 - st) / 1000.0, (et2 - et1) / 1000.0, num * sizeof(SBlockIdx) / 1024.0, pReader->idStr);
566 567 568

  pReader->cost.headFileLoadTime += (et1 - st) / 1000.0;

569
_end:
H
Hongze Cheng 已提交
570
  taosArrayDestroy(aBlockIdx);
H
Haojun Liao 已提交
571 572
  return code;
}
H
Hongze Cheng 已提交
573

574
static void cleanupTableScanInfo(SHashObj* pTableMap) {
575
  STableBlockScanInfo* px = NULL;
dengyihao's avatar
dengyihao 已提交
576
  while (1) {
577
    px = taosHashIterate(pTableMap, px);
578 579 580 581
    if (px == NULL) {
      break;
    }

582
    // reset the index in last block when handing a new file
583
    px->indexInBlockL = INITIAL_ROW_INDEX_VAL;
584
    tMapDataClear(&px->mapData);
585 586
    taosArrayClear(px->pBlockList);
  }
587 588 589 590 591 592 593 594 595 596
}

static int32_t doLoadFileBlock(STsdbReader* pReader, SArray* pIndexList, SArray* pLastBlockIndex,
                               SBlockNumber * pBlockNum, SArray* pQualifiedLastBlock) {
  int32_t numOfQTable = 0;
  size_t  sizeInDisk = 0;
  size_t  numOfTables = taosArrayGetSize(pIndexList);

  int64_t st = taosGetTimestampUs();
  cleanupTableScanInfo(pReader->status.pTableMap);
597

dengyihao's avatar
dengyihao 已提交
598
  for (int32_t i = 0; i < numOfTables; ++i) {
H
Haojun Liao 已提交
599
    SBlockIdx* pBlockIdx = taosArrayGet(pIndexList, i);
H
Hongze Cheng 已提交
600

601
    STableBlockScanInfo* pScanInfo = taosHashGet(pReader->status.pTableMap, &pBlockIdx->uid, sizeof(int64_t));
H
Hongze Cheng 已提交
602

603
    tMapDataReset(&pScanInfo->mapData);
H
Hongze Cheng 已提交
604
    tsdbReadBlock(pReader->pFileReader, pBlockIdx, &pScanInfo->mapData);
605

606
    sizeInDisk += pScanInfo->mapData.nData;
607
    for (int32_t j = 0; j < pScanInfo->mapData.nItem; ++j) {
H
Haojun Liao 已提交
608
      SBlock block = {0};
609
      tMapDataGetItemByIdx(&pScanInfo->mapData, j, &block, tGetBlock);
H
Hongze Cheng 已提交
610

611
      // 1. time range check
612
      if (block.minKey.ts > pReader->window.ekey || block.maxKey.ts < pReader->window.skey) {
H
Haojun Liao 已提交
613 614
        continue;
      }
H
Hongze Cheng 已提交
615

616
      // 2. version range check
H
Hongze Cheng 已提交
617
      if (block.minVer > pReader->verRange.maxVer || block.maxVer < pReader->verRange.minVer) {
618 619
        continue;
      }
620

621
      void* p = taosArrayPush(pScanInfo->pBlockList, &j);
H
Haojun Liao 已提交
622
      if (p == NULL) {
623
        tMapDataClear(&pScanInfo->mapData);
H
Haojun Liao 已提交
624 625
        return TSDB_CODE_OUT_OF_MEMORY;
      }
626

627
      pBlockNum->numOfBlocks += 1;
H
Haojun Liao 已提交
628
    }
H
Hongze Cheng 已提交
629

H
Haojun Liao 已提交
630
    if (pScanInfo->pBlockList != NULL && taosArrayGetSize(pScanInfo->pBlockList) > 0) {
631 632 633 634 635 636 637 638 639 640 641 642
      numOfQTable += 1;
    }
  }

  size_t numOfLast = taosArrayGetSize(pLastBlockIndex);
  for(int32_t i = 0; i < numOfLast; ++i) {
    SBlockL* pLastBlock = taosArrayGet(pLastBlockIndex, i);
    if (pLastBlock->suid != pReader->suid) {
      continue;
    }

    {
643 644 645 646
      // 1. time range check
      if (pLastBlock->minKey > pReader->window.ekey || pLastBlock->maxKey < pReader->window.skey) {
        continue;
      }
647 648 649 650 651 652 653

      // 2. version range check
      if (pLastBlock->minVer > pReader->verRange.maxVer || pLastBlock->maxVer < pReader->verRange.minVer) {
        continue;
      }

      pBlockNum->numOfLastBlocks += 1;
654
      taosArrayPush(pQualifiedLastBlock, pLastBlock);
H
Haojun Liao 已提交
655 656
    }
  }
H
Hongze Cheng 已提交
657

658 659
  int32_t total = pBlockNum->numOfLastBlocks + pBlockNum->numOfBlocks;

660
  double el = (taosGetTimestampUs() - st) / 1000.0;
661 662 663 664 665
  tsdbDebug(
      "load block of %d tables completed, blocks:%d in %d tables, lastBlock:%d, block-info-size:%.2f Kb, elapsed "
      "time:%.2f ms %s",
      numOfTables, pBlockNum->numOfBlocks, numOfQTable, pBlockNum->numOfLastBlocks, sizeInDisk / 1000.0, el,
      pReader->idStr);
666

667
  pReader->cost.numOfBlocks += total;
668
  pReader->cost.headFileLoadTime += el;
669

H
Haojun Liao 已提交
670 671
  return TSDB_CODE_SUCCESS;
}
H
Hongze Cheng 已提交
672

673
static void setBlockAllDumped(SFileBlockDumpInfo* pDumpInfo, int64_t maxKey, int32_t order) {
674
  int32_t step = ASCENDING_TRAVERSE(order) ? 1 : -1;
675
  pDumpInfo->allDumped = true;
676
  pDumpInfo->lastKey = maxKey + step;
H
Haojun Liao 已提交
677 678
}

679 680
static void doCopyColVal(SColumnInfoData* pColInfoData, int32_t rowIndex, int32_t colIndex, SColVal* pColVal,
                         SBlockLoadSuppInfo* pSup) {
H
Haojun Liao 已提交
681
  if (IS_VAR_DATA_TYPE(pColVal->type)) {
682
    if (pColVal->isNull || pColVal->isNone) {
H
Haojun Liao 已提交
683 684 685
      colDataAppendNULL(pColInfoData, rowIndex);
    } else {
      varDataSetLen(pSup->buildBuf[colIndex], pColVal->value.nData);
H
Haojun Liao 已提交
686
      ASSERT(pColVal->value.nData <= pColInfoData->info.bytes);
H
Haojun Liao 已提交
687 688 689 690
      memcpy(varDataVal(pSup->buildBuf[colIndex]), pColVal->value.pData, pColVal->value.nData);
      colDataAppend(pColInfoData, rowIndex, pSup->buildBuf[colIndex], false);
    }
  } else {
691
    colDataAppend(pColInfoData, rowIndex, (const char*)&pColVal->value, pColVal->isNull || pColVal->isNone);
H
Haojun Liao 已提交
692
  }
H
Haojun Liao 已提交
693 694
}

695
static SFileDataBlockInfo* getCurrentBlockInfo(SDataBlockIter* pBlockIter) {
696 697
  if (taosArrayGetSize(pBlockIter->blockList) == 0) {
    ASSERT(pBlockIter->numOfBlocks == taosArrayGetSize(pBlockIter->blockList));
698 699
    return NULL;
  }
700 701 702

  SFileDataBlockInfo* pBlockInfo = taosArrayGet(pBlockIter->blockList, pBlockIter->index);
  return pBlockInfo;
703 704
}

705
static SBlock* getCurrentBlock(SDataBlockIter* pBlockIter) { return &pBlockIter->block; }
706

707
static int32_t copyBlockDataToSDataBlock(STsdbReader* pReader, STableBlockScanInfo* pBlockScanInfo) {
708
  SReaderStatus*  pStatus = &pReader->status;
709
  SDataBlockIter* pBlockIter = &pStatus->blockIter;
H
Hongze Cheng 已提交
710

711
  SBlockData*         pBlockData = &pStatus->fileBlockData;
H
Haojun Liao 已提交
712
  SFileDataBlockInfo* pFBlock = getCurrentBlockInfo(pBlockIter);
713
  SBlock*             pBlock = getCurrentBlock(pBlockIter);
H
Haojun Liao 已提交
714
  SSDataBlock*        pResBlock = pReader->pResBlock;
715
  int32_t             numOfOutputCols = blockDataGetNumOfCols(pResBlock);
H
Haojun Liao 已提交
716

H
Haojun Liao 已提交
717
  SBlockLoadSuppInfo* pSupInfo = &pReader->suppInfo;
718
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;
H
Haojun Liao 已提交
719

H
Haojun Liao 已提交
720
  SColVal cv = {0};
721
  int64_t st = taosGetTimestampUs();
722 723
  bool    asc = ASCENDING_TRAVERSE(pReader->order);
  int32_t step = asc ? 1 : -1;
724

725
  int32_t rowIndex = 0;
726 727
  int32_t remain = asc ? (pBlockData->nRow - pDumpInfo->rowIndex) : (pDumpInfo->rowIndex + 1);

728 729 730 731 732 733 734 735
  int32_t endIndex = 0;
  if (remain <= pReader->capacity) {
    endIndex = pBlockData->nRow;
  } else {
    endIndex = pDumpInfo->rowIndex + step * pReader->capacity;
    remain = pReader->capacity;
  }

736
  int32_t          i = 0;
737 738
  SColumnInfoData* pColData = taosArrayGet(pResBlock->pDataBlock, i);
  if (pColData->info.colId == PRIMARYKEY_TIMESTAMP_COL_ID) {
739
    for (int32_t j = pDumpInfo->rowIndex; j < endIndex && j >= 0; j += step) {
740 741 742 743 744
      colDataAppend(pColData, rowIndex++, (const char*)&pBlockData->aTSKEY[j], false);
    }
    i += 1;
  }

745 746 747
  int32_t colIndex = 0;
  int32_t num = taosArrayGetSize(pBlockData->aIdx);
  while (i < numOfOutputCols && colIndex < num) {
748 749 750
    rowIndex = 0;
    pColData = taosArrayGet(pResBlock->pDataBlock, i);

H
Hongze Cheng 已提交
751
    SColData* pData = tBlockDataGetColDataByIdx(pBlockData, colIndex);
752 753 754
    if (pData->cid < pColData->info.colId) {
      colIndex += 1;
    } else if (pData->cid == pColData->info.colId) {
755
      for (int32_t j = pDumpInfo->rowIndex; j < endIndex && j >= 0; j += step) {
756 757
        tColDataGetValue(pData, j, &cv);
        doCopyColVal(pColData, rowIndex++, i, &cv, pSupInfo);
H
Haojun Liao 已提交
758
      }
759
      colIndex += 1;
760
      i += 1;
761
      ASSERT(rowIndex == remain);
762 763
    } else {  // the specified column does not exist in file block, fill with null data
      colDataAppendNNULL(pColData, 0, remain);
764
      i += 1;
H
Haojun Liao 已提交
765
    }
766 767
  }

768
  while (i < numOfOutputCols) {
769 770 771
    pColData = taosArrayGet(pResBlock->pDataBlock, i);
    colDataAppendNNULL(pColData, 0, remain);
    i += 1;
H
Haojun Liao 已提交
772
  }
H
Haojun Liao 已提交
773

774
  pResBlock->info.rows = remain;
775
  pDumpInfo->rowIndex += step * remain;
776

777
  setBlockAllDumped(pDumpInfo, pBlock->maxKey.ts, pReader->order);
H
Haojun Liao 已提交
778

779
  double elapsedTime = (taosGetTimestampUs() - st) / 1000.0;
H
Haojun Liao 已提交
780
  pReader->cost.blockLoadTime += elapsedTime;
H
Haojun Liao 已提交
781

782
  int32_t unDumpedRows = asc ? pBlock->nRow - pDumpInfo->rowIndex : pDumpInfo->rowIndex + 1;
H
Haojun Liao 已提交
783
  tsdbDebug("%p copy file block to sdatablock, global index:%d, table index:%d, brange:%" PRId64 "-%" PRId64
784
            ", rows:%d, remain:%d, minVer:%" PRId64 ", maxVer:%" PRId64 ", elapsed time:%.2f ms, %s",
785
            pReader, pBlockIter->index, pFBlock->tbBlockIdx, pBlock->minKey.ts, pBlock->maxKey.ts, remain, unDumpedRows,
H
Hongze Cheng 已提交
786
            pBlock->minVer, pBlock->maxVer, elapsedTime, pReader->idStr);
787 788 789 790

  return TSDB_CODE_SUCCESS;
}

791
static int32_t doLoadFileBlockData(STsdbReader* pReader, SDataBlockIter* pBlockIter, SBlockData* pBlockData) {
792 793
  int64_t st = taosGetTimestampUs();

794
  SFileDataBlockInfo* pBlockInfo = getCurrentBlockInfo(pBlockIter);
795
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;
796
  ASSERT(pBlockInfo != NULL);
797

798 799 800 801 802
  SBlock* pBlock = getCurrentBlock(pBlockIter);
  int32_t code = tsdbReadDataBlock(pReader->pFileReader, pBlock, pBlockData);
  if (code != TSDB_CODE_SUCCESS) {
    tsdbError("%p error occurs in loading file block, global index:%d, table index:%d, brange:%" PRId64 "-%" PRId64
              ", rows:%d, code:%s %s",
803
              pReader, pBlockIter->index, pBlockInfo->tbBlockIdx, pBlock->minKey.ts, pBlock->maxKey.ts, pBlock->nRow,
804 805 806
              tstrerror(code), pReader->idStr);
    return code;
  }
807

808
  double elapsedTime = (taosGetTimestampUs() - st) / 1000.0;
809

810 811 812 813
  tsdbDebug("%p load file block into buffer, global index:%d, index in table block list:%d, brange:%" PRId64 "-%" PRId64
            ", rows:%d, minVer:%" PRId64 ", maxVer:%" PRId64 ", elapsed time:%.2f ms, %s",
            pReader, pBlockIter->index, pBlockInfo->tbBlockIdx, pBlock->minKey.ts, pBlock->maxKey.ts, pBlock->nRow,
            pBlock->minVer, pBlock->maxVer, elapsedTime, pReader->idStr);
814 815 816

  pReader->cost.blockLoadTime += elapsedTime;
  pDumpInfo->allDumped = false;
817

H
Haojun Liao 已提交
818
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
819
}
H
Hongze Cheng 已提交
820

H
Haojun Liao 已提交
821 822 823
static void cleanupBlockOrderSupporter(SBlockOrderSupporter* pSup) {
  taosMemoryFreeClear(pSup->numOfBlocksPerTable);
  taosMemoryFreeClear(pSup->indexPerTable);
H
Hongze Cheng 已提交
824

H
Haojun Liao 已提交
825 826 827 828
  for (int32_t i = 0; i < pSup->numOfTables; ++i) {
    SBlockOrderWrapper* pBlockInfo = pSup->pDataBlockInfo[i];
    taosMemoryFreeClear(pBlockInfo);
  }
H
Hongze Cheng 已提交
829

H
Haojun Liao 已提交
830 831
  taosMemoryFreeClear(pSup->pDataBlockInfo);
}
H
Hongze Cheng 已提交
832

H
Haojun Liao 已提交
833 834
static int32_t initBlockOrderSupporter(SBlockOrderSupporter* pSup, int32_t numOfTables) {
  ASSERT(numOfTables >= 1);
H
Hongze Cheng 已提交
835

H
Haojun Liao 已提交
836
  pSup->numOfBlocksPerTable = taosMemoryCalloc(1, sizeof(int32_t) * numOfTables);
837 838
  pSup->indexPerTable = taosMemoryCalloc(1, sizeof(int32_t) * numOfTables);
  pSup->pDataBlockInfo = taosMemoryCalloc(1, POINTER_BYTES * numOfTables);
H
Hongze Cheng 已提交
839

H
Haojun Liao 已提交
840 841 842 843
  if (pSup->numOfBlocksPerTable == NULL || pSup->indexPerTable == NULL || pSup->pDataBlockInfo == NULL) {
    cleanupBlockOrderSupporter(pSup);
    return TSDB_CODE_OUT_OF_MEMORY;
  }
H
Hongze Cheng 已提交
844

H
Haojun Liao 已提交
845 846
  return TSDB_CODE_SUCCESS;
}
H
Hongze Cheng 已提交
847

H
Haojun Liao 已提交
848
static int32_t fileDataBlockOrderCompar(const void* pLeft, const void* pRight, void* param) {
849
  int32_t leftIndex = *(int32_t*)pLeft;
H
Haojun Liao 已提交
850
  int32_t rightIndex = *(int32_t*)pRight;
H
Hongze Cheng 已提交
851

H
Haojun Liao 已提交
852
  SBlockOrderSupporter* pSupporter = (SBlockOrderSupporter*)param;
H
Hongze Cheng 已提交
853

H
Haojun Liao 已提交
854 855
  int32_t leftTableBlockIndex = pSupporter->indexPerTable[leftIndex];
  int32_t rightTableBlockIndex = pSupporter->indexPerTable[rightIndex];
H
Hongze Cheng 已提交
856

H
Haojun Liao 已提交
857 858 859 860 861 862 863
  if (leftTableBlockIndex > pSupporter->numOfBlocksPerTable[leftIndex]) {
    /* left block is empty */
    return 1;
  } else if (rightTableBlockIndex > pSupporter->numOfBlocksPerTable[rightIndex]) {
    /* right block is empty */
    return -1;
  }
H
Hongze Cheng 已提交
864

865
  SBlockOrderWrapper* pLeftBlock = &pSupporter->pDataBlockInfo[leftIndex][leftTableBlockIndex];
H
Haojun Liao 已提交
866
  SBlockOrderWrapper* pRightBlock = &pSupporter->pDataBlockInfo[rightIndex][rightTableBlockIndex];
H
Hongze Cheng 已提交
867

868 869 870 871
  return pLeftBlock->offset > pRightBlock->offset ? 1 : -1;
}

static int32_t doSetCurrentBlock(SDataBlockIter* pBlockIter) {
872 873 874 875
  SFileDataBlockInfo* pBlockInfo = getCurrentBlockInfo(pBlockIter);
  if (pBlockInfo != NULL) {
    STableBlockScanInfo* pScanInfo = taosHashGet(pBlockIter->pTableMap, &pBlockInfo->uid, sizeof(pBlockInfo->uid));
    int32_t* mapDataIndex = taosArrayGet(pScanInfo->pBlockList, pBlockInfo->tbBlockIdx);
876 877
    tMapDataGetItemByIdx(&pScanInfo->mapData, *mapDataIndex, &pBlockIter->block, tGetBlock);
  }
878 879 880 881 882 883

#if 0
  qDebug("check file block, table uid:%"PRIu64" index:%d offset:%"PRId64", ", pScanInfo->uid, *mapDataIndex, pBlockIter->block.aSubBlock[0].offset);
#endif

  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
884
}
H
Hongze Cheng 已提交
885

886
static int32_t initBlockIterator(STsdbReader* pReader, SDataBlockIter* pBlockIter, int32_t numOfBlocks) {
887
  bool asc = ASCENDING_TRAVERSE(pReader->order);
H
Haojun Liao 已提交
888

889
  pBlockIter->numOfBlocks = numOfBlocks;
890
  taosArrayClear(pBlockIter->blockList);
891
  pBlockIter->pTableMap = pReader->status.pTableMap;
892

893 894
  // access data blocks according to the offset of each block in asc/desc order.
  int32_t numOfTables = (int32_t)taosHashGetSize(pReader->status.pTableMap);
H
Haojun Liao 已提交
895

896
  int64_t st = taosGetTimestampUs();
H
Haojun Liao 已提交
897

898
  SBlockOrderSupporter sup = {0};
899
  int32_t              code = initBlockOrderSupporter(&sup, numOfTables);
900 901 902
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }
H
Haojun Liao 已提交
903

904 905 906 907 908 909 910
  int32_t cnt = 0;
  void*   ptr = NULL;
  while (1) {
    ptr = taosHashIterate(pReader->status.pTableMap, ptr);
    if (ptr == NULL) {
      break;
    }
H
Haojun Liao 已提交
911

912 913 914 915
    STableBlockScanInfo* pTableScanInfo = (STableBlockScanInfo*)ptr;
    if (pTableScanInfo->pBlockList == NULL || taosArrayGetSize(pTableScanInfo->pBlockList) == 0) {
      continue;
    }
H
Haojun Liao 已提交
916

917 918
    size_t num = taosArrayGetSize(pTableScanInfo->pBlockList);
    sup.numOfBlocksPerTable[sup.numOfTables] = num;
H
Haojun Liao 已提交
919

920 921 922 923 924
    char* buf = taosMemoryMalloc(sizeof(SBlockOrderWrapper) * num);
    if (buf == NULL) {
      cleanupBlockOrderSupporter(&sup);
      return TSDB_CODE_TDB_OUT_OF_MEMORY;
    }
H
Haojun Liao 已提交
925

926
    sup.pDataBlockInfo[sup.numOfTables] = (SBlockOrderWrapper*)buf;
927
    SBlock block = {0};
928 929
    for (int32_t k = 0; k < num; ++k) {
      SBlockOrderWrapper wrapper = {0};
930 931 932 933

      int32_t* mapDataIndex = taosArrayGet(pTableScanInfo->pBlockList, k);
      tMapDataGetItemByIdx(&pTableScanInfo->mapData, *mapDataIndex, &block, tGetBlock);

934
      wrapper.uid = pTableScanInfo->uid;
935
      wrapper.offset = block.aSubBlock[0].offset;
H
Haojun Liao 已提交
936

937 938 939 940 941 942
      sup.pDataBlockInfo[sup.numOfTables][k] = wrapper;
      cnt++;
    }

    sup.numOfTables += 1;
  }
H
Haojun Liao 已提交
943

944
  ASSERT(numOfBlocks == cnt);
H
Haojun Liao 已提交
945

946
  // since there is only one table qualified, blocks are not sorted
947 948
  if (sup.numOfTables == 1) {
    for (int32_t i = 0; i < numOfBlocks; ++i) {
949 950
      SFileDataBlockInfo blockInfo = {.uid = sup.pDataBlockInfo[0][i].uid, .tbBlockIdx = i};
      taosArrayPush(pBlockIter->blockList, &blockInfo);
951
    }
952

953
    int64_t et = taosGetTimestampUs();
954
    tsdbDebug("%p create blocks info struct completed for one table, %d blocks not sorted, elapsed time:%.2f ms %s",
955
              pReader, numOfBlocks, (et - st) / 1000.0, pReader->idStr);
H
Haojun Liao 已提交
956

957
    pBlockIter->index = asc ? 0 : (numOfBlocks - 1);
H
Haojun Liao 已提交
958
    cleanupBlockOrderSupporter(&sup);
959
    doSetCurrentBlock(pBlockIter);
960
    return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
961
  }
H
Haojun Liao 已提交
962

963 964
  tsdbDebug("%p create data blocks info struct completed, %d blocks in %d tables %s", pReader, cnt, sup.numOfTables,
            pReader->idStr);
965

966
  ASSERT(cnt <= numOfBlocks && sup.numOfTables <= numOfTables);
H
Haojun Liao 已提交
967

968 969 970 971 972
  SMultiwayMergeTreeInfo* pTree = NULL;
  uint8_t                 ret = tMergeTreeCreate(&pTree, sup.numOfTables, &sup, fileDataBlockOrderCompar);
  if (ret != TSDB_CODE_SUCCESS) {
    cleanupBlockOrderSupporter(&sup);
    return TSDB_CODE_TDB_OUT_OF_MEMORY;
H
Haojun Liao 已提交
973
  }
H
Haojun Liao 已提交
974

975 976 977 978
  int32_t numOfTotal = 0;
  while (numOfTotal < cnt) {
    int32_t pos = tMergeTreeGetChosenIndex(pTree);
    int32_t index = sup.indexPerTable[pos]++;
H
Haojun Liao 已提交
979

980 981
    SFileDataBlockInfo blockInfo = {.uid = sup.pDataBlockInfo[pos][index].uid, .tbBlockIdx = index};
    taosArrayPush(pBlockIter->blockList, &blockInfo);
H
Haojun Liao 已提交
982

983 984 985 986
    // set data block index overflow, in order to disable the offset comparator
    if (sup.indexPerTable[pos] >= sup.numOfBlocksPerTable[pos]) {
      sup.indexPerTable[pos] = sup.numOfBlocksPerTable[pos] + 1;
    }
H
Haojun Liao 已提交
987

988 989
    numOfTotal += 1;
    tMergeTreeAdjust(pTree, tMergeTreeGetAdjustIndex(pTree));
H
Haojun Liao 已提交
990
  }
H
Haojun Liao 已提交
991

992
  int64_t et = taosGetTimestampUs();
993
  tsdbDebug("%p %d data blocks access order completed, elapsed time:%.2f ms %s", pReader, numOfBlocks, (et - st) / 1000.0,
994
            pReader->idStr);
995 996
  cleanupBlockOrderSupporter(&sup);
  taosMemoryFree(pTree);
H
Haojun Liao 已提交
997

998
  pBlockIter->index = asc ? 0 : (numOfBlocks - 1);
999 1000
  doSetCurrentBlock(pBlockIter);

1001
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
1002
}
H
Hongze Cheng 已提交
1003

H
Haojun Liao 已提交
1004
static bool blockIteratorNext(SDataBlockIter* pBlockIter) {
1005 1006
  bool asc = ASCENDING_TRAVERSE(pBlockIter->order);

1007
  int32_t step = asc ? 1 : -1;
1008
  if ((pBlockIter->index >= pBlockIter->numOfBlocks - 1 && asc) || (pBlockIter->index <= 0 && (!asc))) {
1009 1010 1011
    return false;
  }

1012
  pBlockIter->index += step;
1013 1014
  doSetCurrentBlock(pBlockIter);

1015 1016 1017
  return true;
}

1018 1019 1020
/**
 * This is an two rectangles overlap cases.
 */
1021
static int32_t dataBlockPartiallyRequired(STimeWindow* pWindow, SVersionRange* pVerRange, SBlock* pBlock) {
1022 1023
  return (pWindow->ekey < pBlock->maxKey.ts && pWindow->ekey >= pBlock->minKey.ts) ||
         (pWindow->skey > pBlock->minKey.ts && pWindow->skey <= pBlock->maxKey.ts) ||
H
Hongze Cheng 已提交
1024 1025
         (pVerRange->minVer > pBlock->minVer && pVerRange->minVer <= pBlock->maxVer) ||
         (pVerRange->maxVer < pBlock->maxVer && pVerRange->maxVer >= pBlock->minVer);
H
Haojun Liao 已提交
1026
}
H
Hongze Cheng 已提交
1027

1028 1029
static SBlock* getNeighborBlockOfSameTable(SFileDataBlockInfo* pFBlockInfo, STableBlockScanInfo* pTableBlockScanInfo,
                                           int32_t* nextIndex, int32_t order) {
1030 1031 1032
  bool asc = ASCENDING_TRAVERSE(order);
  if (asc && pFBlockInfo->tbBlockIdx >= taosArrayGetSize(pTableBlockScanInfo->pBlockList) - 1) {
    return NULL;
1033 1034
  }

1035
  if (!asc && pFBlockInfo->tbBlockIdx == 0) {
1036 1037 1038
    return NULL;
  }

1039
  int32_t step = asc ? 1 : -1;
1040
  *nextIndex = pFBlockInfo->tbBlockIdx + step;
1041

1042
  SBlock*  pBlock = taosMemoryCalloc(1, sizeof(SBlock));
1043 1044 1045 1046
  int32_t* indexInMapdata = taosArrayGet(pTableBlockScanInfo->pBlockList, *nextIndex);

  tMapDataGetItemByIdx(&pTableBlockScanInfo->mapData, *indexInMapdata, pBlock, tGetBlock);
  return pBlock;
1047 1048 1049 1050 1051
}

static int32_t findFileBlockInfoIndex(SDataBlockIter* pBlockIter, SFileDataBlockInfo* pFBlockInfo) {
  ASSERT(pBlockIter != NULL && pFBlockInfo != NULL);

1052
  int32_t step = ASCENDING_TRAVERSE(pBlockIter->order) ? 1 : -1;
1053 1054
  int32_t index = pBlockIter->index;

1055
  while (index < pBlockIter->numOfBlocks && index >= 0) {
1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067
    SFileDataBlockInfo* pFBlock = taosArrayGet(pBlockIter->blockList, index);
    if (pFBlock->uid == pFBlockInfo->uid && pFBlock->tbBlockIdx == pFBlockInfo->tbBlockIdx) {
      return index;
    }

    index += step;
  }

  ASSERT(0);
  return -1;
}

1068
static int32_t setFileBlockActiveInBlockIter(SDataBlockIter* pBlockIter, int32_t index, int32_t step) {
1069
  if (index < 0 || index >= pBlockIter->numOfBlocks) {
1070 1071 1072 1073
    return -1;
  }

  SFileDataBlockInfo fblock = *(SFileDataBlockInfo*)taosArrayGet(pBlockIter->blockList, index);
1074 1075 1076 1077 1078
  pBlockIter->index += step;

  if (index != pBlockIter->index) {
    taosArrayRemove(pBlockIter->blockList, index);
    taosArrayInsert(pBlockIter->blockList, pBlockIter->index, &fblock);
1079

1080 1081 1082
    SFileDataBlockInfo* pBlockInfo = taosArrayGet(pBlockIter->blockList, pBlockIter->index);
    ASSERT(pBlockInfo->uid == fblock.uid && pBlockInfo->tbBlockIdx == fblock.tbBlockIdx);
  }
1083

1084
  doSetCurrentBlock(pBlockIter);
1085 1086 1087 1088 1089 1090 1091 1092 1093 1094
  return TSDB_CODE_SUCCESS;
}

static bool overlapWithNeighborBlock(SBlock* pBlock, SBlock* pNeighbor, int32_t order) {
  // it is the last block in current file, no chance to overlap with neighbor blocks.
  if (ASCENDING_TRAVERSE(order)) {
    return pBlock->maxKey.ts == pNeighbor->minKey.ts;
  } else {
    return pBlock->minKey.ts == pNeighbor->maxKey.ts;
  }
H
Haojun Liao 已提交
1095
}
H
Hongze Cheng 已提交
1096

1097
static bool bufferDataInFileBlockGap(int32_t order, TSDBKEY key, SBlock* pBlock) {
H
Haojun Liao 已提交
1098
  bool ascScan = ASCENDING_TRAVERSE(order);
H
Hongze Cheng 已提交
1099

1100
  return (ascScan && (key.ts != TSKEY_INITIAL_VAL && key.ts <= pBlock->minKey.ts)) ||
1101
         (!ascScan && (key.ts != TSKEY_INITIAL_VAL && key.ts >= pBlock->maxKey.ts));
H
Haojun Liao 已提交
1102
}
H
Hongze Cheng 已提交
1103

H
Haojun Liao 已提交
1104
static bool keyOverlapFileBlock(TSDBKEY key, SBlock* pBlock, SVersionRange* pVerRange) {
H
Hongze Cheng 已提交
1105 1106
  return (key.ts >= pBlock->minKey.ts && key.ts <= pBlock->maxKey.ts) && (pBlock->maxVer >= pVerRange->minVer) &&
         (pBlock->minVer <= pVerRange->maxVer);
H
Haojun Liao 已提交
1107 1108
}

1109 1110 1111 1112 1113 1114
static bool doCheckforDatablockOverlap(STableBlockScanInfo* pBlockScanInfo, const SBlock* pBlock) {
  size_t num = taosArrayGetSize(pBlockScanInfo->delSkyline);

  for (int32_t i = pBlockScanInfo->fileDelIndex; i < num; i += 1) {
    TSDBKEY* p = taosArrayGet(pBlockScanInfo->delSkyline, i);
    if (p->ts >= pBlock->minKey.ts && p->ts <= pBlock->maxKey.ts) {
H
Hongze Cheng 已提交
1115
      if (p->version >= pBlock->minVer) {
1116 1117 1118
        return true;
      }
    } else if (p->ts < pBlock->minKey.ts) {  // p->ts < pBlock->minKey.ts
H
Hongze Cheng 已提交
1119
      if (p->version >= pBlock->minVer) {
1120 1121 1122 1123 1124 1125 1126
        if (i < num - 1) {
          TSDBKEY* pnext = taosArrayGet(pBlockScanInfo->delSkyline, i + 1);
          if (i + 1 == num - 1) {  // pnext is the last point
            if (pnext->ts >= pBlock->minKey.ts) {
              return true;
            }
          } else {
H
Hongze Cheng 已提交
1127
            if (pnext->ts >= pBlock->minKey.ts && pnext->version >= pBlock->minVer) {
1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142
              return true;
            }
          }
        } else {  // it must be the last point
          ASSERT(p->version == 0);
        }
      }
    } else {  // (p->ts > pBlock->maxKey.ts) {
      return false;
    }
  }

  return false;
}

1143
static bool overlapWithDelSkyline(STableBlockScanInfo* pBlockScanInfo, const SBlock* pBlock, int32_t order) {
1144 1145 1146 1147
  if (pBlockScanInfo->delSkyline == NULL) {
    return false;
  }

1148
  // ts is not overlap
1149
  TSDBKEY* pFirst = taosArrayGet(pBlockScanInfo->delSkyline, 0);
L
Liu Jicong 已提交
1150
  TSDBKEY* pLast = taosArrayGetLast(pBlockScanInfo->delSkyline);
1151 1152 1153 1154 1155
  if (pBlock->minKey.ts > pLast->ts || pBlock->maxKey.ts < pFirst->ts) {
    return false;
  }

  // version is not overlap
1156 1157 1158 1159
  if (ASCENDING_TRAVERSE(order)) {
    return doCheckforDatablockOverlap(pBlockScanInfo, pBlock);
  } else {
    int32_t index = pBlockScanInfo->fileDelIndex;
1160
    while (1) {
1161 1162 1163 1164 1165
      TSDBKEY* p = taosArrayGet(pBlockScanInfo->delSkyline, index);
      if (p->ts > pBlock->minKey.ts && index > 0) {
        index -= 1;
      } else {  // find the first point that is smaller than the minKey.ts of dataBlock.
        break;
1166 1167 1168
      }
    }

1169 1170
    return doCheckforDatablockOverlap(pBlockScanInfo, pBlock);
  }
1171 1172
}

1173 1174 1175 1176
// 1. the version of all rows should be less than the endVersion
// 2. current block should not overlap with next neighbor block
// 3. current timestamp should not be overlap with each other
// 4. output buffer should be large enough to hold all rows in current block
1177
// 5. delete info should not overlap with current block data
1178
static bool fileBlockShouldLoad(STsdbReader* pReader, SFileDataBlockInfo* pFBlock, SBlock* pBlock,
1179
                                STableBlockScanInfo* pScanInfo, TSDBKEY key, SLastBlockReader* pLastBlockReader) {
1180 1181 1182
  int32_t neighborIndex = 0;
  SBlock* pNeighbor = getNeighborBlockOfSameTable(pFBlock, pScanInfo, &neighborIndex, pReader->order);

1183
  // overlap with neighbor
1184 1185 1186
  bool overlapWithNeighbor = false;
  if (pNeighbor) {
    overlapWithNeighbor = overlapWithNeighborBlock(pBlock, pNeighbor, pReader->order);
1187
    taosMemoryFree(pNeighbor);
1188 1189
  }

1190
  // has duplicated ts of different version in this block
L
Liu Jicong 已提交
1191 1192
  bool hasDup = (pBlock->nSubBlock == 1) ? pBlock->hasDup : true;
  bool overlapWithDel = overlapWithDelSkyline(pScanInfo, pBlock, pReader->order);
1193

1194 1195
  // todo here we need to each key in the last files to identify if it is really overlapped with last block
  bool overlapWithlastBlock = false;
1196
  if (taosArrayGetSize(pLastBlockReader->pBlockL) > 0 && (pLastBlockReader->currentBlockIndex != -1)) {
1197 1198 1199 1200
    SBlockL *pBlockL = taosArrayGet(pLastBlockReader->pBlockL, pLastBlockReader->currentBlockIndex);
    overlapWithlastBlock = !(pBlock->maxKey.ts < pBlockL->minKey || pBlock->minKey.ts > pBlockL->maxKey);
  }

1201 1202 1203 1204 1205 1206 1207 1208 1209 1210
  bool moreThanOutputCapacity = pBlock->nRow > pReader->capacity;
  bool partiallyRequired = dataBlockPartiallyRequired(&pReader->window, &pReader->verRange, pBlock);
  bool overlapWithKey = keyOverlapFileBlock(key, pBlock, &pReader->verRange);

  bool loadDataBlock = (overlapWithNeighbor || hasDup || partiallyRequired || overlapWithKey ||
                        moreThanOutputCapacity || overlapWithDel || overlapWithlastBlock);

  // log the reason why load the datablock for profile
  if (loadDataBlock) {
    tsdbDebug("%p uid:%" PRIu64
1211
              " need to load the datablock, overlapwithneighborblock:%d, hasDup:%d, partiallyRequired:%d, "
1212 1213 1214 1215 1216 1217
              "overlapWithKey:%d, greaterThanBuf:%d, overlapWithDel:%d, overlapWithlastBlock:%d, %s",
              pReader, pFBlock->uid, overlapWithNeighbor, hasDup, partiallyRequired, overlapWithKey,
              moreThanOutputCapacity, overlapWithDel, overlapWithlastBlock, pReader->idStr);
  }

  return loadDataBlock;
H
Haojun Liao 已提交
1218 1219
}

1220
static int32_t buildDataBlockFromBuf(STsdbReader* pReader, STableBlockScanInfo* pBlockScanInfo, int64_t endKey) {
1221
  if (!(pBlockScanInfo->iiter.hasVal || pBlockScanInfo->iter.hasVal)) {
1222 1223
    return TSDB_CODE_SUCCESS;
  }
H
Haojun Liao 已提交
1224

1225 1226 1227
  SSDataBlock* pBlock = pReader->pResBlock;

  int64_t st = taosGetTimestampUs();
1228
  int32_t code = buildDataBlockFromBufImpl(pBlockScanInfo, endKey, pReader->capacity, pReader);
H
Haojun Liao 已提交
1229

1230
  blockDataUpdateTsWindow(pBlock, 0);
1231
  pBlock->info.uid = pBlockScanInfo->uid;
1232

1233
  setComposedBlockFlag(pReader, true);
1234

1235
  double elapsedTime = (taosGetTimestampUs() - st) / 1000.0;
S
Shengliang Guan 已提交
1236
  tsdbDebug("%p build data block from cache completed, elapsed time:%.2f ms, numOfRows:%d, brange:%" PRId64
1237 1238 1239
            " - %" PRId64 " %s",
            pReader, elapsedTime, pBlock->info.rows, pBlock->info.window.skey, pBlock->info.window.ekey,
            pReader->idStr);
1240 1241

  pReader->cost.buildmemBlock += elapsedTime;
H
Haojun Liao 已提交
1242 1243 1244
  return code;
}

1245 1246
static bool tryCopyDistinctRowFromFileBlock(STsdbReader* pReader, SBlockData* pBlockData, int64_t key,
                                            SFileBlockDumpInfo* pDumpInfo) {
1247 1248 1249 1250 1251
  // opt version
  // 1. it is not a border point
  // 2. the direct next point is not an duplicated timestamp
  if ((pDumpInfo->rowIndex < pDumpInfo->totalRows - 1 && pReader->order == TSDB_ORDER_ASC) ||
      (pDumpInfo->rowIndex > 0 && pReader->order == TSDB_ORDER_DESC)) {
1252
    int32_t step = pReader->order == TSDB_ORDER_ASC ? 1 : -1;
1253 1254

    int64_t nextKey = pBlockData->aTSKEY[pDumpInfo->rowIndex + step];
1255
    if (nextKey != key) {  // merge is not needed
1256
      doAppendRowFromFileBlock(pReader->pResBlock, pReader, pBlockData, pDumpInfo->rowIndex);
1257 1258 1259 1260 1261 1262 1263 1264
      pDumpInfo->rowIndex += step;
      return true;
    }
  }

  return false;
}

H
Haojun Liao 已提交
1265 1266 1267 1268 1269 1270
static FORCE_INLINE STSchema* doGetSchemaForTSRow(int32_t sversion, STsdbReader* pReader, uint64_t uid) {
  // always set the newest schema version in pReader->pSchema
  if (pReader->pSchema == NULL) {
    pReader->pSchema = metaGetTbTSchema(pReader->pTsdb->pVnode->pMeta, uid, -1);
  }

1271
  if (pReader->pSchema && sversion == pReader->pSchema->version) {
H
Haojun Liao 已提交
1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289
    return pReader->pSchema;
  }

  if (pReader->pMemSchema == NULL) {
    int32_t code =
        metaGetTbTSchemaEx(pReader->pTsdb->pVnode->pMeta, pReader->suid, uid, sversion, &pReader->pMemSchema);
    return pReader->pMemSchema;
  }

  if (pReader->pMemSchema->version == sversion) {
    return pReader->pMemSchema;
  }

  taosMemoryFree(pReader->pMemSchema);
  int32_t code = metaGetTbTSchemaEx(pReader->pTsdb->pVnode->pMeta, pReader->suid, uid, sversion, &pReader->pMemSchema);
  return pReader->pMemSchema;
}

1290
static int32_t doMergeBufAndFileRows(STsdbReader* pReader, STableBlockScanInfo* pBlockScanInfo, TSDBROW* pRow,
1291 1292 1293 1294 1295 1296
                                     SIterInfo* pIter, int64_t key, SLastBlockReader* pLastBlockReader) {
  SRowMerger          merge = {0};
  STSRow*             pTSRow = NULL;
  SBlockData*         pBlockData = &pReader->status.fileBlockData;
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;

1297
  int64_t tsLast = INT64_MIN;
1298
  if ((pLastBlockReader->lastBlockData.nRow > 0) && hasDataInLastBlock(pLastBlockReader)) {
1299 1300
    tsLast = getCurrentKeyInLastBlock(pLastBlockReader);
  }
1301 1302 1303 1304 1305 1306

  TSDBKEY  k = TSDBROW_KEY(pRow);
  TSDBROW  fRow = tsdbRowFromBlockData(pBlockData, pDumpInfo->rowIndex);

  SBlockData* pLastBlockData = &pLastBlockReader->lastBlockData;

1307 1308 1309
  int64_t minKey = 0;
  if (pReader->order == TSDB_ORDER_ASC) {
    minKey = INT64_MAX;   // chosen the minimum value
1310
    if (minKey > tsLast && hasDataInLastBlock(pLastBlockReader)) {
1311 1312
      minKey = tsLast;
    }
1313

1314 1315 1316
    if (minKey > k.ts) {
      minKey = k.ts;
    }
1317

1318 1319 1320 1321 1322
    if (minKey > key && pBlockData->nRow > 0) {
      minKey = key;
    }
  } else {
    minKey = INT64_MIN;
1323
    if (minKey < tsLast && hasDataInLastBlock(pLastBlockReader)) {
1324 1325 1326 1327 1328 1329 1330 1331 1332 1333
      minKey = tsLast;
    }

    if (minKey < k.ts) {
      minKey = k.ts;
    }

    if (minKey < key && pBlockData->nRow > 0) {
      minKey = key;
    }
1334 1335 1336 1337
  }

  bool init = false;

1338 1339
  // ASC: file block ---> last block -----> imem -----> mem
  //DESC: mem -----> imem -----> last block -----> file block
1340 1341
  if (pReader->order == TSDB_ORDER_ASC) {
    if (minKey == key) {
1342
      init = true;
1343 1344
      tRowMergerInit(&merge, &fRow, pReader->pSchema);
      doMergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pReader, &merge);
1345 1346
    }

1347
    if (minKey == tsLast) {
H
Haojun Liao 已提交
1348 1349 1350 1351
      TSDBROW fRow1 = tsdbRowFromBlockData(pLastBlockData, *pLastBlockReader->rowIndex);
      if (init) {
        tRowMerge(&merge, &fRow1);
      } else {
1352 1353 1354
        init = true;
        tRowMergerInit(&merge, &fRow1, pReader->pSchema);
      }
H
Haojun Liao 已提交
1355
      doMergeRowsInLastBlock(pLastBlockReader, pBlockScanInfo, tsLast, &merge);
1356
    }
1357

1358
    if (minKey == k.ts) {
H
Haojun Liao 已提交
1359 1360 1361
      if (init) {
        tRowMerge(&merge, pRow);
      } else {
1362 1363 1364 1365 1366 1367 1368 1369 1370
        init = true;
        STSchema* pSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(pRow), pReader, pBlockScanInfo->uid);
        tRowMergerInit(&merge, pRow, pSchema);
      }
      doMergeRowsInBuf(pIter, pBlockScanInfo->uid, k.ts, pBlockScanInfo->delSkyline, &merge, pReader);
    }
  } else {
    if (minKey == k.ts) {
      init = true;
1371 1372
      STSchema* pSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(pRow), pReader, pBlockScanInfo->uid);
      tRowMergerInit(&merge, pRow, pSchema);
1373
      doMergeRowsInBuf(pIter, pBlockScanInfo->uid, k.ts, pBlockScanInfo->delSkyline, &merge, pReader);
1374 1375
    }

1376
    if (minKey == tsLast) {
H
Haojun Liao 已提交
1377 1378 1379 1380
      TSDBROW fRow1 = tsdbRowFromBlockData(pLastBlockData, *pLastBlockReader->rowIndex);
      if (init) {
        tRowMerge(&merge, &fRow1);
      } else {
1381 1382 1383
        init = true;
        tRowMergerInit(&merge, &fRow1, pReader->pSchema);
      }
H
Haojun Liao 已提交
1384
      doMergeRowsInLastBlock(pLastBlockReader, pBlockScanInfo, tsLast, &merge);
1385 1386 1387
    }

    if (minKey == key) {
H
Haojun Liao 已提交
1388 1389 1390
      if (init) {
        tRowMerge(&merge, &fRow);
      } else {
1391 1392 1393 1394 1395
        init = true;
        tRowMergerInit(&merge, &fRow, pReader->pSchema);
      }
      doMergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pReader, &merge);
    }
1396 1397 1398 1399 1400 1401 1402 1403 1404 1405
  }

  tRowMergerGetRow(&merge, &pTSRow);
  doAppendRowFromTSRow(pReader->pResBlock, pReader, pTSRow, pBlockScanInfo->uid);

  taosMemoryFree(pTSRow);
  tRowMergerClear(&merge);
  return TSDB_CODE_SUCCESS;
}

1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432
static int32_t doMergeFileBlockAndLastBlock(SLastBlockReader* pLastBlockReader, STsdbReader* pReader,
                                            STableBlockScanInfo* pBlockScanInfo, SBlockData* pBlockData,
                                            bool mergeBlockData) {
  SBlockData* pLastBlockData = &pLastBlockReader->lastBlockData;
  int64_t     tsLastBlock = getCurrentKeyInLastBlock(pLastBlockReader);

  STSRow*    pTSRow = NULL;
  SRowMerger merge = {0};

  TSDBROW fRow = tsdbRowFromBlockData(pLastBlockData, *pLastBlockReader->rowIndex);

  tRowMergerInit(&merge, &fRow, pReader->pSchema);
  doMergeRowsInLastBlock(pLastBlockReader, pBlockScanInfo, tsLastBlock, &merge);

  // merge with block data if ts == key
  if (mergeBlockData) {
    doMergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pReader, &merge);
  }

  tRowMergerGetRow(&merge, &pTSRow);
  doAppendRowFromTSRow(pReader->pResBlock, pReader, pTSRow, pBlockScanInfo->uid);

  taosMemoryFree(pTSRow);
  tRowMergerClear(&merge);
  return TSDB_CODE_SUCCESS;
}

1433 1434
static int32_t mergeFileBlockAndLastBlock(STsdbReader* pReader, SLastBlockReader* pLastBlockReader, int64_t key,
                                          STableBlockScanInfo* pBlockScanInfo, SBlockData* pBlockData) {
1435 1436
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;

1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453
  if (pBlockData->nRow > 0) {
    // no last block available, only data block exists
    if (pLastBlockReader->lastBlockData.nRow == 0 || (!hasDataInLastBlock(pLastBlockReader))) {
      return mergeRowsInFileBlocks(pBlockData, pBlockScanInfo, key, pReader);
    }

    // row in last file block
    TSDBROW fRow = tsdbRowFromBlockData(pBlockData, pDumpInfo->rowIndex);
    int64_t ts = getCurrentKeyInLastBlock(pLastBlockReader);
    ASSERT(ts >= key);

    if (ASCENDING_TRAVERSE(pReader->order)) {
      if (key < ts) { // imem, mem are all empty, file blocks (data blocks and last block) exist
        return mergeRowsInFileBlocks(pBlockData, pBlockScanInfo, key, pReader);
      } else if (key == ts) {
        STSRow*    pTSRow = NULL;
        SRowMerger merge = {0};
1454

1455 1456
        tRowMergerInit(&merge, &fRow, pReader->pSchema);
        doMergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pReader, &merge);
1457
        doMergeRowsInLastBlock(pLastBlockReader, pBlockScanInfo, ts, &merge);
1458

1459 1460
        tRowMergerGetRow(&merge, &pTSRow);
        doAppendRowFromTSRow(pReader->pResBlock, pReader, pTSRow, pBlockScanInfo->uid);
1461

1462 1463
        taosMemoryFree(pTSRow);
        tRowMergerClear(&merge);
1464 1465
        return TSDB_CODE_SUCCESS;
      } else {
1466 1467
        ASSERT(0);
        return TSDB_CODE_SUCCESS;
1468
      }
1469
    } else {  // desc order
1470
      return doMergeFileBlockAndLastBlock(pLastBlockReader, pReader, pBlockScanInfo, pBlockData, true);
1471
    }
1472
  } else {  // only last block exists
1473
    return doMergeFileBlockAndLastBlock(pLastBlockReader, pReader, pBlockScanInfo, NULL, false);
H
Haojun Liao 已提交
1474
  }
1475 1476
}

1477 1478
static int32_t doMergeMultiLevelRows(STsdbReader* pReader, STableBlockScanInfo* pBlockScanInfo, SBlockData* pBlockData,
                                     SLastBlockReader* pLastBlockReader) {
1479 1480 1481 1482 1483 1484
  SRowMerger merge = {0};
  STSRow*    pTSRow = NULL;

  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;
  SArray*             pDelList = pBlockScanInfo->delSkyline;

1485 1486
  TSDBROW* pRow = getValidMemRow(&pBlockScanInfo->iter, pDelList, pReader);
  TSDBROW* piRow = getValidMemRow(&pBlockScanInfo->iiter, pDelList, pReader);
1487 1488 1489
  ASSERT(pRow != NULL && piRow != NULL);

  SBlockData* pLastBlockData = &pLastBlockReader->lastBlockData;
1490 1491 1492 1493
  int64_t tsLast = INT64_MIN;
  if (hasDataInLastBlock(pLastBlockReader)) {
    tsLast = getCurrentKeyInLastBlock(pLastBlockReader);
  }
1494 1495 1496 1497 1498 1499

  int64_t key = pBlockData->aTSKEY[pDumpInfo->rowIndex];

  TSDBKEY k = TSDBROW_KEY(pRow);
  TSDBKEY ik = TSDBROW_KEY(piRow);

1500
  int64_t minKey = 0;
1501 1502 1503 1504 1505
  if (ASCENDING_TRAVERSE(pReader->order)) {
    minKey = INT64_MAX;  // let's find the minimum
    if (minKey > k.ts) {
      minKey = k.ts;
    }
1506

1507 1508 1509
    if (minKey > ik.ts) {
      minKey = ik.ts;
    }
1510

1511 1512 1513
    if (minKey > key && pBlockData->nRow > 0) {
      minKey = key;
    }
1514

1515
    if (minKey > tsLast && hasDataInLastBlock(pLastBlockReader)) {
1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531
      minKey = tsLast;
    }
  } else {
    minKey = INT64_MIN; // let find the maximum ts value
    if (minKey < k.ts) {
      minKey = k.ts;
    }

    if (minKey < ik.ts) {
      minKey = ik.ts;
    }

    if (minKey < key && pBlockData->nRow > 0) {
      minKey = key;
    }

1532
    if (minKey < tsLast && hasDataInLastBlock(pLastBlockReader)) {
1533 1534
      minKey = tsLast;
    }
1535 1536 1537 1538
  }

  bool init = false;

1539 1540 1541 1542
  // ASC: file block -----> last block -----> imem -----> mem
  // DESC: mem -----> imem -----> last block -----> file block
  if (ASCENDING_TRAVERSE(pReader->order)) {
    if (minKey == key) {
1543
      init = true;
1544 1545 1546
      TSDBROW fRow = tsdbRowFromBlockData(pBlockData, pDumpInfo->rowIndex);
      tRowMergerInit(&merge, &fRow, pReader->pSchema);
      doMergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pReader, &merge);
1547 1548
    }

1549
    if (minKey == tsLast) {
H
Haojun Liao 已提交
1550 1551 1552 1553
      TSDBROW fRow1 = tsdbRowFromBlockData(pLastBlockData, *pLastBlockReader->rowIndex);
      if (init) {
        tRowMerge(&merge, &fRow1);
      } else {
1554 1555 1556
        init = true;
        tRowMergerInit(&merge, &fRow1, pReader->pSchema);
      }
H
Haojun Liao 已提交
1557
      doMergeRowsInLastBlock(pLastBlockReader, pBlockScanInfo, tsLast, &merge);
1558 1559 1560
    }

    if (minKey == ik.ts) {
H
Haojun Liao 已提交
1561 1562 1563
      if (init) {
        tRowMerge(&merge, piRow);
      } else {
1564 1565 1566 1567 1568
        init = true;
        STSchema* pSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(piRow), pReader, pBlockScanInfo->uid);
        tRowMergerInit(&merge, piRow, pSchema);
      }
      doMergeRowsInBuf(&pBlockScanInfo->iiter, pBlockScanInfo->uid, ik.ts, pBlockScanInfo->delSkyline, &merge, pReader);
1569 1570
    }

1571
    if (minKey == k.ts) {
H
Haojun Liao 已提交
1572 1573 1574
      if (init) {
        tRowMerge(&merge, pRow);
      } else {
1575 1576 1577 1578 1579 1580 1581 1582
        STSchema* pSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(pRow), pReader, pBlockScanInfo->uid);
        tRowMergerInit(&merge, pRow, pSchema);
      }
      doMergeRowsInBuf(&pBlockScanInfo->iter, pBlockScanInfo->uid, k.ts, pBlockScanInfo->delSkyline, &merge, pReader);
    }
  } else {
    if (minKey == k.ts) {
      init = true;
1583 1584
      STSchema* pSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(pRow), pReader, pBlockScanInfo->uid);
      tRowMergerInit(&merge, pRow, pSchema);
1585 1586 1587 1588
      doMergeRowsInBuf(&pBlockScanInfo->iter, pBlockScanInfo->uid, k.ts, pBlockScanInfo->delSkyline, &merge, pReader);
    }

    if (minKey == ik.ts) {
H
Haojun Liao 已提交
1589 1590 1591
      if (init) {
        tRowMerge(&merge, piRow);
      } else {
1592 1593 1594 1595 1596 1597 1598 1599
        init = true;
        STSchema* pSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(piRow), pReader, pBlockScanInfo->uid);
        tRowMergerInit(&merge, piRow, pSchema);
      }
      doMergeRowsInBuf(&pBlockScanInfo->iiter, pBlockScanInfo->uid, ik.ts, pBlockScanInfo->delSkyline, &merge, pReader);
    }

    if (minKey == tsLast) {
H
Haojun Liao 已提交
1600 1601 1602 1603
      TSDBROW fRow1 = tsdbRowFromBlockData(pLastBlockData, *pLastBlockReader->rowIndex);
      if (init) {
        tRowMerge(&merge, &fRow1);
      } else {
1604 1605 1606
        init = true;
        tRowMergerInit(&merge, &fRow1, pReader->pSchema);
      }
H
Haojun Liao 已提交
1607
      doMergeRowsInLastBlock(pLastBlockReader, pBlockScanInfo, tsLast, &merge);
1608 1609 1610
    }

    if (minKey == key) {
H
Haojun Liao 已提交
1611
      TSDBROW fRow = tsdbRowFromBlockData(pBlockData, pDumpInfo->rowIndex);
1612 1613
      if (!init) {
        tRowMergerInit(&merge, &fRow, pReader->pSchema);
H
Haojun Liao 已提交
1614 1615
      } else {
        tRowMerge(&merge, &fRow);
1616 1617
      }
      doMergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pReader, &merge);
1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628
    }
  }

  tRowMergerGetRow(&merge, &pTSRow);
  doAppendRowFromTSRow(pReader->pResBlock, pReader, pTSRow, pBlockScanInfo->uid);

  taosMemoryFree(pTSRow);
  tRowMergerClear(&merge);
  return TSDB_CODE_SUCCESS;
}

1629
#if 0
1630
static int32_t doMergeThreeLevelRows(STsdbReader* pReader, STableBlockScanInfo* pBlockScanInfo, SBlockData* pBlockData) {
1631 1632 1633
  SRowMerger merge = {0};
  STSRow*    pTSRow = NULL;

1634
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;
dengyihao's avatar
dengyihao 已提交
1635
  SArray*             pDelList = pBlockScanInfo->delSkyline;
1636

1637 1638
  TSDBROW* pRow = getValidMemRow(&pBlockScanInfo->iter, pDelList, pReader);
  TSDBROW* piRow = getValidMemRow(&pBlockScanInfo->iiter, pDelList, pReader);
1639
  ASSERT(pRow != NULL && piRow != NULL);
H
Haojun Liao 已提交
1640

1641
  int64_t key = pBlockData->aTSKEY[pDumpInfo->rowIndex];
1642
  bool    freeTSRow = false;
H
Haojun Liao 已提交
1643

1644
  uint64_t uid = pBlockScanInfo->uid;
H
Haojun Liao 已提交
1645

1646 1647 1648
  TSDBKEY k = TSDBROW_KEY(pRow);
  TSDBKEY ik = TSDBROW_KEY(piRow);
  if (ASCENDING_TRAVERSE(pReader->order)) {
1649 1650
    // [1&2] key <= [k.ts && ik.ts]
    if (key <= k.ts && key <= ik.ts) {
1651 1652 1653
      TSDBROW fRow = tsdbRowFromBlockData(pBlockData, pDumpInfo->rowIndex);
      tRowMergerInit(&merge, &fRow, pReader->pSchema);

1654
      doMergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pReader, &merge);
H
Haojun Liao 已提交
1655

1656 1657
      if (ik.ts == key) {
        tRowMerge(&merge, piRow);
1658
        doMergeRowsInBuf(&pBlockScanInfo->iiter, uid, key, pBlockScanInfo->delSkyline, &merge, pReader);
1659 1660
      }

1661 1662
      if (k.ts == key) {
        tRowMerge(&merge, pRow);
1663
        doMergeRowsInBuf(&pBlockScanInfo->iter, uid, key, pBlockScanInfo->delSkyline, &merge, pReader);
1664 1665 1666
      }

      tRowMergerGetRow(&merge, &pTSRow);
H
Haojun Liao 已提交
1667
      doAppendRowFromTSRow(pReader->pResBlock, pReader, pTSRow, uid);
1668
      return TSDB_CODE_SUCCESS;
1669
    } else {  // key > ik.ts || key > k.ts
1670 1671
      ASSERT(key != ik.ts);

1672
      // [3] ik.ts < key <= k.ts
1673
      // [4] ik.ts < k.ts <= key
1674
      if (ik.ts < k.ts) {
1675
        doMergeMemTableMultiRows(piRow, uid, &pBlockScanInfo->iiter, pDelList, &pTSRow, pReader, &freeTSRow);
H
Haojun Liao 已提交
1676
        doAppendRowFromTSRow(pReader->pResBlock, pReader, pTSRow, uid);
1677 1678 1679
        if (freeTSRow) {
          taosMemoryFree(pTSRow);
        }
1680 1681 1682
        return TSDB_CODE_SUCCESS;
      }

1683 1684
      // [5] k.ts < key   <= ik.ts
      // [6] k.ts < ik.ts <= key
1685
      if (k.ts < ik.ts) {
1686
        doMergeMemTableMultiRows(pRow, uid, &pBlockScanInfo->iter, pDelList, &pTSRow, pReader, &freeTSRow);
H
Haojun Liao 已提交
1687
        doAppendRowFromTSRow(pReader->pResBlock, pReader, pTSRow, uid);
1688 1689 1690
        if (freeTSRow) {
          taosMemoryFree(pTSRow);
        }
1691 1692 1693
        return TSDB_CODE_SUCCESS;
      }

1694
      // [7] k.ts == ik.ts < key
1695
      if (k.ts == ik.ts) {
1696 1697
        ASSERT(key > ik.ts && key > k.ts);

1698
        doMergeMemIMemRows(pRow, piRow, pBlockScanInfo, pReader, &pTSRow);
H
Haojun Liao 已提交
1699
        doAppendRowFromTSRow(pReader->pResBlock, pReader, pTSRow, uid);
1700
        taosMemoryFree(pTSRow);
1701 1702 1703
        return TSDB_CODE_SUCCESS;
      }
    }
1704 1705 1706
  } else {  // descending order scan
    // [1/2] k.ts >= ik.ts && k.ts >= key
    if (k.ts >= ik.ts && k.ts >= key) {
H
Haojun Liao 已提交
1707
      STSchema* pSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(pRow), pReader, pBlockScanInfo->uid);
1708

H
Haojun Liao 已提交
1709
      tRowMergerInit(&merge, pRow, pSchema);
1710
      doMergeRowsInBuf(&pBlockScanInfo->iter, uid, key, pBlockScanInfo->delSkyline, &merge, pReader);
1711 1712 1713

      if (ik.ts == k.ts) {
        tRowMerge(&merge, piRow);
1714
        doMergeRowsInBuf(&pBlockScanInfo->iiter, uid, key, pBlockScanInfo->delSkyline, &merge, pReader);
1715 1716 1717 1718 1719 1720 1721 1722 1723
      }

      if (k.ts == key) {
        TSDBROW fRow = tsdbRowFromBlockData(pBlockData, pDumpInfo->rowIndex);
        tRowMerge(&merge, &fRow);
        doMergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pReader, &merge);
      }

      tRowMergerGetRow(&merge, &pTSRow);
H
Haojun Liao 已提交
1724
      doAppendRowFromTSRow(pReader->pResBlock, pReader, pTSRow, uid);
1725 1726
      return TSDB_CODE_SUCCESS;
    } else {
1727
      ASSERT(ik.ts != k.ts);  // this case has been included in the previous if branch
1728 1729 1730 1731

      // [3] ik.ts > k.ts >= Key
      // [4] ik.ts > key >= k.ts
      if (ik.ts > key) {
1732
        doMergeMemTableMultiRows(piRow, uid, &pBlockScanInfo->iiter, pDelList, &pTSRow, pReader, &freeTSRow);
H
Haojun Liao 已提交
1733
        doAppendRowFromTSRow(pReader->pResBlock, pReader, pTSRow, uid);
1734 1735 1736
        if (freeTSRow) {
          taosMemoryFree(pTSRow);
        }
1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747
        return TSDB_CODE_SUCCESS;
      }

      // [5] key > ik.ts > k.ts
      // [6] key > k.ts > ik.ts
      if (key > ik.ts) {
        TSDBROW fRow = tsdbRowFromBlockData(pBlockData, pDumpInfo->rowIndex);
        tRowMergerInit(&merge, &fRow, pReader->pSchema);

        doMergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pReader, &merge);
        tRowMergerGetRow(&merge, &pTSRow);
H
Haojun Liao 已提交
1748
        doAppendRowFromTSRow(pReader->pResBlock, pReader, pTSRow, uid);
1749
        taosMemoryFree(pTSRow);
1750 1751 1752 1753 1754
        return TSDB_CODE_SUCCESS;
      }

      //[7] key = ik.ts > k.ts
      if (key == ik.ts) {
1755
        doMergeMemTableMultiRows(piRow, uid, &pBlockScanInfo->iiter, pDelList, &pTSRow, pReader, &freeTSRow);
1756 1757 1758 1759 1760

        TSDBROW fRow = tsdbRowFromBlockData(pBlockData, pDumpInfo->rowIndex);
        tRowMerge(&merge, &fRow);
        doMergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pReader, &merge);
        tRowMergerGetRow(&merge, &pTSRow);
H
Haojun Liao 已提交
1761
        doAppendRowFromTSRow(pReader->pResBlock, pReader, pTSRow, uid);
1762 1763

        taosMemoryFree(pTSRow);
1764 1765 1766 1767 1768 1769
        return TSDB_CODE_SUCCESS;
      }
    }
  }

  ASSERT(0);
S
Shengliang Guan 已提交
1770
  return -1;
1771
}
1772
#endif
1773

dengyihao's avatar
dengyihao 已提交
1774 1775
static bool isValidFileBlockRow(SBlockData* pBlockData, SFileBlockDumpInfo* pDumpInfo,
                                STableBlockScanInfo* pBlockScanInfo, STsdbReader* pReader) {
1776 1777 1778 1779 1780 1781 1782 1783
  // it is an multi-table data block
  if (pBlockData->aUid != NULL) {
    uint64_t uid = pBlockData->aUid[pDumpInfo->rowIndex];
    if (uid != pBlockScanInfo->uid) {  // move to next row
      return false;
    }
  }

1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794
  // check for version and time range
  int64_t ver = pBlockData->aVersion[pDumpInfo->rowIndex];
  if (ver > pReader->verRange.maxVer || ver < pReader->verRange.minVer) {
    return false;
  }

  int64_t ts = pBlockData->aTSKEY[pDumpInfo->rowIndex];
  if (ts > pReader->window.ekey || ts < pReader->window.skey) {
    return false;
  }

1795
  TSDBKEY k = {.ts = ts, .version = ver};
1796
  if (hasBeenDropped(pBlockScanInfo->delSkyline, &pBlockScanInfo->fileDelIndex, &k, pReader->order)) {
1797 1798 1799
    return false;
  }

1800 1801 1802
  return true;
}

1803
static bool outOfTimeWindow(int64_t ts, STimeWindow* pWindow) { return (ts > pWindow->ekey) || (ts < pWindow->skey); }
1804

1805
static void initLastBlockReader(SLastBlockReader* pLastBlockReader, uint64_t uid, int16_t* startPos) {
1806 1807
  pLastBlockReader->uid = uid;
  pLastBlockReader->rowIndex = startPos;
1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819

  if (*startPos == -1) {
    if (ASCENDING_TRAVERSE(pLastBlockReader->order)) {
      // do nothing
    } else {
      *startPos = pLastBlockReader->lastBlockData.nRow;
    }
  }
}

static void setAllRowsChecked(SLastBlockReader *pLastBlockReader) {
  *pLastBlockReader->rowIndex = ALL_ROWS_CHECKED_INDEX;
1820 1821
}

H
Haojun Liao 已提交
1822
static bool nextRowInLastBlock(SLastBlockReader *pLastBlockReader, STableBlockScanInfo* pBlockScanInfo) {
1823 1824
  bool asc = ASCENDING_TRAVERSE(pLastBlockReader->order);
  int32_t step = (asc) ? 1 : -1;
1825
  if (*pLastBlockReader->rowIndex == ALL_ROWS_CHECKED_INDEX) {
1826 1827 1828
    return false;
  }

1829
  *(pLastBlockReader->rowIndex) += step;
1830 1831

  SBlockData* pBlockData = &pLastBlockReader->lastBlockData;
1832
  for(int32_t i = *(pLastBlockReader->rowIndex); i < pBlockData->nRow && i >= 0; i += step) {
1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846
    if (pBlockData->aUid != NULL) {
      if (asc) {
        if (pBlockData->aUid[i] < pLastBlockReader->uid) {
          continue;
        } else if (pBlockData->aUid[i] > pLastBlockReader->uid) {
          break;
        }
      } else {
        if (pBlockData->aUid[i] > pLastBlockReader->uid) {
          continue;
        } else if (pBlockData->aUid[i] < pLastBlockReader->uid) {
          break;
        }
      }
1847 1848
    }

H
Haojun Liao 已提交
1849 1850
    int64_t ts = pBlockData->aTSKEY[i];
    if (ts < pLastBlockReader->window.skey) {
1851 1852 1853
      continue;
    }

H
Haojun Liao 已提交
1854 1855
    int64_t ver = pBlockData->aVersion[i];
    if (ver < pLastBlockReader->verRange.minVer) {
1856 1857 1858
      continue;
    }

H
Haojun Liao 已提交
1859
    // no data any more, todo opt handle desc case
H
Haojun Liao 已提交
1860
    if (ts > pLastBlockReader->window.ekey) {
H
Haojun Liao 已提交
1861
      continue;
1862 1863
    }

H
Haojun Liao 已提交
1864
    // todo opt handle desc case
H
Haojun Liao 已提交
1865 1866 1867 1868 1869
    if (ver > pLastBlockReader->verRange.maxVer) {
      continue;
    }

    TSDBKEY k = {.ts = ts, .version = ver};
1870
    if (hasBeenDropped(pBlockScanInfo->delSkyline, &pBlockScanInfo->lastBlockDelIndex, &k, pLastBlockReader->order)) {
H
Haojun Liao 已提交
1871
      continue;
1872 1873
    }

1874
    *(pLastBlockReader->rowIndex) = i;
1875 1876 1877
    return true;
  }

1878
  // set all data is consumed in last block
1879
  setAllRowsChecked(pLastBlockReader);
1880 1881 1882 1883 1884
  return false;
}

static int64_t getCurrentKeyInLastBlock(SLastBlockReader* pLastBlockReader) {
  SBlockData* pBlockData = &pLastBlockReader->lastBlockData;
1885
  return pBlockData->aTSKEY[*pLastBlockReader->rowIndex];
1886 1887 1888
}

static bool hasDataInLastBlock(SLastBlockReader* pLastBlockReader) {
1889
  if (*pLastBlockReader->rowIndex == ALL_ROWS_CHECKED_INDEX) {
1890 1891
    return false;
  }
1892

1893
  ASSERT(pLastBlockReader->lastBlockData.nRow > 0);
1894 1895 1896
  return true;
}

1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916
int32_t mergeRowsInFileBlocks(SBlockData* pBlockData, STableBlockScanInfo* pBlockScanInfo, int64_t key, STsdbReader* pReader) {
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;

  TSDBROW fRow = tsdbRowFromBlockData(pBlockData, pDumpInfo->rowIndex);

  if (tryCopyDistinctRowFromFileBlock(pReader, pBlockData, key, pDumpInfo)) {
    return TSDB_CODE_SUCCESS;
  } else {
    STSRow*    pTSRow = NULL;
    SRowMerger merge = {0};

    tRowMergerInit(&merge, &fRow, pReader->pSchema);
    doMergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pReader, &merge);
    tRowMergerGetRow(&merge, &pTSRow);
    doAppendRowFromTSRow(pReader->pResBlock, pReader, pTSRow, pBlockScanInfo->uid);

    taosMemoryFree(pTSRow);
    tRowMergerClear(&merge);
    return TSDB_CODE_SUCCESS;
  }
1917

1918 1919 1920
  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
1921 1922
static int32_t buildComposedDataBlockImpl(STsdbReader* pReader, STableBlockScanInfo* pBlockScanInfo,
                                          SBlockData* pBlockData, SLastBlockReader* pLastBlockReader) {
1923 1924
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;

1925
  int64_t key = (pBlockData->nRow > 0)? pBlockData->aTSKEY[pDumpInfo->rowIndex]:INT64_MIN;
1926 1927
  TSDBROW* pRow = getValidMemRow(&pBlockScanInfo->iter, pBlockScanInfo->delSkyline, pReader);
  TSDBROW* piRow = getValidMemRow(&pBlockScanInfo->iiter, pBlockScanInfo->delSkyline, pReader);
1928

1929
  if (pBlockScanInfo->iter.hasVal && pBlockScanInfo->iiter.hasVal) {
1930
    return doMergeMultiLevelRows(pReader, pBlockScanInfo, pBlockData, pLastBlockReader);
1931
  } else {
1932
    // imem + file + last block
1933
    if (pBlockScanInfo->iiter.hasVal) {
1934
      return doMergeBufAndFileRows(pReader, pBlockScanInfo, piRow, &pBlockScanInfo->iiter, key, pLastBlockReader);
1935 1936
    }

1937
    // mem + file + last block
1938
    if (pBlockScanInfo->iter.hasVal) {
1939
      return doMergeBufAndFileRows(pReader, pBlockScanInfo, pRow, &pBlockScanInfo->iter, key, pLastBlockReader);
H
Haojun Liao 已提交
1940
    }
1941

1942 1943
    // files data blocks + last block
    return mergeFileBlockAndLastBlock(pReader, pLastBlockReader, key, pBlockScanInfo, pBlockData);
1944 1945 1946
  }
}

1947
static int32_t buildComposedDataBlock(STsdbReader* pReader) {
1948 1949
  SSDataBlock* pResBlock = pReader->pResBlock;

1950
  SFileDataBlockInfo*  pBlockInfo = getCurrentBlockInfo(&pReader->status.blockIter);
1951 1952 1953 1954 1955 1956 1957 1958

  STableBlockScanInfo* pBlockScanInfo = NULL;
  if (pBlockInfo != NULL) {
    pBlockScanInfo = taosHashGet(pReader->status.pTableMap, &pBlockInfo->uid, sizeof(pBlockInfo->uid));
  } else {
    pBlockScanInfo = pReader->status.pTableIter;
  }

H
Haojun Liao 已提交
1959
  SLastBlockReader*   pLastBlockReader = pReader->status.fileIter.pLastBlockReader;
1960
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;
1961 1962
  SBlockData*         pBlockData = &pReader->status.fileBlockData;
  int32_t             step = ASCENDING_TRAVERSE(pReader->order) ? 1 : -1;
1963

1964 1965
  int64_t st = taosGetTimestampUs();

1966
  while (1) {
1967
    // todo check the validate of row in file block
1968
    bool hasBlockData = false;
1969
    {
H
Haojun Liao 已提交
1970
      while (pBlockData->nRow > 0) {  // find the first qualified row in data block
1971 1972 1973 1974 1975
        if (isValidFileBlockRow(pBlockData, pDumpInfo, pBlockScanInfo, pReader)) {
          hasBlockData = true;
          break;
        }

1976 1977
        pDumpInfo->rowIndex += step;

1978
        SBlock* pBlock = getCurrentBlock(&pReader->status.blockIter);
1979
        if (pDumpInfo->rowIndex >= pBlock->nRow || pDumpInfo->rowIndex < 0) {
1980
          setBlockAllDumped(pDumpInfo, pBlock->maxKey.ts, pReader->order);
1981 1982 1983
          break;
        }
      }
1984
    }
1985

1986
    bool hasBlockLData = hasDataInLastBlock(pLastBlockReader);
1987

1988 1989 1990
    // no data in last block and block, no need to proceed.
    if ((hasBlockData == false) && (hasBlockLData == false)) {
      break;
1991 1992
    }

1993
    buildComposedDataBlockImpl(pReader, pBlockScanInfo, pBlockData, pLastBlockReader);
1994

1995
    // currently loaded file data block is consumed
1996
    if ((pBlockData->nRow > 0) && (pDumpInfo->rowIndex >= pBlockData->nRow || pDumpInfo->rowIndex < 0)) {
1997
      SBlock* pBlock = getCurrentBlock(&pReader->status.blockIter);
1998
      setBlockAllDumped(pDumpInfo, pBlock->maxKey.ts, pReader->order);
1999 2000 2001 2002 2003
      break;
    }

    if (pResBlock->info.rows >= pReader->capacity) {
      break;
2004 2005 2006 2007
    }
  }

  pResBlock->info.uid = pBlockScanInfo->uid;
2008 2009
  blockDataUpdateTsWindow(pResBlock, 0);

2010
  setComposedBlockFlag(pReader, true);
2011
  int64_t et = taosGetTimestampUs();
2012

2013 2014 2015 2016 2017 2018
  if (pResBlock->info.rows > 0) {
    tsdbDebug("%p uid:%" PRIu64 ", composed data block created, brange:%" PRIu64 "-%" PRIu64
              " rows:%d, elapsed time:%.2f ms %s",
              pReader, pBlockScanInfo->uid, pResBlock->info.window.skey, pResBlock->info.window.ekey,
              pResBlock->info.rows, (et - st) / 1000.0, pReader->idStr);
  }
2019

2020 2021 2022 2023 2024
  return TSDB_CODE_SUCCESS;
}

void setComposedBlockFlag(STsdbReader* pReader, bool composed) { pReader->status.composedDataBlock = composed; }

2025
static int32_t initMemDataIterator(STableBlockScanInfo* pBlockScanInfo, STsdbReader* pReader) {
2026 2027 2028 2029
  if (pBlockScanInfo->iterInit) {
    return TSDB_CODE_SUCCESS;
  }

2030
  int32_t code = TSDB_CODE_SUCCESS;
2031 2032 2033 2034 2035 2036 2037 2038 2039

  TSDBKEY startKey = {0};
  if (ASCENDING_TRAVERSE(pReader->order)) {
    startKey = (TSDBKEY){.ts = pReader->window.skey, .version = pReader->verRange.minVer};
  } else {
    startKey = (TSDBKEY){.ts = pReader->window.ekey, .version = pReader->verRange.maxVer};
  }

  int32_t backward = (!ASCENDING_TRAVERSE(pReader->order));
2040 2041

  STbData* d = NULL;
H
Hongze Cheng 已提交
2042
  if (pReader->pReadSnap->pMem != NULL) {
H
Hongze Cheng 已提交
2043
    d = tsdbGetTbDataFromMemTable(pReader->pReadSnap->pMem, pReader->suid, pBlockScanInfo->uid);
2044
    if (d != NULL) {
2045
      code = tsdbTbDataIterCreate(d, &startKey, backward, &pBlockScanInfo->iter.iter);
2046
      if (code == TSDB_CODE_SUCCESS) {
2047
        pBlockScanInfo->iter.hasVal = (tsdbTbDataIterGet(pBlockScanInfo->iter.iter) != NULL);
2048

H
Haojun Liao 已提交
2049
        tsdbDebug("%p uid:%" PRId64 ", check data in mem from skey:%" PRId64 ", order:%d, ts range in buf:%" PRId64
2050 2051
                  "-%" PRId64 " %s",
                  pReader, pBlockScanInfo->uid, startKey.ts, pReader->order, d->minKey, d->maxKey, pReader->idStr);
2052
      } else {
2053 2054
        tsdbError("%p uid:%" PRId64 ", failed to create iterator for imem, code:%s, %s", pReader, pBlockScanInfo->uid,
                  tstrerror(code), pReader->idStr);
2055
        return code;
2056 2057
      }
    }
H
Haojun Liao 已提交
2058
  } else {
2059
    tsdbDebug("%p uid:%" PRId64 ", no data in mem, %s", pReader, pBlockScanInfo->uid, pReader->idStr);
H
Haojun Liao 已提交
2060 2061
  }

2062
  STbData* di = NULL;
H
Hongze Cheng 已提交
2063
  if (pReader->pReadSnap->pIMem != NULL) {
H
Hongze Cheng 已提交
2064
    di = tsdbGetTbDataFromMemTable(pReader->pReadSnap->pIMem, pReader->suid, pBlockScanInfo->uid);
2065
    if (di != NULL) {
2066
      code = tsdbTbDataIterCreate(di, &startKey, backward, &pBlockScanInfo->iiter.iter);
2067
      if (code == TSDB_CODE_SUCCESS) {
2068
        pBlockScanInfo->iiter.hasVal = (tsdbTbDataIterGet(pBlockScanInfo->iiter.iter) != NULL);
2069

H
Haojun Liao 已提交
2070
        tsdbDebug("%p uid:%" PRId64 ", check data in imem from skey:%" PRId64 ", order:%d, ts range in buf:%" PRId64
2071
                  "-%" PRId64 " %s",
2072
                  pReader, pBlockScanInfo->uid, startKey.ts, pReader->order, di->minKey, di->maxKey, pReader->idStr);
2073
      } else {
2074 2075
        tsdbError("%p uid:%" PRId64 ", failed to create iterator for mem, code:%s, %s", pReader, pBlockScanInfo->uid,
                  tstrerror(code), pReader->idStr);
2076
        return code;
2077 2078
      }
    }
H
Haojun Liao 已提交
2079 2080
  } else {
    tsdbDebug("%p uid:%" PRId64 ", no data in imem, %s", pReader, pBlockScanInfo->uid, pReader->idStr);
2081 2082
  }

2083 2084
  initDelSkylineIterator(pBlockScanInfo, pReader, d, di);

2085
  pBlockScanInfo->iterInit = true;
H
Haojun Liao 已提交
2086 2087 2088
  return TSDB_CODE_SUCCESS;
}

dengyihao's avatar
dengyihao 已提交
2089 2090
int32_t initDelSkylineIterator(STableBlockScanInfo* pBlockScanInfo, STsdbReader* pReader, STbData* pMemTbData,
                               STbData* piMemTbData) {
2091 2092 2093
  if (pBlockScanInfo->delSkyline != NULL) {
    return TSDB_CODE_SUCCESS;
  }
2094

2095 2096 2097
  int32_t code = 0;
  STsdb*  pTsdb = pReader->pTsdb;

2098 2099
  SArray* pDelData = taosArrayInit(4, sizeof(SDelData));

H
Hongze Cheng 已提交
2100
  SDelFile* pDelFile = pReader->pReadSnap->fs.pDelFile;
2101 2102
  if (pDelFile) {
    SDelFReader* pDelFReader = NULL;
H
more  
Hongze Cheng 已提交
2103
    code = tsdbDelFReaderOpen(&pDelFReader, pDelFile, pTsdb);
2104
    if (code != TSDB_CODE_SUCCESS) {
2105 2106 2107 2108 2109
      goto _err;
    }

    SArray* aDelIdx = taosArrayInit(4, sizeof(SDelIdx));
    if (aDelIdx == NULL) {
2110
      tsdbDelFReaderClose(&pDelFReader);
2111 2112 2113
      goto _err;
    }

H
Hongze Cheng 已提交
2114
    code = tsdbReadDelIdx(pDelFReader, aDelIdx);
2115 2116 2117
    if (code != TSDB_CODE_SUCCESS) {
      taosArrayDestroy(aDelIdx);
      tsdbDelFReaderClose(&pDelFReader);
2118 2119
      goto _err;
    }
2120

2121 2122 2123
    SDelIdx  idx = {.suid = pReader->suid, .uid = pBlockScanInfo->uid};
    SDelIdx* pIdx = taosArraySearch(aDelIdx, &idx, tCmprDelIdx, TD_EQ);

H
Haojun Liao 已提交
2124
    if (pIdx != NULL) {
H
Hongze Cheng 已提交
2125
      code = tsdbReadDelData(pDelFReader, pIdx, pDelData);
2126 2127 2128 2129 2130 2131 2132
    }

    taosArrayDestroy(aDelIdx);
    tsdbDelFReaderClose(&pDelFReader);

    if (code != TSDB_CODE_SUCCESS) {
      goto _err;
2133
    }
2134
  }
2135

2136 2137 2138 2139 2140 2141 2142
  SDelData* p = NULL;
  if (pMemTbData != NULL) {
    p = pMemTbData->pHead;
    while (p) {
      taosArrayPush(pDelData, p);
      p = p->pNext;
    }
2143 2144
  }

2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158
  if (piMemTbData != NULL) {
    p = piMemTbData->pHead;
    while (p) {
      taosArrayPush(pDelData, p);
      p = p->pNext;
    }
  }

  if (taosArrayGetSize(pDelData) > 0) {
    pBlockScanInfo->delSkyline = taosArrayInit(4, sizeof(TSDBKEY));
    code = tsdbBuildDeleteSkyline(pDelData, 0, (int32_t)(taosArrayGetSize(pDelData) - 1), pBlockScanInfo->delSkyline);
  }

  taosArrayDestroy(pDelData);
dengyihao's avatar
dengyihao 已提交
2159 2160
  pBlockScanInfo->iter.index =
      ASCENDING_TRAVERSE(pReader->order) ? 0 : taosArrayGetSize(pBlockScanInfo->delSkyline) - 1;
2161 2162
  pBlockScanInfo->iiter.index = pBlockScanInfo->iter.index;
  pBlockScanInfo->fileDelIndex = pBlockScanInfo->iter.index;
2163
  pBlockScanInfo->lastBlockDelIndex = pBlockScanInfo->iter.index;
2164 2165
  return code;

2166 2167 2168
_err:
  taosArrayDestroy(pDelData);
  return code;
2169 2170
}

2171
static TSDBKEY getCurrentKeyInBuf(STableBlockScanInfo* pScanInfo, STsdbReader* pReader) {
2172 2173
  TSDBKEY key = {.ts = TSKEY_INITIAL_VAL};

2174
  initMemDataIterator(pScanInfo, pReader);
2175
  TSDBROW* pRow = getValidMemRow(&pScanInfo->iter, pScanInfo->delSkyline, pReader);
2176
  if (pRow != NULL) {
2177 2178 2179
    key = TSDBROW_KEY(pRow);
  }

2180
  pRow = getValidMemRow(&pScanInfo->iiter, pScanInfo->delSkyline, pReader);
2181
  if (pRow != NULL) {
2182 2183 2184 2185 2186 2187 2188 2189 2190
    TSDBKEY k = TSDBROW_KEY(pRow);
    if (key.ts > k.ts) {
      key = k;
    }
  }

  return key;
}

2191
static int32_t moveToNextFile(STsdbReader* pReader, SBlockNumber* pBlockNum) {
H
Haojun Liao 已提交
2192
  SReaderStatus* pStatus = &pReader->status;
2193 2194
  pBlockNum->numOfBlocks = 0;
  pBlockNum->numOfLastBlocks = 0;
2195

2196
  size_t  numOfTables = taosHashGetSize(pReader->status.pTableMap);
2197
  SArray* pIndexList = taosArrayInit(numOfTables, sizeof(SBlockIdx));
2198
  SArray* pLastBlocks = pStatus->fileIter.pLastBlockReader->pBlockL;
2199
  taosArrayClear(pLastBlocks);
H
Haojun Liao 已提交
2200 2201

  while (1) {
2202
    bool hasNext = filesetIteratorNext(&pStatus->fileIter, pReader);
2203
    if (!hasNext) {  // no data files on disk
H
Haojun Liao 已提交
2204 2205 2206
      break;
    }

H
Haojun Liao 已提交
2207
    taosArrayClear(pIndexList);
H
Haojun Liao 已提交
2208 2209
    int32_t code = doLoadBlockIndex(pReader, pReader->pFileReader, pIndexList);
    if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
2210
      taosArrayDestroy(pIndexList);
H
Haojun Liao 已提交
2211 2212 2213
      return code;
    }

2214
    code = tsdbReadBlockL(pReader->pFileReader, pLastBlocks);
2215 2216 2217 2218 2219
    if (code != TSDB_CODE_SUCCESS) {
      taosArrayDestroy(pIndexList);
      return code;
    }

2220 2221 2222 2223
    if (taosArrayGetSize(pIndexList) > 0 || taosArrayGetSize(pLastBlocks) > 0) {
      SArray* pQLastBlock = taosArrayInit(4, sizeof(SBlockL));

      code = doLoadFileBlock(pReader, pIndexList, pLastBlocks, pBlockNum, pQLastBlock);
H
Haojun Liao 已提交
2224
      if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
2225
        taosArrayDestroy(pIndexList);
2226
        taosArrayDestroy(pQLastBlock);
H
Haojun Liao 已提交
2227 2228 2229
        return code;
      }

2230 2231
      if (pBlockNum->numOfBlocks + pBlockNum->numOfLastBlocks > 0) {
        ASSERT(taosArrayGetSize(pQLastBlock) == pBlockNum->numOfLastBlocks);
2232 2233 2234 2235
        taosArrayClear(pLastBlocks);
        taosArrayAddAll(pLastBlocks, pQLastBlock);

        taosArrayDestroy(pQLastBlock);
H
Haojun Liao 已提交
2236 2237
        break;
      }
H
Haojun Liao 已提交
2238 2239

      taosArrayDestroy(pQLastBlock);
H
Haojun Liao 已提交
2240
    }
2241

H
Haojun Liao 已提交
2242 2243 2244
    // no blocks in current file, try next files
  }

H
Haojun Liao 已提交
2245
  taosArrayDestroy(pIndexList);
H
Haojun Liao 已提交
2246 2247 2248
  return TSDB_CODE_SUCCESS;
}

2249
static int32_t doLoadRelatedLastBlock(SLastBlockReader* pLastBlockReader, STableBlockScanInfo *pBlockScanInfo, STsdbReader* pReader) {
2250 2251 2252
  SArray*  pBlocks = pLastBlockReader->pBlockL;
  SBlockL* pBlock = NULL;

2253
  uint64_t uid = pBlockScanInfo->uid;
2254 2255
  int32_t totalLastBlocks = (int32_t)taosArrayGetSize(pBlocks);

2256
  initMemDataIterator(pBlockScanInfo, pReader);
2257

2258 2259 2260
  // find the correct SBlockL. todo binary search
  int32_t index = -1;
  for (int32_t i = 0; i < totalLastBlocks; ++i) {
2261 2262
    SBlockL* p = taosArrayGet(pBlocks, i);
    if (p->minUid <= uid && p->maxUid >= uid) {
2263
      index = i;
2264 2265 2266 2267 2268
      pBlock = p;
      break;
    }
  }

2269 2270
  if (index == -1) {
    pLastBlockReader->currentBlockIndex = index;
H
Haojun Liao 已提交
2271
    tBlockDataReset(&pLastBlockReader->lastBlockData);
2272 2273 2274
    return TSDB_CODE_SUCCESS;
  }

2275 2276 2277 2278 2279
  // the required last datablock has already loaded
  if (index == pLastBlockReader->currentBlockIndex) {
    return TSDB_CODE_SUCCESS;
  }

2280
  int64_t st = taosGetTimestampUs();
H
Haojun Liao 已提交
2281
  int32_t code = tBlockDataInit(&pLastBlockReader->lastBlockData, pReader->suid, pReader->suid ? 0 : uid, pReader->pSchema);
2282
  if (code != TSDB_CODE_SUCCESS) {
2283
    tsdbError("%p init block data failed, code:%s %s", pReader, tstrerror(code), pReader->idStr);
2284 2285 2286 2287
    return code;
  }

  code = tsdbReadLastBlock(pReader->pFileReader, pBlock, &pLastBlockReader->lastBlockData);
2288 2289

  double el = (taosGetTimestampUs() - st) / 1000.0;
2290
  if (code != TSDB_CODE_SUCCESS) {
2291 2292 2293 2294
    tsdbError("%p error occurs in loading last block into buffer, last block index:%d, total:%d code:%s %s", pReader,
              pLastBlockReader->currentBlockIndex, totalLastBlocks, tstrerror(code), pReader->idStr);
  } else {
    tsdbDebug("%p load last block completed, uid:%" PRIu64
2295
              " last block index:%d, total:%d rows:%d, minVer:%d, maxVer:%d, brange:%" PRId64 "-%" PRId64
2296
              " elapsed time:%.2f ms, %s",
2297 2298
              pReader, uid, index, totalLastBlocks, pBlock->nRow, pBlock->minVer, pBlock->maxVer, pBlock->minKey,
              pBlock->maxKey, el, pReader->idStr);
2299 2300
  }

2301
  pLastBlockReader->currentBlockIndex = index;
2302 2303 2304
  pReader->cost.lastBlockLoad += 1;
  pReader->cost.lastBlockLoadTime += el;

2305 2306 2307
  return TSDB_CODE_SUCCESS;
}

2308 2309 2310 2311 2312 2313
static int32_t uidComparFunc(const void* p1, const void* p2) {
  uint64_t pu1 = *(uint64_t*) p1;
  uint64_t pu2 = *(uint64_t*) p2;
  if (pu1 == pu2) {
    return 0;
  } else {
2314
    return (pu1 < pu2)? -1:1;
2315 2316 2317
  }
}

2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331
static void extractOrderedTableUidList(SUidOrderCheckInfo *pOrderCheckInfo, SReaderStatus* pStatus) {
  int32_t index = 0;
  int32_t total = taosHashGetSize(pStatus->pTableMap);

  void* p = taosHashIterate(pStatus->pTableMap, NULL);
  while(p != NULL) {
    STableBlockScanInfo* pScanInfo = p;
    pOrderCheckInfo->tableUidList[index++] = pScanInfo->uid;
    p = taosHashIterate(pStatus->pTableMap, p);
  }

  taosSort(pOrderCheckInfo->tableUidList, total, sizeof(uint64_t), uidComparFunc);
}

2332 2333 2334 2335 2336 2337 2338 2339 2340 2341
static int32_t initOrderCheckInfo(SUidOrderCheckInfo* pOrderCheckInfo, SReaderStatus* pStatus) {
  if (pOrderCheckInfo->tableUidList == NULL) {
    int32_t total = taosHashGetSize(pStatus->pTableMap);

    pOrderCheckInfo->currentIndex = 0;
    pOrderCheckInfo->tableUidList = taosMemoryMalloc(total * sizeof(uint64_t));
    if (pOrderCheckInfo->tableUidList == NULL) {
      return TSDB_CODE_OUT_OF_MEMORY;
    }

2342
    extractOrderedTableUidList(pOrderCheckInfo, pStatus);
2343 2344 2345 2346

    uint64_t uid = pOrderCheckInfo->tableUidList[0];
    pStatus->pTableIter = taosHashGet(pStatus->pTableMap, &uid, sizeof(uid));
  } else {
2347
    if (pStatus->pTableIter == NULL) {  // it is the last block of a new file
2348
//      ASSERT(pOrderCheckInfo->currentIndex == taosHashGetSize(pStatus->pTableMap));
2349 2350

      pOrderCheckInfo->currentIndex = 0;
2351 2352
      uint64_t uid = pOrderCheckInfo->tableUidList[pOrderCheckInfo->currentIndex];
      pStatus->pTableIter = taosHashGet(pStatus->pTableMap, &uid, sizeof(uid));
2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366

      // the tableMap has already updated
      if (pStatus->pTableIter == NULL) {
        void* p = taosMemoryRealloc(pOrderCheckInfo->tableUidList, taosHashGetSize(pStatus->pTableMap)*sizeof(uint64_t));
        if (p == NULL) {
          return TSDB_CODE_OUT_OF_MEMORY;
        }

        pOrderCheckInfo->tableUidList = p;
        extractOrderedTableUidList(pOrderCheckInfo, pStatus);

        uid = pOrderCheckInfo->tableUidList[0];
        pStatus->pTableIter = taosHashGet(pStatus->pTableMap, &uid, sizeof(uid));
      }
2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385
    }
  }

  return TSDB_CODE_SUCCESS;
}

static bool moveToNextTable(SUidOrderCheckInfo *pOrderedCheckInfo, SReaderStatus* pStatus) {
  pOrderedCheckInfo->currentIndex += 1;
  if (pOrderedCheckInfo->currentIndex >= taosHashGetSize(pStatus->pTableMap)) {
    pStatus->pTableIter = NULL;
    return false;
  }

  uint64_t uid = pOrderedCheckInfo->tableUidList[pOrderedCheckInfo->currentIndex];
  pStatus->pTableIter = taosHashGet(pStatus->pTableMap, &uid, sizeof(uid));
  ASSERT(pStatus->pTableIter != NULL);
  return true;
}

2386
static int32_t doLoadLastBlockSequentially(STsdbReader* pReader) {
2387
  SReaderStatus* pStatus = &pReader->status;
2388 2389
  SLastBlockReader* pLastBlockReader = pStatus->fileIter.pLastBlockReader;

2390 2391
  SUidOrderCheckInfo *pOrderedCheckInfo = &pStatus->uidCheckInfo;
  int32_t code = initOrderCheckInfo(pOrderedCheckInfo, pStatus);
2392
  if (code != TSDB_CODE_SUCCESS || (taosHashGetSize(pStatus->pTableMap) == 0)) {
2393 2394
    return code;
  }
2395

2396
  while(1) {
2397 2398
    // load the last data block of current table
    STableBlockScanInfo* pScanInfo = pStatus->pTableIter;
2399
    code = doLoadRelatedLastBlock(pLastBlockReader, pScanInfo, pReader);
2400
    if (code != TSDB_CODE_SUCCESS) {
2401 2402 2403
      return code;
    }

2404 2405
    if (pLastBlockReader->currentBlockIndex != -1) {
      initLastBlockReader(pLastBlockReader, pScanInfo->uid, &pScanInfo->indexInBlockL);
2406
      int32_t index = pScanInfo->indexInBlockL;
2407

2408
      if (index == INITIAL_ROW_INDEX_VAL || index == pLastBlockReader->lastBlockData.nRow) {
H
Haojun Liao 已提交
2409
        bool hasData = nextRowInLastBlock(pLastBlockReader, pScanInfo);
2410
        if (!hasData) {  // current table does not have rows in last block, try next table
2411 2412
          bool hasNexTable = moveToNextTable(pOrderedCheckInfo, pStatus);
          if (!hasNexTable) {
2413 2414 2415
            return TSDB_CODE_SUCCESS;
          }
          continue;
2416
        }
2417
      }
2418
    } else {  // no data in last block, try next table
2419 2420
      bool hasNexTable = moveToNextTable(pOrderedCheckInfo, pStatus);
      if (!hasNexTable) {
2421 2422 2423
        return TSDB_CODE_SUCCESS;
      }
      continue;
2424 2425
    }

2426 2427 2428 2429 2430 2431 2432 2433
    code = doBuildDataBlock(pReader);
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

    if (pReader->pResBlock->info.rows > 0) {
      return TSDB_CODE_SUCCESS;
    }
2434

2435
    // current table is exhausted, let's try next table
2436 2437
    bool hasNexTable = moveToNextTable(pOrderedCheckInfo, pStatus);
    if (!hasNexTable) {
2438 2439
      return TSDB_CODE_SUCCESS;
    }
2440 2441 2442
  }
}

2443
static int32_t doBuildDataBlock(STsdbReader* pReader) {
2444
  TSDBKEY key = {0};
2445
  int32_t code = TSDB_CODE_SUCCESS;
2446
  SBlock* pBlock = NULL;
2447 2448 2449

  SReaderStatus*       pStatus = &pReader->status;
  SDataBlockIter*      pBlockIter = &pStatus->blockIter;
2450 2451 2452
  STableBlockScanInfo* pScanInfo = NULL;
  SFileDataBlockInfo*  pBlockInfo = getCurrentBlockInfo(pBlockIter);
  SLastBlockReader*    pLastBlockReader = pReader->status.fileIter.pLastBlockReader;
2453

2454
  if (pBlockInfo != NULL) {
2455 2456 2457 2458 2459 2460
    pScanInfo = taosHashGet(pReader->status.pTableMap, &pBlockInfo->uid, sizeof(pBlockInfo->uid));
  } else {
    pScanInfo = pReader->status.pTableIter;
  }

  if (pBlockInfo != NULL) {
2461
    pBlock = getCurrentBlock(pBlockIter);
2462 2463 2464 2465
  }

  {
    key = getCurrentKeyInBuf(pScanInfo, pReader);
2466

2467
    // load the last data block of current table
2468
    code = doLoadRelatedLastBlock(pLastBlockReader, pScanInfo, pReader);
2469
    if (code != TSDB_CODE_SUCCESS) {
2470
      return code;
2471 2472
    }

H
Haojun Liao 已提交
2473
    // note: the lastblock may be null here
2474
    initLastBlockReader(pLastBlockReader, pScanInfo->uid, &pScanInfo->indexInBlockL);
2475
    if (pScanInfo->indexInBlockL == INITIAL_ROW_INDEX_VAL || pScanInfo->indexInBlockL == pLastBlockReader->lastBlockData.nRow) {
H
Haojun Liao 已提交
2476
      bool hasData = nextRowInLastBlock(pLastBlockReader, pScanInfo);
2477
    }
2478
  }
2479

2480 2481 2482 2483 2484 2485 2486
  if (pBlockInfo == NULL) {  // build data block from last data file
    ASSERT(pBlockIter->numOfBlocks == 0);
    code = buildComposedDataBlock(pReader);
  } else if (fileBlockShouldLoad(pReader, pBlockInfo, pBlock, pScanInfo, key, pLastBlockReader)) {
    tBlockDataReset(&pStatus->fileBlockData);
    code = tBlockDataInit(&pStatus->fileBlockData, pReader->suid, pScanInfo->uid, pReader->pSchema);
    if (code != TSDB_CODE_SUCCESS) {
2487
      return code;
2488
    }
2489

2490 2491 2492
    code = doLoadFileBlockData(pReader, pBlockIter, &pStatus->fileBlockData);
    if (code != TSDB_CODE_SUCCESS) {
      return code;
2493 2494 2495
    }

    // build composed data block
2496
    code = buildComposedDataBlock(pReader);
2497 2498
  } else if (bufferDataInFileBlockGap(pReader->order, key, pBlock)) {
    // data in memory that are earlier than current file block
2499
    // todo rows in buffer should be less than the file block in asc, greater than file block in desc
2500
    int64_t endKey = (ASCENDING_TRAVERSE(pReader->order)) ? pBlock->minKey.ts : pBlock->maxKey.ts;
2501
    code = buildDataBlockFromBuf(pReader, pScanInfo, endKey);
2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517
  } else {
    if (hasDataInLastBlock(pLastBlockReader) && !ASCENDING_TRAVERSE(pReader->order)) {
      // only return the rows in last block
      int64_t tsLast = getCurrentKeyInLastBlock(pLastBlockReader);
      ASSERT (tsLast >= pBlock->maxKey.ts);
      tBlockDataReset(&pReader->status.fileBlockData);

      code = buildComposedDataBlock(pReader);
    } else {   // whole block is required, return it directly
      SDataBlockInfo* pInfo = &pReader->pResBlock->info;
      pInfo->rows = pBlock->nRow;
      pInfo->uid = pScanInfo->uid;
      pInfo->window = (STimeWindow){.skey = pBlock->minKey.ts, .ekey = pBlock->maxKey.ts};
      setComposedBlockFlag(pReader, false);
      setBlockAllDumped(&pStatus->fBlockDumpInfo, pBlock->maxKey.ts, pReader->order);
    }
2518 2519 2520 2521 2522
  }

  return code;
}

H
Haojun Liao 已提交
2523
static int32_t buildBlockFromBufferSequentially(STsdbReader* pReader) {
2524 2525
  SReaderStatus* pStatus = &pReader->status;

2526
  while (1) {
2527 2528 2529
    if (pStatus->pTableIter == NULL) {
      pStatus->pTableIter = taosHashIterate(pStatus->pTableMap, NULL);
      if (pStatus->pTableIter == NULL) {
H
Haojun Liao 已提交
2530
        return TSDB_CODE_SUCCESS;
2531 2532 2533 2534
      }
    }

    STableBlockScanInfo* pBlockScanInfo = pStatus->pTableIter;
2535
    initMemDataIterator(pBlockScanInfo, pReader);
2536

2537
    int64_t endKey = (ASCENDING_TRAVERSE(pReader->order)) ? INT64_MAX : INT64_MIN;
2538
    int32_t code = buildDataBlockFromBuf(pReader, pBlockScanInfo, endKey);
H
Haojun Liao 已提交
2539 2540 2541 2542
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

2543
    if (pReader->pResBlock->info.rows > 0) {
H
Haojun Liao 已提交
2544
      return TSDB_CODE_SUCCESS;
2545 2546 2547 2548 2549
    }

    // current table is exhausted, let's try the next table
    pStatus->pTableIter = taosHashIterate(pStatus->pTableMap, pStatus->pTableIter);
    if (pStatus->pTableIter == NULL) {
H
Haojun Liao 已提交
2550
      return TSDB_CODE_SUCCESS;
2551 2552 2553 2554
    }
  }
}

2555
// set the correct start position in case of the first/last file block, according to the query time window
2556
static void initBlockDumpInfo(STsdbReader* pReader, SDataBlockIter* pBlockIter) {
2557
  SBlock* pBlock = getCurrentBlock(pBlockIter);
2558

2559 2560 2561
  SReaderStatus* pStatus = &pReader->status;

  SFileBlockDumpInfo* pDumpInfo = &pStatus->fBlockDumpInfo;
2562 2563 2564

  pDumpInfo->totalRows = pBlock->nRow;
  pDumpInfo->allDumped = false;
2565
  pDumpInfo->rowIndex = ASCENDING_TRAVERSE(pReader->order) ? 0 : pBlock->nRow - 1;
2566 2567
}

2568
static int32_t initForFirstBlockInFile(STsdbReader* pReader, SDataBlockIter* pBlockIter) {
2569 2570
  SBlockNumber num = {0};

2571
  int32_t code = moveToNextFile(pReader, &num);
2572 2573 2574 2575 2576
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

  // all data files are consumed, try data in buffer
2577
  if (num.numOfBlocks + num.numOfLastBlocks == 0) {
2578 2579 2580 2581 2582
    pReader->status.loadFromFile = false;
    return code;
  }

  // initialize the block iterator for a new fileset
2583 2584
  if (num.numOfBlocks > 0) {
    code = initBlockIterator(pReader, pBlockIter, num.numOfBlocks);
2585
  } else { // no block data, only last block exists
2586
    tBlockDataReset(&pReader->status.fileBlockData);
2587
    resetDataBlockIterator(pBlockIter, pReader->order);
2588
  }
2589

2590 2591 2592
  SLastBlockReader* pLReader = pReader->status.fileIter.pLastBlockReader;
  pLReader->currentBlockIndex = -1;

2593
  // set the correct start position according to the query time window
2594
  initBlockDumpInfo(pReader, pBlockIter);
2595 2596 2597
  return code;
}

2598
static bool fileBlockPartiallyRead(SFileBlockDumpInfo* pDumpInfo, bool asc) {
2599 2600
  return (!pDumpInfo->allDumped) &&
         ((pDumpInfo->rowIndex > 0 && asc) || (pDumpInfo->rowIndex < (pDumpInfo->totalRows - 1) && (!asc)));
2601 2602
}

2603
static int32_t buildBlockFromFiles(STsdbReader* pReader) {
H
Haojun Liao 已提交
2604
  int32_t code = TSDB_CODE_SUCCESS;
2605 2606
  bool    asc = ASCENDING_TRAVERSE(pReader->order);

2607 2608
  SDataBlockIter* pBlockIter = &pReader->status.blockIter;

2609 2610 2611 2612 2613 2614 2615
  if (pBlockIter->numOfBlocks == 0) {
    _begin:
    code = doLoadLastBlockSequentially(pReader);
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

2616 2617 2618 2619
    if (pReader->pResBlock->info.rows > 0) {
      return TSDB_CODE_SUCCESS;
    }

2620
    // all data blocks are checked in this last block file, now let's try the next file
2621 2622 2623 2624 2625 2626 2627 2628
    if (pReader->status.pTableIter == NULL) {
      code = initForFirstBlockInFile(pReader, pBlockIter);

      // error happens or all the data files are completely checked
      if ((code != TSDB_CODE_SUCCESS) || (pReader->status.loadFromFile == false)) {
        return code;
      }

2629
      // this file does not have data files, let's start check the last block file if exists
2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644
      if (pBlockIter->numOfBlocks == 0) {
        goto _begin;
      }
    }

    code = doBuildDataBlock(pReader);
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

    if (pReader->pResBlock->info.rows > 0) {
      return TSDB_CODE_SUCCESS;
    }
  }

2645
  while (1) {
2646 2647
    SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;

2648
    if (fileBlockPartiallyRead(pDumpInfo, asc)) {  // file data block is partially loaded
2649
      code = buildComposedDataBlock(pReader);
2650 2651 2652 2653 2654 2655 2656
    } else {
      // current block are exhausted, try the next file block
      if (pDumpInfo->allDumped) {
        // try next data block in current file
        bool hasNext = blockIteratorNext(&pReader->status.blockIter);
        if (hasNext) {  // check for the next block in the block accessed order list
          initBlockDumpInfo(pReader, pBlockIter);
2657 2658
        } else if (taosArrayGetSize(pReader->status.fileIter.pLastBlockReader->pBlockL) > 0) {  // data blocks in current file are exhausted, let's try the next file now
          tBlockDataReset(&pReader->status.fileBlockData);
2659
          resetDataBlockIterator(pBlockIter, pReader->order);
2660 2661
          goto _begin;
        } else {
2662 2663 2664 2665 2666 2667
          code = initForFirstBlockInFile(pReader, pBlockIter);

          // error happens or all the data files are completely checked
          if ((code != TSDB_CODE_SUCCESS) || (pReader->status.loadFromFile == false)) {
            return code;
          }
2668 2669 2670 2671 2672

          // this file does not have blocks, let's start check the last block file
          if (pBlockIter->numOfBlocks == 0) {
            goto _begin;
          }
2673
        }
H
Haojun Liao 已提交
2674
      }
2675 2676

      code = doBuildDataBlock(pReader);
2677 2678
    }

2679 2680 2681 2682 2683 2684 2685 2686
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

    if (pReader->pResBlock->info.rows > 0) {
      return TSDB_CODE_SUCCESS;
    }
  }
2687
}
H
refact  
Hongze Cheng 已提交
2688

2689 2690
static STsdb* getTsdbByRetentions(SVnode* pVnode, TSKEY winSKey, SRetention* retentions, const char* idStr,
                                  int8_t* pLevel) {
2691
  if (VND_IS_RSMA(pVnode)) {
2692
    int8_t  level = 0;
2693 2694
    int64_t now = taosGetTimestamp(pVnode->config.tsdbCfg.precision);

2695
    for (int8_t i = 0; i < TSDB_RETENTION_MAX; ++i) {
2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708
      SRetention* pRetention = retentions + level;
      if (pRetention->keep <= 0) {
        if (level > 0) {
          --level;
        }
        break;
      }
      if ((now - pRetention->keep) <= winSKey) {
        break;
      }
      ++level;
    }

2709
    const char* str = (idStr != NULL) ? idStr : "";
2710 2711

    if (level == TSDB_RETENTION_L0) {
2712
      *pLevel = TSDB_RETENTION_L0;
C
Cary Xu 已提交
2713
      tsdbDebug("vgId:%d, rsma level %d is selected to query %s", TD_VID(pVnode), TSDB_RETENTION_L0, str);
2714 2715
      return VND_RSMA0(pVnode);
    } else if (level == TSDB_RETENTION_L1) {
2716
      *pLevel = TSDB_RETENTION_L1;
C
Cary Xu 已提交
2717
      tsdbDebug("vgId:%d, rsma level %d is selected to query %s", TD_VID(pVnode), TSDB_RETENTION_L1, str);
2718 2719
      return VND_RSMA1(pVnode);
    } else {
2720
      *pLevel = TSDB_RETENTION_L2;
C
Cary Xu 已提交
2721
      tsdbDebug("vgId:%d, rsma level %d is selected to query %s", TD_VID(pVnode), TSDB_RETENTION_L2, str);
2722 2723 2724 2725 2726 2727 2728
      return VND_RSMA2(pVnode);
    }
  }

  return VND_TSDB(pVnode);
}

H
Haojun Liao 已提交
2729
SVersionRange getQueryVerRange(SVnode* pVnode, SQueryTableDataCond* pCond, int8_t level) {
L
Liu Jicong 已提交
2730
  int64_t startVer = (pCond->startVersion == -1) ? 0 : pCond->startVersion;
H
Haojun Liao 已提交
2731 2732

  int64_t endVer = 0;
L
Liu Jicong 已提交
2733 2734
  if (pCond->endVersion ==
      -1) {  // user not specified end version, set current maximum version of vnode as the endVersion
H
Haojun Liao 已提交
2735 2736
    endVer = pVnode->state.applied;
  } else {
L
Liu Jicong 已提交
2737
    endVer = (pCond->endVersion > pVnode->state.applied) ? pVnode->state.applied : pCond->endVersion;
2738 2739
  }

H
Haojun Liao 已提交
2740
  return (SVersionRange){.minVer = startVer, .maxVer = endVer};
2741 2742
}

2743
bool hasBeenDropped(const SArray* pDelList, int32_t* index, TSDBKEY* pKey, int32_t order) {
2744 2745 2746 2747
  ASSERT(pKey != NULL);
  if (pDelList == NULL) {
    return false;
  }
L
Liu Jicong 已提交
2748 2749 2750
  size_t  num = taosArrayGetSize(pDelList);
  bool    asc = ASCENDING_TRAVERSE(order);
  int32_t step = asc ? 1 : -1;
2751

2752 2753 2754 2755 2756 2757
  if (asc) {
    if (*index >= num - 1) {
      TSDBKEY* last = taosArrayGetLast(pDelList);
      ASSERT(pKey->ts >= last->ts);

      if (pKey->ts > last->ts) {
2758
        return false;
2759 2760 2761
      } else if (pKey->ts == last->ts) {
        TSDBKEY* prev = taosArrayGet(pDelList, num - 2);
        return (prev->version >= pKey->version);
2762 2763
      }
    } else {
2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793
      TSDBKEY* pCurrent = taosArrayGet(pDelList, *index);
      TSDBKEY* pNext = taosArrayGet(pDelList, (*index) + 1);

      if (pKey->ts < pCurrent->ts) {
        return false;
      }

      if (pCurrent->ts <= pKey->ts && pNext->ts >= pKey->ts && pCurrent->version >= pKey->version) {
        return true;
      }

      while (pNext->ts <= pKey->ts && (*index) < num - 1) {
        (*index) += 1;

        if ((*index) < num - 1) {
          pCurrent = taosArrayGet(pDelList, *index);
          pNext = taosArrayGet(pDelList, (*index) + 1);

          // it is not a consecutive deletion range, ignore it
          if (pCurrent->version == 0 && pNext->version > 0) {
            continue;
          }

          if (pCurrent->ts <= pKey->ts && pNext->ts >= pKey->ts && pCurrent->version >= pKey->version) {
            return true;
          }
        }
      }

      return false;
2794 2795
    }
  } else {
2796 2797
    if (*index <= 0) {
      TSDBKEY* pFirst = taosArrayGet(pDelList, 0);
2798

2799 2800 2801 2802 2803 2804 2805
      if (pKey->ts < pFirst->ts) {
        return false;
      } else if (pKey->ts == pFirst->ts) {
        return pFirst->version >= pKey->version;
      } else {
        ASSERT(0);
      }
2806
    } else {
2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833
      TSDBKEY* pCurrent = taosArrayGet(pDelList, *index);
      TSDBKEY* pPrev = taosArrayGet(pDelList, (*index) - 1);

      if (pKey->ts > pCurrent->ts) {
        return false;
      }

      if (pPrev->ts <= pKey->ts && pCurrent->ts >= pKey->ts && pPrev->version >= pKey->version) {
        return true;
      }

      while (pPrev->ts >= pKey->ts && (*index) > 1) {
        (*index) += step;

        if ((*index) >= 1) {
          pCurrent = taosArrayGet(pDelList, *index);
          pPrev = taosArrayGet(pDelList, (*index) - 1);

          // it is not a consecutive deletion range, ignore it
          if (pCurrent->version > 0 && pPrev->version == 0) {
            continue;
          }

          if (pPrev->ts <= pKey->ts && pCurrent->ts >= pKey->ts && pPrev->version >= pKey->version) {
            return true;
          }
        }
2834 2835 2836 2837 2838
      }

      return false;
    }
  }
2839 2840

  return false;
2841 2842
}

2843
TSDBROW* getValidMemRow(SIterInfo* pIter, const SArray* pDelList, STsdbReader* pReader) {
2844
  if (!pIter->hasVal) {
H
Haojun Liao 已提交
2845 2846
    return NULL;
  }
H
Hongze Cheng 已提交
2847

2848
  TSDBROW* pRow = tsdbTbDataIterGet(pIter->iter);
2849
  TSDBKEY  key = {.ts = pRow->pTSRow->ts, .version = pRow->version};
2850
  if (outOfTimeWindow(key.ts, &pReader->window)) {
2851
    pIter->hasVal = false;
H
Haojun Liao 已提交
2852 2853
    return NULL;
  }
H
Hongze Cheng 已提交
2854

2855
  // it is a valid data version
dengyihao's avatar
dengyihao 已提交
2856
  if ((key.version <= pReader->verRange.maxVer && key.version >= pReader->verRange.minVer) &&
2857
      (!hasBeenDropped(pDelList, &pIter->index, &key, pReader->order))) {
H
Haojun Liao 已提交
2858 2859
    return pRow;
  }
H
Hongze Cheng 已提交
2860

2861
  while (1) {
2862 2863
    pIter->hasVal = tsdbTbDataIterNext(pIter->iter);
    if (!pIter->hasVal) {
H
Haojun Liao 已提交
2864 2865
      return NULL;
    }
H
Hongze Cheng 已提交
2866

2867
    pRow = tsdbTbDataIterGet(pIter->iter);
H
Hongze Cheng 已提交
2868

H
Haojun Liao 已提交
2869
    key = TSDBROW_KEY(pRow);
2870
    if (outOfTimeWindow(key.ts, &pReader->window)) {
2871
      pIter->hasVal = false;
H
Haojun Liao 已提交
2872 2873
      return NULL;
    }
H
Hongze Cheng 已提交
2874

dengyihao's avatar
dengyihao 已提交
2875
    if (key.version <= pReader->verRange.maxVer && key.version >= pReader->verRange.minVer &&
2876
        (!hasBeenDropped(pDelList, &pIter->index, &key, pReader->order))) {
H
Haojun Liao 已提交
2877 2878 2879 2880
      return pRow;
    }
  }
}
H
Hongze Cheng 已提交
2881

2882 2883
int32_t doMergeRowsInBuf(SIterInfo* pIter, uint64_t uid, int64_t ts, SArray* pDelList, SRowMerger* pMerger,
                         STsdbReader* pReader) {
H
Haojun Liao 已提交
2884
  while (1) {
2885 2886
    pIter->hasVal = tsdbTbDataIterNext(pIter->iter);
    if (!pIter->hasVal) {
H
Haojun Liao 已提交
2887 2888
      break;
    }
H
Hongze Cheng 已提交
2889

2890
    // data exists but not valid
2891
    TSDBROW* pRow = getValidMemRow(pIter, pDelList, pReader);
2892 2893 2894 2895 2896
    if (pRow == NULL) {
      break;
    }

    // ts is not identical, quit
H
Haojun Liao 已提交
2897
    TSDBKEY k = TSDBROW_KEY(pRow);
2898
    if (k.ts != ts) {
H
Haojun Liao 已提交
2899 2900 2901
      break;
    }

H
Haojun Liao 已提交
2902
    STSchema* pTSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(pRow), pReader, uid);
2903
    tRowMergerAdd(pMerger, pRow, pTSchema);
H
Haojun Liao 已提交
2904 2905 2906 2907 2908
  }

  return TSDB_CODE_SUCCESS;
}

2909
static int32_t doMergeRowsInFileBlockImpl(SBlockData* pBlockData, int32_t rowIndex, int64_t key, SRowMerger* pMerger,
2910
                                          SVersionRange* pVerRange, int32_t step) {
2911 2912
  while (pBlockData->aTSKEY[rowIndex] == key && rowIndex < pBlockData->nRow && rowIndex >= 0) {
    if (pBlockData->aVersion[rowIndex] > pVerRange->maxVer || pBlockData->aVersion[rowIndex] < pVerRange->minVer) {
2913
      rowIndex += step;
2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930
      continue;
    }

    TSDBROW fRow = tsdbRowFromBlockData(pBlockData, rowIndex);
    tRowMerge(pMerger, &fRow);
    rowIndex += step;
  }

  return rowIndex;
}

typedef enum {
  CHECK_FILEBLOCK_CONT = 0x1,
  CHECK_FILEBLOCK_QUIT = 0x2,
} CHECK_FILEBLOCK_STATE;

static int32_t checkForNeighborFileBlock(STsdbReader* pReader, STableBlockScanInfo* pScanInfo, SBlock* pBlock,
2931 2932
                                         SFileDataBlockInfo* pFBlock, SRowMerger* pMerger, int64_t key,
                                         CHECK_FILEBLOCK_STATE* state) {
2933
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;
2934
  SBlockData*         pBlockData = &pReader->status.fileBlockData;
2935

2936
  *state = CHECK_FILEBLOCK_QUIT;
2937
  int32_t step = ASCENDING_TRAVERSE(pReader->order) ? 1 : -1;
2938 2939 2940

  int32_t nextIndex = -1;
  SBlock* pNeighborBlock = getNeighborBlockOfSameTable(pFBlock, pScanInfo, &nextIndex, pReader->order);
2941
  if (pNeighborBlock == NULL) {  // do nothing
2942 2943 2944 2945
    return 0;
  }

  bool overlap = overlapWithNeighborBlock(pBlock, pNeighborBlock, pReader->order);
2946 2947
  taosMemoryFree(pNeighborBlock);

2948
  if (overlap) {  // load next block
2949
    SReaderStatus*  pStatus = &pReader->status;
2950 2951
    SDataBlockIter* pBlockIter = &pStatus->blockIter;

2952
    // 1. find the next neighbor block in the scan block list
2953
    SFileDataBlockInfo fb = {.uid = pFBlock->uid, .tbBlockIdx = nextIndex};
2954
    int32_t            neighborIndex = findFileBlockInfoIndex(pBlockIter, &fb);
2955

2956
    // 2. remove it from the scan block list
2957
    setFileBlockActiveInBlockIter(pBlockIter, neighborIndex, step);
2958

2959
    // 3. load the neighbor block, and set it to be the currently accessed file data block
H
Haojun Liao 已提交
2960
    tBlockDataReset(&pStatus->fileBlockData);
2961 2962 2963 2964 2965 2966
    int32_t code = tBlockDataInit(&pStatus->fileBlockData, pReader->suid, pFBlock->uid, pReader->pSchema);
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

    code = doLoadFileBlockData(pReader, pBlockIter, &pStatus->fileBlockData);
2967 2968 2969 2970
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

2971
    // 4. check the data values
2972 2973 2974 2975
    initBlockDumpInfo(pReader, pBlockIter);

    pDumpInfo->rowIndex =
        doMergeRowsInFileBlockImpl(pBlockData, pDumpInfo->rowIndex, key, pMerger, &pReader->verRange, step);
H
Haojun Liao 已提交
2976
    if (pDumpInfo->rowIndex >= pDumpInfo->totalRows) {
2977 2978 2979 2980 2981 2982 2983
      *state = CHECK_FILEBLOCK_CONT;
    }
  }

  return TSDB_CODE_SUCCESS;
}

2984 2985
int32_t doMergeRowsInFileBlocks(SBlockData* pBlockData, STableBlockScanInfo* pScanInfo, STsdbReader* pReader,
                                SRowMerger* pMerger) {
2986 2987
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;

2988
  bool    asc = ASCENDING_TRAVERSE(pReader->order);
2989
  int64_t key = pBlockData->aTSKEY[pDumpInfo->rowIndex];
2990
  int32_t step = asc ? 1 : -1;
2991

2992
  pDumpInfo->rowIndex += step;
2993
  if ((pDumpInfo->rowIndex <= pBlockData->nRow - 1 && asc) || (pDumpInfo->rowIndex >= 0 && !asc)) {
2994 2995 2996
    pDumpInfo->rowIndex =
        doMergeRowsInFileBlockImpl(pBlockData, pDumpInfo->rowIndex, key, pMerger, &pReader->verRange, step);
  }
2997

2998 2999 3000 3001
  // all rows are consumed, let's try next file block
  if ((pDumpInfo->rowIndex >= pBlockData->nRow && asc) || (pDumpInfo->rowIndex < 0 && !asc)) {
    while (1) {
      CHECK_FILEBLOCK_STATE st;
3002

3003
      SFileDataBlockInfo* pFileBlockInfo = getCurrentBlockInfo(&pReader->status.blockIter);
3004
      SBlock*             pCurrentBlock = getCurrentBlock(&pReader->status.blockIter);
3005 3006 3007
      checkForNeighborFileBlock(pReader, pScanInfo, pCurrentBlock, pFileBlockInfo, pMerger, key, &st);
      if (st == CHECK_FILEBLOCK_QUIT) {
        break;
3008
      }
3009
    }
H
Haojun Liao 已提交
3010
  }
3011

H
Haojun Liao 已提交
3012 3013 3014
  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
3015 3016
int32_t doMergeRowsInLastBlock(SLastBlockReader* pLastBlockReader, STableBlockScanInfo* pScanInfo, int64_t ts, SRowMerger* pMerger) {
  while(nextRowInLastBlock(pLastBlockReader, pScanInfo)) {
3017 3018
    int64_t next1 = getCurrentKeyInLastBlock(pLastBlockReader);
    if (next1 == ts) {
3019
      TSDBROW fRow1 = tsdbRowFromBlockData(&pLastBlockReader->lastBlockData, *pLastBlockReader->rowIndex);
3020 3021 3022 3023 3024 3025 3026 3027 3028
      tRowMerge(pMerger, &fRow1);
    } else {
      break;
    }
  }

  return TSDB_CODE_SUCCESS;
}

3029
void doMergeMemTableMultiRows(TSDBROW* pRow, uint64_t uid, SIterInfo* pIter, SArray* pDelList, STSRow** pTSRow,
3030
                      STsdbReader* pReader, bool* freeTSRow) {
H
Haojun Liao 已提交
3031
  TSDBROW* pNextRow = NULL;
3032
  TSDBROW  current = *pRow;
3033

3034 3035
  {  // if the timestamp of the next valid row has a different ts, return current row directly
    pIter->hasVal = tsdbTbDataIterNext(pIter->iter);
3036

3037 3038 3039 3040 3041
    if (!pIter->hasVal) {
      *pTSRow = current.pTSRow;
      *freeTSRow = false;
      return;
    } else {  // has next point in mem/imem
3042
      pNextRow = getValidMemRow(pIter, pDelList, pReader);
3043 3044 3045 3046 3047 3048
      if (pNextRow == NULL) {
        *pTSRow = current.pTSRow;
        *freeTSRow = false;
        return;
      }

H
Haojun Liao 已提交
3049
      if (current.pTSRow->ts != pNextRow->pTSRow->ts) {
3050 3051 3052 3053
        *pTSRow = current.pTSRow;
        *freeTSRow = false;
        return;
      }
3054
    }
3055 3056
  }

3057 3058
  SRowMerger merge = {0};

3059
  // get the correct schema for data in memory
H
Haojun Liao 已提交
3060
  STSchema* pTSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(&current), pReader, uid);
H
Haojun Liao 已提交
3061

3062 3063
  if (pReader->pSchema == NULL) {
    pReader->pSchema = pTSchema;
3064
  }
H
Haojun Liao 已提交
3065

H
Haojun Liao 已提交
3066 3067 3068 3069 3070 3071
  tRowMergerInit2(&merge, pReader->pSchema, &current, pTSchema);

  STSchema* pTSchema1 = doGetSchemaForTSRow(TSDBROW_SVERSION(pNextRow), pReader, uid);
  tRowMergerAdd(&merge, pNextRow, pTSchema1);

  doMergeRowsInBuf(pIter, uid, current.pTSRow->ts, pDelList, &merge, pReader);
3072
  tRowMergerGetRow(&merge, pTSRow);
3073
  tRowMergerClear(&merge);
M
Minglei Jin 已提交
3074

3075
  *freeTSRow = true;
3076 3077
}

3078 3079
void doMergeMemIMemRows(TSDBROW* pRow, TSDBROW* piRow, STableBlockScanInfo* pBlockScanInfo, STsdbReader* pReader,
                        STSRow** pTSRow) {
H
Haojun Liao 已提交
3080 3081
  SRowMerger merge = {0};

3082 3083 3084
  TSDBKEY k = TSDBROW_KEY(pRow);
  TSDBKEY ik = TSDBROW_KEY(piRow);

3085
  if (ASCENDING_TRAVERSE(pReader->order)) {  // ascending order imem --> mem
H
Haojun Liao 已提交
3086
    STSchema* pSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(pRow), pReader, pBlockScanInfo->uid);
3087

H
Haojun Liao 已提交
3088
    tRowMergerInit(&merge, piRow, pSchema);
3089
    doMergeRowsInBuf(&pBlockScanInfo->iiter, pBlockScanInfo->uid, ik.ts, pBlockScanInfo->delSkyline, &merge, pReader);
3090

3091
    tRowMerge(&merge, pRow);
3092
    doMergeRowsInBuf(&pBlockScanInfo->iter, pBlockScanInfo->uid, k.ts, pBlockScanInfo->delSkyline, &merge, pReader);
3093
  } else {
H
Haojun Liao 已提交
3094
    STSchema* pSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(pRow), pReader, pBlockScanInfo->uid);
3095

H
Haojun Liao 已提交
3096
    tRowMergerInit(&merge, pRow, pSchema);
3097
    doMergeRowsInBuf(&pBlockScanInfo->iter, pBlockScanInfo->uid, k.ts, pBlockScanInfo->delSkyline, &merge, pReader);
3098 3099

    tRowMerge(&merge, piRow);
3100
    doMergeRowsInBuf(&pBlockScanInfo->iiter, pBlockScanInfo->uid, k.ts, pBlockScanInfo->delSkyline, &merge, pReader);
3101
  }
3102 3103 3104 3105

  tRowMergerGetRow(&merge, pTSRow);
}

3106 3107
int32_t tsdbGetNextRowInMem(STableBlockScanInfo* pBlockScanInfo, STsdbReader* pReader, STSRow** pTSRow, int64_t endKey,
                            bool* freeTSRow) {
3108 3109
  TSDBROW* pRow = getValidMemRow(&pBlockScanInfo->iter, pBlockScanInfo->delSkyline, pReader);
  TSDBROW* piRow = getValidMemRow(&pBlockScanInfo->iiter, pBlockScanInfo->delSkyline, pReader);
dengyihao's avatar
dengyihao 已提交
3110
  SArray*  pDelList = pBlockScanInfo->delSkyline;
3111
  uint64_t uid = pBlockScanInfo->uid;
H
Haojun Liao 已提交
3112

3113 3114
  // todo refactor
  bool asc = ASCENDING_TRAVERSE(pReader->order);
3115
  if (pBlockScanInfo->iter.hasVal) {
3116 3117 3118 3119 3120 3121
    TSDBKEY k = TSDBROW_KEY(pRow);
    if ((k.ts >= endKey && asc) || (k.ts <= endKey && !asc)) {
      pRow = NULL;
    }
  }

3122
  if (pBlockScanInfo->iiter.hasVal) {
3123 3124 3125 3126 3127 3128
    TSDBKEY k = TSDBROW_KEY(piRow);
    if ((k.ts >= endKey && asc) || (k.ts <= endKey && !asc)) {
      piRow = NULL;
    }
  }

3129
  if (pBlockScanInfo->iter.hasVal && pBlockScanInfo->iiter.hasVal && pRow != NULL && piRow != NULL) {
3130
    TSDBKEY k = TSDBROW_KEY(pRow);
3131
    TSDBKEY ik = TSDBROW_KEY(piRow);
H
Haojun Liao 已提交
3132

3133 3134 3135 3136 3137 3138
    if (ik.ts != k.ts) {
      if (((ik.ts < k.ts) && asc) || ((ik.ts > k.ts) && (!asc))) {  // ik.ts < k.ts
        doMergeMemTableMultiRows(piRow, uid, &pBlockScanInfo->iiter, pDelList, pTSRow, pReader, freeTSRow);
      } else if (((k.ts < ik.ts) && asc) || ((k.ts > ik.ts) && (!asc))) {
        doMergeMemTableMultiRows(pRow, uid, &pBlockScanInfo->iter, pDelList, pTSRow, pReader, freeTSRow);
      }
3139 3140
    } else {  // ik.ts == k.ts
      doMergeMemIMemRows(pRow, piRow, pBlockScanInfo, pReader, pTSRow);
3141
      *freeTSRow = true;
H
Haojun Liao 已提交
3142
    }
3143 3144

    return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
3145 3146
  }

3147
  if (pBlockScanInfo->iter.hasVal && pRow != NULL) {
3148
    doMergeMemTableMultiRows(pRow, pBlockScanInfo->uid, &pBlockScanInfo->iter, pDelList, pTSRow, pReader, freeTSRow);
H
Haojun Liao 已提交
3149 3150 3151
    return TSDB_CODE_SUCCESS;
  }

3152
  if (pBlockScanInfo->iiter.hasVal && piRow != NULL) {
3153
    doMergeMemTableMultiRows(piRow, uid, &pBlockScanInfo->iiter, pDelList, pTSRow, pReader, freeTSRow);
H
Haojun Liao 已提交
3154 3155 3156 3157 3158 3159
    return TSDB_CODE_SUCCESS;
  }

  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
3160
int32_t doAppendRowFromTSRow(SSDataBlock* pBlock, STsdbReader* pReader, STSRow* pTSRow, uint64_t uid) {
3161 3162 3163
  int32_t numOfRows = pBlock->info.rows;
  int32_t numOfCols = (int32_t)taosArrayGetSize(pBlock->pDataBlock);

3164
  SBlockLoadSuppInfo* pSupInfo = &pReader->suppInfo;
3165
  STSchema*           pSchema = doGetSchemaForTSRow(pTSRow->sver, pReader, uid);
3166

3167
  SColVal colVal = {0};
3168
  int32_t i = 0, j = 0;
H
Haojun Liao 已提交
3169

3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180
  SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, i);
  if (pColInfoData->info.colId == PRIMARYKEY_TIMESTAMP_COL_ID) {
    colDataAppend(pColInfoData, numOfRows, (const char*)&pTSRow->ts, false);
    i += 1;
  }

  while (i < numOfCols && j < pSchema->numOfCols) {
    pColInfoData = taosArrayGet(pBlock->pDataBlock, i);
    col_id_t colId = pColInfoData->info.colId;

    if (colId == pSchema->columns[j].colId) {
H
Haojun Liao 已提交
3181
      tTSRowGetVal(pTSRow, pSchema, j, &colVal);
3182 3183 3184 3185 3186 3187 3188 3189
      doCopyColVal(pColInfoData, numOfRows, i, &colVal, pSupInfo);
      i += 1;
      j += 1;
    } else if (colId < pSchema->columns[j].colId) {
      colDataAppendNULL(pColInfoData, numOfRows);
      i += 1;
    } else if (colId > pSchema->columns[j].colId) {
      j += 1;
3190
    }
3191 3192
  }

3193
  // set null value since current column does not exist in the "pSchema"
3194
  while (i < numOfCols) {
3195 3196 3197 3198 3199
    pColInfoData = taosArrayGet(pBlock->pDataBlock, i);
    colDataAppendNULL(pColInfoData, numOfRows);
    i += 1;
  }

3200 3201 3202 3203
  pBlock->info.rows += 1;
  return TSDB_CODE_SUCCESS;
}

3204
int32_t doAppendRowFromFileBlock(SSDataBlock* pResBlock, STsdbReader* pReader, SBlockData* pBlockData, int32_t rowIndex) {
3205 3206 3207 3208 3209 3210 3211 3212
  int32_t i = 0, j = 0;
  int32_t outputRowIndex = pResBlock->info.rows;

  SBlockLoadSuppInfo* pSupInfo = &pReader->suppInfo;

  SColumnInfoData* pColData = taosArrayGet(pResBlock->pDataBlock, i);
  if (pColData->info.colId == PRIMARYKEY_TIMESTAMP_COL_ID) {
    colDataAppendInt64(pColData, outputRowIndex, &pBlockData->aTSKEY[rowIndex]);
3213
    i += 1;
3214 3215 3216 3217 3218 3219
  }

  SColVal cv = {0};
  int32_t numOfInputCols = taosArrayGetSize(pBlockData->aIdx);
  int32_t numOfOutputCols = blockDataGetNumOfCols(pResBlock);

3220
  while (i < numOfOutputCols && j < numOfInputCols) {
3221
    SColumnInfoData* pCol = taosArrayGet(pResBlock->pDataBlock, i);
3222
    SColData*        pData = tBlockDataGetColDataByIdx(pBlockData, j);
3223 3224

    if (pData->cid == pCol->info.colId) {
3225 3226
      tColDataGetValue(pData, rowIndex, &cv);
      doCopyColVal(pCol, outputRowIndex, i, &cv, pSupInfo);
3227 3228 3229 3230 3231 3232 3233 3234 3235 3236
      j += 1;
    } else {  // the specified column does not exist in file block, fill with null data
      colDataAppendNULL(pCol, outputRowIndex);
    }

    i += 1;
  }

  while (i < numOfOutputCols) {
    SColumnInfoData* pCol = taosArrayGet(pResBlock->pDataBlock, i);
3237
    colDataAppendNULL(pCol, outputRowIndex);
3238 3239 3240 3241 3242 3243 3244
    i += 1;
  }

  pResBlock->info.rows += 1;
  return TSDB_CODE_SUCCESS;
}

3245 3246
int32_t buildDataBlockFromBufImpl(STableBlockScanInfo* pBlockScanInfo, int64_t endKey, int32_t capacity,
                                  STsdbReader* pReader) {
H
Haojun Liao 已提交
3247 3248 3249 3250
  SSDataBlock* pBlock = pReader->pResBlock;

  do {
    STSRow* pTSRow = NULL;
3251
    bool    freeTSRow = false;
3252
    tsdbGetNextRowInMem(pBlockScanInfo, pReader, &pTSRow, endKey, &freeTSRow);
3253 3254
    if (pTSRow == NULL) {
      break;
H
Haojun Liao 已提交
3255 3256
    }

H
Haojun Liao 已提交
3257
    doAppendRowFromTSRow(pBlock, pReader, pTSRow, pBlockScanInfo->uid);
3258 3259 3260
    if (freeTSRow) {
      taosMemoryFree(pTSRow);
    }
H
Haojun Liao 已提交
3261 3262

    // no data in buffer, return immediately
3263
    if (!(pBlockScanInfo->iter.hasVal || pBlockScanInfo->iiter.hasVal)) {
H
Haojun Liao 已提交
3264 3265 3266
      break;
    }

3267
    if (pBlock->info.rows >= capacity) {
H
Haojun Liao 已提交
3268 3269 3270 3271
      break;
    }
  } while (1);

3272
  ASSERT(pBlock->info.rows <= capacity);
H
Haojun Liao 已提交
3273 3274
  return TSDB_CODE_SUCCESS;
}
H
Hongze Cheng 已提交
3275

3276
// todo refactor, use arraylist instead
H
Hongze Cheng 已提交
3277
int32_t tsdbSetTableId(STsdbReader* pReader, int64_t uid) {
3278 3279 3280
  ASSERT(pReader != NULL);
  taosHashClear(pReader->status.pTableMap);

3281
  STableBlockScanInfo info = {.lastKey = 0, .uid = uid, .indexInBlockL = INITIAL_ROW_INDEX_VAL};
3282
  taosHashPut(pReader->status.pTableMap, &info.uid, sizeof(uint64_t), &info, sizeof(info));
H
Hongze Cheng 已提交
3283 3284 3285
  return TDB_CODE_SUCCESS;
}

dengyihao's avatar
dengyihao 已提交
3286 3287 3288 3289 3290 3291
void* tsdbGetIdx(SMeta* pMeta) {
  if (pMeta == NULL) {
    return NULL;
  }
  return metaGetIdx(pMeta);
}
dengyihao's avatar
dengyihao 已提交
3292

dengyihao's avatar
dengyihao 已提交
3293 3294 3295 3296 3297 3298
void* tsdbGetIvtIdx(SMeta* pMeta) {
  if (pMeta == NULL) {
    return NULL;
  }
  return metaGetIvtIdx(pMeta);
}
L
Liu Jicong 已提交
3299

H
Hongze Cheng 已提交
3300
uint64_t getReaderMaxVersion(STsdbReader* pReader) { return pReader->verRange.maxVer; }
3301

C
Cary Xu 已提交
3302

H
refact  
Hongze Cheng 已提交
3303
// ====================================== EXPOSED APIs ======================================
3304 3305
int32_t tsdbReaderOpen(SVnode* pVnode, SQueryTableDataCond* pCond, SArray* pTableList, STsdbReader** ppReader,
                       const char* idstr) {
3306 3307
  int32_t code = tsdbReaderCreate(pVnode, pCond, ppReader, 4096, idstr);
  if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
3308 3309
    goto _err;
  }
H
Hongze Cheng 已提交
3310

3311
  // check for query time window
H
Haojun Liao 已提交
3312
  STsdbReader* pReader = *ppReader;
3313
  if (isEmptyQueryTimeWindow(&pReader->window)) {
H
Haojun Liao 已提交
3314 3315 3316
    tsdbDebug("%p query window not overlaps with the data set, no result returned, %s", pReader, pReader->idStr);
    return TSDB_CODE_SUCCESS;
  }
H
Hongze Cheng 已提交
3317

3318 3319 3320
  if (pCond->type == TIMEWINDOW_RANGE_EXTERNAL) {
    // update the SQueryTableDataCond to create inner reader
    STimeWindow w = pCond->twindows;
3321
    int32_t     order = pCond->order;
3322 3323 3324 3325 3326 3327 3328 3329 3330 3331
    if (order == TSDB_ORDER_ASC) {
      pCond->twindows.ekey = pCond->twindows.skey;
      pCond->twindows.skey = INT64_MIN;
      pCond->order = TSDB_ORDER_DESC;
    } else {
      pCond->twindows.skey = pCond->twindows.ekey;
      pCond->twindows.ekey = INT64_MAX;
      pCond->order = TSDB_ORDER_ASC;
    }

3332
    // here we only need one more row, so the capacity is set to be ONE.
3333 3334 3335 3336 3337 3338 3339 3340
    code = tsdbReaderCreate(pVnode, pCond, &pReader->innerReader[0], 1, idstr);
    if (code != TSDB_CODE_SUCCESS) {
      goto _err;
    }

    if (order == TSDB_ORDER_ASC) {
      pCond->twindows.skey = w.ekey;
      pCond->twindows.ekey = INT64_MAX;
3341
    } else {
3342 3343 3344 3345 3346 3347 3348 3349 3350 3351
      pCond->twindows.skey = INT64_MIN;
      pCond->twindows.ekey = w.ekey;
    }
    code = tsdbReaderCreate(pVnode, pCond, &pReader->innerReader[1], 1, idstr);
    if (code != TSDB_CODE_SUCCESS) {
      goto _err;
    }
  }

  if (pCond->suid != 0) {
wmmhello's avatar
wmmhello 已提交
3352
    pReader->pSchema = metaGetTbTSchema(pReader->pTsdb->pVnode->pMeta, pReader->suid, pCond->schemaVersion);
3353 3354
  } else if (taosArrayGetSize(pTableList) > 0) {
    STableKeyInfo* pKey = taosArrayGet(pTableList, 0);
wmmhello's avatar
wmmhello 已提交
3355
    pReader->pSchema = metaGetTbTSchema(pReader->pTsdb->pVnode->pMeta, pKey->uid, pCond->schemaVersion);
3356 3357
  }

3358 3359
  int32_t numOfTables = taosArrayGetSize(pTableList);
  pReader->status.pTableMap = createDataBlockScanInfo(pReader, pTableList->pData, numOfTables);
H
Haojun Liao 已提交
3360 3361 3362
  if (pReader->status.pTableMap == NULL) {
    tsdbReaderClose(pReader);
    *ppReader = NULL;
H
Haojun Liao 已提交
3363

H
Haojun Liao 已提交
3364 3365 3366
    code = TSDB_CODE_TDB_OUT_OF_MEMORY;
    goto _err;
  }
H
Hongze Cheng 已提交
3367

H
Hongze Cheng 已提交
3368
  code = tsdbTakeReadSnap(pReader->pTsdb, &pReader->pReadSnap);
3369 3370 3371
  if (code != TSDB_CODE_SUCCESS) {
    goto _err;
  }
H
Hongze Cheng 已提交
3372

3373 3374
  if (pReader->type == TIMEWINDOW_RANGE_CONTAINED) {
    SDataBlockIter* pBlockIter = &pReader->status.blockIter;
3375

3376
    initFilesetIterator(&pReader->status.fileIter, pReader->pReadSnap->fs.aDFileSet, pReader);
3377
    resetDataBlockIterator(&pReader->status.blockIter, pReader->order);
3378 3379 3380 3381 3382 3383 3384 3385 3386 3387

    // no data in files, let's try buffer in memory
    if (pReader->status.fileIter.numOfFiles == 0) {
      pReader->status.loadFromFile = false;
    } else {
      code = initForFirstBlockInFile(pReader, pBlockIter);
      if (code != TSDB_CODE_SUCCESS) {
        return code;
      }
    }
3388
  } else {
3389
    STsdbReader*    pPrevReader = pReader->innerReader[0];
3390 3391
    SDataBlockIter* pBlockIter = &pPrevReader->status.blockIter;

3392 3393 3394 3395 3396
    code = tsdbTakeReadSnap(pPrevReader->pTsdb, &pPrevReader->pReadSnap);
    if (code != TSDB_CODE_SUCCESS) {
      goto _err;
    }

3397
    initFilesetIterator(&pPrevReader->status.fileIter, pPrevReader->pReadSnap->fs.aDFileSet, pPrevReader);
3398
    resetDataBlockIterator(&pPrevReader->status.blockIter, pPrevReader->order);
3399 3400 3401 3402 3403 3404 3405 3406 3407

    // no data in files, let's try buffer in memory
    if (pPrevReader->status.fileIter.numOfFiles == 0) {
      pPrevReader->status.loadFromFile = false;
    } else {
      code = initForFirstBlockInFile(pPrevReader, pBlockIter);
      if (code != TSDB_CODE_SUCCESS) {
        return code;
      }
3408 3409 3410
    }
  }

3411
  tsdbDebug("%p total numOfTable:%d in this query %s", pReader, numOfTables, pReader->idStr);
H
Hongze Cheng 已提交
3412
  return code;
H
Hongze Cheng 已提交
3413 3414

_err:
S
Shengliang Guan 已提交
3415
  tsdbError("failed to create data reader, code:%s %s", tstrerror(code), pReader->idStr);
H
Hongze Cheng 已提交
3416
  return code;
H
refact  
Hongze Cheng 已提交
3417 3418 3419
}

void tsdbReaderClose(STsdbReader* pReader) {
3420 3421
  if (pReader == NULL) {
    return;
3422
  }
H
refact  
Hongze Cheng 已提交
3423

3424
  SBlockLoadSuppInfo* pSupInfo = &pReader->suppInfo;
H
Hongze Cheng 已提交
3425
  tsdbUntakeReadSnap(pReader->pTsdb, pReader->pReadSnap);
H
Hongze Cheng 已提交
3426

3427 3428 3429 3430
  taosMemoryFreeClear(pSupInfo->plist);
  taosMemoryFree(pSupInfo->colIds);

  taosArrayDestroy(pSupInfo->pColAgg);
L
Liu Jicong 已提交
3431
  for (int32_t i = 0; i < blockDataGetNumOfCols(pReader->pResBlock); ++i) {
3432 3433 3434 3435 3436
    if (pSupInfo->buildBuf[i] != NULL) {
      taosMemoryFreeClear(pSupInfo->buildBuf[i]);
    }
  }
  taosMemoryFree(pSupInfo->buildBuf);
H
Hongze Cheng 已提交
3437
  tBlockDataDestroy(&pReader->status.fileBlockData, true);
3438 3439

  cleanupDataBlockIterator(&pReader->status.blockIter);
3440 3441

  size_t numOfTables = taosHashGetSize(pReader->status.pTableMap);
3442
  destroyBlockScanInfo(pReader->status.pTableMap);
3443
  blockDataDestroy(pReader->pResBlock);
3444

H
Haojun Liao 已提交
3445 3446 3447
  if (pReader->pFileReader != NULL) {
    tsdbDataFReaderClose(&pReader->pFileReader);
  }
H
refact  
Hongze Cheng 已提交
3448

3449 3450
  taosMemoryFree(pReader->status.uidCheckInfo.tableUidList);

H
Haojun Liao 已提交
3451 3452 3453 3454 3455 3456 3457
  SFilesetIter* pFilesetIter = &pReader->status.fileIter;
  if (pFilesetIter->pLastBlockReader != NULL) {
    tBlockDataDestroy(&pFilesetIter->pLastBlockReader->lastBlockData, true);
    taosArrayDestroy(pFilesetIter->pLastBlockReader->pBlockL);
    taosMemoryFree(pFilesetIter->pLastBlockReader);
  }

3458
  SIOCostSummary* pCost = &pReader->cost;
H
refact  
Hongze Cheng 已提交
3459

3460
  tsdbDebug("%p :io-cost summary: head-file:%" PRIu64 ", head-file time:%.2f ms, SMA:%" PRId64
3461 3462
            " SMA-time:%.2f ms, fileBlocks:%" PRId64
            ", fileBlocks-time:%.2f ms, "
3463 3464 3465 3466 3467
            "build in-memory-block-time:%.2f ms, lastBlocks:%" PRId64
            ", lastBlocks-time:%.2f ms, STableBlockScanInfo size:%.2f Kb %s",
            pReader, pCost->headFileLoad, pCost->headFileLoadTime, pCost->smaDataLoad, pCost->smaLoadTime,
            pCost->numOfBlocks, pCost->blockLoadTime, pCost->buildmemBlock, pCost->lastBlockLoad,
            pCost->lastBlockLoadTime, numOfTables * sizeof(STableBlockScanInfo) / 1000.0, pReader->idStr);
H
refact  
Hongze Cheng 已提交
3468

3469 3470
  taosMemoryFree(pReader->idStr);
  taosMemoryFree(pReader->pSchema);
3471 3472 3473
  if (pReader->pMemSchema != pReader->pSchema) {
    taosMemoryFree(pReader->pMemSchema);
  }
3474
  taosMemoryFreeClear(pReader);
H
refact  
Hongze Cheng 已提交
3475 3476
}

3477
static bool doTsdbNextDataBlock(STsdbReader* pReader) {
H
Haojun Liao 已提交
3478
  // cleanup the data that belongs to the previous data block
3479 3480
  SSDataBlock* pBlock = pReader->pResBlock;
  blockDataCleanup(pBlock);
H
Hongze Cheng 已提交
3481

3482
  SReaderStatus* pStatus = &pReader->status;
H
Haojun Liao 已提交
3483

3484 3485 3486 3487 3488
  if (pStatus->loadFromFile) {
    int32_t code = buildBlockFromFiles(pReader);
    if (code != TSDB_CODE_SUCCESS) {
      return false;
    }
3489

3490 3491 3492
    if (pBlock->info.rows > 0) {
      return true;
    } else {
H
Haojun Liao 已提交
3493
      buildBlockFromBufferSequentially(pReader);
3494
      return pBlock->info.rows > 0;
H
Haojun Liao 已提交
3495
    }
3496 3497 3498
  } else {  // no data in files, let's try the buffer
    buildBlockFromBufferSequentially(pReader);
    return pBlock->info.rows > 0;
H
Haojun Liao 已提交
3499
  }
3500

3501
  return false;
H
refact  
Hongze Cheng 已提交
3502 3503
}

3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540
bool tsdbNextDataBlock(STsdbReader* pReader) {
  if (isEmptyQueryTimeWindow(&pReader->window)) {
    return false;
  }

  if (pReader->innerReader[0] != NULL) {
    bool ret = doTsdbNextDataBlock(pReader->innerReader[0]);
    if (ret) {
      pReader->step = EXTERNAL_ROWS_PREV;
      return ret;
    }

    tsdbReaderClose(pReader->innerReader[0]);
    pReader->innerReader[0] = NULL;
  }

  pReader->step = EXTERNAL_ROWS_MAIN;
  bool ret = doTsdbNextDataBlock(pReader);
  if (ret) {
    return ret;
  }

  if (pReader->innerReader[1] != NULL) {
    bool ret1 = doTsdbNextDataBlock(pReader->innerReader[1]);
    if (ret1) {
      pReader->step = EXTERNAL_ROWS_NEXT;
      return ret1;
    }

    tsdbReaderClose(pReader->innerReader[1]);
    pReader->innerReader[1] = NULL;
  }

  return false;
}

static void setBlockInfo(STsdbReader* pReader, SDataBlockInfo* pDataBlockInfo) {
3541 3542 3543 3544
  ASSERT(pDataBlockInfo != NULL && pReader != NULL);
  pDataBlockInfo->rows = pReader->pResBlock->info.rows;
  pDataBlockInfo->uid = pReader->pResBlock->info.uid;
  pDataBlockInfo->window = pReader->pResBlock->info.window;
H
Hongze Cheng 已提交
3545 3546
}

3547 3548
void tsdbRetrieveDataBlockInfo(STsdbReader* pReader, SDataBlockInfo* pDataBlockInfo) {
  if (pReader->type == TIMEWINDOW_RANGE_EXTERNAL) {
3549
    if (pReader->step == EXTERNAL_ROWS_MAIN) {
3550
      setBlockInfo(pReader, pDataBlockInfo);
3551
    } else if (pReader->step == EXTERNAL_ROWS_PREV) {
3552 3553 3554 3555 3556 3557 3558 3559 3560
      setBlockInfo(pReader->innerReader[0], pDataBlockInfo);
    } else {
      setBlockInfo(pReader->innerReader[1], pDataBlockInfo);
    }
  } else {
    setBlockInfo(pReader, pDataBlockInfo);
  }
}

3561
int32_t tsdbRetrieveDatablockSMA(STsdbReader* pReader, SColumnDataAgg*** pBlockStatis, bool* allHave) {
H
Hongze Cheng 已提交
3562
  int32_t code = 0;
3563
  *allHave = false;
H
Hongze Cheng 已提交
3564

3565
  if (pReader->type == TIMEWINDOW_RANGE_EXTERNAL) {
3566 3567 3568 3569
    *pBlockStatis = NULL;
    return TSDB_CODE_SUCCESS;
  }

3570
  // there is no statistics data for composed block
3571 3572 3573 3574
  if (pReader->status.composedDataBlock) {
    *pBlockStatis = NULL;
    return TSDB_CODE_SUCCESS;
  }
H
Hongze Cheng 已提交
3575

3576
  SFileDataBlockInfo* pFBlock = getCurrentBlockInfo(&pReader->status.blockIter);
H
Hongze Cheng 已提交
3577

3578
  SBlock* pBlock = getCurrentBlock(&pReader->status.blockIter);
3579
  int64_t stime = taosGetTimestampUs();
H
Hongze Cheng 已提交
3580

3581 3582
  SBlockLoadSuppInfo* pSup = &pReader->suppInfo;

3583
  if (tBlockHasSma(pBlock)) {
H
Hongze Cheng 已提交
3584
    code = tsdbReadBlockSma(pReader->pFileReader, pBlock, pSup->pColAgg);
3585
    if (code != TSDB_CODE_SUCCESS) {
3586 3587
      tsdbDebug("vgId:%d, failed to load block SMA for uid %" PRIu64 ", code:%s, %s", 0, pFBlock->uid, tstrerror(code),
                pReader->idStr);
3588 3589
      return code;
    }
3590 3591 3592
  } else {
    *pBlockStatis = NULL;
    return TSDB_CODE_SUCCESS;
3593
  }
H
Hongze Cheng 已提交
3594

3595
  *allHave = true;
H
Hongze Cheng 已提交
3596

3597 3598
  // always load the first primary timestamp column data
  SColumnDataAgg* pTsAgg = &pSup->tsColAgg;
3599

3600 3601
  pTsAgg->numOfNull = 0;
  pTsAgg->colId = PRIMARYKEY_TIMESTAMP_COL_ID;
3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617
  pTsAgg->min = pReader->pResBlock->info.window.skey;
  pTsAgg->max = pReader->pResBlock->info.window.ekey;
  pSup->plist[0] = pTsAgg;

  // update the number of NULL data rows
  size_t numOfCols = blockDataGetNumOfCols(pReader->pResBlock);

  int32_t i = 0, j = 0;
  while (j < numOfCols && i < taosArrayGetSize(pSup->pColAgg)) {
    SColumnDataAgg* pAgg = taosArrayGet(pSup->pColAgg, i);
    if (pAgg->colId == pSup->colIds[j]) {
      if (IS_BSMA_ON(&(pReader->pSchema->columns[i]))) {
        pSup->plist[j] = pAgg;
      } else {
        *allHave = false;
      }
3618 3619
      i += 1;
      j += 1;
3620 3621 3622 3623 3624 3625 3626
    } else if (pAgg->colId < pSup->colIds[j]) {
      i += 1;
    } else if (pSup->colIds[j] < pAgg->colId) {
      j += 1;
    }
  }

3627
  double elapsed = (taosGetTimestampUs() - stime) / 1000.0;
3628
  pReader->cost.smaLoadTime += elapsed;
3629
  pReader->cost.smaDataLoad += 1;
3630 3631 3632

  *pBlockStatis = pSup->plist;

3633
  tsdbDebug("vgId:%d, succeed to load block SMA for uid %" PRIu64 ", elapsed time:%.2f ms, %s", 0, pFBlock->uid,
3634 3635
            elapsed, pReader->idStr);

H
Hongze Cheng 已提交
3636
  return code;
H
Hongze Cheng 已提交
3637 3638
}

3639
static SArray* doRetrieveDataBlock(STsdbReader* pReader) {
H
Haojun Liao 已提交
3640 3641 3642
  SReaderStatus* pStatus = &pReader->status;

  if (pStatus->composedDataBlock) {
3643
    return pReader->pResBlock->pDataBlock;
3644
  }
3645

3646
  SFileDataBlockInfo*  pFBlock = getCurrentBlockInfo(&pStatus->blockIter);
3647
  STableBlockScanInfo* pBlockScanInfo = taosHashGet(pStatus->pTableMap, &pFBlock->uid, sizeof(pFBlock->uid));
3648

H
Haojun Liao 已提交
3649
  tBlockDataReset(&pStatus->fileBlockData);
3650 3651
  int32_t code = tBlockDataInit(&pStatus->fileBlockData, pReader->suid, pBlockScanInfo->uid, pReader->pSchema);
  if (code != TSDB_CODE_SUCCESS) {
3652 3653
    terrno = code;
    return NULL;
3654 3655 3656
  }

  code = doLoadFileBlockData(pReader, &pStatus->blockIter, &pStatus->fileBlockData);
3657
  if (code != TSDB_CODE_SUCCESS) {
H
Hongze Cheng 已提交
3658
    tBlockDataDestroy(&pStatus->fileBlockData, 1);
3659 3660
    terrno = code;
    return NULL;
3661
  }
3662 3663 3664

  copyBlockDataToSDataBlock(pReader, pBlockScanInfo);
  return pReader->pResBlock->pDataBlock;
H
Hongze Cheng 已提交
3665 3666
}

3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678
SArray* tsdbRetrieveDataBlock(STsdbReader* pReader, SArray* pIdList) {
  if (pReader->type == TIMEWINDOW_RANGE_EXTERNAL) {
    if (pReader->step == EXTERNAL_ROWS_PREV) {
      return doRetrieveDataBlock(pReader->innerReader[0]);
    } else if (pReader->step == EXTERNAL_ROWS_NEXT) {
      return doRetrieveDataBlock(pReader->innerReader[1]);
    }
  }

  return doRetrieveDataBlock(pReader);
}

H
Haojun Liao 已提交
3679
int32_t tsdbReaderReset(STsdbReader* pReader, SQueryTableDataCond* pCond) {
3680 3681 3682
  if (isEmptyQueryTimeWindow(&pReader->window)) {
    return TSDB_CODE_SUCCESS;
  }
H
Hongze Cheng 已提交
3683

L
Liu Jicong 已提交
3684
  pReader->order = pCond->order;
3685
  pReader->type = TIMEWINDOW_RANGE_CONTAINED;
3686
  pReader->status.loadFromFile = true;
dengyihao's avatar
dengyihao 已提交
3687
  pReader->status.pTableIter = NULL;
H
Haojun Liao 已提交
3688
  pReader->window = updateQueryTimeWindow(pReader->pTsdb, &pCond->twindows);
H
Hongze Cheng 已提交
3689

3690
  // allocate buffer in order to load data blocks from file
3691
  memset(&pReader->suppInfo.tsColAgg, 0, sizeof(SColumnDataAgg));
3692 3693
  memset(pReader->suppInfo.plist, 0, POINTER_BYTES);

3694
  pReader->suppInfo.tsColAgg.colId = PRIMARYKEY_TIMESTAMP_COL_ID;
3695
  tsdbDataFReaderClose(&pReader->pFileReader);
3696

3697
  int32_t numOfTables = taosHashGetSize(pReader->status.pTableMap);
L
Liu Jicong 已提交
3698 3699
  tsdbDataFReaderClose(&pReader->pFileReader);

3700
  initFilesetIterator(&pReader->status.fileIter, pReader->pReadSnap->fs.aDFileSet, pReader);
3701
  resetDataBlockIterator(&pReader->status.blockIter, pReader->order);
3702
  resetDataBlockScanInfo(pReader->status.pTableMap);
3703

3704
  int32_t         code = 0;
3705 3706
  SDataBlockIter* pBlockIter = &pReader->status.blockIter;

3707 3708 3709 3710 3711 3712
  // no data in files, let's try buffer in memory
  if (pReader->status.fileIter.numOfFiles == 0) {
    pReader->status.loadFromFile = false;
  } else {
    code = initForFirstBlockInFile(pReader, pBlockIter);
    if (code != TSDB_CODE_SUCCESS) {
3713 3714
      tsdbError("%p reset reader failed, numOfTables:%d, query range:%" PRId64 " - %" PRId64 " in query %s", pReader,
                numOfTables, pReader->window.skey, pReader->window.ekey, pReader->idStr);
3715 3716 3717
      return code;
    }
  }
H
Hongze Cheng 已提交
3718

dengyihao's avatar
dengyihao 已提交
3719 3720
  tsdbDebug("%p reset reader, suid:%" PRIu64 ", numOfTables:%d, query range:%" PRId64 " - %" PRId64 " in query %s",
            pReader, pReader->suid, numOfTables, pReader->window.skey, pReader->window.ekey, pReader->idStr);
3721

3722
  return code;
H
Hongze Cheng 已提交
3723
}
H
Hongze Cheng 已提交
3724

3725 3726 3727
static int32_t getBucketIndex(int32_t startRow, int32_t bucketRange, int32_t numOfRows) {
  return (numOfRows - startRow) / bucketRange;
}
H
Hongze Cheng 已提交
3728

3729 3730 3731 3732
int32_t tsdbGetFileBlocksDistInfo(STsdbReader* pReader, STableBlockDistInfo* pTableBlockInfo) {
  int32_t code = TSDB_CODE_SUCCESS;
  pTableBlockInfo->totalSize = 0;
  pTableBlockInfo->totalRows = 0;
H
Hongze Cheng 已提交
3733

3734 3735
  // find the start data block in file
  SReaderStatus* pStatus = &pReader->status;
H
Hongze Cheng 已提交
3736

3737 3738 3739
  STsdbCfg* pc = &pReader->pTsdb->pVnode->config.tsdbCfg;
  pTableBlockInfo->defMinRows = pc->minRows;
  pTableBlockInfo->defMaxRows = pc->maxRows;
H
Hongze Cheng 已提交
3740

3741
  int32_t bucketRange = ceil((pc->maxRows - pc->minRows) / 20.0);
H
Hongze Cheng 已提交
3742

3743
  pTableBlockInfo->numOfFiles += 1;
H
Hongze Cheng 已提交
3744

3745 3746
  int32_t numOfTables = (int32_t)taosHashGetSize(pStatus->pTableMap);
  int     defaultRows = 4096;
H
Hongze Cheng 已提交
3747

3748 3749
  SDataBlockIter* pBlockIter = &pStatus->blockIter;
  pTableBlockInfo->numOfFiles += pStatus->fileIter.numOfFiles;
H
Haojun Liao 已提交
3750

3751 3752
  if (pBlockIter->numOfBlocks > 0) {
    pTableBlockInfo->numOfBlocks += pBlockIter->numOfBlocks;
H
Haojun Liao 已提交
3753
  }
H
Hongze Cheng 已提交
3754

3755
  pTableBlockInfo->numOfTables = numOfTables;
3756
  bool hasNext = (pBlockIter->numOfBlocks > 0);
H
Hongze Cheng 已提交
3757

3758 3759
  while (true) {
    if (hasNext) {
H
Haojun Liao 已提交
3760
      SBlock* pBlock = getCurrentBlock(pBlockIter);
H
Hongze Cheng 已提交
3761

3762 3763
      int32_t numOfRows = pBlock->nRow;
      pTableBlockInfo->totalRows += numOfRows;
H
Hongze Cheng 已提交
3764

3765 3766 3767
      if (numOfRows > pTableBlockInfo->maxRows) {
        pTableBlockInfo->maxRows = numOfRows;
      }
H
refact  
Hongze Cheng 已提交
3768

3769 3770 3771
      if (numOfRows < pTableBlockInfo->minRows) {
        pTableBlockInfo->minRows = numOfRows;
      }
H
refact  
Hongze Cheng 已提交
3772

3773 3774 3775
      if (numOfRows < defaultRows) {
        pTableBlockInfo->numOfSmallBlocks += 1;
      }
H
refact  
Hongze Cheng 已提交
3776

3777 3778
      int32_t bucketIndex = getBucketIndex(pTableBlockInfo->defMinRows, bucketRange, numOfRows);
      pTableBlockInfo->blockRowsHisto[bucketIndex]++;
3779 3780

      hasNext = blockIteratorNext(&pStatus->blockIter);
3781 3782 3783 3784 3785
    } else {
      code = initForFirstBlockInFile(pReader, pBlockIter);
      if ((code != TSDB_CODE_SUCCESS) || (pReader->status.loadFromFile == false)) {
        break;
      }
H
refact  
Hongze Cheng 已提交
3786

3787 3788
      pTableBlockInfo->numOfBlocks += pBlockIter->numOfBlocks;
      hasNext = (pBlockIter->numOfBlocks > 0);
3789
    }
H
refact  
Hongze Cheng 已提交
3790

H
Hongze Cheng 已提交
3791 3792
    //    tsdbDebug("%p %d blocks found in file for %d table(s), fid:%d, %s", pReader, numOfBlocks, numOfTables,
    //              pReader->pFileGroup->fid, pReader->idStr);
3793
  }
H
Hongze Cheng 已提交
3794

H
refact  
Hongze Cheng 已提交
3795 3796
  return code;
}
H
Hongze Cheng 已提交
3797

H
refact  
Hongze Cheng 已提交
3798
int64_t tsdbGetNumOfRowsInMemTable(STsdbReader* pReader) {
3799
  int64_t rows = 0;
H
Hongze Cheng 已提交
3800

3801 3802
  SReaderStatus* pStatus = &pReader->status;
  pStatus->pTableIter = taosHashIterate(pStatus->pTableMap, NULL);
H
Hongze Cheng 已提交
3803

3804 3805 3806 3807 3808
  while (pStatus->pTableIter != NULL) {
    STableBlockScanInfo* pBlockScanInfo = pStatus->pTableIter;

    STbData* d = NULL;
    if (pReader->pTsdb->mem != NULL) {
H
Hongze Cheng 已提交
3809
      d = tsdbGetTbDataFromMemTable(pReader->pReadSnap->pMem, pReader->suid, pBlockScanInfo->uid);
3810 3811 3812 3813 3814 3815 3816
      if (d != NULL) {
        rows += tsdbGetNRowsInTbData(d);
      }
    }

    STbData* di = NULL;
    if (pReader->pTsdb->imem != NULL) {
H
Hongze Cheng 已提交
3817
      di = tsdbGetTbDataFromMemTable(pReader->pReadSnap->pIMem, pReader->suid, pBlockScanInfo->uid);
3818 3819 3820 3821 3822 3823 3824 3825
      if (di != NULL) {
        rows += tsdbGetNRowsInTbData(di);
      }
    }

    // current table is exhausted, let's try the next table
    pStatus->pTableIter = taosHashIterate(pStatus->pTableMap, pStatus->pTableIter);
  }
H
Hongze Cheng 已提交
3826

H
refact  
Hongze Cheng 已提交
3827
  return rows;
H
Hongze Cheng 已提交
3828
}
D
dapan1121 已提交
3829

L
Liu Jicong 已提交
3830
int32_t tsdbGetTableSchema(SVnode* pVnode, int64_t uid, STSchema** pSchema, int64_t* suid) {
D
dapan1121 已提交
3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842
  int32_t sversion = 1;

  SMetaReader mr = {0};
  metaReaderInit(&mr, pVnode->pMeta, 0);
  int32_t code = metaGetTableEntryByUid(&mr, uid);
  if (code != TSDB_CODE_SUCCESS) {
    terrno = TSDB_CODE_TDB_INVALID_TABLE_ID;
    metaReaderClear(&mr);
    return terrno;
  }

  *suid = 0;
L
Liu Jicong 已提交
3843

D
dapan1121 已提交
3844
  if (mr.me.type == TSDB_CHILD_TABLE) {
D
dapan1121 已提交
3845
    tDecoderClear(&mr.coder);
D
dapan1121 已提交
3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860
    *suid = mr.me.ctbEntry.suid;
    code = metaGetTableEntryByUid(&mr, *suid);
    if (code != TSDB_CODE_SUCCESS) {
      terrno = TSDB_CODE_TDB_INVALID_TABLE_ID;
      metaReaderClear(&mr);
      return terrno;
    }
    sversion = mr.me.stbEntry.schemaRow.version;
  } else {
    ASSERT(mr.me.type == TSDB_NORMAL_TABLE);
    sversion = mr.me.ntbEntry.schemaRow.version;
  }

  metaReaderClear(&mr);
  *pSchema = metaGetTbTSchema(pVnode->pMeta, uid, sversion);
L
Liu Jicong 已提交
3861

D
dapan1121 已提交
3862 3863
  return TSDB_CODE_SUCCESS;
}
H
Hongze Cheng 已提交
3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893

int32_t tsdbTakeReadSnap(STsdb* pTsdb, STsdbReadSnap** ppSnap) {
  int32_t code = 0;

  // alloc
  *ppSnap = (STsdbReadSnap*)taosMemoryCalloc(1, sizeof(STsdbReadSnap));
  if (*ppSnap == NULL) {
    code = TSDB_CODE_OUT_OF_MEMORY;
    goto _exit;
  }

  // lock
  code = taosThreadRwlockRdlock(&pTsdb->rwLock);
  if (code) {
    code = TAOS_SYSTEM_ERROR(code);
    goto _exit;
  }

  // take snapshot
  (*ppSnap)->pMem = pTsdb->mem;
  (*ppSnap)->pIMem = pTsdb->imem;

  if ((*ppSnap)->pMem) {
    tsdbRefMemTable((*ppSnap)->pMem);
  }

  if ((*ppSnap)->pIMem) {
    tsdbRefMemTable((*ppSnap)->pIMem);
  }

H
Hongze Cheng 已提交
3894
  // fs
H
Hongze Cheng 已提交
3895 3896 3897 3898 3899
  code = tsdbFSRef(pTsdb, &(*ppSnap)->fs);
  if (code) {
    taosThreadRwlockUnlock(&pTsdb->rwLock);
    goto _exit;
  }
H
Hongze Cheng 已提交
3900 3901 3902 3903 3904 3905 3906 3907

  // unlock
  code = taosThreadRwlockUnlock(&pTsdb->rwLock);
  if (code) {
    code = TAOS_SYSTEM_ERROR(code);
    goto _exit;
  }

S
Shengliang Guan 已提交
3908
  tsdbTrace("vgId:%d, take read snapshot", TD_VID(pTsdb->pVnode));
H
Hongze Cheng 已提交
3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922
_exit:
  return code;
}

void tsdbUntakeReadSnap(STsdb* pTsdb, STsdbReadSnap* pSnap) {
  if (pSnap) {
    if (pSnap->pMem) {
      tsdbUnrefMemTable(pSnap->pMem);
    }

    if (pSnap->pIMem) {
      tsdbUnrefMemTable(pSnap->pIMem);
    }

H
Hongze Cheng 已提交
3923
    tsdbFSUnref(pTsdb, &pSnap->fs);
H
Hongze Cheng 已提交
3924
    taosMemoryFree(pSnap);
H
Hongze Cheng 已提交
3925
  }
H
Hongze Cheng 已提交
3926

S
Shengliang Guan 已提交
3927
  tsdbTrace("vgId:%d, untake read snapshot", TD_VID(pTsdb->pVnode));
H
Hongze Cheng 已提交
3928
}