tsdbRead.c 165.1 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

H
Hongze Cheng 已提交
19
#define ASCENDING_TRAVERSE(o) (o == TSDB_ORDER_ASC)
H
Hongze Cheng 已提交
20

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

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

33 34
typedef struct {
  int32_t numOfBlocks;
35
  int32_t numOfLastFiles;
36 37
} SBlockNumber;

38
typedef struct SBlockIndex {
39 40
  int32_t     ordinalIndex;
  int64_t     inFileOffset;
H
Haojun Liao 已提交
41
  STimeWindow window;  // todo replace it with overlap flag.
42 43
} SBlockIndex;

H
Haojun Liao 已提交
44
typedef struct STableBlockScanInfo {
dengyihao's avatar
dengyihao 已提交
45 46
  uint64_t  uid;
  TSKEY     lastKey;
47
  TSKEY     lastKeyInStt;       // last accessed key in stt
H
Hongze Cheng 已提交
48
  SMapData  mapData;            // block info (compressed)
49
  SArray*   pBlockList;         // block data index list, SArray<SBlockIndex>
H
Hongze Cheng 已提交
50 51 52 53 54 55
  SIterInfo iter;               // mem buffer skip list iterator
  SIterInfo iiter;              // imem buffer skip list iterator
  SArray*   delSkyline;         // delete info for this table
  int32_t   fileDelIndex;       // file block delete index
  int32_t   lastBlockDelIndex;  // delete index for last block
  bool      iterInit;           // whether to initialize the in-memory skip list iterator or not
H
Haojun Liao 已提交
56 57 58
} STableBlockScanInfo;

typedef struct SBlockOrderWrapper {
dengyihao's avatar
dengyihao 已提交
59
  int64_t uid;
60
  int64_t offset;
H
Haojun Liao 已提交
61
} SBlockOrderWrapper;
H
Hongze Cheng 已提交
62 63

typedef struct SBlockOrderSupporter {
64 65 66 67
  SBlockOrderWrapper** pDataBlockInfo;
  int32_t*             indexPerTable;
  int32_t*             numOfBlocksPerTable;
  int32_t              numOfTables;
H
Hongze Cheng 已提交
68 69 70
} SBlockOrderSupporter;

typedef struct SIOCostSummary {
71 72 73
  int64_t numOfBlocks;
  double  blockLoadTime;
  double  buildmemBlock;
74
  int64_t headFileLoad;
75
  double  headFileLoadTime;
76
  int64_t smaDataLoad;
77
  double  smaLoadTime;
78 79
  int64_t lastBlockLoad;
  double  lastBlockLoadTime;
H
Haojun Liao 已提交
80 81
  int64_t composedBlocks;
  double  buildComposedBlockTime;
H
Haojun Liao 已提交
82
  double  createScanInfoList;
X
Xiaoyu Wang 已提交
83 84 85
  //  double  getTbFromMemTime;
  //  double  getTbFromIMemTime;
  double initDelSkylineIterTime;
H
Hongze Cheng 已提交
86 87 88
} SIOCostSummary;

typedef struct SBlockLoadSuppInfo {
89 90 91 92 93 94 95
  SArray*        pColAgg;
  SColumnDataAgg tsColAgg;
  int16_t*       colId;
  int16_t*       slotId;
  int32_t        numOfCols;
  char**         buildBuf;  // build string tmp buffer, todo remove it later after all string format being updated.
  bool           smaValid;  // the sma on all queried columns are activated
H
Hongze Cheng 已提交
96 97
} SBlockLoadSuppInfo;

98
typedef struct SLastBlockReader {
H
Hongze Cheng 已提交
99 100 101 102 103
  STimeWindow        window;
  SVersionRange      verRange;
  int32_t            order;
  uint64_t           uid;
  SMergeTree         mergeTree;
104
  SSttBlockLoadInfo* pInfo;
105 106
} SLastBlockReader;

107
typedef struct SFilesetIter {
H
Hongze Cheng 已提交
108 109 110
  int32_t           numOfFiles;  // number of total files
  int32_t           index;       // current accessed index in the list
  SArray*           pFileList;   // data file list
111
  int32_t           order;
H
Hongze Cheng 已提交
112
  SLastBlockReader* pLastBlockReader;  // last file block reader
113
} SFilesetIter;
H
Haojun Liao 已提交
114 115

typedef struct SFileDataBlockInfo {
116
  // index position in STableBlockScanInfo in order to check whether neighbor block overlaps with it
dengyihao's avatar
dengyihao 已提交
117
  uint64_t uid;
118
  int32_t  tbBlockIdx;
H
Haojun Liao 已提交
119 120 121
} SFileDataBlockInfo;

typedef struct SDataBlockIter {
122
  int32_t   numOfBlocks;
123
  int32_t   index;
H
Hongze Cheng 已提交
124
  SArray*   blockList;  // SArray<SFileDataBlockInfo>
125
  int32_t   order;
H
Hongze Cheng 已提交
126
  SDataBlk  block;  // current SDataBlk data
127
  SHashObj* pTableMap;
H
Haojun Liao 已提交
128 129 130
} SDataBlockIter;

typedef struct SFileBlockDumpInfo {
dengyihao's avatar
dengyihao 已提交
131 132 133 134
  int32_t totalRows;
  int32_t rowIndex;
  int64_t lastKey;
  bool    allDumped;
H
Haojun Liao 已提交
135 136
} SFileBlockDumpInfo;

137
typedef struct STableUidList {
138 139
  uint64_t* tableUidList;  // access table uid list in uid ascending order list
  int32_t   currentIndex;  // index in table uid list
140
} STableUidList;
141

H
Haojun Liao 已提交
142
typedef struct SReaderStatus {
H
Hongze Cheng 已提交
143 144 145
  bool                  loadFromFile;       // check file stage
  bool                  composedDataBlock;  // the returned data block is a composed block or not
  SHashObj*             pTableMap;          // SHash<STableBlockScanInfo>
146
  STableBlockScanInfo** pTableIter;         // table iterator used in building in-memory buffer data blocks.
147
  STableUidList         uidList;            // check tables in uid order, to avoid the repeatly load of blocks in STT.
H
Hongze Cheng 已提交
148 149 150 151 152
  SFileBlockDumpInfo    fBlockDumpInfo;
  SDFileSet*            pCurrentFileset;  // current opened file set
  SBlockData            fileBlockData;
  SFilesetIter          fileIter;
  SDataBlockIter        blockIter;
H
Haojun Liao 已提交
153 154
} SReaderStatus;

155
typedef struct SBlockInfoBuf {
H
Hongze Cheng 已提交
156 157 158
  int32_t currentIndex;
  SArray* pData;
  int32_t numPerBucket;
D
dapan1121 已提交
159
  int32_t numOfTables;
160 161
} SBlockInfoBuf;

H
Hongze Cheng 已提交
162
struct STsdbReader {
H
Haojun Liao 已提交
163
  STsdb*             pTsdb;
164 165 166
  SVersionRange      verRange;
  TdThreadMutex      readerMutex;
  bool               suspended;
H
Haojun Liao 已提交
167 168
  uint64_t           suid;
  int16_t            order;
H
Haojun Liao 已提交
169
  bool               freeBlock;
H
Haojun Liao 已提交
170 171 172 173
  STimeWindow        window;  // the primary query time window that applies to all queries
  SSDataBlock*       pResBlock;
  int32_t            capacity;
  SReaderStatus      status;
174 175
  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 已提交
176
  SBlockLoadSuppInfo suppInfo;
H
Hongze Cheng 已提交
177
  STsdbReadSnap*     pReadSnap;
178
  SIOCostSummary     cost;
179 180 181 182 183
  STSchema*          pSchema;      // the newest version schema
  STSchema*          pMemSchema;   // the previous schema for in-memory data, to avoid load schema too many times
  SDataFReader*      pFileReader;  // the file reader
  SDelFReader*       pDelFReader;  // the del file reader
  SArray*            pDelIdx;      // del file block index;
184 185 186
  SBlockInfoBuf      blockInfoBuf;
  int32_t            step;
  STsdbReader*       innerReader[2];
H
Hongze Cheng 已提交
187
};
H
Hongze Cheng 已提交
188

H
Haojun Liao 已提交
189
static SFileDataBlockInfo* getCurrentBlockInfo(SDataBlockIter* pBlockIter);
190 191
static int      buildDataBlockFromBufImpl(STableBlockScanInfo* pBlockScanInfo, int64_t endKey, int32_t capacity,
                                          STsdbReader* pReader);
192
static TSDBROW* getValidMemRow(SIterInfo* pIter, const SArray* pDelList, STsdbReader* pReader);
193 194
static int32_t  doMergeRowsInFileBlocks(SBlockData* pBlockData, STableBlockScanInfo* pScanInfo, STsdbReader* pReader,
                                        SRowMerger* pMerger);
H
Hongze Cheng 已提交
195
static int32_t  doMergeRowsInLastBlock(SLastBlockReader* pLastBlockReader, STableBlockScanInfo* pScanInfo, int64_t ts,
196
                                       SRowMerger* pMerger, SVersionRange* pVerRange, const char* id);
197
static int32_t  doMergeRowsInBuf(SIterInfo* pIter, uint64_t uid, int64_t ts, SArray* pDelList, SRowMerger* pMerger,
dengyihao's avatar
dengyihao 已提交
198
                                 STsdbReader* pReader);
H
Hongze Cheng 已提交
199
static int32_t  doAppendRowFromTSRow(SSDataBlock* pBlock, STsdbReader* pReader, SRow* pTSRow,
H
Hongze Cheng 已提交
200
                                     STableBlockScanInfo* pInfo);
201
static int32_t  doAppendRowFromFileBlock(SSDataBlock* pResBlock, STsdbReader* pReader, SBlockData* pBlockData,
H
Hongze Cheng 已提交
202
                                         int32_t rowIndex);
203
static void     setComposedBlockFlag(STsdbReader* pReader, bool composed);
H
Hongze Cheng 已提交
204 205
static bool     hasBeenDropped(const SArray* pDelList, int32_t* index, TSDBKEY* pKey, int32_t order,
                               SVersionRange* pVerRange);
206

H
Hongze Cheng 已提交
207
static int32_t doMergeMemTableMultiRows(TSDBROW* pRow, uint64_t uid, SIterInfo* pIter, SArray* pDelList,
208
                                        TSDBROW* pTSRow, STsdbReader* pReader, bool* freeTSRow);
H
Hongze Cheng 已提交
209
static int32_t doMergeMemIMemRows(TSDBROW* pRow, TSDBROW* piRow, STableBlockScanInfo* pBlockScanInfo,
H
Hongze Cheng 已提交
210
                                  STsdbReader* pReader, SRow** pTSRow);
211 212
static int32_t mergeRowsInFileBlocks(SBlockData* pBlockData, STableBlockScanInfo* pBlockScanInfo, int64_t key,
                                     STsdbReader* pReader);
213

dengyihao's avatar
dengyihao 已提交
214 215 216 217
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);
218
static SVersionRange getQueryVerRange(SVnode* pVnode, SQueryTableDataCond* pCond, int8_t level);
H
Hongze Cheng 已提交
219 220 221
static int64_t       getCurrentKeyInLastBlock(SLastBlockReader* pLastBlockReader);
static bool          hasDataInLastBlock(SLastBlockReader* pLastBlockReader);
static int32_t       doBuildDataBlock(STsdbReader* pReader);
C
Cary Xu 已提交
222
static TSDBKEY       getCurrentKeyInBuf(STableBlockScanInfo* pScanInfo, STsdbReader* pReader);
223
static bool          hasDataInFileBlock(const SBlockData* pBlockData, const SFileBlockDumpInfo* pDumpInfo);
224
static void          initBlockDumpInfo(STsdbReader* pReader, SDataBlockIter* pBlockIter);
225
static int32_t       getInitialDelIndex(const SArray* pDelSkyline, int32_t order);
C
Cary Xu 已提交
226

H
Haojun Liao 已提交
227 228
static STableBlockScanInfo* getTableBlockScanInfo(SHashObj* pTableMap, uint64_t uid, const char* id);

229 230
static FORCE_INLINE STSchema* getLatestTableSchema(STsdbReader* pReader, uint64_t uid);

C
Cary Xu 已提交
231
static bool outOfTimeWindow(int64_t ts, STimeWindow* pWindow) { return (ts > pWindow->ekey) || (ts < pWindow->skey); }
H
Haojun Liao 已提交
232

233 234
static int32_t setColumnIdSlotList(SBlockLoadSuppInfo* pSupInfo, SColumnInfo* pCols, const int32_t* pSlotIdList,
                                   int32_t numOfCols) {
235
  pSupInfo->smaValid = true;
236
  pSupInfo->numOfCols = numOfCols;
237
  pSupInfo->colId = taosMemoryMalloc(numOfCols * (sizeof(int16_t) * 2 + POINTER_BYTES));
H
Haojun Liao 已提交
238 239
  if (pSupInfo->colId == NULL) {
    taosMemoryFree(pSupInfo->colId);
H
Haojun Liao 已提交
240 241
    return TSDB_CODE_OUT_OF_MEMORY;
  }
H
Hongze Cheng 已提交
242

H
Haojun Liao 已提交
243
  pSupInfo->slotId = (int16_t*)((char*)pSupInfo->colId + (sizeof(int16_t) * numOfCols));
244
  pSupInfo->buildBuf = (char**)((char*)pSupInfo->slotId + (sizeof(int16_t) * numOfCols));
H
Haojun Liao 已提交
245
  for (int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
246 247
    pSupInfo->colId[i] = pCols[i].colId;
    pSupInfo->slotId[i] = pSlotIdList[i];
248

H
Haojun Liao 已提交
249 250
    if (IS_VAR_DATA_TYPE(pCols[i].type)) {
      pSupInfo->buildBuf[i] = taosMemoryMalloc(pCols[i].bytes);
H
Haojun Liao 已提交
251 252
    } else {
      pSupInfo->buildBuf[i] = NULL;
253
    }
H
Haojun Liao 已提交
254
  }
H
Hongze Cheng 已提交
255

H
Haojun Liao 已提交
256 257
  return TSDB_CODE_SUCCESS;
}
H
Hongze Cheng 已提交
258

H
Haojun Liao 已提交
259
static int32_t updateBlockSMAInfo(STSchema* pSchema, SBlockLoadSuppInfo* pSupInfo) {
260 261
  int32_t i = 0, j = 0;

H
Hongze Cheng 已提交
262
  while (i < pSchema->numOfCols && j < pSupInfo->numOfCols) {
263
    STColumn* pTCol = &pSchema->columns[i];
H
Haojun Liao 已提交
264
    if (pTCol->colId == pSupInfo->colId[j]) {
265 266
      if (!IS_BSMA_ON(pTCol)) {
        pSupInfo->smaValid = false;
H
Haojun Liao 已提交
267
        return TSDB_CODE_SUCCESS;
268 269 270 271
      }

      i += 1;
      j += 1;
H
Haojun Liao 已提交
272
    } else if (pTCol->colId < pSupInfo->colId[j]) {
273 274 275
      // do nothing
      i += 1;
    } else {
H
Haojun Liao 已提交
276
      return TSDB_CODE_INVALID_PARA;
277 278
    }
  }
H
Haojun Liao 已提交
279 280

  return TSDB_CODE_SUCCESS;
281 282
}

283
static int32_t initBlockScanInfoBuf(SBlockInfoBuf* pBuf, int32_t numOfTables) {
H
Hongze Cheng 已提交
284
  int32_t num = numOfTables / pBuf->numPerBucket;
285 286 287 288 289
  int32_t remainder = numOfTables % pBuf->numPerBucket;
  if (pBuf->pData == NULL) {
    pBuf->pData = taosArrayInit(num + 1, POINTER_BYTES);
  }

H
Hongze Cheng 已提交
290
  for (int32_t i = 0; i < num; ++i) {
291 292 293 294
    char* p = taosMemoryCalloc(pBuf->numPerBucket, sizeof(STableBlockScanInfo));
    if (p == NULL) {
      return TSDB_CODE_OUT_OF_MEMORY;
    }
295

296 297 298 299 300 301 302
    taosArrayPush(pBuf->pData, &p);
  }

  if (remainder > 0) {
    char* p = taosMemoryCalloc(remainder, sizeof(STableBlockScanInfo));
    if (p == NULL) {
      return TSDB_CODE_OUT_OF_MEMORY;
303
    }
304
    taosArrayPush(pBuf->pData, &p);
H
Haojun Liao 已提交
305
  }
H
Hongze Cheng 已提交
306

D
dapan1121 已提交
307 308 309 310 311 312 313 314 315 316 317
  pBuf->numOfTables = numOfTables;

  return TSDB_CODE_SUCCESS;
}

static int32_t ensureBlockScanInfoBuf(SBlockInfoBuf* pBuf, int32_t numOfTables) {
  if (numOfTables <= pBuf->numOfTables) {
    return TSDB_CODE_SUCCESS;
  }

  if (pBuf->numOfTables > 0) {
D
dapan1121 已提交
318 319
    STableBlockScanInfo **p = (STableBlockScanInfo**)taosArrayPop(pBuf->pData);
    taosMemoryFree(*p);
D
dapan1121 已提交
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
    pBuf->numOfTables /= pBuf->numPerBucket;
  }
  
  int32_t num = (numOfTables - pBuf->numOfTables) / pBuf->numPerBucket;
  int32_t remainder = (numOfTables - pBuf->numOfTables) % pBuf->numPerBucket;
  if (pBuf->pData == NULL) {
    pBuf->pData = taosArrayInit(num + 1, POINTER_BYTES);
  }

  for (int32_t i = 0; i < num; ++i) {
    char* p = taosMemoryCalloc(pBuf->numPerBucket, sizeof(STableBlockScanInfo));
    if (p == NULL) {
      return TSDB_CODE_OUT_OF_MEMORY;
    }

    taosArrayPush(pBuf->pData, &p);
  }

  if (remainder > 0) {
    char* p = taosMemoryCalloc(remainder, sizeof(STableBlockScanInfo));
    if (p == NULL) {
      return TSDB_CODE_OUT_OF_MEMORY;
    }
    taosArrayPush(pBuf->pData, &p);
  }

  pBuf->numOfTables = numOfTables;

H
Haojun Liao 已提交
348 349
  return TSDB_CODE_SUCCESS;
}
H
Hongze Cheng 已提交
350

351 352
static void clearBlockScanInfoBuf(SBlockInfoBuf* pBuf) {
  size_t num = taosArrayGetSize(pBuf->pData);
H
Hongze Cheng 已提交
353
  for (int32_t i = 0; i < num; ++i) {
354 355 356 357 358 359 360 361 362
    char** p = taosArrayGet(pBuf->pData, i);
    taosMemoryFree(*p);
  }

  taosArrayDestroy(pBuf->pData);
}

static void* getPosInBlockInfoBuf(SBlockInfoBuf* pBuf, int32_t index) {
  int32_t bucketIndex = index / pBuf->numPerBucket;
H
Hongze Cheng 已提交
363
  char**  pBucket = taosArrayGet(pBuf->pData, bucketIndex);
364 365 366
  return (*pBucket) + (index % pBuf->numPerBucket) * sizeof(STableBlockScanInfo);
}

H
Haojun Liao 已提交
367 368 369 370 371 372 373 374 375 376
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 {
    return (pu1 < pu2) ? -1 : 1;
  }
}

377
// NOTE: speedup the whole processing by preparing the buffer for STableBlockScanInfo in batch model
H
Hongze Cheng 已提交
378
static SHashObj* createDataBlockScanInfo(STsdbReader* pTsdbReader, SBlockInfoBuf* pBuf, const STableKeyInfo* idList,
X
Xiaoyu Wang 已提交
379
                                         STableUidList* pUidList, int32_t numOfTables) {
H
Haojun Liao 已提交
380
  // allocate buffer in order to load data blocks from file
381
  // todo use simple hash instead, optimize the memory consumption
382 383 384
  SHashObj* pTableMap =
      taosHashInit(numOfTables, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT), false, HASH_NO_LOCK);
  if (pTableMap == NULL) {
H
Haojun Liao 已提交
385 386 387
    return NULL;
  }

H
Haojun Liao 已提交
388
  int64_t st = taosGetTimestampUs();
H
Haojun Liao 已提交
389
  initBlockScanInfoBuf(pBuf, numOfTables);
H
Haojun Liao 已提交
390

H
Haojun Liao 已提交
391 392
  pUidList->tableUidList = taosMemoryMalloc(numOfTables * sizeof(uint64_t));
  if (pUidList->tableUidList == NULL) {
H
Haojun Liao 已提交
393 394
    return NULL;
  }
H
Haojun Liao 已提交
395
  pUidList->currentIndex = 0;
H
Haojun Liao 已提交
396

397
  for (int32_t j = 0; j < numOfTables; ++j) {
H
Haojun Liao 已提交
398
    STableBlockScanInfo* pScanInfo = getPosInBlockInfoBuf(pBuf, j);
H
Haojun Liao 已提交
399

400
    pScanInfo->uid = idList[j].uid;
H
Haojun Liao 已提交
401
    pUidList->tableUidList[j] = idList[j].uid;
H
Haojun Liao 已提交
402

403
    if (ASCENDING_TRAVERSE(pTsdbReader->order)) {
H
Haojun Liao 已提交
404
      int64_t skey = pTsdbReader->window.skey;
405
      pScanInfo->lastKey = (skey > INT64_MIN) ? (skey - 1) : skey;
wmmhello's avatar
wmmhello 已提交
406
    } else {
H
Haojun Liao 已提交
407
      int64_t ekey = pTsdbReader->window.ekey;
408
      pScanInfo->lastKey = (ekey < INT64_MAX) ? (ekey + 1) : ekey;
H
Haojun Liao 已提交
409
    }
wmmhello's avatar
wmmhello 已提交
410

411
    pScanInfo->lastKeyInStt = pScanInfo->lastKey;
412
    taosHashPut(pTableMap, &pScanInfo->uid, sizeof(uint64_t), &pScanInfo, POINTER_BYTES);
H
Hongze Cheng 已提交
413 414
    tsdbTrace("%p check table uid:%" PRId64 " from lastKey:%" PRId64 " %s", pTsdbReader, pScanInfo->uid,
              pScanInfo->lastKey, pTsdbReader->idStr);
H
Haojun Liao 已提交
415 416
  }

H
Haojun Liao 已提交
417
  taosSort(pUidList->tableUidList, numOfTables, sizeof(uint64_t), uidComparFunc);
H
Haojun Liao 已提交
418

H
Haojun Liao 已提交
419 420 421 422
  pTsdbReader->cost.createScanInfoList = (taosGetTimestampUs() - st) / 1000.0;
  tsdbDebug("%p create %d tables scan-info, size:%.2f Kb, elapsed time:%.2f ms, %s", pTsdbReader, numOfTables,
            (sizeof(STableBlockScanInfo) * numOfTables) / 1024.0, pTsdbReader->cost.createScanInfoList,
            pTsdbReader->idStr);
423

424
  return pTableMap;
H
Hongze Cheng 已提交
425
}
H
Hongze Cheng 已提交
426

427 428
static void resetAllDataBlockScanInfo(SHashObj* pTableMap, int64_t ts) {
  STableBlockScanInfo** p = NULL;
dengyihao's avatar
dengyihao 已提交
429
  while ((p = taosHashIterate(pTableMap, p)) != NULL) {
H
Hongze Cheng 已提交
430
    STableBlockScanInfo* pInfo = *(STableBlockScanInfo**)p;
431 432

    pInfo->iterInit = false;
H
Haojun Liao 已提交
433
    pInfo->iter.hasVal = false;
434
    pInfo->iiter.hasVal = false;
H
Haojun Liao 已提交
435

436 437
    if (pInfo->iter.iter != NULL) {
      pInfo->iter.iter = tsdbTbDataIterDestroy(pInfo->iter.iter);
438 439
    }

H
Haojun Liao 已提交
440 441
    if (pInfo->iiter.iter != NULL) {
      pInfo->iiter.iter = tsdbTbDataIterDestroy(pInfo->iiter.iter);
442 443
    }

444 445
    pInfo->delSkyline = taosArrayDestroy(pInfo->delSkyline);
    pInfo->lastKey = ts;
446 447 448
  }
}

449 450
static void clearBlockScanInfo(STableBlockScanInfo* p) {
  p->iterInit = false;
H
Haojun Liao 已提交
451 452

  p->iter.hasVal = false;
453
  p->iiter.hasVal = false;
454

455 456 457
  if (p->iter.iter != NULL) {
    p->iter.iter = tsdbTbDataIterDestroy(p->iter.iter);
  }
458

459 460 461
  if (p->iiter.iter != NULL) {
    p->iiter.iter = tsdbTbDataIterDestroy(p->iiter.iter);
  }
462

463 464 465 466
  p->delSkyline = taosArrayDestroy(p->delSkyline);
  p->pBlockList = taosArrayDestroy(p->pBlockList);
  tMapDataClear(&p->mapData);
}
467

H
Haojun Liao 已提交
468
static void destroyAllBlockScanInfo(SHashObj* pTableMap) {
469
  void* p = NULL;
470
  while ((p = taosHashIterate(pTableMap, p)) != NULL) {
471
    clearBlockScanInfo(*(STableBlockScanInfo**)p);
472 473 474 475 476
  }

  taosHashCleanup(pTableMap);
}

477
static bool isEmptyQueryTimeWindow(STimeWindow* pWindow) { return pWindow->skey > pWindow->ekey; }
H
Hongze Cheng 已提交
478

479 480 481
// 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 已提交
482
  STsdbKeepCfg* pCfg = &pTsdb->keepCfg;
H
Hongze Cheng 已提交
483

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

dengyihao's avatar
dengyihao 已提交
487
  STimeWindow win = *pWindow;
488 489 490 491 492 493
  if (win.skey < earilyTs) {
    win.skey = earilyTs;
  }

  return win;
}
H
Hongze Cheng 已提交
494

H
Haojun Liao 已提交
495
// init file iterator
496
static int32_t initFilesetIterator(SFilesetIter* pIter, SArray* aDFileSet, STsdbReader* pReader) {
H
Hongze Cheng 已提交
497
  size_t numOfFileset = taosArrayGetSize(aDFileSet);
498

499 500
  pIter->index = ASCENDING_TRAVERSE(pReader->order) ? -1 : numOfFileset;
  pIter->order = pReader->order;
H
Hongze Cheng 已提交
501
  pIter->pFileList = aDFileSet;
502
  pIter->numOfFiles = numOfFileset;
H
Haojun Liao 已提交
503

504 505 506 507
  if (pIter->pLastBlockReader == NULL) {
    pIter->pLastBlockReader = taosMemoryCalloc(1, sizeof(struct SLastBlockReader));
    if (pIter->pLastBlockReader == NULL) {
      int32_t code = TSDB_CODE_OUT_OF_MEMORY;
508
      tsdbError("failed to prepare the last block iterator, since:%s %s", tstrerror(code), pReader->idStr);
509 510
      return code;
    }
511 512
  }

513 514 515 516 517 518 519 520
  SLastBlockReader* pLReader = pIter->pLastBlockReader;
  pLReader->order = pReader->order;
  pLReader->window = pReader->window;
  pLReader->verRange = pReader->verRange;

  pLReader->uid = 0;
  tMergeTreeClose(&pLReader->mergeTree);

521
  if (pLReader->pInfo == NULL) {
522
    // here we ignore the first column, which is always be the primary timestamp column
523 524 525
    SBlockLoadSuppInfo* pInfo = &pReader->suppInfo;

    int32_t numOfStt = pReader->pTsdb->pVnode->config.sttTrigger;
X
Xiaoyu Wang 已提交
526
    pLReader->pInfo = tCreateLastBlockLoadInfo(pReader->pSchema, &pInfo->colId[1], pInfo->numOfCols - 1, numOfStt);
H
Haojun Liao 已提交
527 528 529 530
    if (pLReader->pInfo == NULL) {
      tsdbDebug("init fileset iterator failed, code:%s %s", tstrerror(terrno), pReader->idStr);
      return terrno;
    }
531 532
  }

533
  tsdbDebug("init fileset iterator, total files:%d %s", pIter->numOfFiles, pReader->idStr);
H
Haojun Liao 已提交
534 535 536
  return TSDB_CODE_SUCCESS;
}

dengyihao's avatar
dengyihao 已提交
537
static int32_t filesetIteratorNext(SFilesetIter* pIter, STsdbReader* pReader, bool* hasNext) {
538 539
  bool    asc = ASCENDING_TRAVERSE(pIter->order);
  int32_t step = asc ? 1 : -1;
540
  pIter->index += step;
D
dapan1121 已提交
541
  int32_t code = 0;
542 543

  if ((asc && pIter->index >= pIter->numOfFiles) || ((!asc) && pIter->index < 0)) {
D
dapan1121 已提交
544 545
    *hasNext = false;
    return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
546 547
  }

H
Haojun Liao 已提交
548 549 550
  SIOCostSummary* pSum = &pReader->cost;
  getLastBlockLoadInfo(pIter->pLastBlockReader->pInfo, &pSum->lastBlockLoad, &pReader->cost.lastBlockLoadTime);

551 552
  pIter->pLastBlockReader->uid = 0;
  tMergeTreeClose(&pIter->pLastBlockReader->mergeTree);
553
  resetLastBlockLoadInfo(pIter->pLastBlockReader->pInfo);
554

H
Haojun Liao 已提交
555 556
  // check file the time range of coverage
  STimeWindow win = {0};
H
Hongze Cheng 已提交
557

558
  while (1) {
H
Haojun Liao 已提交
559 560 561
    if (pReader->pFileReader != NULL) {
      tsdbDataFReaderClose(&pReader->pFileReader);
    }
562

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

D
dapan1121 已提交
565
    code = tsdbDataFReaderOpen(&pReader->pFileReader, pReader->pTsdb, pReader->status.pCurrentFileset);
566 567 568
    if (code != TSDB_CODE_SUCCESS) {
      goto _err;
    }
H
Haojun Liao 已提交
569

570 571
    pReader->cost.headFileLoad += 1;

572 573 574 575 576 577 578
    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);
D
dapan1121 已提交
579 580
      *hasNext = false;
      return TSDB_CODE_SUCCESS;
581 582 583 584
    }

    if ((asc && (win.ekey < pReader->window.skey)) || ((!asc) && (win.skey > pReader->window.ekey))) {
      pIter->index += step;
585
      if ((asc && pIter->index >= pIter->numOfFiles) || ((!asc) && pIter->index < 0)) {
D
dapan1121 已提交
586 587
        *hasNext = false;
        return TSDB_CODE_SUCCESS;
588
      }
589 590
      continue;
    }
C
Cary Xu 已提交
591

592
    tsdbDebug("%p file found fid:%d for qrange:%" PRId64 "-%" PRId64 ", %s", pReader, fid, pReader->window.skey,
593
              pReader->window.ekey, pReader->idStr);
D
dapan1121 已提交
594 595
    *hasNext = true;
    return TSDB_CODE_SUCCESS;
596
  }
597

598
_err:
D
dapan1121 已提交
599 600
  *hasNext = false;
  return code;
H
Haojun Liao 已提交
601 602
}

603
static void resetDataBlockIterator(SDataBlockIter* pIter, int32_t order) {
604 605
  pIter->order = order;
  pIter->index = -1;
606
  pIter->numOfBlocks = 0;
607 608 609 610 611 612 613
  if (pIter->blockList == NULL) {
    pIter->blockList = taosArrayInit(4, sizeof(SFileDataBlockInfo));
  } else {
    taosArrayClear(pIter->blockList);
  }
}

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

H
Haojun Liao 已提交
616
static void initReaderStatus(SReaderStatus* pStatus) {
dengyihao's avatar
dengyihao 已提交
617 618
  pStatus->pTableIter = NULL;
  pStatus->loadFromFile = true;
H
Haojun Liao 已提交
619 620
}

621 622 623 624 625 626 627 628
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) {
H
Haojun Liao 已提交
629
    SColumnInfoData colInfo = {0};
630 631 632 633 634 635 636 637 638 639 640 641 642
    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;
}

643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697
static int32_t tsdbInitReaderLock(STsdbReader* pReader) {
  int32_t code = -1;
  qTrace("tsdb/read: %p, pre-init read mutex: %p, code: %d", pReader, &pReader->readerMutex, code);

  code = taosThreadMutexInit(&pReader->readerMutex, NULL);

  qTrace("tsdb/read: %p, post-init read mutex: %p, code: %d", pReader, &pReader->readerMutex, code);

  return code;
}

static int32_t tsdbUninitReaderLock(STsdbReader* pReader) {
  int32_t code = -1;
  qTrace("tsdb/read: %p, pre-uninit read mutex: %p, code: %d", pReader, &pReader->readerMutex, code);

  code = taosThreadMutexDestroy(&pReader->readerMutex);

  qTrace("tsdb/read: %p, post-uninit read mutex: %p, code: %d", pReader, &pReader->readerMutex, code);

  return code;
}

static int32_t tsdbAcquireReader(STsdbReader* pReader) {
  int32_t code = -1;
  qTrace("tsdb/read: %p, pre-take read mutex: %p, code: %d", pReader, &pReader->readerMutex, code);

  code = taosThreadMutexLock(&pReader->readerMutex);

  qTrace("tsdb/read: %p, post-take read mutex: %p, code: %d", pReader, &pReader->readerMutex, code);

  return code;
}

static int32_t tsdbTryAcquireReader(STsdbReader* pReader) {
  int32_t code = -1;
  qTrace("tsdb/read: %p, pre-trytake read mutex: %p, code: %d", pReader, &pReader->readerMutex, code);

  code = taosThreadMutexTryLock(&pReader->readerMutex);

  qTrace("tsdb/read: %p, post-trytake read mutex: %p, code: %d", pReader, &pReader->readerMutex, code);

  return code;
}

static int32_t tsdbReleaseReader(STsdbReader* pReader) {
  int32_t code = -1;
  qTrace("tsdb/read: %p, pre-untake read mutex: %p, code: %d", pReader, &pReader->readerMutex, code);

  code = taosThreadMutexUnlock(&pReader->readerMutex);

  qTrace("tsdb/read: %p, post-untake read mutex: %p, code: %d", pReader, &pReader->readerMutex, code);

  return code;
}

698 699 700 701 702 703
void tsdbReleaseDataBlock(STsdbReader* pReader) {
  SReaderStatus* pStatus = &pReader->status;
  if (!pStatus->composedDataBlock) {
    tsdbReleaseReader(pReader);
  }
}
704

705
static int32_t tsdbReaderCreate(SVnode* pVnode, SQueryTableDataCond* pCond, STsdbReader** ppReader, int32_t capacity,
H
Haojun Liao 已提交
706
                                SSDataBlock* pResBlock, const char* idstr) {
H
Haojun Liao 已提交
707
  int32_t      code = 0;
708
  int8_t       level = 0;
H
Haojun Liao 已提交
709
  STsdbReader* pReader = (STsdbReader*)taosMemoryCalloc(1, sizeof(*pReader));
H
Hongze Cheng 已提交
710 711
  if (pReader == NULL) {
    code = TSDB_CODE_OUT_OF_MEMORY;
H
Haojun Liao 已提交
712
    goto _end;
H
Hongze Cheng 已提交
713 714
  }

C
Cary Xu 已提交
715
  if (VND_IS_TSMA(pVnode)) {
H
Haojun Liao 已提交
716
    tsdbDebug("vgId:%d, tsma is selected to query, %s", TD_VID(pVnode), idstr);
C
Cary Xu 已提交
717 718
  }

H
Haojun Liao 已提交
719
  initReaderStatus(&pReader->status);
720

L
Liu Jicong 已提交
721
  pReader->pTsdb = getTsdbByRetentions(pVnode, pCond->twindows.skey, pVnode->config.tsdbCfg.retentions, idstr, &level);
dengyihao's avatar
dengyihao 已提交
722 723
  pReader->suid = pCond->suid;
  pReader->order = pCond->order;
724
  pReader->capacity = capacity;
H
Haojun Liao 已提交
725
  pReader->pResBlock = pResBlock;
726
  pReader->idStr = (idstr != NULL) ? taosStrdup(idstr) : NULL;
dengyihao's avatar
dengyihao 已提交
727
  pReader->verRange = getQueryVerRange(pVnode, pCond, level);
728
  pReader->type = pCond->type;
729
  pReader->window = updateQueryTimeWindow(pReader->pTsdb, &pCond->twindows);
H
Hongze Cheng 已提交
730
  pReader->blockInfoBuf.numPerBucket = 1000;  // 1000 tables per bucket
H
Hongze Cheng 已提交
731

H
Haojun Liao 已提交
732 733 734 735 736 737 738 739
  if (pReader->pResBlock == NULL) {
    pReader->freeBlock = true;
    pReader->pResBlock = createResBlock(pCond, pReader->capacity);
    if (pReader->pResBlock == NULL) {
      code = terrno;
      goto _end;
    }
  }
740

H
Haojun Liao 已提交
741 742 743 744 745
  if (pCond->numOfCols <= 0) {
    tsdbError("vgId:%d, invalid column number %d in query cond, %s", TD_VID(pVnode), pCond->numOfCols, idstr);
    code = TSDB_CODE_INVALID_PARA;
    goto _end;
  }
H
Hongze Cheng 已提交
746

747 748
  // allocate buffer in order to load data blocks from file
  SBlockLoadSuppInfo* pSup = &pReader->suppInfo;
749
  pSup->pColAgg = taosArrayInit(pCond->numOfCols, sizeof(SColumnDataAgg));
H
Haojun Liao 已提交
750
  if (pSup->pColAgg == NULL) {
751 752 753
    code = TSDB_CODE_OUT_OF_MEMORY;
    goto _end;
  }
H
Haojun Liao 已提交
754

755 756
  pSup->tsColAgg.colId = PRIMARYKEY_TIMESTAMP_COL_ID;

H
Hongze Cheng 已提交
757
  code = tBlockDataCreate(&pReader->status.fileBlockData);
H
Haojun Liao 已提交
758 759 760 761 762
  if (code != TSDB_CODE_SUCCESS) {
    terrno = code;
    goto _end;
  }

763
  setColumnIdSlotList(pSup, pCond->colList, pCond->pSlotList, pCond->numOfCols);
764

765
  tsdbInitReaderLock(pReader);
766

H
Hongze Cheng 已提交
767 768
  *ppReader = pReader;
  return code;
H
Hongze Cheng 已提交
769

H
Haojun Liao 已提交
770 771
_end:
  tsdbReaderClose(pReader);
H
Hongze Cheng 已提交
772 773 774
  *ppReader = NULL;
  return code;
}
H
Hongze Cheng 已提交
775

H
Haojun Liao 已提交
776
static int32_t doLoadBlockIndex(STsdbReader* pReader, SDataFReader* pFileReader, SArray* pIndexList) {
X
Xiaoyu Wang 已提交
777
  int64_t    st = taosGetTimestampUs();
778 779 780
  LRUHandle* handle = NULL;
  int32_t    code = tsdbCacheGetBlockIdx(pFileReader->pTsdb->biCache, pFileReader, &handle);
  if (code != TSDB_CODE_SUCCESS || handle == NULL) {
781
    goto _end;
H
Haojun Liao 已提交
782
  }
H
Hongze Cheng 已提交
783

H
Haojun Liao 已提交
784 785
  int32_t numOfTables = taosHashGetSize(pReader->status.pTableMap);

786 787
  SArray* aBlockIdx = (SArray*)taosLRUCacheValue(pFileReader->pTsdb->biCache, handle);
  size_t  num = taosArrayGetSize(aBlockIdx);
788
  if (num == 0) {
789
    tsdbBICacheRelease(pFileReader->pTsdb->biCache, handle);
H
Haojun Liao 已提交
790 791
    return TSDB_CODE_SUCCESS;
  }
H
Hongze Cheng 已提交
792

H
Haojun Liao 已提交
793
  // todo binary search to the start position
794 795
  int64_t et1 = taosGetTimestampUs();

X
Xiaoyu Wang 已提交
796
  SBlockIdx*     pBlockIdx = NULL;
797
  STableUidList* pList = &pReader->status.uidList;
H
Haojun Liao 已提交
798

H
Haojun Liao 已提交
799
  int32_t i = 0, j = 0;
X
Xiaoyu Wang 已提交
800
  while (i < num && j < numOfTables) {
H
Haojun Liao 已提交
801
    pBlockIdx = (SBlockIdx*)taosArrayGet(aBlockIdx, i);
H
Hongze Cheng 已提交
802
    if (pBlockIdx->suid != pReader->suid) {
H
Haojun Liao 已提交
803
      i += 1;
H
Haojun Liao 已提交
804 805 806
      continue;
    }

H
Haojun Liao 已提交
807 808
    if (pBlockIdx->uid < pList->tableUidList[j]) {
      i += 1;
H
Haojun Liao 已提交
809 810 811
      continue;
    }

H
Haojun Liao 已提交
812
    if (pBlockIdx->uid > pList->tableUidList[j]) {
H
Haojun Liao 已提交
813
      j += 1;
H
Haojun Liao 已提交
814
      continue;
H
Haojun Liao 已提交
815 816
    }

H
Haojun Liao 已提交
817
    if (pBlockIdx->uid == pList->tableUidList[j]) {
H
Haojun Liao 已提交
818
      // this block belongs to a table that is not queried.
H
Haojun Liao 已提交
819 820 821
      STableBlockScanInfo* pScanInfo = getTableBlockScanInfo(pReader->status.pTableMap, pBlockIdx->uid, pReader->idStr);
      if (pScanInfo == NULL) {
        return terrno;
H
Haojun Liao 已提交
822 823 824 825 826 827 828
      }

      if (pScanInfo->pBlockList == NULL) {
        pScanInfo->pBlockList = taosArrayInit(4, sizeof(SBlockIndex));
      }

      taosArrayPush(pIndexList, pBlockIdx);
H
Haojun Liao 已提交
829

H
Haojun Liao 已提交
830
      i += 1;
H
Haojun Liao 已提交
831
      j += 1;
832
    }
H
Haojun Liao 已提交
833
  }
H
Hongze Cheng 已提交
834

835
  int64_t et2 = taosGetTimestampUs();
H
Haojun Liao 已提交
836 837 838
  tsdbDebug("load block index for %d/%d tables completed, elapsed time:%.2f ms, set blockIdx:%.2f ms, size:%.2f Kb %s",
            numOfTables, (int32_t)num, (et1 - st) / 1000.0, (et2 - et1) / 1000.0, num * sizeof(SBlockIdx) / 1024.0,
            pReader->idStr);
839 840 841

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

842
_end:
843
  tsdbBICacheRelease(pFileReader->pTsdb->biCache, handle);
H
Haojun Liao 已提交
844 845
  return code;
}
H
Hongze Cheng 已提交
846

847
static void cleanupTableScanInfo(SHashObj* pTableMap) {
848
  STableBlockScanInfo** px = NULL;
dengyihao's avatar
dengyihao 已提交
849
  while (1) {
850
    px = taosHashIterate(pTableMap, px);
851 852 853 854
    if (px == NULL) {
      break;
    }

855
    // reset the index in last block when handing a new file
856 857
    tMapDataClear(&(*px)->mapData);
    taosArrayClear((*px)->pBlockList);
858
  }
859 860
}

861
static int32_t doLoadFileBlock(STsdbReader* pReader, SArray* pIndexList, SBlockNumber* pBlockNum) {
862 863 864 865 866 867
  int32_t numOfQTable = 0;
  size_t  sizeInDisk = 0;
  size_t  numOfTables = taosArrayGetSize(pIndexList);

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

dengyihao's avatar
dengyihao 已提交
869
  for (int32_t i = 0; i < numOfTables; ++i) {
X
Xiaoyu Wang 已提交
870
    SBlockIdx*           pBlockIdx = taosArrayGet(pIndexList, i);
H
Haojun Liao 已提交
871 872 873 874
    STableBlockScanInfo* pScanInfo = getTableBlockScanInfo(pReader->status.pTableMap, pBlockIdx->uid, pReader->idStr);
    if (pScanInfo == NULL) {
      return terrno;
    }
H
Hongze Cheng 已提交
875

876
    tMapDataReset(&pScanInfo->mapData);
H
Hongze Cheng 已提交
877
    tsdbReadDataBlk(pReader->pFileReader, pBlockIdx, &pScanInfo->mapData);
H
Haojun Liao 已提交
878
    taosArrayEnsureCap(pScanInfo->pBlockList, pScanInfo->mapData.nItem);
879

880
    sizeInDisk += pScanInfo->mapData.nData;
881 882 883 884 885 886 887 888 889 890 891 892 893

    int32_t     step = ASCENDING_TRAVERSE(pReader->order) ? 1 : -1;
    STimeWindow w = pReader->window;
    if (ASCENDING_TRAVERSE(pReader->order)) {
      w.skey = pScanInfo->lastKey + step;
    } else {
      w.ekey = pScanInfo->lastKey + step;
    }

    if (isEmptyQueryTimeWindow(&w)) {
      continue;
    }

H
Haojun Liao 已提交
894
    SDataBlk block = {0};
895
    for (int32_t j = 0; j < pScanInfo->mapData.nItem; ++j) {
H
Haojun Liao 已提交
896
      tGetDataBlk(pScanInfo->mapData.pData + pScanInfo->mapData.aOffset[j], &block);
H
Hongze Cheng 已提交
897

898
      // 1. time range check
899 900
      // if (block.minKey.ts > pReader->window.ekey || block.maxKey.ts < pReader->window.skey) {
      if (block.minKey.ts > w.ekey || block.maxKey.ts < w.skey) {
H
Haojun Liao 已提交
901 902
        continue;
      }
H
Hongze Cheng 已提交
903

904
      // 2. version range check
H
Hongze Cheng 已提交
905
      if (block.minVer > pReader->verRange.maxVer || block.maxVer < pReader->verRange.minVer) {
906 907
        continue;
      }
908

909
      SBlockIndex bIndex = {.ordinalIndex = j, .inFileOffset = block.aSubBlock->offset};
910
      bIndex.window = (STimeWindow){.skey = block.minKey.ts, .ekey = block.maxKey.ts};
911

H
Haojun Liao 已提交
912 913
      void* p1 = taosArrayPush(pScanInfo->pBlockList, &bIndex);
      if (p1 == NULL) {
914
        tMapDataClear(&pScanInfo->mapData);
H
Haojun Liao 已提交
915 916
        return TSDB_CODE_OUT_OF_MEMORY;
      }
917

918
      pBlockNum->numOfBlocks += 1;
H
Haojun Liao 已提交
919
    }
H
Hongze Cheng 已提交
920

H
Haojun Liao 已提交
921
    if ((pScanInfo->pBlockList != NULL )&& (taosArrayGetSize(pScanInfo->pBlockList) > 0)) {
922 923 924 925
      numOfQTable += 1;
    }
  }

H
Hongze Cheng 已提交
926
  pBlockNum->numOfLastFiles = pReader->pFileReader->pSet->nSttF;
927
  int32_t total = pBlockNum->numOfLastFiles + pBlockNum->numOfBlocks;
928

929
  double el = (taosGetTimestampUs() - st) / 1000.0;
H
Hongze Cheng 已提交
930
  tsdbDebug(
931
      "load block of %ld tables completed, blocks:%d in %d tables, last-files:%d, block-info-size:%.2f Kb, elapsed "
932
      "time:%.2f ms %s",
933
      numOfTables, pBlockNum->numOfBlocks, numOfQTable, pBlockNum->numOfLastFiles, sizeInDisk / 1000.0, el,
H
Hongze Cheng 已提交
934
      pReader->idStr);
935

936
  pReader->cost.numOfBlocks += total;
937
  pReader->cost.headFileLoadTime += el;
938

H
Haojun Liao 已提交
939 940
  return TSDB_CODE_SUCCESS;
}
H
Hongze Cheng 已提交
941

942
static void setBlockAllDumped(SFileBlockDumpInfo* pDumpInfo, int64_t maxKey, int32_t order) {
943
  int32_t step = ASCENDING_TRAVERSE(order) ? 1 : -1;
944
  pDumpInfo->allDumped = true;
945
  pDumpInfo->lastKey = maxKey + step;
H
Haojun Liao 已提交
946 947
}

948 949
static void doCopyColVal(SColumnInfoData* pColInfoData, int32_t rowIndex, int32_t colIndex, SColVal* pColVal,
                         SBlockLoadSuppInfo* pSup) {
H
Haojun Liao 已提交
950
  if (IS_VAR_DATA_TYPE(pColVal->type)) {
H
Hongze Cheng 已提交
951
    if (!COL_VAL_IS_VALUE(pColVal)) {
952
      colDataSetNULL(pColInfoData, rowIndex);
H
Haojun Liao 已提交
953 954
    } else {
      varDataSetLen(pSup->buildBuf[colIndex], pColVal->value.nData);
H
Haojun Liao 已提交
955
      ASSERT(pColVal->value.nData <= pColInfoData->info.bytes);
956 957 958 959
      if (pColVal->value.nData > 0) {  // pData may be null, if nData is 0
        memcpy(varDataVal(pSup->buildBuf[colIndex]), pColVal->value.pData, pColVal->value.nData);
      }

960
      colDataSetVal(pColInfoData, rowIndex, pSup->buildBuf[colIndex], false);
H
Haojun Liao 已提交
961 962
    }
  } else {
963
    colDataSetVal(pColInfoData, rowIndex, (const char*)&pColVal->value, !COL_VAL_IS_VALUE(pColVal));
H
Haojun Liao 已提交
964
  }
H
Haojun Liao 已提交
965 966
}

967
static SFileDataBlockInfo* getCurrentBlockInfo(SDataBlockIter* pBlockIter) {
H
Haojun Liao 已提交
968 969 970
  size_t num = taosArrayGetSize(pBlockIter->blockList);
  if (num == 0) {
    ASSERT(pBlockIter->numOfBlocks == num);
971 972
    return NULL;
  }
973 974 975

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

H
Hongze Cheng 已提交
978
static SDataBlk* getCurrentBlock(SDataBlockIter* pBlockIter) { return &pBlockIter->block; }
979

C
Cary Xu 已提交
980 981 982 983 984 985
static int doBinarySearchKey(TSKEY* keyList, int num, int pos, TSKEY key, int order) {
  // start end position
  int s, e;
  s = pos;

  // check
H
Haojun Liao 已提交
986
  ASSERT(pos >= 0 && pos < num && num > 0);
C
Cary Xu 已提交
987 988
  if (order == TSDB_ORDER_ASC) {
    // find the first position which is smaller than the key
H
Hongze Cheng 已提交
989 990
    e = num - 1;
    if (key < keyList[pos]) return -1;
C
Cary Xu 已提交
991 992
    while (1) {
      // check can return
H
Hongze Cheng 已提交
993 994 995
      if (key >= keyList[e]) return e;
      if (key <= keyList[s]) return s;
      if (e - s <= 1) return s;
C
Cary Xu 已提交
996 997

      // change start or end position
H
Hongze Cheng 已提交
998
      int mid = s + (e - s + 1) / 2;
C
Cary Xu 已提交
999 1000
      if (keyList[mid] > key)
        e = mid;
H
Hongze Cheng 已提交
1001
      else if (keyList[mid] < key)
C
Cary Xu 已提交
1002 1003 1004 1005
        s = mid;
      else
        return mid;
    }
H
Hongze Cheng 已提交
1006
  } else {  // DESC
C
Cary Xu 已提交
1007
    // find the first position which is bigger than the key
H
Hongze Cheng 已提交
1008 1009
    e = 0;
    if (key > keyList[pos]) return -1;
C
Cary Xu 已提交
1010 1011
    while (1) {
      // check can return
H
Hongze Cheng 已提交
1012 1013 1014
      if (key <= keyList[e]) return e;
      if (key >= keyList[s]) return s;
      if (s - e <= 1) return s;
C
Cary Xu 已提交
1015 1016

      // change start or end position
H
Hongze Cheng 已提交
1017
      int mid = s - (s - e + 1) / 2;
C
Cary Xu 已提交
1018 1019
      if (keyList[mid] < key)
        e = mid;
H
Hongze Cheng 已提交
1020
      else if (keyList[mid] > key)
C
Cary Xu 已提交
1021 1022 1023 1024 1025 1026 1027
        s = mid;
      else
        return mid;
    }
  }
}

H
Haojun Liao 已提交
1028
static int32_t getEndPosInDataBlock(STsdbReader* pReader, SBlockData* pBlockData, SDataBlk* pBlock, int32_t pos) {
C
Cary Xu 已提交
1029 1030
  // NOTE: reverse the order to find the end position in data block
  int32_t endPos = -1;
H
Hongze Cheng 已提交
1031
  bool    asc = ASCENDING_TRAVERSE(pReader->order);
C
Cary Xu 已提交
1032 1033 1034 1035 1036 1037

  if (asc && pReader->window.ekey >= pBlock->maxKey.ts) {
    endPos = pBlock->nRow - 1;
  } else if (!asc && pReader->window.skey <= pBlock->minKey.ts) {
    endPos = 0;
  } else {
C
Cary Xu 已提交
1038 1039
    int64_t key = asc ? pReader->window.ekey : pReader->window.skey;
    endPos = doBinarySearchKey(pBlockData->aTSKEY, pBlock->nRow, pos, key, pReader->order);
C
Cary Xu 已提交
1040 1041 1042 1043 1044
  }

  return endPos;
}

H
Haojun Liao 已提交
1045
static void copyPrimaryTsCol(const SBlockData* pBlockData, SFileBlockDumpInfo* pDumpInfo, SColumnInfoData* pColData,
H
Haojun Liao 已提交
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064
                             int32_t dumpedRows, bool asc) {
  if (asc) {
    memcpy(pColData->pData, &pBlockData->aTSKEY[pDumpInfo->rowIndex], dumpedRows * sizeof(int64_t));
  } else {
    int32_t startIndex = pDumpInfo->rowIndex - dumpedRows + 1;
    memcpy(pColData->pData, &pBlockData->aTSKEY[startIndex], dumpedRows * sizeof(int64_t));

    // todo: opt perf by extract the loop
    // reverse the array list
    int32_t  mid = dumpedRows >> 1u;
    int64_t* pts = (int64_t*)pColData->pData;
    for (int32_t j = 0; j < mid; ++j) {
      int64_t t = pts[j];
      pts[j] = pts[dumpedRows - j - 1];
      pts[dumpedRows - j - 1] = t;
    }
  }
}

H
Haojun Liao 已提交
1065 1066
// a faster version of copy procedure.
static void copyNumericCols(const SColData* pData, SFileBlockDumpInfo* pDumpInfo, SColumnInfoData* pColData,
H
Hongze Cheng 已提交
1067
                            int32_t dumpedRows, bool asc) {
H
Haojun Liao 已提交
1068 1069 1070 1071 1072 1073 1074 1075
  uint8_t* p = NULL;
  if (asc) {
    p = pData->pData + tDataTypes[pData->type].bytes * pDumpInfo->rowIndex;
  } else {
    int32_t startIndex = pDumpInfo->rowIndex - dumpedRows + 1;
    p = pData->pData + tDataTypes[pData->type].bytes * startIndex;
  }

H
Hongze Cheng 已提交
1076
  int32_t step = asc ? 1 : -1;
H
Haojun Liao 已提交
1077

H
Haojun Liao 已提交
1078
  // make sure it is aligned to 8bit, the allocated memory address is aligned to 256bit
1079
  //  ASSERT((((uint64_t)pColData->pData) & (0x8 - 1)) == 0);
H
Haojun Liao 已提交
1080 1081 1082 1083 1084 1085

  // 1. copy data in a batch model
  memcpy(pColData->pData, p, dumpedRows * tDataTypes[pData->type].bytes);

  // 2. reverse the array list in case of descending order scan data block
  if (!asc) {
H
Hongze Cheng 已提交
1086
    switch (pColData->info.type) {
H
Haojun Liao 已提交
1087 1088 1089
      case TSDB_DATA_TYPE_TIMESTAMP:
      case TSDB_DATA_TYPE_DOUBLE:
      case TSDB_DATA_TYPE_BIGINT:
H
Hongze Cheng 已提交
1090
      case TSDB_DATA_TYPE_UBIGINT: {
H
Haojun Liao 已提交
1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103
        int32_t  mid = dumpedRows >> 1u;
        int64_t* pts = (int64_t*)pColData->pData;
        for (int32_t j = 0; j < mid; ++j) {
          int64_t t = pts[j];
          pts[j] = pts[dumpedRows - j - 1];
          pts[dumpedRows - j - 1] = t;
        }
        break;
      }

      case TSDB_DATA_TYPE_BOOL:
      case TSDB_DATA_TYPE_TINYINT:
      case TSDB_DATA_TYPE_UTINYINT: {
H
Hongze Cheng 已提交
1104
        int32_t mid = dumpedRows >> 1u;
H
Haojun Liao 已提交
1105 1106
        int8_t* pts = (int8_t*)pColData->pData;
        for (int32_t j = 0; j < mid; ++j) {
H
Haojun Liao 已提交
1107
          int8_t t = pts[j];
H
Haojun Liao 已提交
1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131
          pts[j] = pts[dumpedRows - j - 1];
          pts[dumpedRows - j - 1] = t;
        }
        break;
      }

      case TSDB_DATA_TYPE_SMALLINT:
      case TSDB_DATA_TYPE_USMALLINT: {
        int32_t  mid = dumpedRows >> 1u;
        int16_t* pts = (int16_t*)pColData->pData;
        for (int32_t j = 0; j < mid; ++j) {
          int64_t t = pts[j];
          pts[j] = pts[dumpedRows - j - 1];
          pts[dumpedRows - j - 1] = t;
        }
        break;
      }

      case TSDB_DATA_TYPE_FLOAT:
      case TSDB_DATA_TYPE_INT:
      case TSDB_DATA_TYPE_UINT: {
        int32_t  mid = dumpedRows >> 1u;
        int32_t* pts = (int32_t*)pColData->pData;
        for (int32_t j = 0; j < mid; ++j) {
H
Haojun Liao 已提交
1132
          int32_t t = pts[j];
H
Haojun Liao 已提交
1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154
          pts[j] = pts[dumpedRows - j - 1];
          pts[dumpedRows - j - 1] = t;
        }
        break;
      }
    }
  }

  // 3. if the  null value exists, check items one-by-one
  if (pData->flag != HAS_VALUE) {
    int32_t rowIndex = 0;

    for (int32_t j = pDumpInfo->rowIndex; rowIndex < dumpedRows; j += step, rowIndex++) {
      uint8_t v = tColDataGetBitValue(pData, j);
      if (v == 0 || v == 1) {
        colDataSetNull_f(pColData->nullbitmap, rowIndex);
        pColData->hasNull = true;
      }
    }
  }
}

1155
static int32_t copyBlockDataToSDataBlock(STsdbReader* pReader) {
H
Haojun Liao 已提交
1156 1157 1158 1159
  SReaderStatus*      pStatus = &pReader->status;
  SDataBlockIter*     pBlockIter = &pStatus->blockIter;
  SBlockLoadSuppInfo* pSupInfo = &pReader->suppInfo;
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;
H
Hongze Cheng 已提交
1160

1161
  SBlockData*         pBlockData = &pStatus->fileBlockData;
C
Cary Xu 已提交
1162
  SFileDataBlockInfo* pBlockInfo = getCurrentBlockInfo(pBlockIter);
H
Hongze Cheng 已提交
1163
  SDataBlk*           pBlock = getCurrentBlock(pBlockIter);
H
Haojun Liao 已提交
1164
  SSDataBlock*        pResBlock = pReader->pResBlock;
H
Haojun Liao 已提交
1165
  int32_t             numOfOutputCols = pSupInfo->numOfCols;
H
Haojun Liao 已提交
1166

H
Haojun Liao 已提交
1167
  SColVal cv = {0};
1168
  int64_t st = taosGetTimestampUs();
1169 1170
  bool    asc = ASCENDING_TRAVERSE(pReader->order);
  int32_t step = asc ? 1 : -1;
1171

1172 1173
  // no data exists, return directly.
  if (pBlockData->nRow == 0 || pBlockData->aTSKEY == 0) {
X
Xiaoyu Wang 已提交
1174 1175
    tsdbWarn("%p no need to copy since no data in blockData, table uid:%" PRIu64 " has been dropped, %s", pReader,
             pBlockInfo->uid, pReader->idStr);
1176 1177 1178 1179
    pResBlock->info.rows = 0;
    return 0;
  }

1180 1181
  if ((pDumpInfo->rowIndex == 0 && asc) || (pDumpInfo->rowIndex == pBlock->nRow - 1 && (!asc))) {
    if (asc && pReader->window.skey <= pBlock->minKey.ts) {
1182 1183 1184
      // pDumpInfo->rowIndex = 0;
    } else if (!asc && pReader->window.ekey >= pBlock->maxKey.ts) {
      // pDumpInfo->rowIndex = pBlock->nRow - 1;
H
Haojun Liao 已提交
1185
    } else {  // find the appropriate the start position in current block, and set it to be the current rowIndex
1186
      int32_t pos = asc ? pBlock->nRow - 1 : 0;
C
Cary Xu 已提交
1187 1188 1189
      int32_t order = asc ? TSDB_ORDER_DESC : TSDB_ORDER_ASC;
      int64_t key = asc ? pReader->window.skey : pReader->window.ekey;
      pDumpInfo->rowIndex = doBinarySearchKey(pBlockData->aTSKEY, pBlock->nRow, pos, key, order);
H
Haojun Liao 已提交
1190 1191 1192 1193 1194 1195 1196 1197 1198

      if (pDumpInfo->rowIndex < 0) {
        tsdbError(
            "%p failed to locate the start position in current block, global index:%d, table index:%d, brange:%" PRId64
            "-%" PRId64 ", minVer:%" PRId64 ", maxVer:%" PRId64 " %s",
            pReader, pBlockIter->index, pBlockInfo->tbBlockIdx, pBlock->minKey.ts, pBlock->maxKey.ts, pBlock->minVer,
            pBlock->maxVer, pReader->idStr);
        return TSDB_CODE_INVALID_PARA;
      }
1199
    }
C
Cary Xu 已提交
1200 1201 1202 1203 1204 1205 1206 1207 1208 1209
  }

  // time window check
  int32_t endIndex = getEndPosInDataBlock(pReader, pBlockData, pBlock, pDumpInfo->rowIndex);
  if (endIndex == -1) {
    setBlockAllDumped(pDumpInfo, pReader->window.ekey, pReader->order);
    return TSDB_CODE_SUCCESS;
  }

  endIndex += step;
H
Haojun Liao 已提交
1210 1211 1212
  int32_t dumpedRows = asc ? (endIndex - pDumpInfo->rowIndex) : (pDumpInfo->rowIndex - endIndex);
  if (dumpedRows > pReader->capacity) {  // output buffer check
    dumpedRows = pReader->capacity;
1213 1214
  }

H
Haojun Liao 已提交
1215
  int32_t i = 0;
C
Cary Xu 已提交
1216 1217
  int32_t rowIndex = 0;

H
Haojun Liao 已提交
1218 1219
  SColumnInfoData* pColData = taosArrayGet(pResBlock->pDataBlock, pSupInfo->slotId[i]);
  if (pSupInfo->colId[i] == PRIMARYKEY_TIMESTAMP_COL_ID) {
H
Haojun Liao 已提交
1220
    copyPrimaryTsCol(pBlockData, pDumpInfo, pColData, dumpedRows, asc);
1221 1222 1223
    i += 1;
  }

1224
  int32_t colIndex = 0;
H
Hongze Cheng 已提交
1225
  int32_t num = pBlockData->nColData;
1226
  while (i < numOfOutputCols && colIndex < num) {
1227 1228
    rowIndex = 0;

H
Hongze Cheng 已提交
1229
    SColData* pData = tBlockDataGetColDataByIdx(pBlockData, colIndex);
H
Haojun Liao 已提交
1230
    if (pData->cid < pSupInfo->colId[i]) {
1231
      colIndex += 1;
H
Haojun Liao 已提交
1232 1233
    } else if (pData->cid == pSupInfo->colId[i]) {
      pColData = taosArrayGet(pResBlock->pDataBlock, pSupInfo->slotId[i]);
H
Haojun Liao 已提交
1234

H
Hongze Cheng 已提交
1235
      if (pData->flag == HAS_NONE || pData->flag == HAS_NULL || pData->flag == (HAS_NULL | HAS_NONE)) {
1236
        colDataSetNNULL(pColData, 0, dumpedRows);
C
Cary Xu 已提交
1237
      } else {
H
Haojun Liao 已提交
1238
        if (IS_MATHABLE_TYPE(pColData->info.type)) {
H
Haojun Liao 已提交
1239 1240
          copyNumericCols(pData, pDumpInfo, pColData, dumpedRows, asc);
        } else {  // varchar/nchar type
H
Haojun Liao 已提交
1241
          for (int32_t j = pDumpInfo->rowIndex; rowIndex < dumpedRows; j += step) {
C
Cary Xu 已提交
1242 1243 1244 1245
            tColDataGetValue(pData, j, &cv);
            doCopyColVal(pColData, rowIndex++, i, &cv, pSupInfo);
          }
        }
H
Haojun Liao 已提交
1246
      }
C
Cary Xu 已提交
1247

1248
      colIndex += 1;
1249
      i += 1;
1250
    } else {  // the specified column does not exist in file block, fill with null data
H
Haojun Liao 已提交
1251
      pColData = taosArrayGet(pResBlock->pDataBlock, pSupInfo->slotId[i]);
1252
      colDataSetNNULL(pColData, 0, dumpedRows);
1253
      i += 1;
H
Haojun Liao 已提交
1254
    }
1255 1256
  }

1257
  // fill the mis-matched columns with null value
1258
  while (i < numOfOutputCols) {
H
Haojun Liao 已提交
1259
    pColData = taosArrayGet(pResBlock->pDataBlock, pSupInfo->slotId[i]);
1260
    colDataSetNNULL(pColData, 0, dumpedRows);
1261
    i += 1;
H
Haojun Liao 已提交
1262
  }
H
Haojun Liao 已提交
1263

1264
  pResBlock->info.dataLoad = 1;
H
Haojun Liao 已提交
1265 1266
  pResBlock->info.rows = dumpedRows;
  pDumpInfo->rowIndex += step * dumpedRows;
1267

1268
  // check if current block are all handled
C
Cary Xu 已提交
1269 1270
  if (pDumpInfo->rowIndex >= 0 && pDumpInfo->rowIndex < pBlock->nRow) {
    int64_t ts = pBlockData->aTSKEY[pDumpInfo->rowIndex];
1271 1272 1273
    if (outOfTimeWindow(ts, &pReader->window)) {  // the remain data has out of query time window, ignore current block
      setBlockAllDumped(pDumpInfo, ts, pReader->order);
    }
C
Cary Xu 已提交
1274
  } else {
1275 1276
    int64_t ts = asc ? pBlock->maxKey.ts : pBlock->minKey.ts;
    setBlockAllDumped(pDumpInfo, ts, pReader->order);
C
Cary Xu 已提交
1277
  }
H
Haojun Liao 已提交
1278

1279
  double elapsedTime = (taosGetTimestampUs() - st) / 1000.0;
H
Haojun Liao 已提交
1280
  pReader->cost.blockLoadTime += elapsedTime;
H
Haojun Liao 已提交
1281

1282
  int32_t unDumpedRows = asc ? pBlock->nRow - pDumpInfo->rowIndex : pDumpInfo->rowIndex + 1;
H
Haojun Liao 已提交
1283
  tsdbDebug("%p copy file block to sdatablock, global index:%d, table index:%d, brange:%" PRId64 "-%" PRId64
1284
            ", rows:%d, remain:%d, minVer:%" PRId64 ", maxVer:%" PRId64 ", uid:%" PRIu64 " elapsed time:%.2f ms, %s",
H
Haojun Liao 已提交
1285
            pReader, pBlockIter->index, pBlockInfo->tbBlockIdx, pBlock->minKey.ts, pBlock->maxKey.ts, dumpedRows,
H
Haojun Liao 已提交
1286
            unDumpedRows, pBlock->minVer, pBlock->maxVer, pBlockInfo->uid, elapsedTime, pReader->idStr);
1287 1288 1289 1290

  return TSDB_CODE_SUCCESS;
}

1291 1292
static int32_t doLoadFileBlockData(STsdbReader* pReader, SDataBlockIter* pBlockIter, SBlockData* pBlockData,
                                   uint64_t uid) {
1293
  int32_t code = 0;
1294 1295
  int64_t st = taosGetTimestampUs();

1296
  tBlockDataReset(pBlockData);
1297 1298
  STSchema* pSchema = getLatestTableSchema(pReader, uid);
  if (pSchema == NULL) {
X
Xiaoyu Wang 已提交
1299
    tsdbDebug("%p table uid:%" PRIu64 " has been dropped, no data existed, %s", pReader, uid, pReader->idStr);
1300 1301 1302 1303
    return code;
  }

  SBlockLoadSuppInfo* pSup = &pReader->suppInfo;
X
Xiaoyu Wang 已提交
1304
  TABLEID             tid = {.suid = pReader->suid, .uid = uid};
1305
  code = tBlockDataInit(pBlockData, &tid, pSchema, &pSup->colId[1], pSup->numOfCols - 1);
1306 1307 1308 1309
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

1310
  SFileDataBlockInfo* pBlockInfo = getCurrentBlockInfo(pBlockIter);
1311
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;
1312

H
Hongze Cheng 已提交
1313
  SDataBlk* pBlock = getCurrentBlock(pBlockIter);
1314
  code = tsdbReadDataBlock(pReader->pFileReader, pBlock, pBlockData);
1315 1316 1317
  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",
1318
              pReader, pBlockIter->index, pBlockInfo->tbBlockIdx, pBlock->minKey.ts, pBlock->maxKey.ts, pBlock->nRow,
1319 1320 1321
              tstrerror(code), pReader->idStr);
    return code;
  }
1322

1323
  double elapsedTime = (taosGetTimestampUs() - st) / 1000.0;
1324

1325 1326 1327 1328
  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);
1329 1330 1331

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

H
Haojun Liao 已提交
1333
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
1334
}
H
Hongze Cheng 已提交
1335

H
Haojun Liao 已提交
1336 1337 1338
static void cleanupBlockOrderSupporter(SBlockOrderSupporter* pSup) {
  taosMemoryFreeClear(pSup->numOfBlocksPerTable);
  taosMemoryFreeClear(pSup->indexPerTable);
H
Hongze Cheng 已提交
1339

H
Haojun Liao 已提交
1340 1341 1342 1343
  for (int32_t i = 0; i < pSup->numOfTables; ++i) {
    SBlockOrderWrapper* pBlockInfo = pSup->pDataBlockInfo[i];
    taosMemoryFreeClear(pBlockInfo);
  }
H
Hongze Cheng 已提交
1344

H
Haojun Liao 已提交
1345 1346
  taosMemoryFreeClear(pSup->pDataBlockInfo);
}
H
Hongze Cheng 已提交
1347

H
Haojun Liao 已提交
1348 1349
static int32_t initBlockOrderSupporter(SBlockOrderSupporter* pSup, int32_t numOfTables) {
  pSup->numOfBlocksPerTable = taosMemoryCalloc(1, sizeof(int32_t) * numOfTables);
1350 1351
  pSup->indexPerTable = taosMemoryCalloc(1, sizeof(int32_t) * numOfTables);
  pSup->pDataBlockInfo = taosMemoryCalloc(1, POINTER_BYTES * numOfTables);
H
Hongze Cheng 已提交
1352

H
Haojun Liao 已提交
1353 1354 1355 1356
  if (pSup->numOfBlocksPerTable == NULL || pSup->indexPerTable == NULL || pSup->pDataBlockInfo == NULL) {
    cleanupBlockOrderSupporter(pSup);
    return TSDB_CODE_OUT_OF_MEMORY;
  }
H
Hongze Cheng 已提交
1357

H
Haojun Liao 已提交
1358 1359
  return TSDB_CODE_SUCCESS;
}
H
Hongze Cheng 已提交
1360

H
Haojun Liao 已提交
1361
static int32_t fileDataBlockOrderCompar(const void* pLeft, const void* pRight, void* param) {
1362
  int32_t leftIndex = *(int32_t*)pLeft;
H
Haojun Liao 已提交
1363
  int32_t rightIndex = *(int32_t*)pRight;
H
Hongze Cheng 已提交
1364

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

H
Haojun Liao 已提交
1367 1368
  int32_t leftTableBlockIndex = pSupporter->indexPerTable[leftIndex];
  int32_t rightTableBlockIndex = pSupporter->indexPerTable[rightIndex];
H
Hongze Cheng 已提交
1369

H
Haojun Liao 已提交
1370 1371 1372 1373 1374 1375 1376
  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 已提交
1377

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

1381 1382 1383
  return pLeftBlock->offset > pRightBlock->offset ? 1 : -1;
}

H
Haojun Liao 已提交
1384
static int32_t doSetCurrentBlock(SDataBlockIter* pBlockIter, const char* idStr) {
1385 1386
  SFileDataBlockInfo* pBlockInfo = getCurrentBlockInfo(pBlockIter);
  if (pBlockInfo != NULL) {
H
Haojun Liao 已提交
1387
    STableBlockScanInfo* pScanInfo = getTableBlockScanInfo(pBlockIter->pTableMap, pBlockInfo->uid, idStr);
H
Haojun Liao 已提交
1388
    if (pScanInfo == NULL) {
H
Haojun Liao 已提交
1389
      return terrno;
H
Haojun Liao 已提交
1390 1391
    }

H
Haojun Liao 已提交
1392 1393
    SBlockIndex* pIndex = taosArrayGet(pScanInfo->pBlockList, pBlockInfo->tbBlockIdx);
    tMapDataGetItemByIdx(&pScanInfo->mapData, pIndex->ordinalIndex, &pBlockIter->block, tGetDataBlk);
1394
  }
1395 1396 1397 1398 1399 1400

#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 已提交
1401
}
H
Hongze Cheng 已提交
1402

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

1406
  SBlockOrderSupporter sup = {0};
1407
  pBlockIter->numOfBlocks = numOfBlocks;
1408
  taosArrayClear(pBlockIter->blockList);
1409
  pBlockIter->pTableMap = pReader->status.pTableMap;
1410

1411 1412
  // 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 已提交
1413

1414
  int64_t st = taosGetTimestampUs();
1415
  int32_t code = initBlockOrderSupporter(&sup, numOfTables);
1416 1417 1418
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }
H
Haojun Liao 已提交
1419

1420 1421 1422 1423 1424 1425 1426
  int32_t cnt = 0;
  void*   ptr = NULL;
  while (1) {
    ptr = taosHashIterate(pReader->status.pTableMap, ptr);
    if (ptr == NULL) {
      break;
    }
H
Haojun Liao 已提交
1427

1428
    STableBlockScanInfo* pTableScanInfo = *(STableBlockScanInfo**)ptr;
1429 1430 1431
    if (pTableScanInfo->pBlockList == NULL || taosArrayGetSize(pTableScanInfo->pBlockList) == 0) {
      continue;
    }
H
Haojun Liao 已提交
1432

1433 1434
    size_t num = taosArrayGetSize(pTableScanInfo->pBlockList);
    sup.numOfBlocksPerTable[sup.numOfTables] = num;
H
Haojun Liao 已提交
1435

1436 1437 1438
    char* buf = taosMemoryMalloc(sizeof(SBlockOrderWrapper) * num);
    if (buf == NULL) {
      cleanupBlockOrderSupporter(&sup);
S
Shengliang Guan 已提交
1439
      return TSDB_CODE_OUT_OF_MEMORY;
1440
    }
H
Haojun Liao 已提交
1441

1442
    sup.pDataBlockInfo[sup.numOfTables] = (SBlockOrderWrapper*)buf;
1443

1444 1445 1446
    for (int32_t k = 0; k < num; ++k) {
      SBlockIndex* pIndex = taosArrayGet(pTableScanInfo->pBlockList, k);
      sup.pDataBlockInfo[sup.numOfTables][k] =
1447
          (SBlockOrderWrapper){.uid = pTableScanInfo->uid, .offset = pIndex->inFileOffset};
1448 1449 1450 1451 1452
      cnt++;
    }

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

H
Haojun Liao 已提交
1454 1455 1456 1457
  if (numOfBlocks != cnt && sup.numOfTables != numOfTables) {
    cleanupBlockOrderSupporter(&sup);
    return TSDB_CODE_INVALID_PARA;
  }
H
Haojun Liao 已提交
1458

1459
  // since there is only one table qualified, blocks are not sorted
1460 1461
  if (sup.numOfTables == 1) {
    for (int32_t i = 0; i < numOfBlocks; ++i) {
1462 1463
      SFileDataBlockInfo blockInfo = {.uid = sup.pDataBlockInfo[0][i].uid, .tbBlockIdx = i};
      taosArrayPush(pBlockIter->blockList, &blockInfo);
1464
    }
1465

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

1470
    pBlockIter->index = asc ? 0 : (numOfBlocks - 1);
H
Haojun Liao 已提交
1471
    cleanupBlockOrderSupporter(&sup);
H
Haojun Liao 已提交
1472
    doSetCurrentBlock(pBlockIter, pReader->idStr);
1473
    return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
1474
  }
H
Haojun Liao 已提交
1475

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

1479
  SMultiwayMergeTreeInfo* pTree = NULL;
H
Haojun Liao 已提交
1480 1481

  uint8_t ret = tMergeTreeCreate(&pTree, sup.numOfTables, &sup, fileDataBlockOrderCompar);
1482 1483
  if (ret != TSDB_CODE_SUCCESS) {
    cleanupBlockOrderSupporter(&sup);
S
Shengliang Guan 已提交
1484
    return TSDB_CODE_OUT_OF_MEMORY;
H
Haojun Liao 已提交
1485
  }
H
Haojun Liao 已提交
1486

1487 1488 1489 1490
  int32_t numOfTotal = 0;
  while (numOfTotal < cnt) {
    int32_t pos = tMergeTreeGetChosenIndex(pTree);
    int32_t index = sup.indexPerTable[pos]++;
H
Haojun Liao 已提交
1491

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

1495 1496 1497 1498
    // 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 已提交
1499

1500 1501
    numOfTotal += 1;
    tMergeTreeAdjust(pTree, tMergeTreeGetAdjustIndex(pTree));
H
Haojun Liao 已提交
1502
  }
H
Haojun Liao 已提交
1503

1504
  int64_t et = taosGetTimestampUs();
H
Hongze Cheng 已提交
1505 1506
  tsdbDebug("%p %d data blocks access order completed, elapsed time:%.2f ms %s", pReader, numOfBlocks,
            (et - st) / 1000.0, pReader->idStr);
1507 1508
  cleanupBlockOrderSupporter(&sup);
  taosMemoryFree(pTree);
H
Haojun Liao 已提交
1509

1510
  pBlockIter->index = asc ? 0 : (numOfBlocks - 1);
H
Haojun Liao 已提交
1511
  doSetCurrentBlock(pBlockIter, pReader->idStr);
1512

1513
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
1514
}
H
Hongze Cheng 已提交
1515

H
Haojun Liao 已提交
1516
static bool blockIteratorNext(SDataBlockIter* pBlockIter, const char* idStr) {
1517 1518
  bool asc = ASCENDING_TRAVERSE(pBlockIter->order);

1519
  int32_t step = asc ? 1 : -1;
1520
  if ((pBlockIter->index >= pBlockIter->numOfBlocks - 1 && asc) || (pBlockIter->index <= 0 && (!asc))) {
1521 1522 1523
    return false;
  }

1524
  pBlockIter->index += step;
H
Haojun Liao 已提交
1525
  doSetCurrentBlock(pBlockIter, idStr);
1526

1527 1528 1529
  return true;
}

1530 1531 1532
/**
 * This is an two rectangles overlap cases.
 */
H
Hongze Cheng 已提交
1533
static int32_t dataBlockPartiallyRequired(STimeWindow* pWindow, SVersionRange* pVerRange, SDataBlk* pBlock) {
1534 1535
  return (pWindow->ekey < pBlock->maxKey.ts && pWindow->ekey >= pBlock->minKey.ts) ||
         (pWindow->skey > pBlock->minKey.ts && pWindow->skey <= pBlock->maxKey.ts) ||
H
Hongze Cheng 已提交
1536 1537
         (pVerRange->minVer > pBlock->minVer && pVerRange->minVer <= pBlock->maxVer) ||
         (pVerRange->maxVer < pBlock->maxVer && pVerRange->maxVer >= pBlock->minVer);
H
Haojun Liao 已提交
1538
}
H
Hongze Cheng 已提交
1539

1540
static bool getNeighborBlockOfSameTable(SFileDataBlockInfo* pBlockInfo, STableBlockScanInfo* pTableBlockScanInfo,
1541
                                        int32_t* nextIndex, int32_t order, SBlockIndex* pBlockIndex) {
1542
  bool asc = ASCENDING_TRAVERSE(order);
H
Haojun Liao 已提交
1543
  if (asc && pBlockInfo->tbBlockIdx >= taosArrayGetSize(pTableBlockScanInfo->pBlockList) - 1) {
1544
    return false;
1545 1546
  }

H
Haojun Liao 已提交
1547
  if (!asc && pBlockInfo->tbBlockIdx == 0) {
1548
    return false;
1549 1550
  }

1551
  int32_t step = asc ? 1 : -1;
H
Haojun Liao 已提交
1552
  *nextIndex = pBlockInfo->tbBlockIdx + step;
1553 1554
  *pBlockIndex = *(SBlockIndex*)taosArrayGet(pTableBlockScanInfo->pBlockList, *nextIndex);
  //  tMapDataGetItemByIdx(&pTableBlockScanInfo->mapData, pIndex->ordinalIndex, pBlock, tGetDataBlk);
1555
  return true;
1556 1557 1558
}

static int32_t findFileBlockInfoIndex(SDataBlockIter* pBlockIter, SFileDataBlockInfo* pFBlockInfo) {
1559
  int32_t step = ASCENDING_TRAVERSE(pBlockIter->order) ? 1 : -1;
1560 1561
  int32_t index = pBlockIter->index;

1562
  while (index < pBlockIter->numOfBlocks && index >= 0) {
1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573
    SFileDataBlockInfo* pFBlock = taosArrayGet(pBlockIter->blockList, index);
    if (pFBlock->uid == pFBlockInfo->uid && pFBlock->tbBlockIdx == pFBlockInfo->tbBlockIdx) {
      return index;
    }

    index += step;
  }

  return -1;
}

1574
static int32_t setFileBlockActiveInBlockIter(SDataBlockIter* pBlockIter, int32_t index, int32_t step) {
1575
  if (index < 0 || index >= pBlockIter->numOfBlocks) {
1576 1577 1578 1579
    return -1;
  }

  SFileDataBlockInfo fblock = *(SFileDataBlockInfo*)taosArrayGet(pBlockIter->blockList, index);
1580 1581 1582 1583 1584
  pBlockIter->index += step;

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

1586 1587 1588
    SFileDataBlockInfo* pBlockInfo = taosArrayGet(pBlockIter->blockList, pBlockIter->index);
    ASSERT(pBlockInfo->uid == fblock.uid && pBlockInfo->tbBlockIdx == fblock.tbBlockIdx);
  }
1589

H
Haojun Liao 已提交
1590
  doSetCurrentBlock(pBlockIter, "");
1591 1592 1593
  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
1594
// todo: this attribute could be acquired during extractin the global ordered block list.
1595
static bool overlapWithNeighborBlock(SDataBlk* pBlock, SBlockIndex* pNeighborBlockIndex, int32_t order) {
1596 1597
  // it is the last block in current file, no chance to overlap with neighbor blocks.
  if (ASCENDING_TRAVERSE(order)) {
1598
    return pBlock->maxKey.ts == pNeighborBlockIndex->window.skey;
1599
  } else {
1600
    return pBlock->minKey.ts == pNeighborBlockIndex->window.ekey;
1601
  }
H
Haojun Liao 已提交
1602
}
H
Hongze Cheng 已提交
1603

H
Hongze Cheng 已提交
1604
static bool bufferDataInFileBlockGap(int32_t order, TSDBKEY key, SDataBlk* pBlock) {
H
Haojun Liao 已提交
1605
  bool ascScan = ASCENDING_TRAVERSE(order);
H
Hongze Cheng 已提交
1606

1607
  return (ascScan && (key.ts != TSKEY_INITIAL_VAL && key.ts <= pBlock->minKey.ts)) ||
1608
         (!ascScan && (key.ts != TSKEY_INITIAL_VAL && key.ts >= pBlock->maxKey.ts));
H
Haojun Liao 已提交
1609
}
H
Hongze Cheng 已提交
1610

H
Hongze Cheng 已提交
1611
static bool keyOverlapFileBlock(TSDBKEY key, SDataBlk* pBlock, SVersionRange* pVerRange) {
H
Hongze Cheng 已提交
1612 1613
  return (key.ts >= pBlock->minKey.ts && key.ts <= pBlock->maxKey.ts) && (pBlock->maxVer >= pVerRange->minVer) &&
         (pBlock->minVer <= pVerRange->maxVer);
H
Haojun Liao 已提交
1614 1615
}

H
Hongze Cheng 已提交
1616 1617
static bool doCheckforDatablockOverlap(STableBlockScanInfo* pBlockScanInfo, const SDataBlk* pBlock,
                                       int32_t startIndex) {
1618 1619
  size_t num = taosArrayGetSize(pBlockScanInfo->delSkyline);

1620
  for (int32_t i = startIndex; i < num; i += 1) {
1621 1622
    TSDBKEY* p = taosArrayGet(pBlockScanInfo->delSkyline, i);
    if (p->ts >= pBlock->minKey.ts && p->ts <= pBlock->maxKey.ts) {
H
Hongze Cheng 已提交
1623
      if (p->version >= pBlock->minVer) {
1624 1625 1626
        return true;
      }
    } else if (p->ts < pBlock->minKey.ts) {  // p->ts < pBlock->minKey.ts
H
Hongze Cheng 已提交
1627
      if (p->version >= pBlock->minVer) {
1628 1629
        if (i < num - 1) {
          TSDBKEY* pnext = taosArrayGet(pBlockScanInfo->delSkyline, i + 1);
H
Hongze Cheng 已提交
1630 1631
          if (pnext->ts >= pBlock->minKey.ts) {
            return true;
1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644
          }
        } else {  // it must be the last point
          ASSERT(p->version == 0);
        }
      }
    } else {  // (p->ts > pBlock->maxKey.ts) {
      return false;
    }
  }

  return false;
}

H
Hongze Cheng 已提交
1645
static bool overlapWithDelSkyline(STableBlockScanInfo* pBlockScanInfo, const SDataBlk* pBlock, int32_t order) {
1646 1647 1648 1649
  if (pBlockScanInfo->delSkyline == NULL) {
    return false;
  }

1650
  // ts is not overlap
1651
  TSDBKEY* pFirst = taosArrayGet(pBlockScanInfo->delSkyline, 0);
L
Liu Jicong 已提交
1652
  TSDBKEY* pLast = taosArrayGetLast(pBlockScanInfo->delSkyline);
1653 1654 1655 1656 1657
  if (pBlock->minKey.ts > pLast->ts || pBlock->maxKey.ts < pFirst->ts) {
    return false;
  }

  // version is not overlap
1658
  if (ASCENDING_TRAVERSE(order)) {
1659
    return doCheckforDatablockOverlap(pBlockScanInfo, pBlock, pBlockScanInfo->fileDelIndex);
1660 1661
  } else {
    int32_t index = pBlockScanInfo->fileDelIndex;
1662
    while (1) {
1663 1664 1665 1666 1667
      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;
1668 1669 1670
      }
    }

1671
    return doCheckforDatablockOverlap(pBlockScanInfo, pBlock, index);
1672
  }
1673 1674
}

C
Cary Xu 已提交
1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687
typedef struct {
  bool overlapWithNeighborBlock;
  bool hasDupTs;
  bool overlapWithDelInfo;
  bool overlapWithLastBlock;
  bool overlapWithKeyInBuf;
  bool partiallyRequired;
  bool moreThanCapcity;
} SDataBlockToLoadInfo;

static void getBlockToLoadInfo(SDataBlockToLoadInfo* pInfo, SFileDataBlockInfo* pBlockInfo, SDataBlk* pBlock,
                               STableBlockScanInfo* pScanInfo, TSDBKEY keyInBuf, SLastBlockReader* pLastBlockReader,
                               STsdbReader* pReader) {
1688 1689
  int32_t     neighborIndex = 0;
  SBlockIndex bIndex = {0};
1690

1691
  bool hasNeighbor = getNeighborBlockOfSameTable(pBlockInfo, pScanInfo, &neighborIndex, pReader->order, &bIndex);
1692

1693
  // overlap with neighbor
1694
  if (hasNeighbor) {
1695
    pInfo->overlapWithNeighborBlock = overlapWithNeighborBlock(pBlock, &bIndex, pReader->order);
1696 1697
  }

1698
  // has duplicated ts of different version in this block
C
Cary Xu 已提交
1699 1700
  pInfo->hasDupTs = (pBlock->nSubBlock == 1) ? pBlock->hasDup : true;
  pInfo->overlapWithDelInfo = overlapWithDelSkyline(pScanInfo, pBlock, pReader->order);
1701

1702 1703 1704
  if (hasDataInLastBlock(pLastBlockReader)) {
    int64_t tsLast = getCurrentKeyInLastBlock(pLastBlockReader);
    pInfo->overlapWithLastBlock = !(pBlock->maxKey.ts < tsLast || pBlock->minKey.ts > tsLast);
1705 1706
  }

C
Cary Xu 已提交
1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721
  pInfo->moreThanCapcity = pBlock->nRow > pReader->capacity;
  pInfo->partiallyRequired = dataBlockPartiallyRequired(&pReader->window, &pReader->verRange, pBlock);
  pInfo->overlapWithKeyInBuf = keyOverlapFileBlock(keyInBuf, pBlock, &pReader->verRange);
}

// 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
// 5. delete info should not overlap with current block data
// 6. current block should not contain the duplicated ts
static bool fileBlockShouldLoad(STsdbReader* pReader, SFileDataBlockInfo* pBlockInfo, SDataBlk* pBlock,
                                STableBlockScanInfo* pScanInfo, TSDBKEY keyInBuf, SLastBlockReader* pLastBlockReader) {
  SDataBlockToLoadInfo info = {0};
  getBlockToLoadInfo(&info, pBlockInfo, pBlock, pScanInfo, keyInBuf, pLastBlockReader, pReader);
1722

C
Cary Xu 已提交
1723 1724 1725
  bool loadDataBlock =
      (info.overlapWithNeighborBlock || info.hasDupTs || info.partiallyRequired || info.overlapWithKeyInBuf ||
       info.moreThanCapcity || info.overlapWithDelInfo || info.overlapWithLastBlock);
1726 1727 1728 1729

  // log the reason why load the datablock for profile
  if (loadDataBlock) {
    tsdbDebug("%p uid:%" PRIu64
X
Xiaoyu Wang 已提交
1730
              " need to load the datablock, overlapneighbor:%d, hasDup:%d, partiallyRequired:%d, "
1731
              "overlapWithKey:%d, greaterThanBuf:%d, overlapWithDel:%d, overlapWithlastBlock:%d, %s",
C
Cary Xu 已提交
1732 1733 1734
              pReader, pBlockInfo->uid, info.overlapWithNeighborBlock, info.hasDupTs, info.partiallyRequired,
              info.overlapWithKeyInBuf, info.moreThanCapcity, info.overlapWithDelInfo, info.overlapWithLastBlock,
              pReader->idStr);
1735 1736 1737
  }

  return loadDataBlock;
H
Haojun Liao 已提交
1738 1739
}

C
Cary Xu 已提交
1740 1741 1742 1743 1744 1745 1746 1747 1748
static bool isCleanFileDataBlock(STsdbReader* pReader, SFileDataBlockInfo* pBlockInfo, SDataBlk* pBlock,
                                 STableBlockScanInfo* pScanInfo, TSDBKEY keyInBuf, SLastBlockReader* pLastBlockReader) {
  SDataBlockToLoadInfo info = {0};
  getBlockToLoadInfo(&info, pBlockInfo, pBlock, pScanInfo, keyInBuf, pLastBlockReader, pReader);
  bool isCleanFileBlock = !(info.overlapWithNeighborBlock || info.hasDupTs || info.overlapWithKeyInBuf ||
                            info.overlapWithDelInfo || info.overlapWithLastBlock);
  return isCleanFileBlock;
}

1749
static int32_t buildDataBlockFromBuf(STsdbReader* pReader, STableBlockScanInfo* pBlockScanInfo, int64_t endKey) {
1750
  if (!(pBlockScanInfo->iiter.hasVal || pBlockScanInfo->iter.hasVal)) {
1751 1752
    return TSDB_CODE_SUCCESS;
  }
H
Haojun Liao 已提交
1753

1754 1755 1756
  SSDataBlock* pBlock = pReader->pResBlock;

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

H
Haojun Liao 已提交
1759
  blockDataUpdateTsWindow(pBlock, pReader->suppInfo.slotId[0]);
H
Haojun Liao 已提交
1760
  pBlock->info.id.uid = pBlockScanInfo->uid;
1761

1762
  setComposedBlockFlag(pReader, true);
1763

1764
  double elapsedTime = (taosGetTimestampUs() - st) / 1000.0;
S
Shengliang Guan 已提交
1765
  tsdbDebug("%p build data block from cache completed, elapsed time:%.2f ms, numOfRows:%d, brange:%" PRId64
X
Xiaoyu Wang 已提交
1766
            " - %" PRId64 ", uid:%" PRIu64 ",  %s",
1767
            pReader, elapsedTime, pBlock->info.rows, pBlock->info.window.skey, pBlock->info.window.ekey,
1768
            pBlockScanInfo->uid, pReader->idStr);
1769 1770

  pReader->cost.buildmemBlock += elapsedTime;
H
Haojun Liao 已提交
1771 1772 1773
  return code;
}

1774 1775
static bool tryCopyDistinctRowFromFileBlock(STsdbReader* pReader, SBlockData* pBlockData, int64_t key,
                                            SFileBlockDumpInfo* pDumpInfo) {
1776 1777 1778
  // opt version
  // 1. it is not a border point
  // 2. the direct next point is not an duplicated timestamp
1779 1780
  bool asc = (pReader->order == TSDB_ORDER_ASC);
  if ((pDumpInfo->rowIndex < pDumpInfo->totalRows - 1 && asc) || (pDumpInfo->rowIndex > 0 && (!asc))) {
1781
    int32_t step = pReader->order == TSDB_ORDER_ASC ? 1 : -1;
1782 1783

    int64_t nextKey = pBlockData->aTSKEY[pDumpInfo->rowIndex + step];
1784
    if (nextKey != key) {  // merge is not needed
1785
      doAppendRowFromFileBlock(pReader->pResBlock, pReader, pBlockData, pDumpInfo->rowIndex);
1786 1787 1788 1789 1790 1791 1792 1793
      pDumpInfo->rowIndex += step;
      return true;
    }
  }

  return false;
}

1794
static bool nextRowFromLastBlocks(SLastBlockReader* pLastBlockReader, STableBlockScanInfo* pScanInfo,
1795
                                  SVersionRange* pVerRange) {
X
Xiaoyu Wang 已提交
1796
  int32_t step = ASCENDING_TRAVERSE(pLastBlockReader->order) ? 1 : -1;
H
Haojun Liao 已提交
1797

1798 1799
  while (1) {
    bool hasVal = tMergeTreeNext(&pLastBlockReader->mergeTree);
1800 1801
    if (!hasVal) { // the next value will be the accessed key in stt
      pScanInfo->lastKeyInStt += step;
1802 1803 1804 1805 1806
      return false;
    }

    TSDBROW row = tMergeTreeGetRow(&pLastBlockReader->mergeTree);
    TSDBKEY k = TSDBROW_KEY(&row);
1807 1808 1809
    pScanInfo->lastKeyInStt = k.ts;

    if (!hasBeenDropped(pScanInfo->delSkyline, &pScanInfo->lastBlockDelIndex, &k, pLastBlockReader->order, pVerRange)) {
H
Haojun Liao 已提交
1810 1811
      // the qualifed ts may equal to k.ts, only a greater version one.
      // here we need to fallback one step.
1812 1813 1814
//      if (pScanInfo->lastKey == k.ts) {
//        pScanInfo->lastKey -= step;
//      }
1815 1816 1817 1818 1819 1820 1821
      return true;
    }
  }
}

static bool tryCopyDistinctRowFromSttBlock(TSDBROW* fRow, SLastBlockReader* pLastBlockReader,
                                           STableBlockScanInfo* pScanInfo, int64_t ts, STsdbReader* pReader) {
1822
  bool hasVal = nextRowFromLastBlocks(pLastBlockReader, pScanInfo, &pReader->verRange);
1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836
  if (hasVal) {
    int64_t next1 = getCurrentKeyInLastBlock(pLastBlockReader);
    if (next1 != ts) {
      doAppendRowFromFileBlock(pReader->pResBlock, pReader, fRow->pBlockData, fRow->iRow);
      return true;
    }
  } else {
    doAppendRowFromFileBlock(pReader->pResBlock, pReader, fRow->pBlockData, fRow->iRow);
    return true;
  }

  return false;
}

1837 1838 1839 1840 1841 1842
static FORCE_INLINE STSchema* getLatestTableSchema(STsdbReader* pReader, uint64_t uid) {
  if (pReader->pSchema != NULL) {
    return pReader->pSchema;
  }

  pReader->pSchema = metaGetTbTSchema(pReader->pTsdb->pVnode->pMeta, uid, -1, 1);
X
Xiaoyu Wang 已提交
1843
  if (pReader->pSchema == NULL) {
1844 1845 1846
    tsdbError("failed to get table schema, uid:%" PRIu64 ", it may have been dropped, ver:-1, %s", uid, pReader->idStr);
  }

X
Xiaoyu Wang 已提交
1847
  return pReader->pSchema;
1848 1849
}

H
Haojun Liao 已提交
1850 1851 1852
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) {
1853
    pReader->pSchema = metaGetTbTSchema(pReader->pTsdb->pVnode->pMeta, uid, -1, 1);
H
Haojun Liao 已提交
1854 1855
  }

1856
  if (pReader->pSchema && sversion == pReader->pSchema->version) {
H
Haojun Liao 已提交
1857 1858 1859 1860 1861 1862
    return pReader->pSchema;
  }

  if (pReader->pMemSchema == NULL) {
    int32_t code =
        metaGetTbTSchemaEx(pReader->pTsdb->pVnode->pMeta, pReader->suid, uid, sversion, &pReader->pMemSchema);
H
Haojun Liao 已提交
1863 1864 1865 1866 1867 1868
    if (code != TSDB_CODE_SUCCESS) {
      terrno = code;
      return NULL;
    } else {
      return pReader->pMemSchema;
    }
H
Haojun Liao 已提交
1869 1870 1871 1872 1873 1874
  }

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

H
Haojun Liao 已提交
1875
  taosMemoryFreeClear(pReader->pMemSchema);
H
Haojun Liao 已提交
1876
  int32_t code = metaGetTbTSchemaEx(pReader->pTsdb->pVnode->pMeta, pReader->suid, uid, sversion, &pReader->pMemSchema);
H
Haojun Liao 已提交
1877
  if (code != TSDB_CODE_SUCCESS || pReader->pMemSchema == NULL) {
H
Haojun Liao 已提交
1878 1879
    terrno = code;
    return NULL;
H
Haojun Liao 已提交
1880 1881
  } else {
    return pReader->pMemSchema;
H
Haojun Liao 已提交
1882
  }
H
Haojun Liao 已提交
1883 1884
}

1885
static int32_t doMergeBufAndFileRows(STsdbReader* pReader, STableBlockScanInfo* pBlockScanInfo, TSDBROW* pRow,
1886 1887
                                     SIterInfo* pIter, int64_t key, SLastBlockReader* pLastBlockReader) {
  SRowMerger          merge = {0};
H
Hongze Cheng 已提交
1888
  SRow*               pTSRow = NULL;
1889 1890 1891
  SBlockData*         pBlockData = &pReader->status.fileBlockData;
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;

1892
  int64_t tsLast = INT64_MIN;
1893
  if (hasDataInLastBlock(pLastBlockReader)) {
1894 1895
    tsLast = getCurrentKeyInLastBlock(pLastBlockReader);
  }
1896

H
Hongze Cheng 已提交
1897 1898
  TSDBKEY k = TSDBROW_KEY(pRow);
  TSDBROW fRow = tsdbRowFromBlockData(pBlockData, pDumpInfo->rowIndex);
1899

1900 1901
  int64_t minKey = 0;
  if (pReader->order == TSDB_ORDER_ASC) {
H
Hongze Cheng 已提交
1902
    minKey = INT64_MAX;  // chosen the minimum value
1903
    if (minKey > tsLast && hasDataInLastBlock(pLastBlockReader)) {
1904 1905
      minKey = tsLast;
    }
1906

1907 1908 1909
    if (minKey > k.ts) {
      minKey = k.ts;
    }
1910

1911
    if (minKey > key && hasDataInFileBlock(pBlockData, pDumpInfo)) {
1912 1913 1914 1915
      minKey = key;
    }
  } else {
    minKey = INT64_MIN;
1916
    if (minKey < tsLast && hasDataInLastBlock(pLastBlockReader)) {
1917 1918 1919 1920 1921 1922 1923
      minKey = tsLast;
    }

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

1924
    if (minKey < key && hasDataInFileBlock(pBlockData, pDumpInfo)) {
1925 1926
      minKey = key;
    }
1927 1928 1929 1930
  }

  bool init = false;

1931
  // ASC: file block ---> last block -----> imem -----> mem
H
Hongze Cheng 已提交
1932
  // DESC: mem -----> imem -----> last block -----> file block
1933 1934
  if (pReader->order == TSDB_ORDER_ASC) {
    if (minKey == key) {
1935
      init = true;
H
Hongze Cheng 已提交
1936
      int32_t code = tsdbRowMergerInit(&merge, &fRow, pReader->pSchema);
H
Haojun Liao 已提交
1937 1938 1939
      if (code != TSDB_CODE_SUCCESS) {
        return code;
      }
1940
      doMergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pReader, &merge);
1941 1942
    }

1943
    if (minKey == tsLast) {
1944
      TSDBROW fRow1 = tMergeTreeGetRow(&pLastBlockReader->mergeTree);
H
Haojun Liao 已提交
1945
      if (init) {
H
Hongze Cheng 已提交
1946
        tsdbRowMerge(&merge, &fRow1);
H
Haojun Liao 已提交
1947
      } else {
1948
        init = true;
H
Hongze Cheng 已提交
1949
        int32_t code = tsdbRowMergerInit(&merge, &fRow1, pReader->pSchema);
H
Haojun Liao 已提交
1950 1951 1952
        if (code != TSDB_CODE_SUCCESS) {
          return code;
        }
1953
      }
1954
      doMergeRowsInLastBlock(pLastBlockReader, pBlockScanInfo, tsLast, &merge, &pReader->verRange, pReader->idStr);
1955
    }
1956

1957
    if (minKey == k.ts) {
K
kailixu 已提交
1958 1959 1960 1961
      STSchema* pSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(pRow), pReader, pBlockScanInfo->uid);
      if (pSchema == NULL) {
        return terrno;
      }
H
Haojun Liao 已提交
1962
      if (init) {
X
Xiaoyu Wang 已提交
1963
        tsdbRowMergerAdd(&merge, pRow, pSchema);
H
Haojun Liao 已提交
1964
      } else {
1965
        init = true;
X
Xiaoyu Wang 已提交
1966
        int32_t code = tsdbRowMergerInit(&merge, pRow, pSchema);
H
Haojun Liao 已提交
1967 1968 1969 1970 1971 1972 1973
        if (code != TSDB_CODE_SUCCESS) {
          return code;
        }
      }
      int32_t code = doMergeRowsInBuf(pIter, pBlockScanInfo->uid, k.ts, pBlockScanInfo->delSkyline, &merge, pReader);
      if (code != TSDB_CODE_SUCCESS) {
        return code;
1974 1975 1976 1977 1978
      }
    }
  } else {
    if (minKey == k.ts) {
      init = true;
1979
      STSchema* pSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(pRow), pReader, pBlockScanInfo->uid);
H
Hongze Cheng 已提交
1980
      int32_t   code = tsdbRowMergerInit(&merge, pRow, pSchema);
H
Haojun Liao 已提交
1981 1982 1983 1984 1985
      if (code != TSDB_CODE_SUCCESS) {
        return code;
      }

      code = doMergeRowsInBuf(pIter, pBlockScanInfo->uid, k.ts, pBlockScanInfo->delSkyline, &merge, pReader);
1986
      if (code != TSDB_CODE_SUCCESS || merge.pTSchema == NULL) {
H
Haojun Liao 已提交
1987 1988
        return code;
      }
1989 1990
    }

1991
    if (minKey == tsLast) {
1992
      TSDBROW fRow1 = tMergeTreeGetRow(&pLastBlockReader->mergeTree);
H
Haojun Liao 已提交
1993
      if (init) {
H
Hongze Cheng 已提交
1994
        tsdbRowMerge(&merge, &fRow1);
H
Haojun Liao 已提交
1995
      } else {
1996
        init = true;
H
Hongze Cheng 已提交
1997
        int32_t code = tsdbRowMergerInit(&merge, &fRow1, pReader->pSchema);
H
Haojun Liao 已提交
1998 1999 2000
        if (code != TSDB_CODE_SUCCESS) {
          return code;
        }
2001
      }
2002
      doMergeRowsInLastBlock(pLastBlockReader, pBlockScanInfo, tsLast, &merge, &pReader->verRange, pReader->idStr);
2003 2004 2005
    }

    if (minKey == key) {
H
Haojun Liao 已提交
2006
      if (init) {
H
Hongze Cheng 已提交
2007
        tsdbRowMerge(&merge, &fRow);
H
Haojun Liao 已提交
2008
      } else {
2009
        init = true;
H
Hongze Cheng 已提交
2010
        int32_t code = tsdbRowMergerInit(&merge, &fRow, pReader->pSchema);
H
Haojun Liao 已提交
2011 2012 2013
        if (code != TSDB_CODE_SUCCESS) {
          return code;
        }
2014 2015 2016
      }
      doMergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pReader, &merge);
    }
2017 2018
  }

H
Hongze Cheng 已提交
2019
  int32_t code = tsdbRowMergerGetRow(&merge, &pTSRow);
2020 2021 2022 2023
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

2024
  doAppendRowFromTSRow(pReader->pResBlock, pReader, pTSRow, pBlockScanInfo);
2025 2026

  taosMemoryFree(pTSRow);
H
Hongze Cheng 已提交
2027
  tsdbRowMergerClear(&merge);
2028 2029 2030
  return TSDB_CODE_SUCCESS;
}

2031 2032 2033
static int32_t doMergeFileBlockAndLastBlock(SLastBlockReader* pLastBlockReader, STsdbReader* pReader,
                                            STableBlockScanInfo* pBlockScanInfo, SBlockData* pBlockData,
                                            bool mergeBlockData) {
2034
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;
H
Hongze Cheng 已提交
2035
  int64_t             tsLastBlock = getCurrentKeyInLastBlock(pLastBlockReader);
2036

H
Hongze Cheng 已提交
2037
  SRow*      pTSRow = NULL;
2038
  SRowMerger merge = {0};
2039
  TSDBROW    fRow = tMergeTreeGetRow(&pLastBlockReader->mergeTree);
H
Hongze Cheng 已提交
2040
  tsdbTrace("fRow ptr:%p, %d, uid:%" PRIu64 ", %s", fRow.pBlockData, fRow.iRow, pLastBlockReader->uid, pReader->idStr);
2041

2042 2043 2044
  // only last block exists
  if ((!mergeBlockData) || (tsLastBlock != pBlockData->aTSKEY[pDumpInfo->rowIndex])) {
    if (tryCopyDistinctRowFromSttBlock(&fRow, pLastBlockReader, pBlockScanInfo, tsLastBlock, pReader)) {
2045
      pBlockScanInfo->lastKey = tsLastBlock;
2046 2047
      return TSDB_CODE_SUCCESS;
    } else {
H
Hongze Cheng 已提交
2048
      int32_t code = tsdbRowMergerInit(&merge, &fRow, pReader->pSchema);
H
Haojun Liao 已提交
2049 2050 2051
      if (code != TSDB_CODE_SUCCESS) {
        return code;
      }
2052

2053
      TSDBROW fRow1 = tMergeTreeGetRow(&pLastBlockReader->mergeTree);
H
Hongze Cheng 已提交
2054
      tsdbRowMerge(&merge, &fRow1);
2055
      doMergeRowsInLastBlock(pLastBlockReader, pBlockScanInfo, tsLastBlock, &merge, &pReader->verRange, pReader->idStr);
2056

H
Hongze Cheng 已提交
2057
      code = tsdbRowMergerGetRow(&merge, &pTSRow);
2058 2059 2060
      if (code != TSDB_CODE_SUCCESS) {
        return code;
      }
2061

2062
      doAppendRowFromTSRow(pReader->pResBlock, pReader, pTSRow, pBlockScanInfo);
2063 2064

      taosMemoryFree(pTSRow);
H
Hongze Cheng 已提交
2065
      tsdbRowMergerClear(&merge);
2066 2067
    }
  } else {  // not merge block data
H
Hongze Cheng 已提交
2068
    int32_t code = tsdbRowMergerInit(&merge, &fRow, pReader->pSchema);
H
Haojun Liao 已提交
2069 2070 2071 2072
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

2073
    doMergeRowsInLastBlock(pLastBlockReader, pBlockScanInfo, tsLastBlock, &merge, &pReader->verRange, pReader->idStr);
2074 2075

    // merge with block data if ts == key
H
Haojun Liao 已提交
2076
    if (tsLastBlock == pBlockData->aTSKEY[pDumpInfo->rowIndex]) {
2077 2078 2079
      doMergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pReader, &merge);
    }

H
Hongze Cheng 已提交
2080
    code = tsdbRowMergerGetRow(&merge, &pTSRow);
2081 2082 2083 2084
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

2085
    doAppendRowFromTSRow(pReader->pResBlock, pReader, pTSRow, pBlockScanInfo);
2086 2087

    taosMemoryFree(pTSRow);
H
Hongze Cheng 已提交
2088
    tsdbRowMergerClear(&merge);
2089
  }
2090 2091 2092 2093

  return TSDB_CODE_SUCCESS;
}

2094 2095
static int32_t mergeFileBlockAndLastBlock(STsdbReader* pReader, SLastBlockReader* pLastBlockReader, int64_t key,
                                          STableBlockScanInfo* pBlockScanInfo, SBlockData* pBlockData) {
2096 2097
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;

2098
  if (hasDataInFileBlock(pBlockData, pDumpInfo)) {
2099
    // no last block available, only data block exists
2100
    if (!hasDataInLastBlock(pLastBlockReader)) {
2101 2102 2103 2104 2105 2106 2107 2108 2109
      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)) {
2110
      if (key < ts) {  // imem, mem are all empty, file blocks (data blocks and last block) exist
2111 2112
        return mergeRowsInFileBlocks(pBlockData, pBlockScanInfo, key, pReader);
      } else if (key == ts) {
H
Hongze Cheng 已提交
2113
        SRow*      pTSRow = NULL;
2114
        SRowMerger merge = {0};
2115

H
Hongze Cheng 已提交
2116
        int32_t code = tsdbRowMergerInit(&merge, &fRow, pReader->pSchema);
H
Haojun Liao 已提交
2117 2118 2119 2120
        if (code != TSDB_CODE_SUCCESS) {
          return code;
        }

2121
        doMergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pReader, &merge);
2122 2123

        TSDBROW fRow1 = tMergeTreeGetRow(&pLastBlockReader->mergeTree);
H
Hongze Cheng 已提交
2124
        tsdbRowMerge(&merge, &fRow1);
2125

2126
        doMergeRowsInLastBlock(pLastBlockReader, pBlockScanInfo, ts, &merge, &pReader->verRange, pReader->idStr);
2127

H
Hongze Cheng 已提交
2128
        code = tsdbRowMergerGetRow(&merge, &pTSRow);
2129 2130 2131 2132
        if (code != TSDB_CODE_SUCCESS) {
          return code;
        }

2133
        doAppendRowFromTSRow(pReader->pResBlock, pReader, pTSRow, pBlockScanInfo);
2134

2135
        taosMemoryFree(pTSRow);
H
Hongze Cheng 已提交
2136
        tsdbRowMergerClear(&merge);
2137
        return code;
2138
      } else {
2139
        return TSDB_CODE_SUCCESS;
2140
      }
2141
    } else {  // desc order
2142
      return doMergeFileBlockAndLastBlock(pLastBlockReader, pReader, pBlockScanInfo, pBlockData, true);
2143
    }
2144
  } else {  // only last block exists
2145
    return doMergeFileBlockAndLastBlock(pLastBlockReader, pReader, pBlockScanInfo, NULL, false);
H
Haojun Liao 已提交
2146
  }
2147 2148
}

2149 2150
static int32_t doMergeMultiLevelRows(STsdbReader* pReader, STableBlockScanInfo* pBlockScanInfo, SBlockData* pBlockData,
                                     SLastBlockReader* pLastBlockReader) {
H
Haojun Liao 已提交
2151
  SRowMerger          merge = {0};
H
Hongze Cheng 已提交
2152
  SRow*               pTSRow = NULL;
H
Haojun Liao 已提交
2153
  int32_t             code = TSDB_CODE_SUCCESS;
2154 2155 2156
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;
  SArray*             pDelList = pBlockScanInfo->delSkyline;

2157 2158
  TSDBROW* pRow = getValidMemRow(&pBlockScanInfo->iter, pDelList, pReader);
  TSDBROW* piRow = getValidMemRow(&pBlockScanInfo->iiter, pDelList, pReader);
2159

2160
  int64_t tsLast = INT64_MIN;
2161 2162 2163
  if (hasDataInLastBlock(pLastBlockReader)) {
    tsLast = getCurrentKeyInLastBlock(pLastBlockReader);
  }
2164

H
Hongze Cheng 已提交
2165
  int64_t key = hasDataInFileBlock(pBlockData, pDumpInfo) ? pBlockData->aTSKEY[pDumpInfo->rowIndex] : INT64_MIN;
2166 2167 2168 2169

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

2170
  int64_t minKey = 0;
2171 2172 2173 2174 2175
  if (ASCENDING_TRAVERSE(pReader->order)) {
    minKey = INT64_MAX;  // let's find the minimum
    if (minKey > k.ts) {
      minKey = k.ts;
    }
2176

2177 2178 2179
    if (minKey > ik.ts) {
      minKey = ik.ts;
    }
2180

2181
    if (minKey > key && hasDataInFileBlock(pBlockData, pDumpInfo)) {
2182 2183
      minKey = key;
    }
2184

2185
    if (minKey > tsLast && hasDataInLastBlock(pLastBlockReader)) {
2186 2187 2188
      minKey = tsLast;
    }
  } else {
H
Hongze Cheng 已提交
2189
    minKey = INT64_MIN;  // let find the maximum ts value
2190 2191 2192 2193 2194 2195 2196 2197
    if (minKey < k.ts) {
      minKey = k.ts;
    }

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

2198
    if (minKey < key && hasDataInFileBlock(pBlockData, pDumpInfo)) {
2199 2200 2201
      minKey = key;
    }

2202
    if (minKey < tsLast && hasDataInLastBlock(pLastBlockReader)) {
2203 2204
      minKey = tsLast;
    }
2205 2206 2207 2208
  }

  bool init = false;

2209 2210 2211 2212
  // ASC: file block -----> last block -----> imem -----> mem
  // DESC: mem -----> imem -----> last block -----> file block
  if (ASCENDING_TRAVERSE(pReader->order)) {
    if (minKey == key) {
2213
      init = true;
2214
      TSDBROW fRow = tsdbRowFromBlockData(pBlockData, pDumpInfo->rowIndex);
H
Hongze Cheng 已提交
2215
      code = tsdbRowMergerInit(&merge, &fRow, pReader->pSchema);
H
Haojun Liao 已提交
2216 2217 2218 2219
      if (code != TSDB_CODE_SUCCESS) {
        return code;
      }

2220
      doMergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pReader, &merge);
2221 2222
    }

2223
    if (minKey == tsLast) {
2224
      TSDBROW fRow1 = tMergeTreeGetRow(&pLastBlockReader->mergeTree);
H
Haojun Liao 已提交
2225
      if (init) {
H
Hongze Cheng 已提交
2226
        tsdbRowMerge(&merge, &fRow1);
H
Haojun Liao 已提交
2227
      } else {
2228
        init = true;
H
Hongze Cheng 已提交
2229
        code = tsdbRowMergerInit(&merge, &fRow1, pReader->pSchema);
H
Haojun Liao 已提交
2230 2231 2232
        if (code != TSDB_CODE_SUCCESS) {
          return code;
        }
2233
      }
H
Haojun Liao 已提交
2234

2235
      doMergeRowsInLastBlock(pLastBlockReader, pBlockScanInfo, tsLast, &merge, &pReader->verRange, pReader->idStr);
2236 2237 2238
    }

    if (minKey == ik.ts) {
H
Haojun Liao 已提交
2239
      if (init) {
H
Hongze Cheng 已提交
2240
        tsdbRowMerge(&merge, piRow);
H
Haojun Liao 已提交
2241
      } else {
2242 2243
        init = true;
        STSchema* pSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(piRow), pReader, pBlockScanInfo->uid);
H
Haojun Liao 已提交
2244 2245 2246 2247
        if (pSchema == NULL) {
          return code;
        }

H
Hongze Cheng 已提交
2248
        code = tsdbRowMergerInit(&merge, piRow, pSchema);
H
Haojun Liao 已提交
2249 2250 2251
        if (code != TSDB_CODE_SUCCESS) {
          return code;
        }
2252
      }
H
Haojun Liao 已提交
2253

2254 2255
      code = doMergeRowsInBuf(&pBlockScanInfo->iiter, pBlockScanInfo->uid, ik.ts, pBlockScanInfo->delSkyline, &merge,
                              pReader);
H
Haojun Liao 已提交
2256 2257
      if (code != TSDB_CODE_SUCCESS) {
        return code;
2258
      }
2259 2260
    }

2261
    if (minKey == k.ts) {
H
Haojun Liao 已提交
2262
      if (init) {
2263 2264 2265 2266
        if (merge.pTSchema == NULL) {
          return code;
        }

H
Hongze Cheng 已提交
2267
        tsdbRowMerge(&merge, pRow);
H
Haojun Liao 已提交
2268
      } else {
2269
        STSchema* pSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(pRow), pReader, pBlockScanInfo->uid);
H
Hongze Cheng 已提交
2270
        code = tsdbRowMergerInit(&merge, pRow, pSchema);
H
Haojun Liao 已提交
2271 2272 2273
        if (code != TSDB_CODE_SUCCESS) {
          return code;
        }
2274
      }
H
Haojun Liao 已提交
2275 2276 2277 2278
      code = doMergeRowsInBuf(&pBlockScanInfo->iter, pBlockScanInfo->uid, k.ts, pBlockScanInfo->delSkyline, &merge,
                              pReader);
      if (code != TSDB_CODE_SUCCESS) {
        return code;
2279 2280 2281 2282 2283
      }
    }
  } else {
    if (minKey == k.ts) {
      init = true;
2284
      STSchema* pSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(pRow), pReader, pBlockScanInfo->uid);
H
Hongze Cheng 已提交
2285
      code = tsdbRowMergerInit(&merge, pRow, pSchema);
H
Haojun Liao 已提交
2286 2287 2288 2289
      if (code != TSDB_CODE_SUCCESS) {
        return code;
      }

H
Haojun Liao 已提交
2290 2291 2292 2293 2294
      code = doMergeRowsInBuf(&pBlockScanInfo->iter, pBlockScanInfo->uid, k.ts, pBlockScanInfo->delSkyline, &merge,
                              pReader);
      if (code != TSDB_CODE_SUCCESS) {
        return code;
      }
2295 2296 2297
    }

    if (minKey == ik.ts) {
H
Haojun Liao 已提交
2298
      if (init) {
H
Hongze Cheng 已提交
2299
        tsdbRowMerge(&merge, piRow);
H
Haojun Liao 已提交
2300
      } else {
2301 2302
        init = true;
        STSchema* pSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(piRow), pReader, pBlockScanInfo->uid);
H
Hongze Cheng 已提交
2303
        code = tsdbRowMergerInit(&merge, piRow, pSchema);
H
Haojun Liao 已提交
2304 2305 2306
        if (code != TSDB_CODE_SUCCESS) {
          return code;
        }
2307
      }
H
Haojun Liao 已提交
2308 2309 2310 2311
      code = doMergeRowsInBuf(&pBlockScanInfo->iiter, pBlockScanInfo->uid, ik.ts, pBlockScanInfo->delSkyline, &merge,
                              pReader);
      if (code != TSDB_CODE_SUCCESS) {
        return code;
2312 2313 2314 2315
      }
    }

    if (minKey == tsLast) {
2316
      TSDBROW fRow1 = tMergeTreeGetRow(&pLastBlockReader->mergeTree);
H
Haojun Liao 已提交
2317
      if (init) {
H
Hongze Cheng 已提交
2318
        tsdbRowMerge(&merge, &fRow1);
H
Haojun Liao 已提交
2319
      } else {
2320
        init = true;
H
Hongze Cheng 已提交
2321
        code = tsdbRowMergerInit(&merge, &fRow1, pReader->pSchema);
H
Haojun Liao 已提交
2322 2323 2324
        if (code != TSDB_CODE_SUCCESS) {
          return code;
        }
2325
      }
2326
      doMergeRowsInLastBlock(pLastBlockReader, pBlockScanInfo, tsLast, &merge, &pReader->verRange, pReader->idStr);
2327 2328 2329
    }

    if (minKey == key) {
H
Haojun Liao 已提交
2330
      TSDBROW fRow = tsdbRowFromBlockData(pBlockData, pDumpInfo->rowIndex);
2331
      if (!init) {
H
Hongze Cheng 已提交
2332
        code = tsdbRowMergerInit(&merge, &fRow, pReader->pSchema);
H
Haojun Liao 已提交
2333 2334 2335
        if (code != TSDB_CODE_SUCCESS) {
          return code;
        }
H
Haojun Liao 已提交
2336
      } else {
2337 2338 2339
        if (merge.pTSchema == NULL) {
          return code;
        }
H
Hongze Cheng 已提交
2340
        tsdbRowMerge(&merge, &fRow);
2341 2342
      }
      doMergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pReader, &merge);
2343 2344 2345
    }
  }

2346
  if (merge.pTSchema == NULL) {
2347 2348 2349
    return code;
  }

H
Hongze Cheng 已提交
2350
  code = tsdbRowMergerGetRow(&merge, &pTSRow);
2351 2352 2353 2354
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

2355
  doAppendRowFromTSRow(pReader->pResBlock, pReader, pTSRow, pBlockScanInfo);
2356 2357

  taosMemoryFree(pTSRow);
H
Hongze Cheng 已提交
2358
  tsdbRowMergerClear(&merge);
2359
  return code;
2360 2361
}

2362 2363 2364 2365 2366 2367 2368 2369 2370
static int32_t initMemDataIterator(STableBlockScanInfo* pBlockScanInfo, STsdbReader* pReader) {
  if (pBlockScanInfo->iterInit) {
    return TSDB_CODE_SUCCESS;
  }

  int32_t code = TSDB_CODE_SUCCESS;

  TSDBKEY startKey = {0};
  if (ASCENDING_TRAVERSE(pReader->order)) {
2371 2372
    // startKey = (TSDBKEY){.ts = pReader->window.skey, .version = pReader->verRange.minVer};
    startKey = (TSDBKEY){.ts = pBlockScanInfo->lastKey + 1, .version = pReader->verRange.minVer};
2373
  } else {
2374 2375
    // startKey = (TSDBKEY){.ts = pReader->window.ekey, .version = pReader->verRange.maxVer};
    startKey = (TSDBKEY){.ts = pBlockScanInfo->lastKey - 1, .version = pReader->verRange.maxVer};
2376 2377 2378
  }

  int32_t backward = (!ASCENDING_TRAVERSE(pReader->order));
D
dapan1121 已提交
2379
  int64_t st = 0;
2380 2381 2382 2383 2384 2385 2386 2387 2388

  STbData* d = NULL;
  if (pReader->pReadSnap->pMem != NULL) {
    d = tsdbGetTbDataFromMemTable(pReader->pReadSnap->pMem, pReader->suid, pBlockScanInfo->uid);
    if (d != NULL) {
      code = tsdbTbDataIterCreate(d, &startKey, backward, &pBlockScanInfo->iter.iter);
      if (code == TSDB_CODE_SUCCESS) {
        pBlockScanInfo->iter.hasVal = (tsdbTbDataIterGet(pBlockScanInfo->iter.iter) != NULL);

H
Haojun Liao 已提交
2389
        tsdbDebug("%p uid:%" PRIu64 ", check data in mem from skey:%" PRId64 ", order:%d, ts range in buf:%" PRId64
H
Hongze Cheng 已提交
2390
                  "-%" PRId64 " %s",
2391 2392
                  pReader, pBlockScanInfo->uid, startKey.ts, pReader->order, d->minKey, d->maxKey, pReader->idStr);
      } else {
H
Haojun Liao 已提交
2393
        tsdbError("%p uid:%" PRIu64 ", failed to create iterator for imem, code:%s, %s", pReader, pBlockScanInfo->uid,
2394 2395 2396 2397 2398
                  tstrerror(code), pReader->idStr);
        return code;
      }
    }
  } else {
H
Haojun Liao 已提交
2399
    tsdbDebug("%p uid:%" PRIu64 ", no data in mem, %s", pReader, pBlockScanInfo->uid, pReader->idStr);
2400 2401 2402 2403 2404 2405 2406 2407 2408 2409
  }

  STbData* di = NULL;
  if (pReader->pReadSnap->pIMem != NULL) {
    di = tsdbGetTbDataFromMemTable(pReader->pReadSnap->pIMem, pReader->suid, pBlockScanInfo->uid);
    if (di != NULL) {
      code = tsdbTbDataIterCreate(di, &startKey, backward, &pBlockScanInfo->iiter.iter);
      if (code == TSDB_CODE_SUCCESS) {
        pBlockScanInfo->iiter.hasVal = (tsdbTbDataIterGet(pBlockScanInfo->iiter.iter) != NULL);

H
Haojun Liao 已提交
2410
        tsdbDebug("%p uid:%" PRIu64 ", check data in imem from skey:%" PRId64 ", order:%d, ts range in buf:%" PRId64
H
Hongze Cheng 已提交
2411
                  "-%" PRId64 " %s",
2412 2413
                  pReader, pBlockScanInfo->uid, startKey.ts, pReader->order, di->minKey, di->maxKey, pReader->idStr);
      } else {
H
Haojun Liao 已提交
2414
        tsdbError("%p uid:%" PRIu64 ", failed to create iterator for mem, code:%s, %s", pReader, pBlockScanInfo->uid,
2415 2416 2417 2418 2419
                  tstrerror(code), pReader->idStr);
        return code;
      }
    }
  } else {
H
Haojun Liao 已提交
2420
    tsdbDebug("%p uid:%" PRIu64 ", no data in imem, %s", pReader, pBlockScanInfo->uid, pReader->idStr);
2421 2422
  }

2423
  st = taosGetTimestampUs();
2424
  initDelSkylineIterator(pBlockScanInfo, pReader, d, di);
2425
  pReader->cost.initDelSkylineIterTime += (taosGetTimestampUs() - st) / 1000.0;
2426 2427 2428 2429 2430

  pBlockScanInfo->iterInit = true;
  return TSDB_CODE_SUCCESS;
}

dengyihao's avatar
dengyihao 已提交
2431 2432
static bool isValidFileBlockRow(SBlockData* pBlockData, SFileBlockDumpInfo* pDumpInfo,
                                STableBlockScanInfo* pBlockScanInfo, STsdbReader* pReader) {
2433 2434 2435 2436 2437 2438 2439 2440
  // 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;
    }
  }

2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451
  // 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;
  }

2452
  TSDBKEY k = {.ts = ts, .version = ver};
2453 2454
  if (hasBeenDropped(pBlockScanInfo->delSkyline, &pBlockScanInfo->fileDelIndex, &k, pReader->order,
                     &pReader->verRange)) {
2455 2456 2457
    return false;
  }

2458 2459 2460
  return true;
}

2461
static bool initLastBlockReader(SLastBlockReader* pLBlockReader, STableBlockScanInfo* pScanInfo, STsdbReader* pReader) {
2462
  // the last block reader has been initialized for this table.
2463
  if (pLBlockReader->uid == pScanInfo->uid) {
2464
    return hasDataInLastBlock(pLBlockReader);
2465 2466
  }

2467 2468
  if (pLBlockReader->uid != 0) {
    tMergeTreeClose(&pLBlockReader->mergeTree);
2469 2470
  }

2471 2472
  initMemDataIterator(pScanInfo, pReader);
  pLBlockReader->uid = pScanInfo->uid;
2473

H
Hongze Cheng 已提交
2474
  int32_t     step = ASCENDING_TRAVERSE(pLBlockReader->order) ? 1 : -1;
2475 2476
  STimeWindow w = pLBlockReader->window;
  if (ASCENDING_TRAVERSE(pLBlockReader->order)) {
2477
    w.skey = pScanInfo->lastKeyInStt;
2478
  } else {
2479
    w.ekey = pScanInfo->lastKeyInStt;
2480 2481
  }

X
Xiaoyu Wang 已提交
2482 2483
  tsdbDebug("init last block reader, window:%" PRId64 "-%" PRId64 ", uid:%" PRIu64 ", %s", w.skey, w.ekey,
            pScanInfo->uid, pReader->idStr);
2484 2485 2486
  int32_t code = tMergeTreeOpen(&pLBlockReader->mergeTree, (pLBlockReader->order == TSDB_ORDER_DESC),
                                pReader->pFileReader, pReader->suid, pScanInfo->uid, &w, &pLBlockReader->verRange,
                                pLBlockReader->pInfo, false, pReader->idStr);
2487 2488 2489 2490
  if (code != TSDB_CODE_SUCCESS) {
    return false;
  }

2491
  return nextRowFromLastBlocks(pLBlockReader, pScanInfo, &pReader->verRange);
2492 2493
}

2494
static int64_t getCurrentKeyInLastBlock(SLastBlockReader* pLastBlockReader) {
2495
  TSDBROW row = tMergeTreeGetRow(&pLastBlockReader->mergeTree);
2496
  return TSDBROW_TS(&row);
2497 2498
}

H
Hongze Cheng 已提交
2499
static bool hasDataInLastBlock(SLastBlockReader* pLastBlockReader) { return pLastBlockReader->mergeTree.pIter != NULL; }
2500

2501
bool hasDataInFileBlock(const SBlockData* pBlockData, const SFileBlockDumpInfo* pDumpInfo) {
H
Haojun Liao 已提交
2502
  if ((pBlockData->nRow > 0) && (pBlockData->nRow != pDumpInfo->totalRows)) {
2503
    return false;  // this is an invalid result.
2504
  }
2505
  return pBlockData->nRow > 0 && (!pDumpInfo->allDumped);
2506
}
2507

2508 2509
int32_t mergeRowsInFileBlocks(SBlockData* pBlockData, STableBlockScanInfo* pBlockScanInfo, int64_t key,
                              STsdbReader* pReader) {
2510 2511
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;
  if (tryCopyDistinctRowFromFileBlock(pReader, pBlockData, key, pDumpInfo)) {
2512
    pBlockScanInfo->lastKey = key;
2513 2514
    return TSDB_CODE_SUCCESS;
  } else {
C
Cary Xu 已提交
2515 2516
    TSDBROW fRow = tsdbRowFromBlockData(pBlockData, pDumpInfo->rowIndex);

H
Hongze Cheng 已提交
2517
    SRow*      pTSRow = NULL;
2518 2519
    SRowMerger merge = {0};

H
Hongze Cheng 已提交
2520
    int32_t code = tsdbRowMergerInit(&merge, &fRow, pReader->pSchema);
H
Haojun Liao 已提交
2521 2522 2523 2524
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

2525
    doMergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pReader, &merge);
H
Hongze Cheng 已提交
2526
    code = tsdbRowMergerGetRow(&merge, &pTSRow);
2527 2528 2529 2530
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

2531
    doAppendRowFromTSRow(pReader->pResBlock, pReader, pTSRow, pBlockScanInfo);
2532 2533

    taosMemoryFree(pTSRow);
H
Hongze Cheng 已提交
2534
    tsdbRowMergerClear(&merge);
2535 2536 2537 2538
    return TSDB_CODE_SUCCESS;
  }
}

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

2543
  TSDBROW *pRow = NULL, *piRow = NULL;
2544
  int64_t key = (pBlockData->nRow > 0 && (!pDumpInfo->allDumped)) ? pBlockData->aTSKEY[pDumpInfo->rowIndex] : INT64_MIN;
2545 2546 2547
  if (pBlockScanInfo->iter.hasVal) {
    pRow = getValidMemRow(&pBlockScanInfo->iter, pBlockScanInfo->delSkyline, pReader);
  }
C
Cary Xu 已提交
2548

2549 2550 2551
  if (pBlockScanInfo->iiter.hasVal) {
    piRow = getValidMemRow(&pBlockScanInfo->iiter, pBlockScanInfo->delSkyline, pReader);
  }
C
Cary Xu 已提交
2552

2553 2554 2555 2556
  // two levels of mem-table does contain the valid rows
  if (pRow != NULL && piRow != NULL) {
    return doMergeMultiLevelRows(pReader, pBlockScanInfo, pBlockData, pLastBlockReader);
  }
2557

2558 2559 2560 2561
  // imem + file + last block
  if (pBlockScanInfo->iiter.hasVal) {
    return doMergeBufAndFileRows(pReader, pBlockScanInfo, piRow, &pBlockScanInfo->iiter, key, pLastBlockReader);
  }
2562

2563 2564 2565
  // mem + file + last block
  if (pBlockScanInfo->iter.hasVal) {
    return doMergeBufAndFileRows(pReader, pBlockScanInfo, pRow, &pBlockScanInfo->iter, key, pLastBlockReader);
2566
  }
2567 2568 2569

  // files data blocks + last block
  return mergeFileBlockAndLastBlock(pReader, pLastBlockReader, key, pBlockScanInfo, pBlockData);
2570 2571
}

H
Haojun Liao 已提交
2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611
static int32_t loadNeighborIfOverlap(SFileDataBlockInfo* pBlockInfo, STableBlockScanInfo* pBlockScanInfo,
                                     STsdbReader* pReader, bool* loadNeighbor) {
  int32_t     code = TSDB_CODE_SUCCESS;
  int32_t     step = ASCENDING_TRAVERSE(pReader->order) ? 1 : -1;
  int32_t     nextIndex = -1;
  SBlockIndex nxtBIndex = {0};

  *loadNeighbor = false;
  SDataBlk* pBlock = getCurrentBlock(&pReader->status.blockIter);

  bool hasNeighbor = getNeighborBlockOfSameTable(pBlockInfo, pBlockScanInfo, &nextIndex, pReader->order, &nxtBIndex);
  if (!hasNeighbor) {  // do nothing
    return code;
  }

  if (overlapWithNeighborBlock(pBlock, &nxtBIndex, pReader->order)) {  // load next block
    SReaderStatus*  pStatus = &pReader->status;
    SDataBlockIter* pBlockIter = &pStatus->blockIter;

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

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

    // 3. load the neighbor block, and set it to be the currently accessed file data block
    code = doLoadFileBlockData(pReader, pBlockIter, &pStatus->fileBlockData, pBlockInfo->uid);
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

    // 4. check the data values
    initBlockDumpInfo(pReader, pBlockIter);
    *loadNeighbor = true;
  }

  return code;
}

2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624
static void updateComposedBlockInfo(STsdbReader* pReader, double el, STableBlockScanInfo* pBlockScanInfo) {
  SSDataBlock* pResBlock = pReader->pResBlock;

  pResBlock->info.id.uid = (pBlockScanInfo != NULL) ? pBlockScanInfo->uid : 0;
  pResBlock->info.dataLoad = 1;
  blockDataUpdateTsWindow(pResBlock, pReader->suppInfo.slotId[0]);

  setComposedBlockFlag(pReader, true);

  pReader->cost.composedBlocks += 1;
  pReader->cost.buildComposedBlockTime += el;
}

2625
static int32_t buildComposedDataBlock(STsdbReader* pReader) {
H
Haojun Liao 已提交
2626 2627
  int32_t code = TSDB_CODE_SUCCESS;

2628 2629
  SSDataBlock* pResBlock = pReader->pResBlock;

H
Hongze Cheng 已提交
2630
  SFileDataBlockInfo* pBlockInfo = getCurrentBlockInfo(&pReader->status.blockIter);
C
Cary Xu 已提交
2631 2632
  SLastBlockReader*   pLastBlockReader = pReader->status.fileIter.pLastBlockReader;

2633
  bool    asc = ASCENDING_TRAVERSE(pReader->order);
C
Cary Xu 已提交
2634
  int64_t st = taosGetTimestampUs();
2635
  int32_t step = asc ? 1 : -1;
2636
  double  el = 0;
2637 2638 2639

  STableBlockScanInfo* pBlockScanInfo = NULL;
  if (pBlockInfo != NULL) {
H
Haojun Liao 已提交
2640 2641
    pBlockScanInfo = getTableBlockScanInfo(pReader->status.pTableMap, pBlockInfo->uid, pReader->idStr);
    if (pBlockScanInfo == NULL) {
H
Haojun Liao 已提交
2642 2643 2644
      goto _end;
    }

C
Cary Xu 已提交
2645
    SDataBlk* pBlock = getCurrentBlock(&pReader->status.blockIter);
H
Hongze Cheng 已提交
2646
    TSDBKEY   keyInBuf = getCurrentKeyInBuf(pBlockScanInfo, pReader);
C
Cary Xu 已提交
2647 2648

    // it is a clean block, load it directly
H
Hongze Cheng 已提交
2649
    if (isCleanFileDataBlock(pReader, pBlockInfo, pBlock, pBlockScanInfo, keyInBuf, pLastBlockReader) &&
2650
        pBlock->nRow <= pReader->capacity) {
2651
      if (asc || ((!asc) && (!hasDataInLastBlock(pLastBlockReader)))) {
2652
        copyBlockDataToSDataBlock(pReader);
2653 2654

        // record the last key value
H
Hongze Cheng 已提交
2655
        pBlockScanInfo->lastKey = asc ? pBlock->maxKey.ts : pBlock->minKey.ts;
H
Haojun Liao 已提交
2656 2657
        goto _end;
      }
C
Cary Xu 已提交
2658 2659
    }
  } else {  // file blocks not exist
2660
    pBlockScanInfo = *pReader->status.pTableIter;
2661 2662
  }

2663
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;
2664
  SBlockData*         pBlockData = &pReader->status.fileBlockData;
2665

2666
  while (1) {
2667
    bool hasBlockData = false;
2668
    {
2669 2670
      while (pBlockData->nRow > 0 &&
             pBlockData->uid == pBlockScanInfo->uid) {  // find the first qualified row in data block
2671 2672 2673 2674 2675
        if (isValidFileBlockRow(pBlockData, pDumpInfo, pBlockScanInfo, pReader)) {
          hasBlockData = true;
          break;
        }

2676 2677
        pDumpInfo->rowIndex += step;

H
Hongze Cheng 已提交
2678
        SDataBlk* pBlock = getCurrentBlock(&pReader->status.blockIter);
2679
        if (pDumpInfo->rowIndex >= pBlock->nRow || pDumpInfo->rowIndex < 0) {
H
Haojun Liao 已提交
2680
          pBlockInfo = getCurrentBlockInfo(&pReader->status.blockIter);  // NOTE: get the new block info
H
Haojun Liao 已提交
2681

H
Haojun Liao 已提交
2682 2683 2684 2685 2686
          // continue check for the next file block if the last ts in the current block
          // is overlapped with the next neighbor block
          bool loadNeighbor = false;
          code = loadNeighborIfOverlap(pBlockInfo, pBlockScanInfo, pReader, &loadNeighbor);
          if ((!loadNeighbor) || (code != 0)) {
2687 2688
            setBlockAllDumped(pDumpInfo, pBlock->maxKey.ts, pReader->order);
            break;
2689
          }
2690 2691
        }
      }
2692
    }
2693

2694
    // no data in last block and block, no need to proceed.
2695
    if (hasBlockData == false) {
2696
      break;
2697 2698
    }

2699
    buildComposedDataBlockImpl(pReader, pBlockScanInfo, pBlockData, pLastBlockReader);
2700

2701
    // currently loaded file data block is consumed
2702
    if ((pBlockData->nRow > 0) && (pDumpInfo->rowIndex >= pBlockData->nRow || pDumpInfo->rowIndex < 0)) {
H
Hongze Cheng 已提交
2703
      SDataBlk* pBlock = getCurrentBlock(&pReader->status.blockIter);
2704
      setBlockAllDumped(pDumpInfo, pBlock->maxKey.ts, pReader->order);
2705 2706 2707 2708 2709
      break;
    }

    if (pResBlock->info.rows >= pReader->capacity) {
      break;
2710 2711 2712
    }
  }

H
Hongze Cheng 已提交
2713
_end:
2714 2715
  el = (taosGetTimestampUs() - st) / 1000.0;
  updateComposedBlockInfo(pReader, el, pBlockScanInfo);
2716

2717 2718 2719
  if (pResBlock->info.rows > 0) {
    tsdbDebug("%p uid:%" PRIu64 ", composed data block created, brange:%" PRIu64 "-%" PRIu64
              " rows:%d, elapsed time:%.2f ms %s",
H
Haojun Liao 已提交
2720
              pReader, pResBlock->info.id.uid, pResBlock->info.window.skey, pResBlock->info.window.ekey,
H
Haojun Liao 已提交
2721
              pResBlock->info.rows, el, pReader->idStr);
2722
  }
2723

H
Haojun Liao 已提交
2724
  return code;
2725 2726 2727 2728
}

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

2729 2730 2731 2732 2733 2734 2735 2736
int32_t getInitialDelIndex(const SArray* pDelSkyline, int32_t order) {
  if (pDelSkyline == NULL) {
    return 0;
  }

  return ASCENDING_TRAVERSE(order) ? 0 : taosArrayGetSize(pDelSkyline) - 1;
}

dengyihao's avatar
dengyihao 已提交
2737 2738
int32_t initDelSkylineIterator(STableBlockScanInfo* pBlockScanInfo, STsdbReader* pReader, STbData* pMemTbData,
                               STbData* piMemTbData) {
2739 2740 2741
  if (pBlockScanInfo->delSkyline != NULL) {
    return TSDB_CODE_SUCCESS;
  }
2742

2743
  int32_t code = 0;
2744 2745
  SArray* pDelData = taosArrayInit(4, sizeof(SDelData));

H
Hongze Cheng 已提交
2746
  SDelFile* pDelFile = pReader->pReadSnap->fs.pDelFile;
2747
  if (pDelFile && taosArrayGetSize(pReader->pDelIdx) > 0) {
2748
    SDelIdx  idx = {.suid = pReader->suid, .uid = pBlockScanInfo->uid};
2749
    SDelIdx* pIdx = taosArraySearch(pReader->pDelIdx, &idx, tCmprDelIdx, TD_EQ);
2750

H
Haojun Liao 已提交
2751
    if (pIdx != NULL) {
2752
      code = tsdbReadDelData(pReader->pDelFReader, pIdx, pDelData);
2753 2754 2755
    }
    if (code != TSDB_CODE_SUCCESS) {
      goto _err;
2756
    }
2757
  }
2758

2759 2760 2761 2762 2763 2764 2765
  SDelData* p = NULL;
  if (pMemTbData != NULL) {
    p = pMemTbData->pHead;
    while (p) {
      taosArrayPush(pDelData, p);
      p = p->pNext;
    }
2766 2767
  }

2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781
  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);
2782 2783 2784 2785 2786 2787 2788
  int32_t index = getInitialDelIndex(pBlockScanInfo->delSkyline, pReader->order);

  pBlockScanInfo->iter.index = index;
  pBlockScanInfo->iiter.index = index;
  pBlockScanInfo->fileDelIndex = index;
  pBlockScanInfo->lastBlockDelIndex = index;

2789 2790
  return code;

2791 2792 2793
_err:
  taosArrayDestroy(pDelData);
  return code;
2794 2795
}

C
Cary Xu 已提交
2796
TSDBKEY getCurrentKeyInBuf(STableBlockScanInfo* pScanInfo, STsdbReader* pReader) {
2797
  bool asc = ASCENDING_TRAVERSE(pReader->order);
X
Xiaoyu Wang 已提交
2798
  //  TSKEY initialVal = asc? TSKEY_MIN:TSKEY_MAX;
2799

X
Xiaoyu Wang 已提交
2800
  TSDBKEY key = {.ts = TSKEY_INITIAL_VAL}, ikey = {.ts = TSKEY_INITIAL_VAL};
2801

X
Xiaoyu Wang 已提交
2802
  bool     hasKey = false, hasIKey = false;
2803
  TSDBROW* pRow = getValidMemRow(&pScanInfo->iter, pScanInfo->delSkyline, pReader);
2804
  if (pRow != NULL) {
2805
    hasKey = true;
2806 2807 2808
    key = TSDBROW_KEY(pRow);
  }

2809 2810 2811 2812
  TSDBROW* pIRow = getValidMemRow(&pScanInfo->iiter, pScanInfo->delSkyline, pReader);
  if (pIRow != NULL) {
    hasIKey = true;
    ikey = TSDBROW_KEY(pIRow);
2813 2814
  }

2815
  if (hasKey) {
X
Xiaoyu Wang 已提交
2816
    if (hasIKey) {  // has data in mem & imem
2817 2818
      if (asc) {
        return key.ts <= ikey.ts ? key : ikey;
X
Xiaoyu Wang 已提交
2819 2820
      } else {
        return key.ts <= ikey.ts ? ikey : key;
2821 2822 2823
      }
    } else {  // no data in imem
      return key;
2824
    }
2825 2826 2827 2828
  } else {
    // no data in mem & imem, return the initial value
    // only imem has data, return ikey
    return ikey;
2829 2830 2831
  }
}

2832
static int32_t moveToNextFile(STsdbReader* pReader, SBlockNumber* pBlockNum) {
H
Haojun Liao 已提交
2833
  SReaderStatus* pStatus = &pReader->status;
2834
  pBlockNum->numOfBlocks = 0;
2835
  pBlockNum->numOfLastFiles = 0;
2836

2837
  size_t  numOfTables = taosHashGetSize(pReader->status.pTableMap);
2838
  SArray* pIndexList = taosArrayInit(numOfTables, sizeof(SBlockIdx));
H
Haojun Liao 已提交
2839 2840

  while (1) {
dengyihao's avatar
dengyihao 已提交
2841
    bool    hasNext = false;
D
dapan1121 已提交
2842 2843 2844 2845 2846
    int32_t code = filesetIteratorNext(&pStatus->fileIter, pReader, &hasNext);
    if (code) {
      taosArrayDestroy(pIndexList);
      return code;
    }
dengyihao's avatar
dengyihao 已提交
2847

2848
    if (!hasNext) {  // no data files on disk
H
Haojun Liao 已提交
2849 2850 2851
      break;
    }

H
Haojun Liao 已提交
2852
    taosArrayClear(pIndexList);
D
dapan1121 已提交
2853
    code = doLoadBlockIndex(pReader, pReader->pFileReader, pIndexList);
H
Haojun Liao 已提交
2854
    if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
2855
      taosArrayDestroy(pIndexList);
H
Haojun Liao 已提交
2856 2857 2858
      return code;
    }

H
Hongze Cheng 已提交
2859
    if (taosArrayGetSize(pIndexList) > 0 || pReader->pFileReader->pSet->nSttF > 0) {
2860
      code = doLoadFileBlock(pReader, pIndexList, pBlockNum);
H
Haojun Liao 已提交
2861
      if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
2862
        taosArrayDestroy(pIndexList);
H
Haojun Liao 已提交
2863 2864 2865
        return code;
      }

2866
      if (pBlockNum->numOfBlocks + pBlockNum->numOfLastFiles > 0) {
H
Haojun Liao 已提交
2867 2868 2869
        break;
      }
    }
2870

H
Haojun Liao 已提交
2871 2872 2873
    // no blocks in current file, try next files
  }

H
Haojun Liao 已提交
2874
  taosArrayDestroy(pIndexList);
2875

H
Haojun Liao 已提交
2876 2877 2878 2879 2880 2881 2882
  if (pReader->pReadSnap != NULL) {
    SDelFile* pDelFile = pReader->pReadSnap->fs.pDelFile;
    if (pReader->pDelFReader == NULL && pDelFile != NULL) {
      int32_t code = tsdbDelFReaderOpen(&pReader->pDelFReader, pDelFile, pReader->pTsdb);
      if (code != TSDB_CODE_SUCCESS) {
        return code;
      }
2883

H
Haojun Liao 已提交
2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894
      pReader->pDelIdx = taosArrayInit(4, sizeof(SDelIdx));
      if (pReader->pDelIdx == NULL) {
        code = TSDB_CODE_OUT_OF_MEMORY;
        return code;
      }

      code = tsdbReadDelIdx(pReader->pDelFReader, pReader->pDelIdx);
      if (code != TSDB_CODE_SUCCESS) {
        taosArrayDestroy(pReader->pDelIdx);
        return code;
      }
2895 2896 2897
    }
  }

H
Haojun Liao 已提交
2898 2899 2900
  return TSDB_CODE_SUCCESS;
}

X
Xiaoyu Wang 已提交
2901
static void resetTableListIndex(SReaderStatus* pStatus) {
2902
  STableUidList* pList = &pStatus->uidList;
2903

H
Haojun Liao 已提交
2904 2905 2906
  pList->currentIndex = 0;
  uint64_t uid = pList->tableUidList[0];
  pStatus->pTableIter = taosHashGet(pStatus->pTableMap, &uid, sizeof(uid));
2907 2908
}

2909
static bool moveToNextTable(STableUidList* pOrderedCheckInfo, SReaderStatus* pStatus) {
2910 2911 2912 2913 2914 2915 2916 2917
  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));
2918
  return (pStatus->pTableIter != NULL);
2919 2920
}

2921
static int32_t doLoadLastBlockSequentially(STsdbReader* pReader) {
2922
  SReaderStatus*    pStatus = &pReader->status;
2923
  SLastBlockReader* pLastBlockReader = pStatus->fileIter.pLastBlockReader;
2924
  STableUidList*    pUidList = &pStatus->uidList;
2925

H
Haojun Liao 已提交
2926 2927
  if (taosHashGetSize(pStatus->pTableMap) == 0) {
    return TSDB_CODE_SUCCESS;
2928
  }
2929

2930 2931
  SSDataBlock* pResBlock = pReader->pResBlock;

2932
  while (1) {
2933
    // load the last data block of current table
H
Hongze Cheng 已提交
2934
    STableBlockScanInfo* pScanInfo = *(STableBlockScanInfo**)pStatus->pTableIter;
2935 2936

    bool hasVal = initLastBlockReader(pLastBlockReader, pScanInfo, pReader);
2937
    if (!hasVal) {
2938
      bool hasNexTable = moveToNextTable(pUidList, pStatus);
2939
      if (!hasNexTable) {
2940 2941
        return TSDB_CODE_SUCCESS;
      }
2942

2943
      continue;
2944 2945
    }

2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958
    int64_t st = taosGetTimestampUs();
    while (1) {
      bool hasBlockLData = hasDataInLastBlock(pLastBlockReader);

      // no data in last block and block, no need to proceed.
      if (hasBlockLData == false) {
        break;
      }

      buildComposedDataBlockImpl(pReader, pScanInfo, &pReader->status.fileBlockData, pLastBlockReader);
      if (pResBlock->info.rows >= pReader->capacity) {
        break;
      }
2959 2960
    }

2961 2962 2963 2964 2965 2966 2967 2968
    double el = (taosGetTimestampUs() - st) / 1000.0;
    updateComposedBlockInfo(pReader, el, pScanInfo);

    if (pResBlock->info.rows > 0) {
      tsdbDebug("%p uid:%" PRIu64 ", composed data block created, brange:%" PRIu64 "-%" PRIu64
                " rows:%d, elapsed time:%.2f ms %s",
                pReader, pResBlock->info.id.uid, pResBlock->info.window.skey, pResBlock->info.window.ekey,
                pResBlock->info.rows, el, pReader->idStr);
2969 2970
      return TSDB_CODE_SUCCESS;
    }
2971

2972
    // current table is exhausted, let's try next table
2973
    bool hasNexTable = moveToNextTable(pUidList, pStatus);
2974
    if (!hasNexTable) {
2975 2976
      return TSDB_CODE_SUCCESS;
    }
2977 2978 2979
  }
}

2980
static int32_t doBuildDataBlock(STsdbReader* pReader) {
H
Hongze Cheng 已提交
2981 2982
  int32_t   code = TSDB_CODE_SUCCESS;
  SDataBlk* pBlock = NULL;
2983 2984 2985

  SReaderStatus*       pStatus = &pReader->status;
  SDataBlockIter*      pBlockIter = &pStatus->blockIter;
2986 2987 2988
  STableBlockScanInfo* pScanInfo = NULL;
  SFileDataBlockInfo*  pBlockInfo = getCurrentBlockInfo(pBlockIter);
  SLastBlockReader*    pLastBlockReader = pReader->status.fileIter.pLastBlockReader;
2989

H
Haojun Liao 已提交
2990
  pScanInfo = getTableBlockScanInfo(pReader->status.pTableMap, pBlockInfo->uid, pReader->idStr);
H
Haojun Liao 已提交
2991
  if (pScanInfo == NULL) {
H
Haojun Liao 已提交
2992
    return terrno;
H
Haojun Liao 已提交
2993 2994
  }

2995
  pBlock = getCurrentBlock(pBlockIter);
2996

2997
  initLastBlockReader(pLastBlockReader, pScanInfo, pReader);
C
Cary Xu 已提交
2998
  TSDBKEY keyInBuf = getCurrentKeyInBuf(pScanInfo, pReader);
2999

3000
  if (fileBlockShouldLoad(pReader, pBlockInfo, pBlock, pScanInfo, keyInBuf, pLastBlockReader)) {
3001
    code = doLoadFileBlockData(pReader, pBlockIter, &pStatus->fileBlockData, pScanInfo->uid);
3002 3003
    if (code != TSDB_CODE_SUCCESS) {
      return code;
3004 3005 3006
    }

    // build composed data block
3007
    code = buildComposedDataBlock(pReader);
C
Cary Xu 已提交
3008
  } else if (bufferDataInFileBlockGap(pReader->order, keyInBuf, pBlock)) {
3009
    // data in memory that are earlier than current file block
3010
    // rows in buffer should be less than the file block in asc, greater than file block in desc
3011
    int64_t endKey = (ASCENDING_TRAVERSE(pReader->order)) ? pBlock->minKey.ts : pBlock->maxKey.ts;
3012
    code = buildDataBlockFromBuf(pReader, pScanInfo, endKey);
3013 3014 3015 3016
  } else {
    if (hasDataInLastBlock(pLastBlockReader) && !ASCENDING_TRAVERSE(pReader->order)) {
      // only return the rows in last block
      int64_t tsLast = getCurrentKeyInLastBlock(pLastBlockReader);
H
Hongze Cheng 已提交
3017
      ASSERT(tsLast >= pBlock->maxKey.ts);
3018

3019 3020 3021 3022
      SBlockData* pBData = &pReader->status.fileBlockData;
      tBlockDataReset(pBData);

      SSDataBlock* pResBlock = pReader->pResBlock;
3023
      tsdbDebug("load data in last block firstly, due to desc scan data, %s", pReader->idStr);
3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045

      int64_t st = taosGetTimestampUs();

      while (1) {
        bool hasBlockLData = hasDataInLastBlock(pLastBlockReader);

        // no data in last block and block, no need to proceed.
        if (hasBlockLData == false) {
          break;
        }

        buildComposedDataBlockImpl(pReader, pScanInfo, &pReader->status.fileBlockData, pLastBlockReader);
        if (pResBlock->info.rows >= pReader->capacity) {
          break;
        }
      }

      double el = (taosGetTimestampUs() - st) / 1000.0;
      updateComposedBlockInfo(pReader, el, pScanInfo);

      if (pResBlock->info.rows > 0) {
        tsdbDebug("%p uid:%" PRIu64 ", composed data block created, brange:%" PRIu64 "-%" PRIu64
X
Xiaoyu Wang 已提交
3046
                  " rows:%d, elapsed time:%.2f ms %s",
3047 3048 3049
                  pReader, pResBlock->info.id.uid, pResBlock->info.window.skey, pResBlock->info.window.ekey,
                  pResBlock->info.rows, el, pReader->idStr);
      }
H
Hongze Cheng 已提交
3050
    } else {  // whole block is required, return it directly
3051 3052
      SDataBlockInfo* pInfo = &pReader->pResBlock->info;
      pInfo->rows = pBlock->nRow;
H
Haojun Liao 已提交
3053
      pInfo->id.uid = pScanInfo->uid;
3054
      pInfo->dataLoad = 0;
3055 3056 3057
      pInfo->window = (STimeWindow){.skey = pBlock->minKey.ts, .ekey = pBlock->maxKey.ts};
      setComposedBlockFlag(pReader, false);
      setBlockAllDumped(&pStatus->fBlockDumpInfo, pBlock->maxKey.ts, pReader->order);
3058

3059
      // update the last key for the corresponding table
H
Hongze Cheng 已提交
3060
      pScanInfo->lastKey = ASCENDING_TRAVERSE(pReader->order) ? pInfo->window.ekey : pInfo->window.skey;
X
Xiaoyu Wang 已提交
3061 3062
      tsdbDebug("%p uid:%" PRIu64
                " clean file block retrieved from file, global index:%d, "
H
Haojun Liao 已提交
3063 3064 3065
                "table index:%d, rows:%d, brange:%" PRId64 "-%" PRId64 ", %s",
                pReader, pScanInfo->uid, pBlockIter->index, pBlockInfo->tbBlockIdx, pBlock->nRow, pBlock->minKey.ts,
                pBlock->maxKey.ts, pReader->idStr);
3066
    }
3067 3068 3069 3070 3071
  }

  return code;
}

H
Haojun Liao 已提交
3072
static int32_t buildBlockFromBufferSequentially(STsdbReader* pReader) {
3073
  SReaderStatus* pStatus = &pReader->status;
3074
  STableUidList* pUidList = &pStatus->uidList;
3075

3076
  while (1) {
X
Xiaoyu Wang 已提交
3077 3078 3079 3080 3081 3082
    //    if (pStatus->pTableIter == NULL) {
    //      pStatus->pTableIter = taosHashIterate(pStatus->pTableMap, NULL);
    //      if (pStatus->pTableIter == NULL) {
    //        return TSDB_CODE_SUCCESS;
    //      }
    //    }
3083

3084 3085
    STableBlockScanInfo** pBlockScanInfo = pStatus->pTableIter;
    initMemDataIterator(*pBlockScanInfo, pReader);
3086

3087
    int64_t endKey = (ASCENDING_TRAVERSE(pReader->order)) ? INT64_MAX : INT64_MIN;
3088
    int32_t code = buildDataBlockFromBuf(pReader, *pBlockScanInfo, endKey);
H
Haojun Liao 已提交
3089 3090 3091 3092
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

3093
    if (pReader->pResBlock->info.rows > 0) {
H
Haojun Liao 已提交
3094
      return TSDB_CODE_SUCCESS;
3095 3096
    }

3097 3098 3099
    // current table is exhausted, let's try next table
    bool hasNexTable = moveToNextTable(pUidList, pStatus);
    if (!hasNexTable) {
H
Haojun Liao 已提交
3100
      return TSDB_CODE_SUCCESS;
3101 3102 3103 3104
    }
  }
}

3105
// set the correct start position in case of the first/last file block, according to the query time window
3106
static void initBlockDumpInfo(STsdbReader* pReader, SDataBlockIter* pBlockIter) {
3107 3108 3109 3110 3111 3112 3113 3114
  int64_t             lastKey = ASCENDING_TRAVERSE(pReader->order) ? INT64_MIN : INT64_MAX;
  SDataBlk*           pBlock = getCurrentBlock(pBlockIter);
  SFileDataBlockInfo* pBlockInfo = getCurrentBlockInfo(pBlockIter);
  if (pBlockInfo) {
    STableBlockScanInfo* pScanInfo = taosHashGet(pBlockIter->pTableMap, &pBlockInfo->uid, sizeof(pBlockInfo->uid));
    if (pScanInfo) {
      lastKey = pScanInfo->lastKey;
    }
3115
  }
3116 3117 3118
  SReaderStatus* pStatus = &pReader->status;

  SFileBlockDumpInfo* pDumpInfo = &pStatus->fBlockDumpInfo;
3119 3120 3121

  pDumpInfo->totalRows = pBlock->nRow;
  pDumpInfo->allDumped = false;
3122
  pDumpInfo->rowIndex = ASCENDING_TRAVERSE(pReader->order) ? 0 : pBlock->nRow - 1;
3123
  pDumpInfo->lastKey = lastKey;
3124 3125
}

3126
static int32_t initForFirstBlockInFile(STsdbReader* pReader, SDataBlockIter* pBlockIter) {
3127
  SBlockNumber num = {0};
X
Xiaoyu Wang 已提交
3128
  int32_t      code = moveToNextFile(pReader, &num);
3129 3130 3131 3132 3133
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

  // all data files are consumed, try data in buffer
3134
  if (num.numOfBlocks + num.numOfLastFiles == 0) {
3135 3136 3137 3138 3139
    pReader->status.loadFromFile = false;
    return code;
  }

  // initialize the block iterator for a new fileset
3140 3141
  if (num.numOfBlocks > 0) {
    code = initBlockIterator(pReader, pBlockIter, num.numOfBlocks);
H
Hongze Cheng 已提交
3142
  } else {  // no block data, only last block exists
3143
    tBlockDataReset(&pReader->status.fileBlockData);
3144
    resetDataBlockIterator(pBlockIter, pReader->order);
H
Haojun Liao 已提交
3145
    resetTableListIndex(&pReader->status);
3146
  }
3147 3148

  // set the correct start position according to the query time window
3149
  initBlockDumpInfo(pReader, pBlockIter);
3150 3151 3152
  return code;
}

3153
static bool fileBlockPartiallyRead(SFileBlockDumpInfo* pDumpInfo, bool asc) {
3154 3155
  return (!pDumpInfo->allDumped) &&
         ((pDumpInfo->rowIndex > 0 && asc) || (pDumpInfo->rowIndex < (pDumpInfo->totalRows - 1) && (!asc)));
3156 3157
}

3158
static int32_t buildBlockFromFiles(STsdbReader* pReader) {
H
Haojun Liao 已提交
3159
  int32_t code = TSDB_CODE_SUCCESS;
3160 3161
  bool    asc = ASCENDING_TRAVERSE(pReader->order);

3162 3163
  SDataBlockIter* pBlockIter = &pReader->status.blockIter;

3164
  if (pBlockIter->numOfBlocks == 0) {
H
Hongze Cheng 已提交
3165
  _begin:
3166 3167 3168 3169 3170
    code = doLoadLastBlockSequentially(pReader);
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

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

3175
    // all data blocks are checked in this last block file, now let's try the next file
3176 3177 3178 3179 3180 3181 3182 3183
    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;
      }

3184
      // this file does not have data files, let's start check the last block file if exists
3185
      if (pBlockIter->numOfBlocks == 0) {
H
Haojun Liao 已提交
3186
        resetTableListIndex(&pReader->status);
3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200
        goto _begin;
      }
    }

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

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

3201
  while (1) {
3202 3203
    SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;

3204
    if (fileBlockPartiallyRead(pDumpInfo, asc)) {  // file data block is partially loaded
3205
      code = buildComposedDataBlock(pReader);
3206 3207 3208 3209
    } else {
      // current block are exhausted, try the next file block
      if (pDumpInfo->allDumped) {
        // try next data block in current file
H
Haojun Liao 已提交
3210
        bool hasNext = blockIteratorNext(&pReader->status.blockIter, pReader->idStr);
3211 3212
        if (hasNext) {  // check for the next block in the block accessed order list
          initBlockDumpInfo(pReader, pBlockIter);
3213
        } else {
H
Haojun Liao 已提交
3214
          if (pReader->status.pCurrentFileset->nSttF > 0) {
3215
            // data blocks in current file are exhausted, let's try the next file now
H
Haojun Liao 已提交
3216 3217 3218 3219 3220 3221
            SBlockData* pBlockData = &pReader->status.fileBlockData;
            if (pBlockData->uid != 0) {
              tBlockDataClear(pBlockData);
            }

            tBlockDataReset(pBlockData);
3222
            resetDataBlockIterator(pBlockIter, pReader->order);
H
Haojun Liao 已提交
3223
            resetTableListIndex(&pReader->status);
3224 3225 3226
            goto _begin;
          } else {
            code = initForFirstBlockInFile(pReader, pBlockIter);
3227

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

3233 3234
            // this file does not have blocks, let's start check the last block file
            if (pBlockIter->numOfBlocks == 0) {
H
Haojun Liao 已提交
3235
              resetTableListIndex(&pReader->status);
3236 3237
              goto _begin;
            }
3238
          }
3239
        }
H
Haojun Liao 已提交
3240
      }
3241 3242

      code = doBuildDataBlock(pReader);
3243 3244
    }

3245 3246 3247 3248 3249 3250 3251 3252
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

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

3255 3256
static STsdb* getTsdbByRetentions(SVnode* pVnode, TSKEY winSKey, SRetention* retentions, const char* idStr,
                                  int8_t* pLevel) {
3257
  if (VND_IS_RSMA(pVnode)) {
3258
    int8_t  level = 0;
3259 3260
    int8_t  precision = pVnode->config.tsdbCfg.precision;
    int64_t now = taosGetTimestamp(precision);
H
Haojun Liao 已提交
3261 3262 3263
    int64_t offset = tsQueryRsmaTolerance * ((precision == TSDB_TIME_PRECISION_MILLI)   ? 1L
                                             : (precision == TSDB_TIME_PRECISION_MICRO) ? 1000L
                                                                                        : 1000000L);
3264

3265
    for (int8_t i = 0; i < TSDB_RETENTION_MAX; ++i) {
3266 3267 3268 3269 3270 3271 3272
      SRetention* pRetention = retentions + level;
      if (pRetention->keep <= 0) {
        if (level > 0) {
          --level;
        }
        break;
      }
3273
      if ((now - pRetention->keep) <= (winSKey + offset)) {
3274 3275 3276 3277 3278
        break;
      }
      ++level;
    }

3279
    const char* str = (idStr != NULL) ? idStr : "";
3280 3281

    if (level == TSDB_RETENTION_L0) {
3282
      *pLevel = TSDB_RETENTION_L0;
C
Cary Xu 已提交
3283
      tsdbDebug("vgId:%d, rsma level %d is selected to query %s", TD_VID(pVnode), TSDB_RETENTION_L0, str);
3284 3285
      return VND_RSMA0(pVnode);
    } else if (level == TSDB_RETENTION_L1) {
3286
      *pLevel = TSDB_RETENTION_L1;
C
Cary Xu 已提交
3287
      tsdbDebug("vgId:%d, rsma level %d is selected to query %s", TD_VID(pVnode), TSDB_RETENTION_L1, str);
3288 3289
      return VND_RSMA1(pVnode);
    } else {
3290
      *pLevel = TSDB_RETENTION_L2;
C
Cary Xu 已提交
3291
      tsdbDebug("vgId:%d, rsma level %d is selected to query %s", TD_VID(pVnode), TSDB_RETENTION_L2, str);
3292 3293 3294 3295 3296 3297 3298
      return VND_RSMA2(pVnode);
    }
  }

  return VND_TSDB(pVnode);
}

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

  int64_t endVer = 0;
L
Liu Jicong 已提交
3303 3304
  if (pCond->endVersion ==
      -1) {  // user not specified end version, set current maximum version of vnode as the endVersion
H
Haojun Liao 已提交
3305 3306
    endVer = pVnode->state.applied;
  } else {
L
Liu Jicong 已提交
3307
    endVer = (pCond->endVersion > pVnode->state.applied) ? pVnode->state.applied : pCond->endVersion;
3308 3309
  }

H
Haojun Liao 已提交
3310
  return (SVersionRange){.minVer = startVer, .maxVer = endVer};
3311 3312
}

3313
bool hasBeenDropped(const SArray* pDelList, int32_t* index, TSDBKEY* pKey, int32_t order, SVersionRange* pVerRange) {
3314 3315 3316
  if (pDelList == NULL) {
    return false;
  }
H
Haojun Liao 已提交
3317

L
Liu Jicong 已提交
3318 3319 3320
  size_t  num = taosArrayGetSize(pDelList);
  bool    asc = ASCENDING_TRAVERSE(order);
  int32_t step = asc ? 1 : -1;
3321

3322 3323 3324 3325 3326 3327
  if (asc) {
    if (*index >= num - 1) {
      TSDBKEY* last = taosArrayGetLast(pDelList);
      ASSERT(pKey->ts >= last->ts);

      if (pKey->ts > last->ts) {
3328
        return false;
3329 3330
      } else if (pKey->ts == last->ts) {
        TSDBKEY* prev = taosArrayGet(pDelList, num - 2);
3331 3332
        return (prev->version >= pKey->version && prev->version <= pVerRange->maxVer &&
                prev->version >= pVerRange->minVer);
3333 3334
      }
    } else {
3335 3336 3337 3338 3339 3340 3341
      TSDBKEY* pCurrent = taosArrayGet(pDelList, *index);
      TSDBKEY* pNext = taosArrayGet(pDelList, (*index) + 1);

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

3342 3343
      if (pCurrent->ts <= pKey->ts && pNext->ts >= pKey->ts && pCurrent->version >= pKey->version &&
          pVerRange->maxVer >= pCurrent->version) {
3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358
        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;
          }

3359 3360
          if (pCurrent->ts <= pKey->ts && pNext->ts >= pKey->ts && pCurrent->version >= pKey->version &&
              pVerRange->maxVer >= pCurrent->version) {
3361 3362 3363 3364 3365 3366
            return true;
          }
        }
      }

      return false;
3367 3368
    }
  } else {
3369 3370
    if (*index <= 0) {
      TSDBKEY* pFirst = taosArrayGet(pDelList, 0);
3371

3372 3373 3374 3375 3376 3377 3378
      if (pKey->ts < pFirst->ts) {
        return false;
      } else if (pKey->ts == pFirst->ts) {
        return pFirst->version >= pKey->version;
      } else {
        ASSERT(0);
      }
3379
    } else {
3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406
      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;
          }
        }
3407 3408 3409 3410 3411
      }

      return false;
    }
  }
3412 3413

  return false;
3414 3415
}

3416
TSDBROW* getValidMemRow(SIterInfo* pIter, const SArray* pDelList, STsdbReader* pReader) {
3417
  if (!pIter->hasVal) {
H
Haojun Liao 已提交
3418 3419
    return NULL;
  }
H
Hongze Cheng 已提交
3420

3421
  TSDBROW* pRow = tsdbTbDataIterGet(pIter->iter);
H
Hongze Cheng 已提交
3422 3423
  TSDBKEY  key = TSDBROW_KEY(pRow);

3424
  if (outOfTimeWindow(key.ts, &pReader->window)) {
3425
    pIter->hasVal = false;
H
Haojun Liao 已提交
3426 3427
    return NULL;
  }
H
Hongze Cheng 已提交
3428

3429
  // it is a valid data version
dengyihao's avatar
dengyihao 已提交
3430
  if ((key.version <= pReader->verRange.maxVer && key.version >= pReader->verRange.minVer) &&
3431
      (!hasBeenDropped(pDelList, &pIter->index, &key, pReader->order, &pReader->verRange))) {
H
Haojun Liao 已提交
3432 3433
    return pRow;
  }
H
Hongze Cheng 已提交
3434

3435
  while (1) {
3436 3437
    pIter->hasVal = tsdbTbDataIterNext(pIter->iter);
    if (!pIter->hasVal) {
H
Haojun Liao 已提交
3438 3439
      return NULL;
    }
H
Hongze Cheng 已提交
3440

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

H
Haojun Liao 已提交
3443
    key = TSDBROW_KEY(pRow);
3444
    if (outOfTimeWindow(key.ts, &pReader->window)) {
3445
      pIter->hasVal = false;
H
Haojun Liao 已提交
3446 3447
      return NULL;
    }
H
Hongze Cheng 已提交
3448

dengyihao's avatar
dengyihao 已提交
3449
    if (key.version <= pReader->verRange.maxVer && key.version >= pReader->verRange.minVer &&
3450
        (!hasBeenDropped(pDelList, &pIter->index, &key, pReader->order, &pReader->verRange))) {
H
Haojun Liao 已提交
3451 3452 3453 3454
      return pRow;
    }
  }
}
H
Hongze Cheng 已提交
3455

3456 3457
int32_t doMergeRowsInBuf(SIterInfo* pIter, uint64_t uid, int64_t ts, SArray* pDelList, SRowMerger* pMerger,
                         STsdbReader* pReader) {
H
Haojun Liao 已提交
3458
  while (1) {
3459 3460
    pIter->hasVal = tsdbTbDataIterNext(pIter->iter);
    if (!pIter->hasVal) {
H
Haojun Liao 已提交
3461 3462
      break;
    }
H
Hongze Cheng 已提交
3463

3464
    // data exists but not valid
3465
    TSDBROW* pRow = getValidMemRow(pIter, pDelList, pReader);
3466 3467 3468 3469 3470
    if (pRow == NULL) {
      break;
    }

    // ts is not identical, quit
H
Haojun Liao 已提交
3471
    TSDBKEY k = TSDBROW_KEY(pRow);
3472
    if (k.ts != ts) {
H
Haojun Liao 已提交
3473 3474 3475
      break;
    }

3476 3477 3478 3479 3480
    if (pRow->type == TSDBROW_ROW_FMT) {
      STSchema* pTSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(pRow), pReader, uid);
      if (pTSchema == NULL) {
        return terrno;
      }
H
Haojun Liao 已提交
3481

3482 3483 3484 3485
      tsdbRowMergerAdd(pMerger, pRow, pTSchema);
    } else {  // column format
      tsdbRowMerge(pMerger, pRow);
    }
H
Haojun Liao 已提交
3486 3487 3488 3489 3490
  }

  return TSDB_CODE_SUCCESS;
}

3491
static int32_t doMergeRowsInFileBlockImpl(SBlockData* pBlockData, int32_t rowIndex, int64_t key, SRowMerger* pMerger,
3492
                                          SVersionRange* pVerRange, int32_t step) {
3493
  while (rowIndex < pBlockData->nRow && rowIndex >= 0 && pBlockData->aTSKEY[rowIndex] == key) {
3494
    if (pBlockData->aVersion[rowIndex] > pVerRange->maxVer || pBlockData->aVersion[rowIndex] < pVerRange->minVer) {
3495
      rowIndex += step;
3496 3497 3498 3499
      continue;
    }

    TSDBROW fRow = tsdbRowFromBlockData(pBlockData, rowIndex);
H
Hongze Cheng 已提交
3500
    tsdbRowMerge(pMerger, &fRow);
3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511
    rowIndex += step;
  }

  return rowIndex;
}

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

H
Hongze Cheng 已提交
3512
static int32_t checkForNeighborFileBlock(STsdbReader* pReader, STableBlockScanInfo* pScanInfo, SDataBlk* pBlock,
3513 3514
                                         SFileDataBlockInfo* pFBlock, SRowMerger* pMerger, int64_t key,
                                         CHECK_FILEBLOCK_STATE* state) {
3515
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;
3516
  SBlockData*         pBlockData = &pReader->status.fileBlockData;
3517

3518
  *state = CHECK_FILEBLOCK_QUIT;
3519
  int32_t step = ASCENDING_TRAVERSE(pReader->order) ? 1 : -1;
3520

3521
  bool    loadNeighbor = true;
H
Haojun Liao 已提交
3522
  int32_t code = loadNeighborIfOverlap(pFBlock, pScanInfo, pReader, &loadNeighbor);
3523

H
Haojun Liao 已提交
3524
  if (loadNeighbor && (code == TSDB_CODE_SUCCESS)) {
3525 3526
    pDumpInfo->rowIndex =
        doMergeRowsInFileBlockImpl(pBlockData, pDumpInfo->rowIndex, key, pMerger, &pReader->verRange, step);
H
Haojun Liao 已提交
3527
    if (pDumpInfo->rowIndex >= pDumpInfo->totalRows) {
3528 3529 3530 3531
      *state = CHECK_FILEBLOCK_CONT;
    }
  }

H
Haojun Liao 已提交
3532
  return code;
3533 3534
}

3535 3536
int32_t doMergeRowsInFileBlocks(SBlockData* pBlockData, STableBlockScanInfo* pScanInfo, STsdbReader* pReader,
                                SRowMerger* pMerger) {
3537 3538
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;

3539
  bool    asc = ASCENDING_TRAVERSE(pReader->order);
3540
  int64_t key = pBlockData->aTSKEY[pDumpInfo->rowIndex];
3541
  int32_t step = asc ? 1 : -1;
3542

3543
  pDumpInfo->rowIndex += step;
3544
  if ((pDumpInfo->rowIndex <= pBlockData->nRow - 1 && asc) || (pDumpInfo->rowIndex >= 0 && !asc)) {
3545 3546 3547
    pDumpInfo->rowIndex =
        doMergeRowsInFileBlockImpl(pBlockData, pDumpInfo->rowIndex, key, pMerger, &pReader->verRange, step);
  }
3548

3549 3550 3551 3552
  // 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;
3553

3554
      SFileDataBlockInfo* pFileBlockInfo = getCurrentBlockInfo(&pReader->status.blockIter);
H
Hongze Cheng 已提交
3555
      SDataBlk*           pCurrentBlock = getCurrentBlock(&pReader->status.blockIter);
H
Haojun Liao 已提交
3556 3557 3558 3559 3560
      if (pFileBlockInfo == NULL) {
        st = CHECK_FILEBLOCK_QUIT;
        break;
      }

3561 3562 3563
      checkForNeighborFileBlock(pReader, pScanInfo, pCurrentBlock, pFileBlockInfo, pMerger, key, &st);
      if (st == CHECK_FILEBLOCK_QUIT) {
        break;
3564
      }
3565
    }
H
Haojun Liao 已提交
3566
  }
3567

H
Haojun Liao 已提交
3568 3569 3570
  return TSDB_CODE_SUCCESS;
}

H
Hongze Cheng 已提交
3571
int32_t doMergeRowsInLastBlock(SLastBlockReader* pLastBlockReader, STableBlockScanInfo* pScanInfo, int64_t ts,
3572
                               SRowMerger* pMerger, SVersionRange* pVerRange, const char* idStr) {
3573
  while (nextRowFromLastBlocks(pLastBlockReader, pScanInfo, pVerRange)) {
3574 3575
    int64_t next1 = getCurrentKeyInLastBlock(pLastBlockReader);
    if (next1 == ts) {
3576
      TSDBROW fRow1 = tMergeTreeGetRow(&pLastBlockReader->mergeTree);
H
Hongze Cheng 已提交
3577
      tsdbRowMerge(pMerger, &fRow1);
3578
    } else {
3579 3580 3581
      tsdbTrace("uid:%" PRIu64 " last del index:%d, del range:%d, lastKeyInStt:%" PRId64 ", %s", pScanInfo->uid,
                pScanInfo->lastBlockDelIndex, (int32_t)taosArrayGetSize(pScanInfo->delSkyline), pScanInfo->lastKeyInStt,
                idStr);
3582 3583 3584 3585 3586 3587 3588
      break;
    }
  }

  return TSDB_CODE_SUCCESS;
}

3589
int32_t doMergeMemTableMultiRows(TSDBROW* pRow, uint64_t uid, SIterInfo* pIter, SArray* pDelList, TSDBROW* pResRow,
3590
                                 STsdbReader* pReader, bool* freeTSRow) {
H
Haojun Liao 已提交
3591
  TSDBROW* pNextRow = NULL;
3592
  TSDBROW  current = *pRow;
3593

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

3597
    if (!pIter->hasVal) {
3598
      *pResRow = *pRow;
3599
      *freeTSRow = false;
3600
      return TSDB_CODE_SUCCESS;
3601
    } else {  // has next point in mem/imem
3602
      pNextRow = getValidMemRow(pIter, pDelList, pReader);
3603
      if (pNextRow == NULL) {
H
Haojun Liao 已提交
3604
        *pResRow = current;
3605
        *freeTSRow = false;
3606
        return TSDB_CODE_SUCCESS;
3607 3608
      }

H
Hongze Cheng 已提交
3609
      if (TSDBROW_TS(&current) != TSDBROW_TS(pNextRow)) {
H
Haojun Liao 已提交
3610
        *pResRow = current;
3611
        *freeTSRow = false;
3612
        return TSDB_CODE_SUCCESS;
3613
      }
3614
    }
3615 3616
  }

3617
  SRowMerger merge = {0};
H
Haojun Liao 已提交
3618
  terrno = 0;
3619
  int32_t code = 0;
H
Haojun Liao 已提交
3620

3621 3622 3623 3624 3625 3626 3627
  // start to merge duplicated rows
  if (current.type == TSDBROW_ROW_FMT) {
    // get the correct schema for data in memory
    STSchema* pTSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(&current), pReader, uid);
    if (pTSchema == NULL) {
      return terrno;
    }
H
Haojun Liao 已提交
3628

3629 3630 3631
    if (pReader->pSchema == NULL) {
      pReader->pSchema = pTSchema;
    }
H
Haojun Liao 已提交
3632

3633
    code = tsdbRowMergerInit2(&merge, pReader->pSchema, &current, pTSchema);
3634 3635 3636
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }
H
Haojun Liao 已提交
3637

3638 3639 3640 3641
    STSchema* pTSchema1 = doGetSchemaForTSRow(TSDBROW_SVERSION(pNextRow), pReader, uid);
    if (pTSchema1 == NULL) {
      return terrno;
    }
H
Haojun Liao 已提交
3642

3643
    tsdbRowMergerAdd(&merge, pNextRow, pTSchema1);
3644 3645
  } else {  // let's merge rows in file block
    code = tsdbRowMergerInit(&merge, &current, pReader->pSchema);
3646 3647 3648
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }
H
Haojun Liao 已提交
3649

3650 3651
    tsdbRowMerge(&merge, pNextRow);
  }
H
Haojun Liao 已提交
3652

wmmhello's avatar
wmmhello 已提交
3653
  code = doMergeRowsInBuf(pIter, uid, TSDBROW_TS(&current), pDelList, &merge, pReader);
H
Haojun Liao 已提交
3654 3655 3656 3657
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

3658
  code = tsdbRowMergerGetRow(&merge, &pResRow->pTSRow);
3659 3660 3661
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }
M
Minglei Jin 已提交
3662

wmmhello's avatar
wmmhello 已提交
3663
  pResRow->type = TSDBROW_ROW_FMT;
3664
  tsdbRowMergerClear(&merge);
3665
  *freeTSRow = true;
3666

3667
  return TSDB_CODE_SUCCESS;
3668 3669
}

3670
int32_t doMergeMemIMemRows(TSDBROW* pRow, TSDBROW* piRow, STableBlockScanInfo* pBlockScanInfo, STsdbReader* pReader,
H
Hongze Cheng 已提交
3671
                           SRow** pTSRow) {
H
Haojun Liao 已提交
3672 3673
  SRowMerger merge = {0};

3674 3675 3676
  TSDBKEY k = TSDBROW_KEY(pRow);
  TSDBKEY ik = TSDBROW_KEY(piRow);

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

H
Hongze Cheng 已提交
3680
    int32_t code = tsdbRowMergerInit(&merge, piRow, pSchema);
H
Haojun Liao 已提交
3681 3682 3683 3684 3685 3686 3687 3688 3689
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

    code = doMergeRowsInBuf(&pBlockScanInfo->iiter, pBlockScanInfo->uid, ik.ts, pBlockScanInfo->delSkyline, &merge,
                            pReader);
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }
3690

H
Hongze Cheng 已提交
3691
    tsdbRowMerge(&merge, pRow);
H
Haojun Liao 已提交
3692 3693 3694 3695 3696 3697
    code =
        doMergeRowsInBuf(&pBlockScanInfo->iter, pBlockScanInfo->uid, k.ts, pBlockScanInfo->delSkyline, &merge, pReader);
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

3698
  } else {
H
Haojun Liao 已提交
3699
    STSchema* pSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(pRow), pReader, pBlockScanInfo->uid);
3700

H
Hongze Cheng 已提交
3701
    int32_t code = tsdbRowMergerInit(&merge, pRow, pSchema);
3702
    if (code != TSDB_CODE_SUCCESS || merge.pTSchema == NULL) {
H
Haojun Liao 已提交
3703 3704 3705 3706 3707 3708 3709 3710
      return code;
    }

    code =
        doMergeRowsInBuf(&pBlockScanInfo->iter, pBlockScanInfo->uid, k.ts, pBlockScanInfo->delSkyline, &merge, pReader);
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }
3711

H
Hongze Cheng 已提交
3712
    tsdbRowMerge(&merge, piRow);
H
Haojun Liao 已提交
3713 3714 3715 3716 3717
    code = doMergeRowsInBuf(&pBlockScanInfo->iiter, pBlockScanInfo->uid, ik.ts, pBlockScanInfo->delSkyline, &merge,
                            pReader);
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }
3718
  }
3719

H
Haojun Liao 已提交
3720 3721
  int32_t code = tsdbRowMergerGetRow(&merge, pTSRow);
  tsdbRowMergerClear(&merge);
3722
  return code;
3723 3724
}

3725
int32_t tsdbGetNextRowInMem(STableBlockScanInfo* pBlockScanInfo, STsdbReader* pReader, TSDBROW* pResRow, int64_t endKey,
3726
                            bool* freeTSRow) {
3727 3728
  TSDBROW* pRow = getValidMemRow(&pBlockScanInfo->iter, pBlockScanInfo->delSkyline, pReader);
  TSDBROW* piRow = getValidMemRow(&pBlockScanInfo->iiter, pBlockScanInfo->delSkyline, pReader);
dengyihao's avatar
dengyihao 已提交
3729
  SArray*  pDelList = pBlockScanInfo->delSkyline;
3730
  uint64_t uid = pBlockScanInfo->uid;
H
Haojun Liao 已提交
3731

3732 3733
  // todo refactor
  bool asc = ASCENDING_TRAVERSE(pReader->order);
3734
  if (pBlockScanInfo->iter.hasVal) {
3735 3736 3737 3738 3739 3740
    TSDBKEY k = TSDBROW_KEY(pRow);
    if ((k.ts >= endKey && asc) || (k.ts <= endKey && !asc)) {
      pRow = NULL;
    }
  }

3741
  if (pBlockScanInfo->iiter.hasVal) {
3742 3743 3744 3745 3746 3747
    TSDBKEY k = TSDBROW_KEY(piRow);
    if ((k.ts >= endKey && asc) || (k.ts <= endKey && !asc)) {
      piRow = NULL;
    }
  }

3748
  if (pBlockScanInfo->iter.hasVal && pBlockScanInfo->iiter.hasVal && pRow != NULL && piRow != NULL) {
3749
    TSDBKEY k = TSDBROW_KEY(pRow);
3750
    TSDBKEY ik = TSDBROW_KEY(piRow);
H
Haojun Liao 已提交
3751

3752
    int32_t code = TSDB_CODE_SUCCESS;
3753 3754
    if (ik.ts != k.ts) {
      if (((ik.ts < k.ts) && asc) || ((ik.ts > k.ts) && (!asc))) {  // ik.ts < k.ts
3755
        code = doMergeMemTableMultiRows(piRow, uid, &pBlockScanInfo->iiter, pDelList, pResRow, pReader, freeTSRow);
3756
      } else if (((k.ts < ik.ts) && asc) || ((k.ts > ik.ts) && (!asc))) {
3757
        code = doMergeMemTableMultiRows(pRow, uid, &pBlockScanInfo->iter, pDelList, pResRow, pReader, freeTSRow);
3758
      }
3759
    } else {  // ik.ts == k.ts
3760
      *freeTSRow = true;
3761 3762
      pResRow->type = TSDBROW_ROW_FMT;
      code = doMergeMemIMemRows(pRow, piRow, pBlockScanInfo, pReader, &pResRow->pTSRow);
3763 3764 3765
      if (code != TSDB_CODE_SUCCESS) {
        return code;
      }
H
Haojun Liao 已提交
3766
    }
3767

3768
    return code;
H
Haojun Liao 已提交
3769 3770
  }

3771
  if (pBlockScanInfo->iter.hasVal && pRow != NULL) {
3772
    return doMergeMemTableMultiRows(pRow, pBlockScanInfo->uid, &pBlockScanInfo->iter, pDelList, pResRow, pReader,
H
Hongze Cheng 已提交
3773
                                    freeTSRow);
H
Haojun Liao 已提交
3774 3775
  }

3776
  if (pBlockScanInfo->iiter.hasVal && piRow != NULL) {
3777
    return doMergeMemTableMultiRows(piRow, uid, &pBlockScanInfo->iiter, pDelList, pResRow, pReader, freeTSRow);
H
Haojun Liao 已提交
3778 3779 3780 3781 3782
  }

  return TSDB_CODE_SUCCESS;
}

H
Hongze Cheng 已提交
3783
int32_t doAppendRowFromTSRow(SSDataBlock* pBlock, STsdbReader* pReader, SRow* pTSRow, STableBlockScanInfo* pScanInfo) {
H
Haojun Liao 已提交
3784
  int32_t outputRowIndex = pBlock->info.rows;
3785
  int64_t uid = pScanInfo->uid;
3786 3787 3788

  int32_t numOfCols = (int32_t)taosArrayGetSize(pBlock->pDataBlock);

3789
  SBlockLoadSuppInfo* pSupInfo = &pReader->suppInfo;
3790
  STSchema*           pSchema = doGetSchemaForTSRow(pTSRow->sver, pReader, uid);
3791

3792
  SColVal colVal = {0};
3793
  int32_t i = 0, j = 0;
H
Haojun Liao 已提交
3794

3795
  if (pSupInfo->colId[i] == PRIMARYKEY_TIMESTAMP_COL_ID) {
H
Haojun Liao 已提交
3796
    SColumnInfoData* pColData = taosArrayGet(pBlock->pDataBlock, pSupInfo->slotId[i]);
H
Haojun Liao 已提交
3797
    ((int64_t*)pColData->pData)[outputRowIndex] = pTSRow->ts;
3798 3799 3800
    i += 1;
  }

H
Haojun Liao 已提交
3801
  while (i < pSupInfo->numOfCols && j < pSchema->numOfCols) {
H
Haojun Liao 已提交
3802
    col_id_t colId = pSupInfo->colId[i];
3803 3804

    if (colId == pSchema->columns[j].colId) {
H
Haojun Liao 已提交
3805
      SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, pSupInfo->slotId[i]);
H
Haojun Liao 已提交
3806

H
Hongze Cheng 已提交
3807
      tRowGet(pTSRow, pSchema, j, &colVal);
H
Haojun Liao 已提交
3808
      doCopyColVal(pColInfoData, outputRowIndex, i, &colVal, pSupInfo);
3809 3810 3811
      i += 1;
      j += 1;
    } else if (colId < pSchema->columns[j].colId) {
H
Haojun Liao 已提交
3812
      SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, pSupInfo->slotId[i]);
H
Haojun Liao 已提交
3813

3814
      colDataSetNULL(pColInfoData, outputRowIndex);
3815 3816 3817
      i += 1;
    } else if (colId > pSchema->columns[j].colId) {
      j += 1;
3818
    }
3819 3820
  }

3821
  // set null value since current column does not exist in the "pSchema"
H
Haojun Liao 已提交
3822
  while (i < pSupInfo->numOfCols) {
H
Haojun Liao 已提交
3823
    SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, pSupInfo->slotId[i]);
3824
    colDataSetNULL(pColInfoData, outputRowIndex);
3825 3826 3827
    i += 1;
  }

3828
  pBlock->info.dataLoad = 1;
3829
  pBlock->info.rows += 1;
3830
  pScanInfo->lastKey = pTSRow->ts;
3831 3832 3833
  return TSDB_CODE_SUCCESS;
}

H
Hongze Cheng 已提交
3834 3835
int32_t doAppendRowFromFileBlock(SSDataBlock* pResBlock, STsdbReader* pReader, SBlockData* pBlockData,
                                 int32_t rowIndex) {
3836 3837 3838 3839
  int32_t i = 0, j = 0;
  int32_t outputRowIndex = pResBlock->info.rows;

  SBlockLoadSuppInfo* pSupInfo = &pReader->suppInfo;
3840
  if (pReader->suppInfo.colId[i] == PRIMARYKEY_TIMESTAMP_COL_ID) {
H
Haojun Liao 已提交
3841
    SColumnInfoData* pColData = taosArrayGet(pResBlock->pDataBlock, pSupInfo->slotId[i]);
H
Haojun Liao 已提交
3842
    ((int64_t*)pColData->pData)[outputRowIndex] = pBlockData->aTSKEY[rowIndex];
3843
    i += 1;
3844 3845 3846
  }

  SColVal cv = {0};
H
Hongze Cheng 已提交
3847
  int32_t numOfInputCols = pBlockData->nColData;
H
Haojun Liao 已提交
3848
  int32_t numOfOutputCols = pSupInfo->numOfCols;
3849

3850
  while (i < numOfOutputCols && j < numOfInputCols) {
H
Haojun Liao 已提交
3851
    SColData* pData = tBlockDataGetColDataByIdx(pBlockData, j);
H
Haojun Liao 已提交
3852
    if (pData->cid < pSupInfo->colId[i]) {
3853 3854 3855 3856
      j += 1;
      continue;
    }

H
Haojun Liao 已提交
3857 3858
    SColumnInfoData* pCol = TARRAY_GET_ELEM(pResBlock->pDataBlock, pSupInfo->slotId[i]);
    if (pData->cid == pSupInfo->colId[i]) {
3859 3860
      tColDataGetValue(pData, rowIndex, &cv);
      doCopyColVal(pCol, outputRowIndex, i, &cv, pSupInfo);
3861
      j += 1;
H
Haojun Liao 已提交
3862 3863
    } else if (pData->cid > pCol->info.colId) {
      // the specified column does not exist in file block, fill with null data
3864
      colDataSetNULL(pCol, outputRowIndex);
3865 3866 3867 3868 3869 3870
    }

    i += 1;
  }

  while (i < numOfOutputCols) {
H
Haojun Liao 已提交
3871
    SColumnInfoData* pCol = taosArrayGet(pResBlock->pDataBlock, pSupInfo->slotId[i]);
3872
    colDataSetNULL(pCol, outputRowIndex);
3873 3874 3875
    i += 1;
  }

3876
  pResBlock->info.dataLoad = 1;
3877 3878 3879 3880
  pResBlock->info.rows += 1;
  return TSDB_CODE_SUCCESS;
}

3881 3882
int32_t buildDataBlockFromBufImpl(STableBlockScanInfo* pBlockScanInfo, int64_t endKey, int32_t capacity,
                                  STsdbReader* pReader) {
H
Haojun Liao 已提交
3883 3884 3885
  SSDataBlock* pBlock = pReader->pResBlock;

  do {
3886
    //    SRow* pTSRow = NULL;
3887
    TSDBROW row = {.type = -1};
3888
    bool    freeTSRow = false;
3889 3890
    tsdbGetNextRowInMem(pBlockScanInfo, pReader, &row, endKey, &freeTSRow);
    if (row.type == -1) {
3891
      break;
H
Haojun Liao 已提交
3892 3893
    }

3894 3895
    if (row.type == TSDBROW_ROW_FMT) {
      doAppendRowFromTSRow(pBlock, pReader, row.pTSRow, pBlockScanInfo);
3896

3897 3898 3899 3900 3901
      if (freeTSRow) {
        taosMemoryFree(row.pTSRow);
      }
    } else {
      doAppendRowFromFileBlock(pBlock, pReader, row.pBlockData, row.iRow);
3902
    }
H
Haojun Liao 已提交
3903 3904

    // no data in buffer, return immediately
3905
    if (!(pBlockScanInfo->iter.hasVal || pBlockScanInfo->iiter.hasVal)) {
H
Haojun Liao 已提交
3906 3907 3908
      break;
    }

3909
    if (pBlock->info.rows >= capacity) {
H
Haojun Liao 已提交
3910 3911 3912 3913 3914 3915
      break;
    }
  } while (1);

  return TSDB_CODE_SUCCESS;
}
H
Hongze Cheng 已提交
3916

3917 3918
// TODO refactor: with createDataBlockScanInfo
int32_t tsdbSetTableList(STsdbReader* pReader, const void* pTableList, int32_t num) {
3919
  int32_t size = taosHashGetSize(pReader->status.pTableMap);
3920

3921
  STableBlockScanInfo** p = NULL;
3922
  while ((p = taosHashIterate(pReader->status.pTableMap, p)) != NULL) {
3923
    clearBlockScanInfo(*p);
3924 3925
  }

D
dapan1121 已提交
3926 3927 3928 3929 3930
  if (size < num) {
    int32_t code = ensureBlockScanInfoBuf(&pReader->blockInfoBuf, num);
    if (code) {
      return code;
    }
D
dapan1121 已提交
3931
    pReader->status.uidList.tableUidList = (uint64_t*)taosMemoryRealloc(pReader->status.uidList.tableUidList, sizeof(uint64_t) * num);
D
dapan1121 已提交
3932
  }
3933

3934
  taosHashClear(pReader->status.pTableMap);
3935
  STableUidList* pUidList = &pReader->status.uidList;
H
Haojun Liao 已提交
3936
  pUidList->currentIndex = 0;
3937

3938 3939
  STableKeyInfo* pList = (STableKeyInfo*)pTableList;
  for (int32_t i = 0; i < num; ++i) {
3940 3941
    STableBlockScanInfo* pInfo = getPosInBlockInfoBuf(&pReader->blockInfoBuf, i);
    pInfo->uid = pList[i].uid;
H
Haojun Liao 已提交
3942 3943
    pUidList->tableUidList[i] = pList[i].uid;

3944
    taosHashPut(pReader->status.pTableMap, &pInfo->uid, sizeof(uint64_t), &pInfo, POINTER_BYTES);
3945 3946
  }

H
Hongze Cheng 已提交
3947 3948 3949
  return TDB_CODE_SUCCESS;
}

dengyihao's avatar
dengyihao 已提交
3950 3951 3952 3953 3954 3955
void* tsdbGetIdx(SMeta* pMeta) {
  if (pMeta == NULL) {
    return NULL;
  }
  return metaGetIdx(pMeta);
}
dengyihao's avatar
dengyihao 已提交
3956

dengyihao's avatar
dengyihao 已提交
3957 3958 3959 3960 3961 3962
void* tsdbGetIvtIdx(SMeta* pMeta) {
  if (pMeta == NULL) {
    return NULL;
  }
  return metaGetIvtIdx(pMeta);
}
L
Liu Jicong 已提交
3963

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

3966
static int32_t doOpenReaderImpl(STsdbReader* pReader) {
3967 3968
  SReaderStatus*  pStatus = &pReader->status;
  SDataBlockIter* pBlockIter = &pStatus->blockIter;
3969

3970 3971
  initFilesetIterator(&pStatus->fileIter, pReader->pReadSnap->fs.aDFileSet, pReader);
  resetDataBlockIterator(&pStatus->blockIter, pReader->order);
3972

3973 3974 3975
  int32_t code = TSDB_CODE_SUCCESS;
  if (pStatus->fileIter.numOfFiles == 0) {
    pStatus->loadFromFile = false;
3976
  } else {
3977
    code = initForFirstBlockInFile(pReader, pBlockIter);
3978
  }
3979 3980 3981

  if (!pStatus->loadFromFile) {
    resetTableListIndex(pStatus);
3982
  }
3983 3984

  return code;
3985 3986
}

H
refact  
Hongze Cheng 已提交
3987
// ====================================== EXPOSED APIs ======================================
3988
int32_t tsdbReaderOpen(SVnode* pVnode, SQueryTableDataCond* pCond, void* pTableList, int32_t numOfTables,
H
Haojun Liao 已提交
3989
                       SSDataBlock* pResBlock, STsdbReader** ppReader, const char* idstr) {
3990 3991 3992 3993 3994 3995
  STimeWindow window = pCond->twindows;
  if (pCond->type == TIMEWINDOW_RANGE_EXTERNAL) {
    pCond->twindows.skey += 1;
    pCond->twindows.ekey -= 1;
  }

3996 3997 3998
  int32_t capacity = pVnode->config.tsdbCfg.maxRows;
  if (pResBlock != NULL) {
    blockDataEnsureCapacity(pResBlock, capacity);
H
Haojun Liao 已提交
3999 4000 4001
  }

  int32_t code = tsdbReaderCreate(pVnode, pCond, ppReader, capacity, pResBlock, idstr);
4002
  if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
4003 4004
    goto _err;
  }
H
Hongze Cheng 已提交
4005

4006
  // check for query time window
H
Haojun Liao 已提交
4007
  STsdbReader* pReader = *ppReader;
4008
  if (isEmptyQueryTimeWindow(&pReader->window) && pCond->type == TIMEWINDOW_RANGE_CONTAINED) {
H
Haojun Liao 已提交
4009 4010 4011
    tsdbDebug("%p query window not overlaps with the data set, no result returned, %s", pReader, pReader->idStr);
    return TSDB_CODE_SUCCESS;
  }
H
Hongze Cheng 已提交
4012

4013 4014
  if (pCond->type == TIMEWINDOW_RANGE_EXTERNAL) {
    // update the SQueryTableDataCond to create inner reader
4015
    int32_t order = pCond->order;
4016
    if (order == TSDB_ORDER_ASC) {
4017
      pCond->twindows.ekey = window.skey;
4018 4019 4020
      pCond->twindows.skey = INT64_MIN;
      pCond->order = TSDB_ORDER_DESC;
    } else {
4021
      pCond->twindows.skey = window.ekey;
4022 4023 4024 4025
      pCond->twindows.ekey = INT64_MAX;
      pCond->order = TSDB_ORDER_ASC;
    }

4026
    // here we only need one more row, so the capacity is set to be ONE.
H
Haojun Liao 已提交
4027
    code = tsdbReaderCreate(pVnode, pCond, &pReader->innerReader[0], 1, pResBlock, idstr);
4028 4029 4030 4031 4032
    if (code != TSDB_CODE_SUCCESS) {
      goto _err;
    }

    if (order == TSDB_ORDER_ASC) {
4033
      pCond->twindows.skey = window.ekey;
4034
      pCond->twindows.ekey = INT64_MAX;
4035
    } else {
4036
      pCond->twindows.skey = INT64_MIN;
4037
      pCond->twindows.ekey = window.ekey;
4038
    }
4039 4040
    pCond->order = order;

H
Haojun Liao 已提交
4041
    code = tsdbReaderCreate(pVnode, pCond, &pReader->innerReader[1], 1, pResBlock, idstr);
4042 4043 4044 4045 4046
    if (code != TSDB_CODE_SUCCESS) {
      goto _err;
    }
  }

H
Haojun Liao 已提交
4047
  // NOTE: the endVersion in pCond is the data version not schema version, so pCond->endVersion is not correct here.
4048 4049
  //  no valid error code set in metaGetTbTSchema, so let's set the error code here.
  //  we should proceed in case of tmq processing.
4050
  if (pCond->suid != 0) {
4051
    pReader->pSchema = metaGetTbTSchema(pReader->pTsdb->pVnode->pMeta, pReader->suid, -1, 1);
H
Haojun Liao 已提交
4052
    if (pReader->pSchema == NULL) {
H
Haojun Liao 已提交
4053
      tsdbError("failed to get table schema, suid:%" PRIu64 ", ver:-1, %s", pReader->suid, pReader->idStr);
H
Haojun Liao 已提交
4054
    }
4055 4056
  } else if (numOfTables > 0) {
    STableKeyInfo* pKey = pTableList;
4057
    pReader->pSchema = metaGetTbTSchema(pReader->pTsdb->pVnode->pMeta, pKey->uid, -1, 1);
H
Haojun Liao 已提交
4058
    if (pReader->pSchema == NULL) {
H
Haojun Liao 已提交
4059
      tsdbError("failed to get table schema, uid:%" PRIu64 ", ver:-1, %s", pKey->uid, pReader->idStr);
H
Haojun Liao 已提交
4060
    }
4061 4062
  }

4063
  if (pReader->pSchema != NULL) {
H
Haojun Liao 已提交
4064 4065 4066 4067
    code = updateBlockSMAInfo(pReader->pSchema, &pReader->suppInfo);
    if (code != TSDB_CODE_SUCCESS) {
      goto _err;
    }
4068
  }
4069

4070
  STsdbReader* p = (pReader->innerReader[0] != NULL) ? pReader->innerReader[0] : pReader;
X
Xiaoyu Wang 已提交
4071 4072
  pReader->status.pTableMap =
      createDataBlockScanInfo(p, &pReader->blockInfoBuf, pTableList, &pReader->status.uidList, numOfTables);
H
Haojun Liao 已提交
4073 4074
  if (pReader->status.pTableMap == NULL) {
    *ppReader = NULL;
S
Shengliang Guan 已提交
4075
    code = TSDB_CODE_OUT_OF_MEMORY;
H
Haojun Liao 已提交
4076 4077
    goto _err;
  }
H
Hongze Cheng 已提交
4078

4079
  pReader->suspended = true;
4080

4081
  tsdbDebug("%p total numOfTable:%d in this query %s", pReader, numOfTables, pReader->idStr);
H
Hongze Cheng 已提交
4082
  return code;
H
Hongze Cheng 已提交
4083 4084

_err:
H
Haojun Liao 已提交
4085
  tsdbError("failed to create data reader, code:%s %s", tstrerror(code), idstr);
4086
  tsdbReaderClose(pReader);
X
Xiaoyu Wang 已提交
4087
  *ppReader = NULL;  // reset the pointer value.
H
Hongze Cheng 已提交
4088
  return code;
H
refact  
Hongze Cheng 已提交
4089 4090 4091
}

void tsdbReaderClose(STsdbReader* pReader) {
4092 4093
  if (pReader == NULL) {
    return;
4094
  }
H
refact  
Hongze Cheng 已提交
4095

4096
  tsdbAcquireReader(pReader);
4097
  {
H
Haojun Liao 已提交
4098
    if (pReader->innerReader[0] != NULL || pReader->innerReader[1] != NULL) {
4099
      STsdbReader* p = pReader->innerReader[0];
4100

4101
      p->status.pTableMap = NULL;
H
Haojun Liao 已提交
4102
      p->status.uidList.tableUidList = NULL;
4103 4104 4105 4106 4107 4108 4109
      p->pReadSnap = NULL;
      p->pSchema = NULL;
      p->pMemSchema = NULL;

      p = pReader->innerReader[1];

      p->status.pTableMap = NULL;
H
Haojun Liao 已提交
4110
      p->status.uidList.tableUidList = NULL;
4111 4112 4113
      p->pReadSnap = NULL;
      p->pSchema = NULL;
      p->pMemSchema = NULL;
4114 4115 4116 4117 4118 4119

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

4120
  SBlockLoadSuppInfo* pSupInfo = &pReader->suppInfo;
H
Hongze Cheng 已提交
4121

4122
  taosArrayDestroy(pSupInfo->pColAgg);
H
Haojun Liao 已提交
4123
  for (int32_t i = 0; i < pSupInfo->numOfCols; ++i) {
4124 4125 4126 4127
    if (pSupInfo->buildBuf[i] != NULL) {
      taosMemoryFreeClear(pSupInfo->buildBuf[i]);
    }
  }
4128

H
Haojun Liao 已提交
4129 4130 4131
  if (pReader->freeBlock) {
    pReader->pResBlock = blockDataDestroy(pReader->pResBlock);
  }
4132

H
Haojun Liao 已提交
4133
  taosMemoryFree(pSupInfo->colId);
H
Hongze Cheng 已提交
4134
  tBlockDataDestroy(&pReader->status.fileBlockData);
4135
  cleanupDataBlockIterator(&pReader->status.blockIter);
4136 4137

  size_t numOfTables = taosHashGetSize(pReader->status.pTableMap);
H
Haojun Liao 已提交
4138 4139 4140 4141
  if (pReader->status.pTableMap != NULL) {
    destroyAllBlockScanInfo(pReader->status.pTableMap);
    clearBlockScanInfoBuf(&pReader->blockInfoBuf);
  }
4142

H
Haojun Liao 已提交
4143 4144 4145
  if (pReader->pFileReader != NULL) {
    tsdbDataFReaderClose(&pReader->pFileReader);
  }
H
refact  
Hongze Cheng 已提交
4146

4147 4148 4149 4150 4151 4152 4153 4154 4155
  if (pReader->pDelFReader != NULL) {
    tsdbDelFReaderClose(&pReader->pDelFReader);
  }

  if (pReader->pDelIdx != NULL) {
    taosArrayDestroy(pReader->pDelIdx);
    pReader->pDelIdx = NULL;
  }

4156
  qTrace("tsdb/reader-close: %p, untake snapshot", pReader);
4157
  tsdbUntakeReadSnap(pReader, pReader->pReadSnap, true);
4158
  pReader->pReadSnap = NULL;
4159

4160 4161
  tsdbReleaseReader(pReader);

4162
  tsdbUninitReaderLock(pReader);
4163

4164
  taosMemoryFree(pReader->status.uidList.tableUidList);
H
Haojun Liao 已提交
4165
  SIOCostSummary* pCost = &pReader->cost;
4166

H
Haojun Liao 已提交
4167 4168
  SFilesetIter* pFilesetIter = &pReader->status.fileIter;
  if (pFilesetIter->pLastBlockReader != NULL) {
H
Haojun Liao 已提交
4169 4170
    SLastBlockReader* pLReader = pFilesetIter->pLastBlockReader;
    tMergeTreeClose(&pLReader->mergeTree);
H
Haojun Liao 已提交
4171

H
Haojun Liao 已提交
4172
    getLastBlockLoadInfo(pLReader->pInfo, &pCost->lastBlockLoad, &pCost->lastBlockLoadTime);
H
refact  
Hongze Cheng 已提交
4173

H
Haojun Liao 已提交
4174 4175 4176
    pLReader->pInfo = destroyLastBlockLoadInfo(pLReader->pInfo);
    taosMemoryFree(pLReader);
  }
H
refact  
Hongze Cheng 已提交
4177

4178 4179 4180 4181 4182
  tsdbDebug(
      "%p :io-cost summary: head-file:%" PRIu64 ", head-file time:%.2f ms, SMA:%" PRId64
      " SMA-time:%.2f ms, fileBlocks:%" PRId64
      ", fileBlocks-load-time:%.2f ms, "
      "build in-memory-block-time:%.2f ms, lastBlocks:%" PRId64 ", lastBlocks-time:%.2f ms, composed-blocks:%" PRId64
X
Xiaoyu Wang 已提交
4183 4184
      ", composed-blocks-time:%.2fms, STableBlockScanInfo size:%.2f Kb, createTime:%.2f ms,initDelSkylineIterTime:%.2f "
      "ms, %s",
4185 4186 4187
      pReader, pCost->headFileLoad, pCost->headFileLoadTime, pCost->smaDataLoad, pCost->smaLoadTime, pCost->numOfBlocks,
      pCost->blockLoadTime, pCost->buildmemBlock, pCost->lastBlockLoad, pCost->lastBlockLoadTime, pCost->composedBlocks,
      pCost->buildComposedBlockTime, numOfTables * sizeof(STableBlockScanInfo) / 1000.0, pCost->createScanInfoList,
H
Haojun Liao 已提交
4188
      pCost->initDelSkylineIterTime, pReader->idStr);
H
refact  
Hongze Cheng 已提交
4189

4190 4191
  taosMemoryFree(pReader->idStr);
  taosMemoryFree(pReader->pSchema);
4192

4193 4194 4195
  if (pReader->pMemSchema != pReader->pSchema) {
    taosMemoryFree(pReader->pMemSchema);
  }
4196

4197
  taosMemoryFreeClear(pReader);
H
refact  
Hongze Cheng 已提交
4198 4199
}

4200 4201 4202 4203 4204 4205 4206 4207 4208 4209
int32_t tsdbReaderSuspend(STsdbReader* pReader) {
  int32_t code = 0;

  // save reader's base state & reset top state to be reconstructed from base state
  SReaderStatus*       pStatus = &pReader->status;
  STableBlockScanInfo* pBlockScanInfo = NULL;

  if (pStatus->loadFromFile) {
    SFileDataBlockInfo* pBlockInfo = getCurrentBlockInfo(&pReader->status.blockIter);
    if (pBlockInfo != NULL) {
4210 4211
      pBlockScanInfo =
          *(STableBlockScanInfo**)taosHashGet(pStatus->pTableMap, &pBlockInfo->uid, sizeof(pBlockInfo->uid));
4212 4213 4214 4215 4216 4217 4218
      if (pBlockScanInfo == NULL) {
        code = TSDB_CODE_INVALID_PARA;
        tsdbError("failed to locate the uid:%" PRIu64 " in query table uid list, total tables:%d, %s", pBlockInfo->uid,
                  taosHashGetSize(pReader->status.pTableMap), pReader->idStr);
        goto _err;
      }
    } else {
4219
      pBlockScanInfo = *pStatus->pTableIter;
4220 4221 4222 4223 4224
    }

    tsdbDataFReaderClose(&pReader->pFileReader);

    // resetDataBlockScanInfo excluding lastKey
4225
    STableBlockScanInfo** p = NULL;
4226 4227

    while ((p = taosHashIterate(pStatus->pTableMap, p)) != NULL) {
4228 4229 4230 4231 4232 4233 4234 4235
      STableBlockScanInfo* pInfo = *(STableBlockScanInfo**)p;

      pInfo->iterInit = false;
      pInfo->iter.hasVal = false;
      pInfo->iiter.hasVal = false;

      if (pInfo->iter.iter != NULL) {
        pInfo->iter.iter = tsdbTbDataIterDestroy(pInfo->iter.iter);
4236 4237
      }

4238 4239 4240 4241 4242 4243
      if (pInfo->iiter.iter != NULL) {
        pInfo->iiter.iter = tsdbTbDataIterDestroy(pInfo->iiter.iter);
      }

      pInfo->delSkyline = taosArrayDestroy(pInfo->delSkyline);
      // pInfo->lastKey = ts;
4244 4245
    }
  } else {
4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267
    // resetDataBlockScanInfo excluding lastKey
    STableBlockScanInfo** p = NULL;

    while ((p = taosHashIterate(pStatus->pTableMap, p)) != NULL) {
      STableBlockScanInfo* pInfo = *(STableBlockScanInfo**)p;

      pInfo->iterInit = false;
      pInfo->iter.hasVal = false;
      pInfo->iiter.hasVal = false;

      if (pInfo->iter.iter != NULL) {
        pInfo->iter.iter = tsdbTbDataIterDestroy(pInfo->iter.iter);
      }

      if (pInfo->iiter.iter != NULL) {
        pInfo->iiter.iter = tsdbTbDataIterDestroy(pInfo->iiter.iter);
      }

      pInfo->delSkyline = taosArrayDestroy(pInfo->delSkyline);
      // pInfo->lastKey = ts;
    }

4268
    pBlockScanInfo = pStatus->pTableIter == NULL ? NULL : *pStatus->pTableIter;
4269 4270 4271 4272 4273 4274 4275
    if (pBlockScanInfo) {
      // save lastKey to restore memory iterator
      STimeWindow w = pReader->pResBlock->info.window;
      pBlockScanInfo->lastKey = ASCENDING_TRAVERSE(pReader->order) ? w.ekey : w.skey;

      // reset current current table's data block scan info,
      pBlockScanInfo->iterInit = false;
4276 4277
      pBlockScanInfo->iter.hasVal = false;
      pBlockScanInfo->iiter.hasVal = false;
4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292
      if (pBlockScanInfo->iter.iter != NULL) {
        pBlockScanInfo->iter.iter = tsdbTbDataIterDestroy(pBlockScanInfo->iter.iter);
      }

      if (pBlockScanInfo->iiter.iter != NULL) {
        pBlockScanInfo->iiter.iter = tsdbTbDataIterDestroy(pBlockScanInfo->iiter.iter);
      }

      pBlockScanInfo->pBlockList = taosArrayDestroy(pBlockScanInfo->pBlockList);
      tMapDataClear(&pBlockScanInfo->mapData);
      // TODO: keep skyline for reuse
      pBlockScanInfo->delSkyline = taosArrayDestroy(pBlockScanInfo->delSkyline);
    }
  }

4293
  tsdbUntakeReadSnap(pReader, pReader->pReadSnap, false);
4294
  pReader->pReadSnap = NULL;
4295 4296 4297

  pReader->suspended = true;

4298 4299
  tsdbDebug("reader: %p suspended uid %" PRIu64 " in this query %s", pReader, pBlockScanInfo ? pBlockScanInfo->uid : 0,
            pReader->idStr);
4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310
  return code;

_err:
  tsdbError("failed to suspend data reader, code:%s %s", tstrerror(code), pReader->idStr);
  return code;
}

static int32_t tsdbSetQueryReseek(void* pQHandle) {
  int32_t      code = 0;
  STsdbReader* pReader = pQHandle;

4311
  code = tsdbTryAcquireReader(pReader);
4312 4313
  if (code == 0) {
    if (pReader->suspended) {
4314
      tsdbReleaseReader(pReader);
4315 4316 4317 4318
      return code;
    }

    tsdbReaderSuspend(pReader);
4319

4320
    tsdbReleaseReader(pReader);
4321

4322
    return code;
4323 4324 4325
  } else if (code == EBUSY) {
    return TSDB_CODE_VND_QUERY_BUSY;
  } else {
4326 4327
    terrno = TAOS_SYSTEM_ERROR(code);
    return TSDB_CODE_FAILED;
4328 4329 4330 4331 4332 4333
  }
}

int32_t tsdbReaderResume(STsdbReader* pReader) {
  int32_t code = 0;

4334
  STableBlockScanInfo** pBlockScanInfo = pReader->status.pTableIter;
4335 4336 4337

  //  restore reader's state
  //  task snapshot
4338
  int32_t numOfTables = taosHashGetSize(pReader->status.pTableMap);
4339
  if (numOfTables > 0) {
4340
    qTrace("tsdb/reader: %p, take snapshot", pReader);
4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357
    code = tsdbTakeReadSnap(pReader, tsdbSetQueryReseek, &pReader->pReadSnap);
    if (code != TSDB_CODE_SUCCESS) {
      goto _err;
    }

    if (pReader->type == TIMEWINDOW_RANGE_CONTAINED) {
      code = doOpenReaderImpl(pReader);
      if (code != TSDB_CODE_SUCCESS) {
        return code;
      }
    } else {
      STsdbReader* pPrevReader = pReader->innerReader[0];
      STsdbReader* pNextReader = pReader->innerReader[1];

      // we need only one row
      pPrevReader->capacity = 1;
      pPrevReader->status.pTableMap = pReader->status.pTableMap;
X
Xiaoyu Wang 已提交
4358
      pPrevReader->status.uidList = pReader->status.uidList;
4359 4360 4361 4362 4363 4364
      pPrevReader->pSchema = pReader->pSchema;
      pPrevReader->pMemSchema = pReader->pMemSchema;
      pPrevReader->pReadSnap = pReader->pReadSnap;

      pNextReader->capacity = 1;
      pNextReader->status.pTableMap = pReader->status.pTableMap;
X
Xiaoyu Wang 已提交
4365
      pNextReader->status.uidList = pReader->status.uidList;
4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378
      pNextReader->pSchema = pReader->pSchema;
      pNextReader->pMemSchema = pReader->pMemSchema;
      pNextReader->pReadSnap = pReader->pReadSnap;

      code = doOpenReaderImpl(pPrevReader);
      if (code != TSDB_CODE_SUCCESS) {
        return code;
      }
    }
  }

  pReader->suspended = false;

4379 4380
  tsdbDebug("reader: %p resumed uid %" PRIu64 ", numOfTable:%" PRId32 ", in this query %s", pReader,
            pBlockScanInfo ? (*pBlockScanInfo)->uid : 0, numOfTables, pReader->idStr);
4381 4382 4383 4384 4385 4386 4387
  return code;

_err:
  tsdbError("failed to resume data reader, code:%s %s", tstrerror(code), pReader->idStr);
  return code;
}

4388
static bool doTsdbNextDataBlock(STsdbReader* pReader) {
H
Haojun Liao 已提交
4389
  // cleanup the data that belongs to the previous data block
4390 4391
  SSDataBlock* pBlock = pReader->pResBlock;
  blockDataCleanup(pBlock);
H
Hongze Cheng 已提交
4392

4393
  SReaderStatus* pStatus = &pReader->status;
4394
  if (taosHashGetSize(pStatus->pTableMap) == 0) {
4395 4396
    return false;
  }
H
Haojun Liao 已提交
4397

4398 4399 4400 4401 4402
  if (pStatus->loadFromFile) {
    int32_t code = buildBlockFromFiles(pReader);
    if (code != TSDB_CODE_SUCCESS) {
      return false;
    }
4403

4404 4405 4406
    if (pBlock->info.rows > 0) {
      return true;
    } else {
4407
      resetTableListIndex(&pReader->status);
H
Haojun Liao 已提交
4408
      buildBlockFromBufferSequentially(pReader);
4409
      return pBlock->info.rows > 0;
H
Haojun Liao 已提交
4410
    }
4411 4412 4413
  } else {  // no data in files, let's try the buffer
    buildBlockFromBufferSequentially(pReader);
    return pBlock->info.rows > 0;
H
Haojun Liao 已提交
4414
  }
H
refact  
Hongze Cheng 已提交
4415 4416
}

4417
bool tsdbNextDataBlock(STsdbReader* pReader) {
4418
  if (isEmptyQueryTimeWindow(&pReader->window) || pReader->step == EXTERNAL_ROWS_NEXT) {
4419 4420 4421
    return false;
  }

4422 4423
  SReaderStatus* pStatus = &pReader->status;

4424 4425 4426
  int32_t code = tsdbAcquireReader(pReader);
  qTrace("tsdb/read: %p, take read mutex, code: %d", pReader, code);

4427 4428 4429 4430
  if (pReader->suspended) {
    tsdbReaderResume(pReader);
  }

4431
  if (pReader->innerReader[0] != NULL && pReader->step == 0) {
4432
    bool ret = doTsdbNextDataBlock(pReader->innerReader[0]);
4433
    pReader->step = EXTERNAL_ROWS_PREV;
4434
    if (ret) {
4435
      pStatus = &pReader->innerReader[0]->status;
4436
      if (pStatus->composedDataBlock) {
4437
        qTrace("tsdb/read: %p, unlock read mutex", pReader);
4438
        tsdbReleaseReader(pReader);
4439 4440
      }

4441 4442
      return ret;
    }
4443
  }
4444

4445
  if (pReader->step == EXTERNAL_ROWS_PREV) {
4446 4447
    // prepare for the main scan
    int32_t code = doOpenReaderImpl(pReader);
4448
    resetAllDataBlockScanInfo(pReader->status.pTableMap, pReader->innerReader[0]->window.ekey);
4449 4450 4451 4452 4453

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

4454
    pReader->step = EXTERNAL_ROWS_MAIN;
4455 4456 4457 4458
  }

  bool ret = doTsdbNextDataBlock(pReader);
  if (ret) {
4459
    if (pStatus->composedDataBlock) {
4460
      qTrace("tsdb/read: %p, unlock read mutex", pReader);
4461
      tsdbReleaseReader(pReader);
4462 4463
    }

4464 4465 4466
    return ret;
  }

4467
  if (pReader->step == EXTERNAL_ROWS_MAIN && pReader->innerReader[1] != NULL) {
4468 4469
    // prepare for the next row scan
    int32_t code = doOpenReaderImpl(pReader->innerReader[1]);
4470
    resetAllDataBlockScanInfo(pReader->innerReader[1]->status.pTableMap, pReader->window.ekey);
4471 4472 4473 4474
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

4475
    ret = doTsdbNextDataBlock(pReader->innerReader[1]);
4476
    pReader->step = EXTERNAL_ROWS_NEXT;
4477
    if (ret) {
4478
      pStatus = &pReader->innerReader[1]->status;
4479
      if (pStatus->composedDataBlock) {
4480
        qTrace("tsdb/read: %p, unlock read mutex", pReader);
4481
        tsdbReleaseReader(pReader);
4482 4483
      }

4484
      return ret;
4485 4486 4487
    }
  }

4488
  qTrace("tsdb/read: %p, unlock read mutex", pReader);
4489
  tsdbReleaseReader(pReader);
4490

4491 4492 4493
  return false;
}

4494
static void doFillNullColSMA(SBlockLoadSuppInfo* pSup, int32_t numOfRows, int32_t numOfCols, SColumnDataAgg* pTsAgg) {
4495 4496
  // do fill all null column value SMA info
  int32_t i = 0, j = 0;
4497
  int32_t size = (int32_t)taosArrayGetSize(pSup->pColAgg);
4498
  taosArrayInsert(pSup->pColAgg, 0, pTsAgg);
4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509

  while (j < numOfCols && i < size) {
    SColumnDataAgg* pAgg = taosArrayGet(pSup->pColAgg, i);
    if (pAgg->colId == pSup->colId[j]) {
      i += 1;
      j += 1;
    } else if (pAgg->colId < pSup->colId[j]) {
      i += 1;
    } else if (pSup->colId[j] < pAgg->colId) {
      if (pSup->colId[j] != PRIMARYKEY_TIMESTAMP_COL_ID) {
        SColumnDataAgg nullColAgg = {.colId = pSup->colId[j], .numOfNull = numOfRows};
4510
        taosArrayInsert(pSup->pColAgg, i, &nullColAgg);
4511 4512 4513 4514 4515 4516
      }
      j += 1;
    }
  }
}

4517
int32_t tsdbRetrieveDatablockSMA(STsdbReader* pReader, SSDataBlock* pDataBlock, bool* allHave) {
H
Haojun Liao 已提交
4518 4519
  SColumnDataAgg*** pBlockSMA = &pDataBlock->pBlockAgg;

H
Hongze Cheng 已提交
4520
  int32_t code = 0;
4521
  *allHave = false;
H
Haojun Liao 已提交
4522
  *pBlockSMA = NULL;
H
Hongze Cheng 已提交
4523

4524
  if (pReader->type == TIMEWINDOW_RANGE_EXTERNAL) {
4525 4526 4527
    return TSDB_CODE_SUCCESS;
  }

4528
  // there is no statistics data for composed block
4529
  if (pReader->status.composedDataBlock || (!pReader->suppInfo.smaValid)) {
4530 4531
    return TSDB_CODE_SUCCESS;
  }
H
Hongze Cheng 已提交
4532

4533
  SFileDataBlockInfo* pFBlock = getCurrentBlockInfo(&pReader->status.blockIter);
4534 4535
  SBlockLoadSuppInfo* pSup = &pReader->suppInfo;

H
Haojun Liao 已提交
4536 4537 4538
  if (pReader->pResBlock->info.id.uid != pFBlock->uid) {
    return TSDB_CODE_SUCCESS;
  }
4539 4540

  SDataBlk* pBlock = getCurrentBlock(&pReader->status.blockIter);
H
Hongze Cheng 已提交
4541
  if (tDataBlkHasSma(pBlock)) {
H
Hongze Cheng 已提交
4542
    code = tsdbReadBlockSma(pReader->pFileReader, pBlock, pSup->pColAgg);
4543
    if (code != TSDB_CODE_SUCCESS) {
4544 4545
      tsdbDebug("vgId:%d, failed to load block SMA for uid %" PRIu64 ", code:%s, %s", 0, pFBlock->uid, tstrerror(code),
                pReader->idStr);
4546 4547
      return code;
    }
4548
  } else {
H
Haojun Liao 已提交
4549
    *pBlockSMA = NULL;
4550
    return TSDB_CODE_SUCCESS;
4551
  }
H
Hongze Cheng 已提交
4552

4553
  *allHave = true;
H
Hongze Cheng 已提交
4554

4555 4556
  // always load the first primary timestamp column data
  SColumnDataAgg* pTsAgg = &pSup->tsColAgg;
4557

4558 4559
  pTsAgg->numOfNull = 0;
  pTsAgg->colId = PRIMARYKEY_TIMESTAMP_COL_ID;
4560 4561 4562 4563
  pTsAgg->min = pReader->pResBlock->info.window.skey;
  pTsAgg->max = pReader->pResBlock->info.window.ekey;

  // update the number of NULL data rows
4564
  size_t numOfCols = pSup->numOfCols;
4565

4566
  // ensure capacity
H
Haojun Liao 已提交
4567 4568 4569
  if (pDataBlock->pDataBlock) {
    size_t colsNum = taosArrayGetSize(pDataBlock->pDataBlock);
    taosArrayEnsureCap(pSup->pColAgg, colsNum);
4570 4571
  }

4572 4573 4574
  SSDataBlock* pResBlock = pReader->pResBlock;
  if (pResBlock->pBlockAgg == NULL) {
    size_t num = taosArrayGetSize(pResBlock->pDataBlock);
H
Haojun Liao 已提交
4575
    pResBlock->pBlockAgg = taosMemoryCalloc(num, POINTER_BYTES);
4576
  }
4577

4578
  // do fill all null column value SMA info
4579
  doFillNullColSMA(pSup, pBlock->nRow, numOfCols, pTsAgg);
H
Haojun Liao 已提交
4580
  size_t size = taosArrayGetSize(pSup->pColAgg);
4581

H
Haojun Liao 已提交
4582
  int32_t i = 0, j = 0;
4583
  while (j < numOfCols && i < size) {
4584
    SColumnDataAgg* pAgg = taosArrayGet(pSup->pColAgg, i);
H
Haojun Liao 已提交
4585 4586
    if (pAgg->colId == pSup->colId[j]) {
      pResBlock->pBlockAgg[pSup->slotId[j]] = pAgg;
4587 4588
      i += 1;
      j += 1;
H
Haojun Liao 已提交
4589
    } else if (pAgg->colId < pSup->colId[j]) {
4590
      i += 1;
H
Haojun Liao 已提交
4591
    } else if (pSup->colId[j] < pAgg->colId) {
H
Haojun Liao 已提交
4592
      // ASSERT(pSup->colId[j] == PRIMARYKEY_TIMESTAMP_COL_ID);
4593
      pResBlock->pBlockAgg[pSup->slotId[j]] = &pSup->tsColAgg;
4594 4595 4596 4597
      j += 1;
    }
  }

H
Haojun Liao 已提交
4598
  *pBlockSMA = pResBlock->pBlockAgg;
4599
  pReader->cost.smaDataLoad += 1;
4600

4601
  tsdbDebug("vgId:%d, succeed to load block SMA for uid %" PRIu64 ", %s", 0, pFBlock->uid, pReader->idStr);
H
Hongze Cheng 已提交
4602
  return code;
H
Hongze Cheng 已提交
4603 4604
}

H
Haojun Liao 已提交
4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616
STableBlockScanInfo* getTableBlockScanInfo(SHashObj* pTableMap, uint64_t uid, const char* id) {
  STableBlockScanInfo** p = taosHashGet(pTableMap, &uid, sizeof(uid));
  if (p == NULL || *p == NULL) {
    terrno = TSDB_CODE_INVALID_PARA;
    int32_t size = taosHashGetSize(pTableMap);
    tsdbError("failed to locate the uid:%" PRIu64 " in query table uid list, total tables:%d, %s", uid, size, id);
    return NULL;
  }

  return *p;
}

H
Haojun Liao 已提交
4617
static SSDataBlock* doRetrieveDataBlock(STsdbReader* pReader) {
4618
  SReaderStatus*       pStatus = &pReader->status;
H
Haojun Liao 已提交
4619
  SFileDataBlockInfo*  pBlockInfo = getCurrentBlockInfo(&pStatus->blockIter);
H
Haojun Liao 已提交
4620
  STableBlockScanInfo* pBlockScanInfo = getTableBlockScanInfo(pStatus->pTableMap, pBlockInfo->uid, pReader->idStr);
H
Haojun Liao 已提交
4621
  if (pBlockScanInfo == NULL) {
4622
    return NULL;
4623 4624
  }

4625
  int32_t code = doLoadFileBlockData(pReader, &pStatus->blockIter, &pStatus->fileBlockData, pBlockScanInfo->uid);
4626
  if (code != TSDB_CODE_SUCCESS) {
H
Hongze Cheng 已提交
4627
    tBlockDataDestroy(&pStatus->fileBlockData);
4628 4629
    terrno = code;
    return NULL;
4630
  }
4631

4632
  copyBlockDataToSDataBlock(pReader);
H
Haojun Liao 已提交
4633
  return pReader->pResBlock;
H
Hongze Cheng 已提交
4634 4635
}

H
Haojun Liao 已提交
4636
SSDataBlock* tsdbRetrieveDataBlock(STsdbReader* pReader, SArray* pIdList) {
4637
  STsdbReader* pTReader = pReader;
4638 4639
  if (pReader->type == TIMEWINDOW_RANGE_EXTERNAL) {
    if (pReader->step == EXTERNAL_ROWS_PREV) {
4640
      pTReader = pReader->innerReader[0];
4641
    } else if (pReader->step == EXTERNAL_ROWS_NEXT) {
4642
      pTReader = pReader->innerReader[1];
4643 4644 4645
    }
  }

4646 4647 4648 4649 4650 4651 4652
  SReaderStatus* pStatus = &pTReader->status;
  if (pStatus->composedDataBlock) {
    return pTReader->pResBlock;
  }

  SSDataBlock* ret = doRetrieveDataBlock(pTReader);

4653
  qTrace("tsdb/read-retrieve: %p, unlock read mutex", pReader);
4654
  tsdbReleaseReader(pReader);
4655 4656

  return ret;
4657 4658
}

H
Haojun Liao 已提交
4659
int32_t tsdbReaderReset(STsdbReader* pReader, SQueryTableDataCond* pCond) {
4660
  qTrace("tsdb/reader-reset: %p, take read mutex", pReader);
4661
  tsdbAcquireReader(pReader);
L
Liu Jicong 已提交
4662 4663 4664 4665 4666

  if (pReader->suspended) {
    tsdbReaderResume(pReader);
  }

H
Haojun Liao 已提交
4667
  if (isEmptyQueryTimeWindow(&pReader->window) || pReader->pReadSnap == NULL) {
L
Liu Jicong 已提交
4668
    tsdbDebug("tsdb reader reset return %p", pReader->pReadSnap);
4669

4670
    tsdbReleaseReader(pReader);
4671

4672 4673
    return TSDB_CODE_SUCCESS;
  }
H
Hongze Cheng 已提交
4674

H
Haojun Liao 已提交
4675 4676 4677
  SReaderStatus* pStatus = &pReader->status;

  SDataBlockIter* pBlockIter = &pStatus->blockIter;
4678

L
Liu Jicong 已提交
4679
  pReader->order = pCond->order;
4680
  pReader->type = TIMEWINDOW_RANGE_CONTAINED;
H
Haojun Liao 已提交
4681 4682
  pStatus->loadFromFile = true;
  pStatus->pTableIter = NULL;
H
Haojun Liao 已提交
4683
  pReader->window = updateQueryTimeWindow(pReader->pTsdb, &pCond->twindows);
H
Hongze Cheng 已提交
4684

4685
  // allocate buffer in order to load data blocks from file
4686
  memset(&pReader->suppInfo.tsColAgg, 0, sizeof(SColumnDataAgg));
4687

4688
  pReader->suppInfo.tsColAgg.colId = PRIMARYKEY_TIMESTAMP_COL_ID;
4689
  tsdbDataFReaderClose(&pReader->pFileReader);
4690

H
Haojun Liao 已提交
4691
  int32_t numOfTables = taosHashGetSize(pStatus->pTableMap);
L
Liu Jicong 已提交
4692

H
Haojun Liao 已提交
4693
  initFilesetIterator(&pStatus->fileIter, pReader->pReadSnap->fs.aDFileSet, pReader);
4694
  resetDataBlockIterator(pBlockIter, pReader->order);
H
Haojun Liao 已提交
4695
  resetTableListIndex(&pReader->status);
H
Haojun Liao 已提交
4696

H
Hongze Cheng 已提交
4697
  int64_t ts = ASCENDING_TRAVERSE(pReader->order) ? pReader->window.skey - 1 : pReader->window.ekey + 1;
H
Haojun Liao 已提交
4698
  resetAllDataBlockScanInfo(pStatus->pTableMap, ts);
4699

4700
  int32_t code = 0;
4701

4702
  // no data in files, let's try buffer in memory
H
Haojun Liao 已提交
4703 4704
  if (pStatus->fileIter.numOfFiles == 0) {
    pStatus->loadFromFile = false;
4705
    resetTableListIndex(pStatus);
4706 4707 4708
  } else {
    code = initForFirstBlockInFile(pReader, pBlockIter);
    if (code != TSDB_CODE_SUCCESS) {
4709 4710
      tsdbError("%p reset reader failed, numOfTables:%d, query range:%" PRId64 " - %" PRId64 " in query %s", pReader,
                numOfTables, pReader->window.skey, pReader->window.ekey, pReader->idStr);
4711

4712
      tsdbReleaseReader(pReader);
4713

4714 4715 4716
      return code;
    }
  }
H
Hongze Cheng 已提交
4717

H
Hongze Cheng 已提交
4718 4719 4720 4721
  tsdbDebug("%p reset reader, suid:%" PRIu64 ", numOfTables:%d, skey:%" PRId64 ", query range:%" PRId64 " - %" PRId64
            " in query %s",
            pReader, pReader->suid, numOfTables, pCond->twindows.skey, pReader->window.skey, pReader->window.ekey,
            pReader->idStr);
4722

4723
  tsdbReleaseReader(pReader);
4724

4725
  return code;
H
Hongze Cheng 已提交
4726
}
H
Hongze Cheng 已提交
4727

4728 4729 4730 4731 4732 4733
static int32_t getBucketIndex(int32_t startRow, int32_t bucketRange, int32_t numOfRows, int32_t numOfBucket) {
  int32_t bucketIndex = (numOfRows - startRow) / bucketRange;
  if (bucketIndex == numOfBucket) {
    bucketIndex -= 1;
  }
  return bucketIndex;
4734
}
H
Hongze Cheng 已提交
4735

4736 4737 4738 4739
int32_t tsdbGetFileBlocksDistInfo(STsdbReader* pReader, STableBlockDistInfo* pTableBlockInfo) {
  int32_t code = TSDB_CODE_SUCCESS;
  pTableBlockInfo->totalSize = 0;
  pTableBlockInfo->totalRows = 0;
4740
  pTableBlockInfo->numOfVgroups = 1;
H
Hongze Cheng 已提交
4741

4742
  const int32_t numOfBucket = 20.0;
dengyihao's avatar
dengyihao 已提交
4743

4744
  // find the start data block in file
dengyihao's avatar
dengyihao 已提交
4745 4746 4747 4748
  tsdbAcquireReader(pReader);
  if (pReader->suspended) {
    tsdbReaderResume(pReader);
  }
4749
  SReaderStatus* pStatus = &pReader->status;
H
Hongze Cheng 已提交
4750

4751 4752 4753
  STsdbCfg* pc = &pReader->pTsdb->pVnode->config.tsdbCfg;
  pTableBlockInfo->defMinRows = pc->minRows;
  pTableBlockInfo->defMaxRows = pc->maxRows;
H
Hongze Cheng 已提交
4754

4755
  int32_t bucketRange = ceil((pc->maxRows - pc->minRows) / numOfBucket);
H
Hongze Cheng 已提交
4756

4757
  pTableBlockInfo->numOfFiles += 1;
H
Hongze Cheng 已提交
4758

4759 4760
  int32_t numOfTables = (int32_t)taosHashGetSize(pStatus->pTableMap);
  int     defaultRows = 4096;
H
Hongze Cheng 已提交
4761

4762 4763
  SDataBlockIter* pBlockIter = &pStatus->blockIter;
  pTableBlockInfo->numOfFiles += pStatus->fileIter.numOfFiles;
H
Haojun Liao 已提交
4764

4765 4766
  if (pBlockIter->numOfBlocks > 0) {
    pTableBlockInfo->numOfBlocks += pBlockIter->numOfBlocks;
H
Haojun Liao 已提交
4767
  }
H
Hongze Cheng 已提交
4768

4769
  pTableBlockInfo->numOfTables = numOfTables;
4770
  bool hasNext = (pBlockIter->numOfBlocks > 0);
H
Hongze Cheng 已提交
4771

4772 4773
  while (true) {
    if (hasNext) {
H
Hongze Cheng 已提交
4774
      SDataBlk* pBlock = getCurrentBlock(pBlockIter);
H
Hongze Cheng 已提交
4775

4776 4777
      int32_t numOfRows = pBlock->nRow;
      pTableBlockInfo->totalRows += numOfRows;
H
Hongze Cheng 已提交
4778

4779 4780 4781
      if (numOfRows > pTableBlockInfo->maxRows) {
        pTableBlockInfo->maxRows = numOfRows;
      }
H
refact  
Hongze Cheng 已提交
4782

4783 4784 4785
      if (numOfRows < pTableBlockInfo->minRows) {
        pTableBlockInfo->minRows = numOfRows;
      }
H
refact  
Hongze Cheng 已提交
4786

4787 4788 4789
      if (numOfRows < defaultRows) {
        pTableBlockInfo->numOfSmallBlocks += 1;
      }
H
refact  
Hongze Cheng 已提交
4790

4791
      pTableBlockInfo->totalSize += pBlock->aSubBlock[0].szBlock;
4792

4793
      int32_t bucketIndex = getBucketIndex(pTableBlockInfo->defMinRows, bucketRange, numOfRows, numOfBucket);
4794
      pTableBlockInfo->blockRowsHisto[bucketIndex]++;
4795

H
Haojun Liao 已提交
4796
      hasNext = blockIteratorNext(&pStatus->blockIter, pReader->idStr);
4797 4798
    } else {
      code = initForFirstBlockInFile(pReader, pBlockIter);
H
Haojun Liao 已提交
4799
      if ((code != TSDB_CODE_SUCCESS) || (pStatus->loadFromFile == false)) {
4800 4801
        break;
      }
H
refact  
Hongze Cheng 已提交
4802

4803 4804
      pTableBlockInfo->numOfBlocks += pBlockIter->numOfBlocks;
      hasNext = (pBlockIter->numOfBlocks > 0);
4805
    }
H
refact  
Hongze Cheng 已提交
4806

H
Hongze Cheng 已提交
4807 4808
    //    tsdbDebug("%p %d blocks found in file for %d table(s), fid:%d, %s", pReader, numOfBlocks, numOfTables,
    //              pReader->pFileGroup->fid, pReader->idStr);
4809
  }
dengyihao's avatar
dengyihao 已提交
4810
  tsdbReleaseReader(pReader);
H
refact  
Hongze Cheng 已提交
4811 4812
  return code;
}
H
Hongze Cheng 已提交
4813

H
refact  
Hongze Cheng 已提交
4814
int64_t tsdbGetNumOfRowsInMemTable(STsdbReader* pReader) {
4815
  int64_t rows = 0;
H
Hongze Cheng 已提交
4816

4817
  SReaderStatus* pStatus = &pReader->status;
4818
  tsdbAcquireReader(pReader);
4819 4820 4821 4822
  if (pReader->suspended) {
    tsdbReaderResume(pReader);
  }

4823
  pStatus->pTableIter = taosHashIterate(pStatus->pTableMap, NULL);
H
Hongze Cheng 已提交
4824

4825
  while (pStatus->pTableIter != NULL) {
4826
    STableBlockScanInfo* pBlockScanInfo = *(STableBlockScanInfo**)pStatus->pTableIter;
4827 4828

    STbData* d = NULL;
4829
    if (pReader->pReadSnap->pMem != NULL) {
H
Hongze Cheng 已提交
4830
      d = tsdbGetTbDataFromMemTable(pReader->pReadSnap->pMem, pReader->suid, pBlockScanInfo->uid);
4831 4832 4833 4834 4835 4836
      if (d != NULL) {
        rows += tsdbGetNRowsInTbData(d);
      }
    }

    STbData* di = NULL;
4837
    if (pReader->pReadSnap->pIMem != NULL) {
H
Hongze Cheng 已提交
4838
      di = tsdbGetTbDataFromMemTable(pReader->pReadSnap->pIMem, pReader->suid, pBlockScanInfo->uid);
4839 4840 4841 4842 4843 4844 4845 4846
      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 已提交
4847

4848
  tsdbReleaseReader(pReader);
4849

H
refact  
Hongze Cheng 已提交
4850
  return rows;
H
Hongze Cheng 已提交
4851
}
D
dapan1121 已提交
4852

L
Liu Jicong 已提交
4853
int32_t tsdbGetTableSchema(SVnode* pVnode, int64_t uid, STSchema** pSchema, int64_t* suid) {
D
dapan1121 已提交
4854 4855 4856 4857
  int32_t sversion = 1;

  SMetaReader mr = {0};
  metaReaderInit(&mr, pVnode->pMeta, 0);
H
Haojun Liao 已提交
4858
  int32_t code = metaGetTableEntryByUidCache(&mr, uid);
D
dapan1121 已提交
4859 4860 4861 4862 4863 4864 4865
  if (code != TSDB_CODE_SUCCESS) {
    terrno = TSDB_CODE_TDB_INVALID_TABLE_ID;
    metaReaderClear(&mr);
    return terrno;
  }

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

D
dapan1121 已提交
4867
  if (mr.me.type == TSDB_CHILD_TABLE) {
D
dapan1121 已提交
4868
    tDecoderClear(&mr.coder);
D
dapan1121 已提交
4869
    *suid = mr.me.ctbEntry.suid;
H
Haojun Liao 已提交
4870
    code = metaGetTableEntryByUidCache(&mr, *suid);
D
dapan1121 已提交
4871 4872 4873 4874 4875 4876
    if (code != TSDB_CODE_SUCCESS) {
      terrno = TSDB_CODE_TDB_INVALID_TABLE_ID;
      metaReaderClear(&mr);
      return terrno;
    }
    sversion = mr.me.stbEntry.schemaRow.version;
H
Haojun Liao 已提交
4877
  } else if (mr.me.type == TSDB_NORMAL_TABLE) {
D
dapan1121 已提交
4878
    sversion = mr.me.ntbEntry.schemaRow.version;
H
Haojun Liao 已提交
4879 4880 4881 4882
  } else {
    terrno = TSDB_CODE_INVALID_PARA;
    metaReaderClear(&mr);
    return terrno;
D
dapan1121 已提交
4883 4884 4885
  }

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

D
dapan1121 已提交
4888 4889
  return TSDB_CODE_SUCCESS;
}
H
Hongze Cheng 已提交
4890

H
Hongze Cheng 已提交
4891
int32_t tsdbTakeReadSnap(STsdbReader* pReader, _query_reseek_func_t reseek, STsdbReadSnap** ppSnap) {
H
Hongze Cheng 已提交
4892 4893 4894
  int32_t        code = 0;
  STsdb*         pTsdb = pReader->pTsdb;
  SVersionRange* pRange = &pReader->verRange;
H
Hongze Cheng 已提交
4895 4896

  // alloc
H
Hongze Cheng 已提交
4897 4898
  STsdbReadSnap* pSnap = (STsdbReadSnap*)taosMemoryCalloc(1, sizeof(*pSnap));
  if (pSnap == NULL) {
H
Hongze Cheng 已提交
4899 4900 4901 4902 4903
    code = TSDB_CODE_OUT_OF_MEMORY;
    goto _exit;
  }

  // lock
H
Hongze Cheng 已提交
4904
  taosThreadRwlockRdlock(&pTsdb->rwLock);
H
Hongze Cheng 已提交
4905 4906

  // take snapshot
H
Hongze Cheng 已提交
4907
  if (pTsdb->mem && (pRange->minVer <= pTsdb->mem->maxVer && pRange->maxVer >= pTsdb->mem->minVer)) {
H
Hongze Cheng 已提交
4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918
    pSnap->pMem = pTsdb->mem;
    pSnap->pNode = taosMemoryMalloc(sizeof(*pSnap->pNode));
    if (pSnap->pNode == NULL) {
      taosThreadRwlockUnlock(&pTsdb->rwLock);
      code = TSDB_CODE_OUT_OF_MEMORY;
      goto _exit;
    }
    pSnap->pNode->pQHandle = pReader;
    pSnap->pNode->reseek = reseek;

    tsdbRefMemTable(pTsdb->mem, pSnap->pNode);
H
Hongze Cheng 已提交
4919 4920
  }

H
Hongze Cheng 已提交
4921
  if (pTsdb->imem && (pRange->minVer <= pTsdb->imem->maxVer && pRange->maxVer >= pTsdb->imem->minVer)) {
H
Hongze Cheng 已提交
4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932
    pSnap->pIMem = pTsdb->imem;
    pSnap->pINode = taosMemoryMalloc(sizeof(*pSnap->pINode));
    if (pSnap->pINode == NULL) {
      taosThreadRwlockUnlock(&pTsdb->rwLock);
      code = TSDB_CODE_OUT_OF_MEMORY;
      goto _exit;
    }
    pSnap->pINode->pQHandle = pReader;
    pSnap->pINode->reseek = reseek;

    tsdbRefMemTable(pTsdb->imem, pSnap->pINode);
H
Hongze Cheng 已提交
4933 4934
  }

H
Hongze Cheng 已提交
4935
  // fs
H
Hongze Cheng 已提交
4936
  code = tsdbFSRef(pTsdb, &pSnap->fs);
H
Hongze Cheng 已提交
4937 4938 4939 4940
  if (code) {
    taosThreadRwlockUnlock(&pTsdb->rwLock);
    goto _exit;
  }
H
Hongze Cheng 已提交
4941 4942

  // unlock
H
Hongze Cheng 已提交
4943
  taosThreadRwlockUnlock(&pTsdb->rwLock);
H
Hongze Cheng 已提交
4944

4945
  tsdbTrace("vgId:%d, take read snapshot", TD_VID(pTsdb->pVnode));
H
Hongze Cheng 已提交
4946

H
Hongze Cheng 已提交
4947
_exit:
H
Hongze Cheng 已提交
4948 4949 4950 4951 4952 4953 4954 4955 4956 4957
  if (code) {
    *ppSnap = NULL;
    if (pSnap) {
      if (pSnap->pNode) taosMemoryFree(pSnap->pNode);
      if (pSnap->pINode) taosMemoryFree(pSnap->pINode);
      taosMemoryFree(pSnap);
    }
  } else {
    *ppSnap = pSnap;
  }
H
Hongze Cheng 已提交
4958 4959 4960
  return code;
}

4961
void tsdbUntakeReadSnap(STsdbReader* pReader, STsdbReadSnap* pSnap, bool proactive) {
H
Hongze Cheng 已提交
4962 4963
  STsdb* pTsdb = pReader->pTsdb;

H
Hongze Cheng 已提交
4964 4965
  if (pSnap) {
    if (pSnap->pMem) {
4966
      tsdbUnrefMemTable(pSnap->pMem, pSnap->pNode, proactive);
H
Hongze Cheng 已提交
4967 4968 4969
    }

    if (pSnap->pIMem) {
4970
      tsdbUnrefMemTable(pSnap->pIMem, pSnap->pINode, proactive);
H
Hongze Cheng 已提交
4971 4972
    }

H
Hongze Cheng 已提交
4973
    tsdbFSUnref(pTsdb, &pSnap->fs);
H
Hongze Cheng 已提交
4974 4975
    if (pSnap->pNode) taosMemoryFree(pSnap->pNode);
    if (pSnap->pINode) taosMemoryFree(pSnap->pINode);
H
Hongze Cheng 已提交
4976
    taosMemoryFree(pSnap);
H
Hongze Cheng 已提交
4977
  }
4978
  tsdbTrace("vgId:%d, untake read snapshot", TD_VID(pTsdb->pVnode));
H
Hongze Cheng 已提交
4979
}