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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

typedef struct SReaderStatus {
dengyihao's avatar
dengyihao 已提交
131 132
  bool                 loadFromFile;  // check file stage
  SHashObj*            pTableMap;     // SHash<STableBlockScanInfo>
133
  STableBlockScanInfo* pTableIter;    // table iterator used in building in-memory buffer data blocks.
134
  SFileBlockDumpInfo   fBlockDumpInfo;
135 136 137 138 139
  SDFileSet*           pCurrentFileset;  // current opened file set
  SBlockData           fileBlockData;
  SFilesetIter         fileIter;
  SDataBlockIter       blockIter;
  bool                 composedDataBlock;  // the returned data block is a composed block or not
H
Haojun Liao 已提交
140 141
} SReaderStatus;

H
Hongze Cheng 已提交
142
struct STsdbReader {
H
Haojun Liao 已提交
143 144 145 146 147 148 149
  STsdb*             pTsdb;
  uint64_t           suid;
  int16_t            order;
  STimeWindow        window;  // the primary query time window that applies to all queries
  SSDataBlock*       pResBlock;
  int32_t            capacity;
  SReaderStatus      status;
150 151
  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 已提交
152
  SBlockLoadSuppInfo suppInfo;
H
Hongze Cheng 已提交
153
  STsdbReadSnap*     pReadSnap;
154
  SIOCostSummary     cost;
155 156
  STSchema*          pSchema;     // the newest version schema
  STSchema*          pMemSchema;  // the previous schema for in-memory data, to avoid load schema too many times
157 158
  SDataFReader*      pFileReader;
  SVersionRange      verRange;
159

160 161
  int32_t      step;
  STsdbReader* innerReader[2];
H
Hongze Cheng 已提交
162
};
H
Hongze Cheng 已提交
163

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

dengyihao's avatar
dengyihao 已提交
179
static void doMergeMultiRows(TSDBROW* pRow, uint64_t uid, SIterInfo* pIter, SArray* pDelList, STSRow** pTSRow,
180
                             STsdbReader* pReader, bool* freeTSRow);
181 182
static void doMergeMemIMemRows(TSDBROW* pRow, TSDBROW* piRow, STableBlockScanInfo* pBlockScanInfo, STsdbReader* pReader,
                               STSRow** pTSRow);
dengyihao's avatar
dengyihao 已提交
183 184 185 186
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);
187
static SVersionRange getQueryVerRange(SVnode* pVnode, SQueryTableDataCond* pCond, int8_t level);
188
static int64_t getCurrentKeyInLastBlock(SLastBlockReader* pLastBlockReader);
189 190
static bool    hasDataInLastBlock(SLastBlockReader* pLastBlockReader);
static int32_t doBuildDataBlock(STsdbReader* pReader);
H
Haojun Liao 已提交
191

192 193 194
static int32_t setColumnIdSlotList(STsdbReader* pReader, SSDataBlock* pBlock) {
  SBlockLoadSuppInfo* pSupInfo = &pReader->suppInfo;

195
  size_t numOfCols = blockDataGetNumOfCols(pBlock);
196

197
  pSupInfo->colIds = taosMemoryMalloc(numOfCols * sizeof(int16_t));
198
  pSupInfo->buildBuf = taosMemoryCalloc(numOfCols, POINTER_BYTES);
199 200 201
  if (pSupInfo->buildBuf == NULL || pSupInfo->colIds == NULL) {
    taosMemoryFree(pSupInfo->colIds);
    taosMemoryFree(pSupInfo->buildBuf);
H
Haojun Liao 已提交
202 203
    return TSDB_CODE_OUT_OF_MEMORY;
  }
H
Hongze Cheng 已提交
204

H
Haojun Liao 已提交
205 206
  for (int32_t i = 0; i < numOfCols; ++i) {
    SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, i);
207
    pSupInfo->colIds[i] = pCol->info.colId;
208 209 210 211

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

H
Haojun Liao 已提交
214 215
  return TSDB_CODE_SUCCESS;
}
H
Hongze Cheng 已提交
216

217
static SHashObj* createDataBlockScanInfo(STsdbReader* pTsdbReader, const STableKeyInfo* idList, int32_t numOfTables) {
H
Haojun Liao 已提交
218
  // allocate buffer in order to load data blocks from file
219
  // todo use simple hash instead, optimize the memory consumption
220 221 222
  SHashObj* pTableMap =
      taosHashInit(numOfTables, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT), false, HASH_NO_LOCK);
  if (pTableMap == NULL) {
H
Haojun Liao 已提交
223 224 225
    return NULL;
  }

226
  for (int32_t j = 0; j < numOfTables; ++j) {
227
    STableBlockScanInfo info = {.lastKey = 0, .uid = idList[j].uid, .indexInBlockL = DEFAULT_ROW_INDEX_VAL};
228 229 230
    if (ASCENDING_TRAVERSE(pTsdbReader->order)) {
      if (info.lastKey == INT64_MIN || info.lastKey < pTsdbReader->window.skey) {
        info.lastKey = pTsdbReader->window.skey;
H
Haojun Liao 已提交
231 232
      }

233
      ASSERT(info.lastKey >= pTsdbReader->window.skey && info.lastKey <= pTsdbReader->window.ekey);
wmmhello's avatar
wmmhello 已提交
234
    } else {
235
      info.lastKey = pTsdbReader->window.skey;
H
Haojun Liao 已提交
236
    }
wmmhello's avatar
wmmhello 已提交
237

238 239 240
    taosHashPut(pTableMap, &info.uid, sizeof(uint64_t), &info, sizeof(info));
    tsdbDebug("%p check table uid:%" PRId64 " from lastKey:%" PRId64 " %s", pTsdbReader, info.uid, info.lastKey,
              pTsdbReader->idStr);
H
Haojun Liao 已提交
241 242
  }

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

246
  return pTableMap;
H
Hongze Cheng 已提交
247
}
H
Hongze Cheng 已提交
248

249 250 251
static void resetDataBlockScanInfo(SHashObj* pTableMap) {
  STableBlockScanInfo* p = NULL;

dengyihao's avatar
dengyihao 已提交
252
  while ((p = taosHashIterate(pTableMap, p)) != NULL) {
253 254
    p->iterInit = false;
    p->iiter.hasVal = false;
dengyihao's avatar
dengyihao 已提交
255
    if (p->iter.iter != NULL) {
256
      p->iter.iter = tsdbTbDataIterDestroy(p->iter.iter);
257 258
    }

259
    p->delSkyline = taosArrayDestroy(p->delSkyline);
260 261 262
  }
}

263 264 265 266 267 268 269 270
static void destroyBlockScanInfo(SHashObj* pTableMap) {
  STableBlockScanInfo* p = NULL;

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

    if (p->iter.iter != NULL) {
271
      p->iter.iter = tsdbTbDataIterDestroy(p->iter.iter);
272 273 274
    }

    if (p->iiter.iter != NULL) {
275
      p->iiter.iter = tsdbTbDataIterDestroy(p->iiter.iter);
276 277
    }

278 279
    p->delSkyline = taosArrayDestroy(p->delSkyline);
    p->pBlockList = taosArrayDestroy(p->pBlockList);
280
    tMapDataClear(&p->mapData);
281 282 283 284 285
  }

  taosHashCleanup(pTableMap);
}

286
static bool isEmptyQueryTimeWindow(STimeWindow* pWindow) {
287 288
  ASSERT(pWindow != NULL);
  return pWindow->skey > pWindow->ekey;
H
Haojun Liao 已提交
289
}
H
Hongze Cheng 已提交
290

291 292 293
// 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 已提交
294
  STsdbKeepCfg* pCfg = &pTsdb->keepCfg;
H
Hongze Cheng 已提交
295

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

dengyihao's avatar
dengyihao 已提交
299
  STimeWindow win = *pWindow;
300 301 302 303 304 305
  if (win.skey < earilyTs) {
    win.skey = earilyTs;
  }

  return win;
}
H
Hongze Cheng 已提交
306

H
Haojun Liao 已提交
307
static void limitOutputBufferSize(const SQueryTableDataCond* pCond, int32_t* capacity) {
H
Haojun Liao 已提交
308 309 310 311 312 313
  int32_t rowLen = 0;
  for (int32_t i = 0; i < pCond->numOfCols; ++i) {
    rowLen += pCond->colList[i].bytes;
  }

  // make sure the output SSDataBlock size be less than 2MB.
H
Haojun Liao 已提交
314 315 316
  const int32_t TWOMB = 2 * 1024 * 1024;
  if ((*capacity) * rowLen > TWOMB) {
    (*capacity) = TWOMB / rowLen;
H
Haojun Liao 已提交
317 318 319 320
  }
}

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

324 325
  pIter->index = ASCENDING_TRAVERSE(pReader->order) ? -1 : numOfFileset;
  pIter->order = pReader->order;
H
Hongze Cheng 已提交
326
  pIter->pFileList = aDFileSet;
327
  pIter->numOfFiles = numOfFileset;
H
Haojun Liao 已提交
328

329 330 331 332
  if (pIter->pLastBlockReader == NULL) {
    pIter->pLastBlockReader = taosMemoryCalloc(1, sizeof(struct SLastBlockReader));
    if (pIter->pLastBlockReader == NULL) {
      int32_t code = TSDB_CODE_OUT_OF_MEMORY;
333
      tsdbError("failed to prepare the last block iterator, code:%d %s", tstrerror(code), pReader->idStr);
334 335 336
      return code;
    }

337 338 339 340 341
    SLastBlockReader* pLReader = pIter->pLastBlockReader;
    pLReader->pBlockL = taosArrayInit(4, sizeof(SBlockL));
    pLReader->order   = pReader->order;
    pLReader->window  = pReader->window;
    pLReader->verRange = pReader->verRange;
342
    pLReader->currentBlockIndex = -1;
H
Haojun Liao 已提交
343 344 345 346 347

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

350
  tsdbDebug("init fileset iterator, total files:%d %s", pIter->numOfFiles, pReader->idStr);
H
Haojun Liao 已提交
351 352 353
  return TSDB_CODE_SUCCESS;
}

354
static bool filesetIteratorNext(SFilesetIter* pIter, STsdbReader* pReader) {
355 356
  bool    asc = ASCENDING_TRAVERSE(pIter->order);
  int32_t step = asc ? 1 : -1;
357 358 359
  pIter->index += step;

  if ((asc && pIter->index >= pIter->numOfFiles) || ((!asc) && pIter->index < 0)) {
H
Haojun Liao 已提交
360 361 362 363 364
    return false;
  }

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

366
  while (1) {
H
Haojun Liao 已提交
367 368 369
    if (pReader->pFileReader != NULL) {
      tsdbDataFReaderClose(&pReader->pFileReader);
    }
370

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

373 374 375 376
    int32_t code = tsdbDataFReaderOpen(&pReader->pFileReader, pReader->pTsdb, pReader->status.pCurrentFileset);
    if (code != TSDB_CODE_SUCCESS) {
      goto _err;
    }
H
Haojun Liao 已提交
377

378 379
    pReader->cost.headFileLoad += 1;

380 381 382 383 384 385 386 387 388 389 390 391
    int32_t fid = pReader->status.pCurrentFileset->fid;
    tsdbFidKeyRange(fid, pReader->pTsdb->keepCfg.days, pReader->pTsdb->keepCfg.precision, &win.skey, &win.ekey);

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

    if ((asc && (win.ekey < pReader->window.skey)) || ((!asc) && (win.skey > pReader->window.ekey))) {
      pIter->index += step;
392 393 394
      if ((asc && pIter->index >= pIter->numOfFiles) || ((!asc) && pIter->index < 0)) {
        return false;
      }
395 396
      continue;
    }
C
Cary Xu 已提交
397

398
    tsdbDebug("%p file found fid:%d for qrange:%" PRId64 "-%" PRId64 ", %s", pReader, fid, pReader->window.skey,
399
              pReader->window.ekey, pReader->idStr);
400 401
    return true;
  }
402

403
_err:
H
Haojun Liao 已提交
404 405 406
  return false;
}

407
static void resetDataBlockIterator(SDataBlockIter* pIter, int32_t order, SHashObj* pTableMap) {
408 409
  pIter->order = order;
  pIter->index = -1;
410
  pIter->numOfBlocks = 0;
411 412 413 414 415
  if (pIter->blockList == NULL) {
    pIter->blockList = taosArrayInit(4, sizeof(SFileDataBlockInfo));
  } else {
    taosArrayClear(pIter->blockList);
  }
416
  pIter->pTableMap = pTableMap;
417 418
}

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

H
Haojun Liao 已提交
421
static void initReaderStatus(SReaderStatus* pStatus) {
dengyihao's avatar
dengyihao 已提交
422 423
  pStatus->pTableIter = NULL;
  pStatus->loadFromFile = true;
H
Haojun Liao 已提交
424 425
}

426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
static SSDataBlock* createResBlock(SQueryTableDataCond* pCond, int32_t capacity) {
  SSDataBlock* pResBlock = createDataBlock();
  if (pResBlock == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

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

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

  return pResBlock;
}

449 450
static int32_t tsdbReaderCreate(SVnode* pVnode, SQueryTableDataCond* pCond, STsdbReader** ppReader, int32_t capacity,
                                const char* idstr) {
H
Haojun Liao 已提交
451
  int32_t      code = 0;
452
  int8_t       level = 0;
H
Haojun Liao 已提交
453
  STsdbReader* pReader = (STsdbReader*)taosMemoryCalloc(1, sizeof(*pReader));
H
Hongze Cheng 已提交
454 455
  if (pReader == NULL) {
    code = TSDB_CODE_OUT_OF_MEMORY;
H
Haojun Liao 已提交
456
    goto _end;
H
Hongze Cheng 已提交
457 458
  }

C
Cary Xu 已提交
459 460 461 462
  if (VND_IS_TSMA(pVnode)) {
    tsdbDebug("vgId:%d, tsma is selected to query", TD_VID(pVnode));
  }

H
Haojun Liao 已提交
463
  initReaderStatus(&pReader->status);
464

L
Liu Jicong 已提交
465
  pReader->pTsdb = getTsdbByRetentions(pVnode, pCond->twindows.skey, pVnode->config.tsdbCfg.retentions, idstr, &level);
dengyihao's avatar
dengyihao 已提交
466 467
  pReader->suid = pCond->suid;
  pReader->order = pCond->order;
468
  pReader->capacity = 4096;
dengyihao's avatar
dengyihao 已提交
469 470
  pReader->idStr = (idstr != NULL) ? strdup(idstr) : NULL;
  pReader->verRange = getQueryVerRange(pVnode, pCond, level);
471
  pReader->type = pCond->type;
472
  pReader->window = updateQueryTimeWindow(pReader->pTsdb, &pCond->twindows);
473

474
  ASSERT(pCond->numOfCols > 0);
H
Hongze Cheng 已提交
475

476
  limitOutputBufferSize(pCond, &pReader->capacity);
477

478 479
  // allocate buffer in order to load data blocks from file
  SBlockLoadSuppInfo* pSup = &pReader->suppInfo;
480
  pSup->pColAgg = taosArrayInit(4, sizeof(SColumnDataAgg));
481
  pSup->plist = taosMemoryCalloc(pCond->numOfCols, POINTER_BYTES);
482
  if (pSup->pColAgg == NULL || pSup->plist == NULL) {
483 484 485
    code = TSDB_CODE_OUT_OF_MEMORY;
    goto _end;
  }
H
Haojun Liao 已提交
486

487 488
  pSup->tsColAgg.colId = PRIMARYKEY_TIMESTAMP_COL_ID;

H
Hongze Cheng 已提交
489
  code = tBlockDataCreate(&pReader->status.fileBlockData);
H
Haojun Liao 已提交
490 491 492 493 494
  if (code != TSDB_CODE_SUCCESS) {
    terrno = code;
    goto _end;
  }

495 496 497 498
  pReader->pResBlock = createResBlock(pCond, pReader->capacity);
  if (pReader->pResBlock == NULL) {
    code = terrno;
    goto _end;
H
Hongze Cheng 已提交
499
  }
H
Hongze Cheng 已提交
500

501 502
  setColumnIdSlotList(pReader, pReader->pResBlock);

H
Hongze Cheng 已提交
503 504
  *ppReader = pReader;
  return code;
H
Hongze Cheng 已提交
505

H
Haojun Liao 已提交
506 507
_end:
  tsdbReaderClose(pReader);
H
Hongze Cheng 已提交
508 509 510
  *ppReader = NULL;
  return code;
}
H
Hongze Cheng 已提交
511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543

// void tsdbResetQueryHandleForNewTable(STsdbReader* queryHandle, SQueryTableDataCond* pCond, STableListInfo* tableList,
//                                      int32_t tWinIdx) {
//   STsdbReader* pTsdbReadHandle = queryHandle;

//   pTsdbReadHandle->order = pCond->order;
//   pTsdbReadHandle->window = pCond->twindows[tWinIdx];
//   pTsdbReadHandle->type = TSDB_QUERY_TYPE_ALL;
//   pTsdbReadHandle->cur.fid = -1;
//   pTsdbReadHandle->cur.win = TSWINDOW_INITIALIZER;
//   pTsdbReadHandle->checkFiles = true;
//   pTsdbReadHandle->activeIndex = 0;  // current active table index
//   pTsdbReadHandle->locateStart = false;
//   pTsdbReadHandle->loadExternalRow = pCond->loadExternalRows;

//   if (ASCENDING_TRAVERSE(pCond->order)) {
//     assert(pTsdbReadHandle->window.skey <= pTsdbReadHandle->window.ekey);
//   } else {
//     assert(pTsdbReadHandle->window.skey >= pTsdbReadHandle->window.ekey);
//   }

//   // allocate buffer in order to load data blocks from file
//   memset(pTsdbReadHandle->suppInfo.pstatis, 0, sizeof(SColumnDataAgg));
//   memset(pTsdbReadHandle->suppInfo.plist, 0, POINTER_BYTES);

//   tsdbInitDataBlockLoadInfo(&pTsdbReadHandle->dataBlockLoadInfo);
//   tsdbInitCompBlockLoadInfo(&pTsdbReadHandle->compBlockLoadInfo);

//   SArray* pTable = NULL;
//   //  STsdbMeta* pMeta = tsdbGetMeta(pTsdbReadHandle->pTsdb);

//   //  pTsdbReadHandle->pTableCheckInfo = destroyTableCheckInfo(pTsdbReadHandle->pTableCheckInfo);

H
Haojun Liao 已提交
544
//   pTsdbReadHandle->pTableCheckInfo = NULL;  // createDataBlockScanInfo(pTsdbReadHandle, groupList, pMeta,
H
Hongze Cheng 已提交
545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567
//                                             // &pTable);
//   if (pTsdbReadHandle->pTableCheckInfo == NULL) {
//     //    tsdbReaderClose(pTsdbReadHandle);
//     terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
//   }

//   //  pTsdbReadHandle->prev = doFreeColumnInfoData(pTsdbReadHandle->prev);
//   //  pTsdbReadHandle->next = doFreeColumnInfoData(pTsdbReadHandle->next);
// }

// SArray* tsdbGetQueriedTableList(STsdbReader** pHandle) {
//   assert(pHandle != NULL);

//   STsdbReader* pTsdbReadHandle = (STsdbReader*)pHandle;

//   size_t  size = taosArrayGetSize(pTsdbReadHandle->pTableCheckInfo);
//   SArray* res = taosArrayInit(size, POINTER_BYTES);
//   return res;
// }

// static int32_t binarySearchForBlock(SBlock* pBlock, int32_t numOfBlocks, TSKEY skey, int32_t order) {
//   int32_t firstSlot = 0;
//   int32_t lastSlot = numOfBlocks - 1;
H
Hongze Cheng 已提交
568

H
Hongze Cheng 已提交
569
//   int32_t midSlot = firstSlot;
H
Hongze Cheng 已提交
570

H
Hongze Cheng 已提交
571 572 573
//   while (1) {
//     numOfBlocks = lastSlot - firstSlot + 1;
//     midSlot = (firstSlot + (numOfBlocks >> 1));
H
Hongze Cheng 已提交
574

H
Hongze Cheng 已提交
575
//     if (numOfBlocks == 1) break;
H
Hongze Cheng 已提交
576

H
Hongze Cheng 已提交
577 578 579 580 581 582 583 584 585 586 587
//     if (skey > pBlock[midSlot].maxKey.ts) {
//       if (numOfBlocks == 2) break;
//       if ((order == TSDB_ORDER_DESC) && (skey < pBlock[midSlot + 1].minKey.ts)) break;
//       firstSlot = midSlot + 1;
//     } else if (skey < pBlock[midSlot].minKey.ts) {
//       if ((order == TSDB_ORDER_ASC) && (skey > pBlock[midSlot - 1].maxKey.ts)) break;
//       lastSlot = midSlot - 1;
//     } else {
//       break;  // got the slot
//     }
//   }
H
Hongze Cheng 已提交
588

H
Hongze Cheng 已提交
589 590
//   return midSlot;
// }
H
Hongze Cheng 已提交
591

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

595
  int64_t st = taosGetTimestampUs();
H
Hongze Cheng 已提交
596
  int32_t code = tsdbReadBlockIdx(pFileReader, aBlockIdx);
H
Haojun Liao 已提交
597
  if (code != TSDB_CODE_SUCCESS) {
598
    goto _end;
H
Haojun Liao 已提交
599
  }
H
Hongze Cheng 已提交
600

601 602
  size_t num = taosArrayGetSize(aBlockIdx);
  if (num == 0) {
H
Haojun Liao 已提交
603
    taosArrayDestroy(aBlockIdx);
H
Haojun Liao 已提交
604 605
    return TSDB_CODE_SUCCESS;
  }
H
Hongze Cheng 已提交
606

607 608 609 610
  int64_t et1 = taosGetTimestampUs();

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

613
    // uid check
H
Hongze Cheng 已提交
614
    if (pBlockIdx->suid != pReader->suid) {
H
Haojun Liao 已提交
615 616 617 618
      continue;
    }

    // this block belongs to a table that is not queried.
H
Hongze Cheng 已提交
619
    void* p = taosHashGet(pReader->status.pTableMap, &pBlockIdx->uid, sizeof(uint64_t));
H
Haojun Liao 已提交
620 621 622 623 624 625
    if (p == NULL) {
      continue;
    }

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

H
Hongze Cheng 已提交
629
    taosArrayPush(pIndexList, pBlockIdx);
H
Haojun Liao 已提交
630
  }
H
Hongze Cheng 已提交
631

632
  int64_t et2 = taosGetTimestampUs();
633
  tsdbDebug("load block index for %d tables completed, elapsed time:%.2f ms, set blockIdx:%.2f ms, size:%.2f Kb %s",
634
            (int32_t)num, (et1 - st) / 1000.0, (et2 - et1) / 1000.0, num * sizeof(SBlockIdx) / 1024.0, pReader->idStr);
635 636 637

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

638
_end:
H
Hongze Cheng 已提交
639
  taosArrayDestroy(aBlockIdx);
H
Haojun Liao 已提交
640 641
  return code;
}
H
Hongze Cheng 已提交
642

643
static void cleanupTableScanInfo(SHashObj* pTableMap) {
644
  STableBlockScanInfo* px = NULL;
dengyihao's avatar
dengyihao 已提交
645
  while (1) {
646
    px = taosHashIterate(pTableMap, px);
647 648 649 650
    if (px == NULL) {
      break;
    }

651 652
    // reset the index in last block when handing a new file
    px->indexInBlockL = -1;
653
    tMapDataClear(&px->mapData);
654 655
    taosArrayClear(px->pBlockList);
  }
656 657 658 659 660 661 662 663 664 665
}

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

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

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

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

672
    tMapDataReset(&pScanInfo->mapData);
H
Hongze Cheng 已提交
673
    tsdbReadBlock(pReader->pFileReader, pBlockIdx, &pScanInfo->mapData);
674

675
    sizeInDisk += pScanInfo->mapData.nData;
676
    for (int32_t j = 0; j < pScanInfo->mapData.nItem; ++j) {
H
Haojun Liao 已提交
677
      SBlock block = {0};
678
      tMapDataGetItemByIdx(&pScanInfo->mapData, j, &block, tGetBlock);
H
Hongze Cheng 已提交
679

680
      // 1. time range check
681
      if (block.minKey.ts > pReader->window.ekey || block.maxKey.ts < pReader->window.skey) {
H
Haojun Liao 已提交
682 683
        continue;
      }
H
Hongze Cheng 已提交
684

685
      // 2. version range check
H
Hongze Cheng 已提交
686
      if (block.minVer > pReader->verRange.maxVer || block.maxVer < pReader->verRange.minVer) {
687 688
        continue;
      }
689

690
      void* p = taosArrayPush(pScanInfo->pBlockList, &j);
H
Haojun Liao 已提交
691
      if (p == NULL) {
692
        tMapDataClear(&pScanInfo->mapData);
H
Haojun Liao 已提交
693 694
        return TSDB_CODE_OUT_OF_MEMORY;
      }
695

696
      pBlockNum->numOfBlocks += 1;
H
Haojun Liao 已提交
697
    }
H
Hongze Cheng 已提交
698

H
Haojun Liao 已提交
699
    if (pScanInfo->pBlockList != NULL && taosArrayGetSize(pScanInfo->pBlockList) > 0) {
700 701 702 703 704 705 706 707 708 709 710 711
      numOfQTable += 1;
    }
  }

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

    {
712 713 714 715
      // 1. time range check
      if (pLastBlock->minKey > pReader->window.ekey || pLastBlock->maxKey < pReader->window.skey) {
        continue;
      }
716 717 718 719 720 721 722

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

      pBlockNum->numOfLastBlocks += 1;
723
      taosArrayPush(pQualifiedLastBlock, pLastBlock);
H
Haojun Liao 已提交
724 725
    }
  }
H
Hongze Cheng 已提交
726

727 728
  int32_t total = pBlockNum->numOfLastBlocks + pBlockNum->numOfBlocks;

729
  double el = (taosGetTimestampUs() - st) / 1000.0;
730
  tsdbDebug("load block of %d tables completed, blocks:%d in %d tables, lastBlock:%d, size:%.2f Kb, elapsed time:%.2f ms %s",
731 732
            numOfTables, total, numOfQTable, pBlockNum->numOfLastBlocks, sizeInDisk
            / 1000.0, el, pReader->idStr);
733

734
  pReader->cost.numOfBlocks += total;
735
  pReader->cost.headFileLoadTime += el;
736

H
Haojun Liao 已提交
737 738
  return TSDB_CODE_SUCCESS;
}
H
Hongze Cheng 已提交
739

740
static void setBlockAllDumped(SFileBlockDumpInfo* pDumpInfo, int64_t maxKey, int32_t order) {
741
  int32_t step = ASCENDING_TRAVERSE(order) ? 1 : -1;
742
  pDumpInfo->allDumped = true;
743
  pDumpInfo->lastKey = maxKey + step;
H
Haojun Liao 已提交
744 745
}

746 747
static void doCopyColVal(SColumnInfoData* pColInfoData, int32_t rowIndex, int32_t colIndex, SColVal* pColVal,
                         SBlockLoadSuppInfo* pSup) {
H
Haojun Liao 已提交
748
  if (IS_VAR_DATA_TYPE(pColVal->type)) {
749
    if (pColVal->isNull || pColVal->isNone) {
H
Haojun Liao 已提交
750 751 752
      colDataAppendNULL(pColInfoData, rowIndex);
    } else {
      varDataSetLen(pSup->buildBuf[colIndex], pColVal->value.nData);
H
Haojun Liao 已提交
753
      ASSERT(pColVal->value.nData <= pColInfoData->info.bytes);
H
Haojun Liao 已提交
754 755 756 757
      memcpy(varDataVal(pSup->buildBuf[colIndex]), pColVal->value.pData, pColVal->value.nData);
      colDataAppend(pColInfoData, rowIndex, pSup->buildBuf[colIndex], false);
    }
  } else {
758
    colDataAppend(pColInfoData, rowIndex, (const char*)&pColVal->value, pColVal->isNull || pColVal->isNone);
H
Haojun Liao 已提交
759
  }
H
Haojun Liao 已提交
760 761
}

762
static SFileDataBlockInfo* getCurrentBlockInfo(SDataBlockIter* pBlockIter) {
763 764
  if (taosArrayGetSize(pBlockIter->blockList) == 0) {
    ASSERT(pBlockIter->numOfBlocks == taosArrayGetSize(pBlockIter->blockList));
765 766
    return NULL;
  }
767 768 769

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

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

774
static int32_t copyBlockDataToSDataBlock(STsdbReader* pReader, STableBlockScanInfo* pBlockScanInfo) {
775
  SReaderStatus*  pStatus = &pReader->status;
776
  SDataBlockIter* pBlockIter = &pStatus->blockIter;
H
Hongze Cheng 已提交
777

778
  SBlockData*         pBlockData = &pStatus->fileBlockData;
H
Haojun Liao 已提交
779
  SFileDataBlockInfo* pFBlock = getCurrentBlockInfo(pBlockIter);
780
  SBlock*             pBlock = getCurrentBlock(pBlockIter);
H
Haojun Liao 已提交
781
  SSDataBlock*        pResBlock = pReader->pResBlock;
782
  int32_t             numOfOutputCols = blockDataGetNumOfCols(pResBlock);
H
Haojun Liao 已提交
783

H
Haojun Liao 已提交
784
  SBlockLoadSuppInfo* pSupInfo = &pReader->suppInfo;
785
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;
H
Haojun Liao 已提交
786

H
Haojun Liao 已提交
787
  SColVal cv = {0};
788
  int64_t st = taosGetTimestampUs();
789 790
  bool    asc = ASCENDING_TRAVERSE(pReader->order);
  int32_t step = asc ? 1 : -1;
791

792
  int32_t rowIndex = 0;
793 794
  int32_t remain = asc ? (pBlockData->nRow - pDumpInfo->rowIndex) : (pDumpInfo->rowIndex + 1);

795 796 797 798 799 800 801 802
  int32_t endIndex = 0;
  if (remain <= pReader->capacity) {
    endIndex = pBlockData->nRow;
  } else {
    endIndex = pDumpInfo->rowIndex + step * pReader->capacity;
    remain = pReader->capacity;
  }

803
  int32_t          i = 0;
804 805
  SColumnInfoData* pColData = taosArrayGet(pResBlock->pDataBlock, i);
  if (pColData->info.colId == PRIMARYKEY_TIMESTAMP_COL_ID) {
806
    for (int32_t j = pDumpInfo->rowIndex; j < endIndex && j >= 0; j += step) {
807 808 809 810 811
      colDataAppend(pColData, rowIndex++, (const char*)&pBlockData->aTSKEY[j], false);
    }
    i += 1;
  }

812 813 814
  int32_t colIndex = 0;
  int32_t num = taosArrayGetSize(pBlockData->aIdx);
  while (i < numOfOutputCols && colIndex < num) {
815 816 817
    rowIndex = 0;
    pColData = taosArrayGet(pResBlock->pDataBlock, i);

H
Hongze Cheng 已提交
818
    SColData* pData = tBlockDataGetColDataByIdx(pBlockData, colIndex);
819 820 821
    if (pData->cid < pColData->info.colId) {
      colIndex += 1;
    } else if (pData->cid == pColData->info.colId) {
822
      for (int32_t j = pDumpInfo->rowIndex; j < endIndex && j >= 0; j += step) {
823 824
        tColDataGetValue(pData, j, &cv);
        doCopyColVal(pColData, rowIndex++, i, &cv, pSupInfo);
H
Haojun Liao 已提交
825
      }
826
      colIndex += 1;
827
      i += 1;
828
      ASSERT(rowIndex == remain);
829 830
    } else {  // the specified column does not exist in file block, fill with null data
      colDataAppendNNULL(pColData, 0, remain);
831
      i += 1;
H
Haojun Liao 已提交
832
    }
833 834
  }

835
  while (i < numOfOutputCols) {
836 837 838
    pColData = taosArrayGet(pResBlock->pDataBlock, i);
    colDataAppendNNULL(pColData, 0, remain);
    i += 1;
H
Haojun Liao 已提交
839
  }
H
Haojun Liao 已提交
840

841
  pResBlock->info.rows = remain;
842
  pDumpInfo->rowIndex += step * remain;
843

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

846
  double elapsedTime = (taosGetTimestampUs() - st) / 1000.0;
H
Haojun Liao 已提交
847
  pReader->cost.blockLoadTime += elapsedTime;
H
Haojun Liao 已提交
848

849
  int32_t unDumpedRows = asc ? pBlock->nRow - pDumpInfo->rowIndex : pDumpInfo->rowIndex + 1;
H
Haojun Liao 已提交
850
  tsdbDebug("%p copy file block to sdatablock, global index:%d, table index:%d, brange:%" PRId64 "-%" PRId64
851
            ", rows:%d, remain:%d, minVer:%" PRId64 ", maxVer:%" PRId64 ", elapsed time:%.2f ms, %s",
852
            pReader, pBlockIter->index, pFBlock->tbBlockIdx, pBlock->minKey.ts, pBlock->maxKey.ts, remain, unDumpedRows,
H
Hongze Cheng 已提交
853
            pBlock->minVer, pBlock->maxVer, elapsedTime, pReader->idStr);
854 855 856 857

  return TSDB_CODE_SUCCESS;
}

858
static int32_t doLoadFileBlockData(STsdbReader* pReader, SDataBlockIter* pBlockIter, SBlockData* pBlockData) {
859
  int64_t st = taosGetTimestampUs();
860
  double  elapsedTime = 0;
861
  int32_t code = 0;
862

863
  SFileDataBlockInfo* pBlockInfo = getCurrentBlockInfo(pBlockIter);
864
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;
865

866
  if (pBlockInfo != NULL) {
867 868 869
    SBlock* pBlock = getCurrentBlock(pBlockIter);
    code = tsdbReadDataBlock(pReader->pFileReader, pBlock, pBlockData);
    if (code != TSDB_CODE_SUCCESS) {
870 871 872 873
      tsdbError("%p error occurs in loading file block, global index:%d, table index:%d, brange:%" PRId64 "-%" PRId64
                ", rows:%d, code:%s %s",
                pReader, pBlockIter->index, pBlockInfo->tbBlockIdx, pBlock->minKey.ts, pBlock->maxKey.ts, pBlock->nRow,
                tstrerror(code), pReader->idStr);
874 875
      goto _error;
    }
876

877
    elapsedTime = (taosGetTimestampUs() - st) / 1000.0;
878

879 880
    tsdbDebug("%p load file block into buffer, global index:%d, table index:%d, brange:%" PRId64 "-%" PRId64
                  ", rows:%d, minVer:%" PRId64 ", maxVer:%" PRId64 ", elapsed time:%.2f ms, %s",
881
              pReader, pBlockIter->index, pBlockInfo->tbBlockIdx, pBlock->minKey.ts, pBlock->maxKey.ts, pBlock->nRow,
882 883
              pBlock->minVer, pBlock->maxVer, elapsedTime, pReader->idStr);
  } else {
884 885 886 887 888
#if 0
    SLastBlockReader* pLastBlockReader = pReader->status.fileIter.pLastBlockReader;

    uint64_t uid = pBlockInfo->uid;
    SArray*  pBlocks = pLastBlockReader->pBlockL;
889

890 891 892 893 894 895 896 897 898 899 900 901
    pLastBlockReader->currentBlockIndex = -1;

    // find the correct SBlockL
    for(int32_t i = 0; i < taosArrayGetSize(pBlocks); ++i) {
      SBlockL* pBlock = taosArrayGet(pBlocks, i);
      if (pBlock->minUid >= uid && pBlock->maxUid <= uid) {
        pLastBlockReader->currentBlockIndex = i;
        break;
      }
    }

//    SBlockL* pBlockL = taosArrayGet(pLastBlockReader->pBlockL, *index);
902
    code = tsdbReadLastBlock(pReader->pFileReader, pBlockL, pBlockData);
903 904 905 906 907 908 909 910 911 912 913 914 915
    if (code != TSDB_CODE_SUCCESS) {
      tsdbDebug("%p error occurs in loading last block into buffer, last block index:%d, total:%d brange:%" PRId64 "-%" PRId64
                    ", rows:%d, minVer:%" PRId64 ", maxVer:%" PRId64 ", code:%s %s",
                pReader, *index, pBlockIter->numOfBlocks.numOfLastBlocks, 0, 0, pBlockL->nRow,
                pBlockL->minVer, pBlockL->maxVer, tstrerror(code), pReader->idStr);
      goto _error;
    }

    tsdbDebug("%p load last file block into buffer, last block index:%d, total:%d brange:%" PRId64 "-%" PRId64
                  ", rows:%d, minVer:%" PRId64 ", maxVer:%" PRId64 ", elapsed time:%.2f ms, %s",
              pReader, *index, pBlockIter->numOfBlocks.numOfLastBlocks, 0, 0, pBlockL->nRow,
              pBlockL->minVer, pBlockL->maxVer, elapsedTime, pReader->idStr);
#endif
916 917 918 919
  }

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

H
Haojun Liao 已提交
921
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
922 923

_error:
H
Haojun Liao 已提交
924
  return code;
H
Haojun Liao 已提交
925
}
H
Hongze Cheng 已提交
926

H
Haojun Liao 已提交
927 928 929
static void cleanupBlockOrderSupporter(SBlockOrderSupporter* pSup) {
  taosMemoryFreeClear(pSup->numOfBlocksPerTable);
  taosMemoryFreeClear(pSup->indexPerTable);
H
Hongze Cheng 已提交
930

H
Haojun Liao 已提交
931 932 933 934
  for (int32_t i = 0; i < pSup->numOfTables; ++i) {
    SBlockOrderWrapper* pBlockInfo = pSup->pDataBlockInfo[i];
    taosMemoryFreeClear(pBlockInfo);
  }
H
Hongze Cheng 已提交
935

H
Haojun Liao 已提交
936 937
  taosMemoryFreeClear(pSup->pDataBlockInfo);
}
H
Hongze Cheng 已提交
938

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

H
Haojun Liao 已提交
942
  pSup->numOfBlocksPerTable = taosMemoryCalloc(1, sizeof(int32_t) * numOfTables);
943 944
  pSup->indexPerTable = taosMemoryCalloc(1, sizeof(int32_t) * numOfTables);
  pSup->pDataBlockInfo = taosMemoryCalloc(1, POINTER_BYTES * numOfTables);
H
Hongze Cheng 已提交
945

H
Haojun Liao 已提交
946 947 948 949
  if (pSup->numOfBlocksPerTable == NULL || pSup->indexPerTable == NULL || pSup->pDataBlockInfo == NULL) {
    cleanupBlockOrderSupporter(pSup);
    return TSDB_CODE_OUT_OF_MEMORY;
  }
H
Hongze Cheng 已提交
950

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

H
Haojun Liao 已提交
954
static int32_t fileDataBlockOrderCompar(const void* pLeft, const void* pRight, void* param) {
955
  int32_t leftIndex = *(int32_t*)pLeft;
H
Haojun Liao 已提交
956
  int32_t rightIndex = *(int32_t*)pRight;
H
Hongze Cheng 已提交
957

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

H
Haojun Liao 已提交
960 961
  int32_t leftTableBlockIndex = pSupporter->indexPerTable[leftIndex];
  int32_t rightTableBlockIndex = pSupporter->indexPerTable[rightIndex];
H
Hongze Cheng 已提交
962

H
Haojun Liao 已提交
963 964 965 966 967 968 969
  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 已提交
970

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

974 975 976 977
  return pLeftBlock->offset > pRightBlock->offset ? 1 : -1;
}

static int32_t doSetCurrentBlock(SDataBlockIter* pBlockIter) {
978
  SFileDataBlockInfo*  pFBlock = getCurrentBlockInfo(pBlockIter);
979 980 981 982 983
  if (pFBlock != NULL) {
    STableBlockScanInfo* pScanInfo = taosHashGet(pBlockIter->pTableMap, &pFBlock->uid, sizeof(pFBlock->uid));
    int32_t* mapDataIndex = taosArrayGet(pScanInfo->pBlockList, pFBlock->tbBlockIdx);
    tMapDataGetItemByIdx(&pScanInfo->mapData, *mapDataIndex, &pBlockIter->block, tGetBlock);
  }
984 985 986 987 988 989

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

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

995
  pBlockIter->numOfBlocks = numOfBlocks;
996 997
  taosArrayClear(pBlockIter->blockList);

998 999
  // 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 已提交
1000

1001
  int64_t st = taosGetTimestampUs();
H
Haojun Liao 已提交
1002

1003
  SBlockOrderSupporter sup = {0};
1004
  int32_t              code = initBlockOrderSupporter(&sup, numOfTables);
1005 1006 1007
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }
H
Haojun Liao 已提交
1008

1009 1010 1011 1012 1013 1014 1015
  int32_t cnt = 0;
  void*   ptr = NULL;
  while (1) {
    ptr = taosHashIterate(pReader->status.pTableMap, ptr);
    if (ptr == NULL) {
      break;
    }
H
Haojun Liao 已提交
1016

1017 1018 1019 1020
    STableBlockScanInfo* pTableScanInfo = (STableBlockScanInfo*)ptr;
    if (pTableScanInfo->pBlockList == NULL || taosArrayGetSize(pTableScanInfo->pBlockList) == 0) {
      continue;
    }
H
Haojun Liao 已提交
1021

1022 1023
    size_t num = taosArrayGetSize(pTableScanInfo->pBlockList);
    sup.numOfBlocksPerTable[sup.numOfTables] = num;
H
Haojun Liao 已提交
1024

1025 1026 1027 1028 1029
    char* buf = taosMemoryMalloc(sizeof(SBlockOrderWrapper) * num);
    if (buf == NULL) {
      cleanupBlockOrderSupporter(&sup);
      return TSDB_CODE_TDB_OUT_OF_MEMORY;
    }
H
Haojun Liao 已提交
1030

1031
    sup.pDataBlockInfo[sup.numOfTables] = (SBlockOrderWrapper*)buf;
1032
    SBlock block = {0};
1033 1034
    for (int32_t k = 0; k < num; ++k) {
      SBlockOrderWrapper wrapper = {0};
1035 1036 1037 1038

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

1039
      wrapper.uid = pTableScanInfo->uid;
1040
      wrapper.offset = block.aSubBlock[0].offset;
H
Haojun Liao 已提交
1041

1042 1043 1044 1045 1046 1047
      sup.pDataBlockInfo[sup.numOfTables][k] = wrapper;
      cnt++;
    }

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

1049
  ASSERT(numOfBlocks == cnt);
H
Haojun Liao 已提交
1050

1051
  // since there is only one table qualified, blocks are not sorted
1052 1053
  if (sup.numOfTables == 1) {
    for (int32_t i = 0; i < numOfBlocks; ++i) {
1054 1055
      SFileDataBlockInfo blockInfo = {.uid = sup.pDataBlockInfo[0][i].uid, .tbBlockIdx = i};
      taosArrayPush(pBlockIter->blockList, &blockInfo);
1056
    }
1057

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

1062
    pBlockIter->index = asc ? 0 : (numOfBlocks - 1);
H
Haojun Liao 已提交
1063
    cleanupBlockOrderSupporter(&sup);
1064
    doSetCurrentBlock(pBlockIter);
1065
    return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
1066
  }
H
Haojun Liao 已提交
1067

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

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

1073 1074 1075 1076 1077
  SMultiwayMergeTreeInfo* pTree = NULL;
  uint8_t                 ret = tMergeTreeCreate(&pTree, sup.numOfTables, &sup, fileDataBlockOrderCompar);
  if (ret != TSDB_CODE_SUCCESS) {
    cleanupBlockOrderSupporter(&sup);
    return TSDB_CODE_TDB_OUT_OF_MEMORY;
H
Haojun Liao 已提交
1078
  }
H
Haojun Liao 已提交
1079

1080 1081 1082 1083
  int32_t numOfTotal = 0;
  while (numOfTotal < cnt) {
    int32_t pos = tMergeTreeGetChosenIndex(pTree);
    int32_t index = sup.indexPerTable[pos]++;
H
Haojun Liao 已提交
1084

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

1088 1089 1090 1091
    // 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 已提交
1092

1093 1094
    numOfTotal += 1;
    tMergeTreeAdjust(pTree, tMergeTreeGetAdjustIndex(pTree));
H
Haojun Liao 已提交
1095
  }
H
Haojun Liao 已提交
1096

1097
  int64_t et = taosGetTimestampUs();
1098
  tsdbDebug("%p %d data blocks access order completed, elapsed time:%.2f ms %s", pReader, numOfBlocks, (et - st) / 1000.0,
1099
            pReader->idStr);
1100 1101
  cleanupBlockOrderSupporter(&sup);
  taosMemoryFree(pTree);
H
Haojun Liao 已提交
1102

1103
  pBlockIter->index = asc ? 0 : (numOfBlocks - 1);
1104 1105
  doSetCurrentBlock(pBlockIter);

1106
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
1107
}
H
Hongze Cheng 已提交
1108

H
Haojun Liao 已提交
1109
static bool blockIteratorNext(SDataBlockIter* pBlockIter) {
1110 1111
  bool asc = ASCENDING_TRAVERSE(pBlockIter->order);

1112
  int32_t step = asc ? 1 : -1;
1113
  if ((pBlockIter->index >= pBlockIter->numOfBlocks - 1 && asc) || (pBlockIter->index <= 0 && (!asc))) {
1114 1115 1116
    return false;
  }

1117
  pBlockIter->index += step;
1118 1119
  doSetCurrentBlock(pBlockIter);

1120 1121 1122
  return true;
}

1123 1124 1125
/**
 * This is an two rectangles overlap cases.
 */
1126
static int32_t dataBlockPartiallyRequired(STimeWindow* pWindow, SVersionRange* pVerRange, SBlock* pBlock) {
1127 1128
  return (pWindow->ekey < pBlock->maxKey.ts && pWindow->ekey >= pBlock->minKey.ts) ||
         (pWindow->skey > pBlock->minKey.ts && pWindow->skey <= pBlock->maxKey.ts) ||
H
Hongze Cheng 已提交
1129 1130
         (pVerRange->minVer > pBlock->minVer && pVerRange->minVer <= pBlock->maxVer) ||
         (pVerRange->maxVer < pBlock->maxVer && pVerRange->maxVer >= pBlock->minVer);
H
Haojun Liao 已提交
1131
}
H
Hongze Cheng 已提交
1132

1133 1134
static SBlock* getNeighborBlockOfSameTable(SFileDataBlockInfo* pFBlockInfo, STableBlockScanInfo* pTableBlockScanInfo,
                                           int32_t* nextIndex, int32_t order) {
1135 1136 1137
  bool asc = ASCENDING_TRAVERSE(order);
  if (asc && pFBlockInfo->tbBlockIdx >= taosArrayGetSize(pTableBlockScanInfo->pBlockList) - 1) {
    return NULL;
1138 1139
  }

1140
  if (!asc && pFBlockInfo->tbBlockIdx == 0) {
1141 1142 1143
    return NULL;
  }

1144
  int32_t step = asc ? 1 : -1;
1145
  *nextIndex = pFBlockInfo->tbBlockIdx + step;
1146

1147
  SBlock*  pBlock = taosMemoryCalloc(1, sizeof(SBlock));
1148 1149 1150 1151
  int32_t* indexInMapdata = taosArrayGet(pTableBlockScanInfo->pBlockList, *nextIndex);

  tMapDataGetItemByIdx(&pTableBlockScanInfo->mapData, *indexInMapdata, pBlock, tGetBlock);
  return pBlock;
1152 1153 1154 1155 1156
}

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

1157
  int32_t step = ASCENDING_TRAVERSE(pBlockIter->order) ? 1 : -1;
1158 1159
  int32_t index = pBlockIter->index;

1160
  while (index < pBlockIter->numOfBlocks && index >= 0) {
1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172
    SFileDataBlockInfo* pFBlock = taosArrayGet(pBlockIter->blockList, index);
    if (pFBlock->uid == pFBlockInfo->uid && pFBlock->tbBlockIdx == pFBlockInfo->tbBlockIdx) {
      return index;
    }

    index += step;
  }

  ASSERT(0);
  return -1;
}

1173
static int32_t setFileBlockActiveInBlockIter(SDataBlockIter* pBlockIter, int32_t index, int32_t step) {
1174
  if (index < 0 || index >= pBlockIter->numOfBlocks) {
1175 1176 1177 1178
    return -1;
  }

  SFileDataBlockInfo fblock = *(SFileDataBlockInfo*)taosArrayGet(pBlockIter->blockList, index);
1179 1180 1181 1182 1183
  pBlockIter->index += step;

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

1185 1186 1187
    SFileDataBlockInfo* pBlockInfo = taosArrayGet(pBlockIter->blockList, pBlockIter->index);
    ASSERT(pBlockInfo->uid == fblock.uid && pBlockInfo->tbBlockIdx == fblock.tbBlockIdx);
  }
1188

1189
  doSetCurrentBlock(pBlockIter);
1190 1191 1192 1193 1194 1195 1196 1197 1198 1199
  return TSDB_CODE_SUCCESS;
}

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

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

1205
  return (ascScan && (key.ts != TSKEY_INITIAL_VAL && key.ts <= pBlock->minKey.ts)) ||
1206
         (!ascScan && (key.ts != TSKEY_INITIAL_VAL && key.ts >= pBlock->maxKey.ts));
H
Haojun Liao 已提交
1207
}
H
Hongze Cheng 已提交
1208

H
Haojun Liao 已提交
1209
static bool keyOverlapFileBlock(TSDBKEY key, SBlock* pBlock, SVersionRange* pVerRange) {
H
Hongze Cheng 已提交
1210 1211
  return (key.ts >= pBlock->minKey.ts && key.ts <= pBlock->maxKey.ts) && (pBlock->maxVer >= pVerRange->minVer) &&
         (pBlock->minVer <= pVerRange->maxVer);
H
Haojun Liao 已提交
1212 1213
}

1214 1215 1216 1217 1218 1219
static bool doCheckforDatablockOverlap(STableBlockScanInfo* pBlockScanInfo, const SBlock* pBlock) {
  size_t num = taosArrayGetSize(pBlockScanInfo->delSkyline);

  for (int32_t i = pBlockScanInfo->fileDelIndex; i < num; i += 1) {
    TSDBKEY* p = taosArrayGet(pBlockScanInfo->delSkyline, i);
    if (p->ts >= pBlock->minKey.ts && p->ts <= pBlock->maxKey.ts) {
H
Hongze Cheng 已提交
1220
      if (p->version >= pBlock->minVer) {
1221 1222 1223
        return true;
      }
    } else if (p->ts < pBlock->minKey.ts) {  // p->ts < pBlock->minKey.ts
H
Hongze Cheng 已提交
1224
      if (p->version >= pBlock->minVer) {
1225 1226 1227 1228 1229 1230 1231
        if (i < num - 1) {
          TSDBKEY* pnext = taosArrayGet(pBlockScanInfo->delSkyline, i + 1);
          if (i + 1 == num - 1) {  // pnext is the last point
            if (pnext->ts >= pBlock->minKey.ts) {
              return true;
            }
          } else {
H
Hongze Cheng 已提交
1232
            if (pnext->ts >= pBlock->minKey.ts && pnext->version >= pBlock->minVer) {
1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247
              return true;
            }
          }
        } else {  // it must be the last point
          ASSERT(p->version == 0);
        }
      }
    } else {  // (p->ts > pBlock->maxKey.ts) {
      return false;
    }
  }

  return false;
}

1248
static bool overlapWithDelSkyline(STableBlockScanInfo* pBlockScanInfo, const SBlock* pBlock, int32_t order) {
1249 1250 1251 1252
  if (pBlockScanInfo->delSkyline == NULL) {
    return false;
  }

1253
  // ts is not overlap
1254
  TSDBKEY* pFirst = taosArrayGet(pBlockScanInfo->delSkyline, 0);
L
Liu Jicong 已提交
1255
  TSDBKEY* pLast = taosArrayGetLast(pBlockScanInfo->delSkyline);
1256 1257 1258 1259 1260
  if (pBlock->minKey.ts > pLast->ts || pBlock->maxKey.ts < pFirst->ts) {
    return false;
  }

  // version is not overlap
1261 1262 1263 1264
  if (ASCENDING_TRAVERSE(order)) {
    return doCheckforDatablockOverlap(pBlockScanInfo, pBlock);
  } else {
    int32_t index = pBlockScanInfo->fileDelIndex;
1265
    while (1) {
1266 1267 1268 1269 1270
      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;
1271 1272 1273
      }
    }

1274 1275
    return doCheckforDatablockOverlap(pBlockScanInfo, pBlock);
  }
1276 1277
}

1278 1279 1280 1281
// 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
1282
// 5. delete info should not overlap with current block data
1283
static bool fileBlockShouldLoad(STsdbReader* pReader, SFileDataBlockInfo* pFBlock, SBlock* pBlock,
1284
                                STableBlockScanInfo* pScanInfo, TSDBKEY key, SLastBlockReader* pLastBlockReader) {
1285 1286 1287
  int32_t neighborIndex = 0;
  SBlock* pNeighbor = getNeighborBlockOfSameTable(pFBlock, pScanInfo, &neighborIndex, pReader->order);

1288
  // overlap with neighbor
1289 1290 1291
  bool overlapWithNeighbor = false;
  if (pNeighbor) {
    overlapWithNeighbor = overlapWithNeighborBlock(pBlock, pNeighbor, pReader->order);
1292
    taosMemoryFree(pNeighbor);
1293 1294
  }

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

1299 1300
  // todo here we need to each key in the last files to identify if it is really overlapped with last block
  bool overlapWithlastBlock = false;
1301
  if (taosArrayGetSize(pLastBlockReader->pBlockL) > 0 && (pLastBlockReader->currentBlockIndex != -1)) {
1302 1303 1304 1305
    SBlockL *pBlockL = taosArrayGet(pLastBlockReader->pBlockL, pLastBlockReader->currentBlockIndex);
    overlapWithlastBlock = !(pBlock->maxKey.ts < pBlockL->minKey || pBlock->minKey.ts > pBlockL->maxKey);
  }

1306
  return (overlapWithNeighbor || hasDup || dataBlockPartiallyRequired(&pReader->window, &pReader->verRange, pBlock) ||
1307 1308
          keyOverlapFileBlock(key, pBlock, &pReader->verRange) || (pBlock->nRow > pReader->capacity) ||
          overlapWithDel || overlapWithlastBlock);
H
Haojun Liao 已提交
1309 1310
}

1311
static int32_t buildDataBlockFromBuf(STsdbReader* pReader, STableBlockScanInfo* pBlockScanInfo, int64_t endKey) {
1312
  if (!(pBlockScanInfo->iiter.hasVal || pBlockScanInfo->iter.hasVal)) {
1313 1314
    return TSDB_CODE_SUCCESS;
  }
H
Haojun Liao 已提交
1315

1316 1317 1318
  SSDataBlock* pBlock = pReader->pResBlock;

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

1321
  blockDataUpdateTsWindow(pBlock, 0);
1322
  pBlock->info.uid = pBlockScanInfo->uid;
1323

1324
  setComposedBlockFlag(pReader, true);
1325

1326
  double elapsedTime = (taosGetTimestampUs() - st) / 1000.0;
S
Shengliang Guan 已提交
1327
  tsdbDebug("%p build data block from cache completed, elapsed time:%.2f ms, numOfRows:%d, brange:%" PRId64
1328 1329 1330
            " - %" PRId64 " %s",
            pReader, elapsedTime, pBlock->info.rows, pBlock->info.window.skey, pBlock->info.window.ekey,
            pReader->idStr);
1331 1332

  pReader->cost.buildmemBlock += elapsedTime;
H
Haojun Liao 已提交
1333 1334 1335
  return code;
}

1336 1337
static bool tryCopyDistinctRowFromFileBlock(STsdbReader* pReader, SBlockData* pBlockData, int64_t key,
                                            SFileBlockDumpInfo* pDumpInfo) {
1338 1339 1340 1341 1342
  // opt version
  // 1. it is not a border point
  // 2. the direct next point is not an duplicated timestamp
  if ((pDumpInfo->rowIndex < pDumpInfo->totalRows - 1 && pReader->order == TSDB_ORDER_ASC) ||
      (pDumpInfo->rowIndex > 0 && pReader->order == TSDB_ORDER_DESC)) {
1343
    int32_t step = pReader->order == TSDB_ORDER_ASC ? 1 : -1;
1344 1345

    int64_t nextKey = pBlockData->aTSKEY[pDumpInfo->rowIndex + step];
1346
    if (nextKey != key) {  // merge is not needed
1347
      doAppendRowFromFileBlock(pReader->pResBlock, pReader, pBlockData, pDumpInfo->rowIndex);
1348 1349 1350 1351 1352 1353 1354 1355
      pDumpInfo->rowIndex += step;
      return true;
    }
  }

  return false;
}

H
Haojun Liao 已提交
1356 1357 1358 1359 1360 1361
static FORCE_INLINE STSchema* doGetSchemaForTSRow(int32_t sversion, STsdbReader* pReader, uint64_t uid) {
  // always set the newest schema version in pReader->pSchema
  if (pReader->pSchema == NULL) {
    pReader->pSchema = metaGetTbTSchema(pReader->pTsdb->pVnode->pMeta, uid, -1);
  }

1362
  if (pReader->pSchema && sversion == pReader->pSchema->version) {
H
Haojun Liao 已提交
1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380
    return pReader->pSchema;
  }

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

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

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

1381 1382 1383 1384 1385 1386 1387
static int32_t doMergeBufAndFileRows_Rv(STsdbReader* pReader, STableBlockScanInfo* pBlockScanInfo, TSDBROW* pRow,
                                     SIterInfo* pIter, int64_t key, SLastBlockReader* pLastBlockReader) {
  SRowMerger          merge = {0};
  STSRow*             pTSRow = NULL;
  SBlockData*         pBlockData = &pReader->status.fileBlockData;
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;

1388 1389 1390 1391
  int64_t tsLast = INT64_MIN;
  if (pLastBlockReader->lastBlockData.nRow > 0) {
    tsLast = getCurrentKeyInLastBlock(pLastBlockReader);
  }
1392 1393 1394 1395 1396 1397

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

  SBlockData* pLastBlockData = &pLastBlockReader->lastBlockData;

1398 1399 1400 1401 1402 1403
  int64_t minKey = 0;
  if (pReader->order == TSDB_ORDER_ASC) {
    minKey = INT64_MAX;   // chosen the minimum value
    if (minKey > tsLast && pLastBlockReader->lastBlockData.nRow > 0) {
      minKey = tsLast;
    }
1404

1405 1406 1407
    if (minKey > k.ts) {
      minKey = k.ts;
    }
1408

1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424
    if (minKey > key && pBlockData->nRow > 0) {
      minKey = key;
    }
  } else {
    minKey = INT64_MIN;
    if (minKey < tsLast && pLastBlockReader->lastBlockData.nRow > 0) {
      minKey = tsLast;
    }

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

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

  bool init = false;

1429 1430
  // ASC: file block ---> last block -----> imem -----> mem
  //DESC: mem -----> imem -----> last block -----> file block
1431 1432
  if (pReader->order == TSDB_ORDER_ASC) {
    if (minKey == key) {
1433
      init = true;
1434 1435
      tRowMergerInit(&merge, &fRow, pReader->pSchema);
      doMergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pReader, &merge);
1436 1437
    }

1438
    if (minKey == tsLast) {
H
Haojun Liao 已提交
1439 1440 1441 1442
      TSDBROW fRow1 = tsdbRowFromBlockData(pLastBlockData, *pLastBlockReader->rowIndex);
      if (init) {
        tRowMerge(&merge, &fRow1);
      } else {
1443 1444 1445
        init = true;
        tRowMergerInit(&merge, &fRow1, pReader->pSchema);
      }
H
Haojun Liao 已提交
1446
      doMergeRowsInLastBlock(pLastBlockReader, pBlockScanInfo, tsLast, &merge);
1447
    }
1448

1449
    if (minKey == k.ts) {
H
Haojun Liao 已提交
1450 1451 1452
      if (init) {
        tRowMerge(&merge, pRow);
      } else {
1453 1454 1455 1456 1457 1458 1459 1460 1461
        init = true;
        STSchema* pSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(pRow), pReader, pBlockScanInfo->uid);
        tRowMergerInit(&merge, pRow, pSchema);
      }
      doMergeRowsInBuf(pIter, pBlockScanInfo->uid, k.ts, pBlockScanInfo->delSkyline, &merge, pReader);
    }
  } else {
    if (minKey == k.ts) {
      init = true;
1462 1463
      STSchema* pSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(pRow), pReader, pBlockScanInfo->uid);
      tRowMergerInit(&merge, pRow, pSchema);
1464
      doMergeRowsInBuf(pIter, pBlockScanInfo->uid, k.ts, pBlockScanInfo->delSkyline, &merge, pReader);
1465 1466
    }

1467
    if (minKey == tsLast) {
H
Haojun Liao 已提交
1468 1469 1470 1471
      TSDBROW fRow1 = tsdbRowFromBlockData(pLastBlockData, *pLastBlockReader->rowIndex);
      if (init) {
        tRowMerge(&merge, &fRow1);
      } else {
1472 1473 1474
        init = true;
        tRowMergerInit(&merge, &fRow1, pReader->pSchema);
      }
H
Haojun Liao 已提交
1475
      doMergeRowsInLastBlock(pLastBlockReader, pBlockScanInfo, tsLast, &merge);
1476 1477 1478
    }

    if (minKey == key) {
H
Haojun Liao 已提交
1479 1480 1481
      if (init) {
        tRowMerge(&merge, &fRow);
      } else {
1482 1483 1484 1485 1486
        init = true;
        tRowMergerInit(&merge, &fRow, pReader->pSchema);
      }
      doMergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pReader, &merge);
    }
1487 1488 1489 1490 1491 1492 1493 1494 1495 1496
  }

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

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

1497
static int32_t doMergeBufAndFileRows(STsdbReader* pReader, STableBlockScanInfo* pBlockScanInfo, TSDBROW* pRow,
1498
                                     SIterInfo* pIter, int64_t key, SLastBlockReader* pLastBlockReader) {
1499
  SRowMerger          merge = {0};
H
Haojun Liao 已提交
1500
  STSRow*             pTSRow = NULL;
1501 1502 1503
  SBlockData*         pBlockData = &pReader->status.fileBlockData;
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;

1504 1505 1506 1507
  TSDBKEY  k = TSDBROW_KEY(pRow);
  TSDBROW  fRow = tsdbRowFromBlockData(pBlockData, pDumpInfo->rowIndex);
  SArray*  pDelList = pBlockScanInfo->delSkyline;
  bool     freeTSRow = false;
H
Haojun Liao 已提交
1508
  uint64_t uid = pBlockScanInfo->uid;
1509

1510 1511 1512
  // ascending order traverse
  if (ASCENDING_TRAVERSE(pReader->order)) {
    if (key < k.ts) {
1513 1514 1515 1516 1517 1518 1519
      // imem & mem are all empty, only file exist
      if (tryCopyDistinctRowFromFileBlock(pReader, pBlockData, key, pDumpInfo)) {
        return TSDB_CODE_SUCCESS;
      } else {
        tRowMergerInit(&merge, &fRow, pReader->pSchema);
        doMergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pReader, &merge);
        tRowMergerGetRow(&merge, &pTSRow);
H
Haojun Liao 已提交
1520
        freeTSRow = true;
1521
      }
1522
    } else if (k.ts < key) {  // k.ts < key
1523
      doMergeMultiRows(pRow, pBlockScanInfo->uid, pIter, pDelList, &pTSRow, pReader, &freeTSRow);
1524 1525 1526
    } else {  // k.ts == key, ascending order: file block ----> imem rows -----> mem rows
      tRowMergerInit(&merge, &fRow, pReader->pSchema);
      doMergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pReader, &merge);
1527 1528

      tRowMerge(&merge, pRow);
1529
      doMergeRowsInBuf(pIter, pBlockScanInfo->uid, k.ts, pBlockScanInfo->delSkyline, &merge, pReader);
1530 1531

      tRowMergerGetRow(&merge, &pTSRow);
H
Haojun Liao 已提交
1532
      freeTSRow = true;
1533
    }
1534 1535
  } else {  // descending order scan
    if (key < k.ts) {
1536
      doMergeMultiRows(pRow, pBlockScanInfo->uid, pIter, pDelList, &pTSRow, pReader, &freeTSRow);
1537
    } else if (k.ts < key) {
1538 1539 1540 1541 1542 1543
      if (tryCopyDistinctRowFromFileBlock(pReader, pBlockData, key, pDumpInfo)) {
        return TSDB_CODE_SUCCESS;
      } else {
        tRowMergerInit(&merge, &fRow, pReader->pSchema);
        doMergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pReader, &merge);
        tRowMergerGetRow(&merge, &pTSRow);
H
Haojun Liao 已提交
1544
        freeTSRow = true;
1545
      }
1546
    } else {  // descending order: mem rows -----> imem rows ------> file block
H
Haojun Liao 已提交
1547
      STSchema* pSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(pRow), pReader, pBlockScanInfo->uid);
1548

H
Haojun Liao 已提交
1549
      tRowMergerInit(&merge, pRow, pSchema);
1550
      doMergeRowsInBuf(pIter, pBlockScanInfo->uid, k.ts, pBlockScanInfo->delSkyline, &merge, pReader);
1551 1552 1553 1554 1555

      tRowMerge(&merge, &fRow);
      doMergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pReader, &merge);

      tRowMergerGetRow(&merge, &pTSRow);
H
Haojun Liao 已提交
1556
      freeTSRow = true;
1557
    }
1558 1559
  }

1560
  tRowMergerClear(&merge);
H
Haojun Liao 已提交
1561
  doAppendRowFromTSRow(pReader->pResBlock, pReader, pTSRow, uid);
H
Haojun Liao 已提交
1562

H
Haojun Liao 已提交
1563 1564 1565
  if (freeTSRow) {
    taosMemoryFree(pTSRow);
  }
H
Haojun Liao 已提交
1566

1567 1568 1569
  return TSDB_CODE_SUCCESS;
}

1570
static int32_t doMergeMultiLevelRowsRv(STsdbReader* pReader, STableBlockScanInfo* pBlockScanInfo, SBlockData* pBlockData, SLastBlockReader* pLastBlockReader) {
1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588
  SRowMerger merge = {0};
  STSRow*    pTSRow = NULL;

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

  TSDBROW* pRow = getValidRow(&pBlockScanInfo->iter, pDelList, pReader);
  TSDBROW* piRow = getValidRow(&pBlockScanInfo->iiter, pDelList, pReader);
  ASSERT(pRow != NULL && piRow != NULL);

  SBlockData* pLastBlockData = &pLastBlockReader->lastBlockData;
  int64_t tsLast = getCurrentKeyInLastBlock(pLastBlockReader);

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

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

1589 1590 1591 1592 1593 1594
  int64_t minKey = 0;//INT64_MAX;
  if (ASCENDING_TRAVERSE(pReader->order)) {
    minKey = INT64_MAX;  // let's find the minimum
    if (minKey > k.ts) {
      minKey = k.ts;
    }
1595

1596 1597 1598
    if (minKey > ik.ts) {
      minKey = ik.ts;
    }
1599

1600 1601 1602
    if (minKey > key && pBlockData->nRow > 0) {
      minKey = key;
    }
1603

1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623
    if (minKey > tsLast && pLastBlockData->nRow > 0) {
      minKey = tsLast;
    }
  } else {
    minKey = INT64_MIN; // let find the maximum ts value
    if (minKey < k.ts) {
      minKey = k.ts;
    }

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

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

    if (minKey < tsLast && pLastBlockData->nRow > 0) {
      minKey = tsLast;
    }
1624 1625 1626 1627
  }

  bool init = false;

1628 1629 1630 1631
  // ASC: file block -----> last block -----> imem -----> mem
  // DESC: mem -----> imem -----> last block -----> file block
  if (ASCENDING_TRAVERSE(pReader->order)) {
    if (minKey == key) {
1632
      init = true;
1633 1634 1635
      TSDBROW fRow = tsdbRowFromBlockData(pBlockData, pDumpInfo->rowIndex);
      tRowMergerInit(&merge, &fRow, pReader->pSchema);
      doMergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pReader, &merge);
1636 1637
    }

1638
    if (minKey == tsLast) {
H
Haojun Liao 已提交
1639 1640 1641 1642
      TSDBROW fRow1 = tsdbRowFromBlockData(pLastBlockData, *pLastBlockReader->rowIndex);
      if (init) {
        tRowMerge(&merge, &fRow1);
      } else {
1643 1644 1645
        init = true;
        tRowMergerInit(&merge, &fRow1, pReader->pSchema);
      }
H
Haojun Liao 已提交
1646
      doMergeRowsInLastBlock(pLastBlockReader, pBlockScanInfo, tsLast, &merge);
1647 1648 1649
    }

    if (minKey == ik.ts) {
H
Haojun Liao 已提交
1650 1651 1652
      if (init) {
        tRowMerge(&merge, piRow);
      } else {
1653 1654 1655 1656 1657
        init = true;
        STSchema* pSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(piRow), pReader, pBlockScanInfo->uid);
        tRowMergerInit(&merge, piRow, pSchema);
      }
      doMergeRowsInBuf(&pBlockScanInfo->iiter, pBlockScanInfo->uid, ik.ts, pBlockScanInfo->delSkyline, &merge, pReader);
1658 1659
    }

1660
    if (minKey == k.ts) {
H
Haojun Liao 已提交
1661 1662 1663
      if (init) {
        tRowMerge(&merge, pRow);
      } else {
1664 1665 1666 1667 1668 1669 1670 1671
        STSchema* pSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(pRow), pReader, pBlockScanInfo->uid);
        tRowMergerInit(&merge, pRow, pSchema);
      }
      doMergeRowsInBuf(&pBlockScanInfo->iter, pBlockScanInfo->uid, k.ts, pBlockScanInfo->delSkyline, &merge, pReader);
    }
  } else {
    if (minKey == k.ts) {
      init = true;
1672 1673
      STSchema* pSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(pRow), pReader, pBlockScanInfo->uid);
      tRowMergerInit(&merge, pRow, pSchema);
1674 1675 1676 1677
      doMergeRowsInBuf(&pBlockScanInfo->iter, pBlockScanInfo->uid, k.ts, pBlockScanInfo->delSkyline, &merge, pReader);
    }

    if (minKey == ik.ts) {
H
Haojun Liao 已提交
1678 1679 1680
      if (init) {
        tRowMerge(&merge, piRow);
      } else {
1681 1682 1683 1684 1685 1686 1687 1688
        init = true;
        STSchema* pSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(piRow), pReader, pBlockScanInfo->uid);
        tRowMergerInit(&merge, piRow, pSchema);
      }
      doMergeRowsInBuf(&pBlockScanInfo->iiter, pBlockScanInfo->uid, ik.ts, pBlockScanInfo->delSkyline, &merge, pReader);
    }

    if (minKey == tsLast) {
H
Haojun Liao 已提交
1689 1690 1691 1692
      TSDBROW fRow1 = tsdbRowFromBlockData(pLastBlockData, *pLastBlockReader->rowIndex);
      if (init) {
        tRowMerge(&merge, &fRow1);
      } else {
1693 1694 1695
        init = true;
        tRowMergerInit(&merge, &fRow1, pReader->pSchema);
      }
H
Haojun Liao 已提交
1696
      doMergeRowsInLastBlock(pLastBlockReader, pBlockScanInfo, tsLast, &merge);
1697 1698 1699
    }

    if (minKey == key) {
H
Haojun Liao 已提交
1700
      TSDBROW fRow = tsdbRowFromBlockData(pBlockData, pDumpInfo->rowIndex);
1701 1702
      if (!init) {
        tRowMergerInit(&merge, &fRow, pReader->pSchema);
H
Haojun Liao 已提交
1703 1704
      } else {
        tRowMerge(&merge, &fRow);
1705 1706
      }
      doMergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pReader, &merge);
1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717
    }
  }

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

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

1718
static int32_t doMergeThreeLevelRows(STsdbReader* pReader, STableBlockScanInfo* pBlockScanInfo, SBlockData* pBlockData) {
1719 1720 1721
  SRowMerger merge = {0};
  STSRow*    pTSRow = NULL;

1722
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;
dengyihao's avatar
dengyihao 已提交
1723
  SArray*             pDelList = pBlockScanInfo->delSkyline;
1724

1725 1726
  TSDBROW* pRow = getValidRow(&pBlockScanInfo->iter, pDelList, pReader);
  TSDBROW* piRow = getValidRow(&pBlockScanInfo->iiter, pDelList, pReader);
1727
  ASSERT(pRow != NULL && piRow != NULL);
H
Haojun Liao 已提交
1728

1729
  int64_t key = pBlockData->aTSKEY[pDumpInfo->rowIndex];
1730
  bool    freeTSRow = false;
H
Haojun Liao 已提交
1731

1732
  uint64_t uid = pBlockScanInfo->uid;
H
Haojun Liao 已提交
1733

1734 1735 1736
  TSDBKEY k = TSDBROW_KEY(pRow);
  TSDBKEY ik = TSDBROW_KEY(piRow);
  if (ASCENDING_TRAVERSE(pReader->order)) {
1737 1738
    // [1&2] key <= [k.ts && ik.ts]
    if (key <= k.ts && key <= ik.ts) {
1739 1740 1741
      TSDBROW fRow = tsdbRowFromBlockData(pBlockData, pDumpInfo->rowIndex);
      tRowMergerInit(&merge, &fRow, pReader->pSchema);

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

1744 1745
      if (ik.ts == key) {
        tRowMerge(&merge, piRow);
1746
        doMergeRowsInBuf(&pBlockScanInfo->iiter, uid, key, pBlockScanInfo->delSkyline, &merge, pReader);
1747 1748
      }

1749 1750
      if (k.ts == key) {
        tRowMerge(&merge, pRow);
1751
        doMergeRowsInBuf(&pBlockScanInfo->iter, uid, key, pBlockScanInfo->delSkyline, &merge, pReader);
1752 1753 1754
      }

      tRowMergerGetRow(&merge, &pTSRow);
H
Haojun Liao 已提交
1755
      doAppendRowFromTSRow(pReader->pResBlock, pReader, pTSRow, uid);
1756
      return TSDB_CODE_SUCCESS;
1757
    } else {  // key > ik.ts || key > k.ts
1758 1759
      ASSERT(key != ik.ts);

1760
      // [3] ik.ts < key <= k.ts
1761
      // [4] ik.ts < k.ts <= key
1762
      if (ik.ts < k.ts) {
1763
        doMergeMultiRows(piRow, uid, &pBlockScanInfo->iiter, pDelList, &pTSRow, pReader, &freeTSRow);
H
Haojun Liao 已提交
1764
        doAppendRowFromTSRow(pReader->pResBlock, pReader, pTSRow, uid);
1765 1766 1767
        if (freeTSRow) {
          taosMemoryFree(pTSRow);
        }
1768 1769 1770
        return TSDB_CODE_SUCCESS;
      }

1771 1772
      // [5] k.ts < key   <= ik.ts
      // [6] k.ts < ik.ts <= key
1773
      if (k.ts < ik.ts) {
1774
        doMergeMultiRows(pRow, uid, &pBlockScanInfo->iter, pDelList, &pTSRow, pReader, &freeTSRow);
H
Haojun Liao 已提交
1775
        doAppendRowFromTSRow(pReader->pResBlock, pReader, pTSRow, uid);
1776 1777 1778
        if (freeTSRow) {
          taosMemoryFree(pTSRow);
        }
1779 1780 1781
        return TSDB_CODE_SUCCESS;
      }

1782
      // [7] k.ts == ik.ts < key
1783
      if (k.ts == ik.ts) {
1784 1785
        ASSERT(key > ik.ts && key > k.ts);

1786
        doMergeMemIMemRows(pRow, piRow, pBlockScanInfo, pReader, &pTSRow);
H
Haojun Liao 已提交
1787
        doAppendRowFromTSRow(pReader->pResBlock, pReader, pTSRow, uid);
1788
        taosMemoryFree(pTSRow);
1789 1790 1791
        return TSDB_CODE_SUCCESS;
      }
    }
1792 1793 1794
  } else {  // descending order scan
    // [1/2] k.ts >= ik.ts && k.ts >= key
    if (k.ts >= ik.ts && k.ts >= key) {
H
Haojun Liao 已提交
1795
      STSchema* pSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(pRow), pReader, pBlockScanInfo->uid);
1796

H
Haojun Liao 已提交
1797
      tRowMergerInit(&merge, pRow, pSchema);
1798
      doMergeRowsInBuf(&pBlockScanInfo->iter, uid, key, pBlockScanInfo->delSkyline, &merge, pReader);
1799 1800 1801

      if (ik.ts == k.ts) {
        tRowMerge(&merge, piRow);
1802
        doMergeRowsInBuf(&pBlockScanInfo->iiter, uid, key, pBlockScanInfo->delSkyline, &merge, pReader);
1803 1804 1805 1806 1807 1808 1809 1810 1811
      }

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

      tRowMergerGetRow(&merge, &pTSRow);
H
Haojun Liao 已提交
1812
      doAppendRowFromTSRow(pReader->pResBlock, pReader, pTSRow, uid);
1813 1814
      return TSDB_CODE_SUCCESS;
    } else {
1815
      ASSERT(ik.ts != k.ts);  // this case has been included in the previous if branch
1816 1817 1818 1819

      // [3] ik.ts > k.ts >= Key
      // [4] ik.ts > key >= k.ts
      if (ik.ts > key) {
1820
        doMergeMultiRows(piRow, uid, &pBlockScanInfo->iiter, pDelList, &pTSRow, pReader, &freeTSRow);
H
Haojun Liao 已提交
1821
        doAppendRowFromTSRow(pReader->pResBlock, pReader, pTSRow, uid);
1822 1823 1824
        if (freeTSRow) {
          taosMemoryFree(pTSRow);
        }
1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835
        return TSDB_CODE_SUCCESS;
      }

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

        doMergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pReader, &merge);
        tRowMergerGetRow(&merge, &pTSRow);
H
Haojun Liao 已提交
1836
        doAppendRowFromTSRow(pReader->pResBlock, pReader, pTSRow, uid);
1837
        taosMemoryFree(pTSRow);
1838 1839 1840 1841 1842
        return TSDB_CODE_SUCCESS;
      }

      //[7] key = ik.ts > k.ts
      if (key == ik.ts) {
1843
        doMergeMultiRows(piRow, uid, &pBlockScanInfo->iiter, pDelList, &pTSRow, pReader, &freeTSRow);
1844 1845 1846 1847 1848

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

        taosMemoryFree(pTSRow);
1852 1853 1854 1855 1856 1857
        return TSDB_CODE_SUCCESS;
      }
    }
  }

  ASSERT(0);
S
Shengliang Guan 已提交
1858
  return -1;
1859 1860
}

dengyihao's avatar
dengyihao 已提交
1861 1862
static bool isValidFileBlockRow(SBlockData* pBlockData, SFileBlockDumpInfo* pDumpInfo,
                                STableBlockScanInfo* pBlockScanInfo, STsdbReader* pReader) {
1863 1864 1865 1866 1867 1868 1869 1870
  // 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;
    }
  }

1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881
  // 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;
  }

1882
  TSDBKEY k = {.ts = ts, .version = ver};
1883
  if (hasBeenDropped(pBlockScanInfo->delSkyline, &pBlockScanInfo->fileDelIndex, &k, pReader->order)) {
1884 1885 1886
    return false;
  }

1887 1888 1889
  return true;
}

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

1892
static void initLastBlockReader(SLastBlockReader* pLastBlockReader, uint64_t uid, int16_t* startPos) {
1893 1894
  pLastBlockReader->uid = uid;
  pLastBlockReader->rowIndex = startPos;
1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906

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

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

H
Haojun Liao 已提交
1909
static bool nextRowInLastBlock(SLastBlockReader *pLastBlockReader, STableBlockScanInfo* pBlockScanInfo) {
1910 1911
  int32_t step = (pLastBlockReader->order == TSDB_ORDER_ASC) ? 1 : -1;
  if (*pLastBlockReader->rowIndex == ALL_ROWS_CHECKED_INDEX) {
1912 1913 1914
    return false;
  }

1915
  *(pLastBlockReader->rowIndex) += step;
1916 1917

  SBlockData* pBlockData = &pLastBlockReader->lastBlockData;
1918
  for(int32_t i = *(pLastBlockReader->rowIndex); i < pBlockData->nRow && i >= 0; i += step) {
H
Haojun Liao 已提交
1919
    if (pBlockData->aUid != NULL && pBlockData->aUid[i] != pLastBlockReader->uid) {
1920 1921 1922
      continue;
    }

H
Haojun Liao 已提交
1923 1924
    int64_t ts = pBlockData->aTSKEY[i];
    if (ts < pLastBlockReader->window.skey) {
1925 1926 1927
      continue;
    }

H
Haojun Liao 已提交
1928 1929
    int64_t ver = pBlockData->aVersion[i];
    if (ver < pLastBlockReader->verRange.minVer) {
1930 1931 1932
      continue;
    }

H
Haojun Liao 已提交
1933
    // no data any more, todo opt handle desc case
H
Haojun Liao 已提交
1934
    if (ts > pLastBlockReader->window.ekey) {
H
Haojun Liao 已提交
1935
      continue;
1936 1937
    }

H
Haojun Liao 已提交
1938
    // todo opt handle desc case
H
Haojun Liao 已提交
1939 1940 1941 1942 1943
    if (ver > pLastBlockReader->verRange.maxVer) {
      continue;
    }

    TSDBKEY k = {.ts = ts, .version = ver};
1944
    if (hasBeenDropped(pBlockScanInfo->delSkyline, &pBlockScanInfo->lastBlockDelIndex, &k, pLastBlockReader->order)) {
H
Haojun Liao 已提交
1945
      continue;
1946 1947
    }

1948
    *(pLastBlockReader->rowIndex) = i;
1949 1950 1951
    return true;
  }

1952
  // set all data is consumed in last block
1953
  setAllRowsChecked(pLastBlockReader);
1954 1955 1956 1957 1958
  return false;
}

static int64_t getCurrentKeyInLastBlock(SLastBlockReader* pLastBlockReader) {
  SBlockData* pBlockData = &pLastBlockReader->lastBlockData;
1959
  return pBlockData->aTSKEY[*pLastBlockReader->rowIndex];
1960 1961 1962
}

static bool hasDataInLastBlock(SLastBlockReader* pLastBlockReader) {
1963
  if (*pLastBlockReader->rowIndex == ALL_ROWS_CHECKED_INDEX) {
1964 1965 1966 1967 1968
    return false;
  }
  return true;
}

1969
// todo refactor
H
Haojun Liao 已提交
1970 1971
static int32_t buildComposedDataBlockImpl(STsdbReader* pReader, STableBlockScanInfo* pBlockScanInfo,
                                          SBlockData* pBlockData, SLastBlockReader* pLastBlockReader) {
1972 1973
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;

1974
  int64_t key = (pBlockData->nRow > 0)? pBlockData->aTSKEY[pDumpInfo->rowIndex]:INT64_MIN;
1975 1976
  TSDBROW* pRow = getValidRow(&pBlockScanInfo->iter, pBlockScanInfo->delSkyline, pReader);
  TSDBROW* piRow = getValidRow(&pBlockScanInfo->iiter, pBlockScanInfo->delSkyline, pReader);
1977

1978
  if (pBlockScanInfo->iter.hasVal && pBlockScanInfo->iiter.hasVal) {
1979
    return doMergeMultiLevelRowsRv(pReader, pBlockScanInfo, pBlockData, pLastBlockReader);
1980
  } else {
1981
    // imem + file + last block
1982
    if (pBlockScanInfo->iiter.hasVal) {
1983
      return doMergeBufAndFileRows_Rv(pReader, pBlockScanInfo, piRow, &pBlockScanInfo->iiter, key, pLastBlockReader);
1984 1985
    }

1986
    // mem + file
1987
    if (pBlockScanInfo->iter.hasVal) {
1988
      return doMergeBufAndFileRows_Rv(pReader, pBlockScanInfo, pRow, &pBlockScanInfo->iter, key, pLastBlockReader);
H
Haojun Liao 已提交
1989
    }
1990

1991
    if (pBlockData->nRow > 0) {
1992
      TSDBROW fRow = tsdbRowFromBlockData(pBlockData, pDumpInfo->rowIndex);
1993

1994
      // no last block
1995
      if (pLastBlockReader->lastBlockData.nRow == 0 || (!hasDataInLastBlock(pLastBlockReader))) {
1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012
        if (tryCopyDistinctRowFromFileBlock(pReader, pBlockData, key, pDumpInfo)) {
          return TSDB_CODE_SUCCESS;
        } else {
          STSRow*    pTSRow = NULL;
          SRowMerger merge = {0};

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

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

2013 2014 2015 2016 2017 2018 2019 2020
      // row in last file block
      int64_t ts = getCurrentKeyInLastBlock(pLastBlockReader);
      if (ts < key) {  // save rows in last block
        SBlockData* pLastBlockData = &pLastBlockReader->lastBlockData;

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

2021
        TSDBROW fRow1 = tsdbRowFromBlockData(pLastBlockData, *pLastBlockReader->rowIndex);
2022 2023

        tRowMergerInit(&merge, &fRow1, pReader->pSchema);
H
Haojun Liao 已提交
2024
        doMergeRowsInLastBlock(pLastBlockReader, pBlockScanInfo, ts, &merge);
2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037
        tRowMergerGetRow(&merge, &pTSRow);

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

        taosMemoryFree(pTSRow);
        tRowMergerClear(&merge);
        return TSDB_CODE_SUCCESS;
      } else if (ts == key) {
        STSRow*    pTSRow = NULL;
        SRowMerger merge = {0};

        tRowMergerInit(&merge, &fRow, pReader->pSchema);
        doMergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pReader, &merge);
H
Haojun Liao 已提交
2038
        doMergeRowsInLastBlock(pLastBlockReader, pBlockScanInfo, ts, &merge);
2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067

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

        taosMemoryFree(pTSRow);
        tRowMergerClear(&merge);
        return TSDB_CODE_SUCCESS;
      } else {  // ts > key, asc; todo handle desc
        // imem & mem are all empty, only file exist
        if (tryCopyDistinctRowFromFileBlock(pReader, pBlockData, key, pDumpInfo)) {
          return TSDB_CODE_SUCCESS;
        } else {
          STSRow*    pTSRow = NULL;
          SRowMerger merge = {0};

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

          taosMemoryFree(pTSRow);
          tRowMergerClear(&merge);
          return TSDB_CODE_SUCCESS;
        }
      }
    } else {  // only last block exists
      SBlockData* pLastBlockData = &pLastBlockReader->lastBlockData;
      int64_t     tsLastBlock = getCurrentKeyInLastBlock(pLastBlockReader);

2068 2069
      STSRow*    pTSRow = NULL;
      SRowMerger merge = {0};
H
Haojun Liao 已提交
2070

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

2073
      tRowMergerInit(&merge, &fRow, pReader->pSchema);
H
Haojun Liao 已提交
2074
      doMergeRowsInLastBlock(pLastBlockReader, pBlockScanInfo, tsLastBlock, &merge);
2075
      tRowMergerGetRow(&merge, &pTSRow);
2076

H
Haojun Liao 已提交
2077
      doAppendRowFromTSRow(pReader->pResBlock, pReader, pTSRow, pBlockScanInfo->uid);
2078

2079 2080 2081 2082
      taosMemoryFree(pTSRow);
      tRowMergerClear(&merge);
      return TSDB_CODE_SUCCESS;
    }
2083 2084 2085
  }
}

2086
static int32_t buildComposedDataBlock(STsdbReader* pReader) {
2087 2088
  SSDataBlock* pResBlock = pReader->pResBlock;

2089
  SFileDataBlockInfo*  pBlockInfo = getCurrentBlockInfo(&pReader->status.blockIter);
2090 2091 2092 2093 2094 2095 2096 2097

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

H
Haojun Liao 已提交
2098
  SLastBlockReader*   pLastBlockReader = pReader->status.fileIter.pLastBlockReader;
2099
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;
2100 2101
  SBlockData*         pBlockData = &pReader->status.fileBlockData;
  int32_t             step = ASCENDING_TRAVERSE(pReader->order) ? 1 : -1;
2102

2103 2104
  int64_t st = taosGetTimestampUs();

2105
  while (1) {
2106 2107
    // todo check the validate of row in file block
    {
2108 2109
      bool hasBlockData = false;

H
Haojun Liao 已提交
2110
      while (pBlockData->nRow > 0) {  // find the first qualified row in data block
2111 2112 2113 2114 2115
        if (isValidFileBlockRow(pBlockData, pDumpInfo, pBlockScanInfo, pReader)) {
          hasBlockData = true;
          break;
        }

2116 2117
        pDumpInfo->rowIndex += step;

2118
        SBlock* pBlock = getCurrentBlock(&pReader->status.blockIter);
2119
        if (pDumpInfo->rowIndex >= pBlock->nRow || pDumpInfo->rowIndex < 0) {
2120
          setBlockAllDumped(pDumpInfo, pBlock->maxKey.ts, pReader->order);
2121 2122 2123
          break;
        }
      }
2124

2125 2126 2127 2128
      bool hasBlockLData = hasDataInLastBlock(pLastBlockReader);

      // no data in last block and block, no need to proceed.
      if ((hasBlockData == false) && (hasBlockLData == false)) {
2129 2130
        break;
      }
2131 2132
    }

2133
    buildComposedDataBlockImpl(pReader, pBlockScanInfo, pBlockData, pLastBlockReader);
2134

2135
    // currently loaded file data block is consumed
2136
    if ((pBlockData->nRow > 0) && (pDumpInfo->rowIndex >= pBlockData->nRow || pDumpInfo->rowIndex < 0)) {
2137
      SBlock* pBlock = getCurrentBlock(&pReader->status.blockIter);
2138
      setBlockAllDumped(pDumpInfo, pBlock->maxKey.ts, pReader->order);
2139 2140 2141 2142 2143
      break;
    }

    if (pResBlock->info.rows >= pReader->capacity) {
      break;
2144 2145 2146 2147
    }
  }

  pResBlock->info.uid = pBlockScanInfo->uid;
2148 2149
  blockDataUpdateTsWindow(pResBlock, 0);

2150
  setComposedBlockFlag(pReader, true);
2151
  int64_t et = taosGetTimestampUs();
2152

H
Haojun Liao 已提交
2153
  tsdbDebug("%p uid:%" PRIu64 ", composed data block created, brange:%" PRIu64 "-%" PRIu64 " rows:%d, elapsed time:%.2f ms %s",
2154
            pReader, pBlockScanInfo->uid, pResBlock->info.window.skey, pResBlock->info.window.ekey,
2155
            pResBlock->info.rows, (et - st) / 1000.0, pReader->idStr);
2156

2157 2158 2159 2160 2161
  return TSDB_CODE_SUCCESS;
}

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

2162
static int32_t initMemDataIterator(STableBlockScanInfo* pBlockScanInfo, STsdbReader* pReader) {
2163 2164 2165 2166
  if (pBlockScanInfo->iterInit) {
    return TSDB_CODE_SUCCESS;
  }

2167
  int32_t code = TSDB_CODE_SUCCESS;
2168 2169 2170 2171 2172 2173 2174 2175 2176

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

  int32_t backward = (!ASCENDING_TRAVERSE(pReader->order));
2177 2178

  STbData* d = NULL;
H
Hongze Cheng 已提交
2179
  if (pReader->pReadSnap->pMem != NULL) {
H
Hongze Cheng 已提交
2180
    d = tsdbGetTbDataFromMemTable(pReader->pReadSnap->pMem, pReader->suid, pBlockScanInfo->uid);
2181
    if (d != NULL) {
2182
      code = tsdbTbDataIterCreate(d, &startKey, backward, &pBlockScanInfo->iter.iter);
2183
      if (code == TSDB_CODE_SUCCESS) {
2184
        pBlockScanInfo->iter.hasVal = (tsdbTbDataIterGet(pBlockScanInfo->iter.iter) != NULL);
2185

H
Haojun Liao 已提交
2186
        tsdbDebug("%p uid:%" PRId64 ", check data in mem from skey:%" PRId64 ", order:%d, ts range in buf:%" PRId64
2187 2188
                  "-%" PRId64 " %s",
                  pReader, pBlockScanInfo->uid, startKey.ts, pReader->order, d->minKey, d->maxKey, pReader->idStr);
2189
      } else {
2190 2191
        tsdbError("%p uid:%" PRId64 ", failed to create iterator for imem, code:%s, %s", pReader, pBlockScanInfo->uid,
                  tstrerror(code), pReader->idStr);
2192
        return code;
2193 2194
      }
    }
H
Haojun Liao 已提交
2195
  } else {
2196
    tsdbDebug("%p uid:%" PRId64 ", no data in mem, %s", pReader, pBlockScanInfo->uid, pReader->idStr);
H
Haojun Liao 已提交
2197 2198
  }

2199
  STbData* di = NULL;
H
Hongze Cheng 已提交
2200
  if (pReader->pReadSnap->pIMem != NULL) {
H
Hongze Cheng 已提交
2201
    di = tsdbGetTbDataFromMemTable(pReader->pReadSnap->pIMem, pReader->suid, pBlockScanInfo->uid);
2202
    if (di != NULL) {
2203
      code = tsdbTbDataIterCreate(di, &startKey, backward, &pBlockScanInfo->iiter.iter);
2204
      if (code == TSDB_CODE_SUCCESS) {
2205
        pBlockScanInfo->iiter.hasVal = (tsdbTbDataIterGet(pBlockScanInfo->iiter.iter) != NULL);
2206

H
Haojun Liao 已提交
2207
        tsdbDebug("%p uid:%" PRId64 ", check data in imem from skey:%" PRId64 ", order:%d, ts range in buf:%" PRId64
2208
                  "-%" PRId64 " %s",
2209
                  pReader, pBlockScanInfo->uid, startKey.ts, pReader->order, di->minKey, di->maxKey, pReader->idStr);
2210
      } else {
2211 2212
        tsdbError("%p uid:%" PRId64 ", failed to create iterator for mem, code:%s, %s", pReader, pBlockScanInfo->uid,
                  tstrerror(code), pReader->idStr);
2213
        return code;
2214 2215
      }
    }
H
Haojun Liao 已提交
2216 2217
  } else {
    tsdbDebug("%p uid:%" PRId64 ", no data in imem, %s", pReader, pBlockScanInfo->uid, pReader->idStr);
2218 2219
  }

2220 2221
  initDelSkylineIterator(pBlockScanInfo, pReader, d, di);

2222
  pBlockScanInfo->iterInit = true;
H
Haojun Liao 已提交
2223 2224 2225
  return TSDB_CODE_SUCCESS;
}

dengyihao's avatar
dengyihao 已提交
2226 2227
int32_t initDelSkylineIterator(STableBlockScanInfo* pBlockScanInfo, STsdbReader* pReader, STbData* pMemTbData,
                               STbData* piMemTbData) {
2228 2229 2230
  if (pBlockScanInfo->delSkyline != NULL) {
    return TSDB_CODE_SUCCESS;
  }
2231

2232 2233 2234
  int32_t code = 0;
  STsdb*  pTsdb = pReader->pTsdb;

2235 2236
  SArray* pDelData = taosArrayInit(4, sizeof(SDelData));

H
Hongze Cheng 已提交
2237
  SDelFile* pDelFile = pReader->pReadSnap->fs.pDelFile;
2238 2239
  if (pDelFile) {
    SDelFReader* pDelFReader = NULL;
H
more  
Hongze Cheng 已提交
2240
    code = tsdbDelFReaderOpen(&pDelFReader, pDelFile, pTsdb);
2241
    if (code != TSDB_CODE_SUCCESS) {
2242 2243 2244 2245 2246
      goto _err;
    }

    SArray* aDelIdx = taosArrayInit(4, sizeof(SDelIdx));
    if (aDelIdx == NULL) {
2247
      tsdbDelFReaderClose(&pDelFReader);
2248 2249 2250
      goto _err;
    }

H
Hongze Cheng 已提交
2251
    code = tsdbReadDelIdx(pDelFReader, aDelIdx);
2252 2253 2254
    if (code != TSDB_CODE_SUCCESS) {
      taosArrayDestroy(aDelIdx);
      tsdbDelFReaderClose(&pDelFReader);
2255 2256
      goto _err;
    }
2257

2258 2259 2260
    SDelIdx  idx = {.suid = pReader->suid, .uid = pBlockScanInfo->uid};
    SDelIdx* pIdx = taosArraySearch(aDelIdx, &idx, tCmprDelIdx, TD_EQ);

H
Haojun Liao 已提交
2261
    if (pIdx != NULL) {
H
Hongze Cheng 已提交
2262
      code = tsdbReadDelData(pDelFReader, pIdx, pDelData);
2263 2264 2265 2266 2267 2268 2269
    }

    taosArrayDestroy(aDelIdx);
    tsdbDelFReaderClose(&pDelFReader);

    if (code != TSDB_CODE_SUCCESS) {
      goto _err;
2270
    }
2271
  }
2272

2273 2274 2275 2276 2277 2278 2279
  SDelData* p = NULL;
  if (pMemTbData != NULL) {
    p = pMemTbData->pHead;
    while (p) {
      taosArrayPush(pDelData, p);
      p = p->pNext;
    }
2280 2281
  }

2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295
  if (piMemTbData != NULL) {
    p = piMemTbData->pHead;
    while (p) {
      taosArrayPush(pDelData, p);
      p = p->pNext;
    }
  }

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

  taosArrayDestroy(pDelData);
dengyihao's avatar
dengyihao 已提交
2296 2297
  pBlockScanInfo->iter.index =
      ASCENDING_TRAVERSE(pReader->order) ? 0 : taosArrayGetSize(pBlockScanInfo->delSkyline) - 1;
2298 2299
  pBlockScanInfo->iiter.index = pBlockScanInfo->iter.index;
  pBlockScanInfo->fileDelIndex = pBlockScanInfo->iter.index;
2300
  pBlockScanInfo->lastBlockDelIndex = pBlockScanInfo->iter.index;
2301 2302
  return code;

2303 2304 2305
_err:
  taosArrayDestroy(pDelData);
  return code;
2306 2307
}

2308
static TSDBKEY getCurrentKeyInBuf(STableBlockScanInfo* pScanInfo, STsdbReader* pReader) {
2309 2310
  TSDBKEY key = {.ts = TSKEY_INITIAL_VAL};

2311 2312
  initMemDataIterator(pScanInfo, pReader);
  TSDBROW* pRow = getValidRow(&pScanInfo->iter, pScanInfo->delSkyline, pReader);
2313
  if (pRow != NULL) {
2314 2315 2316
    key = TSDBROW_KEY(pRow);
  }

2317
  pRow = getValidRow(&pScanInfo->iiter, pScanInfo->delSkyline, pReader);
2318
  if (pRow != NULL) {
2319 2320 2321 2322 2323 2324 2325 2326 2327
    TSDBKEY k = TSDBROW_KEY(pRow);
    if (key.ts > k.ts) {
      key = k;
    }
  }

  return key;
}

2328
static int32_t moveToNextFile(STsdbReader* pReader, SBlockNumber* pBlockNum) {
H
Haojun Liao 已提交
2329
  SReaderStatus* pStatus = &pReader->status;
2330 2331
  pBlockNum->numOfBlocks = 0;
  pBlockNum->numOfLastBlocks = 0;
2332

2333
  size_t  numOfTables = taosHashGetSize(pReader->status.pTableMap);
2334
  SArray* pIndexList = taosArrayInit(numOfTables, sizeof(SBlockIdx));
2335
  SArray* pLastBlocks = pStatus->fileIter.pLastBlockReader->pBlockL;
2336
  taosArrayClear(pLastBlocks);
H
Haojun Liao 已提交
2337 2338

  while (1) {
2339
    bool hasNext = filesetIteratorNext(&pStatus->fileIter, pReader);
2340
    if (!hasNext) {  // no data files on disk
H
Haojun Liao 已提交
2341 2342 2343
      break;
    }

H
Haojun Liao 已提交
2344
    taosArrayClear(pIndexList);
H
Haojun Liao 已提交
2345 2346
    int32_t code = doLoadBlockIndex(pReader, pReader->pFileReader, pIndexList);
    if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
2347
      taosArrayDestroy(pIndexList);
H
Haojun Liao 已提交
2348 2349 2350
      return code;
    }

2351
    code = tsdbReadBlockL(pReader->pFileReader, pLastBlocks);
2352 2353 2354 2355 2356
    if (code != TSDB_CODE_SUCCESS) {
      taosArrayDestroy(pIndexList);
      return code;
    }

2357 2358 2359 2360
    if (taosArrayGetSize(pIndexList) > 0 || taosArrayGetSize(pLastBlocks) > 0) {
      SArray* pQLastBlock = taosArrayInit(4, sizeof(SBlockL));

      code = doLoadFileBlock(pReader, pIndexList, pLastBlocks, pBlockNum, pQLastBlock);
H
Haojun Liao 已提交
2361
      if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
2362
        taosArrayDestroy(pIndexList);
2363
        taosArrayDestroy(pQLastBlock);
H
Haojun Liao 已提交
2364 2365 2366
        return code;
      }

2367 2368
      if (pBlockNum->numOfBlocks + pBlockNum->numOfLastBlocks > 0) {
        ASSERT(taosArrayGetSize(pQLastBlock) == pBlockNum->numOfLastBlocks);
2369 2370 2371 2372
        taosArrayClear(pLastBlocks);
        taosArrayAddAll(pLastBlocks, pQLastBlock);

        taosArrayDestroy(pQLastBlock);
H
Haojun Liao 已提交
2373 2374
        break;
      }
H
Haojun Liao 已提交
2375 2376

      taosArrayDestroy(pQLastBlock);
H
Haojun Liao 已提交
2377
    }
2378

H
Haojun Liao 已提交
2379 2380 2381
    // no blocks in current file, try next files
  }

H
Haojun Liao 已提交
2382
  taosArrayDestroy(pIndexList);
H
Haojun Liao 已提交
2383 2384 2385
  return TSDB_CODE_SUCCESS;
}

2386
// todo add elapsed time results
2387
static int32_t doLoadRelatedLastBlock(SLastBlockReader* pLastBlockReader, STableBlockScanInfo *pBlockScanInfo, STsdbReader* pReader) {
2388 2389 2390
  SArray*  pBlocks = pLastBlockReader->pBlockL;
  SBlockL* pBlock = NULL;

2391
  uint64_t uid = pBlockScanInfo->uid;
2392 2393
  int32_t totalLastBlocks = (int32_t)taosArrayGetSize(pBlocks);

2394
  initMemDataIterator(pBlockScanInfo, pReader);
2395

2396 2397 2398
  // find the correct SBlockL. todo binary search
  int32_t index = -1;
  for (int32_t i = 0; i < totalLastBlocks; ++i) {
2399 2400
    SBlockL* p = taosArrayGet(pBlocks, i);
    if (p->minUid <= uid && p->maxUid >= uid) {
2401
      index = i;
2402 2403 2404 2405 2406
      pBlock = p;
      break;
    }
  }

2407 2408
  if (index == -1) {
    pLastBlockReader->currentBlockIndex = index;
H
Haojun Liao 已提交
2409
    tBlockDataReset(&pLastBlockReader->lastBlockData);
2410 2411 2412
    return TSDB_CODE_SUCCESS;
  }

2413 2414 2415 2416 2417
  // the required last datablock has already loaded
  if (index == pLastBlockReader->currentBlockIndex) {
    return TSDB_CODE_SUCCESS;
  }

H
Haojun Liao 已提交
2418
  int32_t code = tBlockDataInit(&pLastBlockReader->lastBlockData, pReader->suid, pReader->suid ? 0 : uid, pReader->pSchema);
2419
  if (code != TSDB_CODE_SUCCESS) {
2420
    tsdbError("%p init block data failed, code:%s %s", pReader, tstrerror(code), pReader->idStr);
2421 2422 2423 2424 2425
    return code;
  }

  code = tsdbReadLastBlock(pReader->pFileReader, pBlock, &pLastBlockReader->lastBlockData);
  if (code != TSDB_CODE_SUCCESS) {
2426 2427 2428 2429 2430 2431 2432
    tsdbError("%p error occurs in loading last block into buffer, last block index:%d, total:%d code:%s %s", pReader,
              pLastBlockReader->currentBlockIndex, totalLastBlocks, tstrerror(code), pReader->idStr);
  } else {
    tsdbDebug("%p load last block completed, uid:%" PRIu64
              " last block index:%d, total:%d rows:%d, minVer:%d, maxVer:%d, brange:%" PRId64 " - %" PRId64 " %s",
              pReader, uid, pLastBlockReader->currentBlockIndex, totalLastBlocks, pBlock->nRow, pBlock->minVer,
              pBlock->maxVer, pBlock->minKey, pBlock->maxKey, pReader->idStr);
2433 2434
  }

2435
  pLastBlockReader->currentBlockIndex = index;
2436 2437 2438 2439
  return TSDB_CODE_SUCCESS;
}

static int32_t doLoadLastBlockSequentially(STsdbReader* pReader) {
2440
  SReaderStatus* pStatus = &pReader->status;
2441 2442 2443 2444 2445 2446 2447 2448
  SLastBlockReader* pLastBlockReader = pStatus->fileIter.pLastBlockReader;

  while(1) {
    if (pStatus->pTableIter == NULL) {
      pStatus->pTableIter = taosHashIterate(pStatus->pTableMap, NULL);
      if (pStatus->pTableIter == NULL) {
        return TSDB_CODE_SUCCESS;
      }
2449 2450 2451 2452 2453
    }

    // load the last data block of current table
    // todo opt perf by avoiding load last block repeatly
    STableBlockScanInfo* pScanInfo = pStatus->pTableIter;
2454
    int32_t code = doLoadRelatedLastBlock(pLastBlockReader, pScanInfo, pReader);
2455
    if (code != TSDB_CODE_SUCCESS) {
2456 2457 2458
      return code;
    }

2459 2460
    if (pLastBlockReader->currentBlockIndex != -1) {
      initLastBlockReader(pLastBlockReader, pScanInfo->uid, &pScanInfo->indexInBlockL);
2461 2462
      int32_t index = pScanInfo->indexInBlockL;
      if (index == DEFAULT_ROW_INDEX_VAL || index == pLastBlockReader->lastBlockData.nRow) {
H
Haojun Liao 已提交
2463
        bool hasData = nextRowInLastBlock(pLastBlockReader, pScanInfo);
2464 2465 2466 2467 2468 2469
        if (!hasData) {  // current table does not have rows in last block, try next table
          pStatus->pTableIter = taosHashIterate(pStatus->pTableMap, pStatus->pTableIter);
          if (pStatus->pTableIter == NULL) {
            return TSDB_CODE_SUCCESS;
          }
          continue;
2470
        }
2471
      }
2472 2473 2474 2475 2476 2477
    } else {  // no data in last block, try next table
      pStatus->pTableIter = taosHashIterate(pStatus->pTableMap, pStatus->pTableIter);
      if (pStatus->pTableIter == NULL) {
        return TSDB_CODE_SUCCESS;
      }
      continue;
2478 2479
    }

2480 2481 2482 2483 2484 2485 2486 2487
    code = doBuildDataBlock(pReader);
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

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

2489 2490 2491 2492 2493
    // current table is exhausted, let's try next table
    pStatus->pTableIter = taosHashIterate(pStatus->pTableMap, pStatus->pTableIter);
    if (pStatus->pTableIter == NULL) {
      return TSDB_CODE_SUCCESS;
    }
2494 2495 2496
  }
}

2497
static int32_t doBuildDataBlock(STsdbReader* pReader) {
2498
  TSDBKEY key = {0};
2499
  int32_t code = TSDB_CODE_SUCCESS;
2500
  SBlock* pBlock = NULL;
2501 2502 2503

  SReaderStatus*       pStatus = &pReader->status;
  SDataBlockIter*      pBlockIter = &pStatus->blockIter;
2504 2505 2506
  STableBlockScanInfo* pScanInfo = NULL;
  SFileDataBlockInfo*  pBlockInfo = getCurrentBlockInfo(pBlockIter);
  SLastBlockReader*    pLastBlockReader = pReader->status.fileIter.pLastBlockReader;
2507

2508
  if (pBlockInfo != NULL) {
2509 2510 2511 2512 2513 2514
    pScanInfo = taosHashGet(pReader->status.pTableMap, &pBlockInfo->uid, sizeof(pBlockInfo->uid));
  } else {
    pScanInfo = pReader->status.pTableIter;
  }

  if (pBlockInfo != NULL) {
2515
    pBlock = getCurrentBlock(pBlockIter);
2516 2517 2518 2519
  }

  {
    key = getCurrentKeyInBuf(pScanInfo, pReader);
2520

2521
    // load the last data block of current table
2522
    code = doLoadRelatedLastBlock(pLastBlockReader, pScanInfo, pReader);
2523
    if (code != TSDB_CODE_SUCCESS) {
2524
      return code;
2525 2526
    }

H
Haojun Liao 已提交
2527
    // note: the lastblock may be null here
2528 2529
    initLastBlockReader(pLastBlockReader, pScanInfo->uid, &pScanInfo->indexInBlockL);
    if (pScanInfo->indexInBlockL == DEFAULT_ROW_INDEX_VAL || pScanInfo->indexInBlockL == pLastBlockReader->lastBlockData.nRow) {
H
Haojun Liao 已提交
2530
      bool hasData = nextRowInLastBlock(pLastBlockReader, pScanInfo);
2531
    }
2532
  }
2533

2534 2535 2536 2537 2538 2539 2540
  if (pBlockInfo == NULL) {  // build data block from last data file
    ASSERT(pBlockIter->numOfBlocks == 0);
    code = buildComposedDataBlock(pReader);
  } else if (fileBlockShouldLoad(pReader, pBlockInfo, pBlock, pScanInfo, key, pLastBlockReader)) {
    tBlockDataReset(&pStatus->fileBlockData);
    code = tBlockDataInit(&pStatus->fileBlockData, pReader->suid, pScanInfo->uid, pReader->pSchema);
    if (code != TSDB_CODE_SUCCESS) {
2541
      return code;
2542
    }
2543

2544 2545 2546
    code = doLoadFileBlockData(pReader, pBlockIter, &pStatus->fileBlockData);
    if (code != TSDB_CODE_SUCCESS) {
      return code;
2547 2548 2549
    }

    // build composed data block
2550
    code = buildComposedDataBlock(pReader);
2551 2552
  } else if (bufferDataInFileBlockGap(pReader->order, key, pBlock)) {
    // data in memory that are earlier than current file block
2553
    // todo rows in buffer should be less than the file block in asc, greater than file block in desc
2554
    int64_t endKey = (ASCENDING_TRAVERSE(pReader->order)) ? pBlock->minKey.ts : pBlock->maxKey.ts;
2555
    code = buildDataBlockFromBuf(pReader, pScanInfo, endKey);
2556
  } else {  // whole block is required, return it directly
2557
    SDataBlockInfo* pInfo = &pReader->pResBlock->info;
2558 2559 2560
    pInfo->rows = pBlock->nRow;
    pInfo->uid = pScanInfo->uid;
    pInfo->window = (STimeWindow){.skey = pBlock->minKey.ts, .ekey = pBlock->maxKey.ts};
2561
    setComposedBlockFlag(pReader, false);
2562
    setBlockAllDumped(&pStatus->fBlockDumpInfo, pBlock->maxKey.ts, pReader->order);
2563 2564 2565 2566 2567
  }

  return code;
}

H
Haojun Liao 已提交
2568
static int32_t buildBlockFromBufferSequentially(STsdbReader* pReader) {
2569 2570
  SReaderStatus* pStatus = &pReader->status;

2571
  while (1) {
2572 2573 2574
    if (pStatus->pTableIter == NULL) {
      pStatus->pTableIter = taosHashIterate(pStatus->pTableMap, NULL);
      if (pStatus->pTableIter == NULL) {
H
Haojun Liao 已提交
2575
        return TSDB_CODE_SUCCESS;
2576 2577 2578 2579
      }
    }

    STableBlockScanInfo* pBlockScanInfo = pStatus->pTableIter;
2580
    initMemDataIterator(pBlockScanInfo, pReader);
2581

2582
    int64_t endKey = (ASCENDING_TRAVERSE(pReader->order)) ? INT64_MAX : INT64_MIN;
2583
    int32_t code = buildDataBlockFromBuf(pReader, pBlockScanInfo, endKey);
H
Haojun Liao 已提交
2584 2585 2586 2587
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

2588
    if (pReader->pResBlock->info.rows > 0) {
H
Haojun Liao 已提交
2589
      return TSDB_CODE_SUCCESS;
2590 2591 2592 2593 2594
    }

    // current table is exhausted, let's try the next table
    pStatus->pTableIter = taosHashIterate(pStatus->pTableMap, pStatus->pTableIter);
    if (pStatus->pTableIter == NULL) {
H
Haojun Liao 已提交
2595
      return TSDB_CODE_SUCCESS;
2596 2597 2598 2599
    }
  }
}

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

2604 2605 2606
  SReaderStatus* pStatus = &pReader->status;

  SFileBlockDumpInfo* pDumpInfo = &pStatus->fBlockDumpInfo;
2607 2608 2609

  pDumpInfo->totalRows = pBlock->nRow;
  pDumpInfo->allDumped = false;
2610
  pDumpInfo->rowIndex = ASCENDING_TRAVERSE(pReader->order) ? 0 : pBlock->nRow - 1;
2611 2612
}

2613
static int32_t initForFirstBlockInFile(STsdbReader* pReader, SDataBlockIter* pBlockIter) {
2614 2615
  SBlockNumber num = {0};

2616
  int32_t code = moveToNextFile(pReader, &num);
2617 2618 2619 2620 2621
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

  // all data files are consumed, try data in buffer
2622
  if (num.numOfBlocks + num.numOfLastBlocks == 0) {
2623 2624 2625 2626 2627
    pReader->status.loadFromFile = false;
    return code;
  }

  // initialize the block iterator for a new fileset
2628 2629 2630
  if (num.numOfBlocks > 0) {
    code = initBlockIterator(pReader, pBlockIter, num.numOfBlocks);
  } else {
2631 2632
    tBlockDataReset(&pReader->status.fileBlockData);
    resetDataBlockIterator(pBlockIter, pReader->order, pReader->status.pTableMap);
2633
  }
2634

2635 2636 2637
  SLastBlockReader* pLReader = pReader->status.fileIter.pLastBlockReader;
  pLReader->currentBlockIndex = -1;

2638
  // set the correct start position according to the query time window
2639
  initBlockDumpInfo(pReader, pBlockIter);
2640 2641 2642
  return code;
}

2643
static bool fileBlockPartiallyRead(SFileBlockDumpInfo* pDumpInfo, bool asc) {
2644 2645
  return (!pDumpInfo->allDumped) &&
         ((pDumpInfo->rowIndex > 0 && asc) || (pDumpInfo->rowIndex < (pDumpInfo->totalRows - 1) && (!asc)));
2646 2647
}

2648
static int32_t buildBlockFromFiles(STsdbReader* pReader) {
H
Haojun Liao 已提交
2649
  int32_t code = TSDB_CODE_SUCCESS;
2650 2651
  bool    asc = ASCENDING_TRAVERSE(pReader->order);

2652 2653
  SDataBlockIter* pBlockIter = &pReader->status.blockIter;

2654 2655 2656 2657 2658 2659 2660
  if (pBlockIter->numOfBlocks == 0) {
    _begin:
    code = doLoadLastBlockSequentially(pReader);
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

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

2665
    // all data blocks are checked in this last block file, now let's try the next file
2666 2667 2668 2669 2670 2671 2672 2673
    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;
      }

2674
      // this file does not have data files, let's start check the last block file if exists
2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689
      if (pBlockIter->numOfBlocks == 0) {
        goto _begin;
      }
    }

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

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

2690
  while (1) {
2691 2692
    SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;

2693
    if (fileBlockPartiallyRead(pDumpInfo, asc)) {  // file data block is partially loaded
2694
      code = buildComposedDataBlock(pReader);
2695 2696 2697 2698 2699 2700 2701
    } else {
      // current block are exhausted, try the next file block
      if (pDumpInfo->allDumped) {
        // try next data block in current file
        bool hasNext = blockIteratorNext(&pReader->status.blockIter);
        if (hasNext) {  // check for the next block in the block accessed order list
          initBlockDumpInfo(pReader, pBlockIter);
2702 2703 2704
        } else if (taosArrayGetSize(pReader->status.fileIter.pLastBlockReader->pBlockL) > 0) {  // data blocks in current file are exhausted, let's try the next file now
          // todo dump all data in last block if exists.
          tBlockDataReset(&pReader->status.fileBlockData);
2705
          resetDataBlockIterator(pBlockIter, pReader->order, pReader->status.pTableMap);
2706 2707
          goto _begin;
        } else {
2708 2709 2710 2711 2712 2713
          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;
          }
2714 2715 2716 2717 2718

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

      code = doBuildDataBlock(pReader);
2723 2724
    }

2725 2726 2727 2728 2729 2730 2731 2732
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

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

2735 2736
static STsdb* getTsdbByRetentions(SVnode* pVnode, TSKEY winSKey, SRetention* retentions, const char* idStr,
                                  int8_t* pLevel) {
2737
  if (VND_IS_RSMA(pVnode)) {
2738
    int8_t  level = 0;
2739 2740
    int64_t now = taosGetTimestamp(pVnode->config.tsdbCfg.precision);

2741
    for (int8_t i = 0; i < TSDB_RETENTION_MAX; ++i) {
2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754
      SRetention* pRetention = retentions + level;
      if (pRetention->keep <= 0) {
        if (level > 0) {
          --level;
        }
        break;
      }
      if ((now - pRetention->keep) <= winSKey) {
        break;
      }
      ++level;
    }

2755
    const char* str = (idStr != NULL) ? idStr : "";
2756 2757

    if (level == TSDB_RETENTION_L0) {
2758
      *pLevel = TSDB_RETENTION_L0;
C
Cary Xu 已提交
2759
      tsdbDebug("vgId:%d, rsma level %d is selected to query %s", TD_VID(pVnode), TSDB_RETENTION_L0, str);
2760 2761
      return VND_RSMA0(pVnode);
    } else if (level == TSDB_RETENTION_L1) {
2762
      *pLevel = TSDB_RETENTION_L1;
C
Cary Xu 已提交
2763
      tsdbDebug("vgId:%d, rsma level %d is selected to query %s", TD_VID(pVnode), TSDB_RETENTION_L1, str);
2764 2765
      return VND_RSMA1(pVnode);
    } else {
2766
      *pLevel = TSDB_RETENTION_L2;
C
Cary Xu 已提交
2767
      tsdbDebug("vgId:%d, rsma level %d is selected to query %s", TD_VID(pVnode), TSDB_RETENTION_L2, str);
2768 2769 2770 2771 2772 2773 2774
      return VND_RSMA2(pVnode);
    }
  }

  return VND_TSDB(pVnode);
}

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

  int64_t endVer = 0;
L
Liu Jicong 已提交
2779 2780
  if (pCond->endVersion ==
      -1) {  // user not specified end version, set current maximum version of vnode as the endVersion
H
Haojun Liao 已提交
2781 2782
    endVer = pVnode->state.applied;
  } else {
L
Liu Jicong 已提交
2783
    endVer = (pCond->endVersion > pVnode->state.applied) ? pVnode->state.applied : pCond->endVersion;
2784 2785
  }

H
Haojun Liao 已提交
2786
  return (SVersionRange){.minVer = startVer, .maxVer = endVer};
2787 2788
}

2789
bool hasBeenDropped(const SArray* pDelList, int32_t* index, TSDBKEY* pKey, int32_t order) {
2790 2791 2792 2793
  ASSERT(pKey != NULL);
  if (pDelList == NULL) {
    return false;
  }
L
Liu Jicong 已提交
2794 2795 2796
  size_t  num = taosArrayGetSize(pDelList);
  bool    asc = ASCENDING_TRAVERSE(order);
  int32_t step = asc ? 1 : -1;
2797

2798 2799 2800 2801 2802 2803
  if (asc) {
    if (*index >= num - 1) {
      TSDBKEY* last = taosArrayGetLast(pDelList);
      ASSERT(pKey->ts >= last->ts);

      if (pKey->ts > last->ts) {
2804
        return false;
2805 2806 2807
      } else if (pKey->ts == last->ts) {
        TSDBKEY* prev = taosArrayGet(pDelList, num - 2);
        return (prev->version >= pKey->version);
2808 2809
      }
    } else {
2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839
      TSDBKEY* pCurrent = taosArrayGet(pDelList, *index);
      TSDBKEY* pNext = taosArrayGet(pDelList, (*index) + 1);

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

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

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

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

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

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

      return false;
2840 2841
    }
  } else {
2842 2843
    if (*index <= 0) {
      TSDBKEY* pFirst = taosArrayGet(pDelList, 0);
2844

2845 2846 2847 2848 2849 2850 2851
      if (pKey->ts < pFirst->ts) {
        return false;
      } else if (pKey->ts == pFirst->ts) {
        return pFirst->version >= pKey->version;
      } else {
        ASSERT(0);
      }
2852
    } else {
2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879
      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;
          }
        }
2880 2881 2882 2883 2884
      }

      return false;
    }
  }
2885 2886

  return false;
2887 2888 2889 2890
}

TSDBROW* getValidRow(SIterInfo* pIter, const SArray* pDelList, STsdbReader* pReader) {
  if (!pIter->hasVal) {
H
Haojun Liao 已提交
2891 2892
    return NULL;
  }
H
Hongze Cheng 已提交
2893

2894
  TSDBROW* pRow = tsdbTbDataIterGet(pIter->iter);
2895
  TSDBKEY  key = {.ts = pRow->pTSRow->ts, .version = pRow->version};
2896
  if (outOfTimeWindow(key.ts, &pReader->window)) {
2897
    pIter->hasVal = false;
H
Haojun Liao 已提交
2898 2899
    return NULL;
  }
H
Hongze Cheng 已提交
2900

2901
  // it is a valid data version
dengyihao's avatar
dengyihao 已提交
2902
  if ((key.version <= pReader->verRange.maxVer && key.version >= pReader->verRange.minVer) &&
2903
      (!hasBeenDropped(pDelList, &pIter->index, &key, pReader->order))) {
H
Haojun Liao 已提交
2904 2905
    return pRow;
  }
H
Hongze Cheng 已提交
2906

2907
  while (1) {
2908 2909
    pIter->hasVal = tsdbTbDataIterNext(pIter->iter);
    if (!pIter->hasVal) {
H
Haojun Liao 已提交
2910 2911
      return NULL;
    }
H
Hongze Cheng 已提交
2912

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

H
Haojun Liao 已提交
2915
    key = TSDBROW_KEY(pRow);
2916
    if (outOfTimeWindow(key.ts, &pReader->window)) {
2917
      pIter->hasVal = false;
H
Haojun Liao 已提交
2918 2919
      return NULL;
    }
H
Hongze Cheng 已提交
2920

dengyihao's avatar
dengyihao 已提交
2921
    if (key.version <= pReader->verRange.maxVer && key.version >= pReader->verRange.minVer &&
2922
        (!hasBeenDropped(pDelList, &pIter->index, &key, pReader->order))) {
H
Haojun Liao 已提交
2923 2924 2925 2926
      return pRow;
    }
  }
}
H
Hongze Cheng 已提交
2927

2928 2929
int32_t doMergeRowsInBuf(SIterInfo* pIter, uint64_t uid, int64_t ts, SArray* pDelList, SRowMerger* pMerger,
                         STsdbReader* pReader) {
H
Haojun Liao 已提交
2930
  while (1) {
2931 2932
    pIter->hasVal = tsdbTbDataIterNext(pIter->iter);
    if (!pIter->hasVal) {
H
Haojun Liao 已提交
2933 2934
      break;
    }
H
Hongze Cheng 已提交
2935

2936
    // data exists but not valid
2937
    TSDBROW* pRow = getValidRow(pIter, pDelList, pReader);
2938 2939 2940 2941 2942
    if (pRow == NULL) {
      break;
    }

    // ts is not identical, quit
H
Haojun Liao 已提交
2943
    TSDBKEY k = TSDBROW_KEY(pRow);
2944
    if (k.ts != ts) {
H
Haojun Liao 已提交
2945 2946 2947
      break;
    }

H
Haojun Liao 已提交
2948
    STSchema* pTSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(pRow), pReader, uid);
2949
    tRowMergerAdd(pMerger, pRow, pTSchema);
H
Haojun Liao 已提交
2950 2951 2952 2953 2954
  }

  return TSDB_CODE_SUCCESS;
}

2955
static int32_t doMergeRowsInFileBlockImpl(SBlockData* pBlockData, int32_t rowIndex, int64_t key, SRowMerger* pMerger,
2956
                                          SVersionRange* pVerRange, int32_t step) {
2957 2958
  while (pBlockData->aTSKEY[rowIndex] == key && rowIndex < pBlockData->nRow && rowIndex >= 0) {
    if (pBlockData->aVersion[rowIndex] > pVerRange->maxVer || pBlockData->aVersion[rowIndex] < pVerRange->minVer) {
2959
      rowIndex += step;
2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976
      continue;
    }

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

  return rowIndex;
}

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

static int32_t checkForNeighborFileBlock(STsdbReader* pReader, STableBlockScanInfo* pScanInfo, SBlock* pBlock,
2977 2978
                                         SFileDataBlockInfo* pFBlock, SRowMerger* pMerger, int64_t key,
                                         CHECK_FILEBLOCK_STATE* state) {
2979
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;
2980
  SBlockData*         pBlockData = &pReader->status.fileBlockData;
2981

2982
  *state = CHECK_FILEBLOCK_QUIT;
2983
  int32_t step = ASCENDING_TRAVERSE(pReader->order) ? 1 : -1;
2984 2985 2986

  int32_t nextIndex = -1;
  SBlock* pNeighborBlock = getNeighborBlockOfSameTable(pFBlock, pScanInfo, &nextIndex, pReader->order);
2987
  if (pNeighborBlock == NULL) {  // do nothing
2988 2989 2990 2991
    return 0;
  }

  bool overlap = overlapWithNeighborBlock(pBlock, pNeighborBlock, pReader->order);
2992 2993
  taosMemoryFree(pNeighborBlock);

2994
  if (overlap) {  // load next block
2995
    SReaderStatus*  pStatus = &pReader->status;
2996 2997
    SDataBlockIter* pBlockIter = &pStatus->blockIter;

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

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

3005
    // 3. load the neighbor block, and set it to be the currently accessed file data block
H
Haojun Liao 已提交
3006
    tBlockDataReset(&pStatus->fileBlockData);
3007
    int32_t code = doLoadFileBlockData(pReader, pBlockIter, &pStatus->fileBlockData);
3008 3009 3010 3011
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

3012
    // 4. check the data values
3013 3014 3015 3016
    initBlockDumpInfo(pReader, pBlockIter);

    pDumpInfo->rowIndex =
        doMergeRowsInFileBlockImpl(pBlockData, pDumpInfo->rowIndex, key, pMerger, &pReader->verRange, step);
H
Haojun Liao 已提交
3017
    if (pDumpInfo->rowIndex >= pDumpInfo->totalRows) {
3018 3019 3020 3021 3022 3023 3024
      *state = CHECK_FILEBLOCK_CONT;
    }
  }

  return TSDB_CODE_SUCCESS;
}

3025 3026
int32_t doMergeRowsInFileBlocks(SBlockData* pBlockData, STableBlockScanInfo* pScanInfo, STsdbReader* pReader,
                                SRowMerger* pMerger) {
3027 3028
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;

3029
  bool    asc = ASCENDING_TRAVERSE(pReader->order);
3030
  int64_t key = pBlockData->aTSKEY[pDumpInfo->rowIndex];
3031
  int32_t step = asc ? 1 : -1;
3032

3033
  pDumpInfo->rowIndex += step;
3034
  if ((pDumpInfo->rowIndex <= pBlockData->nRow - 1 && asc) || (pDumpInfo->rowIndex >= 0 && !asc)) {
3035 3036 3037
    pDumpInfo->rowIndex =
        doMergeRowsInFileBlockImpl(pBlockData, pDumpInfo->rowIndex, key, pMerger, &pReader->verRange, step);
  }
3038

3039 3040 3041 3042
  // 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;
3043

3044
      SFileDataBlockInfo* pFileBlockInfo = getCurrentBlockInfo(&pReader->status.blockIter);
3045
      SBlock*             pCurrentBlock = getCurrentBlock(&pReader->status.blockIter);
3046 3047 3048
      checkForNeighborFileBlock(pReader, pScanInfo, pCurrentBlock, pFileBlockInfo, pMerger, key, &st);
      if (st == CHECK_FILEBLOCK_QUIT) {
        break;
3049
      }
3050
    }
H
Haojun Liao 已提交
3051
  }
3052

H
Haojun Liao 已提交
3053 3054 3055
  return TSDB_CODE_SUCCESS;
}

3056
// todo check if the rows are dropped or not
H
Haojun Liao 已提交
3057 3058
int32_t doMergeRowsInLastBlock(SLastBlockReader* pLastBlockReader, STableBlockScanInfo* pScanInfo, int64_t ts, SRowMerger* pMerger) {
  while(nextRowInLastBlock(pLastBlockReader, pScanInfo)) {
3059 3060
    int64_t next1 = getCurrentKeyInLastBlock(pLastBlockReader);
    if (next1 == ts) {
3061
      TSDBROW fRow1 = tsdbRowFromBlockData(&pLastBlockReader->lastBlockData, *pLastBlockReader->rowIndex);
3062 3063 3064 3065 3066 3067 3068 3069 3070
      tRowMerge(pMerger, &fRow1);
    } else {
      break;
    }
  }

  return TSDB_CODE_SUCCESS;
}

dengyihao's avatar
dengyihao 已提交
3071
void doMergeMultiRows(TSDBROW* pRow, uint64_t uid, SIterInfo* pIter, SArray* pDelList, STSRow** pTSRow,
3072
                      STsdbReader* pReader, bool* freeTSRow) {
H
Haojun Liao 已提交
3073
  TSDBROW* pNextRow = NULL;
3074
  TSDBROW  current = *pRow;
3075

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

3079 3080 3081 3082 3083
    if (!pIter->hasVal) {
      *pTSRow = current.pTSRow;
      *freeTSRow = false;
      return;
    } else {  // has next point in mem/imem
H
Haojun Liao 已提交
3084
      pNextRow = getValidRow(pIter, pDelList, pReader);
3085 3086 3087 3088 3089 3090
      if (pNextRow == NULL) {
        *pTSRow = current.pTSRow;
        *freeTSRow = false;
        return;
      }

H
Haojun Liao 已提交
3091
      if (current.pTSRow->ts != pNextRow->pTSRow->ts) {
3092 3093 3094 3095
        *pTSRow = current.pTSRow;
        *freeTSRow = false;
        return;
      }
3096
    }
3097 3098
  }

3099 3100
  SRowMerger merge = {0};

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

3104 3105
  if (pReader->pSchema == NULL) {
    pReader->pSchema = pTSchema;
3106
  }
H
Haojun Liao 已提交
3107

H
Haojun Liao 已提交
3108 3109 3110 3111 3112 3113
  tRowMergerInit2(&merge, pReader->pSchema, &current, pTSchema);

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

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

3117
  *freeTSRow = true;
3118 3119
}

3120 3121
void doMergeMemIMemRows(TSDBROW* pRow, TSDBROW* piRow, STableBlockScanInfo* pBlockScanInfo, STsdbReader* pReader,
                        STSRow** pTSRow) {
H
Haojun Liao 已提交
3122 3123
  SRowMerger merge = {0};

3124 3125 3126
  TSDBKEY k = TSDBROW_KEY(pRow);
  TSDBKEY ik = TSDBROW_KEY(piRow);

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

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

3133
    tRowMerge(&merge, pRow);
3134
    doMergeRowsInBuf(&pBlockScanInfo->iter, pBlockScanInfo->uid, k.ts, pBlockScanInfo->delSkyline, &merge, pReader);
3135
  } else {
H
Haojun Liao 已提交
3136
    STSchema* pSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(pRow), pReader, pBlockScanInfo->uid);
3137

H
Haojun Liao 已提交
3138
    tRowMergerInit(&merge, pRow, pSchema);
3139
    doMergeRowsInBuf(&pBlockScanInfo->iter, pBlockScanInfo->uid, k.ts, pBlockScanInfo->delSkyline, &merge, pReader);
3140 3141

    tRowMerge(&merge, piRow);
3142
    doMergeRowsInBuf(&pBlockScanInfo->iiter, pBlockScanInfo->uid, k.ts, pBlockScanInfo->delSkyline, &merge, pReader);
3143
  }
3144 3145 3146 3147

  tRowMergerGetRow(&merge, pTSRow);
}

3148 3149
int32_t tsdbGetNextRowInMem(STableBlockScanInfo* pBlockScanInfo, STsdbReader* pReader, STSRow** pTSRow, int64_t endKey,
                            bool* freeTSRow) {
3150 3151
  TSDBROW* pRow = getValidRow(&pBlockScanInfo->iter, pBlockScanInfo->delSkyline, pReader);
  TSDBROW* piRow = getValidRow(&pBlockScanInfo->iiter, pBlockScanInfo->delSkyline, pReader);
dengyihao's avatar
dengyihao 已提交
3152
  SArray*  pDelList = pBlockScanInfo->delSkyline;
H
Haojun Liao 已提交
3153

3154 3155
  // todo refactor
  bool asc = ASCENDING_TRAVERSE(pReader->order);
3156
  if (pBlockScanInfo->iter.hasVal) {
3157 3158 3159 3160 3161 3162
    TSDBKEY k = TSDBROW_KEY(pRow);
    if ((k.ts >= endKey && asc) || (k.ts <= endKey && !asc)) {
      pRow = NULL;
    }
  }

3163
  if (pBlockScanInfo->iiter.hasVal) {
3164 3165 3166 3167 3168 3169
    TSDBKEY k = TSDBROW_KEY(piRow);
    if ((k.ts >= endKey && asc) || (k.ts <= endKey && !asc)) {
      piRow = NULL;
    }
  }

3170
  if (pBlockScanInfo->iter.hasVal && pBlockScanInfo->iiter.hasVal && pRow != NULL && piRow != NULL) {
3171
    TSDBKEY k = TSDBROW_KEY(pRow);
3172
    TSDBKEY ik = TSDBROW_KEY(piRow);
H
Haojun Liao 已提交
3173

3174
    if (ik.ts < k.ts) {  // ik.ts < k.ts
3175
      doMergeMultiRows(piRow, pBlockScanInfo->uid, &pBlockScanInfo->iiter, pDelList, pTSRow, pReader, freeTSRow);
3176
    } else if (k.ts < ik.ts) {
3177
      doMergeMultiRows(pRow, pBlockScanInfo->uid, &pBlockScanInfo->iter, pDelList, pTSRow, pReader, freeTSRow);
3178 3179
    } else {  // ik.ts == k.ts
      doMergeMemIMemRows(pRow, piRow, pBlockScanInfo, pReader, pTSRow);
3180
      *freeTSRow = true;
H
Haojun Liao 已提交
3181
    }
3182 3183

    return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
3184 3185
  }

3186
  if (pBlockScanInfo->iter.hasVal && pRow != NULL) {
3187
    doMergeMultiRows(pRow, pBlockScanInfo->uid, &pBlockScanInfo->iter, pDelList, pTSRow, pReader, freeTSRow);
H
Haojun Liao 已提交
3188 3189 3190
    return TSDB_CODE_SUCCESS;
  }

3191
  if (pBlockScanInfo->iiter.hasVal && piRow != NULL) {
3192
    doMergeMultiRows(piRow, pBlockScanInfo->uid, &pBlockScanInfo->iiter, pDelList, pTSRow, pReader, freeTSRow);
H
Haojun Liao 已提交
3193 3194 3195 3196 3197 3198
    return TSDB_CODE_SUCCESS;
  }

  return TSDB_CODE_SUCCESS;
}

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

3203
  SBlockLoadSuppInfo* pSupInfo = &pReader->suppInfo;
3204
  STSchema*           pSchema = doGetSchemaForTSRow(pTSRow->sver, pReader, uid);
3205

3206
  SColVal colVal = {0};
3207
  int32_t i = 0, j = 0;
H
Haojun Liao 已提交
3208

3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219
  SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, i);
  if (pColInfoData->info.colId == PRIMARYKEY_TIMESTAMP_COL_ID) {
    colDataAppend(pColInfoData, numOfRows, (const char*)&pTSRow->ts, false);
    i += 1;
  }

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

    if (colId == pSchema->columns[j].colId) {
H
Haojun Liao 已提交
3220
      tTSRowGetVal(pTSRow, pSchema, j, &colVal);
3221 3222 3223 3224 3225 3226 3227 3228
      doCopyColVal(pColInfoData, numOfRows, i, &colVal, pSupInfo);
      i += 1;
      j += 1;
    } else if (colId < pSchema->columns[j].colId) {
      colDataAppendNULL(pColInfoData, numOfRows);
      i += 1;
    } else if (colId > pSchema->columns[j].colId) {
      j += 1;
3229
    }
3230 3231
  }

3232
  // set null value since current column does not exist in the "pSchema"
3233
  while (i < numOfCols) {
3234 3235 3236 3237 3238
    pColInfoData = taosArrayGet(pBlock->pDataBlock, i);
    colDataAppendNULL(pColInfoData, numOfRows);
    i += 1;
  }

3239 3240 3241 3242
  pBlock->info.rows += 1;
  return TSDB_CODE_SUCCESS;
}

3243
int32_t doAppendRowFromFileBlock(SSDataBlock* pResBlock, STsdbReader* pReader, SBlockData* pBlockData, int32_t rowIndex) {
3244 3245 3246 3247 3248 3249 3250 3251
  int32_t i = 0, j = 0;
  int32_t outputRowIndex = pResBlock->info.rows;

  SBlockLoadSuppInfo* pSupInfo = &pReader->suppInfo;

  SColumnInfoData* pColData = taosArrayGet(pResBlock->pDataBlock, i);
  if (pColData->info.colId == PRIMARYKEY_TIMESTAMP_COL_ID) {
    colDataAppendInt64(pColData, outputRowIndex, &pBlockData->aTSKEY[rowIndex]);
3252
    i += 1;
3253 3254 3255 3256 3257 3258
  }

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

3259
  while (i < numOfOutputCols && j < numOfInputCols) {
3260
    SColumnInfoData* pCol = taosArrayGet(pResBlock->pDataBlock, i);
3261
    SColData*        pData = tBlockDataGetColDataByIdx(pBlockData, j);
3262 3263

    if (pData->cid == pCol->info.colId) {
3264 3265
      tColDataGetValue(pData, rowIndex, &cv);
      doCopyColVal(pCol, outputRowIndex, i, &cv, pSupInfo);
3266 3267 3268 3269 3270 3271 3272 3273 3274 3275
      j += 1;
    } else {  // the specified column does not exist in file block, fill with null data
      colDataAppendNULL(pCol, outputRowIndex);
    }

    i += 1;
  }

  while (i < numOfOutputCols) {
    SColumnInfoData* pCol = taosArrayGet(pResBlock->pDataBlock, i);
3276
    colDataAppendNULL(pCol, outputRowIndex);
3277 3278 3279 3280 3281 3282 3283
    i += 1;
  }

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

3284 3285
int32_t buildDataBlockFromBufImpl(STableBlockScanInfo* pBlockScanInfo, int64_t endKey, int32_t capacity,
                                  STsdbReader* pReader) {
H
Haojun Liao 已提交
3286 3287 3288 3289
  SSDataBlock* pBlock = pReader->pResBlock;

  do {
    STSRow* pTSRow = NULL;
3290
    bool    freeTSRow = false;
3291
    tsdbGetNextRowInMem(pBlockScanInfo, pReader, &pTSRow, endKey, &freeTSRow);
3292 3293
    if (pTSRow == NULL) {
      break;
H
Haojun Liao 已提交
3294 3295
    }

H
Haojun Liao 已提交
3296
    doAppendRowFromTSRow(pBlock, pReader, pTSRow, pBlockScanInfo->uid);
3297 3298 3299
    if (freeTSRow) {
      taosMemoryFree(pTSRow);
    }
H
Haojun Liao 已提交
3300 3301

    // no data in buffer, return immediately
3302
    if (!(pBlockScanInfo->iter.hasVal || pBlockScanInfo->iiter.hasVal)) {
H
Haojun Liao 已提交
3303 3304 3305
      break;
    }

3306
    if (pBlock->info.rows >= capacity) {
H
Haojun Liao 已提交
3307 3308 3309 3310
      break;
    }
  } while (1);

3311
  ASSERT(pBlock->info.rows <= capacity);
H
Haojun Liao 已提交
3312 3313
  return TSDB_CODE_SUCCESS;
}
H
Hongze Cheng 已提交
3314

3315
// todo refactor, use arraylist instead
H
Hongze Cheng 已提交
3316
int32_t tsdbSetTableId(STsdbReader* pReader, int64_t uid) {
3317 3318 3319
  ASSERT(pReader != NULL);
  taosHashClear(pReader->status.pTableMap);

3320
  STableBlockScanInfo info = {.lastKey = 0, .uid = uid, .indexInBlockL = DEFAULT_ROW_INDEX_VAL};
3321
  taosHashPut(pReader->status.pTableMap, &info.uid, sizeof(uint64_t), &info, sizeof(info));
H
Hongze Cheng 已提交
3322 3323 3324
  return TDB_CODE_SUCCESS;
}

dengyihao's avatar
dengyihao 已提交
3325 3326 3327 3328 3329 3330
void* tsdbGetIdx(SMeta* pMeta) {
  if (pMeta == NULL) {
    return NULL;
  }
  return metaGetIdx(pMeta);
}
dengyihao's avatar
dengyihao 已提交
3331

dengyihao's avatar
dengyihao 已提交
3332 3333 3334 3335 3336 3337
void* tsdbGetIvtIdx(SMeta* pMeta) {
  if (pMeta == NULL) {
    return NULL;
  }
  return metaGetIvtIdx(pMeta);
}
L
Liu Jicong 已提交
3338

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

C
Cary Xu 已提交
3341

H
refact  
Hongze Cheng 已提交
3342
// ====================================== EXPOSED APIs ======================================
3343 3344
int32_t tsdbReaderOpen(SVnode* pVnode, SQueryTableDataCond* pCond, SArray* pTableList, STsdbReader** ppReader,
                       const char* idstr) {
3345 3346
  int32_t code = tsdbReaderCreate(pVnode, pCond, ppReader, 4096, idstr);
  if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
3347 3348
    goto _err;
  }
H
Hongze Cheng 已提交
3349

3350
  // check for query time window
H
Haojun Liao 已提交
3351
  STsdbReader* pReader = *ppReader;
3352
  if (isEmptyQueryTimeWindow(&pReader->window)) {
H
Haojun Liao 已提交
3353 3354 3355
    tsdbDebug("%p query window not overlaps with the data set, no result returned, %s", pReader, pReader->idStr);
    return TSDB_CODE_SUCCESS;
  }
H
Hongze Cheng 已提交
3356

3357 3358 3359
  if (pCond->type == TIMEWINDOW_RANGE_EXTERNAL) {
    // update the SQueryTableDataCond to create inner reader
    STimeWindow w = pCond->twindows;
3360
    int32_t     order = pCond->order;
3361 3362 3363 3364 3365 3366 3367 3368 3369 3370
    if (order == TSDB_ORDER_ASC) {
      pCond->twindows.ekey = pCond->twindows.skey;
      pCond->twindows.skey = INT64_MIN;
      pCond->order = TSDB_ORDER_DESC;
    } else {
      pCond->twindows.skey = pCond->twindows.ekey;
      pCond->twindows.ekey = INT64_MAX;
      pCond->order = TSDB_ORDER_ASC;
    }

3371
    // here we only need one more row, so the capacity is set to be ONE.
3372 3373 3374 3375 3376 3377 3378 3379
    code = tsdbReaderCreate(pVnode, pCond, &pReader->innerReader[0], 1, idstr);
    if (code != TSDB_CODE_SUCCESS) {
      goto _err;
    }

    if (order == TSDB_ORDER_ASC) {
      pCond->twindows.skey = w.ekey;
      pCond->twindows.ekey = INT64_MAX;
3380
    } else {
3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396
      pCond->twindows.skey = INT64_MIN;
      pCond->twindows.ekey = w.ekey;
    }
    code = tsdbReaderCreate(pVnode, pCond, &pReader->innerReader[1], 1, idstr);
    if (code != TSDB_CODE_SUCCESS) {
      goto _err;
    }
  }

  if (pCond->suid != 0) {
    pReader->pSchema = metaGetTbTSchema(pReader->pTsdb->pVnode->pMeta, pReader->suid, -1);
  } else if (taosArrayGetSize(pTableList) > 0) {
    STableKeyInfo* pKey = taosArrayGet(pTableList, 0);
    pReader->pSchema = metaGetTbTSchema(pReader->pTsdb->pVnode->pMeta, pKey->uid, -1);
  }

3397 3398
  int32_t numOfTables = taosArrayGetSize(pTableList);
  pReader->status.pTableMap = createDataBlockScanInfo(pReader, pTableList->pData, numOfTables);
H
Haojun Liao 已提交
3399 3400 3401
  if (pReader->status.pTableMap == NULL) {
    tsdbReaderClose(pReader);
    *ppReader = NULL;
H
Haojun Liao 已提交
3402

H
Haojun Liao 已提交
3403 3404 3405
    code = TSDB_CODE_TDB_OUT_OF_MEMORY;
    goto _err;
  }
H
Hongze Cheng 已提交
3406

H
Hongze Cheng 已提交
3407
  code = tsdbTakeReadSnap(pReader->pTsdb, &pReader->pReadSnap);
3408 3409 3410
  if (code != TSDB_CODE_SUCCESS) {
    goto _err;
  }
H
Hongze Cheng 已提交
3411

3412 3413
  if (pReader->type == TIMEWINDOW_RANGE_CONTAINED) {
    SDataBlockIter* pBlockIter = &pReader->status.blockIter;
3414

3415
    initFilesetIterator(&pReader->status.fileIter, pReader->pReadSnap->fs.aDFileSet, pReader);
3416
    resetDataBlockIterator(&pReader->status.blockIter, pReader->order, pReader->status.pTableMap);
3417 3418 3419 3420 3421 3422 3423 3424 3425 3426

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

3431 3432 3433 3434 3435
    code = tsdbTakeReadSnap(pPrevReader->pTsdb, &pPrevReader->pReadSnap);
    if (code != TSDB_CODE_SUCCESS) {
      goto _err;
    }

3436
    initFilesetIterator(&pPrevReader->status.fileIter, pPrevReader->pReadSnap->fs.aDFileSet, pPrevReader);
3437
    resetDataBlockIterator(&pPrevReader->status.blockIter, pPrevReader->order, pReader->status.pTableMap);
3438 3439 3440 3441 3442 3443 3444 3445 3446

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

3450
  tsdbDebug("%p total numOfTable:%d in this query %s", pReader, numOfTables, pReader->idStr);
H
Hongze Cheng 已提交
3451
  return code;
H
Hongze Cheng 已提交
3452 3453

_err:
S
Shengliang Guan 已提交
3454
  tsdbError("failed to create data reader, code:%s %s", tstrerror(code), pReader->idStr);
H
Hongze Cheng 已提交
3455
  return code;
H
refact  
Hongze Cheng 已提交
3456 3457 3458
}

void tsdbReaderClose(STsdbReader* pReader) {
3459 3460
  if (pReader == NULL) {
    return;
3461
  }
H
refact  
Hongze Cheng 已提交
3462

3463
  SBlockLoadSuppInfo* pSupInfo = &pReader->suppInfo;
H
Hongze Cheng 已提交
3464
  tsdbUntakeReadSnap(pReader->pTsdb, pReader->pReadSnap);
H
Hongze Cheng 已提交
3465

3466 3467 3468 3469
  taosMemoryFreeClear(pSupInfo->plist);
  taosMemoryFree(pSupInfo->colIds);

  taosArrayDestroy(pSupInfo->pColAgg);
L
Liu Jicong 已提交
3470
  for (int32_t i = 0; i < blockDataGetNumOfCols(pReader->pResBlock); ++i) {
3471 3472 3473 3474 3475
    if (pSupInfo->buildBuf[i] != NULL) {
      taosMemoryFreeClear(pSupInfo->buildBuf[i]);
    }
  }
  taosMemoryFree(pSupInfo->buildBuf);
H
Hongze Cheng 已提交
3476
  tBlockDataDestroy(&pReader->status.fileBlockData, true);
3477 3478

  cleanupDataBlockIterator(&pReader->status.blockIter);
3479 3480

  size_t numOfTables = taosHashGetSize(pReader->status.pTableMap);
3481
  destroyBlockScanInfo(pReader->status.pTableMap);
3482
  blockDataDestroy(pReader->pResBlock);
3483

H
Haojun Liao 已提交
3484 3485 3486
  if (pReader->pFileReader != NULL) {
    tsdbDataFReaderClose(&pReader->pFileReader);
  }
H
refact  
Hongze Cheng 已提交
3487

H
Haojun Liao 已提交
3488 3489 3490 3491 3492 3493 3494
  SFilesetIter* pFilesetIter = &pReader->status.fileIter;
  if (pFilesetIter->pLastBlockReader != NULL) {
    tBlockDataDestroy(&pFilesetIter->pLastBlockReader->lastBlockData, true);
    taosArrayDestroy(pFilesetIter->pLastBlockReader->pBlockL);
    taosMemoryFree(pFilesetIter->pLastBlockReader);
  }

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

3497
  tsdbDebug("%p :io-cost summary: head-file:%" PRIu64 ", head-file time:%.2f ms, SMA:%" PRId64
3498 3499
            " SMA-time:%.2f ms, fileBlocks:%" PRId64
            ", fileBlocks-time:%.2f ms, "
3500
            "build in-memory-block-time:%.2f ms, STableBlockScanInfo size:%.2f Kb %s",
3501
            pReader, pCost->headFileLoad, pCost->headFileLoadTime, pCost->smaData, pCost->smaLoadTime,
3502
            pCost->numOfBlocks, pCost->blockLoadTime, pCost->buildmemBlock,
3503
            numOfTables * sizeof(STableBlockScanInfo) / 1000.0, pReader->idStr);
H
refact  
Hongze Cheng 已提交
3504

3505 3506
  taosMemoryFree(pReader->idStr);
  taosMemoryFree(pReader->pSchema);
3507 3508 3509
  if (pReader->pMemSchema != pReader->pSchema) {
    taosMemoryFree(pReader->pMemSchema);
  }
3510
  taosMemoryFreeClear(pReader);
H
refact  
Hongze Cheng 已提交
3511 3512
}

3513
static bool doTsdbNextDataBlock(STsdbReader* pReader) {
H
Haojun Liao 已提交
3514
  // cleanup the data that belongs to the previous data block
3515 3516
  SSDataBlock* pBlock = pReader->pResBlock;
  blockDataCleanup(pBlock);
H
Hongze Cheng 已提交
3517

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

3520 3521 3522 3523 3524
  if (pStatus->loadFromFile) {
    int32_t code = buildBlockFromFiles(pReader);
    if (code != TSDB_CODE_SUCCESS) {
      return false;
    }
3525

3526 3527 3528
    if (pBlock->info.rows > 0) {
      return true;
    } else {
H
Haojun Liao 已提交
3529
      buildBlockFromBufferSequentially(pReader);
3530
      return pBlock->info.rows > 0;
H
Haojun Liao 已提交
3531
    }
3532 3533 3534
  } else {  // no data in files, let's try the buffer
    buildBlockFromBufferSequentially(pReader);
    return pBlock->info.rows > 0;
H
Haojun Liao 已提交
3535
  }
3536

3537
  return false;
H
refact  
Hongze Cheng 已提交
3538 3539
}

3540 3541 3542 3543 3544 3545 3546 3547 3548 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 3576
bool tsdbNextDataBlock(STsdbReader* pReader) {
  if (isEmptyQueryTimeWindow(&pReader->window)) {
    return false;
  }

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

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

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

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

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

  return false;
}

static void setBlockInfo(STsdbReader* pReader, SDataBlockInfo* pDataBlockInfo) {
3577 3578 3579 3580
  ASSERT(pDataBlockInfo != NULL && pReader != NULL);
  pDataBlockInfo->rows = pReader->pResBlock->info.rows;
  pDataBlockInfo->uid = pReader->pResBlock->info.uid;
  pDataBlockInfo->window = pReader->pResBlock->info.window;
H
Hongze Cheng 已提交
3581 3582
}

3583 3584
void tsdbRetrieveDataBlockInfo(STsdbReader* pReader, SDataBlockInfo* pDataBlockInfo) {
  if (pReader->type == TIMEWINDOW_RANGE_EXTERNAL) {
3585
    if (pReader->step == EXTERNAL_ROWS_MAIN) {
3586
      setBlockInfo(pReader, pDataBlockInfo);
3587
    } else if (pReader->step == EXTERNAL_ROWS_PREV) {
3588 3589 3590 3591 3592 3593 3594 3595 3596
      setBlockInfo(pReader->innerReader[0], pDataBlockInfo);
    } else {
      setBlockInfo(pReader->innerReader[1], pDataBlockInfo);
    }
  } else {
    setBlockInfo(pReader, pDataBlockInfo);
  }
}

3597
int32_t tsdbRetrieveDatablockSMA(STsdbReader* pReader, SColumnDataAgg*** pBlockStatis, bool* allHave) {
H
Hongze Cheng 已提交
3598
  int32_t code = 0;
3599
  *allHave = false;
H
Hongze Cheng 已提交
3600

3601
  if (pReader->type == TIMEWINDOW_RANGE_EXTERNAL) {
3602 3603 3604 3605
    *pBlockStatis = NULL;
    return TSDB_CODE_SUCCESS;
  }

3606
  // there is no statistics data for composed block
3607 3608 3609 3610
  if (pReader->status.composedDataBlock) {
    *pBlockStatis = NULL;
    return TSDB_CODE_SUCCESS;
  }
H
Hongze Cheng 已提交
3611

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

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

3617 3618
  SBlockLoadSuppInfo* pSup = &pReader->suppInfo;

3619
  if (tBlockHasSma(pBlock)) {
H
Hongze Cheng 已提交
3620
    code = tsdbReadBlockSma(pReader->pFileReader, pBlock, pSup->pColAgg);
3621
    if (code != TSDB_CODE_SUCCESS) {
3622 3623
      tsdbDebug("vgId:%d, failed to load block SMA for uid %" PRIu64 ", code:%s, %s", 0, pFBlock->uid, tstrerror(code),
                pReader->idStr);
3624 3625
      return code;
    }
3626 3627 3628
  } else {
    *pBlockStatis = NULL;
    return TSDB_CODE_SUCCESS;
3629
  }
H
Hongze Cheng 已提交
3630

3631
  *allHave = true;
H
Hongze Cheng 已提交
3632

3633 3634
  // always load the first primary timestamp column data
  SColumnDataAgg* pTsAgg = &pSup->tsColAgg;
3635

3636 3637
  pTsAgg->numOfNull = 0;
  pTsAgg->colId = PRIMARYKEY_TIMESTAMP_COL_ID;
3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653
  pTsAgg->min = pReader->pResBlock->info.window.skey;
  pTsAgg->max = pReader->pResBlock->info.window.ekey;
  pSup->plist[0] = pTsAgg;

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

  int32_t i = 0, j = 0;
  while (j < numOfCols && i < taosArrayGetSize(pSup->pColAgg)) {
    SColumnDataAgg* pAgg = taosArrayGet(pSup->pColAgg, i);
    if (pAgg->colId == pSup->colIds[j]) {
      if (IS_BSMA_ON(&(pReader->pSchema->columns[i]))) {
        pSup->plist[j] = pAgg;
      } else {
        *allHave = false;
      }
3654 3655
      i += 1;
      j += 1;
3656 3657 3658 3659 3660 3661 3662
    } else if (pAgg->colId < pSup->colIds[j]) {
      i += 1;
    } else if (pSup->colIds[j] < pAgg->colId) {
      j += 1;
    }
  }

3663
  double elapsed = (taosGetTimestampUs() - stime) / 1000.0;
3664
  pReader->cost.smaLoadTime += elapsed;
3665
  pReader->cost.smaData += 1;
3666 3667 3668

  *pBlockStatis = pSup->plist;

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

H
Hongze Cheng 已提交
3672
  return code;
H
Hongze Cheng 已提交
3673 3674
}

3675
static SArray* doRetrieveDataBlock(STsdbReader* pReader) {
H
Haojun Liao 已提交
3676 3677 3678
  SReaderStatus* pStatus = &pReader->status;

  if (pStatus->composedDataBlock) {
3679
    return pReader->pResBlock->pDataBlock;
3680
  }
3681

3682
  SFileDataBlockInfo*  pFBlock = getCurrentBlockInfo(&pStatus->blockIter);
3683
  STableBlockScanInfo* pBlockScanInfo = taosHashGet(pStatus->pTableMap, &pFBlock->uid, sizeof(pFBlock->uid));
3684

H
Haojun Liao 已提交
3685
  tBlockDataReset(&pStatus->fileBlockData);
3686 3687
  int32_t code = tBlockDataInit(&pStatus->fileBlockData, pReader->suid, pBlockScanInfo->uid, pReader->pSchema);
  if (code != TSDB_CODE_SUCCESS) {
3688 3689
    terrno = code;
    return NULL;
3690 3691 3692
  }

  code = doLoadFileBlockData(pReader, &pStatus->blockIter, &pStatus->fileBlockData);
3693
  if (code != TSDB_CODE_SUCCESS) {
H
Hongze Cheng 已提交
3694
    tBlockDataDestroy(&pStatus->fileBlockData, 1);
3695 3696
    terrno = code;
    return NULL;
3697
  }
3698 3699 3700

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

3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714
SArray* tsdbRetrieveDataBlock(STsdbReader* pReader, SArray* pIdList) {
  if (pReader->type == TIMEWINDOW_RANGE_EXTERNAL) {
    if (pReader->step == EXTERNAL_ROWS_PREV) {
      return doRetrieveDataBlock(pReader->innerReader[0]);
    } else if (pReader->step == EXTERNAL_ROWS_NEXT) {
      return doRetrieveDataBlock(pReader->innerReader[1]);
    }
  }

  return doRetrieveDataBlock(pReader);
}

H
Haojun Liao 已提交
3715
int32_t tsdbReaderReset(STsdbReader* pReader, SQueryTableDataCond* pCond) {
3716 3717 3718
  if (isEmptyQueryTimeWindow(&pReader->window)) {
    return TSDB_CODE_SUCCESS;
  }
H
Hongze Cheng 已提交
3719

L
Liu Jicong 已提交
3720
  pReader->order = pCond->order;
3721
  pReader->type = TIMEWINDOW_RANGE_CONTAINED;
3722
  pReader->status.loadFromFile = true;
dengyihao's avatar
dengyihao 已提交
3723
  pReader->status.pTableIter = NULL;
H
Haojun Liao 已提交
3724
  pReader->window = updateQueryTimeWindow(pReader->pTsdb, &pCond->twindows);
H
Hongze Cheng 已提交
3725

3726
  // allocate buffer in order to load data blocks from file
3727
  memset(&pReader->suppInfo.tsColAgg, 0, sizeof(SColumnDataAgg));
3728 3729
  memset(pReader->suppInfo.plist, 0, POINTER_BYTES);

3730
  pReader->suppInfo.tsColAgg.colId = PRIMARYKEY_TIMESTAMP_COL_ID;
3731
  tsdbDataFReaderClose(&pReader->pFileReader);
3732

3733
  int32_t numOfTables = taosHashGetSize(pReader->status.pTableMap);
L
Liu Jicong 已提交
3734 3735
  tsdbDataFReaderClose(&pReader->pFileReader);

3736
  initFilesetIterator(&pReader->status.fileIter, pReader->pReadSnap->fs.aDFileSet, pReader);
3737
  resetDataBlockIterator(&pReader->status.blockIter, pReader->order, pReader->status.pTableMap);
3738
  resetDataBlockScanInfo(pReader->status.pTableMap);
3739

3740
  int32_t         code = 0;
3741 3742
  SDataBlockIter* pBlockIter = &pReader->status.blockIter;

3743 3744 3745 3746 3747 3748
  // no data in files, let's try buffer in memory
  if (pReader->status.fileIter.numOfFiles == 0) {
    pReader->status.loadFromFile = false;
  } else {
    code = initForFirstBlockInFile(pReader, pBlockIter);
    if (code != TSDB_CODE_SUCCESS) {
3749 3750
      tsdbError("%p reset reader failed, numOfTables:%d, query range:%" PRId64 " - %" PRId64 " in query %s", pReader,
                numOfTables, pReader->window.skey, pReader->window.ekey, pReader->idStr);
3751 3752 3753
      return code;
    }
  }
H
Hongze Cheng 已提交
3754

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

3758
  return code;
H
Hongze Cheng 已提交
3759
}
H
Hongze Cheng 已提交
3760

3761 3762 3763
static int32_t getBucketIndex(int32_t startRow, int32_t bucketRange, int32_t numOfRows) {
  return (numOfRows - startRow) / bucketRange;
}
H
Hongze Cheng 已提交
3764

3765 3766 3767 3768
int32_t tsdbGetFileBlocksDistInfo(STsdbReader* pReader, STableBlockDistInfo* pTableBlockInfo) {
  int32_t code = TSDB_CODE_SUCCESS;
  pTableBlockInfo->totalSize = 0;
  pTableBlockInfo->totalRows = 0;
H
Hongze Cheng 已提交
3769

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

3773 3774 3775
  STsdbCfg* pc = &pReader->pTsdb->pVnode->config.tsdbCfg;
  pTableBlockInfo->defMinRows = pc->minRows;
  pTableBlockInfo->defMaxRows = pc->maxRows;
H
Hongze Cheng 已提交
3776

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

3779
  pTableBlockInfo->numOfFiles += 1;
H
Hongze Cheng 已提交
3780

3781 3782
  int32_t numOfTables = (int32_t)taosHashGetSize(pStatus->pTableMap);
  int     defaultRows = 4096;
H
Hongze Cheng 已提交
3783

3784 3785
  SDataBlockIter* pBlockIter = &pStatus->blockIter;
  pTableBlockInfo->numOfFiles += pStatus->fileIter.numOfFiles;
H
Haojun Liao 已提交
3786

3787 3788
  if (pBlockIter->numOfBlocks > 0) {
    pTableBlockInfo->numOfBlocks += pBlockIter->numOfBlocks;
H
Haojun Liao 已提交
3789
  }
H
Hongze Cheng 已提交
3790

3791
  pTableBlockInfo->numOfTables = numOfTables;
3792
  bool hasNext = (pBlockIter->numOfBlocks > 0);
H
Hongze Cheng 已提交
3793

3794 3795
  while (true) {
    if (hasNext) {
H
Haojun Liao 已提交
3796
      SBlock* pBlock = getCurrentBlock(pBlockIter);
H
Hongze Cheng 已提交
3797

3798 3799
      int32_t numOfRows = pBlock->nRow;
      pTableBlockInfo->totalRows += numOfRows;
H
Hongze Cheng 已提交
3800

3801 3802 3803
      if (numOfRows > pTableBlockInfo->maxRows) {
        pTableBlockInfo->maxRows = numOfRows;
      }
H
refact  
Hongze Cheng 已提交
3804

3805 3806 3807
      if (numOfRows < pTableBlockInfo->minRows) {
        pTableBlockInfo->minRows = numOfRows;
      }
H
refact  
Hongze Cheng 已提交
3808

3809 3810 3811
      if (numOfRows < defaultRows) {
        pTableBlockInfo->numOfSmallBlocks += 1;
      }
H
refact  
Hongze Cheng 已提交
3812

3813 3814
      int32_t bucketIndex = getBucketIndex(pTableBlockInfo->defMinRows, bucketRange, numOfRows);
      pTableBlockInfo->blockRowsHisto[bucketIndex]++;
3815 3816

      hasNext = blockIteratorNext(&pStatus->blockIter);
3817 3818 3819 3820 3821
    } else {
      code = initForFirstBlockInFile(pReader, pBlockIter);
      if ((code != TSDB_CODE_SUCCESS) || (pReader->status.loadFromFile == false)) {
        break;
      }
H
refact  
Hongze Cheng 已提交
3822

3823 3824
      pTableBlockInfo->numOfBlocks += pBlockIter->numOfBlocks;
      hasNext = (pBlockIter->numOfBlocks > 0);
3825
    }
H
refact  
Hongze Cheng 已提交
3826

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

H
refact  
Hongze Cheng 已提交
3831 3832
  return code;
}
H
Hongze Cheng 已提交
3833

H
refact  
Hongze Cheng 已提交
3834
int64_t tsdbGetNumOfRowsInMemTable(STsdbReader* pReader) {
3835
  int64_t rows = 0;
H
Hongze Cheng 已提交
3836

3837 3838
  SReaderStatus* pStatus = &pReader->status;
  pStatus->pTableIter = taosHashIterate(pStatus->pTableMap, NULL);
H
Hongze Cheng 已提交
3839

3840 3841 3842 3843 3844
  while (pStatus->pTableIter != NULL) {
    STableBlockScanInfo* pBlockScanInfo = pStatus->pTableIter;

    STbData* d = NULL;
    if (pReader->pTsdb->mem != NULL) {
H
Hongze Cheng 已提交
3845
      d = tsdbGetTbDataFromMemTable(pReader->pReadSnap->pMem, pReader->suid, pBlockScanInfo->uid);
3846 3847 3848 3849 3850 3851 3852
      if (d != NULL) {
        rows += tsdbGetNRowsInTbData(d);
      }
    }

    STbData* di = NULL;
    if (pReader->pTsdb->imem != NULL) {
H
Hongze Cheng 已提交
3853
      di = tsdbGetTbDataFromMemTable(pReader->pReadSnap->pIMem, pReader->suid, pBlockScanInfo->uid);
3854 3855 3856 3857 3858 3859 3860 3861
      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 已提交
3862

H
refact  
Hongze Cheng 已提交
3863
  return rows;
H
Hongze Cheng 已提交
3864
}
D
dapan1121 已提交
3865

L
Liu Jicong 已提交
3866
int32_t tsdbGetTableSchema(SVnode* pVnode, int64_t uid, STSchema** pSchema, int64_t* suid) {
D
dapan1121 已提交
3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878
  int32_t sversion = 1;

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

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

D
dapan1121 已提交
3880
  if (mr.me.type == TSDB_CHILD_TABLE) {
D
dapan1121 已提交
3881
    tDecoderClear(&mr.coder);
D
dapan1121 已提交
3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896
    *suid = mr.me.ctbEntry.suid;
    code = metaGetTableEntryByUid(&mr, *suid);
    if (code != TSDB_CODE_SUCCESS) {
      terrno = TSDB_CODE_TDB_INVALID_TABLE_ID;
      metaReaderClear(&mr);
      return terrno;
    }
    sversion = mr.me.stbEntry.schemaRow.version;
  } else {
    ASSERT(mr.me.type == TSDB_NORMAL_TABLE);
    sversion = mr.me.ntbEntry.schemaRow.version;
  }

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

D
dapan1121 已提交
3898 3899
  return TSDB_CODE_SUCCESS;
}
H
Hongze Cheng 已提交
3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929

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

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

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

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

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

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

H
Hongze Cheng 已提交
3930
  // fs
H
Hongze Cheng 已提交
3931 3932 3933 3934 3935
  code = tsdbFSRef(pTsdb, &(*ppSnap)->fs);
  if (code) {
    taosThreadRwlockUnlock(&pTsdb->rwLock);
    goto _exit;
  }
H
Hongze Cheng 已提交
3936 3937 3938 3939 3940 3941 3942 3943

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

S
Shengliang Guan 已提交
3944
  tsdbTrace("vgId:%d, take read snapshot", TD_VID(pTsdb->pVnode));
H
Hongze Cheng 已提交
3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958
_exit:
  return code;
}

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

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

H
Hongze Cheng 已提交
3959
    tsdbFSUnref(pTsdb, &pSnap->fs);
H
Hongze Cheng 已提交
3960
    taosMemoryFree(pSnap);
H
Hongze Cheng 已提交
3961
  }
H
Hongze Cheng 已提交
3962

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