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

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

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;

D
dapan1121 已提交
27 28 29 30 31
typedef enum {
  READ_MODE_COUNT_ONLY = 0x1,
  READ_MODE_ALL,
} EReadMode;

32
typedef struct {
dengyihao's avatar
dengyihao 已提交
33
  STbDataIter* iter;
34 35 36 37
  int32_t      index;
  bool         hasVal;
} SIterInfo;

38 39
typedef struct {
  int32_t numOfBlocks;
40
  int32_t numOfLastFiles;
41 42
} SBlockNumber;

43
typedef struct SBlockIndex {
44 45
  int32_t     ordinalIndex;
  int64_t     inFileOffset;
H
Haojun Liao 已提交
46
  STimeWindow window;  // todo replace it with overlap flag.
47 48
} SBlockIndex;

H
Haojun Liao 已提交
49
typedef struct STableBlockScanInfo {
dengyihao's avatar
dengyihao 已提交
50 51
  uint64_t  uid;
  TSKEY     lastKey;
52
  TSKEY     lastKeyInStt;       // last accessed key in stt
H
Hongze Cheng 已提交
53
  SMapData  mapData;            // block info (compressed)
54
  SArray*   pBlockList;         // block data index list, SArray<SBlockIndex>
H
Hongze Cheng 已提交
55 56 57 58 59 60
  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 已提交
61 62 63
} STableBlockScanInfo;

typedef struct SBlockOrderWrapper {
dengyihao's avatar
dengyihao 已提交
64
  int64_t uid;
65
  int64_t offset;
H
Haojun Liao 已提交
66
} SBlockOrderWrapper;
H
Hongze Cheng 已提交
67 68

typedef struct SBlockOrderSupporter {
69 70 71 72
  SBlockOrderWrapper** pDataBlockInfo;
  int32_t*             indexPerTable;
  int32_t*             numOfBlocksPerTable;
  int32_t              numOfTables;
H
Hongze Cheng 已提交
73 74 75
} SBlockOrderSupporter;

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

typedef struct SBlockLoadSuppInfo {
94 95 96 97 98 99 100
  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 已提交
101 102
} SBlockLoadSuppInfo;

103
typedef struct SLastBlockReader {
H
Hongze Cheng 已提交
104 105 106 107 108
  STimeWindow        window;
  SVersionRange      verRange;
  int32_t            order;
  uint64_t           uid;
  SMergeTree         mergeTree;
109
  SSttBlockLoadInfo* pInfo;
110 111
} SLastBlockReader;

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

typedef struct SFileDataBlockInfo {
121
  // index position in STableBlockScanInfo in order to check whether neighbor block overlaps with it
dengyihao's avatar
dengyihao 已提交
122
  uint64_t uid;
123
  int32_t  tbBlockIdx;
H
Haojun Liao 已提交
124 125 126
} SFileDataBlockInfo;

typedef struct SDataBlockIter {
127
  int32_t   numOfBlocks;
128
  int32_t   index;
H
Hongze Cheng 已提交
129
  SArray*   blockList;  // SArray<SFileDataBlockInfo>
130
  int32_t   order;
H
Hongze Cheng 已提交
131
  SDataBlk  block;  // current SDataBlk data
132
  SHashObj* pTableMap;
H
Haojun Liao 已提交
133 134 135
} SDataBlockIter;

typedef struct SFileBlockDumpInfo {
dengyihao's avatar
dengyihao 已提交
136 137 138 139
  int32_t totalRows;
  int32_t rowIndex;
  int64_t lastKey;
  bool    allDumped;
H
Haojun Liao 已提交
140 141
} SFileBlockDumpInfo;

142
typedef struct STableUidList {
143 144
  uint64_t* tableUidList;  // access table uid list in uid ascending order list
  int32_t   currentIndex;  // index in table uid list
145
} STableUidList;
146

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

160
typedef struct SBlockInfoBuf {
H
Hongze Cheng 已提交
161 162 163
  int32_t currentIndex;
  SArray* pData;
  int32_t numPerBucket;
D
dapan1121 已提交
164
  int32_t numOfTables;
165 166
} SBlockInfoBuf;

H
Hongze Cheng 已提交
167
struct STsdbReader {
H
Haojun Liao 已提交
168
  STsdb*             pTsdb;
169 170 171
  SVersionRange      verRange;
  TdThreadMutex      readerMutex;
  bool               suspended;
H
Haojun Liao 已提交
172 173
  uint64_t           suid;
  int16_t            order;
H
Haojun Liao 已提交
174
  bool               freeBlock;
D
dapan1121 已提交
175 176
  EReadMode          readMode;
  uint64_t           rowsNum;
H
Haojun Liao 已提交
177 178 179 180
  STimeWindow        window;  // the primary query time window that applies to all queries
  SSDataBlock*       pResBlock;
  int32_t            capacity;
  SReaderStatus      status;
181 182
  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 已提交
183
  SBlockLoadSuppInfo suppInfo;
H
Hongze Cheng 已提交
184
  STsdbReadSnap*     pReadSnap;
185
  SIOCostSummary     cost;
186 187 188 189 190
  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;
191 192 193
  SBlockInfoBuf      blockInfoBuf;
  int32_t            step;
  STsdbReader*       innerReader[2];
H
Hongze Cheng 已提交
194
};
H
Hongze Cheng 已提交
195

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

H
Hongze Cheng 已提交
214
static int32_t doMergeMemTableMultiRows(TSDBROW* pRow, uint64_t uid, SIterInfo* pIter, SArray* pDelList,
215
                                        TSDBROW* pTSRow, STsdbReader* pReader, bool* freeTSRow);
H
Hongze Cheng 已提交
216
static int32_t doMergeMemIMemRows(TSDBROW* pRow, TSDBROW* piRow, STableBlockScanInfo* pBlockScanInfo,
H
Hongze Cheng 已提交
217
                                  STsdbReader* pReader, SRow** pTSRow);
218 219
static int32_t mergeRowsInFileBlocks(SBlockData* pBlockData, STableBlockScanInfo* pBlockScanInfo, int64_t key,
                                     STsdbReader* pReader);
220

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

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

236 237
static FORCE_INLINE STSchema* getLatestTableSchema(STsdbReader* pReader, uint64_t uid);

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

240 241
static int32_t setColumnIdSlotList(SBlockLoadSuppInfo* pSupInfo, SColumnInfo* pCols, const int32_t* pSlotIdList,
                                   int32_t numOfCols) {
242
  pSupInfo->smaValid = true;
243
  pSupInfo->numOfCols = numOfCols;
244
  pSupInfo->colId = taosMemoryMalloc(numOfCols * (sizeof(int16_t) * 2 + POINTER_BYTES));
H
Haojun Liao 已提交
245 246
  if (pSupInfo->colId == NULL) {
    taosMemoryFree(pSupInfo->colId);
H
Haojun Liao 已提交
247 248
    return TSDB_CODE_OUT_OF_MEMORY;
  }
H
Hongze Cheng 已提交
249

H
Haojun Liao 已提交
250
  pSupInfo->slotId = (int16_t*)((char*)pSupInfo->colId + (sizeof(int16_t) * numOfCols));
251
  pSupInfo->buildBuf = (char**)((char*)pSupInfo->slotId + (sizeof(int16_t) * numOfCols));
H
Haojun Liao 已提交
252
  for (int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
253 254
    pSupInfo->colId[i] = pCols[i].colId;
    pSupInfo->slotId[i] = pSlotIdList[i];
255

H
Haojun Liao 已提交
256 257
    if (IS_VAR_DATA_TYPE(pCols[i].type)) {
      pSupInfo->buildBuf[i] = taosMemoryMalloc(pCols[i].bytes);
H
Haojun Liao 已提交
258 259
    } else {
      pSupInfo->buildBuf[i] = NULL;
260
    }
H
Haojun Liao 已提交
261
  }
H
Hongze Cheng 已提交
262

H
Haojun Liao 已提交
263 264
  return TSDB_CODE_SUCCESS;
}
H
Hongze Cheng 已提交
265

H
Haojun Liao 已提交
266
static int32_t updateBlockSMAInfo(STSchema* pSchema, SBlockLoadSuppInfo* pSupInfo) {
267 268
  int32_t i = 0, j = 0;

H
Hongze Cheng 已提交
269
  while (i < pSchema->numOfCols && j < pSupInfo->numOfCols) {
270
    STColumn* pTCol = &pSchema->columns[i];
H
Haojun Liao 已提交
271
    if (pTCol->colId == pSupInfo->colId[j]) {
272 273
      if (!IS_BSMA_ON(pTCol)) {
        pSupInfo->smaValid = false;
H
Haojun Liao 已提交
274
        return TSDB_CODE_SUCCESS;
275 276 277 278
      }

      i += 1;
      j += 1;
H
Haojun Liao 已提交
279
    } else if (pTCol->colId < pSupInfo->colId[j]) {
280 281 282
      // do nothing
      i += 1;
    } else {
H
Haojun Liao 已提交
283
      return TSDB_CODE_INVALID_PARA;
284 285
    }
  }
H
Haojun Liao 已提交
286 287

  return TSDB_CODE_SUCCESS;
288 289
}

290
static int32_t initBlockScanInfoBuf(SBlockInfoBuf* pBuf, int32_t numOfTables) {
H
Hongze Cheng 已提交
291
  int32_t num = numOfTables / pBuf->numPerBucket;
292 293 294 295 296
  int32_t remainder = numOfTables % pBuf->numPerBucket;
  if (pBuf->pData == NULL) {
    pBuf->pData = taosArrayInit(num + 1, POINTER_BYTES);
  }

H
Hongze Cheng 已提交
297
  for (int32_t i = 0; i < num; ++i) {
298 299 300 301
    char* p = taosMemoryCalloc(pBuf->numPerBucket, sizeof(STableBlockScanInfo));
    if (p == NULL) {
      return TSDB_CODE_OUT_OF_MEMORY;
    }
302

303 304 305 306 307 308 309
    taosArrayPush(pBuf->pData, &p);
  }

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

D
dapan1121 已提交
314 315 316 317 318 319 320 321 322 323 324
  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) {
325
    STableBlockScanInfo** p = (STableBlockScanInfo**)taosArrayPop(pBuf->pData);
D
dapan1121 已提交
326
    taosMemoryFree(*p);
D
dapan1121 已提交
327 328
    pBuf->numOfTables /= pBuf->numPerBucket;
  }
329

D
dapan1121 已提交
330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
  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 已提交
355 356
  return TSDB_CODE_SUCCESS;
}
H
Hongze Cheng 已提交
357

358 359
static void clearBlockScanInfoBuf(SBlockInfoBuf* pBuf) {
  size_t num = taosArrayGetSize(pBuf->pData);
H
Hongze Cheng 已提交
360
  for (int32_t i = 0; i < num; ++i) {
361 362 363 364 365 366 367 368 369
    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 已提交
370
  char**  pBucket = taosArrayGet(pBuf->pData, bucketIndex);
371 372 373
  return (*pBucket) + (index % pBuf->numPerBucket) * sizeof(STableBlockScanInfo);
}

H
Haojun Liao 已提交
374 375 376 377 378 379 380 381 382 383
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;
  }
}

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

H
Haojun Liao 已提交
395
  int64_t st = taosGetTimestampUs();
H
Haojun Liao 已提交
396
  initBlockScanInfoBuf(pBuf, numOfTables);
H
Haojun Liao 已提交
397

H
Haojun Liao 已提交
398 399
  pUidList->tableUidList = taosMemoryMalloc(numOfTables * sizeof(uint64_t));
  if (pUidList->tableUidList == NULL) {
H
Haojun Liao 已提交
400
    taosHashCleanup(pTableMap);
H
Haojun Liao 已提交
401 402
    return NULL;
  }
H
Haojun Liao 已提交
403

H
Haojun Liao 已提交
404
  pUidList->currentIndex = 0;
H
Haojun Liao 已提交
405

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

409
    pScanInfo->uid = idList[j].uid;
H
Haojun Liao 已提交
410
    pUidList->tableUidList[j] = idList[j].uid;
H
Haojun Liao 已提交
411

412
    if (ASCENDING_TRAVERSE(pTsdbReader->order)) {
H
Haojun Liao 已提交
413
      int64_t skey = pTsdbReader->window.skey;
414
      pScanInfo->lastKey = (skey > INT64_MIN) ? (skey - 1) : skey;
H
Haojun Liao 已提交
415
      pScanInfo->lastKeyInStt = skey;
wmmhello's avatar
wmmhello 已提交
416
    } else {
H
Haojun Liao 已提交
417
      int64_t ekey = pTsdbReader->window.ekey;
418
      pScanInfo->lastKey = (ekey < INT64_MAX) ? (ekey + 1) : ekey;
H
Haojun Liao 已提交
419
      pScanInfo->lastKeyInStt = ekey;
H
Haojun Liao 已提交
420
    }
wmmhello's avatar
wmmhello 已提交
421

422
    taosHashPut(pTableMap, &pScanInfo->uid, sizeof(uint64_t), &pScanInfo, POINTER_BYTES);
H
Hongze Cheng 已提交
423 424
    tsdbTrace("%p check table uid:%" PRId64 " from lastKey:%" PRId64 " %s", pTsdbReader, pScanInfo->uid,
              pScanInfo->lastKey, pTsdbReader->idStr);
H
Haojun Liao 已提交
425 426
  }

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

H
Haojun Liao 已提交
429 430 431 432
  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);
433

434
  return pTableMap;
H
Hongze Cheng 已提交
435
}
H
Hongze Cheng 已提交
436

437
static void resetAllDataBlockScanInfo(SHashObj* pTableMap, int64_t ts, int32_t step) {
438
  STableBlockScanInfo** p = NULL;
dengyihao's avatar
dengyihao 已提交
439
  while ((p = taosHashIterate(pTableMap, p)) != NULL) {
H
Hongze Cheng 已提交
440
    STableBlockScanInfo* pInfo = *(STableBlockScanInfo**)p;
441 442

    pInfo->iterInit = false;
H
Haojun Liao 已提交
443
    pInfo->iter.hasVal = false;
444
    pInfo->iiter.hasVal = false;
H
Haojun Liao 已提交
445

446 447
    if (pInfo->iter.iter != NULL) {
      pInfo->iter.iter = tsdbTbDataIterDestroy(pInfo->iter.iter);
448 449
    }

H
Haojun Liao 已提交
450 451
    if (pInfo->iiter.iter != NULL) {
      pInfo->iiter.iter = tsdbTbDataIterDestroy(pInfo->iiter.iter);
452 453
    }

454 455
    pInfo->delSkyline = taosArrayDestroy(pInfo->delSkyline);
    pInfo->lastKey = ts;
456
    pInfo->lastKeyInStt = ts + step;
457 458 459
  }
}

460 461
static void clearBlockScanInfo(STableBlockScanInfo* p) {
  p->iterInit = false;
H
Haojun Liao 已提交
462 463

  p->iter.hasVal = false;
464
  p->iiter.hasVal = false;
465

466 467 468
  if (p->iter.iter != NULL) {
    p->iter.iter = tsdbTbDataIterDestroy(p->iter.iter);
  }
469

470 471 472
  if (p->iiter.iter != NULL) {
    p->iiter.iter = tsdbTbDataIterDestroy(p->iiter.iter);
  }
473

474 475 476 477
  p->delSkyline = taosArrayDestroy(p->delSkyline);
  p->pBlockList = taosArrayDestroy(p->pBlockList);
  tMapDataClear(&p->mapData);
}
478

H
Haojun Liao 已提交
479
static void destroyAllBlockScanInfo(SHashObj* pTableMap) {
480
  void* p = NULL;
481
  while ((p = taosHashIterate(pTableMap, p)) != NULL) {
482
    clearBlockScanInfo(*(STableBlockScanInfo**)p);
483 484 485 486 487
  }

  taosHashCleanup(pTableMap);
}

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

490 491 492
// 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 已提交
493
  STsdbKeepCfg* pCfg = &pTsdb->keepCfg;
H
Hongze Cheng 已提交
494

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

dengyihao's avatar
dengyihao 已提交
498
  STimeWindow win = *pWindow;
499 500 501 502 503 504
  if (win.skey < earilyTs) {
    win.skey = earilyTs;
  }

  return win;
}
H
Hongze Cheng 已提交
505

H
Haojun Liao 已提交
506
// init file iterator
507
static int32_t initFilesetIterator(SFilesetIter* pIter, SArray* aDFileSet, STsdbReader* pReader) {
H
Hongze Cheng 已提交
508
  size_t numOfFileset = taosArrayGetSize(aDFileSet);
509

510 511
  pIter->index = ASCENDING_TRAVERSE(pReader->order) ? -1 : numOfFileset;
  pIter->order = pReader->order;
H
Hongze Cheng 已提交
512
  pIter->pFileList = aDFileSet;
513
  pIter->numOfFiles = numOfFileset;
H
Haojun Liao 已提交
514

515 516 517 518
  if (pIter->pLastBlockReader == NULL) {
    pIter->pLastBlockReader = taosMemoryCalloc(1, sizeof(struct SLastBlockReader));
    if (pIter->pLastBlockReader == NULL) {
      int32_t code = TSDB_CODE_OUT_OF_MEMORY;
519
      tsdbError("failed to prepare the last block iterator, since:%s %s", tstrerror(code), pReader->idStr);
520 521
      return code;
    }
522 523
  }

524 525 526 527 528 529 530 531
  SLastBlockReader* pLReader = pIter->pLastBlockReader;
  pLReader->order = pReader->order;
  pLReader->window = pReader->window;
  pLReader->verRange = pReader->verRange;

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

532
  if (pLReader->pInfo == NULL) {
533
    // here we ignore the first column, which is always be the primary timestamp column
534 535 536
    SBlockLoadSuppInfo* pInfo = &pReader->suppInfo;

    int32_t numOfStt = pReader->pTsdb->pVnode->config.sttTrigger;
X
Xiaoyu Wang 已提交
537
    pLReader->pInfo = tCreateLastBlockLoadInfo(pReader->pSchema, &pInfo->colId[1], pInfo->numOfCols - 1, numOfStt);
H
Haojun Liao 已提交
538 539 540 541
    if (pLReader->pInfo == NULL) {
      tsdbDebug("init fileset iterator failed, code:%s %s", tstrerror(terrno), pReader->idStr);
      return terrno;
    }
542 543
  }

544
  tsdbDebug("init fileset iterator, total files:%d %s", pIter->numOfFiles, pReader->idStr);
H
Haojun Liao 已提交
545 546 547
  return TSDB_CODE_SUCCESS;
}

dengyihao's avatar
dengyihao 已提交
548
static int32_t filesetIteratorNext(SFilesetIter* pIter, STsdbReader* pReader, bool* hasNext) {
549 550
  bool    asc = ASCENDING_TRAVERSE(pIter->order);
  int32_t step = asc ? 1 : -1;
551
  pIter->index += step;
D
dapan1121 已提交
552
  int32_t code = 0;
553 554

  if ((asc && pIter->index >= pIter->numOfFiles) || ((!asc) && pIter->index < 0)) {
D
dapan1121 已提交
555 556
    *hasNext = false;
    return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
557 558
  }

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

562 563
  pIter->pLastBlockReader->uid = 0;
  tMergeTreeClose(&pIter->pLastBlockReader->mergeTree);
564
  resetLastBlockLoadInfo(pIter->pLastBlockReader->pInfo);
565

H
Haojun Liao 已提交
566 567
  // check file the time range of coverage
  STimeWindow win = {0};
H
Hongze Cheng 已提交
568

569
  while (1) {
H
Haojun Liao 已提交
570 571 572
    if (pReader->pFileReader != NULL) {
      tsdbDataFReaderClose(&pReader->pFileReader);
    }
573

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

D
dapan1121 已提交
576
    code = tsdbDataFReaderOpen(&pReader->pFileReader, pReader->pTsdb, pReader->status.pCurrentFileset);
577 578 579
    if (code != TSDB_CODE_SUCCESS) {
      goto _err;
    }
H
Haojun Liao 已提交
580

581 582
    pReader->cost.headFileLoad += 1;

583 584 585 586 587 588 589
    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 已提交
590 591
      *hasNext = false;
      return TSDB_CODE_SUCCESS;
592 593 594 595
    }

    if ((asc && (win.ekey < pReader->window.skey)) || ((!asc) && (win.skey > pReader->window.ekey))) {
      pIter->index += step;
596
      if ((asc && pIter->index >= pIter->numOfFiles) || ((!asc) && pIter->index < 0)) {
D
dapan1121 已提交
597 598
        *hasNext = false;
        return TSDB_CODE_SUCCESS;
599
      }
600 601
      continue;
    }
C
Cary Xu 已提交
602

603
    tsdbDebug("%p file found fid:%d for qrange:%" PRId64 "-%" PRId64 ", %s", pReader, fid, pReader->window.skey,
604
              pReader->window.ekey, pReader->idStr);
D
dapan1121 已提交
605 606
    *hasNext = true;
    return TSDB_CODE_SUCCESS;
607
  }
608

609
_err:
D
dapan1121 已提交
610 611
  *hasNext = false;
  return code;
H
Haojun Liao 已提交
612 613
}

614
static void resetDataBlockIterator(SDataBlockIter* pIter, int32_t order) {
615 616
  pIter->order = order;
  pIter->index = -1;
617
  pIter->numOfBlocks = 0;
618 619 620 621 622 623 624
  if (pIter->blockList == NULL) {
    pIter->blockList = taosArrayInit(4, sizeof(SFileDataBlockInfo));
  } else {
    taosArrayClear(pIter->blockList);
  }
}

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

H
Haojun Liao 已提交
627
static void initReaderStatus(SReaderStatus* pStatus) {
dengyihao's avatar
dengyihao 已提交
628 629
  pStatus->pTableIter = NULL;
  pStatus->loadFromFile = true;
H
Haojun Liao 已提交
630 631
}

632 633 634 635 636 637 638 639
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 已提交
640
    SColumnInfoData colInfo = {0};
641 642 643 644 645 646 647 648 649 650 651 652 653
    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;
}

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 698 699 700 701 702 703 704 705 706 707 708
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;
}

709 710 711 712 713 714
void tsdbReleaseDataBlock(STsdbReader* pReader) {
  SReaderStatus* pStatus = &pReader->status;
  if (!pStatus->composedDataBlock) {
    tsdbReleaseReader(pReader);
  }
}
715

716
static int32_t tsdbReaderCreate(SVnode* pVnode, SQueryTableDataCond* pCond, STsdbReader** ppReader, int32_t capacity,
H
Haojun Liao 已提交
717
                                SSDataBlock* pResBlock, const char* idstr) {
H
Haojun Liao 已提交
718
  int32_t      code = 0;
719
  int8_t       level = 0;
H
Haojun Liao 已提交
720
  STsdbReader* pReader = (STsdbReader*)taosMemoryCalloc(1, sizeof(*pReader));
H
Hongze Cheng 已提交
721 722
  if (pReader == NULL) {
    code = TSDB_CODE_OUT_OF_MEMORY;
H
Haojun Liao 已提交
723
    goto _end;
H
Hongze Cheng 已提交
724 725
  }

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

H
Haojun Liao 已提交
730
  initReaderStatus(&pReader->status);
731

L
Liu Jicong 已提交
732
  pReader->pTsdb = getTsdbByRetentions(pVnode, pCond->twindows.skey, pVnode->config.tsdbCfg.retentions, idstr, &level);
dengyihao's avatar
dengyihao 已提交
733 734
  pReader->suid = pCond->suid;
  pReader->order = pCond->order;
735
  pReader->capacity = capacity;
H
Haojun Liao 已提交
736
  pReader->pResBlock = pResBlock;
737
  pReader->idStr = (idstr != NULL) ? taosStrdup(idstr) : NULL;
dengyihao's avatar
dengyihao 已提交
738
  pReader->verRange = getQueryVerRange(pVnode, pCond, level);
739
  pReader->type = pCond->type;
740
  pReader->window = updateQueryTimeWindow(pReader->pTsdb, &pCond->twindows);
H
Hongze Cheng 已提交
741
  pReader->blockInfoBuf.numPerBucket = 1000;  // 1000 tables per bucket
H
Hongze Cheng 已提交
742

H
Haojun Liao 已提交
743 744 745 746 747 748 749 750
  if (pReader->pResBlock == NULL) {
    pReader->freeBlock = true;
    pReader->pResBlock = createResBlock(pCond, pReader->capacity);
    if (pReader->pResBlock == NULL) {
      code = terrno;
      goto _end;
    }
  }
751

H
Haojun Liao 已提交
752 753 754 755 756
  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 已提交
757

758 759
  // allocate buffer in order to load data blocks from file
  SBlockLoadSuppInfo* pSup = &pReader->suppInfo;
760
  pSup->pColAgg = taosArrayInit(pCond->numOfCols, sizeof(SColumnDataAgg));
H
Haojun Liao 已提交
761
  if (pSup->pColAgg == NULL) {
762 763 764
    code = TSDB_CODE_OUT_OF_MEMORY;
    goto _end;
  }
H
Haojun Liao 已提交
765

766 767
  pSup->tsColAgg.colId = PRIMARYKEY_TIMESTAMP_COL_ID;

H
Hongze Cheng 已提交
768
  code = tBlockDataCreate(&pReader->status.fileBlockData);
H
Haojun Liao 已提交
769 770 771 772 773
  if (code != TSDB_CODE_SUCCESS) {
    terrno = code;
    goto _end;
  }

774
  setColumnIdSlotList(pSup, pCond->colList, pCond->pSlotList, pCond->numOfCols);
775

776
  tsdbInitReaderLock(pReader);
777

H
Hongze Cheng 已提交
778 779
  *ppReader = pReader;
  return code;
H
Hongze Cheng 已提交
780

H
Haojun Liao 已提交
781 782
_end:
  tsdbReaderClose(pReader);
H
Hongze Cheng 已提交
783 784 785
  *ppReader = NULL;
  return code;
}
H
Hongze Cheng 已提交
786

H
Haojun Liao 已提交
787
static int32_t doLoadBlockIndex(STsdbReader* pReader, SDataFReader* pFileReader, SArray* pIndexList) {
X
Xiaoyu Wang 已提交
788
  int64_t    st = taosGetTimestampUs();
789 790 791
  LRUHandle* handle = NULL;
  int32_t    code = tsdbCacheGetBlockIdx(pFileReader->pTsdb->biCache, pFileReader, &handle);
  if (code != TSDB_CODE_SUCCESS || handle == NULL) {
792
    goto _end;
H
Haojun Liao 已提交
793
  }
H
Hongze Cheng 已提交
794

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

797 798
  SArray* aBlockIdx = (SArray*)taosLRUCacheValue(pFileReader->pTsdb->biCache, handle);
  size_t  num = taosArrayGetSize(aBlockIdx);
799
  if (num == 0) {
800
    tsdbBICacheRelease(pFileReader->pTsdb->biCache, handle);
H
Haojun Liao 已提交
801 802
    return TSDB_CODE_SUCCESS;
  }
H
Hongze Cheng 已提交
803

H
Haojun Liao 已提交
804
  // todo binary search to the start position
805 806
  int64_t et1 = taosGetTimestampUs();

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

H
Haojun Liao 已提交
810
  int32_t i = 0, j = 0;
X
Xiaoyu Wang 已提交
811
  while (i < num && j < numOfTables) {
H
Haojun Liao 已提交
812
    pBlockIdx = (SBlockIdx*)taosArrayGet(aBlockIdx, i);
H
Hongze Cheng 已提交
813
    if (pBlockIdx->suid != pReader->suid) {
H
Haojun Liao 已提交
814
      i += 1;
H
Haojun Liao 已提交
815 816 817
      continue;
    }

H
Haojun Liao 已提交
818 819
    if (pBlockIdx->uid < pList->tableUidList[j]) {
      i += 1;
H
Haojun Liao 已提交
820 821 822
      continue;
    }

H
Haojun Liao 已提交
823
    if (pBlockIdx->uid > pList->tableUidList[j]) {
H
Haojun Liao 已提交
824
      j += 1;
H
Haojun Liao 已提交
825
      continue;
H
Haojun Liao 已提交
826 827
    }

H
Haojun Liao 已提交
828
    if (pBlockIdx->uid == pList->tableUidList[j]) {
H
Haojun Liao 已提交
829
      // this block belongs to a table that is not queried.
H
Haojun Liao 已提交
830 831 832
      STableBlockScanInfo* pScanInfo = getTableBlockScanInfo(pReader->status.pTableMap, pBlockIdx->uid, pReader->idStr);
      if (pScanInfo == NULL) {
        return terrno;
H
Haojun Liao 已提交
833 834 835 836 837 838 839
      }

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

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

H
Haojun Liao 已提交
841
      i += 1;
H
Haojun Liao 已提交
842
      j += 1;
843
    }
H
Haojun Liao 已提交
844
  }
H
Hongze Cheng 已提交
845

846
  int64_t et2 = taosGetTimestampUs();
H
Haojun Liao 已提交
847 848 849
  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);
850 851 852

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

853
_end:
854
  tsdbBICacheRelease(pFileReader->pTsdb->biCache, handle);
H
Haojun Liao 已提交
855 856
  return code;
}
H
Hongze Cheng 已提交
857

858
static void cleanupTableScanInfo(SHashObj* pTableMap) {
859
  STableBlockScanInfo** px = NULL;
dengyihao's avatar
dengyihao 已提交
860
  while (1) {
861
    px = taosHashIterate(pTableMap, px);
862 863 864 865
    if (px == NULL) {
      break;
    }

866
    // reset the index in last block when handing a new file
867 868
    tMapDataClear(&(*px)->mapData);
    taosArrayClear((*px)->pBlockList);
869
  }
870 871
}

872
static int32_t doLoadFileBlock(STsdbReader* pReader, SArray* pIndexList, SBlockNumber* pBlockNum) {
873 874 875 876 877 878
  int32_t numOfQTable = 0;
  size_t  sizeInDisk = 0;
  size_t  numOfTables = taosArrayGetSize(pIndexList);

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

dengyihao's avatar
dengyihao 已提交
880
  for (int32_t i = 0; i < numOfTables; ++i) {
X
Xiaoyu Wang 已提交
881
    SBlockIdx*           pBlockIdx = taosArrayGet(pIndexList, i);
H
Haojun Liao 已提交
882 883 884 885
    STableBlockScanInfo* pScanInfo = getTableBlockScanInfo(pReader->status.pTableMap, pBlockIdx->uid, pReader->idStr);
    if (pScanInfo == NULL) {
      return terrno;
    }
H
Hongze Cheng 已提交
886

887
    tMapDataReset(&pScanInfo->mapData);
H
Hongze Cheng 已提交
888
    tsdbReadDataBlk(pReader->pFileReader, pBlockIdx, &pScanInfo->mapData);
H
Haojun Liao 已提交
889
    taosArrayEnsureCap(pScanInfo->pBlockList, pScanInfo->mapData.nItem);
890

891
    sizeInDisk += pScanInfo->mapData.nData;
892 893 894 895 896 897 898 899 900 901 902 903 904

    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 已提交
905
    SDataBlk block = {0};
906
    for (int32_t j = 0; j < pScanInfo->mapData.nItem; ++j) {
H
Haojun Liao 已提交
907
      tGetDataBlk(pScanInfo->mapData.pData + pScanInfo->mapData.aOffset[j], &block);
H
Hongze Cheng 已提交
908

909
      // 1. time range check
910 911
      // 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 已提交
912 913
        continue;
      }
H
Hongze Cheng 已提交
914

915
      // 2. version range check
H
Hongze Cheng 已提交
916
      if (block.minVer > pReader->verRange.maxVer || block.maxVer < pReader->verRange.minVer) {
917 918
        continue;
      }
919

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

H
Haojun Liao 已提交
923 924
      void* p1 = taosArrayPush(pScanInfo->pBlockList, &bIndex);
      if (p1 == NULL) {
925
        tMapDataClear(&pScanInfo->mapData);
H
Haojun Liao 已提交
926 927
        return TSDB_CODE_OUT_OF_MEMORY;
      }
928

929
      pBlockNum->numOfBlocks += 1;
H
Haojun Liao 已提交
930
    }
H
Hongze Cheng 已提交
931

H
Haojun Liao 已提交
932
    if (taosArrayGetSize(pScanInfo->pBlockList) > 0) {
933 934 935 936
      numOfQTable += 1;
    }
  }

H
Hongze Cheng 已提交
937
  pBlockNum->numOfLastFiles = pReader->pFileReader->pSet->nSttF;
938
  int32_t total = pBlockNum->numOfLastFiles + pBlockNum->numOfBlocks;
939

940
  double el = (taosGetTimestampUs() - st) / 1000.0;
H
Hongze Cheng 已提交
941
  tsdbDebug(
942
      "load block of %ld tables completed, blocks:%d in %d tables, last-files:%d, block-info-size:%.2f Kb, elapsed "
943
      "time:%.2f ms %s",
944
      numOfTables, pBlockNum->numOfBlocks, numOfQTable, pBlockNum->numOfLastFiles, sizeInDisk / 1000.0, el,
H
Hongze Cheng 已提交
945
      pReader->idStr);
946

947
  pReader->cost.numOfBlocks += total;
948
  pReader->cost.headFileLoadTime += el;
949

H
Haojun Liao 已提交
950 951
  return TSDB_CODE_SUCCESS;
}
H
Hongze Cheng 已提交
952

953
static void setBlockAllDumped(SFileBlockDumpInfo* pDumpInfo, int64_t maxKey, int32_t order) {
954
  int32_t step = ASCENDING_TRAVERSE(order) ? 1 : -1;
955
  pDumpInfo->allDumped = true;
956
  pDumpInfo->lastKey = maxKey + step;
H
Haojun Liao 已提交
957 958
}

959 960
static void doCopyColVal(SColumnInfoData* pColInfoData, int32_t rowIndex, int32_t colIndex, SColVal* pColVal,
                         SBlockLoadSuppInfo* pSup) {
H
Haojun Liao 已提交
961
  if (IS_VAR_DATA_TYPE(pColVal->type)) {
H
Hongze Cheng 已提交
962
    if (!COL_VAL_IS_VALUE(pColVal)) {
963
      colDataSetNULL(pColInfoData, rowIndex);
H
Haojun Liao 已提交
964 965
    } else {
      varDataSetLen(pSup->buildBuf[colIndex], pColVal->value.nData);
H
Haojun Liao 已提交
966
      ASSERT(pColVal->value.nData <= pColInfoData->info.bytes);
967 968 969 970
      if (pColVal->value.nData > 0) {  // pData may be null, if nData is 0
        memcpy(varDataVal(pSup->buildBuf[colIndex]), pColVal->value.pData, pColVal->value.nData);
      }

971
      colDataSetVal(pColInfoData, rowIndex, pSup->buildBuf[colIndex], false);
H
Haojun Liao 已提交
972 973
    }
  } else {
974
    colDataSetVal(pColInfoData, rowIndex, (const char*)&pColVal->value, !COL_VAL_IS_VALUE(pColVal));
H
Haojun Liao 已提交
975
  }
H
Haojun Liao 已提交
976 977
}

978
static SFileDataBlockInfo* getCurrentBlockInfo(SDataBlockIter* pBlockIter) {
H
Haojun Liao 已提交
979 980 981
  size_t num = taosArrayGetSize(pBlockIter->blockList);
  if (num == 0) {
    ASSERT(pBlockIter->numOfBlocks == num);
982 983
    return NULL;
  }
984 985 986

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

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

C
Cary Xu 已提交
991 992 993 994 995 996
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 已提交
997
  ASSERT(pos >= 0 && pos < num && num > 0);
C
Cary Xu 已提交
998 999
  if (order == TSDB_ORDER_ASC) {
    // find the first position which is smaller than the key
H
Hongze Cheng 已提交
1000 1001
    e = num - 1;
    if (key < keyList[pos]) return -1;
C
Cary Xu 已提交
1002 1003
    while (1) {
      // check can return
H
Hongze Cheng 已提交
1004 1005 1006
      if (key >= keyList[e]) return e;
      if (key <= keyList[s]) return s;
      if (e - s <= 1) return s;
C
Cary Xu 已提交
1007 1008

      // change start or end position
H
Hongze Cheng 已提交
1009
      int mid = s + (e - s + 1) / 2;
C
Cary Xu 已提交
1010 1011
      if (keyList[mid] > key)
        e = mid;
H
Hongze Cheng 已提交
1012
      else if (keyList[mid] < key)
C
Cary Xu 已提交
1013 1014 1015 1016
        s = mid;
      else
        return mid;
    }
H
Hongze Cheng 已提交
1017
  } else {  // DESC
C
Cary Xu 已提交
1018
    // find the first position which is bigger than the key
H
Hongze Cheng 已提交
1019 1020
    e = 0;
    if (key > keyList[pos]) return -1;
C
Cary Xu 已提交
1021 1022
    while (1) {
      // check can return
H
Hongze Cheng 已提交
1023 1024 1025
      if (key <= keyList[e]) return e;
      if (key >= keyList[s]) return s;
      if (s - e <= 1) return s;
C
Cary Xu 已提交
1026 1027

      // change start or end position
H
Hongze Cheng 已提交
1028
      int mid = s - (s - e + 1) / 2;
C
Cary Xu 已提交
1029 1030
      if (keyList[mid] < key)
        e = mid;
H
Hongze Cheng 已提交
1031
      else if (keyList[mid] > key)
C
Cary Xu 已提交
1032 1033 1034 1035 1036 1037 1038
        s = mid;
      else
        return mid;
    }
  }
}

H
Haojun Liao 已提交
1039
static int32_t getEndPosInDataBlock(STsdbReader* pReader, SBlockData* pBlockData, SDataBlk* pBlock, int32_t pos) {
C
Cary Xu 已提交
1040 1041
  // NOTE: reverse the order to find the end position in data block
  int32_t endPos = -1;
H
Hongze Cheng 已提交
1042
  bool    asc = ASCENDING_TRAVERSE(pReader->order);
C
Cary Xu 已提交
1043 1044 1045 1046 1047 1048

  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 已提交
1049 1050
    int64_t key = asc ? pReader->window.ekey : pReader->window.skey;
    endPos = doBinarySearchKey(pBlockData->aTSKEY, pBlock->nRow, pos, key, pReader->order);
C
Cary Xu 已提交
1051 1052 1053 1054 1055
  }

  return endPos;
}

H
Haojun Liao 已提交
1056
static void copyPrimaryTsCol(const SBlockData* pBlockData, SFileBlockDumpInfo* pDumpInfo, SColumnInfoData* pColData,
H
Haojun Liao 已提交
1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075
                             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 已提交
1076 1077
// a faster version of copy procedure.
static void copyNumericCols(const SColData* pData, SFileBlockDumpInfo* pDumpInfo, SColumnInfoData* pColData,
H
Hongze Cheng 已提交
1078
                            int32_t dumpedRows, bool asc) {
H
Haojun Liao 已提交
1079 1080 1081 1082 1083 1084 1085 1086
  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 已提交
1087
  int32_t step = asc ? 1 : -1;
H
Haojun Liao 已提交
1088

H
Haojun Liao 已提交
1089
  // make sure it is aligned to 8bit, the allocated memory address is aligned to 256bit
1090
  //  ASSERT((((uint64_t)pColData->pData) & (0x8 - 1)) == 0);
H
Haojun Liao 已提交
1091 1092 1093 1094 1095 1096

  // 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 已提交
1097
    switch (pColData->info.type) {
H
Haojun Liao 已提交
1098 1099 1100
      case TSDB_DATA_TYPE_TIMESTAMP:
      case TSDB_DATA_TYPE_DOUBLE:
      case TSDB_DATA_TYPE_BIGINT:
H
Hongze Cheng 已提交
1101
      case TSDB_DATA_TYPE_UBIGINT: {
H
Haojun Liao 已提交
1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114
        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 已提交
1115
        int32_t mid = dumpedRows >> 1u;
H
Haojun Liao 已提交
1116 1117
        int8_t* pts = (int8_t*)pColData->pData;
        for (int32_t j = 0; j < mid; ++j) {
H
Haojun Liao 已提交
1118
          int8_t t = pts[j];
H
Haojun Liao 已提交
1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142
          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 已提交
1143
          int32_t t = pts[j];
H
Haojun Liao 已提交
1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165
          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;
      }
    }
  }
}

1166
static int32_t copyBlockDataToSDataBlock(STsdbReader* pReader) {
H
Haojun Liao 已提交
1167 1168 1169 1170
  SReaderStatus*      pStatus = &pReader->status;
  SDataBlockIter*     pBlockIter = &pStatus->blockIter;
  SBlockLoadSuppInfo* pSupInfo = &pReader->suppInfo;
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;
H
Hongze Cheng 已提交
1171

1172
  SBlockData*         pBlockData = &pStatus->fileBlockData;
C
Cary Xu 已提交
1173
  SFileDataBlockInfo* pBlockInfo = getCurrentBlockInfo(pBlockIter);
H
Hongze Cheng 已提交
1174
  SDataBlk*           pBlock = getCurrentBlock(pBlockIter);
H
Haojun Liao 已提交
1175
  SSDataBlock*        pResBlock = pReader->pResBlock;
H
Haojun Liao 已提交
1176
  int32_t             numOfOutputCols = pSupInfo->numOfCols;
H
Haojun Liao 已提交
1177

H
Haojun Liao 已提交
1178
  SColVal cv = {0};
1179
  int64_t st = taosGetTimestampUs();
1180 1181
  bool    asc = ASCENDING_TRAVERSE(pReader->order);
  int32_t step = asc ? 1 : -1;
1182

1183 1184
  // no data exists, return directly.
  if (pBlockData->nRow == 0 || pBlockData->aTSKEY == 0) {
X
Xiaoyu Wang 已提交
1185 1186
    tsdbWarn("%p no need to copy since no data in blockData, table uid:%" PRIu64 " has been dropped, %s", pReader,
             pBlockInfo->uid, pReader->idStr);
1187 1188 1189 1190
    pResBlock->info.rows = 0;
    return 0;
  }

1191 1192
  if ((pDumpInfo->rowIndex == 0 && asc) || (pDumpInfo->rowIndex == pBlock->nRow - 1 && (!asc))) {
    if (asc && pReader->window.skey <= pBlock->minKey.ts) {
1193 1194 1195
      // pDumpInfo->rowIndex = 0;
    } else if (!asc && pReader->window.ekey >= pBlock->maxKey.ts) {
      // pDumpInfo->rowIndex = pBlock->nRow - 1;
H
Haojun Liao 已提交
1196
    } else {  // find the appropriate the start position in current block, and set it to be the current rowIndex
1197
      int32_t pos = asc ? pBlock->nRow - 1 : 0;
C
Cary Xu 已提交
1198 1199 1200
      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 已提交
1201 1202 1203 1204 1205 1206 1207 1208 1209

      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;
      }
1210
    }
C
Cary Xu 已提交
1211 1212 1213 1214 1215 1216 1217 1218 1219 1220
  }

  // 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 已提交
1221 1222 1223
  int32_t dumpedRows = asc ? (endIndex - pDumpInfo->rowIndex) : (pDumpInfo->rowIndex - endIndex);
  if (dumpedRows > pReader->capacity) {  // output buffer check
    dumpedRows = pReader->capacity;
1224 1225
  }

H
Haojun Liao 已提交
1226
  int32_t i = 0;
C
Cary Xu 已提交
1227 1228
  int32_t rowIndex = 0;

H
Haojun Liao 已提交
1229 1230
  SColumnInfoData* pColData = taosArrayGet(pResBlock->pDataBlock, pSupInfo->slotId[i]);
  if (pSupInfo->colId[i] == PRIMARYKEY_TIMESTAMP_COL_ID) {
H
Haojun Liao 已提交
1231
    copyPrimaryTsCol(pBlockData, pDumpInfo, pColData, dumpedRows, asc);
1232 1233 1234
    i += 1;
  }

1235
  int32_t colIndex = 0;
H
Hongze Cheng 已提交
1236
  int32_t num = pBlockData->nColData;
1237
  while (i < numOfOutputCols && colIndex < num) {
1238 1239
    rowIndex = 0;

H
Hongze Cheng 已提交
1240
    SColData* pData = tBlockDataGetColDataByIdx(pBlockData, colIndex);
H
Haojun Liao 已提交
1241
    if (pData->cid < pSupInfo->colId[i]) {
1242
      colIndex += 1;
H
Haojun Liao 已提交
1243 1244
    } else if (pData->cid == pSupInfo->colId[i]) {
      pColData = taosArrayGet(pResBlock->pDataBlock, pSupInfo->slotId[i]);
H
Haojun Liao 已提交
1245

H
Hongze Cheng 已提交
1246
      if (pData->flag == HAS_NONE || pData->flag == HAS_NULL || pData->flag == (HAS_NULL | HAS_NONE)) {
1247
        colDataSetNNULL(pColData, 0, dumpedRows);
C
Cary Xu 已提交
1248
      } else {
H
Haojun Liao 已提交
1249
        if (IS_MATHABLE_TYPE(pColData->info.type)) {
H
Haojun Liao 已提交
1250 1251
          copyNumericCols(pData, pDumpInfo, pColData, dumpedRows, asc);
        } else {  // varchar/nchar type
H
Haojun Liao 已提交
1252
          for (int32_t j = pDumpInfo->rowIndex; rowIndex < dumpedRows; j += step) {
C
Cary Xu 已提交
1253 1254 1255 1256
            tColDataGetValue(pData, j, &cv);
            doCopyColVal(pColData, rowIndex++, i, &cv, pSupInfo);
          }
        }
H
Haojun Liao 已提交
1257
      }
C
Cary Xu 已提交
1258

1259
      colIndex += 1;
1260
      i += 1;
1261
    } else {  // the specified column does not exist in file block, fill with null data
H
Haojun Liao 已提交
1262
      pColData = taosArrayGet(pResBlock->pDataBlock, pSupInfo->slotId[i]);
1263
      colDataSetNNULL(pColData, 0, dumpedRows);
1264
      i += 1;
H
Haojun Liao 已提交
1265
    }
1266 1267
  }

1268
  // fill the mis-matched columns with null value
1269
  while (i < numOfOutputCols) {
H
Haojun Liao 已提交
1270
    pColData = taosArrayGet(pResBlock->pDataBlock, pSupInfo->slotId[i]);
1271
    colDataSetNNULL(pColData, 0, dumpedRows);
1272
    i += 1;
H
Haojun Liao 已提交
1273
  }
H
Haojun Liao 已提交
1274

1275
  pResBlock->info.dataLoad = 1;
H
Haojun Liao 已提交
1276 1277
  pResBlock->info.rows = dumpedRows;
  pDumpInfo->rowIndex += step * dumpedRows;
1278

1279
  // check if current block are all handled
C
Cary Xu 已提交
1280 1281
  if (pDumpInfo->rowIndex >= 0 && pDumpInfo->rowIndex < pBlock->nRow) {
    int64_t ts = pBlockData->aTSKEY[pDumpInfo->rowIndex];
1282 1283 1284
    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 已提交
1285
  } else {
1286 1287
    int64_t ts = asc ? pBlock->maxKey.ts : pBlock->minKey.ts;
    setBlockAllDumped(pDumpInfo, ts, pReader->order);
C
Cary Xu 已提交
1288
  }
H
Haojun Liao 已提交
1289

1290
  double elapsedTime = (taosGetTimestampUs() - st) / 1000.0;
H
Haojun Liao 已提交
1291
  pReader->cost.blockLoadTime += elapsedTime;
H
Haojun Liao 已提交
1292

1293
  int32_t unDumpedRows = asc ? pBlock->nRow - pDumpInfo->rowIndex : pDumpInfo->rowIndex + 1;
H
Haojun Liao 已提交
1294
  tsdbDebug("%p copy file block to sdatablock, global index:%d, table index:%d, brange:%" PRId64 "-%" PRId64
1295
            ", rows:%d, remain:%d, minVer:%" PRId64 ", maxVer:%" PRId64 ", uid:%" PRIu64 " elapsed time:%.2f ms, %s",
H
Haojun Liao 已提交
1296
            pReader, pBlockIter->index, pBlockInfo->tbBlockIdx, pBlock->minKey.ts, pBlock->maxKey.ts, dumpedRows,
H
Haojun Liao 已提交
1297
            unDumpedRows, pBlock->minVer, pBlock->maxVer, pBlockInfo->uid, elapsedTime, pReader->idStr);
1298 1299 1300 1301

  return TSDB_CODE_SUCCESS;
}

1302 1303
static int32_t doLoadFileBlockData(STsdbReader* pReader, SDataBlockIter* pBlockIter, SBlockData* pBlockData,
                                   uint64_t uid) {
1304
  int32_t code = 0;
1305 1306
  int64_t st = taosGetTimestampUs();

1307
  tBlockDataReset(pBlockData);
1308 1309
  STSchema* pSchema = getLatestTableSchema(pReader, uid);
  if (pSchema == NULL) {
X
Xiaoyu Wang 已提交
1310
    tsdbDebug("%p table uid:%" PRIu64 " has been dropped, no data existed, %s", pReader, uid, pReader->idStr);
1311 1312 1313 1314
    return code;
  }

  SBlockLoadSuppInfo* pSup = &pReader->suppInfo;
X
Xiaoyu Wang 已提交
1315
  TABLEID             tid = {.suid = pReader->suid, .uid = uid};
1316
  code = tBlockDataInit(pBlockData, &tid, pSchema, &pSup->colId[1], pSup->numOfCols - 1);
1317 1318 1319 1320
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

1321
  SFileDataBlockInfo* pBlockInfo = getCurrentBlockInfo(pBlockIter);
1322
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;
1323

H
Hongze Cheng 已提交
1324
  SDataBlk* pBlock = getCurrentBlock(pBlockIter);
1325
  code = tsdbReadDataBlock(pReader->pFileReader, pBlock, pBlockData);
1326 1327 1328
  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",
1329
              pReader, pBlockIter->index, pBlockInfo->tbBlockIdx, pBlock->minKey.ts, pBlock->maxKey.ts, pBlock->nRow,
1330 1331 1332
              tstrerror(code), pReader->idStr);
    return code;
  }
1333

1334
  double elapsedTime = (taosGetTimestampUs() - st) / 1000.0;
1335

1336 1337 1338 1339
  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);
1340 1341 1342

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

H
Haojun Liao 已提交
1344
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
1345
}
H
Hongze Cheng 已提交
1346

H
Haojun Liao 已提交
1347 1348 1349
static void cleanupBlockOrderSupporter(SBlockOrderSupporter* pSup) {
  taosMemoryFreeClear(pSup->numOfBlocksPerTable);
  taosMemoryFreeClear(pSup->indexPerTable);
H
Hongze Cheng 已提交
1350

H
Haojun Liao 已提交
1351 1352 1353 1354
  for (int32_t i = 0; i < pSup->numOfTables; ++i) {
    SBlockOrderWrapper* pBlockInfo = pSup->pDataBlockInfo[i];
    taosMemoryFreeClear(pBlockInfo);
  }
H
Hongze Cheng 已提交
1355

H
Haojun Liao 已提交
1356 1357
  taosMemoryFreeClear(pSup->pDataBlockInfo);
}
H
Hongze Cheng 已提交
1358

H
Haojun Liao 已提交
1359 1360
static int32_t initBlockOrderSupporter(SBlockOrderSupporter* pSup, int32_t numOfTables) {
  pSup->numOfBlocksPerTable = taosMemoryCalloc(1, sizeof(int32_t) * numOfTables);
1361 1362
  pSup->indexPerTable = taosMemoryCalloc(1, sizeof(int32_t) * numOfTables);
  pSup->pDataBlockInfo = taosMemoryCalloc(1, POINTER_BYTES * numOfTables);
H
Hongze Cheng 已提交
1363

H
Haojun Liao 已提交
1364 1365 1366 1367
  if (pSup->numOfBlocksPerTable == NULL || pSup->indexPerTable == NULL || pSup->pDataBlockInfo == NULL) {
    cleanupBlockOrderSupporter(pSup);
    return TSDB_CODE_OUT_OF_MEMORY;
  }
H
Hongze Cheng 已提交
1368

H
Haojun Liao 已提交
1369 1370
  return TSDB_CODE_SUCCESS;
}
H
Hongze Cheng 已提交
1371

H
Haojun Liao 已提交
1372
static int32_t fileDataBlockOrderCompar(const void* pLeft, const void* pRight, void* param) {
1373
  int32_t leftIndex = *(int32_t*)pLeft;
H
Haojun Liao 已提交
1374
  int32_t rightIndex = *(int32_t*)pRight;
H
Hongze Cheng 已提交
1375

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

H
Haojun Liao 已提交
1378 1379
  int32_t leftTableBlockIndex = pSupporter->indexPerTable[leftIndex];
  int32_t rightTableBlockIndex = pSupporter->indexPerTable[rightIndex];
H
Hongze Cheng 已提交
1380

H
Haojun Liao 已提交
1381 1382 1383 1384 1385 1386 1387
  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 已提交
1388

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

1392 1393 1394
  return pLeftBlock->offset > pRightBlock->offset ? 1 : -1;
}

H
Haojun Liao 已提交
1395
static int32_t doSetCurrentBlock(SDataBlockIter* pBlockIter, const char* idStr) {
1396 1397
  SFileDataBlockInfo* pBlockInfo = getCurrentBlockInfo(pBlockIter);
  if (pBlockInfo != NULL) {
H
Haojun Liao 已提交
1398
    STableBlockScanInfo* pScanInfo = getTableBlockScanInfo(pBlockIter->pTableMap, pBlockInfo->uid, idStr);
H
Haojun Liao 已提交
1399
    if (pScanInfo == NULL) {
H
Haojun Liao 已提交
1400
      return terrno;
H
Haojun Liao 已提交
1401 1402
    }

H
Haojun Liao 已提交
1403 1404
    SBlockIndex* pIndex = taosArrayGet(pScanInfo->pBlockList, pBlockInfo->tbBlockIdx);
    tMapDataGetItemByIdx(&pScanInfo->mapData, pIndex->ordinalIndex, &pBlockIter->block, tGetDataBlk);
1405
  }
1406 1407 1408 1409 1410 1411

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

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

1417
  SBlockOrderSupporter sup = {0};
1418
  pBlockIter->numOfBlocks = numOfBlocks;
1419
  taosArrayClear(pBlockIter->blockList);
1420
  pBlockIter->pTableMap = pReader->status.pTableMap;
1421

1422 1423
  // 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 已提交
1424

1425
  int64_t st = taosGetTimestampUs();
1426
  int32_t code = initBlockOrderSupporter(&sup, numOfTables);
1427 1428 1429
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }
H
Haojun Liao 已提交
1430

1431 1432 1433 1434 1435 1436 1437
  int32_t cnt = 0;
  void*   ptr = NULL;
  while (1) {
    ptr = taosHashIterate(pReader->status.pTableMap, ptr);
    if (ptr == NULL) {
      break;
    }
H
Haojun Liao 已提交
1438

1439
    STableBlockScanInfo* pTableScanInfo = *(STableBlockScanInfo**)ptr;
1440 1441 1442
    if (pTableScanInfo->pBlockList == NULL || taosArrayGetSize(pTableScanInfo->pBlockList) == 0) {
      continue;
    }
H
Haojun Liao 已提交
1443

1444 1445
    size_t num = taosArrayGetSize(pTableScanInfo->pBlockList);
    sup.numOfBlocksPerTable[sup.numOfTables] = num;
H
Haojun Liao 已提交
1446

1447 1448 1449
    char* buf = taosMemoryMalloc(sizeof(SBlockOrderWrapper) * num);
    if (buf == NULL) {
      cleanupBlockOrderSupporter(&sup);
S
Shengliang Guan 已提交
1450
      return TSDB_CODE_OUT_OF_MEMORY;
1451
    }
H
Haojun Liao 已提交
1452

1453
    sup.pDataBlockInfo[sup.numOfTables] = (SBlockOrderWrapper*)buf;
1454

1455 1456 1457
    for (int32_t k = 0; k < num; ++k) {
      SBlockIndex* pIndex = taosArrayGet(pTableScanInfo->pBlockList, k);
      sup.pDataBlockInfo[sup.numOfTables][k] =
1458
          (SBlockOrderWrapper){.uid = pTableScanInfo->uid, .offset = pIndex->inFileOffset};
1459 1460 1461 1462 1463
      cnt++;
    }

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

H
Haojun Liao 已提交
1465 1466 1467 1468
  if (numOfBlocks != cnt && sup.numOfTables != numOfTables) {
    cleanupBlockOrderSupporter(&sup);
    return TSDB_CODE_INVALID_PARA;
  }
H
Haojun Liao 已提交
1469

1470
  // since there is only one table qualified, blocks are not sorted
1471 1472
  if (sup.numOfTables == 1) {
    for (int32_t i = 0; i < numOfBlocks; ++i) {
1473 1474
      SFileDataBlockInfo blockInfo = {.uid = sup.pDataBlockInfo[0][i].uid, .tbBlockIdx = i};
      taosArrayPush(pBlockIter->blockList, &blockInfo);
1475
    }
1476

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

1481
    pBlockIter->index = asc ? 0 : (numOfBlocks - 1);
H
Haojun Liao 已提交
1482
    cleanupBlockOrderSupporter(&sup);
H
Haojun Liao 已提交
1483
    doSetCurrentBlock(pBlockIter, pReader->idStr);
1484
    return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
1485
  }
H
Haojun Liao 已提交
1486

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

1490
  SMultiwayMergeTreeInfo* pTree = NULL;
H
Haojun Liao 已提交
1491 1492

  uint8_t ret = tMergeTreeCreate(&pTree, sup.numOfTables, &sup, fileDataBlockOrderCompar);
1493 1494
  if (ret != TSDB_CODE_SUCCESS) {
    cleanupBlockOrderSupporter(&sup);
S
Shengliang Guan 已提交
1495
    return TSDB_CODE_OUT_OF_MEMORY;
H
Haojun Liao 已提交
1496
  }
H
Haojun Liao 已提交
1497

1498 1499 1500 1501
  int32_t numOfTotal = 0;
  while (numOfTotal < cnt) {
    int32_t pos = tMergeTreeGetChosenIndex(pTree);
    int32_t index = sup.indexPerTable[pos]++;
H
Haojun Liao 已提交
1502

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

1506 1507 1508 1509
    // 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 已提交
1510

1511 1512
    numOfTotal += 1;
    tMergeTreeAdjust(pTree, tMergeTreeGetAdjustIndex(pTree));
H
Haojun Liao 已提交
1513
  }
H
Haojun Liao 已提交
1514

1515
  int64_t et = taosGetTimestampUs();
H
Hongze Cheng 已提交
1516 1517
  tsdbDebug("%p %d data blocks access order completed, elapsed time:%.2f ms %s", pReader, numOfBlocks,
            (et - st) / 1000.0, pReader->idStr);
1518 1519
  cleanupBlockOrderSupporter(&sup);
  taosMemoryFree(pTree);
H
Haojun Liao 已提交
1520

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

1524
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
1525
}
H
Hongze Cheng 已提交
1526

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

1530
  int32_t step = asc ? 1 : -1;
1531
  if ((pBlockIter->index >= pBlockIter->numOfBlocks - 1 && asc) || (pBlockIter->index <= 0 && (!asc))) {
1532 1533 1534
    return false;
  }

1535
  pBlockIter->index += step;
H
Haojun Liao 已提交
1536
  doSetCurrentBlock(pBlockIter, idStr);
1537

1538 1539 1540
  return true;
}

1541 1542 1543
/**
 * This is an two rectangles overlap cases.
 */
H
Hongze Cheng 已提交
1544
static int32_t dataBlockPartiallyRequired(STimeWindow* pWindow, SVersionRange* pVerRange, SDataBlk* pBlock) {
1545 1546
  return (pWindow->ekey < pBlock->maxKey.ts && pWindow->ekey >= pBlock->minKey.ts) ||
         (pWindow->skey > pBlock->minKey.ts && pWindow->skey <= pBlock->maxKey.ts) ||
H
Hongze Cheng 已提交
1547 1548
         (pVerRange->minVer > pBlock->minVer && pVerRange->minVer <= pBlock->maxVer) ||
         (pVerRange->maxVer < pBlock->maxVer && pVerRange->maxVer >= pBlock->minVer);
H
Haojun Liao 已提交
1549
}
H
Hongze Cheng 已提交
1550

1551
static bool getNeighborBlockOfSameTable(SFileDataBlockInfo* pBlockInfo, STableBlockScanInfo* pTableBlockScanInfo,
1552
                                        int32_t* nextIndex, int32_t order, SBlockIndex* pBlockIndex) {
1553
  bool asc = ASCENDING_TRAVERSE(order);
H
Haojun Liao 已提交
1554
  if (asc && pBlockInfo->tbBlockIdx >= taosArrayGetSize(pTableBlockScanInfo->pBlockList) - 1) {
1555
    return false;
1556 1557
  }

H
Haojun Liao 已提交
1558
  if (!asc && pBlockInfo->tbBlockIdx == 0) {
1559
    return false;
1560 1561
  }

1562
  int32_t step = asc ? 1 : -1;
H
Haojun Liao 已提交
1563
  *nextIndex = pBlockInfo->tbBlockIdx + step;
1564 1565
  *pBlockIndex = *(SBlockIndex*)taosArrayGet(pTableBlockScanInfo->pBlockList, *nextIndex);
  //  tMapDataGetItemByIdx(&pTableBlockScanInfo->mapData, pIndex->ordinalIndex, pBlock, tGetDataBlk);
1566
  return true;
1567 1568 1569
}

static int32_t findFileBlockInfoIndex(SDataBlockIter* pBlockIter, SFileDataBlockInfo* pFBlockInfo) {
1570
  int32_t step = ASCENDING_TRAVERSE(pBlockIter->order) ? 1 : -1;
1571 1572
  int32_t index = pBlockIter->index;

1573
  while (index < pBlockIter->numOfBlocks && index >= 0) {
1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584
    SFileDataBlockInfo* pFBlock = taosArrayGet(pBlockIter->blockList, index);
    if (pFBlock->uid == pFBlockInfo->uid && pFBlock->tbBlockIdx == pFBlockInfo->tbBlockIdx) {
      return index;
    }

    index += step;
  }

  return -1;
}

1585
static int32_t setFileBlockActiveInBlockIter(SDataBlockIter* pBlockIter, int32_t index, int32_t step) {
1586
  if (index < 0 || index >= pBlockIter->numOfBlocks) {
1587 1588 1589 1590
    return -1;
  }

  SFileDataBlockInfo fblock = *(SFileDataBlockInfo*)taosArrayGet(pBlockIter->blockList, index);
1591 1592 1593 1594 1595
  pBlockIter->index += step;

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

1597 1598 1599
    SFileDataBlockInfo* pBlockInfo = taosArrayGet(pBlockIter->blockList, pBlockIter->index);
    ASSERT(pBlockInfo->uid == fblock.uid && pBlockInfo->tbBlockIdx == fblock.tbBlockIdx);
  }
1600

H
Haojun Liao 已提交
1601
  doSetCurrentBlock(pBlockIter, "");
1602 1603 1604
  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
1605
// todo: this attribute could be acquired during extractin the global ordered block list.
1606
static bool overlapWithNeighborBlock(SDataBlk* pBlock, SBlockIndex* pNeighborBlockIndex, int32_t order) {
1607 1608
  // it is the last block in current file, no chance to overlap with neighbor blocks.
  if (ASCENDING_TRAVERSE(order)) {
1609
    return pBlock->maxKey.ts == pNeighborBlockIndex->window.skey;
1610
  } else {
1611
    return pBlock->minKey.ts == pNeighborBlockIndex->window.ekey;
1612
  }
H
Haojun Liao 已提交
1613
}
H
Hongze Cheng 已提交
1614

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

1618
  return (ascScan && (key.ts != TSKEY_INITIAL_VAL && key.ts <= pBlock->minKey.ts)) ||
1619
         (!ascScan && (key.ts != TSKEY_INITIAL_VAL && key.ts >= pBlock->maxKey.ts));
H
Haojun Liao 已提交
1620
}
H
Hongze Cheng 已提交
1621

H
Hongze Cheng 已提交
1622
static bool keyOverlapFileBlock(TSDBKEY key, SDataBlk* pBlock, SVersionRange* pVerRange) {
H
Hongze Cheng 已提交
1623 1624
  return (key.ts >= pBlock->minKey.ts && key.ts <= pBlock->maxKey.ts) && (pBlock->maxVer >= pVerRange->minVer) &&
         (pBlock->minVer <= pVerRange->maxVer);
H
Haojun Liao 已提交
1625 1626
}

H
Hongze Cheng 已提交
1627 1628
static bool doCheckforDatablockOverlap(STableBlockScanInfo* pBlockScanInfo, const SDataBlk* pBlock,
                                       int32_t startIndex) {
1629 1630
  size_t num = taosArrayGetSize(pBlockScanInfo->delSkyline);

1631
  for (int32_t i = startIndex; i < num; i += 1) {
1632 1633
    TSDBKEY* p = taosArrayGet(pBlockScanInfo->delSkyline, i);
    if (p->ts >= pBlock->minKey.ts && p->ts <= pBlock->maxKey.ts) {
H
Hongze Cheng 已提交
1634
      if (p->version >= pBlock->minVer) {
1635 1636 1637
        return true;
      }
    } else if (p->ts < pBlock->minKey.ts) {  // p->ts < pBlock->minKey.ts
H
Hongze Cheng 已提交
1638
      if (p->version >= pBlock->minVer) {
1639 1640
        if (i < num - 1) {
          TSDBKEY* pnext = taosArrayGet(pBlockScanInfo->delSkyline, i + 1);
H
Hongze Cheng 已提交
1641 1642
          if (pnext->ts >= pBlock->minKey.ts) {
            return true;
1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655
          }
        } else {  // it must be the last point
          ASSERT(p->version == 0);
        }
      }
    } else {  // (p->ts > pBlock->maxKey.ts) {
      return false;
    }
  }

  return false;
}

H
Hongze Cheng 已提交
1656
static bool overlapWithDelSkyline(STableBlockScanInfo* pBlockScanInfo, const SDataBlk* pBlock, int32_t order) {
1657 1658 1659 1660
  if (pBlockScanInfo->delSkyline == NULL) {
    return false;
  }

1661
  // ts is not overlap
1662
  TSDBKEY* pFirst = taosArrayGet(pBlockScanInfo->delSkyline, 0);
L
Liu Jicong 已提交
1663
  TSDBKEY* pLast = taosArrayGetLast(pBlockScanInfo->delSkyline);
1664 1665 1666 1667 1668
  if (pBlock->minKey.ts > pLast->ts || pBlock->maxKey.ts < pFirst->ts) {
    return false;
  }

  // version is not overlap
1669
  if (ASCENDING_TRAVERSE(order)) {
1670
    return doCheckforDatablockOverlap(pBlockScanInfo, pBlock, pBlockScanInfo->fileDelIndex);
1671 1672
  } else {
    int32_t index = pBlockScanInfo->fileDelIndex;
1673
    while (1) {
1674 1675 1676 1677 1678
      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;
1679 1680 1681
      }
    }

1682
    return doCheckforDatablockOverlap(pBlockScanInfo, pBlock, index);
1683
  }
1684 1685
}

C
Cary Xu 已提交
1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698
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) {
1699 1700
  int32_t     neighborIndex = 0;
  SBlockIndex bIndex = {0};
1701

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

1704
  // overlap with neighbor
1705
  if (hasNeighbor) {
1706
    pInfo->overlapWithNeighborBlock = overlapWithNeighborBlock(pBlock, &bIndex, pReader->order);
1707 1708
  }

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

1713 1714 1715
  if (hasDataInLastBlock(pLastBlockReader)) {
    int64_t tsLast = getCurrentKeyInLastBlock(pLastBlockReader);
    pInfo->overlapWithLastBlock = !(pBlock->maxKey.ts < tsLast || pBlock->minKey.ts > tsLast);
1716 1717
  }

C
Cary Xu 已提交
1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732
  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);
1733

C
Cary Xu 已提交
1734 1735 1736
  bool loadDataBlock =
      (info.overlapWithNeighborBlock || info.hasDupTs || info.partiallyRequired || info.overlapWithKeyInBuf ||
       info.moreThanCapcity || info.overlapWithDelInfo || info.overlapWithLastBlock);
1737 1738 1739 1740

  // log the reason why load the datablock for profile
  if (loadDataBlock) {
    tsdbDebug("%p uid:%" PRIu64
X
Xiaoyu Wang 已提交
1741
              " need to load the datablock, overlapneighbor:%d, hasDup:%d, partiallyRequired:%d, "
1742
              "overlapWithKey:%d, greaterThanBuf:%d, overlapWithDel:%d, overlapWithlastBlock:%d, %s",
C
Cary Xu 已提交
1743 1744 1745
              pReader, pBlockInfo->uid, info.overlapWithNeighborBlock, info.hasDupTs, info.partiallyRequired,
              info.overlapWithKeyInBuf, info.moreThanCapcity, info.overlapWithDelInfo, info.overlapWithLastBlock,
              pReader->idStr);
1746 1747 1748
  }

  return loadDataBlock;
H
Haojun Liao 已提交
1749 1750
}

C
Cary Xu 已提交
1751 1752 1753 1754 1755 1756 1757 1758 1759
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;
}

1760
static int32_t buildDataBlockFromBuf(STsdbReader* pReader, STableBlockScanInfo* pBlockScanInfo, int64_t endKey) {
1761
  if (!(pBlockScanInfo->iiter.hasVal || pBlockScanInfo->iter.hasVal)) {
1762 1763
    return TSDB_CODE_SUCCESS;
  }
H
Haojun Liao 已提交
1764

1765 1766 1767
  SSDataBlock* pBlock = pReader->pResBlock;

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

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

1773
  setComposedBlockFlag(pReader, true);
1774

1775
  double elapsedTime = (taosGetTimestampUs() - st) / 1000.0;
S
Shengliang Guan 已提交
1776
  tsdbDebug("%p build data block from cache completed, elapsed time:%.2f ms, numOfRows:%d, brange:%" PRId64
X
Xiaoyu Wang 已提交
1777
            " - %" PRId64 ", uid:%" PRIu64 ",  %s",
1778
            pReader, elapsedTime, pBlock->info.rows, pBlock->info.window.skey, pBlock->info.window.ekey,
1779
            pBlockScanInfo->uid, pReader->idStr);
1780 1781

  pReader->cost.buildmemBlock += elapsedTime;
H
Haojun Liao 已提交
1782 1783 1784
  return code;
}

1785 1786
static bool tryCopyDistinctRowFromFileBlock(STsdbReader* pReader, SBlockData* pBlockData, int64_t key,
                                            SFileBlockDumpInfo* pDumpInfo) {
1787 1788 1789
  // opt version
  // 1. it is not a border point
  // 2. the direct next point is not an duplicated timestamp
1790 1791
  bool asc = (pReader->order == TSDB_ORDER_ASC);
  if ((pDumpInfo->rowIndex < pDumpInfo->totalRows - 1 && asc) || (pDumpInfo->rowIndex > 0 && (!asc))) {
1792
    int32_t step = pReader->order == TSDB_ORDER_ASC ? 1 : -1;
1793 1794

    int64_t nextKey = pBlockData->aTSKEY[pDumpInfo->rowIndex + step];
1795
    if (nextKey != key) {  // merge is not needed
1796
      doAppendRowFromFileBlock(pReader->pResBlock, pReader, pBlockData, pDumpInfo->rowIndex);
1797 1798 1799 1800 1801 1802 1803 1804
      pDumpInfo->rowIndex += step;
      return true;
    }
  }

  return false;
}

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

1809 1810
  while (1) {
    bool hasVal = tMergeTreeNext(&pLastBlockReader->mergeTree);
1811
    if (!hasVal) {  // the next value will be the accessed key in stt
1812
      pScanInfo->lastKeyInStt += step;
1813 1814 1815 1816 1817
      return false;
    }

    TSDBROW row = tMergeTreeGetRow(&pLastBlockReader->mergeTree);
    TSDBKEY k = TSDBROW_KEY(&row);
1818 1819 1820
    pScanInfo->lastKeyInStt = k.ts;

    if (!hasBeenDropped(pScanInfo->delSkyline, &pScanInfo->lastBlockDelIndex, &k, pLastBlockReader->order, pVerRange)) {
H
Haojun Liao 已提交
1821 1822
      // the qualifed ts may equal to k.ts, only a greater version one.
      // here we need to fallback one step.
1823 1824 1825 1826 1827 1828 1829
      return true;
    }
  }
}

static bool tryCopyDistinctRowFromSttBlock(TSDBROW* fRow, SLastBlockReader* pLastBlockReader,
                                           STableBlockScanInfo* pScanInfo, int64_t ts, STsdbReader* pReader) {
1830
  bool hasVal = nextRowFromLastBlocks(pLastBlockReader, pScanInfo, &pReader->verRange);
1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844
  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;
}

1845 1846 1847 1848 1849 1850
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 已提交
1851
  if (pReader->pSchema == NULL) {
1852 1853 1854
    tsdbError("failed to get table schema, uid:%" PRIu64 ", it may have been dropped, ver:-1, %s", uid, pReader->idStr);
  }

X
Xiaoyu Wang 已提交
1855
  return pReader->pSchema;
1856 1857
}

H
Haojun Liao 已提交
1858 1859 1860
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) {
1861
    pReader->pSchema = metaGetTbTSchema(pReader->pTsdb->pVnode->pMeta, uid, -1, 1);
H
Haojun Liao 已提交
1862 1863
  }

1864
  if (pReader->pSchema && sversion == pReader->pSchema->version) {
H
Haojun Liao 已提交
1865 1866 1867 1868 1869 1870
    return pReader->pSchema;
  }

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

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

H
Haojun Liao 已提交
1883
  taosMemoryFreeClear(pReader->pMemSchema);
H
Haojun Liao 已提交
1884
  int32_t code = metaGetTbTSchemaEx(pReader->pTsdb->pVnode->pMeta, pReader->suid, uid, sversion, &pReader->pMemSchema);
H
Haojun Liao 已提交
1885
  if (code != TSDB_CODE_SUCCESS || pReader->pMemSchema == NULL) {
H
Haojun Liao 已提交
1886 1887
    terrno = code;
    return NULL;
H
Haojun Liao 已提交
1888 1889
  } else {
    return pReader->pMemSchema;
H
Haojun Liao 已提交
1890
  }
H
Haojun Liao 已提交
1891 1892
}

1893
static int32_t doMergeBufAndFileRows(STsdbReader* pReader, STableBlockScanInfo* pBlockScanInfo, TSDBROW* pRow,
1894 1895
                                     SIterInfo* pIter, int64_t key, SLastBlockReader* pLastBlockReader) {
  SRowMerger          merge = {0};
H
Hongze Cheng 已提交
1896
  SRow*               pTSRow = NULL;
1897 1898 1899
  SBlockData*         pBlockData = &pReader->status.fileBlockData;
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;

1900
  int64_t tsLast = INT64_MIN;
1901
  if (hasDataInLastBlock(pLastBlockReader)) {
1902 1903
    tsLast = getCurrentKeyInLastBlock(pLastBlockReader);
  }
1904

H
Hongze Cheng 已提交
1905 1906
  TSDBKEY k = TSDBROW_KEY(pRow);
  TSDBROW fRow = tsdbRowFromBlockData(pBlockData, pDumpInfo->rowIndex);
1907

1908 1909
  int64_t minKey = 0;
  if (pReader->order == TSDB_ORDER_ASC) {
H
Hongze Cheng 已提交
1910
    minKey = INT64_MAX;  // chosen the minimum value
1911
    if (minKey > tsLast && hasDataInLastBlock(pLastBlockReader)) {
1912 1913
      minKey = tsLast;
    }
1914

1915 1916 1917
    if (minKey > k.ts) {
      minKey = k.ts;
    }
1918

1919
    if (minKey > key && hasDataInFileBlock(pBlockData, pDumpInfo)) {
1920 1921 1922 1923
      minKey = key;
    }
  } else {
    minKey = INT64_MIN;
1924
    if (minKey < tsLast && hasDataInLastBlock(pLastBlockReader)) {
1925 1926 1927 1928 1929 1930 1931
      minKey = tsLast;
    }

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

1932
    if (minKey < key && hasDataInFileBlock(pBlockData, pDumpInfo)) {
1933 1934
      minKey = key;
    }
1935 1936 1937 1938
  }

  bool init = false;

1939
  // ASC: file block ---> last block -----> imem -----> mem
H
Hongze Cheng 已提交
1940
  // DESC: mem -----> imem -----> last block -----> file block
1941 1942
  if (pReader->order == TSDB_ORDER_ASC) {
    if (minKey == key) {
1943
      init = true;
H
Hongze Cheng 已提交
1944
      int32_t code = tsdbRowMergerInit(&merge, &fRow, pReader->pSchema);
H
Haojun Liao 已提交
1945 1946 1947
      if (code != TSDB_CODE_SUCCESS) {
        return code;
      }
1948
      doMergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pReader, &merge);
1949 1950
    }

1951
    if (minKey == tsLast) {
1952
      TSDBROW fRow1 = tMergeTreeGetRow(&pLastBlockReader->mergeTree);
H
Haojun Liao 已提交
1953
      if (init) {
H
Hongze Cheng 已提交
1954
        tsdbRowMerge(&merge, &fRow1);
H
Haojun Liao 已提交
1955
      } else {
1956
        init = true;
H
Hongze Cheng 已提交
1957
        int32_t code = tsdbRowMergerInit(&merge, &fRow1, pReader->pSchema);
H
Haojun Liao 已提交
1958 1959 1960
        if (code != TSDB_CODE_SUCCESS) {
          return code;
        }
1961
      }
1962
      doMergeRowsInLastBlock(pLastBlockReader, pBlockScanInfo, tsLast, &merge, &pReader->verRange, pReader->idStr);
1963
    }
1964

1965
    if (minKey == k.ts) {
K
kailixu 已提交
1966 1967 1968 1969
      STSchema* pSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(pRow), pReader, pBlockScanInfo->uid);
      if (pSchema == NULL) {
        return terrno;
      }
H
Haojun Liao 已提交
1970
      if (init) {
X
Xiaoyu Wang 已提交
1971
        tsdbRowMergerAdd(&merge, pRow, pSchema);
H
Haojun Liao 已提交
1972
      } else {
1973
        init = true;
X
Xiaoyu Wang 已提交
1974
        int32_t code = tsdbRowMergerInit(&merge, pRow, pSchema);
H
Haojun Liao 已提交
1975 1976 1977 1978 1979 1980 1981
        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;
1982 1983 1984 1985 1986
      }
    }
  } else {
    if (minKey == k.ts) {
      init = true;
1987
      STSchema* pSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(pRow), pReader, pBlockScanInfo->uid);
H
Hongze Cheng 已提交
1988
      int32_t   code = tsdbRowMergerInit(&merge, pRow, pSchema);
H
Haojun Liao 已提交
1989 1990 1991 1992 1993
      if (code != TSDB_CODE_SUCCESS) {
        return code;
      }

      code = doMergeRowsInBuf(pIter, pBlockScanInfo->uid, k.ts, pBlockScanInfo->delSkyline, &merge, pReader);
1994
      if (code != TSDB_CODE_SUCCESS || merge.pTSchema == NULL) {
H
Haojun Liao 已提交
1995 1996
        return code;
      }
1997 1998
    }

1999
    if (minKey == tsLast) {
2000
      TSDBROW fRow1 = tMergeTreeGetRow(&pLastBlockReader->mergeTree);
H
Haojun Liao 已提交
2001
      if (init) {
H
Hongze Cheng 已提交
2002
        tsdbRowMerge(&merge, &fRow1);
H
Haojun Liao 已提交
2003
      } else {
2004
        init = true;
H
Hongze Cheng 已提交
2005
        int32_t code = tsdbRowMergerInit(&merge, &fRow1, pReader->pSchema);
H
Haojun Liao 已提交
2006 2007 2008
        if (code != TSDB_CODE_SUCCESS) {
          return code;
        }
2009
      }
2010
      doMergeRowsInLastBlock(pLastBlockReader, pBlockScanInfo, tsLast, &merge, &pReader->verRange, pReader->idStr);
2011 2012 2013
    }

    if (minKey == key) {
H
Haojun Liao 已提交
2014
      if (init) {
H
Hongze Cheng 已提交
2015
        tsdbRowMerge(&merge, &fRow);
H
Haojun Liao 已提交
2016
      } else {
2017
        init = true;
H
Hongze Cheng 已提交
2018
        int32_t code = tsdbRowMergerInit(&merge, &fRow, pReader->pSchema);
H
Haojun Liao 已提交
2019 2020 2021
        if (code != TSDB_CODE_SUCCESS) {
          return code;
        }
2022 2023 2024
      }
      doMergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pReader, &merge);
    }
2025 2026
  }

H
Hongze Cheng 已提交
2027
  int32_t code = tsdbRowMergerGetRow(&merge, &pTSRow);
2028 2029 2030 2031
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

2032
  doAppendRowFromTSRow(pReader->pResBlock, pReader, pTSRow, pBlockScanInfo);
2033 2034

  taosMemoryFree(pTSRow);
H
Hongze Cheng 已提交
2035
  tsdbRowMergerClear(&merge);
2036 2037 2038
  return TSDB_CODE_SUCCESS;
}

2039 2040 2041
static int32_t doMergeFileBlockAndLastBlock(SLastBlockReader* pLastBlockReader, STsdbReader* pReader,
                                            STableBlockScanInfo* pBlockScanInfo, SBlockData* pBlockData,
                                            bool mergeBlockData) {
2042
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;
H
Hongze Cheng 已提交
2043
  int64_t             tsLastBlock = getCurrentKeyInLastBlock(pLastBlockReader);
2044

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

2050 2051 2052
  // only last block exists
  if ((!mergeBlockData) || (tsLastBlock != pBlockData->aTSKEY[pDumpInfo->rowIndex])) {
    if (tryCopyDistinctRowFromSttBlock(&fRow, pLastBlockReader, pBlockScanInfo, tsLastBlock, pReader)) {
2053
      pBlockScanInfo->lastKey = tsLastBlock;
2054 2055
      return TSDB_CODE_SUCCESS;
    } else {
H
Hongze Cheng 已提交
2056
      int32_t code = tsdbRowMergerInit(&merge, &fRow, pReader->pSchema);
H
Haojun Liao 已提交
2057 2058 2059
      if (code != TSDB_CODE_SUCCESS) {
        return code;
      }
2060

2061
      TSDBROW fRow1 = tMergeTreeGetRow(&pLastBlockReader->mergeTree);
H
Hongze Cheng 已提交
2062
      tsdbRowMerge(&merge, &fRow1);
2063
      doMergeRowsInLastBlock(pLastBlockReader, pBlockScanInfo, tsLastBlock, &merge, &pReader->verRange, pReader->idStr);
2064

H
Hongze Cheng 已提交
2065
      code = tsdbRowMergerGetRow(&merge, &pTSRow);
2066 2067 2068
      if (code != TSDB_CODE_SUCCESS) {
        return code;
      }
2069

2070
      doAppendRowFromTSRow(pReader->pResBlock, pReader, pTSRow, pBlockScanInfo);
2071 2072

      taosMemoryFree(pTSRow);
H
Hongze Cheng 已提交
2073
      tsdbRowMergerClear(&merge);
2074 2075
    }
  } else {  // not merge block data
H
Hongze Cheng 已提交
2076
    int32_t code = tsdbRowMergerInit(&merge, &fRow, pReader->pSchema);
H
Haojun Liao 已提交
2077 2078 2079 2080
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

2081
    doMergeRowsInLastBlock(pLastBlockReader, pBlockScanInfo, tsLastBlock, &merge, &pReader->verRange, pReader->idStr);
2082 2083

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

H
Hongze Cheng 已提交
2088
    code = tsdbRowMergerGetRow(&merge, &pTSRow);
2089 2090 2091 2092
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

2093
    doAppendRowFromTSRow(pReader->pResBlock, pReader, pTSRow, pBlockScanInfo);
2094 2095

    taosMemoryFree(pTSRow);
H
Hongze Cheng 已提交
2096
    tsdbRowMergerClear(&merge);
2097
  }
2098 2099 2100 2101

  return TSDB_CODE_SUCCESS;
}

2102 2103
static int32_t mergeFileBlockAndLastBlock(STsdbReader* pReader, SLastBlockReader* pLastBlockReader, int64_t key,
                                          STableBlockScanInfo* pBlockScanInfo, SBlockData* pBlockData) {
2104 2105
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;

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

H
Hongze Cheng 已提交
2124
        int32_t code = tsdbRowMergerInit(&merge, &fRow, pReader->pSchema);
H
Haojun Liao 已提交
2125 2126 2127 2128
        if (code != TSDB_CODE_SUCCESS) {
          return code;
        }

2129
        doMergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pReader, &merge);
2130 2131

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

2134
        doMergeRowsInLastBlock(pLastBlockReader, pBlockScanInfo, ts, &merge, &pReader->verRange, pReader->idStr);
2135

H
Hongze Cheng 已提交
2136
        code = tsdbRowMergerGetRow(&merge, &pTSRow);
2137 2138 2139 2140
        if (code != TSDB_CODE_SUCCESS) {
          return code;
        }

2141
        doAppendRowFromTSRow(pReader->pResBlock, pReader, pTSRow, pBlockScanInfo);
2142

2143
        taosMemoryFree(pTSRow);
H
Hongze Cheng 已提交
2144
        tsdbRowMergerClear(&merge);
2145
        return code;
2146
      } else {
2147
        return TSDB_CODE_SUCCESS;
2148
      }
2149
    } else {  // desc order
2150
      return doMergeFileBlockAndLastBlock(pLastBlockReader, pReader, pBlockScanInfo, pBlockData, true);
2151
    }
2152
  } else {  // only last block exists
2153
    return doMergeFileBlockAndLastBlock(pLastBlockReader, pReader, pBlockScanInfo, NULL, false);
H
Haojun Liao 已提交
2154
  }
2155 2156
}

2157 2158
static int32_t doMergeMultiLevelRows(STsdbReader* pReader, STableBlockScanInfo* pBlockScanInfo, SBlockData* pBlockData,
                                     SLastBlockReader* pLastBlockReader) {
H
Haojun Liao 已提交
2159
  SRowMerger          merge = {0};
H
Hongze Cheng 已提交
2160
  SRow*               pTSRow = NULL;
H
Haojun Liao 已提交
2161
  int32_t             code = TSDB_CODE_SUCCESS;
2162 2163 2164
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;
  SArray*             pDelList = pBlockScanInfo->delSkyline;

2165 2166
  TSDBROW* pRow = getValidMemRow(&pBlockScanInfo->iter, pDelList, pReader);
  TSDBROW* piRow = getValidMemRow(&pBlockScanInfo->iiter, pDelList, pReader);
2167

2168
  int64_t tsLast = INT64_MIN;
2169 2170 2171
  if (hasDataInLastBlock(pLastBlockReader)) {
    tsLast = getCurrentKeyInLastBlock(pLastBlockReader);
  }
2172

H
Hongze Cheng 已提交
2173
  int64_t key = hasDataInFileBlock(pBlockData, pDumpInfo) ? pBlockData->aTSKEY[pDumpInfo->rowIndex] : INT64_MIN;
2174 2175 2176 2177

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

2178
  int64_t minKey = 0;
2179 2180 2181 2182 2183
  if (ASCENDING_TRAVERSE(pReader->order)) {
    minKey = INT64_MAX;  // let's find the minimum
    if (minKey > k.ts) {
      minKey = k.ts;
    }
2184

2185 2186 2187
    if (minKey > ik.ts) {
      minKey = ik.ts;
    }
2188

2189
    if (minKey > key && hasDataInFileBlock(pBlockData, pDumpInfo)) {
2190 2191
      minKey = key;
    }
2192

2193
    if (minKey > tsLast && hasDataInLastBlock(pLastBlockReader)) {
2194 2195 2196
      minKey = tsLast;
    }
  } else {
H
Hongze Cheng 已提交
2197
    minKey = INT64_MIN;  // let find the maximum ts value
2198 2199 2200 2201 2202 2203 2204 2205
    if (minKey < k.ts) {
      minKey = k.ts;
    }

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

2206
    if (minKey < key && hasDataInFileBlock(pBlockData, pDumpInfo)) {
2207 2208 2209
      minKey = key;
    }

2210
    if (minKey < tsLast && hasDataInLastBlock(pLastBlockReader)) {
2211 2212
      minKey = tsLast;
    }
2213 2214 2215 2216
  }

  bool init = false;

2217 2218 2219 2220
  // ASC: file block -----> last block -----> imem -----> mem
  // DESC: mem -----> imem -----> last block -----> file block
  if (ASCENDING_TRAVERSE(pReader->order)) {
    if (minKey == key) {
2221
      init = true;
2222
      TSDBROW fRow = tsdbRowFromBlockData(pBlockData, pDumpInfo->rowIndex);
H
Hongze Cheng 已提交
2223
      code = tsdbRowMergerInit(&merge, &fRow, pReader->pSchema);
H
Haojun Liao 已提交
2224 2225 2226 2227
      if (code != TSDB_CODE_SUCCESS) {
        return code;
      }

2228
      doMergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pReader, &merge);
2229 2230
    }

2231
    if (minKey == tsLast) {
2232
      TSDBROW fRow1 = tMergeTreeGetRow(&pLastBlockReader->mergeTree);
H
Haojun Liao 已提交
2233
      if (init) {
H
Hongze Cheng 已提交
2234
        tsdbRowMerge(&merge, &fRow1);
H
Haojun Liao 已提交
2235
      } else {
2236
        init = true;
H
Hongze Cheng 已提交
2237
        code = tsdbRowMergerInit(&merge, &fRow1, pReader->pSchema);
H
Haojun Liao 已提交
2238 2239 2240
        if (code != TSDB_CODE_SUCCESS) {
          return code;
        }
2241
      }
H
Haojun Liao 已提交
2242

2243
      doMergeRowsInLastBlock(pLastBlockReader, pBlockScanInfo, tsLast, &merge, &pReader->verRange, pReader->idStr);
2244 2245 2246
    }

    if (minKey == ik.ts) {
H
Haojun Liao 已提交
2247
      if (init) {
H
Hongze Cheng 已提交
2248
        tsdbRowMerge(&merge, piRow);
H
Haojun Liao 已提交
2249
      } else {
2250 2251
        init = true;
        STSchema* pSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(piRow), pReader, pBlockScanInfo->uid);
H
Haojun Liao 已提交
2252 2253 2254 2255
        if (pSchema == NULL) {
          return code;
        }

H
Hongze Cheng 已提交
2256
        code = tsdbRowMergerInit(&merge, piRow, pSchema);
H
Haojun Liao 已提交
2257 2258 2259
        if (code != TSDB_CODE_SUCCESS) {
          return code;
        }
2260
      }
H
Haojun Liao 已提交
2261

2262 2263
      code = doMergeRowsInBuf(&pBlockScanInfo->iiter, pBlockScanInfo->uid, ik.ts, pBlockScanInfo->delSkyline, &merge,
                              pReader);
H
Haojun Liao 已提交
2264 2265
      if (code != TSDB_CODE_SUCCESS) {
        return code;
2266
      }
2267 2268
    }

2269
    if (minKey == k.ts) {
H
Haojun Liao 已提交
2270
      if (init) {
2271 2272 2273 2274
        if (merge.pTSchema == NULL) {
          return code;
        }

H
Hongze Cheng 已提交
2275
        tsdbRowMerge(&merge, pRow);
H
Haojun Liao 已提交
2276
      } else {
2277
        STSchema* pSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(pRow), pReader, pBlockScanInfo->uid);
H
Hongze Cheng 已提交
2278
        code = tsdbRowMergerInit(&merge, pRow, pSchema);
H
Haojun Liao 已提交
2279 2280 2281
        if (code != TSDB_CODE_SUCCESS) {
          return code;
        }
2282
      }
H
Haojun Liao 已提交
2283 2284 2285 2286
      code = doMergeRowsInBuf(&pBlockScanInfo->iter, pBlockScanInfo->uid, k.ts, pBlockScanInfo->delSkyline, &merge,
                              pReader);
      if (code != TSDB_CODE_SUCCESS) {
        return code;
2287 2288 2289 2290 2291
      }
    }
  } else {
    if (minKey == k.ts) {
      init = true;
2292
      STSchema* pSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(pRow), pReader, pBlockScanInfo->uid);
H
Hongze Cheng 已提交
2293
      code = tsdbRowMergerInit(&merge, pRow, pSchema);
H
Haojun Liao 已提交
2294 2295 2296 2297
      if (code != TSDB_CODE_SUCCESS) {
        return code;
      }

H
Haojun Liao 已提交
2298 2299 2300 2301 2302
      code = doMergeRowsInBuf(&pBlockScanInfo->iter, pBlockScanInfo->uid, k.ts, pBlockScanInfo->delSkyline, &merge,
                              pReader);
      if (code != TSDB_CODE_SUCCESS) {
        return code;
      }
2303 2304 2305
    }

    if (minKey == ik.ts) {
H
Haojun Liao 已提交
2306
      if (init) {
H
Hongze Cheng 已提交
2307
        tsdbRowMerge(&merge, piRow);
H
Haojun Liao 已提交
2308
      } else {
2309 2310
        init = true;
        STSchema* pSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(piRow), pReader, pBlockScanInfo->uid);
H
Hongze Cheng 已提交
2311
        code = tsdbRowMergerInit(&merge, piRow, pSchema);
H
Haojun Liao 已提交
2312 2313 2314
        if (code != TSDB_CODE_SUCCESS) {
          return code;
        }
2315
      }
H
Haojun Liao 已提交
2316 2317 2318 2319
      code = doMergeRowsInBuf(&pBlockScanInfo->iiter, pBlockScanInfo->uid, ik.ts, pBlockScanInfo->delSkyline, &merge,
                              pReader);
      if (code != TSDB_CODE_SUCCESS) {
        return code;
2320 2321 2322 2323
      }
    }

    if (minKey == tsLast) {
2324
      TSDBROW fRow1 = tMergeTreeGetRow(&pLastBlockReader->mergeTree);
H
Haojun Liao 已提交
2325
      if (init) {
H
Hongze Cheng 已提交
2326
        tsdbRowMerge(&merge, &fRow1);
H
Haojun Liao 已提交
2327
      } else {
2328
        init = true;
H
Hongze Cheng 已提交
2329
        code = tsdbRowMergerInit(&merge, &fRow1, pReader->pSchema);
H
Haojun Liao 已提交
2330 2331 2332
        if (code != TSDB_CODE_SUCCESS) {
          return code;
        }
2333
      }
2334
      doMergeRowsInLastBlock(pLastBlockReader, pBlockScanInfo, tsLast, &merge, &pReader->verRange, pReader->idStr);
2335 2336 2337
    }

    if (minKey == key) {
H
Haojun Liao 已提交
2338
      TSDBROW fRow = tsdbRowFromBlockData(pBlockData, pDumpInfo->rowIndex);
2339
      if (!init) {
H
Hongze Cheng 已提交
2340
        code = tsdbRowMergerInit(&merge, &fRow, pReader->pSchema);
H
Haojun Liao 已提交
2341 2342 2343
        if (code != TSDB_CODE_SUCCESS) {
          return code;
        }
H
Haojun Liao 已提交
2344
      } else {
2345 2346 2347
        if (merge.pTSchema == NULL) {
          return code;
        }
H
Hongze Cheng 已提交
2348
        tsdbRowMerge(&merge, &fRow);
2349 2350
      }
      doMergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pReader, &merge);
2351 2352 2353
    }
  }

2354
  if (merge.pTSchema == NULL) {
2355 2356 2357
    return code;
  }

H
Hongze Cheng 已提交
2358
  code = tsdbRowMergerGetRow(&merge, &pTSRow);
2359 2360 2361 2362
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

2363
  doAppendRowFromTSRow(pReader->pResBlock, pReader, pTSRow, pBlockScanInfo);
2364 2365

  taosMemoryFree(pTSRow);
H
Hongze Cheng 已提交
2366
  tsdbRowMergerClear(&merge);
2367
  return code;
2368 2369
}

2370 2371 2372 2373 2374 2375 2376 2377 2378
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)) {
2379 2380
    // startKey = (TSDBKEY){.ts = pReader->window.skey, .version = pReader->verRange.minVer};
    startKey = (TSDBKEY){.ts = pBlockScanInfo->lastKey + 1, .version = pReader->verRange.minVer};
2381
  } else {
2382 2383
    // startKey = (TSDBKEY){.ts = pReader->window.ekey, .version = pReader->verRange.maxVer};
    startKey = (TSDBKEY){.ts = pBlockScanInfo->lastKey - 1, .version = pReader->verRange.maxVer};
2384 2385 2386
  }

  int32_t backward = (!ASCENDING_TRAVERSE(pReader->order));
D
dapan1121 已提交
2387
  int64_t st = 0;
2388 2389 2390 2391 2392 2393 2394 2395 2396

  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 已提交
2397
        tsdbDebug("%p uid:%" PRIu64 ", check data in mem from skey:%" PRId64 ", order:%d, ts range in buf:%" PRId64
H
Hongze Cheng 已提交
2398
                  "-%" PRId64 " %s",
2399 2400
                  pReader, pBlockScanInfo->uid, startKey.ts, pReader->order, d->minKey, d->maxKey, pReader->idStr);
      } else {
H
Haojun Liao 已提交
2401
        tsdbError("%p uid:%" PRIu64 ", failed to create iterator for imem, code:%s, %s", pReader, pBlockScanInfo->uid,
2402 2403 2404 2405 2406
                  tstrerror(code), pReader->idStr);
        return code;
      }
    }
  } else {
H
Haojun Liao 已提交
2407
    tsdbDebug("%p uid:%" PRIu64 ", no data in mem, %s", pReader, pBlockScanInfo->uid, pReader->idStr);
2408 2409 2410 2411 2412 2413 2414 2415 2416 2417
  }

  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 已提交
2418
        tsdbDebug("%p uid:%" PRIu64 ", check data in imem from skey:%" PRId64 ", order:%d, ts range in buf:%" PRId64
H
Hongze Cheng 已提交
2419
                  "-%" PRId64 " %s",
2420 2421
                  pReader, pBlockScanInfo->uid, startKey.ts, pReader->order, di->minKey, di->maxKey, pReader->idStr);
      } else {
H
Haojun Liao 已提交
2422
        tsdbError("%p uid:%" PRIu64 ", failed to create iterator for mem, code:%s, %s", pReader, pBlockScanInfo->uid,
2423 2424 2425 2426 2427
                  tstrerror(code), pReader->idStr);
        return code;
      }
    }
  } else {
H
Haojun Liao 已提交
2428
    tsdbDebug("%p uid:%" PRIu64 ", no data in imem, %s", pReader, pBlockScanInfo->uid, pReader->idStr);
2429 2430
  }

2431
  st = taosGetTimestampUs();
2432
  initDelSkylineIterator(pBlockScanInfo, pReader, d, di);
2433
  pReader->cost.initDelSkylineIterTime += (taosGetTimestampUs() - st) / 1000.0;
2434 2435 2436 2437 2438

  pBlockScanInfo->iterInit = true;
  return TSDB_CODE_SUCCESS;
}

dengyihao's avatar
dengyihao 已提交
2439 2440
static bool isValidFileBlockRow(SBlockData* pBlockData, SFileBlockDumpInfo* pDumpInfo,
                                STableBlockScanInfo* pBlockScanInfo, STsdbReader* pReader) {
2441 2442 2443 2444 2445 2446 2447 2448
  // 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;
    }
  }

2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459
  // 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;
  }

2460
  TSDBKEY k = {.ts = ts, .version = ver};
2461 2462
  if (hasBeenDropped(pBlockScanInfo->delSkyline, &pBlockScanInfo->fileDelIndex, &k, pReader->order,
                     &pReader->verRange)) {
2463 2464 2465
    return false;
  }

2466 2467 2468
  return true;
}

2469
static bool initLastBlockReader(SLastBlockReader* pLBlockReader, STableBlockScanInfo* pScanInfo, STsdbReader* pReader) {
2470
  // the last block reader has been initialized for this table.
2471
  if (pLBlockReader->uid == pScanInfo->uid) {
2472
    return hasDataInLastBlock(pLBlockReader);
2473 2474
  }

2475 2476
  if (pLBlockReader->uid != 0) {
    tMergeTreeClose(&pLBlockReader->mergeTree);
2477 2478
  }

2479 2480
  initMemDataIterator(pScanInfo, pReader);
  pLBlockReader->uid = pScanInfo->uid;
2481

2482 2483
  STimeWindow w = pLBlockReader->window;
  if (ASCENDING_TRAVERSE(pLBlockReader->order)) {
2484
    w.skey = pScanInfo->lastKeyInStt;
2485
  } else {
2486
    w.ekey = pScanInfo->lastKeyInStt;
2487 2488
  }

X
Xiaoyu Wang 已提交
2489 2490
  tsdbDebug("init last block reader, window:%" PRId64 "-%" PRId64 ", uid:%" PRIu64 ", %s", w.skey, w.ekey,
            pScanInfo->uid, pReader->idStr);
2491 2492
  int32_t code = tMergeTreeOpen(&pLBlockReader->mergeTree, (pLBlockReader->order == TSDB_ORDER_DESC),
                                pReader->pFileReader, pReader->suid, pScanInfo->uid, &w, &pLBlockReader->verRange,
2493
                                pLBlockReader->pInfo, false, pReader->idStr, false);
2494 2495 2496 2497
  if (code != TSDB_CODE_SUCCESS) {
    return false;
  }

2498
  return nextRowFromLastBlocks(pLBlockReader, pScanInfo, &pReader->verRange);
2499 2500
}

2501
static int64_t getCurrentKeyInLastBlock(SLastBlockReader* pLastBlockReader) {
2502
  TSDBROW row = tMergeTreeGetRow(&pLastBlockReader->mergeTree);
2503
  return TSDBROW_TS(&row);
2504 2505
}

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

2508
bool hasDataInFileBlock(const SBlockData* pBlockData, const SFileBlockDumpInfo* pDumpInfo) {
H
Haojun Liao 已提交
2509
  if ((pBlockData->nRow > 0) && (pBlockData->nRow != pDumpInfo->totalRows)) {
2510
    return false;  // this is an invalid result.
2511
  }
2512
  return pBlockData->nRow > 0 && (!pDumpInfo->allDumped);
2513
}
2514

2515 2516
int32_t mergeRowsInFileBlocks(SBlockData* pBlockData, STableBlockScanInfo* pBlockScanInfo, int64_t key,
                              STsdbReader* pReader) {
2517 2518
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;
  if (tryCopyDistinctRowFromFileBlock(pReader, pBlockData, key, pDumpInfo)) {
2519
    pBlockScanInfo->lastKey = key;
2520 2521
    return TSDB_CODE_SUCCESS;
  } else {
C
Cary Xu 已提交
2522 2523
    TSDBROW fRow = tsdbRowFromBlockData(pBlockData, pDumpInfo->rowIndex);

H
Hongze Cheng 已提交
2524
    SRow*      pTSRow = NULL;
2525 2526
    SRowMerger merge = {0};

H
Hongze Cheng 已提交
2527
    int32_t code = tsdbRowMergerInit(&merge, &fRow, pReader->pSchema);
H
Haojun Liao 已提交
2528 2529 2530 2531
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

2532
    doMergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pReader, &merge);
H
Hongze Cheng 已提交
2533
    code = tsdbRowMergerGetRow(&merge, &pTSRow);
2534 2535 2536 2537
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

2538
    doAppendRowFromTSRow(pReader->pResBlock, pReader, pTSRow, pBlockScanInfo);
2539 2540

    taosMemoryFree(pTSRow);
H
Hongze Cheng 已提交
2541
    tsdbRowMergerClear(&merge);
2542 2543 2544 2545
    return TSDB_CODE_SUCCESS;
  }
}

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

2550
  TSDBROW *pRow = NULL, *piRow = NULL;
2551
  int64_t key = (pBlockData->nRow > 0 && (!pDumpInfo->allDumped)) ? pBlockData->aTSKEY[pDumpInfo->rowIndex] : INT64_MIN;
2552 2553 2554
  if (pBlockScanInfo->iter.hasVal) {
    pRow = getValidMemRow(&pBlockScanInfo->iter, pBlockScanInfo->delSkyline, pReader);
  }
C
Cary Xu 已提交
2555

2556 2557 2558
  if (pBlockScanInfo->iiter.hasVal) {
    piRow = getValidMemRow(&pBlockScanInfo->iiter, pBlockScanInfo->delSkyline, pReader);
  }
C
Cary Xu 已提交
2559

2560 2561 2562 2563
  // two levels of mem-table does contain the valid rows
  if (pRow != NULL && piRow != NULL) {
    return doMergeMultiLevelRows(pReader, pBlockScanInfo, pBlockData, pLastBlockReader);
  }
2564

2565 2566 2567 2568
  // imem + file + last block
  if (pBlockScanInfo->iiter.hasVal) {
    return doMergeBufAndFileRows(pReader, pBlockScanInfo, piRow, &pBlockScanInfo->iiter, key, pLastBlockReader);
  }
2569

2570 2571 2572
  // mem + file + last block
  if (pBlockScanInfo->iter.hasVal) {
    return doMergeBufAndFileRows(pReader, pBlockScanInfo, pRow, &pBlockScanInfo->iter, key, pLastBlockReader);
2573
  }
2574 2575 2576

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

H
Haojun Liao 已提交
2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618
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;
}

2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631
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;
}

2632
static int32_t buildComposedDataBlock(STsdbReader* pReader) {
H
Haojun Liao 已提交
2633 2634
  int32_t code = TSDB_CODE_SUCCESS;

2635 2636
  SSDataBlock* pResBlock = pReader->pResBlock;

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

2640
  bool    asc = ASCENDING_TRAVERSE(pReader->order);
C
Cary Xu 已提交
2641
  int64_t st = taosGetTimestampUs();
2642
  int32_t step = asc ? 1 : -1;
2643
  double  el = 0;
2644 2645 2646

  STableBlockScanInfo* pBlockScanInfo = NULL;
  if (pBlockInfo != NULL) {
H
Haojun Liao 已提交
2647 2648
    pBlockScanInfo = getTableBlockScanInfo(pReader->status.pTableMap, pBlockInfo->uid, pReader->idStr);
    if (pBlockScanInfo == NULL) {
H
Haojun Liao 已提交
2649 2650 2651
      goto _end;
    }

C
Cary Xu 已提交
2652
    SDataBlk* pBlock = getCurrentBlock(&pReader->status.blockIter);
H
Hongze Cheng 已提交
2653
    TSDBKEY   keyInBuf = getCurrentKeyInBuf(pBlockScanInfo, pReader);
C
Cary Xu 已提交
2654 2655

    // it is a clean block, load it directly
H
Hongze Cheng 已提交
2656
    if (isCleanFileDataBlock(pReader, pBlockInfo, pBlock, pBlockScanInfo, keyInBuf, pLastBlockReader) &&
2657
        pBlock->nRow <= pReader->capacity) {
2658
      if (asc || ((!asc) && (!hasDataInLastBlock(pLastBlockReader)))) {
2659
        copyBlockDataToSDataBlock(pReader);
2660 2661

        // record the last key value
H
Hongze Cheng 已提交
2662
        pBlockScanInfo->lastKey = asc ? pBlock->maxKey.ts : pBlock->minKey.ts;
H
Haojun Liao 已提交
2663 2664
        goto _end;
      }
C
Cary Xu 已提交
2665 2666
    }
  } else {  // file blocks not exist
2667
    pBlockScanInfo = *pReader->status.pTableIter;
2668 2669
  }

2670
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;
2671
  SBlockData*         pBlockData = &pReader->status.fileBlockData;
2672

2673
  while (1) {
2674
    bool hasBlockData = false;
2675
    {
2676 2677
      while (pBlockData->nRow > 0 &&
             pBlockData->uid == pBlockScanInfo->uid) {  // find the first qualified row in data block
2678 2679 2680 2681 2682
        if (isValidFileBlockRow(pBlockData, pDumpInfo, pBlockScanInfo, pReader)) {
          hasBlockData = true;
          break;
        }

2683 2684
        pDumpInfo->rowIndex += step;

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

H
Haojun Liao 已提交
2689 2690 2691 2692 2693
          // 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)) {
2694 2695
            setBlockAllDumped(pDumpInfo, pBlock->maxKey.ts, pReader->order);
            break;
2696
          }
2697 2698
        }
      }
2699
    }
2700

2701
    // no data in last block and block, no need to proceed.
2702
    if (hasBlockData == false) {
2703
      break;
2704 2705
    }

2706
    buildComposedDataBlockImpl(pReader, pBlockScanInfo, pBlockData, pLastBlockReader);
2707

2708
    // currently loaded file data block is consumed
2709
    if ((pBlockData->nRow > 0) && (pDumpInfo->rowIndex >= pBlockData->nRow || pDumpInfo->rowIndex < 0)) {
H
Hongze Cheng 已提交
2710
      SDataBlk* pBlock = getCurrentBlock(&pReader->status.blockIter);
2711
      setBlockAllDumped(pDumpInfo, pBlock->maxKey.ts, pReader->order);
2712 2713 2714 2715 2716
      break;
    }

    if (pResBlock->info.rows >= pReader->capacity) {
      break;
2717 2718 2719
    }
  }

H
Hongze Cheng 已提交
2720
_end:
2721 2722
  el = (taosGetTimestampUs() - st) / 1000.0;
  updateComposedBlockInfo(pReader, el, pBlockScanInfo);
2723

2724 2725 2726
  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 已提交
2727
              pReader, pResBlock->info.id.uid, pResBlock->info.window.skey, pResBlock->info.window.ekey,
H
Haojun Liao 已提交
2728
              pResBlock->info.rows, el, pReader->idStr);
2729
  }
2730

H
Haojun Liao 已提交
2731
  return code;
2732 2733 2734 2735
}

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

2736 2737 2738 2739 2740 2741 2742 2743
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 已提交
2744 2745
int32_t initDelSkylineIterator(STableBlockScanInfo* pBlockScanInfo, STsdbReader* pReader, STbData* pMemTbData,
                               STbData* piMemTbData) {
2746 2747 2748
  if (pBlockScanInfo->delSkyline != NULL) {
    return TSDB_CODE_SUCCESS;
  }
2749

2750
  int32_t code = 0;
2751 2752
  SArray* pDelData = taosArrayInit(4, sizeof(SDelData));

H
Hongze Cheng 已提交
2753
  SDelFile* pDelFile = pReader->pReadSnap->fs.pDelFile;
2754
  if (pDelFile && taosArrayGetSize(pReader->pDelIdx) > 0) {
2755
    SDelIdx  idx = {.suid = pReader->suid, .uid = pBlockScanInfo->uid};
2756
    SDelIdx* pIdx = taosArraySearch(pReader->pDelIdx, &idx, tCmprDelIdx, TD_EQ);
2757

H
Haojun Liao 已提交
2758
    if (pIdx != NULL) {
2759
      code = tsdbReadDelData(pReader->pDelFReader, pIdx, pDelData);
2760 2761 2762
    }
    if (code != TSDB_CODE_SUCCESS) {
      goto _err;
2763
    }
2764
  }
2765

2766 2767 2768 2769 2770 2771 2772
  SDelData* p = NULL;
  if (pMemTbData != NULL) {
    p = pMemTbData->pHead;
    while (p) {
      taosArrayPush(pDelData, p);
      p = p->pNext;
    }
2773 2774
  }

2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788
  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);
2789 2790 2791 2792 2793 2794 2795
  int32_t index = getInitialDelIndex(pBlockScanInfo->delSkyline, pReader->order);

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

2796 2797
  return code;

2798 2799 2800
_err:
  taosArrayDestroy(pDelData);
  return code;
2801 2802
}

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

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

X
Xiaoyu Wang 已提交
2809
  bool     hasKey = false, hasIKey = false;
2810
  TSDBROW* pRow = getValidMemRow(&pScanInfo->iter, pScanInfo->delSkyline, pReader);
2811
  if (pRow != NULL) {
2812
    hasKey = true;
2813 2814 2815
    key = TSDBROW_KEY(pRow);
  }

2816 2817 2818 2819
  TSDBROW* pIRow = getValidMemRow(&pScanInfo->iiter, pScanInfo->delSkyline, pReader);
  if (pIRow != NULL) {
    hasIKey = true;
    ikey = TSDBROW_KEY(pIRow);
2820 2821
  }

2822
  if (hasKey) {
X
Xiaoyu Wang 已提交
2823
    if (hasIKey) {  // has data in mem & imem
2824 2825
      if (asc) {
        return key.ts <= ikey.ts ? key : ikey;
X
Xiaoyu Wang 已提交
2826 2827
      } else {
        return key.ts <= ikey.ts ? ikey : key;
2828 2829 2830
      }
    } else {  // no data in imem
      return key;
2831
    }
2832 2833 2834 2835
  } else {
    // no data in mem & imem, return the initial value
    // only imem has data, return ikey
    return ikey;
2836 2837 2838
  }
}

2839
static int32_t moveToNextFile(STsdbReader* pReader, SBlockNumber* pBlockNum) {
H
Haojun Liao 已提交
2840
  SReaderStatus* pStatus = &pReader->status;
2841
  pBlockNum->numOfBlocks = 0;
2842
  pBlockNum->numOfLastFiles = 0;
2843

2844
  size_t  numOfTables = taosHashGetSize(pReader->status.pTableMap);
2845
  SArray* pIndexList = taosArrayInit(numOfTables, sizeof(SBlockIdx));
H
Haojun Liao 已提交
2846 2847

  while (1) {
dengyihao's avatar
dengyihao 已提交
2848
    bool    hasNext = false;
D
dapan1121 已提交
2849 2850 2851 2852 2853
    int32_t code = filesetIteratorNext(&pStatus->fileIter, pReader, &hasNext);
    if (code) {
      taosArrayDestroy(pIndexList);
      return code;
    }
dengyihao's avatar
dengyihao 已提交
2854

2855
    if (!hasNext) {  // no data files on disk
H
Haojun Liao 已提交
2856 2857 2858
      break;
    }

H
Haojun Liao 已提交
2859
    taosArrayClear(pIndexList);
D
dapan1121 已提交
2860
    code = doLoadBlockIndex(pReader, pReader->pFileReader, pIndexList);
H
Haojun Liao 已提交
2861
    if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
2862
      taosArrayDestroy(pIndexList);
H
Haojun Liao 已提交
2863 2864 2865
      return code;
    }

H
Hongze Cheng 已提交
2866
    if (taosArrayGetSize(pIndexList) > 0 || pReader->pFileReader->pSet->nSttF > 0) {
2867
      code = doLoadFileBlock(pReader, pIndexList, pBlockNum);
H
Haojun Liao 已提交
2868
      if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
2869
        taosArrayDestroy(pIndexList);
H
Haojun Liao 已提交
2870 2871 2872
        return code;
      }

2873
      if (pBlockNum->numOfBlocks + pBlockNum->numOfLastFiles > 0) {
H
Haojun Liao 已提交
2874 2875 2876
        break;
      }
    }
2877

H
Haojun Liao 已提交
2878 2879 2880
    // no blocks in current file, try next files
  }

H
Haojun Liao 已提交
2881
  taosArrayDestroy(pIndexList);
2882

H
Haojun Liao 已提交
2883 2884 2885 2886 2887 2888 2889
  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;
      }
2890

H
Haojun Liao 已提交
2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901
      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;
      }
2902 2903 2904
    }
  }

H
Haojun Liao 已提交
2905 2906 2907
  return TSDB_CODE_SUCCESS;
}

X
Xiaoyu Wang 已提交
2908
static void resetTableListIndex(SReaderStatus* pStatus) {
2909
  STableUidList* pList = &pStatus->uidList;
2910

H
Haojun Liao 已提交
2911 2912 2913
  pList->currentIndex = 0;
  uint64_t uid = pList->tableUidList[0];
  pStatus->pTableIter = taosHashGet(pStatus->pTableMap, &uid, sizeof(uid));
2914 2915
}

2916
static bool moveToNextTable(STableUidList* pOrderedCheckInfo, SReaderStatus* pStatus) {
2917 2918 2919 2920 2921 2922 2923 2924
  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));
2925
  return (pStatus->pTableIter != NULL);
2926 2927
}

2928
static int32_t doLoadLastBlockSequentially(STsdbReader* pReader) {
2929
  SReaderStatus*    pStatus = &pReader->status;
2930
  SLastBlockReader* pLastBlockReader = pStatus->fileIter.pLastBlockReader;
2931
  STableUidList*    pUidList = &pStatus->uidList;
2932

H
Haojun Liao 已提交
2933 2934
  if (taosHashGetSize(pStatus->pTableMap) == 0) {
    return TSDB_CODE_SUCCESS;
2935
  }
2936

2937 2938
  SSDataBlock* pResBlock = pReader->pResBlock;

2939
  while (1) {
2940
    // load the last data block of current table
H
Hongze Cheng 已提交
2941
    STableBlockScanInfo* pScanInfo = *(STableBlockScanInfo**)pStatus->pTableIter;
2942 2943

    bool hasVal = initLastBlockReader(pLastBlockReader, pScanInfo, pReader);
2944
    if (!hasVal) {
2945
      bool hasNexTable = moveToNextTable(pUidList, pStatus);
2946
      if (!hasNexTable) {
2947 2948
        return TSDB_CODE_SUCCESS;
      }
2949

2950
      continue;
2951 2952
    }

2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965
    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;
      }
2966 2967
    }

2968 2969 2970 2971 2972 2973 2974 2975
    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);
2976 2977
      return TSDB_CODE_SUCCESS;
    }
2978

2979
    // current table is exhausted, let's try next table
2980
    bool hasNexTable = moveToNextTable(pUidList, pStatus);
2981
    if (!hasNexTable) {
2982 2983
      return TSDB_CODE_SUCCESS;
    }
2984 2985 2986
  }
}

2987
static int32_t doBuildDataBlock(STsdbReader* pReader) {
H
Hongze Cheng 已提交
2988 2989
  int32_t   code = TSDB_CODE_SUCCESS;
  SDataBlk* pBlock = NULL;
2990 2991 2992

  SReaderStatus*       pStatus = &pReader->status;
  SDataBlockIter*      pBlockIter = &pStatus->blockIter;
2993 2994 2995
  STableBlockScanInfo* pScanInfo = NULL;
  SFileDataBlockInfo*  pBlockInfo = getCurrentBlockInfo(pBlockIter);
  SLastBlockReader*    pLastBlockReader = pReader->status.fileIter.pLastBlockReader;
2996

H
Haojun Liao 已提交
2997
  pScanInfo = getTableBlockScanInfo(pReader->status.pTableMap, pBlockInfo->uid, pReader->idStr);
H
Haojun Liao 已提交
2998
  if (pScanInfo == NULL) {
H
Haojun Liao 已提交
2999
    return terrno;
H
Haojun Liao 已提交
3000 3001
  }

3002
  pBlock = getCurrentBlock(pBlockIter);
3003

3004
  initLastBlockReader(pLastBlockReader, pScanInfo, pReader);
C
Cary Xu 已提交
3005
  TSDBKEY keyInBuf = getCurrentKeyInBuf(pScanInfo, pReader);
3006

3007
  if (fileBlockShouldLoad(pReader, pBlockInfo, pBlock, pScanInfo, keyInBuf, pLastBlockReader)) {
D
dapan1121 已提交
3008 3009 3010
    if (READ_MODE_COUNT_ONLY == pReader->readMode && pReader->rowsNum > 0) {
      return code;
    }
3011
    code = doLoadFileBlockData(pReader, pBlockIter, &pStatus->fileBlockData, pScanInfo->uid);
3012 3013
    if (code != TSDB_CODE_SUCCESS) {
      return code;
3014 3015 3016
    }

    // build composed data block
3017
    code = buildComposedDataBlock(pReader);
C
Cary Xu 已提交
3018
  } else if (bufferDataInFileBlockGap(pReader->order, keyInBuf, pBlock)) {
D
dapan1121 已提交
3019 3020 3021
    if (READ_MODE_COUNT_ONLY == pReader->readMode && pReader->rowsNum > 0) {
      return code;
    }
3022
    // data in memory that are earlier than current file block
3023
    // rows in buffer should be less than the file block in asc, greater than file block in desc
3024
    int64_t endKey = (ASCENDING_TRAVERSE(pReader->order)) ? pBlock->minKey.ts : pBlock->maxKey.ts;
3025
    code = buildDataBlockFromBuf(pReader, pScanInfo, endKey);
3026 3027
  } else {
    if (hasDataInLastBlock(pLastBlockReader) && !ASCENDING_TRAVERSE(pReader->order)) {
D
dapan1121 已提交
3028 3029 3030 3031
      if (READ_MODE_COUNT_ONLY == pReader->readMode && pReader->rowsNum > 0) {
        return code;
      }

3032 3033
      // only return the rows in last block
      int64_t tsLast = getCurrentKeyInLastBlock(pLastBlockReader);
H
Hongze Cheng 已提交
3034
      ASSERT(tsLast >= pBlock->maxKey.ts);
3035

3036 3037 3038 3039
      SBlockData* pBData = &pReader->status.fileBlockData;
      tBlockDataReset(pBData);

      SSDataBlock* pResBlock = pReader->pResBlock;
3040
      tsdbDebug("load data in last block firstly, due to desc scan data, %s", pReader->idStr);
3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062

      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 已提交
3063
                  " rows:%d, elapsed time:%.2f ms %s",
3064 3065 3066
                  pReader, pResBlock->info.id.uid, pResBlock->info.window.skey, pResBlock->info.window.ekey,
                  pResBlock->info.rows, el, pReader->idStr);
      }
H
Hongze Cheng 已提交
3067
    } else {  // whole block is required, return it directly
3068 3069
      SDataBlockInfo* pInfo = &pReader->pResBlock->info;
      pInfo->rows = pBlock->nRow;
H
Haojun Liao 已提交
3070
      pInfo->id.uid = pScanInfo->uid;
3071
      pInfo->dataLoad = 0;
3072 3073 3074
      pInfo->window = (STimeWindow){.skey = pBlock->minKey.ts, .ekey = pBlock->maxKey.ts};
      setComposedBlockFlag(pReader, false);
      setBlockAllDumped(&pStatus->fBlockDumpInfo, pBlock->maxKey.ts, pReader->order);
3075

3076
      // update the last key for the corresponding table
H
Hongze Cheng 已提交
3077
      pScanInfo->lastKey = ASCENDING_TRAVERSE(pReader->order) ? pInfo->window.ekey : pInfo->window.skey;
X
Xiaoyu Wang 已提交
3078 3079
      tsdbDebug("%p uid:%" PRIu64
                " clean file block retrieved from file, global index:%d, "
H
Haojun Liao 已提交
3080 3081 3082
                "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);
3083
    }
3084 3085 3086 3087 3088
  }

  return code;
}

D
dapan1121 已提交
3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213

static int32_t doSumBlockRows(STsdbReader* pReader, SDataFReader* pFileReader) {
  int64_t    st = taosGetTimestampUs();
  LRUHandle* handle = NULL;
  int32_t    code = tsdbCacheGetBlockIdx(pFileReader->pTsdb->biCache, pFileReader, &handle);
  if (code != TSDB_CODE_SUCCESS || handle == NULL) {
    goto _end;
  }

  int32_t numOfTables = taosHashGetSize(pReader->status.pTableMap);

  SArray* aBlockIdx = (SArray*)taosLRUCacheValue(pFileReader->pTsdb->biCache, handle);
  size_t  num = taosArrayGetSize(aBlockIdx);
  if (num == 0) {
    tsdbBICacheRelease(pFileReader->pTsdb->biCache, handle);
    return TSDB_CODE_SUCCESS;
  }

  SBlockIdx*     pBlockIdx = NULL;
  int32_t i = 0;
  for (int32_t i = 0; i < num; ++i) {
    pBlockIdx = (SBlockIdx*)taosArrayGet(aBlockIdx, i);
    if (pBlockIdx->suid != pReader->suid) {
      continue;
    }

    STableBlockScanInfo** p = taosHashGet(pReader->status.pTableMap, &pBlockIdx->uid, sizeof(pBlockIdx->uid));
    if (p == NULL || *p == NULL) {
      continue;
    }

    STableBlockScanInfo *pScanInfo = *p;
    tMapDataReset(&pScanInfo->mapData);
    tsdbReadDataBlk(pReader->pFileReader, pBlockIdx, &pScanInfo->mapData);

    SDataBlk block = {0};
    for (int32_t j = 0; j < pScanInfo->mapData.nItem; ++j) {
      tGetDataBlk(pScanInfo->mapData.pData + pScanInfo->mapData.aOffset[j], &block);
      pReader->rowsNum += block.nRow;
    }
  }

_end:
  tsdbBICacheRelease(pFileReader->pTsdb->biCache, handle);
  return code;
}


static int32_t readRowsCountFromFile(STsdbReader* pReader) {
  int32_t   code = TSDB_CODE_SUCCESS;

  while (1) {
    bool    hasNext = false;
    int32_t code = filesetIteratorNext(&pReader->status.fileIter, pReader, &hasNext);
    if (code) {
      return code;
    }

    if (!hasNext) {  // no data files on disk
      break;
    }

    code = doSumBlockRows(pReader, pReader->pFileReader);
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }
  }

  pReader->status.loadFromFile = false;

  return code;
}

static int32_t readRowsCountFromStt(STsdbReader* pReader) {
  int32_t   code = TSDB_CODE_SUCCESS;
  SLastBlockReader*    pLastBlockReader = pReader->status.fileIter.pLastBlockReader;
  SSttBlockLoadInfo*   pBlockLoadInfo = NULL;

  for (int32_t i = 0; i < pReader->pFileReader->pSet->nSttF; ++i) {  // open all last file
    pBlockLoadInfo = &pLastBlockReader->pInfo[i];
    
    if (!pLastBlockReader->pInfo[i].sttBlockLoaded) {
      pLastBlockReader->pInfo[i].sttBlockLoaded = true;
    
      code = tsdbReadSttBlk(pReader->pFileReader, i, pBlockLoadInfo->aSttBlk);
      if (code) {
        return code;
      }
    }

    size_t size = taosArrayGetSize(pBlockLoadInfo->aSttBlk);
  
    if (size >= 1) {
      SSttBlk *pStart = taosArrayGet(pBlockLoadInfo->aSttBlk, 0);
      SSttBlk *pEnd = taosArrayGet(pBlockLoadInfo->aSttBlk, size - 1);
  
      // all identical
      if (pStart->suid == pEnd->suid) {
        if (pStart->suid != pReader->suid) {
          // no qualified stt block existed
          taosArrayClear(pBlockLoadInfo->aSttBlk);
          continue;
        }
      } else {
        for (int32_t i = 0; i < size; ++i) {
          SSttBlk *p = taosArrayGet(pBlockLoadInfo->aSttBlk, i);
          uint64_t s = p->suid;
          if (s < pReader->suid) {
            continue;
          }
  
          if (s == pReader->suid) {
            pReader->rowsNum += p->nRow;
          } else if (s > pReader->suid) {
            break;
          }
        }
      }
    }
  }

  return code;
}


H
Haojun Liao 已提交
3214
static int32_t buildBlockFromBufferSequentially(STsdbReader* pReader) {
3215
  SReaderStatus* pStatus = &pReader->status;
3216
  STableUidList* pUidList = &pStatus->uidList;
3217

3218
  while (1) {
X
Xiaoyu Wang 已提交
3219 3220 3221 3222 3223 3224
    //    if (pStatus->pTableIter == NULL) {
    //      pStatus->pTableIter = taosHashIterate(pStatus->pTableMap, NULL);
    //      if (pStatus->pTableIter == NULL) {
    //        return TSDB_CODE_SUCCESS;
    //      }
    //    }
3225

3226 3227
    STableBlockScanInfo** pBlockScanInfo = pStatus->pTableIter;
    initMemDataIterator(*pBlockScanInfo, pReader);
3228

3229
    int64_t endKey = (ASCENDING_TRAVERSE(pReader->order)) ? INT64_MAX : INT64_MIN;
3230
    int32_t code = buildDataBlockFromBuf(pReader, *pBlockScanInfo, endKey);
H
Haojun Liao 已提交
3231 3232 3233 3234
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

3235
    if (pReader->pResBlock->info.rows > 0) {
H
Haojun Liao 已提交
3236
      return TSDB_CODE_SUCCESS;
3237 3238
    }

3239 3240 3241
    // current table is exhausted, let's try next table
    bool hasNexTable = moveToNextTable(pUidList, pStatus);
    if (!hasNexTable) {
H
Haojun Liao 已提交
3242
      return TSDB_CODE_SUCCESS;
3243 3244 3245 3246
    }
  }
}

3247
// set the correct start position in case of the first/last file block, according to the query time window
3248
static void initBlockDumpInfo(STsdbReader* pReader, SDataBlockIter* pBlockIter) {
3249 3250 3251 3252 3253 3254 3255 3256
  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;
    }
3257
  }
3258 3259 3260
  SReaderStatus* pStatus = &pReader->status;

  SFileBlockDumpInfo* pDumpInfo = &pStatus->fBlockDumpInfo;
3261 3262 3263

  pDumpInfo->totalRows = pBlock->nRow;
  pDumpInfo->allDumped = false;
3264
  pDumpInfo->rowIndex = ASCENDING_TRAVERSE(pReader->order) ? 0 : pBlock->nRow - 1;
3265
  pDumpInfo->lastKey = lastKey;
3266 3267
}

3268
static int32_t initForFirstBlockInFile(STsdbReader* pReader, SDataBlockIter* pBlockIter) {
3269
  SBlockNumber num = {0};
X
Xiaoyu Wang 已提交
3270
  int32_t      code = moveToNextFile(pReader, &num);
3271 3272 3273 3274 3275
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

  // all data files are consumed, try data in buffer
3276
  if (num.numOfBlocks + num.numOfLastFiles == 0) {
3277 3278 3279 3280 3281
    pReader->status.loadFromFile = false;
    return code;
  }

  // initialize the block iterator for a new fileset
3282 3283
  if (num.numOfBlocks > 0) {
    code = initBlockIterator(pReader, pBlockIter, num.numOfBlocks);
H
Hongze Cheng 已提交
3284
  } else {  // no block data, only last block exists
3285
    tBlockDataReset(&pReader->status.fileBlockData);
3286
    resetDataBlockIterator(pBlockIter, pReader->order);
H
Haojun Liao 已提交
3287
    resetTableListIndex(&pReader->status);
3288
  }
3289 3290

  // set the correct start position according to the query time window
3291
  initBlockDumpInfo(pReader, pBlockIter);
3292 3293 3294
  return code;
}

3295
static bool fileBlockPartiallyRead(SFileBlockDumpInfo* pDumpInfo, bool asc) {
3296 3297
  return (!pDumpInfo->allDumped) &&
         ((pDumpInfo->rowIndex > 0 && asc) || (pDumpInfo->rowIndex < (pDumpInfo->totalRows - 1) && (!asc)));
3298 3299
}

3300
static int32_t buildBlockFromFiles(STsdbReader* pReader) {
H
Haojun Liao 已提交
3301
  int32_t code = TSDB_CODE_SUCCESS;
3302 3303
  bool    asc = ASCENDING_TRAVERSE(pReader->order);

3304 3305
  SDataBlockIter* pBlockIter = &pReader->status.blockIter;

3306
  if (pBlockIter->numOfBlocks == 0) {
H
Hongze Cheng 已提交
3307
  _begin:
3308 3309 3310 3311 3312
    code = doLoadLastBlockSequentially(pReader);
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

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

3317
    // all data blocks are checked in this last block file, now let's try the next file
3318 3319 3320 3321 3322 3323 3324 3325
    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;
      }

3326
      // this file does not have data files, let's start check the last block file if exists
3327
      if (pBlockIter->numOfBlocks == 0) {
H
Haojun Liao 已提交
3328
        resetTableListIndex(&pReader->status);
3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342
        goto _begin;
      }
    }

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

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

3343
  while (1) {
3344 3345
    SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;

3346
    if (fileBlockPartiallyRead(pDumpInfo, asc)) {  // file data block is partially loaded
3347
      code = buildComposedDataBlock(pReader);
3348 3349 3350 3351
    } else {
      // current block are exhausted, try the next file block
      if (pDumpInfo->allDumped) {
        // try next data block in current file
H
Haojun Liao 已提交
3352
        bool hasNext = blockIteratorNext(&pReader->status.blockIter, pReader->idStr);
3353 3354
        if (hasNext) {  // check for the next block in the block accessed order list
          initBlockDumpInfo(pReader, pBlockIter);
3355
        } else {
H
Haojun Liao 已提交
3356
          if (pReader->status.pCurrentFileset->nSttF > 0) {
D
dapan1121 已提交
3357 3358 3359 3360 3361 3362
            if (READ_MODE_COUNT_ONLY == pReader->readMode && pReader->rowsNum > 0) {
              pReader->pResBlock->info.rows = pReader->rowsNum;
              pReader->rowsNum = 0;
              return TSDB_CODE_SUCCESS;
            }

3363
            // data blocks in current file are exhausted, let's try the next file now
H
Haojun Liao 已提交
3364 3365 3366 3367 3368 3369
            SBlockData* pBlockData = &pReader->status.fileBlockData;
            if (pBlockData->uid != 0) {
              tBlockDataClear(pBlockData);
            }

            tBlockDataReset(pBlockData);
3370
            resetDataBlockIterator(pBlockIter, pReader->order);
H
Haojun Liao 已提交
3371
            resetTableListIndex(&pReader->status);
3372 3373 3374
            goto _begin;
          } else {
            code = initForFirstBlockInFile(pReader, pBlockIter);
3375

3376
            // error happens or all the data files are completely checked
D
dapan1121 已提交
3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387
            if (code != TSDB_CODE_SUCCESS) {
              return code;
            }

            if (READ_MODE_COUNT_ONLY == pReader->readMode && pReader->rowsNum > 0) {
              pReader->pResBlock->info.rows = pReader->rowsNum;
              pReader->rowsNum = 0;
              return TSDB_CODE_SUCCESS;
            }

            if (pReader->status.loadFromFile == false) {
3388 3389
              return code;
            }
3390

3391 3392
            // this file does not have blocks, let's start check the last block file
            if (pBlockIter->numOfBlocks == 0) {
H
Haojun Liao 已提交
3393
              resetTableListIndex(&pReader->status);
3394 3395
              goto _begin;
            }
3396
          }
3397
        }
H
Haojun Liao 已提交
3398
      }
3399 3400

      code = doBuildDataBlock(pReader);
D
dapan1121 已提交
3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411
      if (READ_MODE_COUNT_ONLY == pReader->readMode) {
        if (false == pReader->status.composedDataBlock && pDumpInfo->allDumped) {
          pReader->rowsNum += pReader->pResBlock->info.rows;
          pReader->pResBlock->info.rows = 0;
          continue;
        } else if (pReader->pResBlock->info.rows == 0 && pReader->rowsNum > 0) {
          pReader->pResBlock->info.rows = pReader->rowsNum;
          pReader->rowsNum = 0;
          return TSDB_CODE_SUCCESS;
        }
      }
3412 3413
    }

3414 3415 3416 3417 3418 3419 3420 3421
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

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

3424 3425
static STsdb* getTsdbByRetentions(SVnode* pVnode, TSKEY winSKey, SRetention* retentions, const char* idStr,
                                  int8_t* pLevel) {
3426
  if (VND_IS_RSMA(pVnode)) {
3427
    int8_t  level = 0;
3428 3429
    int8_t  precision = pVnode->config.tsdbCfg.precision;
    int64_t now = taosGetTimestamp(precision);
H
Haojun Liao 已提交
3430 3431 3432
    int64_t offset = tsQueryRsmaTolerance * ((precision == TSDB_TIME_PRECISION_MILLI)   ? 1L
                                             : (precision == TSDB_TIME_PRECISION_MICRO) ? 1000L
                                                                                        : 1000000L);
3433

3434
    for (int8_t i = 0; i < TSDB_RETENTION_MAX; ++i) {
3435 3436 3437 3438 3439 3440 3441
      SRetention* pRetention = retentions + level;
      if (pRetention->keep <= 0) {
        if (level > 0) {
          --level;
        }
        break;
      }
3442
      if ((now - pRetention->keep) <= (winSKey + offset)) {
3443 3444 3445 3446 3447
        break;
      }
      ++level;
    }

3448
    const char* str = (idStr != NULL) ? idStr : "";
3449 3450

    if (level == TSDB_RETENTION_L0) {
3451
      *pLevel = TSDB_RETENTION_L0;
C
Cary Xu 已提交
3452
      tsdbDebug("vgId:%d, rsma level %d is selected to query %s", TD_VID(pVnode), TSDB_RETENTION_L0, str);
3453 3454
      return VND_RSMA0(pVnode);
    } else if (level == TSDB_RETENTION_L1) {
3455
      *pLevel = TSDB_RETENTION_L1;
C
Cary Xu 已提交
3456
      tsdbDebug("vgId:%d, rsma level %d is selected to query %s", TD_VID(pVnode), TSDB_RETENTION_L1, str);
3457 3458
      return VND_RSMA1(pVnode);
    } else {
3459
      *pLevel = TSDB_RETENTION_L2;
C
Cary Xu 已提交
3460
      tsdbDebug("vgId:%d, rsma level %d is selected to query %s", TD_VID(pVnode), TSDB_RETENTION_L2, str);
3461 3462 3463 3464 3465 3466 3467
      return VND_RSMA2(pVnode);
    }
  }

  return VND_TSDB(pVnode);
}

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

  int64_t endVer = 0;
L
Liu Jicong 已提交
3472 3473
  if (pCond->endVersion ==
      -1) {  // user not specified end version, set current maximum version of vnode as the endVersion
H
Haojun Liao 已提交
3474 3475
    endVer = pVnode->state.applied;
  } else {
L
Liu Jicong 已提交
3476
    endVer = (pCond->endVersion > pVnode->state.applied) ? pVnode->state.applied : pCond->endVersion;
3477 3478
  }

H
Haojun Liao 已提交
3479
  return (SVersionRange){.minVer = startVer, .maxVer = endVer};
3480 3481
}

3482
bool hasBeenDropped(const SArray* pDelList, int32_t* index, TSDBKEY* pKey, int32_t order, SVersionRange* pVerRange) {
3483 3484 3485
  if (pDelList == NULL) {
    return false;
  }
H
Haojun Liao 已提交
3486

L
Liu Jicong 已提交
3487 3488 3489
  size_t  num = taosArrayGetSize(pDelList);
  bool    asc = ASCENDING_TRAVERSE(order);
  int32_t step = asc ? 1 : -1;
3490

3491 3492 3493 3494 3495 3496
  if (asc) {
    if (*index >= num - 1) {
      TSDBKEY* last = taosArrayGetLast(pDelList);
      ASSERT(pKey->ts >= last->ts);

      if (pKey->ts > last->ts) {
3497
        return false;
3498 3499
      } else if (pKey->ts == last->ts) {
        TSDBKEY* prev = taosArrayGet(pDelList, num - 2);
3500 3501
        return (prev->version >= pKey->version && prev->version <= pVerRange->maxVer &&
                prev->version >= pVerRange->minVer);
3502 3503
      }
    } else {
3504 3505 3506 3507 3508 3509 3510
      TSDBKEY* pCurrent = taosArrayGet(pDelList, *index);
      TSDBKEY* pNext = taosArrayGet(pDelList, (*index) + 1);

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

3511 3512
      if (pCurrent->ts <= pKey->ts && pNext->ts >= pKey->ts && pCurrent->version >= pKey->version &&
          pVerRange->maxVer >= pCurrent->version) {
3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527
        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;
          }

3528 3529
          if (pCurrent->ts <= pKey->ts && pNext->ts >= pKey->ts && pCurrent->version >= pKey->version &&
              pVerRange->maxVer >= pCurrent->version) {
3530 3531 3532 3533 3534 3535
            return true;
          }
        }
      }

      return false;
3536 3537
    }
  } else {
3538 3539
    if (*index <= 0) {
      TSDBKEY* pFirst = taosArrayGet(pDelList, 0);
3540

3541 3542 3543 3544 3545 3546 3547
      if (pKey->ts < pFirst->ts) {
        return false;
      } else if (pKey->ts == pFirst->ts) {
        return pFirst->version >= pKey->version;
      } else {
        ASSERT(0);
      }
3548
    } else {
3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575
      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;
          }
        }
3576 3577 3578 3579 3580
      }

      return false;
    }
  }
3581 3582

  return false;
3583 3584
}

3585
TSDBROW* getValidMemRow(SIterInfo* pIter, const SArray* pDelList, STsdbReader* pReader) {
3586
  if (!pIter->hasVal) {
H
Haojun Liao 已提交
3587 3588
    return NULL;
  }
H
Hongze Cheng 已提交
3589

3590
  TSDBROW* pRow = tsdbTbDataIterGet(pIter->iter);
H
Hongze Cheng 已提交
3591 3592
  TSDBKEY  key = TSDBROW_KEY(pRow);

3593
  if (outOfTimeWindow(key.ts, &pReader->window)) {
3594
    pIter->hasVal = false;
H
Haojun Liao 已提交
3595 3596
    return NULL;
  }
H
Hongze Cheng 已提交
3597

3598
  // it is a valid data version
dengyihao's avatar
dengyihao 已提交
3599
  if ((key.version <= pReader->verRange.maxVer && key.version >= pReader->verRange.minVer) &&
3600
      (!hasBeenDropped(pDelList, &pIter->index, &key, pReader->order, &pReader->verRange))) {
H
Haojun Liao 已提交
3601 3602
    return pRow;
  }
H
Hongze Cheng 已提交
3603

3604
  while (1) {
3605 3606
    pIter->hasVal = tsdbTbDataIterNext(pIter->iter);
    if (!pIter->hasVal) {
H
Haojun Liao 已提交
3607 3608
      return NULL;
    }
H
Hongze Cheng 已提交
3609

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

H
Haojun Liao 已提交
3612
    key = TSDBROW_KEY(pRow);
3613
    if (outOfTimeWindow(key.ts, &pReader->window)) {
3614
      pIter->hasVal = false;
H
Haojun Liao 已提交
3615 3616
      return NULL;
    }
H
Hongze Cheng 已提交
3617

dengyihao's avatar
dengyihao 已提交
3618
    if (key.version <= pReader->verRange.maxVer && key.version >= pReader->verRange.minVer &&
3619
        (!hasBeenDropped(pDelList, &pIter->index, &key, pReader->order, &pReader->verRange))) {
H
Haojun Liao 已提交
3620 3621 3622 3623
      return pRow;
    }
  }
}
H
Hongze Cheng 已提交
3624

3625 3626
int32_t doMergeRowsInBuf(SIterInfo* pIter, uint64_t uid, int64_t ts, SArray* pDelList, SRowMerger* pMerger,
                         STsdbReader* pReader) {
H
Haojun Liao 已提交
3627
  while (1) {
3628 3629
    pIter->hasVal = tsdbTbDataIterNext(pIter->iter);
    if (!pIter->hasVal) {
H
Haojun Liao 已提交
3630 3631
      break;
    }
H
Hongze Cheng 已提交
3632

3633
    // data exists but not valid
3634
    TSDBROW* pRow = getValidMemRow(pIter, pDelList, pReader);
3635 3636 3637 3638 3639
    if (pRow == NULL) {
      break;
    }

    // ts is not identical, quit
H
Haojun Liao 已提交
3640
    TSDBKEY k = TSDBROW_KEY(pRow);
3641
    if (k.ts != ts) {
H
Haojun Liao 已提交
3642 3643 3644
      break;
    }

3645 3646 3647 3648 3649
    if (pRow->type == TSDBROW_ROW_FMT) {
      STSchema* pTSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(pRow), pReader, uid);
      if (pTSchema == NULL) {
        return terrno;
      }
H
Haojun Liao 已提交
3650

3651 3652 3653 3654
      tsdbRowMergerAdd(pMerger, pRow, pTSchema);
    } else {  // column format
      tsdbRowMerge(pMerger, pRow);
    }
H
Haojun Liao 已提交
3655 3656 3657 3658 3659
  }

  return TSDB_CODE_SUCCESS;
}

3660
static int32_t doMergeRowsInFileBlockImpl(SBlockData* pBlockData, int32_t rowIndex, int64_t key, SRowMerger* pMerger,
3661
                                          SVersionRange* pVerRange, int32_t step) {
3662
  while (rowIndex < pBlockData->nRow && rowIndex >= 0 && pBlockData->aTSKEY[rowIndex] == key) {
3663
    if (pBlockData->aVersion[rowIndex] > pVerRange->maxVer || pBlockData->aVersion[rowIndex] < pVerRange->minVer) {
3664
      rowIndex += step;
3665 3666 3667 3668
      continue;
    }

    TSDBROW fRow = tsdbRowFromBlockData(pBlockData, rowIndex);
H
Hongze Cheng 已提交
3669
    tsdbRowMerge(pMerger, &fRow);
3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680
    rowIndex += step;
  }

  return rowIndex;
}

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

H
Hongze Cheng 已提交
3681
static int32_t checkForNeighborFileBlock(STsdbReader* pReader, STableBlockScanInfo* pScanInfo, SDataBlk* pBlock,
3682 3683
                                         SFileDataBlockInfo* pFBlock, SRowMerger* pMerger, int64_t key,
                                         CHECK_FILEBLOCK_STATE* state) {
3684
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;
3685
  SBlockData*         pBlockData = &pReader->status.fileBlockData;
3686
  bool                asc = ASCENDING_TRAVERSE(pReader->order);
3687

3688
  *state = CHECK_FILEBLOCK_QUIT;
3689
  int32_t step = ASCENDING_TRAVERSE(pReader->order) ? 1 : -1;
3690

3691
  bool    loadNeighbor = true;
H
Haojun Liao 已提交
3692
  int32_t code = loadNeighborIfOverlap(pFBlock, pScanInfo, pReader, &loadNeighbor);
3693

H
Haojun Liao 已提交
3694
  if (loadNeighbor && (code == TSDB_CODE_SUCCESS)) {
3695 3696
    pDumpInfo->rowIndex =
        doMergeRowsInFileBlockImpl(pBlockData, pDumpInfo->rowIndex, key, pMerger, &pReader->verRange, step);
3697
    if ((pDumpInfo->rowIndex >= pDumpInfo->totalRows && asc) || (pDumpInfo->rowIndex < 0 && !asc)) {
3698 3699 3700 3701
      *state = CHECK_FILEBLOCK_CONT;
    }
  }

H
Haojun Liao 已提交
3702
  return code;
3703 3704
}

3705 3706
int32_t doMergeRowsInFileBlocks(SBlockData* pBlockData, STableBlockScanInfo* pScanInfo, STsdbReader* pReader,
                                SRowMerger* pMerger) {
3707 3708
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;

3709
  bool    asc = ASCENDING_TRAVERSE(pReader->order);
3710
  int64_t key = pBlockData->aTSKEY[pDumpInfo->rowIndex];
3711
  int32_t step = asc ? 1 : -1;
3712

3713
  pDumpInfo->rowIndex += step;
3714
  if ((pDumpInfo->rowIndex <= pBlockData->nRow - 1 && asc) || (pDumpInfo->rowIndex >= 0 && !asc)) {
3715 3716 3717
    pDumpInfo->rowIndex =
        doMergeRowsInFileBlockImpl(pBlockData, pDumpInfo->rowIndex, key, pMerger, &pReader->verRange, step);
  }
3718

3719 3720 3721 3722
  // 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;
3723

3724
      SFileDataBlockInfo* pFileBlockInfo = getCurrentBlockInfo(&pReader->status.blockIter);
H
Hongze Cheng 已提交
3725
      SDataBlk*           pCurrentBlock = getCurrentBlock(&pReader->status.blockIter);
H
Haojun Liao 已提交
3726 3727 3728 3729 3730
      if (pFileBlockInfo == NULL) {
        st = CHECK_FILEBLOCK_QUIT;
        break;
      }

3731 3732 3733
      checkForNeighborFileBlock(pReader, pScanInfo, pCurrentBlock, pFileBlockInfo, pMerger, key, &st);
      if (st == CHECK_FILEBLOCK_QUIT) {
        break;
3734
      }
3735
    }
H
Haojun Liao 已提交
3736
  }
3737

H
Haojun Liao 已提交
3738 3739 3740
  return TSDB_CODE_SUCCESS;
}

H
Hongze Cheng 已提交
3741
int32_t doMergeRowsInLastBlock(SLastBlockReader* pLastBlockReader, STableBlockScanInfo* pScanInfo, int64_t ts,
3742
                               SRowMerger* pMerger, SVersionRange* pVerRange, const char* idStr) {
3743
  while (nextRowFromLastBlocks(pLastBlockReader, pScanInfo, pVerRange)) {
3744 3745
    int64_t next1 = getCurrentKeyInLastBlock(pLastBlockReader);
    if (next1 == ts) {
3746
      TSDBROW fRow1 = tMergeTreeGetRow(&pLastBlockReader->mergeTree);
H
Hongze Cheng 已提交
3747
      tsdbRowMerge(pMerger, &fRow1);
3748
    } else {
3749 3750 3751
      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);
3752 3753 3754 3755 3756 3757 3758
      break;
    }
  }

  return TSDB_CODE_SUCCESS;
}

3759
int32_t doMergeMemTableMultiRows(TSDBROW* pRow, uint64_t uid, SIterInfo* pIter, SArray* pDelList, TSDBROW* pResRow,
3760
                                 STsdbReader* pReader, bool* freeTSRow) {
H
Haojun Liao 已提交
3761
  TSDBROW* pNextRow = NULL;
3762
  TSDBROW  current = *pRow;
3763

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

3767
    if (!pIter->hasVal) {
3768
      *pResRow = *pRow;
3769
      *freeTSRow = false;
3770
      return TSDB_CODE_SUCCESS;
3771
    } else {  // has next point in mem/imem
3772
      pNextRow = getValidMemRow(pIter, pDelList, pReader);
3773
      if (pNextRow == NULL) {
H
Haojun Liao 已提交
3774
        *pResRow = current;
3775
        *freeTSRow = false;
3776
        return TSDB_CODE_SUCCESS;
3777 3778
      }

H
Hongze Cheng 已提交
3779
      if (TSDBROW_TS(&current) != TSDBROW_TS(pNextRow)) {
H
Haojun Liao 已提交
3780
        *pResRow = current;
3781
        *freeTSRow = false;
3782
        return TSDB_CODE_SUCCESS;
3783
      }
3784
    }
3785 3786
  }

3787
  SRowMerger merge = {0};
H
Haojun Liao 已提交
3788
  terrno = 0;
3789
  int32_t code = 0;
H
Haojun Liao 已提交
3790

3791 3792 3793 3794 3795 3796 3797
  // 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 已提交
3798

3799 3800 3801
    if (pReader->pSchema == NULL) {
      pReader->pSchema = pTSchema;
    }
H
Haojun Liao 已提交
3802

3803
    code = tsdbRowMergerInit2(&merge, pReader->pSchema, &current, pTSchema);
3804 3805 3806
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }
H
Haojun Liao 已提交
3807

3808 3809 3810 3811
    STSchema* pTSchema1 = doGetSchemaForTSRow(TSDBROW_SVERSION(pNextRow), pReader, uid);
    if (pTSchema1 == NULL) {
      return terrno;
    }
H
Haojun Liao 已提交
3812

3813
    tsdbRowMergerAdd(&merge, pNextRow, pTSchema1);
3814 3815
  } else {  // let's merge rows in file block
    code = tsdbRowMergerInit(&merge, &current, pReader->pSchema);
3816 3817 3818
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }
H
Haojun Liao 已提交
3819

3820 3821
    tsdbRowMerge(&merge, pNextRow);
  }
H
Haojun Liao 已提交
3822

wmmhello's avatar
wmmhello 已提交
3823
  code = doMergeRowsInBuf(pIter, uid, TSDBROW_TS(&current), pDelList, &merge, pReader);
H
Haojun Liao 已提交
3824 3825 3826 3827
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

3828
  code = tsdbRowMergerGetRow(&merge, &pResRow->pTSRow);
3829 3830 3831
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }
M
Minglei Jin 已提交
3832

wmmhello's avatar
wmmhello 已提交
3833
  pResRow->type = TSDBROW_ROW_FMT;
3834
  tsdbRowMergerClear(&merge);
3835
  *freeTSRow = true;
3836

3837
  return TSDB_CODE_SUCCESS;
3838 3839
}

3840
int32_t doMergeMemIMemRows(TSDBROW* pRow, TSDBROW* piRow, STableBlockScanInfo* pBlockScanInfo, STsdbReader* pReader,
H
Hongze Cheng 已提交
3841
                           SRow** pTSRow) {
H
Haojun Liao 已提交
3842 3843
  SRowMerger merge = {0};

3844 3845 3846
  TSDBKEY k = TSDBROW_KEY(pRow);
  TSDBKEY ik = TSDBROW_KEY(piRow);

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

H
Hongze Cheng 已提交
3850
    int32_t code = tsdbRowMergerInit(&merge, piRow, pSchema);
H
Haojun Liao 已提交
3851 3852 3853 3854 3855 3856 3857 3858 3859
    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;
    }
3860

H
Hongze Cheng 已提交
3861
    tsdbRowMerge(&merge, pRow);
H
Haojun Liao 已提交
3862 3863 3864 3865 3866 3867
    code =
        doMergeRowsInBuf(&pBlockScanInfo->iter, pBlockScanInfo->uid, k.ts, pBlockScanInfo->delSkyline, &merge, pReader);
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

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

H
Hongze Cheng 已提交
3871
    int32_t code = tsdbRowMergerInit(&merge, pRow, pSchema);
3872
    if (code != TSDB_CODE_SUCCESS || merge.pTSchema == NULL) {
H
Haojun Liao 已提交
3873 3874 3875 3876 3877 3878 3879 3880
      return code;
    }

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

H
Hongze Cheng 已提交
3882
    tsdbRowMerge(&merge, piRow);
H
Haojun Liao 已提交
3883 3884 3885 3886 3887
    code = doMergeRowsInBuf(&pBlockScanInfo->iiter, pBlockScanInfo->uid, ik.ts, pBlockScanInfo->delSkyline, &merge,
                            pReader);
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }
3888
  }
3889

H
Haojun Liao 已提交
3890 3891
  int32_t code = tsdbRowMergerGetRow(&merge, pTSRow);
  tsdbRowMergerClear(&merge);
3892
  return code;
3893 3894
}

3895
int32_t tsdbGetNextRowInMem(STableBlockScanInfo* pBlockScanInfo, STsdbReader* pReader, TSDBROW* pResRow, int64_t endKey,
3896
                            bool* freeTSRow) {
3897 3898
  TSDBROW* pRow = getValidMemRow(&pBlockScanInfo->iter, pBlockScanInfo->delSkyline, pReader);
  TSDBROW* piRow = getValidMemRow(&pBlockScanInfo->iiter, pBlockScanInfo->delSkyline, pReader);
dengyihao's avatar
dengyihao 已提交
3899
  SArray*  pDelList = pBlockScanInfo->delSkyline;
3900
  uint64_t uid = pBlockScanInfo->uid;
H
Haojun Liao 已提交
3901

3902 3903
  // todo refactor
  bool asc = ASCENDING_TRAVERSE(pReader->order);
3904
  if (pBlockScanInfo->iter.hasVal) {
3905 3906 3907 3908 3909 3910
    TSDBKEY k = TSDBROW_KEY(pRow);
    if ((k.ts >= endKey && asc) || (k.ts <= endKey && !asc)) {
      pRow = NULL;
    }
  }

3911
  if (pBlockScanInfo->iiter.hasVal) {
3912 3913 3914 3915 3916 3917
    TSDBKEY k = TSDBROW_KEY(piRow);
    if ((k.ts >= endKey && asc) || (k.ts <= endKey && !asc)) {
      piRow = NULL;
    }
  }

3918
  if (pBlockScanInfo->iter.hasVal && pBlockScanInfo->iiter.hasVal && pRow != NULL && piRow != NULL) {
3919
    TSDBKEY k = TSDBROW_KEY(pRow);
3920
    TSDBKEY ik = TSDBROW_KEY(piRow);
H
Haojun Liao 已提交
3921

3922
    int32_t code = TSDB_CODE_SUCCESS;
3923 3924
    if (ik.ts != k.ts) {
      if (((ik.ts < k.ts) && asc) || ((ik.ts > k.ts) && (!asc))) {  // ik.ts < k.ts
3925
        code = doMergeMemTableMultiRows(piRow, uid, &pBlockScanInfo->iiter, pDelList, pResRow, pReader, freeTSRow);
3926
      } else if (((k.ts < ik.ts) && asc) || ((k.ts > ik.ts) && (!asc))) {
3927
        code = doMergeMemTableMultiRows(pRow, uid, &pBlockScanInfo->iter, pDelList, pResRow, pReader, freeTSRow);
3928
      }
3929
    } else {  // ik.ts == k.ts
3930
      *freeTSRow = true;
3931 3932
      pResRow->type = TSDBROW_ROW_FMT;
      code = doMergeMemIMemRows(pRow, piRow, pBlockScanInfo, pReader, &pResRow->pTSRow);
3933 3934 3935
      if (code != TSDB_CODE_SUCCESS) {
        return code;
      }
H
Haojun Liao 已提交
3936
    }
3937

3938
    return code;
H
Haojun Liao 已提交
3939 3940
  }

3941
  if (pBlockScanInfo->iter.hasVal && pRow != NULL) {
3942
    return doMergeMemTableMultiRows(pRow, pBlockScanInfo->uid, &pBlockScanInfo->iter, pDelList, pResRow, pReader,
H
Hongze Cheng 已提交
3943
                                    freeTSRow);
H
Haojun Liao 已提交
3944 3945
  }

3946
  if (pBlockScanInfo->iiter.hasVal && piRow != NULL) {
3947
    return doMergeMemTableMultiRows(piRow, uid, &pBlockScanInfo->iiter, pDelList, pResRow, pReader, freeTSRow);
H
Haojun Liao 已提交
3948 3949 3950 3951 3952
  }

  return TSDB_CODE_SUCCESS;
}

H
Hongze Cheng 已提交
3953
int32_t doAppendRowFromTSRow(SSDataBlock* pBlock, STsdbReader* pReader, SRow* pTSRow, STableBlockScanInfo* pScanInfo) {
H
Haojun Liao 已提交
3954
  int32_t outputRowIndex = pBlock->info.rows;
3955
  int64_t uid = pScanInfo->uid;
3956 3957 3958

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

3959
  SBlockLoadSuppInfo* pSupInfo = &pReader->suppInfo;
3960
  STSchema*           pSchema = doGetSchemaForTSRow(pTSRow->sver, pReader, uid);
3961

3962
  SColVal colVal = {0};
3963
  int32_t i = 0, j = 0;
H
Haojun Liao 已提交
3964

3965
  if (pSupInfo->colId[i] == PRIMARYKEY_TIMESTAMP_COL_ID) {
H
Haojun Liao 已提交
3966
    SColumnInfoData* pColData = taosArrayGet(pBlock->pDataBlock, pSupInfo->slotId[i]);
H
Haojun Liao 已提交
3967
    ((int64_t*)pColData->pData)[outputRowIndex] = pTSRow->ts;
3968 3969 3970
    i += 1;
  }

H
Haojun Liao 已提交
3971
  while (i < pSupInfo->numOfCols && j < pSchema->numOfCols) {
H
Haojun Liao 已提交
3972
    col_id_t colId = pSupInfo->colId[i];
3973 3974

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

H
Hongze Cheng 已提交
3977
      tRowGet(pTSRow, pSchema, j, &colVal);
H
Haojun Liao 已提交
3978
      doCopyColVal(pColInfoData, outputRowIndex, i, &colVal, pSupInfo);
3979 3980 3981
      i += 1;
      j += 1;
    } else if (colId < pSchema->columns[j].colId) {
H
Haojun Liao 已提交
3982
      SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, pSupInfo->slotId[i]);
H
Haojun Liao 已提交
3983

3984
      colDataSetNULL(pColInfoData, outputRowIndex);
3985 3986 3987
      i += 1;
    } else if (colId > pSchema->columns[j].colId) {
      j += 1;
3988
    }
3989 3990
  }

3991
  // set null value since current column does not exist in the "pSchema"
H
Haojun Liao 已提交
3992
  while (i < pSupInfo->numOfCols) {
H
Haojun Liao 已提交
3993
    SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, pSupInfo->slotId[i]);
3994
    colDataSetNULL(pColInfoData, outputRowIndex);
3995 3996 3997
    i += 1;
  }

3998
  pBlock->info.dataLoad = 1;
3999
  pBlock->info.rows += 1;
4000
  pScanInfo->lastKey = pTSRow->ts;
4001 4002 4003
  return TSDB_CODE_SUCCESS;
}

H
Hongze Cheng 已提交
4004 4005
int32_t doAppendRowFromFileBlock(SSDataBlock* pResBlock, STsdbReader* pReader, SBlockData* pBlockData,
                                 int32_t rowIndex) {
4006 4007 4008 4009
  int32_t i = 0, j = 0;
  int32_t outputRowIndex = pResBlock->info.rows;

  SBlockLoadSuppInfo* pSupInfo = &pReader->suppInfo;
4010
  if (pReader->suppInfo.colId[i] == PRIMARYKEY_TIMESTAMP_COL_ID) {
H
Haojun Liao 已提交
4011
    SColumnInfoData* pColData = taosArrayGet(pResBlock->pDataBlock, pSupInfo->slotId[i]);
H
Haojun Liao 已提交
4012
    ((int64_t*)pColData->pData)[outputRowIndex] = pBlockData->aTSKEY[rowIndex];
4013
    i += 1;
4014 4015 4016
  }

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

4020
  while (i < numOfOutputCols && j < numOfInputCols) {
H
Haojun Liao 已提交
4021
    SColData* pData = tBlockDataGetColDataByIdx(pBlockData, j);
H
Haojun Liao 已提交
4022
    if (pData->cid < pSupInfo->colId[i]) {
4023 4024 4025 4026
      j += 1;
      continue;
    }

H
Haojun Liao 已提交
4027 4028
    SColumnInfoData* pCol = TARRAY_GET_ELEM(pResBlock->pDataBlock, pSupInfo->slotId[i]);
    if (pData->cid == pSupInfo->colId[i]) {
4029 4030
      tColDataGetValue(pData, rowIndex, &cv);
      doCopyColVal(pCol, outputRowIndex, i, &cv, pSupInfo);
4031
      j += 1;
H
Haojun Liao 已提交
4032 4033
    } else if (pData->cid > pCol->info.colId) {
      // the specified column does not exist in file block, fill with null data
4034
      colDataSetNULL(pCol, outputRowIndex);
4035 4036 4037 4038 4039 4040
    }

    i += 1;
  }

  while (i < numOfOutputCols) {
H
Haojun Liao 已提交
4041
    SColumnInfoData* pCol = taosArrayGet(pResBlock->pDataBlock, pSupInfo->slotId[i]);
4042
    colDataSetNULL(pCol, outputRowIndex);
4043 4044 4045
    i += 1;
  }

4046
  pResBlock->info.dataLoad = 1;
4047 4048 4049 4050
  pResBlock->info.rows += 1;
  return TSDB_CODE_SUCCESS;
}

4051 4052
int32_t buildDataBlockFromBufImpl(STableBlockScanInfo* pBlockScanInfo, int64_t endKey, int32_t capacity,
                                  STsdbReader* pReader) {
H
Haojun Liao 已提交
4053 4054 4055
  SSDataBlock* pBlock = pReader->pResBlock;

  do {
4056
    //    SRow* pTSRow = NULL;
4057
    TSDBROW row = {.type = -1};
4058
    bool    freeTSRow = false;
4059 4060
    tsdbGetNextRowInMem(pBlockScanInfo, pReader, &row, endKey, &freeTSRow);
    if (row.type == -1) {
4061
      break;
H
Haojun Liao 已提交
4062 4063
    }

4064 4065
    if (row.type == TSDBROW_ROW_FMT) {
      doAppendRowFromTSRow(pBlock, pReader, row.pTSRow, pBlockScanInfo);
4066

4067 4068 4069 4070 4071
      if (freeTSRow) {
        taosMemoryFree(row.pTSRow);
      }
    } else {
      doAppendRowFromFileBlock(pBlock, pReader, row.pBlockData, row.iRow);
4072
    }
H
Haojun Liao 已提交
4073 4074

    // no data in buffer, return immediately
4075
    if (!(pBlockScanInfo->iter.hasVal || pBlockScanInfo->iiter.hasVal)) {
H
Haojun Liao 已提交
4076 4077 4078
      break;
    }

4079
    if (pBlock->info.rows >= capacity) {
H
Haojun Liao 已提交
4080 4081 4082 4083 4084 4085
      break;
    }
  } while (1);

  return TSDB_CODE_SUCCESS;
}
H
Hongze Cheng 已提交
4086

4087 4088
// TODO refactor: with createDataBlockScanInfo
int32_t tsdbSetTableList(STsdbReader* pReader, const void* pTableList, int32_t num) {
4089
  int32_t size = taosHashGetSize(pReader->status.pTableMap);
4090

4091
  STableBlockScanInfo** p = NULL;
4092
  while ((p = taosHashIterate(pReader->status.pTableMap, p)) != NULL) {
4093
    clearBlockScanInfo(*p);
4094 4095
  }

D
dapan1121 已提交
4096 4097 4098 4099 4100
  if (size < num) {
    int32_t code = ensureBlockScanInfoBuf(&pReader->blockInfoBuf, num);
    if (code) {
      return code;
    }
4101 4102
    pReader->status.uidList.tableUidList =
        (uint64_t*)taosMemoryRealloc(pReader->status.uidList.tableUidList, sizeof(uint64_t) * num);
D
dapan1121 已提交
4103
  }
4104

4105
  taosHashClear(pReader->status.pTableMap);
4106
  STableUidList* pUidList = &pReader->status.uidList;
H
Haojun Liao 已提交
4107
  pUidList->currentIndex = 0;
4108

4109 4110
  STableKeyInfo* pList = (STableKeyInfo*)pTableList;
  for (int32_t i = 0; i < num; ++i) {
4111 4112
    STableBlockScanInfo* pInfo = getPosInBlockInfoBuf(&pReader->blockInfoBuf, i);
    pInfo->uid = pList[i].uid;
H
Haojun Liao 已提交
4113 4114
    pUidList->tableUidList[i] = pList[i].uid;

4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125
    // todo extract method
    if (ASCENDING_TRAVERSE(pReader->order)) {
      int64_t skey = pReader->window.skey;
      pInfo->lastKey = (skey > INT64_MIN) ? (skey - 1) : skey;
      pInfo->lastKeyInStt = skey;
    } else {
      int64_t ekey = pReader->window.ekey;
      pInfo->lastKey = (ekey < INT64_MAX) ? (ekey + 1) : ekey;
      pInfo->lastKeyInStt = ekey;
    }

4126
    taosHashPut(pReader->status.pTableMap, &pInfo->uid, sizeof(uint64_t), &pInfo, POINTER_BYTES);
4127 4128
  }

H
Hongze Cheng 已提交
4129 4130 4131
  return TDB_CODE_SUCCESS;
}

dengyihao's avatar
dengyihao 已提交
4132 4133 4134 4135 4136 4137
void* tsdbGetIdx(SMeta* pMeta) {
  if (pMeta == NULL) {
    return NULL;
  }
  return metaGetIdx(pMeta);
}
dengyihao's avatar
dengyihao 已提交
4138

dengyihao's avatar
dengyihao 已提交
4139 4140 4141 4142 4143 4144
void* tsdbGetIvtIdx(SMeta* pMeta) {
  if (pMeta == NULL) {
    return NULL;
  }
  return metaGetIvtIdx(pMeta);
}
L
Liu Jicong 已提交
4145

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

4148
static int32_t doOpenReaderImpl(STsdbReader* pReader) {
4149 4150
  SReaderStatus*  pStatus = &pReader->status;
  SDataBlockIter* pBlockIter = &pStatus->blockIter;
4151

4152 4153
  initFilesetIterator(&pStatus->fileIter, pReader->pReadSnap->fs.aDFileSet, pReader);
  resetDataBlockIterator(&pStatus->blockIter, pReader->order);
4154

4155 4156 4157
  int32_t code = TSDB_CODE_SUCCESS;
  if (pStatus->fileIter.numOfFiles == 0) {
    pStatus->loadFromFile = false;
D
dapan1121 已提交
4158 4159
  } else if (READ_MODE_COUNT_ONLY == pReader->readMode) {
    // DO NOTHING
4160
  } else {
4161
    code = initForFirstBlockInFile(pReader, pBlockIter);
4162
  }
4163 4164 4165

  if (!pStatus->loadFromFile) {
    resetTableListIndex(pStatus);
4166
  }
4167 4168

  return code;
4169 4170
}

H
refact  
Hongze Cheng 已提交
4171
// ====================================== EXPOSED APIs ======================================
4172
int32_t tsdbReaderOpen(SVnode* pVnode, SQueryTableDataCond* pCond, void* pTableList, int32_t numOfTables,
H
Haojun Liao 已提交
4173
                       SSDataBlock* pResBlock, STsdbReader** ppReader, const char* idstr) {
4174 4175 4176 4177 4178 4179
  STimeWindow window = pCond->twindows;
  if (pCond->type == TIMEWINDOW_RANGE_EXTERNAL) {
    pCond->twindows.skey += 1;
    pCond->twindows.ekey -= 1;
  }

4180 4181 4182
  int32_t capacity = pVnode->config.tsdbCfg.maxRows;
  if (pResBlock != NULL) {
    blockDataEnsureCapacity(pResBlock, capacity);
H
Haojun Liao 已提交
4183 4184 4185
  }

  int32_t code = tsdbReaderCreate(pVnode, pCond, ppReader, capacity, pResBlock, idstr);
4186
  if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
4187 4188
    goto _err;
  }
H
Hongze Cheng 已提交
4189

4190
  // check for query time window
H
Haojun Liao 已提交
4191
  STsdbReader* pReader = *ppReader;
4192
  if (isEmptyQueryTimeWindow(&pReader->window) && pCond->type == TIMEWINDOW_RANGE_CONTAINED) {
H
Haojun Liao 已提交
4193 4194 4195
    tsdbDebug("%p query window not overlaps with the data set, no result returned, %s", pReader, pReader->idStr);
    return TSDB_CODE_SUCCESS;
  }
H
Hongze Cheng 已提交
4196

4197 4198
  if (pCond->type == TIMEWINDOW_RANGE_EXTERNAL) {
    // update the SQueryTableDataCond to create inner reader
4199
    int32_t order = pCond->order;
4200
    if (order == TSDB_ORDER_ASC) {
4201
      pCond->twindows.ekey = window.skey;
4202 4203 4204
      pCond->twindows.skey = INT64_MIN;
      pCond->order = TSDB_ORDER_DESC;
    } else {
4205
      pCond->twindows.skey = window.ekey;
4206 4207 4208 4209
      pCond->twindows.ekey = INT64_MAX;
      pCond->order = TSDB_ORDER_ASC;
    }

4210
    // here we only need one more row, so the capacity is set to be ONE.
H
Haojun Liao 已提交
4211
    code = tsdbReaderCreate(pVnode, pCond, &pReader->innerReader[0], 1, pResBlock, idstr);
4212 4213 4214 4215 4216
    if (code != TSDB_CODE_SUCCESS) {
      goto _err;
    }

    if (order == TSDB_ORDER_ASC) {
4217
      pCond->twindows.skey = window.ekey;
4218
      pCond->twindows.ekey = INT64_MAX;
4219
    } else {
4220
      pCond->twindows.skey = INT64_MIN;
4221
      pCond->twindows.ekey = window.ekey;
4222
    }
4223 4224
    pCond->order = order;

H
Haojun Liao 已提交
4225
    code = tsdbReaderCreate(pVnode, pCond, &pReader->innerReader[1], 1, pResBlock, idstr);
4226 4227 4228 4229 4230
    if (code != TSDB_CODE_SUCCESS) {
      goto _err;
    }
  }

H
Haojun Liao 已提交
4231
  // NOTE: the endVersion in pCond is the data version not schema version, so pCond->endVersion is not correct here.
4232 4233
  //  no valid error code set in metaGetTbTSchema, so let's set the error code here.
  //  we should proceed in case of tmq processing.
4234
  if (pCond->suid != 0) {
4235
    pReader->pSchema = metaGetTbTSchema(pReader->pTsdb->pVnode->pMeta, pReader->suid, -1, 1);
H
Haojun Liao 已提交
4236
    if (pReader->pSchema == NULL) {
H
Haojun Liao 已提交
4237
      tsdbError("failed to get table schema, suid:%" PRIu64 ", ver:-1, %s", pReader->suid, pReader->idStr);
H
Haojun Liao 已提交
4238
    }
4239 4240
  } else if (numOfTables > 0) {
    STableKeyInfo* pKey = pTableList;
4241
    pReader->pSchema = metaGetTbTSchema(pReader->pTsdb->pVnode->pMeta, pKey->uid, -1, 1);
H
Haojun Liao 已提交
4242
    if (pReader->pSchema == NULL) {
H
Haojun Liao 已提交
4243
      tsdbError("failed to get table schema, uid:%" PRIu64 ", ver:-1, %s", pKey->uid, pReader->idStr);
H
Haojun Liao 已提交
4244
    }
4245 4246
  }

4247
  if (pReader->pSchema != NULL) {
H
Haojun Liao 已提交
4248 4249 4250 4251
    code = updateBlockSMAInfo(pReader->pSchema, &pReader->suppInfo);
    if (code != TSDB_CODE_SUCCESS) {
      goto _err;
    }
4252
  }
4253

4254
  STsdbReader* p = (pReader->innerReader[0] != NULL) ? pReader->innerReader[0] : pReader;
X
Xiaoyu Wang 已提交
4255 4256
  pReader->status.pTableMap =
      createDataBlockScanInfo(p, &pReader->blockInfoBuf, pTableList, &pReader->status.uidList, numOfTables);
H
Haojun Liao 已提交
4257 4258
  if (pReader->status.pTableMap == NULL) {
    *ppReader = NULL;
S
Shengliang Guan 已提交
4259
    code = TSDB_CODE_OUT_OF_MEMORY;
H
Haojun Liao 已提交
4260 4261
    goto _err;
  }
H
Hongze Cheng 已提交
4262

4263
  pReader->suspended = true;
4264

D
dapan1121 已提交
4265 4266 4267
  
  pReader->readMode = READ_MODE_COUNT_ONLY;

4268
  tsdbDebug("%p total numOfTable:%d in this query %s", pReader, numOfTables, pReader->idStr);
H
Hongze Cheng 已提交
4269
  return code;
H
Hongze Cheng 已提交
4270 4271

_err:
H
Haojun Liao 已提交
4272
  tsdbError("failed to create data reader, code:%s %s", tstrerror(code), idstr);
4273
  tsdbReaderClose(pReader);
X
Xiaoyu Wang 已提交
4274
  *ppReader = NULL;  // reset the pointer value.
H
Hongze Cheng 已提交
4275
  return code;
H
refact  
Hongze Cheng 已提交
4276 4277 4278
}

void tsdbReaderClose(STsdbReader* pReader) {
4279 4280
  if (pReader == NULL) {
    return;
4281
  }
H
refact  
Hongze Cheng 已提交
4282

4283
  tsdbAcquireReader(pReader);
4284
  {
H
Haojun Liao 已提交
4285
    if (pReader->innerReader[0] != NULL || pReader->innerReader[1] != NULL) {
4286
      STsdbReader* p = pReader->innerReader[0];
4287

4288
      p->status.pTableMap = NULL;
H
Haojun Liao 已提交
4289
      p->status.uidList.tableUidList = NULL;
4290 4291 4292 4293 4294 4295 4296
      p->pReadSnap = NULL;
      p->pSchema = NULL;
      p->pMemSchema = NULL;

      p = pReader->innerReader[1];

      p->status.pTableMap = NULL;
H
Haojun Liao 已提交
4297
      p->status.uidList.tableUidList = NULL;
4298 4299 4300
      p->pReadSnap = NULL;
      p->pSchema = NULL;
      p->pMemSchema = NULL;
4301 4302 4303 4304 4305 4306

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

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

4309
  taosArrayDestroy(pSupInfo->pColAgg);
H
Haojun Liao 已提交
4310
  for (int32_t i = 0; i < pSupInfo->numOfCols; ++i) {
4311 4312 4313 4314
    if (pSupInfo->buildBuf[i] != NULL) {
      taosMemoryFreeClear(pSupInfo->buildBuf[i]);
    }
  }
4315

H
Haojun Liao 已提交
4316 4317 4318
  if (pReader->freeBlock) {
    pReader->pResBlock = blockDataDestroy(pReader->pResBlock);
  }
4319

H
Haojun Liao 已提交
4320
  taosMemoryFree(pSupInfo->colId);
H
Hongze Cheng 已提交
4321
  tBlockDataDestroy(&pReader->status.fileBlockData);
4322
  cleanupDataBlockIterator(&pReader->status.blockIter);
4323 4324

  size_t numOfTables = taosHashGetSize(pReader->status.pTableMap);
H
Haojun Liao 已提交
4325 4326 4327 4328
  if (pReader->status.pTableMap != NULL) {
    destroyAllBlockScanInfo(pReader->status.pTableMap);
    clearBlockScanInfoBuf(&pReader->blockInfoBuf);
  }
4329

H
Haojun Liao 已提交
4330 4331 4332
  if (pReader->pFileReader != NULL) {
    tsdbDataFReaderClose(&pReader->pFileReader);
  }
H
refact  
Hongze Cheng 已提交
4333

4334 4335 4336 4337 4338 4339 4340 4341 4342
  if (pReader->pDelFReader != NULL) {
    tsdbDelFReaderClose(&pReader->pDelFReader);
  }

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

4343
  qTrace("tsdb/reader-close: %p, untake snapshot", pReader);
4344
  tsdbUntakeReadSnap(pReader, pReader->pReadSnap, true);
4345
  pReader->pReadSnap = NULL;
4346

4347 4348
  tsdbReleaseReader(pReader);

4349
  tsdbUninitReaderLock(pReader);
4350

4351
  taosMemoryFree(pReader->status.uidList.tableUidList);
H
Haojun Liao 已提交
4352
  SIOCostSummary* pCost = &pReader->cost;
4353

H
Haojun Liao 已提交
4354 4355
  SFilesetIter* pFilesetIter = &pReader->status.fileIter;
  if (pFilesetIter->pLastBlockReader != NULL) {
H
Haojun Liao 已提交
4356 4357
    SLastBlockReader* pLReader = pFilesetIter->pLastBlockReader;
    tMergeTreeClose(&pLReader->mergeTree);
H
Haojun Liao 已提交
4358

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

H
Haojun Liao 已提交
4361 4362 4363
    pLReader->pInfo = destroyLastBlockLoadInfo(pLReader->pInfo);
    taosMemoryFree(pLReader);
  }
H
refact  
Hongze Cheng 已提交
4364

4365 4366 4367 4368 4369
  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 已提交
4370 4371
      ", composed-blocks-time:%.2fms, STableBlockScanInfo size:%.2f Kb, createTime:%.2f ms,initDelSkylineIterTime:%.2f "
      "ms, %s",
4372 4373 4374
      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 已提交
4375
      pCost->initDelSkylineIterTime, pReader->idStr);
H
refact  
Hongze Cheng 已提交
4376

4377 4378
  taosMemoryFree(pReader->idStr);
  taosMemoryFree(pReader->pSchema);
4379

4380 4381 4382
  if (pReader->pMemSchema != pReader->pSchema) {
    taosMemoryFree(pReader->pMemSchema);
  }
4383

4384
  taosMemoryFreeClear(pReader);
H
refact  
Hongze Cheng 已提交
4385 4386
}

4387 4388 4389 4390 4391 4392 4393 4394 4395 4396
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) {
H
Haojun Liao 已提交
4397
      pBlockScanInfo = getTableBlockScanInfo(pStatus->pTableMap, pBlockInfo->uid, pReader->idStr);
4398 4399 4400 4401
      if (pBlockScanInfo == NULL) {
        goto _err;
      }
    } else {
4402
      pBlockScanInfo = *pStatus->pTableIter;
4403 4404 4405 4406 4407
    }

    tsdbDataFReaderClose(&pReader->pFileReader);

    // resetDataBlockScanInfo excluding lastKey
4408
    STableBlockScanInfo** p = NULL;
4409 4410

    while ((p = taosHashIterate(pStatus->pTableMap, p)) != NULL) {
4411 4412 4413 4414 4415 4416 4417 4418
      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);
4419 4420
      }

4421 4422 4423 4424 4425 4426
      if (pInfo->iiter.iter != NULL) {
        pInfo->iiter.iter = tsdbTbDataIterDestroy(pInfo->iiter.iter);
      }

      pInfo->delSkyline = taosArrayDestroy(pInfo->delSkyline);
      // pInfo->lastKey = ts;
4427 4428
    }
  } else {
4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450
    // 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;
    }

4451
    pBlockScanInfo = pStatus->pTableIter == NULL ? NULL : *pStatus->pTableIter;
4452 4453 4454 4455 4456 4457 4458
    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;
4459 4460
      pBlockScanInfo->iter.hasVal = false;
      pBlockScanInfo->iiter.hasVal = false;
4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475
      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);
    }
  }

4476
  tsdbUntakeReadSnap(pReader, pReader->pReadSnap, false);
4477
  pReader->pReadSnap = NULL;
4478 4479 4480

  pReader->suspended = true;

4481 4482
  tsdbDebug("reader: %p suspended uid %" PRIu64 " in this query %s", pReader, pBlockScanInfo ? pBlockScanInfo->uid : 0,
            pReader->idStr);
4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493
  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;

4494
  code = tsdbTryAcquireReader(pReader);
4495 4496
  if (code == 0) {
    if (pReader->suspended) {
4497
      tsdbReleaseReader(pReader);
4498 4499 4500 4501
      return code;
    }

    tsdbReaderSuspend(pReader);
4502

4503
    tsdbReleaseReader(pReader);
4504

4505
    return code;
4506 4507 4508
  } else if (code == EBUSY) {
    return TSDB_CODE_VND_QUERY_BUSY;
  } else {
4509 4510
    terrno = TAOS_SYSTEM_ERROR(code);
    return TSDB_CODE_FAILED;
4511 4512 4513 4514 4515 4516
  }
}

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

4517
  STableBlockScanInfo** pBlockScanInfo = pReader->status.pTableIter;
4518 4519 4520

  //  restore reader's state
  //  task snapshot
4521
  int32_t numOfTables = taosHashGetSize(pReader->status.pTableMap);
4522
  if (numOfTables > 0) {
4523
    qTrace("tsdb/reader: %p, take snapshot", pReader);
4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540
    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 已提交
4541
      pPrevReader->status.uidList = pReader->status.uidList;
4542 4543 4544 4545 4546 4547
      pPrevReader->pSchema = pReader->pSchema;
      pPrevReader->pMemSchema = pReader->pMemSchema;
      pPrevReader->pReadSnap = pReader->pReadSnap;

      pNextReader->capacity = 1;
      pNextReader->status.pTableMap = pReader->status.pTableMap;
X
Xiaoyu Wang 已提交
4548
      pNextReader->status.uidList = pReader->status.uidList;
4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561
      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;

4562 4563
  tsdbDebug("reader: %p resumed uid %" PRIu64 ", numOfTable:%" PRId32 ", in this query %s", pReader,
            pBlockScanInfo ? (*pBlockScanInfo)->uid : 0, numOfTables, pReader->idStr);
4564 4565 4566 4567 4568 4569 4570
  return code;

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

D
dapan1121 已提交
4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599
static bool tsdbReadRowsCountOnly(STsdbReader* pReader) {
  int32_t code =  TSDB_CODE_SUCCESS;
  SSDataBlock* pBlock = pReader->pResBlock;

  while (1) {
    if (pReader->status.loadFromFile == false) {
      break;
    }
  
    code = readRowsCountFromFile(pReader);
    if (code != TSDB_CODE_SUCCESS) {
      return false;
    }

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

  pBlock->info.rows = pReader->rowsNum;
  pBlock->info.id.uid = 0;
  pBlock->info.dataLoad = 0;
  
  pReader->rowsNum = 0;
  
  return pBlock->info.rows > 0;
}

4600
static bool doTsdbNextDataBlock(STsdbReader* pReader) {
H
Haojun Liao 已提交
4601
  // cleanup the data that belongs to the previous data block
4602 4603
  SSDataBlock* pBlock = pReader->pResBlock;
  blockDataCleanup(pBlock);
H
Hongze Cheng 已提交
4604

4605
  SReaderStatus* pStatus = &pReader->status;
4606
  if (taosHashGetSize(pStatus->pTableMap) == 0) {
4607 4608
    return false;
  }
H
Haojun Liao 已提交
4609

D
dapan1121 已提交
4610 4611 4612 4613
  if (READ_MODE_COUNT_ONLY == pReader->readMode) {
    return tsdbReadRowsCountOnly(pReader);
  }

4614 4615 4616 4617 4618
  if (pStatus->loadFromFile) {
    int32_t code = buildBlockFromFiles(pReader);
    if (code != TSDB_CODE_SUCCESS) {
      return false;
    }
4619

4620 4621 4622
    if (pBlock->info.rows > 0) {
      return true;
    } else {
4623
      resetTableListIndex(&pReader->status);
H
Haojun Liao 已提交
4624
      buildBlockFromBufferSequentially(pReader);
4625
      return pBlock->info.rows > 0;
H
Haojun Liao 已提交
4626
    }
4627 4628 4629
  } else {  // no data in files, let's try the buffer
    buildBlockFromBufferSequentially(pReader);
    return pBlock->info.rows > 0;
H
Haojun Liao 已提交
4630
  }
H
refact  
Hongze Cheng 已提交
4631 4632
}

4633
bool tsdbNextDataBlock(STsdbReader* pReader) {
4634
  if (isEmptyQueryTimeWindow(&pReader->window) || pReader->step == EXTERNAL_ROWS_NEXT) {
4635 4636 4637
    return false;
  }

4638 4639
  SReaderStatus* pStatus = &pReader->status;

4640 4641 4642
  int32_t code = tsdbAcquireReader(pReader);
  qTrace("tsdb/read: %p, take read mutex, code: %d", pReader, code);

4643 4644 4645 4646
  if (pReader->suspended) {
    tsdbReaderResume(pReader);
  }

4647
  if (pReader->innerReader[0] != NULL && pReader->step == 0) {
4648
    bool ret = doTsdbNextDataBlock(pReader->innerReader[0]);
4649
    pReader->step = EXTERNAL_ROWS_PREV;
4650
    if (ret) {
4651
      pStatus = &pReader->innerReader[0]->status;
4652
      if (pStatus->composedDataBlock) {
4653
        qTrace("tsdb/read: %p, unlock read mutex", pReader);
4654
        tsdbReleaseReader(pReader);
4655 4656
      }

4657 4658
      return ret;
    }
4659
  }
4660

4661
  if (pReader->step == EXTERNAL_ROWS_PREV) {
4662
    // prepare for the main scan
4663 4664 4665
    code = doOpenReaderImpl(pReader);
    int32_t step = 1;
    resetAllDataBlockScanInfo(pReader->status.pTableMap, pReader->innerReader[0]->window.ekey, step);
4666 4667 4668 4669 4670

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

4671
    pReader->step = EXTERNAL_ROWS_MAIN;
4672 4673 4674 4675
  }

  bool ret = doTsdbNextDataBlock(pReader);
  if (ret) {
4676
    if (pStatus->composedDataBlock) {
4677
      qTrace("tsdb/read: %p, unlock read mutex", pReader);
4678
      tsdbReleaseReader(pReader);
4679 4680
    }

4681 4682 4683
    return ret;
  }

4684
  if (pReader->step == EXTERNAL_ROWS_MAIN && pReader->innerReader[1] != NULL) {
4685
    // prepare for the next row scan
4686 4687 4688
    int32_t step = -1;
    code = doOpenReaderImpl(pReader->innerReader[1]);
    resetAllDataBlockScanInfo(pReader->innerReader[1]->status.pTableMap, pReader->window.ekey, step);
4689 4690 4691 4692
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

4693
    ret = doTsdbNextDataBlock(pReader->innerReader[1]);
4694
    pReader->step = EXTERNAL_ROWS_NEXT;
4695
    if (ret) {
4696
      pStatus = &pReader->innerReader[1]->status;
4697
      if (pStatus->composedDataBlock) {
4698
        qTrace("tsdb/read: %p, unlock read mutex", pReader);
4699
        tsdbReleaseReader(pReader);
4700 4701
      }

4702
      return ret;
4703 4704 4705
    }
  }

4706
  qTrace("tsdb/read: %p, unlock read mutex", pReader);
4707
  tsdbReleaseReader(pReader);
4708

4709 4710 4711
  return false;
}

4712
static void doFillNullColSMA(SBlockLoadSuppInfo* pSup, int32_t numOfRows, int32_t numOfCols, SColumnDataAgg* pTsAgg) {
4713 4714
  // do fill all null column value SMA info
  int32_t i = 0, j = 0;
4715
  int32_t size = (int32_t)taosArrayGetSize(pSup->pColAgg);
4716
  taosArrayInsert(pSup->pColAgg, 0, pTsAgg);
4717
  size++;
4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728

  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};
4729
        taosArrayInsert(pSup->pColAgg, i, &nullColAgg);
4730
        i += 1;
D
dapan1121 已提交
4731
        size++;
4732 4733 4734 4735
      }
      j += 1;
    }
  }
4736 4737 4738 4739 4740 4741 4742 4743 4744

  while (j < numOfCols) {
    if (pSup->colId[j] != PRIMARYKEY_TIMESTAMP_COL_ID) {
      SColumnDataAgg nullColAgg = {.colId = pSup->colId[j], .numOfNull = numOfRows};
      taosArrayInsert(pSup->pColAgg, i, &nullColAgg);
      i += 1;
    }
    j++;
  }
4745 4746
}

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

H
Hongze Cheng 已提交
4750
  int32_t code = 0;
4751
  *allHave = false;
H
Haojun Liao 已提交
4752
  *pBlockSMA = NULL;
H
Hongze Cheng 已提交
4753

4754
  if (pReader->type == TIMEWINDOW_RANGE_EXTERNAL) {
4755 4756 4757
    return TSDB_CODE_SUCCESS;
  }

4758
  // there is no statistics data for composed block
4759
  if (pReader->status.composedDataBlock || (!pReader->suppInfo.smaValid)) {
4760 4761
    return TSDB_CODE_SUCCESS;
  }
H
Hongze Cheng 已提交
4762

4763
  SFileDataBlockInfo* pFBlock = getCurrentBlockInfo(&pReader->status.blockIter);
4764 4765
  SBlockLoadSuppInfo* pSup = &pReader->suppInfo;

H
Haojun Liao 已提交
4766 4767 4768
  if (pReader->pResBlock->info.id.uid != pFBlock->uid) {
    return TSDB_CODE_SUCCESS;
  }
4769

D
dapan1121 已提交
4770 4771
  int64_t st = taosGetTimestampUs();

4772
  SDataBlk* pBlock = getCurrentBlock(&pReader->status.blockIter);
H
Hongze Cheng 已提交
4773
  if (tDataBlkHasSma(pBlock)) {
H
Hongze Cheng 已提交
4774
    code = tsdbReadBlockSma(pReader->pFileReader, pBlock, pSup->pColAgg);
4775
    if (code != TSDB_CODE_SUCCESS) {
4776 4777
      tsdbDebug("vgId:%d, failed to load block SMA for uid %" PRIu64 ", code:%s, %s", 0, pFBlock->uid, tstrerror(code),
                pReader->idStr);
4778 4779
      return code;
    }
4780
  } else {
H
Haojun Liao 已提交
4781
    *pBlockSMA = NULL;
4782
    return TSDB_CODE_SUCCESS;
4783
  }
H
Hongze Cheng 已提交
4784

4785
  *allHave = true;
H
Hongze Cheng 已提交
4786

4787 4788
  // always load the first primary timestamp column data
  SColumnDataAgg* pTsAgg = &pSup->tsColAgg;
4789

4790 4791
  pTsAgg->numOfNull = 0;
  pTsAgg->colId = PRIMARYKEY_TIMESTAMP_COL_ID;
4792 4793 4794 4795
  pTsAgg->min = pReader->pResBlock->info.window.skey;
  pTsAgg->max = pReader->pResBlock->info.window.ekey;

  // update the number of NULL data rows
4796
  size_t numOfCols = pSup->numOfCols;
4797

4798
  // ensure capacity
H
Haojun Liao 已提交
4799 4800 4801
  if (pDataBlock->pDataBlock) {
    size_t colsNum = taosArrayGetSize(pDataBlock->pDataBlock);
    taosArrayEnsureCap(pSup->pColAgg, colsNum);
4802 4803
  }

4804 4805 4806
  SSDataBlock* pResBlock = pReader->pResBlock;
  if (pResBlock->pBlockAgg == NULL) {
    size_t num = taosArrayGetSize(pResBlock->pDataBlock);
H
Haojun Liao 已提交
4807
    pResBlock->pBlockAgg = taosMemoryCalloc(num, POINTER_BYTES);
4808
  }
4809

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

H
Haojun Liao 已提交
4814
  int32_t i = 0, j = 0;
4815
  while (j < numOfCols && i < size) {
4816
    SColumnDataAgg* pAgg = taosArrayGet(pSup->pColAgg, i);
H
Haojun Liao 已提交
4817 4818
    if (pAgg->colId == pSup->colId[j]) {
      pResBlock->pBlockAgg[pSup->slotId[j]] = pAgg;
4819 4820
      i += 1;
      j += 1;
H
Haojun Liao 已提交
4821
    } else if (pAgg->colId < pSup->colId[j]) {
4822
      i += 1;
H
Haojun Liao 已提交
4823
    } else if (pSup->colId[j] < pAgg->colId) {
4824 4825
      pResBlock->pBlockAgg[pSup->slotId[j]] = NULL;
      *allHave = false;
4826 4827 4828 4829
      j += 1;
    }
  }

H
Haojun Liao 已提交
4830
  *pBlockSMA = pResBlock->pBlockAgg;
4831
  pReader->cost.smaDataLoad += 1;
4832

D
dapan1121 已提交
4833 4834 4835
  double elapsedTime = (taosGetTimestampUs() - st) / 1000.0;
  pReader->cost.smaLoadTime += elapsedTime;

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

H
Haojun Liao 已提交
4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851
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 已提交
4852
static SSDataBlock* doRetrieveDataBlock(STsdbReader* pReader) {
4853
  SReaderStatus*       pStatus = &pReader->status;
H
Haojun Liao 已提交
4854
  SFileDataBlockInfo*  pBlockInfo = getCurrentBlockInfo(&pStatus->blockIter);
H
Haojun Liao 已提交
4855
  STableBlockScanInfo* pBlockScanInfo = getTableBlockScanInfo(pStatus->pTableMap, pBlockInfo->uid, pReader->idStr);
H
Haojun Liao 已提交
4856
  if (pBlockScanInfo == NULL) {
4857
    return NULL;
4858 4859
  }

4860
  int32_t code = doLoadFileBlockData(pReader, &pStatus->blockIter, &pStatus->fileBlockData, pBlockScanInfo->uid);
4861
  if (code != TSDB_CODE_SUCCESS) {
H
Hongze Cheng 已提交
4862
    tBlockDataDestroy(&pStatus->fileBlockData);
4863 4864
    terrno = code;
    return NULL;
4865
  }
4866

4867
  copyBlockDataToSDataBlock(pReader);
H
Haojun Liao 已提交
4868
  return pReader->pResBlock;
H
Hongze Cheng 已提交
4869 4870
}

H
Haojun Liao 已提交
4871
SSDataBlock* tsdbRetrieveDataBlock(STsdbReader* pReader, SArray* pIdList) {
4872
  STsdbReader* pTReader = pReader;
4873 4874
  if (pReader->type == TIMEWINDOW_RANGE_EXTERNAL) {
    if (pReader->step == EXTERNAL_ROWS_PREV) {
4875
      pTReader = pReader->innerReader[0];
4876
    } else if (pReader->step == EXTERNAL_ROWS_NEXT) {
4877
      pTReader = pReader->innerReader[1];
4878 4879 4880
    }
  }

4881 4882 4883 4884 4885 4886 4887
  SReaderStatus* pStatus = &pTReader->status;
  if (pStatus->composedDataBlock) {
    return pTReader->pResBlock;
  }

  SSDataBlock* ret = doRetrieveDataBlock(pTReader);

4888
  qTrace("tsdb/read-retrieve: %p, unlock read mutex", pReader);
4889
  tsdbReleaseReader(pReader);
4890 4891

  return ret;
4892 4893
}

H
Haojun Liao 已提交
4894
int32_t tsdbReaderReset(STsdbReader* pReader, SQueryTableDataCond* pCond) {
4895
  qTrace("tsdb/reader-reset: %p, take read mutex", pReader);
4896
  tsdbAcquireReader(pReader);
L
Liu Jicong 已提交
4897 4898 4899 4900 4901

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

H
Haojun Liao 已提交
4902
  if (isEmptyQueryTimeWindow(&pReader->window) || pReader->pReadSnap == NULL) {
4903
    tsdbDebug("tsdb reader reset return %p, %s", pReader->pReadSnap, pReader->idStr);
4904
    tsdbReleaseReader(pReader);
4905 4906
    return TSDB_CODE_SUCCESS;
  }
H
Hongze Cheng 已提交
4907

H
Haojun Liao 已提交
4908 4909
  SReaderStatus* pStatus = &pReader->status;
  SDataBlockIter* pBlockIter = &pStatus->blockIter;
4910

L
Liu Jicong 已提交
4911
  pReader->order = pCond->order;
4912
  pReader->type = TIMEWINDOW_RANGE_CONTAINED;
H
Haojun Liao 已提交
4913 4914
  pStatus->loadFromFile = true;
  pStatus->pTableIter = NULL;
H
Haojun Liao 已提交
4915
  pReader->window = updateQueryTimeWindow(pReader->pTsdb, &pCond->twindows);
H
Hongze Cheng 已提交
4916

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

4920
  pReader->suppInfo.tsColAgg.colId = PRIMARYKEY_TIMESTAMP_COL_ID;
4921
  tsdbDataFReaderClose(&pReader->pFileReader);
4922

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

H
Haojun Liao 已提交
4925
  initFilesetIterator(&pStatus->fileIter, pReader->pReadSnap->fs.aDFileSet, pReader);
4926
  resetDataBlockIterator(pBlockIter, pReader->order);
H
Haojun Liao 已提交
4927
  resetTableListIndex(&pReader->status);
H
Haojun Liao 已提交
4928

4929 4930 4931 4932
  bool asc = ASCENDING_TRAVERSE(pReader->order);
  int32_t step = asc? 1:-1;
  int64_t ts = asc? pReader->window.skey - 1 : pReader->window.ekey + 1;
  resetAllDataBlockScanInfo(pStatus->pTableMap, ts, step);
4933

4934
  int32_t code = 0;
4935

4936
  // no data in files, let's try buffer in memory
H
Haojun Liao 已提交
4937 4938
  if (pStatus->fileIter.numOfFiles == 0) {
    pStatus->loadFromFile = false;
4939
    resetTableListIndex(pStatus);
4940 4941 4942
  } else {
    code = initForFirstBlockInFile(pReader, pBlockIter);
    if (code != TSDB_CODE_SUCCESS) {
4943 4944
      tsdbError("%p reset reader failed, numOfTables:%d, query range:%" PRId64 " - %" PRId64 " in query %s", pReader,
                numOfTables, pReader->window.skey, pReader->window.ekey, pReader->idStr);
4945

4946
      tsdbReleaseReader(pReader);
4947 4948 4949
      return code;
    }
  }
H
Hongze Cheng 已提交
4950

H
Hongze Cheng 已提交
4951 4952 4953 4954
  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);
4955

4956
  tsdbReleaseReader(pReader);
4957

4958
  return code;
H
Hongze Cheng 已提交
4959
}
H
Hongze Cheng 已提交
4960

4961 4962 4963 4964 4965 4966
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;
4967
}
H
Hongze Cheng 已提交
4968

4969 4970 4971 4972
int32_t tsdbGetFileBlocksDistInfo(STsdbReader* pReader, STableBlockDistInfo* pTableBlockInfo) {
  int32_t code = TSDB_CODE_SUCCESS;
  pTableBlockInfo->totalSize = 0;
  pTableBlockInfo->totalRows = 0;
4973
  pTableBlockInfo->numOfVgroups = 1;
H
Hongze Cheng 已提交
4974

4975
  const int32_t numOfBucket = 20.0;
dengyihao's avatar
dengyihao 已提交
4976

4977
  // find the start data block in file
dengyihao's avatar
dengyihao 已提交
4978 4979 4980 4981
  tsdbAcquireReader(pReader);
  if (pReader->suspended) {
    tsdbReaderResume(pReader);
  }
4982
  SReaderStatus* pStatus = &pReader->status;
H
Hongze Cheng 已提交
4983

4984 4985 4986
  STsdbCfg* pc = &pReader->pTsdb->pVnode->config.tsdbCfg;
  pTableBlockInfo->defMinRows = pc->minRows;
  pTableBlockInfo->defMaxRows = pc->maxRows;
H
Hongze Cheng 已提交
4987

H
Haojun Liao 已提交
4988
  int32_t bucketRange = ceil(((double)(pc->maxRows - pc->minRows)) / numOfBucket);
H
Hongze Cheng 已提交
4989

4990
  pTableBlockInfo->numOfFiles += 1;
H
Hongze Cheng 已提交
4991

4992 4993
  int32_t numOfTables = (int32_t)taosHashGetSize(pStatus->pTableMap);
  int     defaultRows = 4096;
H
Hongze Cheng 已提交
4994

4995 4996
  SDataBlockIter* pBlockIter = &pStatus->blockIter;
  pTableBlockInfo->numOfFiles += pStatus->fileIter.numOfFiles;
H
Haojun Liao 已提交
4997

4998 4999
  if (pBlockIter->numOfBlocks > 0) {
    pTableBlockInfo->numOfBlocks += pBlockIter->numOfBlocks;
H
Haojun Liao 已提交
5000
  }
H
Hongze Cheng 已提交
5001

5002
  pTableBlockInfo->numOfTables = numOfTables;
5003
  bool hasNext = (pBlockIter->numOfBlocks > 0);
H
Hongze Cheng 已提交
5004

5005 5006
  while (true) {
    if (hasNext) {
H
Hongze Cheng 已提交
5007
      SDataBlk* pBlock = getCurrentBlock(pBlockIter);
H
Hongze Cheng 已提交
5008

5009 5010
      int32_t numOfRows = pBlock->nRow;
      pTableBlockInfo->totalRows += numOfRows;
H
Hongze Cheng 已提交
5011

5012 5013 5014
      if (numOfRows > pTableBlockInfo->maxRows) {
        pTableBlockInfo->maxRows = numOfRows;
      }
H
refact  
Hongze Cheng 已提交
5015

5016 5017 5018
      if (numOfRows < pTableBlockInfo->minRows) {
        pTableBlockInfo->minRows = numOfRows;
      }
H
refact  
Hongze Cheng 已提交
5019

5020 5021 5022
      if (numOfRows < defaultRows) {
        pTableBlockInfo->numOfSmallBlocks += 1;
      }
H
refact  
Hongze Cheng 已提交
5023

5024
      pTableBlockInfo->totalSize += pBlock->aSubBlock[0].szBlock;
5025

5026
      int32_t bucketIndex = getBucketIndex(pTableBlockInfo->defMinRows, bucketRange, numOfRows, numOfBucket);
5027
      pTableBlockInfo->blockRowsHisto[bucketIndex]++;
5028

H
Haojun Liao 已提交
5029
      hasNext = blockIteratorNext(&pStatus->blockIter, pReader->idStr);
5030 5031
    } else {
      code = initForFirstBlockInFile(pReader, pBlockIter);
H
Haojun Liao 已提交
5032
      if ((code != TSDB_CODE_SUCCESS) || (pStatus->loadFromFile == false)) {
5033 5034
        break;
      }
H
refact  
Hongze Cheng 已提交
5035

5036 5037
      pTableBlockInfo->numOfBlocks += pBlockIter->numOfBlocks;
      hasNext = (pBlockIter->numOfBlocks > 0);
5038
    }
H
refact  
Hongze Cheng 已提交
5039

H
Hongze Cheng 已提交
5040 5041
    //    tsdbDebug("%p %d blocks found in file for %d table(s), fid:%d, %s", pReader, numOfBlocks, numOfTables,
    //              pReader->pFileGroup->fid, pReader->idStr);
5042
  }
dengyihao's avatar
dengyihao 已提交
5043
  tsdbReleaseReader(pReader);
H
refact  
Hongze Cheng 已提交
5044 5045
  return code;
}
H
Hongze Cheng 已提交
5046

H
refact  
Hongze Cheng 已提交
5047
int64_t tsdbGetNumOfRowsInMemTable(STsdbReader* pReader) {
5048
  int64_t rows = 0;
H
Hongze Cheng 已提交
5049

5050
  SReaderStatus* pStatus = &pReader->status;
5051
  tsdbAcquireReader(pReader);
5052 5053 5054 5055
  if (pReader->suspended) {
    tsdbReaderResume(pReader);
  }

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

5058
  while (pStatus->pTableIter != NULL) {
5059
    STableBlockScanInfo* pBlockScanInfo = *(STableBlockScanInfo**)pStatus->pTableIter;
5060 5061

    STbData* d = NULL;
5062
    if (pReader->pReadSnap->pMem != NULL) {
H
Hongze Cheng 已提交
5063
      d = tsdbGetTbDataFromMemTable(pReader->pReadSnap->pMem, pReader->suid, pBlockScanInfo->uid);
5064 5065 5066 5067 5068 5069
      if (d != NULL) {
        rows += tsdbGetNRowsInTbData(d);
      }
    }

    STbData* di = NULL;
5070
    if (pReader->pReadSnap->pIMem != NULL) {
H
Hongze Cheng 已提交
5071
      di = tsdbGetTbDataFromMemTable(pReader->pReadSnap->pIMem, pReader->suid, pBlockScanInfo->uid);
5072 5073 5074 5075 5076 5077 5078 5079
      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 已提交
5080

5081
  tsdbReleaseReader(pReader);
5082

H
refact  
Hongze Cheng 已提交
5083
  return rows;
H
Hongze Cheng 已提交
5084
}
D
dapan1121 已提交
5085

L
Liu Jicong 已提交
5086
int32_t tsdbGetTableSchema(SVnode* pVnode, int64_t uid, STSchema** pSchema, int64_t* suid) {
D
dapan1121 已提交
5087 5088 5089 5090
  int32_t sversion = 1;

  SMetaReader mr = {0};
  metaReaderInit(&mr, pVnode->pMeta, 0);
H
Haojun Liao 已提交
5091
  int32_t code = metaGetTableEntryByUidCache(&mr, uid);
D
dapan1121 已提交
5092 5093 5094 5095 5096 5097 5098
  if (code != TSDB_CODE_SUCCESS) {
    terrno = TSDB_CODE_TDB_INVALID_TABLE_ID;
    metaReaderClear(&mr);
    return terrno;
  }

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

D
dapan1121 已提交
5100
  if (mr.me.type == TSDB_CHILD_TABLE) {
D
dapan1121 已提交
5101
    tDecoderClear(&mr.coder);
D
dapan1121 已提交
5102
    *suid = mr.me.ctbEntry.suid;
H
Haojun Liao 已提交
5103
    code = metaGetTableEntryByUidCache(&mr, *suid);
D
dapan1121 已提交
5104 5105 5106 5107 5108 5109
    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 已提交
5110
  } else if (mr.me.type == TSDB_NORMAL_TABLE) {
D
dapan1121 已提交
5111
    sversion = mr.me.ntbEntry.schemaRow.version;
H
Haojun Liao 已提交
5112 5113 5114 5115
  } else {
    terrno = TSDB_CODE_INVALID_PARA;
    metaReaderClear(&mr);
    return terrno;
D
dapan1121 已提交
5116 5117 5118
  }

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

D
dapan1121 已提交
5121 5122
  return TSDB_CODE_SUCCESS;
}
H
Hongze Cheng 已提交
5123

H
Hongze Cheng 已提交
5124
int32_t tsdbTakeReadSnap(STsdbReader* pReader, _query_reseek_func_t reseek, STsdbReadSnap** ppSnap) {
H
Hongze Cheng 已提交
5125 5126 5127
  int32_t        code = 0;
  STsdb*         pTsdb = pReader->pTsdb;
  SVersionRange* pRange = &pReader->verRange;
H
Hongze Cheng 已提交
5128 5129

  // alloc
H
Hongze Cheng 已提交
5130 5131
  STsdbReadSnap* pSnap = (STsdbReadSnap*)taosMemoryCalloc(1, sizeof(*pSnap));
  if (pSnap == NULL) {
H
Hongze Cheng 已提交
5132 5133 5134 5135 5136
    code = TSDB_CODE_OUT_OF_MEMORY;
    goto _exit;
  }

  // lock
H
Hongze Cheng 已提交
5137
  taosThreadRwlockRdlock(&pTsdb->rwLock);
H
Hongze Cheng 已提交
5138 5139

  // take snapshot
H
Hongze Cheng 已提交
5140
  if (pTsdb->mem && (pRange->minVer <= pTsdb->mem->maxVer && pRange->maxVer >= pTsdb->mem->minVer)) {
H
Hongze Cheng 已提交
5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151
    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 已提交
5152 5153
  }

H
Hongze Cheng 已提交
5154
  if (pTsdb->imem && (pRange->minVer <= pTsdb->imem->maxVer && pRange->maxVer >= pTsdb->imem->minVer)) {
H
Hongze Cheng 已提交
5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165
    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 已提交
5166 5167
  }

H
Hongze Cheng 已提交
5168
  // fs
H
Hongze Cheng 已提交
5169
  code = tsdbFSRef(pTsdb, &pSnap->fs);
H
Hongze Cheng 已提交
5170 5171 5172 5173
  if (code) {
    taosThreadRwlockUnlock(&pTsdb->rwLock);
    goto _exit;
  }
H
Hongze Cheng 已提交
5174 5175

  // unlock
H
Hongze Cheng 已提交
5176
  taosThreadRwlockUnlock(&pTsdb->rwLock);
H
Hongze Cheng 已提交
5177

5178
  tsdbTrace("vgId:%d, take read snapshot", TD_VID(pTsdb->pVnode));
H
Hongze Cheng 已提交
5179

H
Hongze Cheng 已提交
5180
_exit:
H
Hongze Cheng 已提交
5181 5182 5183 5184 5185 5186 5187 5188 5189 5190
  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 已提交
5191 5192 5193
  return code;
}

5194
void tsdbUntakeReadSnap(STsdbReader* pReader, STsdbReadSnap* pSnap, bool proactive) {
H
Hongze Cheng 已提交
5195 5196
  STsdb* pTsdb = pReader->pTsdb;

H
Hongze Cheng 已提交
5197 5198
  if (pSnap) {
    if (pSnap->pMem) {
5199
      tsdbUnrefMemTable(pSnap->pMem, pSnap->pNode, proactive);
H
Hongze Cheng 已提交
5200 5201 5202
    }

    if (pSnap->pIMem) {
5203
      tsdbUnrefMemTable(pSnap->pIMem, pSnap->pINode, proactive);
H
Hongze Cheng 已提交
5204 5205
    }

H
Hongze Cheng 已提交
5206
    tsdbFSUnref(pTsdb, &pSnap->fs);
H
Hongze Cheng 已提交
5207 5208
    if (pSnap->pNode) taosMemoryFree(pSnap->pNode);
    if (pSnap->pINode) taosMemoryFree(pSnap->pINode);
H
Hongze Cheng 已提交
5209
    taosMemoryFree(pSnap);
H
Hongze Cheng 已提交
5210
  }
5211
  tsdbTrace("vgId:%d, untake read snapshot", TD_VID(pTsdb->pVnode));
H
Hongze Cheng 已提交
5212
}
5213 5214 5215 5216 5217

// if failed, do nothing
void tsdbReaderSetId(STsdbReader* pReader, const char* idstr) {
  taosMemoryFreeClear(pReader->idStr);
  pReader->idStr = taosStrdup(idstr);
5218
}