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

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

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

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

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

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

H
Haojun Liao 已提交
40
typedef struct STableBlockScanInfo {
dengyihao's avatar
dengyihao 已提交
41 42
  uint64_t  uid;
  TSKEY     lastKey;
H
Hongze Cheng 已提交
43 44 45 46 47 48 49 50
  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
  int32_t   fileDelIndex;       // file block delete index
  int32_t   lastBlockDelIndex;  // delete index for last block
  bool      iterInit;           // whether to initialize the in-memory skip list iterator or not
H
Haojun Liao 已提交
51 52 53
} STableBlockScanInfo;

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

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

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

typedef struct SBlockLoadSuppInfo {
78
  SArray*          pColAgg;
79
  SColumnDataAgg   tsColAgg;
C
Cary Xu 已提交
80
  SColumnDataAgg** plist;
81 82
  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 已提交
83 84
} SBlockLoadSuppInfo;

85 86 87
typedef struct SLastBlockReader {
  STimeWindow   window;
  SVersionRange verRange;
88
  int32_t       order;
89
  uint64_t      uid;
90
  SMergeTree    mergeTree;
91 92
} SLastBlockReader;

93
typedef struct SFilesetIter {
H
Hongze Cheng 已提交
94 95 96
  int32_t           numOfFiles;  // number of total files
  int32_t           index;       // current accessed index in the list
  SArray*           pFileList;   // data file list
97
  int32_t           order;
H
Hongze Cheng 已提交
98
  SLastBlockReader* pLastBlockReader;  // last file block reader
99
} SFilesetIter;
H
Haojun Liao 已提交
100 101

typedef struct SFileDataBlockInfo {
102
  // index position in STableBlockScanInfo in order to check whether neighbor block overlaps with it
dengyihao's avatar
dengyihao 已提交
103
  uint64_t uid;
104
  int32_t  tbBlockIdx;
H
Haojun Liao 已提交
105 106 107
} SFileDataBlockInfo;

typedef struct SDataBlockIter {
108
  int32_t   numOfBlocks;
109
  int32_t   index;
H
Hongze Cheng 已提交
110
  SArray*   blockList;  // SArray<SFileDataBlockInfo>
111
  int32_t   order;
H
Hongze Cheng 已提交
112
  SDataBlk  block;  // current SDataBlk data
113
  SHashObj* pTableMap;
H
Haojun Liao 已提交
114 115 116
} SDataBlockIter;

typedef struct SFileBlockDumpInfo {
dengyihao's avatar
dengyihao 已提交
117 118 119 120
  int32_t totalRows;
  int32_t rowIndex;
  int64_t lastKey;
  bool    allDumped;
H
Haojun Liao 已提交
121 122
} SFileBlockDumpInfo;

123
typedef struct SUidOrderCheckInfo {
124 125
  uint64_t* tableUidList;  // access table uid list in uid ascending order list
  int32_t   currentIndex;  // index in table uid list
126 127
} SUidOrderCheckInfo;

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

H
Hongze Cheng 已提交
141
struct STsdbReader {
H
Haojun Liao 已提交
142 143 144 145 146 147 148
  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;
149 150
  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 已提交
151
  SBlockLoadSuppInfo suppInfo;
H
Hongze Cheng 已提交
152
  STsdbReadSnap*     pReadSnap;
153
  SIOCostSummary     cost;
154 155
  STSchema*          pSchema;     // the newest version schema
  STSchema*          pMemSchema;  // the previous schema for in-memory data, to avoid load schema too many times
156 157
  SDataFReader*      pFileReader;
  SVersionRange      verRange;
158

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

H
Haojun Liao 已提交
163
static SFileDataBlockInfo* getCurrentBlockInfo(SDataBlockIter* pBlockIter);
164 165
static int      buildDataBlockFromBufImpl(STableBlockScanInfo* pBlockScanInfo, int64_t endKey, int32_t capacity,
                                          STsdbReader* pReader);
166
static TSDBROW* getValidMemRow(SIterInfo* pIter, const SArray* pDelList, STsdbReader* pReader);
167 168
static int32_t  doMergeRowsInFileBlocks(SBlockData* pBlockData, STableBlockScanInfo* pScanInfo, STsdbReader* pReader,
                                        SRowMerger* pMerger);
H
Hongze Cheng 已提交
169 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,
H
Hongze Cheng 已提交
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

H
Hongze Cheng 已提交
179 180 181 182
static int32_t doMergeMemTableMultiRows(TSDBROW* pRow, uint64_t uid, SIterInfo* pIter, SArray* pDelList,
                                        STSRow** pTSRow, STsdbReader* pReader, bool* freeTSRow);
static int32_t doMergeMemIMemRows(TSDBROW* pRow, TSDBROW* piRow, STableBlockScanInfo* pBlockScanInfo,
                                  STsdbReader* pReader, STSRow** pTSRow);
183 184
static int32_t mergeRowsInFileBlocks(SBlockData* pBlockData, STableBlockScanInfo* pBlockScanInfo, int64_t key,
                                     STsdbReader* pReader);
185

dengyihao's avatar
dengyihao 已提交
186 187 188 189
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);
190
static SVersionRange getQueryVerRange(SVnode* pVnode, SQueryTableDataCond* pCond, int8_t level);
H
Hongze Cheng 已提交
191 192 193
static int64_t       getCurrentKeyInLastBlock(SLastBlockReader* pLastBlockReader);
static bool          hasDataInLastBlock(SLastBlockReader* pLastBlockReader);
static int32_t       doBuildDataBlock(STsdbReader* pReader);
H
Haojun Liao 已提交
194

195 196 197
static int32_t setColumnIdSlotList(STsdbReader* pReader, SSDataBlock* pBlock) {
  SBlockLoadSuppInfo* pSupInfo = &pReader->suppInfo;

198
  size_t numOfCols = blockDataGetNumOfCols(pBlock);
199

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

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

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

H
Haojun Liao 已提交
217 218
  return TSDB_CODE_SUCCESS;
}
H
Hongze Cheng 已提交
219

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

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

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

241 242 243
    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 已提交
244 245
  }

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

249
  return pTableMap;
H
Hongze Cheng 已提交
250
}
H
Hongze Cheng 已提交
251

252 253 254
static void resetDataBlockScanInfo(SHashObj* pTableMap) {
  STableBlockScanInfo* p = NULL;

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

262
    p->delSkyline = taosArrayDestroy(p->delSkyline);
263 264 265
  }
}

266 267 268 269 270 271 272 273
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) {
274
      p->iter.iter = tsdbTbDataIterDestroy(p->iter.iter);
275 276 277
    }

    if (p->iiter.iter != NULL) {
278
      p->iiter.iter = tsdbTbDataIterDestroy(p->iiter.iter);
279 280
    }

281 282
    p->delSkyline = taosArrayDestroy(p->delSkyline);
    p->pBlockList = taosArrayDestroy(p->pBlockList);
283
    tMapDataClear(&p->mapData);
284 285 286 287 288
  }

  taosHashCleanup(pTableMap);
}

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

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

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

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

  return win;
}
H
Hongze Cheng 已提交
309

H
Haojun Liao 已提交
310
static void limitOutputBufferSize(const SQueryTableDataCond* pCond, int32_t* capacity) {
H
Haojun Liao 已提交
311 312 313 314 315 316
  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 已提交
317 318 319
  const int32_t TWOMB = 2 * 1024 * 1024;
  if ((*capacity) * rowLen > TWOMB) {
    (*capacity) = TWOMB / rowLen;
H
Haojun Liao 已提交
320 321 322 323
  }
}

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

328 329
  pIter->index = ASCENDING_TRAVERSE(pReader->order) ? -1 : numOfFileset;
  pIter->order = pReader->order;
H
Hongze Cheng 已提交
330
  pIter->pFileList = aDFileSet;
331
  pIter->numOfFiles = numOfFileset;
H
Haojun Liao 已提交
332

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

342 343 344 345 346 347 348 349
  SLastBlockReader* pLReader = pIter->pLastBlockReader;
  pLReader->order = pReader->order;
  pLReader->window = pReader->window;
  pLReader->verRange = pReader->verRange;

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

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
    return false;
  }

363 364 365
  pIter->pLastBlockReader->uid = 0;
  tMergeTreeClose(&pIter->pLastBlockReader->mergeTree);

H
Haojun Liao 已提交
366 367
  // check file the time range of coverage
  STimeWindow win = {0};
H
Hongze Cheng 已提交
368

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

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

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

381 382
    pReader->cost.headFileLoad += 1;

383 384 385 386 387 388 389 390 391 392 393 394
    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;
395 396 397
      if ((asc && pIter->index >= pIter->numOfFiles) || ((!asc) && pIter->index < 0)) {
        return false;
      }
398 399
      continue;
    }
C
Cary Xu 已提交
400

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

406
_err:
H
Haojun Liao 已提交
407 408 409
  return false;
}

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

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

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

428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
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;
}

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

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

H
Haojun Liao 已提交
465
  initReaderStatus(&pReader->status);
466

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

476
  ASSERT(pCond->numOfCols > 0);
H
Hongze Cheng 已提交
477

478
  limitOutputBufferSize(pCond, &pReader->capacity);
479

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

489 490
  pSup->tsColAgg.colId = PRIMARYKEY_TIMESTAMP_COL_ID;

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

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

503 504
  setColumnIdSlotList(pReader, pReader->pResBlock);

H
Hongze Cheng 已提交
505 506
  *ppReader = pReader;
  return code;
H
Hongze Cheng 已提交
507

H
Haojun Liao 已提交
508 509
_end:
  tsdbReaderClose(pReader);
H
Hongze Cheng 已提交
510 511 512
  *ppReader = NULL;
  return code;
}
H
Hongze Cheng 已提交
513

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

517
  int64_t st = taosGetTimestampUs();
H
Hongze Cheng 已提交
518
  int32_t code = tsdbReadBlockIdx(pFileReader, aBlockIdx);
H
Haojun Liao 已提交
519
  if (code != TSDB_CODE_SUCCESS) {
520
    goto _end;
H
Haojun Liao 已提交
521
  }
H
Hongze Cheng 已提交
522

523 524
  size_t num = taosArrayGetSize(aBlockIdx);
  if (num == 0) {
H
Haojun Liao 已提交
525
    taosArrayDestroy(aBlockIdx);
H
Haojun Liao 已提交
526 527
    return TSDB_CODE_SUCCESS;
  }
H
Hongze Cheng 已提交
528

529 530 531 532
  int64_t et1 = taosGetTimestampUs();

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

535
    // uid check
H
Hongze Cheng 已提交
536
    if (pBlockIdx->suid != pReader->suid) {
H
Haojun Liao 已提交
537 538 539 540
      continue;
    }

    // this block belongs to a table that is not queried.
H
Hongze Cheng 已提交
541
    void* p = taosHashGet(pReader->status.pTableMap, &pBlockIdx->uid, sizeof(uint64_t));
H
Haojun Liao 已提交
542 543 544 545 546 547
    if (p == NULL) {
      continue;
    }

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

H
Hongze Cheng 已提交
551
    taosArrayPush(pIndexList, pBlockIdx);
H
Haojun Liao 已提交
552
  }
H
Hongze Cheng 已提交
553

554
  int64_t et2 = taosGetTimestampUs();
555
  tsdbDebug("load block index for %d tables completed, elapsed time:%.2f ms, set blockIdx:%.2f ms, size:%.2f Kb %s",
556
            (int32_t)num, (et1 - st) / 1000.0, (et2 - et1) / 1000.0, num * sizeof(SBlockIdx) / 1024.0, pReader->idStr);
557 558 559

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

560
_end:
H
Hongze Cheng 已提交
561
  taosArrayDestroy(aBlockIdx);
H
Haojun Liao 已提交
562 563
  return code;
}
H
Hongze Cheng 已提交
564

565
static void cleanupTableScanInfo(SHashObj* pTableMap) {
566
  STableBlockScanInfo* px = NULL;
dengyihao's avatar
dengyihao 已提交
567
  while (1) {
568
    px = taosHashIterate(pTableMap, px);
569 570 571 572
    if (px == NULL) {
      break;
    }

573
    // reset the index in last block when handing a new file
574
    tMapDataClear(&px->mapData);
575 576
    taosArrayClear(px->pBlockList);
  }
577 578
}

579
static int32_t doLoadFileBlock(STsdbReader* pReader, SArray* pIndexList, SBlockNumber* pBlockNum) {
580 581 582 583 584 585
  int32_t numOfQTable = 0;
  size_t  sizeInDisk = 0;
  size_t  numOfTables = taosArrayGetSize(pIndexList);

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

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

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

592
    tMapDataReset(&pScanInfo->mapData);
H
Hongze Cheng 已提交
593
    tsdbReadBlock(pReader->pFileReader, pBlockIdx, &pScanInfo->mapData);
594

595
    sizeInDisk += pScanInfo->mapData.nData;
596
    for (int32_t j = 0; j < pScanInfo->mapData.nItem; ++j) {
H
Hongze Cheng 已提交
597 598
      SDataBlk block = {0};
      tMapDataGetItemByIdx(&pScanInfo->mapData, j, &block, tGetDataBlk);
H
Hongze Cheng 已提交
599

600
      // 1. time range check
601
      if (block.minKey.ts > pReader->window.ekey || block.maxKey.ts < pReader->window.skey) {
H
Haojun Liao 已提交
602 603
        continue;
      }
H
Hongze Cheng 已提交
604

605
      // 2. version range check
H
Hongze Cheng 已提交
606
      if (block.minVer > pReader->verRange.maxVer || block.maxVer < pReader->verRange.minVer) {
607 608
        continue;
      }
609

610
      void* p = taosArrayPush(pScanInfo->pBlockList, &j);
H
Haojun Liao 已提交
611
      if (p == NULL) {
612
        tMapDataClear(&pScanInfo->mapData);
H
Haojun Liao 已提交
613 614
        return TSDB_CODE_OUT_OF_MEMORY;
      }
615

616
      pBlockNum->numOfBlocks += 1;
H
Haojun Liao 已提交
617
    }
H
Hongze Cheng 已提交
618

H
Haojun Liao 已提交
619
    if (pScanInfo->pBlockList != NULL && taosArrayGetSize(pScanInfo->pBlockList) > 0) {
620 621 622 623
      numOfQTable += 1;
    }
  }

H
Hongze Cheng 已提交
624
  pBlockNum->numOfLastFiles = pReader->pFileReader->pSet->nSttF;
625
  int32_t total = pBlockNum->numOfLastFiles + pBlockNum->numOfBlocks;
626

627
  double el = (taosGetTimestampUs() - st) / 1000.0;
H
Hongze Cheng 已提交
628
  tsdbDebug(
629
      "load block of %d tables completed, blocks:%d in %d tables, last-files:%d, block-info-size:%.2f Kb, elapsed "
630
      "time:%.2f ms %s",
631
      numOfTables, pBlockNum->numOfBlocks, numOfQTable, pBlockNum->numOfLastFiles, sizeInDisk / 1000.0, el,
H
Hongze Cheng 已提交
632
      pReader->idStr);
633

634
  pReader->cost.numOfBlocks += total;
635
  pReader->cost.headFileLoadTime += el;
636

H
Haojun Liao 已提交
637 638
  return TSDB_CODE_SUCCESS;
}
H
Hongze Cheng 已提交
639

640
static void setBlockAllDumped(SFileBlockDumpInfo* pDumpInfo, int64_t maxKey, int32_t order) {
641
  int32_t step = ASCENDING_TRAVERSE(order) ? 1 : -1;
642
  pDumpInfo->allDumped = true;
643
  pDumpInfo->lastKey = maxKey + step;
H
Haojun Liao 已提交
644 645
}

646 647
static void doCopyColVal(SColumnInfoData* pColInfoData, int32_t rowIndex, int32_t colIndex, SColVal* pColVal,
                         SBlockLoadSuppInfo* pSup) {
H
Haojun Liao 已提交
648
  if (IS_VAR_DATA_TYPE(pColVal->type)) {
649
    if (pColVal->isNull || pColVal->isNone) {
H
Haojun Liao 已提交
650 651 652
      colDataAppendNULL(pColInfoData, rowIndex);
    } else {
      varDataSetLen(pSup->buildBuf[colIndex], pColVal->value.nData);
H
Haojun Liao 已提交
653
      ASSERT(pColVal->value.nData <= pColInfoData->info.bytes);
H
Haojun Liao 已提交
654 655 656 657
      memcpy(varDataVal(pSup->buildBuf[colIndex]), pColVal->value.pData, pColVal->value.nData);
      colDataAppend(pColInfoData, rowIndex, pSup->buildBuf[colIndex], false);
    }
  } else {
658
    colDataAppend(pColInfoData, rowIndex, (const char*)&pColVal->value, pColVal->isNull || pColVal->isNone);
H
Haojun Liao 已提交
659
  }
H
Haojun Liao 已提交
660 661
}

662
static SFileDataBlockInfo* getCurrentBlockInfo(SDataBlockIter* pBlockIter) {
663 664
  if (taosArrayGetSize(pBlockIter->blockList) == 0) {
    ASSERT(pBlockIter->numOfBlocks == taosArrayGetSize(pBlockIter->blockList));
665 666
    return NULL;
  }
667 668 669

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

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

674
static int32_t copyBlockDataToSDataBlock(STsdbReader* pReader, STableBlockScanInfo* pBlockScanInfo) {
675
  SReaderStatus*  pStatus = &pReader->status;
676
  SDataBlockIter* pBlockIter = &pStatus->blockIter;
H
Hongze Cheng 已提交
677

678
  SBlockData*         pBlockData = &pStatus->fileBlockData;
H
Haojun Liao 已提交
679
  SFileDataBlockInfo* pFBlock = getCurrentBlockInfo(pBlockIter);
H
Hongze Cheng 已提交
680
  SDataBlk*           pBlock = getCurrentBlock(pBlockIter);
H
Haojun Liao 已提交
681
  SSDataBlock*        pResBlock = pReader->pResBlock;
682
  int32_t             numOfOutputCols = blockDataGetNumOfCols(pResBlock);
H
Haojun Liao 已提交
683

H
Haojun Liao 已提交
684
  SBlockLoadSuppInfo* pSupInfo = &pReader->suppInfo;
685
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;
H
Haojun Liao 已提交
686

H
Haojun Liao 已提交
687
  SColVal cv = {0};
688
  int64_t st = taosGetTimestampUs();
689 690
  bool    asc = ASCENDING_TRAVERSE(pReader->order);
  int32_t step = asc ? 1 : -1;
691

692
  int32_t rowIndex = 0;
693 694
  int32_t remain = asc ? (pBlockData->nRow - pDumpInfo->rowIndex) : (pDumpInfo->rowIndex + 1);

695 696 697 698 699 700 701 702
  int32_t endIndex = 0;
  if (remain <= pReader->capacity) {
    endIndex = pBlockData->nRow;
  } else {
    endIndex = pDumpInfo->rowIndex + step * pReader->capacity;
    remain = pReader->capacity;
  }

703
  int32_t          i = 0;
704 705
  SColumnInfoData* pColData = taosArrayGet(pResBlock->pDataBlock, i);
  if (pColData->info.colId == PRIMARYKEY_TIMESTAMP_COL_ID) {
706
    for (int32_t j = pDumpInfo->rowIndex; j < endIndex && j >= 0; j += step) {
707 708 709 710 711
      colDataAppend(pColData, rowIndex++, (const char*)&pBlockData->aTSKEY[j], false);
    }
    i += 1;
  }

712 713 714
  int32_t colIndex = 0;
  int32_t num = taosArrayGetSize(pBlockData->aIdx);
  while (i < numOfOutputCols && colIndex < num) {
715 716 717
    rowIndex = 0;
    pColData = taosArrayGet(pResBlock->pDataBlock, i);

H
Hongze Cheng 已提交
718
    SColData* pData = tBlockDataGetColDataByIdx(pBlockData, colIndex);
719 720 721
    if (pData->cid < pColData->info.colId) {
      colIndex += 1;
    } else if (pData->cid == pColData->info.colId) {
722
      for (int32_t j = pDumpInfo->rowIndex; j < endIndex && j >= 0; j += step) {
723 724
        tColDataGetValue(pData, j, &cv);
        doCopyColVal(pColData, rowIndex++, i, &cv, pSupInfo);
H
Haojun Liao 已提交
725
      }
726
      colIndex += 1;
727
      i += 1;
728
      ASSERT(rowIndex == remain);
729 730
    } else {  // the specified column does not exist in file block, fill with null data
      colDataAppendNNULL(pColData, 0, remain);
731
      i += 1;
H
Haojun Liao 已提交
732
    }
733 734
  }

735
  while (i < numOfOutputCols) {
736 737 738
    pColData = taosArrayGet(pResBlock->pDataBlock, i);
    colDataAppendNNULL(pColData, 0, remain);
    i += 1;
H
Haojun Liao 已提交
739
  }
H
Haojun Liao 已提交
740

741
  pResBlock->info.rows = remain;
742
  pDumpInfo->rowIndex += step * remain;
743

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

746
  double elapsedTime = (taosGetTimestampUs() - st) / 1000.0;
H
Haojun Liao 已提交
747
  pReader->cost.blockLoadTime += elapsedTime;
H
Haojun Liao 已提交
748

749
  int32_t unDumpedRows = asc ? pBlock->nRow - pDumpInfo->rowIndex : pDumpInfo->rowIndex + 1;
H
Haojun Liao 已提交
750
  tsdbDebug("%p copy file block to sdatablock, global index:%d, table index:%d, brange:%" PRId64 "-%" PRId64
751
            ", rows:%d, remain:%d, minVer:%" PRId64 ", maxVer:%" PRId64 ", elapsed time:%.2f ms, %s",
752
            pReader, pBlockIter->index, pFBlock->tbBlockIdx, pBlock->minKey.ts, pBlock->maxKey.ts, remain, unDumpedRows,
H
Hongze Cheng 已提交
753
            pBlock->minVer, pBlock->maxVer, elapsedTime, pReader->idStr);
754 755 756 757

  return TSDB_CODE_SUCCESS;
}

758
static int32_t doLoadFileBlockData(STsdbReader* pReader, SDataBlockIter* pBlockIter, SBlockData* pBlockData) {
759 760
  int64_t st = taosGetTimestampUs();

761
  SFileDataBlockInfo* pBlockInfo = getCurrentBlockInfo(pBlockIter);
762
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;
763
  ASSERT(pBlockInfo != NULL);
764

H
Hongze Cheng 已提交
765 766
  SDataBlk* pBlock = getCurrentBlock(pBlockIter);
  int32_t   code = tsdbReadDataBlock(pReader->pFileReader, pBlock, pBlockData);
767 768 769
  if (code != TSDB_CODE_SUCCESS) {
    tsdbError("%p error occurs in loading file block, global index:%d, table index:%d, brange:%" PRId64 "-%" PRId64
              ", rows:%d, code:%s %s",
770
              pReader, pBlockIter->index, pBlockInfo->tbBlockIdx, pBlock->minKey.ts, pBlock->maxKey.ts, pBlock->nRow,
771 772 773
              tstrerror(code), pReader->idStr);
    return code;
  }
774

775
  double elapsedTime = (taosGetTimestampUs() - st) / 1000.0;
776

777 778 779 780
  tsdbDebug("%p load file block into buffer, global index:%d, index in table block list:%d, brange:%" PRId64 "-%" PRId64
            ", rows:%d, minVer:%" PRId64 ", maxVer:%" PRId64 ", elapsed time:%.2f ms, %s",
            pReader, pBlockIter->index, pBlockInfo->tbBlockIdx, pBlock->minKey.ts, pBlock->maxKey.ts, pBlock->nRow,
            pBlock->minVer, pBlock->maxVer, elapsedTime, pReader->idStr);
781 782 783

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

H
Haojun Liao 已提交
785
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
786
}
H
Hongze Cheng 已提交
787

H
Haojun Liao 已提交
788 789 790
static void cleanupBlockOrderSupporter(SBlockOrderSupporter* pSup) {
  taosMemoryFreeClear(pSup->numOfBlocksPerTable);
  taosMemoryFreeClear(pSup->indexPerTable);
H
Hongze Cheng 已提交
791

H
Haojun Liao 已提交
792 793 794 795
  for (int32_t i = 0; i < pSup->numOfTables; ++i) {
    SBlockOrderWrapper* pBlockInfo = pSup->pDataBlockInfo[i];
    taosMemoryFreeClear(pBlockInfo);
  }
H
Hongze Cheng 已提交
796

H
Haojun Liao 已提交
797 798
  taosMemoryFreeClear(pSup->pDataBlockInfo);
}
H
Hongze Cheng 已提交
799

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

H
Haojun Liao 已提交
803
  pSup->numOfBlocksPerTable = taosMemoryCalloc(1, sizeof(int32_t) * numOfTables);
804 805
  pSup->indexPerTable = taosMemoryCalloc(1, sizeof(int32_t) * numOfTables);
  pSup->pDataBlockInfo = taosMemoryCalloc(1, POINTER_BYTES * numOfTables);
H
Hongze Cheng 已提交
806

H
Haojun Liao 已提交
807 808 809 810
  if (pSup->numOfBlocksPerTable == NULL || pSup->indexPerTable == NULL || pSup->pDataBlockInfo == NULL) {
    cleanupBlockOrderSupporter(pSup);
    return TSDB_CODE_OUT_OF_MEMORY;
  }
H
Hongze Cheng 已提交
811

H
Haojun Liao 已提交
812 813
  return TSDB_CODE_SUCCESS;
}
H
Hongze Cheng 已提交
814

H
Haojun Liao 已提交
815
static int32_t fileDataBlockOrderCompar(const void* pLeft, const void* pRight, void* param) {
816
  int32_t leftIndex = *(int32_t*)pLeft;
H
Haojun Liao 已提交
817
  int32_t rightIndex = *(int32_t*)pRight;
H
Hongze Cheng 已提交
818

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

H
Haojun Liao 已提交
821 822
  int32_t leftTableBlockIndex = pSupporter->indexPerTable[leftIndex];
  int32_t rightTableBlockIndex = pSupporter->indexPerTable[rightIndex];
H
Hongze Cheng 已提交
823

H
Haojun Liao 已提交
824 825 826 827 828 829 830
  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 已提交
831

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

835 836 837 838
  return pLeftBlock->offset > pRightBlock->offset ? 1 : -1;
}

static int32_t doSetCurrentBlock(SDataBlockIter* pBlockIter) {
839 840 841
  SFileDataBlockInfo* pBlockInfo = getCurrentBlockInfo(pBlockIter);
  if (pBlockInfo != NULL) {
    STableBlockScanInfo* pScanInfo = taosHashGet(pBlockIter->pTableMap, &pBlockInfo->uid, sizeof(pBlockInfo->uid));
842
    int32_t*             mapDataIndex = taosArrayGet(pScanInfo->pBlockList, pBlockInfo->tbBlockIdx);
H
Hongze Cheng 已提交
843
    tMapDataGetItemByIdx(&pScanInfo->mapData, *mapDataIndex, &pBlockIter->block, tGetDataBlk);
844
  }
845 846 847 848 849 850

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

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

856
  pBlockIter->numOfBlocks = numOfBlocks;
857
  taosArrayClear(pBlockIter->blockList);
858
  pBlockIter->pTableMap = pReader->status.pTableMap;
859

860 861
  // 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 已提交
862

863
  int64_t st = taosGetTimestampUs();
H
Haojun Liao 已提交
864

865
  SBlockOrderSupporter sup = {0};
866
  int32_t              code = initBlockOrderSupporter(&sup, numOfTables);
867 868 869
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }
H
Haojun Liao 已提交
870

871 872 873 874 875 876 877
  int32_t cnt = 0;
  void*   ptr = NULL;
  while (1) {
    ptr = taosHashIterate(pReader->status.pTableMap, ptr);
    if (ptr == NULL) {
      break;
    }
H
Haojun Liao 已提交
878

879 880 881 882
    STableBlockScanInfo* pTableScanInfo = (STableBlockScanInfo*)ptr;
    if (pTableScanInfo->pBlockList == NULL || taosArrayGetSize(pTableScanInfo->pBlockList) == 0) {
      continue;
    }
H
Haojun Liao 已提交
883

884 885
    size_t num = taosArrayGetSize(pTableScanInfo->pBlockList);
    sup.numOfBlocksPerTable[sup.numOfTables] = num;
H
Haojun Liao 已提交
886

887 888 889 890 891
    char* buf = taosMemoryMalloc(sizeof(SBlockOrderWrapper) * num);
    if (buf == NULL) {
      cleanupBlockOrderSupporter(&sup);
      return TSDB_CODE_TDB_OUT_OF_MEMORY;
    }
H
Haojun Liao 已提交
892

893
    sup.pDataBlockInfo[sup.numOfTables] = (SBlockOrderWrapper*)buf;
H
Hongze Cheng 已提交
894
    SDataBlk block = {0};
895 896
    for (int32_t k = 0; k < num; ++k) {
      SBlockOrderWrapper wrapper = {0};
897 898

      int32_t* mapDataIndex = taosArrayGet(pTableScanInfo->pBlockList, k);
H
Hongze Cheng 已提交
899
      tMapDataGetItemByIdx(&pTableScanInfo->mapData, *mapDataIndex, &block, tGetDataBlk);
900

901
      wrapper.uid = pTableScanInfo->uid;
902
      wrapper.offset = block.aSubBlock[0].offset;
H
Haojun Liao 已提交
903

904 905 906 907 908 909
      sup.pDataBlockInfo[sup.numOfTables][k] = wrapper;
      cnt++;
    }

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

911
  ASSERT(numOfBlocks == cnt);
H
Haojun Liao 已提交
912

913
  // since there is only one table qualified, blocks are not sorted
914 915
  if (sup.numOfTables == 1) {
    for (int32_t i = 0; i < numOfBlocks; ++i) {
916 917
      SFileDataBlockInfo blockInfo = {.uid = sup.pDataBlockInfo[0][i].uid, .tbBlockIdx = i};
      taosArrayPush(pBlockIter->blockList, &blockInfo);
918
    }
919

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

924
    pBlockIter->index = asc ? 0 : (numOfBlocks - 1);
H
Haojun Liao 已提交
925
    cleanupBlockOrderSupporter(&sup);
926
    doSetCurrentBlock(pBlockIter);
927
    return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
928
  }
H
Haojun Liao 已提交
929

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

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

935 936 937 938 939
  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 已提交
940
  }
H
Haojun Liao 已提交
941

942 943 944 945
  int32_t numOfTotal = 0;
  while (numOfTotal < cnt) {
    int32_t pos = tMergeTreeGetChosenIndex(pTree);
    int32_t index = sup.indexPerTable[pos]++;
H
Haojun Liao 已提交
946

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

950 951 952 953
    // 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 已提交
954

955 956
    numOfTotal += 1;
    tMergeTreeAdjust(pTree, tMergeTreeGetAdjustIndex(pTree));
H
Haojun Liao 已提交
957
  }
H
Haojun Liao 已提交
958

959
  int64_t et = taosGetTimestampUs();
H
Hongze Cheng 已提交
960 961
  tsdbDebug("%p %d data blocks access order completed, elapsed time:%.2f ms %s", pReader, numOfBlocks,
            (et - st) / 1000.0, pReader->idStr);
962 963
  cleanupBlockOrderSupporter(&sup);
  taosMemoryFree(pTree);
H
Haojun Liao 已提交
964

965
  pBlockIter->index = asc ? 0 : (numOfBlocks - 1);
966 967
  doSetCurrentBlock(pBlockIter);

968
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
969
}
H
Hongze Cheng 已提交
970

H
Haojun Liao 已提交
971
static bool blockIteratorNext(SDataBlockIter* pBlockIter) {
972 973
  bool asc = ASCENDING_TRAVERSE(pBlockIter->order);

974
  int32_t step = asc ? 1 : -1;
975
  if ((pBlockIter->index >= pBlockIter->numOfBlocks - 1 && asc) || (pBlockIter->index <= 0 && (!asc))) {
976 977 978
    return false;
  }

979
  pBlockIter->index += step;
980 981
  doSetCurrentBlock(pBlockIter);

982 983 984
  return true;
}

985 986 987
/**
 * This is an two rectangles overlap cases.
 */
H
Hongze Cheng 已提交
988
static int32_t dataBlockPartiallyRequired(STimeWindow* pWindow, SVersionRange* pVerRange, SDataBlk* pBlock) {
989 990
  return (pWindow->ekey < pBlock->maxKey.ts && pWindow->ekey >= pBlock->minKey.ts) ||
         (pWindow->skey > pBlock->minKey.ts && pWindow->skey <= pBlock->maxKey.ts) ||
H
Hongze Cheng 已提交
991 992
         (pVerRange->minVer > pBlock->minVer && pVerRange->minVer <= pBlock->maxVer) ||
         (pVerRange->maxVer < pBlock->maxVer && pVerRange->maxVer >= pBlock->minVer);
H
Haojun Liao 已提交
993
}
H
Hongze Cheng 已提交
994

H
Hongze Cheng 已提交
995 996
static SDataBlk* getNeighborBlockOfSameTable(SFileDataBlockInfo* pFBlockInfo, STableBlockScanInfo* pTableBlockScanInfo,
                                             int32_t* nextIndex, int32_t order) {
997 998 999
  bool asc = ASCENDING_TRAVERSE(order);
  if (asc && pFBlockInfo->tbBlockIdx >= taosArrayGetSize(pTableBlockScanInfo->pBlockList) - 1) {
    return NULL;
1000 1001
  }

1002
  if (!asc && pFBlockInfo->tbBlockIdx == 0) {
1003 1004 1005
    return NULL;
  }

1006
  int32_t step = asc ? 1 : -1;
1007
  *nextIndex = pFBlockInfo->tbBlockIdx + step;
1008

H
Hongze Cheng 已提交
1009 1010
  SDataBlk* pBlock = taosMemoryCalloc(1, sizeof(SDataBlk));
  int32_t*  indexInMapdata = taosArrayGet(pTableBlockScanInfo->pBlockList, *nextIndex);
1011

H
Hongze Cheng 已提交
1012
  tMapDataGetItemByIdx(&pTableBlockScanInfo->mapData, *indexInMapdata, pBlock, tGetDataBlk);
1013
  return pBlock;
1014 1015 1016 1017 1018
}

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

1019
  int32_t step = ASCENDING_TRAVERSE(pBlockIter->order) ? 1 : -1;
1020 1021
  int32_t index = pBlockIter->index;

1022
  while (index < pBlockIter->numOfBlocks && index >= 0) {
1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034
    SFileDataBlockInfo* pFBlock = taosArrayGet(pBlockIter->blockList, index);
    if (pFBlock->uid == pFBlockInfo->uid && pFBlock->tbBlockIdx == pFBlockInfo->tbBlockIdx) {
      return index;
    }

    index += step;
  }

  ASSERT(0);
  return -1;
}

1035
static int32_t setFileBlockActiveInBlockIter(SDataBlockIter* pBlockIter, int32_t index, int32_t step) {
1036
  if (index < 0 || index >= pBlockIter->numOfBlocks) {
1037 1038 1039 1040
    return -1;
  }

  SFileDataBlockInfo fblock = *(SFileDataBlockInfo*)taosArrayGet(pBlockIter->blockList, index);
1041 1042 1043 1044 1045
  pBlockIter->index += step;

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

1047 1048 1049
    SFileDataBlockInfo* pBlockInfo = taosArrayGet(pBlockIter->blockList, pBlockIter->index);
    ASSERT(pBlockInfo->uid == fblock.uid && pBlockInfo->tbBlockIdx == fblock.tbBlockIdx);
  }
1050

1051
  doSetCurrentBlock(pBlockIter);
1052 1053 1054
  return TSDB_CODE_SUCCESS;
}

H
Hongze Cheng 已提交
1055
static bool overlapWithNeighborBlock(SDataBlk* pBlock, SDataBlk* pNeighbor, int32_t order) {
1056 1057 1058 1059 1060 1061
  // 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 已提交
1062
}
H
Hongze Cheng 已提交
1063

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

1067
  return (ascScan && (key.ts != TSKEY_INITIAL_VAL && key.ts <= pBlock->minKey.ts)) ||
1068
         (!ascScan && (key.ts != TSKEY_INITIAL_VAL && key.ts >= pBlock->maxKey.ts));
H
Haojun Liao 已提交
1069
}
H
Hongze Cheng 已提交
1070

H
Hongze Cheng 已提交
1071
static bool keyOverlapFileBlock(TSDBKEY key, SDataBlk* pBlock, SVersionRange* pVerRange) {
H
Hongze Cheng 已提交
1072 1073
  return (key.ts >= pBlock->minKey.ts && key.ts <= pBlock->maxKey.ts) && (pBlock->maxVer >= pVerRange->minVer) &&
         (pBlock->minVer <= pVerRange->maxVer);
H
Haojun Liao 已提交
1074 1075
}

H
Hongze Cheng 已提交
1076
static bool doCheckforDatablockOverlap(STableBlockScanInfo* pBlockScanInfo, const SDataBlk* pBlock) {
1077 1078 1079 1080 1081
  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 已提交
1082
      if (p->version >= pBlock->minVer) {
1083 1084 1085
        return true;
      }
    } else if (p->ts < pBlock->minKey.ts) {  // p->ts < pBlock->minKey.ts
H
Hongze Cheng 已提交
1086
      if (p->version >= pBlock->minVer) {
1087 1088 1089 1090 1091 1092 1093
        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 已提交
1094
            if (pnext->ts >= pBlock->minKey.ts && pnext->version >= pBlock->minVer) {
1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109
              return true;
            }
          }
        } else {  // it must be the last point
          ASSERT(p->version == 0);
        }
      }
    } else {  // (p->ts > pBlock->maxKey.ts) {
      return false;
    }
  }

  return false;
}

H
Hongze Cheng 已提交
1110
static bool overlapWithDelSkyline(STableBlockScanInfo* pBlockScanInfo, const SDataBlk* pBlock, int32_t order) {
1111 1112 1113 1114
  if (pBlockScanInfo->delSkyline == NULL) {
    return false;
  }

1115
  // ts is not overlap
1116
  TSDBKEY* pFirst = taosArrayGet(pBlockScanInfo->delSkyline, 0);
L
Liu Jicong 已提交
1117
  TSDBKEY* pLast = taosArrayGetLast(pBlockScanInfo->delSkyline);
1118 1119 1120 1121 1122
  if (pBlock->minKey.ts > pLast->ts || pBlock->maxKey.ts < pFirst->ts) {
    return false;
  }

  // version is not overlap
1123 1124 1125 1126
  if (ASCENDING_TRAVERSE(order)) {
    return doCheckforDatablockOverlap(pBlockScanInfo, pBlock);
  } else {
    int32_t index = pBlockScanInfo->fileDelIndex;
1127
    while (1) {
1128 1129 1130 1131 1132
      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;
1133 1134 1135
      }
    }

1136 1137
    return doCheckforDatablockOverlap(pBlockScanInfo, pBlock);
  }
1138 1139
}

1140 1141 1142 1143
// 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
1144
// 5. delete info should not overlap with current block data
H
Hongze Cheng 已提交
1145
static bool fileBlockShouldLoad(STsdbReader* pReader, SFileDataBlockInfo* pFBlock, SDataBlk* pBlock,
1146
                                STableBlockScanInfo* pScanInfo, TSDBKEY key, SLastBlockReader* pLastBlockReader) {
H
Hongze Cheng 已提交
1147 1148
  int32_t   neighborIndex = 0;
  SDataBlk* pNeighbor = getNeighborBlockOfSameTable(pFBlock, pScanInfo, &neighborIndex, pReader->order);
1149

1150
  // overlap with neighbor
1151 1152 1153
  bool overlapWithNeighbor = false;
  if (pNeighbor) {
    overlapWithNeighbor = overlapWithNeighborBlock(pBlock, pNeighbor, pReader->order);
1154
    taosMemoryFree(pNeighbor);
1155 1156
  }

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

1161
  // todo here we need to each key in the last files to identify if it is really overlapped with last block
1162
  // todo
1163
  bool overlapWithlastBlock = false;
1164
#if 0
H
Hongze Cheng 已提交
1165
  if (taosArrayGetSize(pLastBlockReader->pSstBlk) > 0 && (pLastBlockReader->currentBlockIndex != -1)) {
H
Hongze Cheng 已提交
1166
    SSttBlk* pSstBlk = taosArrayGet(pLastBlockReader->pSstBlk, pLastBlockReader->currentBlockIndex);
H
Hongze Cheng 已提交
1167
    overlapWithlastBlock = !(pBlock->maxKey.ts < pSstBlk->minKey || pBlock->minKey.ts > pSstBlk->maxKey);
1168
  }
1169
#endif
1170

1171 1172 1173 1174 1175 1176 1177 1178 1179 1180
  bool moreThanOutputCapacity = pBlock->nRow > pReader->capacity;
  bool partiallyRequired = dataBlockPartiallyRequired(&pReader->window, &pReader->verRange, pBlock);
  bool overlapWithKey = keyOverlapFileBlock(key, pBlock, &pReader->verRange);

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

  // log the reason why load the datablock for profile
  if (loadDataBlock) {
    tsdbDebug("%p uid:%" PRIu64
1181
              " need to load the datablock, overlapwithneighborblock:%d, hasDup:%d, partiallyRequired:%d, "
1182 1183 1184 1185 1186 1187
              "overlapWithKey:%d, greaterThanBuf:%d, overlapWithDel:%d, overlapWithlastBlock:%d, %s",
              pReader, pFBlock->uid, overlapWithNeighbor, hasDup, partiallyRequired, overlapWithKey,
              moreThanOutputCapacity, overlapWithDel, overlapWithlastBlock, pReader->idStr);
  }

  return loadDataBlock;
H
Haojun Liao 已提交
1188 1189
}

1190
static int32_t buildDataBlockFromBuf(STsdbReader* pReader, STableBlockScanInfo* pBlockScanInfo, int64_t endKey) {
1191
  if (!(pBlockScanInfo->iiter.hasVal || pBlockScanInfo->iter.hasVal)) {
1192 1193
    return TSDB_CODE_SUCCESS;
  }
H
Haojun Liao 已提交
1194

1195 1196 1197
  SSDataBlock* pBlock = pReader->pResBlock;

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

1200
  blockDataUpdateTsWindow(pBlock, 0);
1201
  pBlock->info.uid = pBlockScanInfo->uid;
1202

1203
  setComposedBlockFlag(pReader, true);
1204

1205
  double elapsedTime = (taosGetTimestampUs() - st) / 1000.0;
S
Shengliang Guan 已提交
1206
  tsdbDebug("%p build data block from cache completed, elapsed time:%.2f ms, numOfRows:%d, brange:%" PRId64
1207 1208 1209
            " - %" PRId64 " %s",
            pReader, elapsedTime, pBlock->info.rows, pBlock->info.window.skey, pBlock->info.window.ekey,
            pReader->idStr);
1210 1211

  pReader->cost.buildmemBlock += elapsedTime;
H
Haojun Liao 已提交
1212 1213 1214
  return code;
}

1215 1216
static bool tryCopyDistinctRowFromFileBlock(STsdbReader* pReader, SBlockData* pBlockData, int64_t key,
                                            SFileBlockDumpInfo* pDumpInfo) {
1217 1218 1219 1220 1221
  // 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)) {
1222
    int32_t step = pReader->order == TSDB_ORDER_ASC ? 1 : -1;
1223 1224

    int64_t nextKey = pBlockData->aTSKEY[pDumpInfo->rowIndex + step];
1225
    if (nextKey != key) {  // merge is not needed
1226
      doAppendRowFromFileBlock(pReader->pResBlock, pReader, pBlockData, pDumpInfo->rowIndex);
1227 1228 1229 1230 1231 1232 1233 1234
      pDumpInfo->rowIndex += step;
      return true;
    }
  }

  return false;
}

H
Haojun Liao 已提交
1235 1236 1237 1238 1239 1240
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);
  }

1241
  if (pReader->pSchema && sversion == pReader->pSchema->version) {
H
Haojun Liao 已提交
1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259
    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;
}

1260
static int32_t doMergeBufAndFileRows(STsdbReader* pReader, STableBlockScanInfo* pBlockScanInfo, TSDBROW* pRow,
1261 1262 1263 1264 1265 1266
                                     SIterInfo* pIter, int64_t key, SLastBlockReader* pLastBlockReader) {
  SRowMerger          merge = {0};
  STSRow*             pTSRow = NULL;
  SBlockData*         pBlockData = &pReader->status.fileBlockData;
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;

1267
  int64_t tsLast = INT64_MIN;
1268
  if (hasDataInLastBlock(pLastBlockReader)) {
1269 1270
    tsLast = getCurrentKeyInLastBlock(pLastBlockReader);
  }
1271

H
Hongze Cheng 已提交
1272 1273
  TSDBKEY k = TSDBROW_KEY(pRow);
  TSDBROW fRow = tsdbRowFromBlockData(pBlockData, pDumpInfo->rowIndex);
1274

1275 1276
  int64_t minKey = 0;
  if (pReader->order == TSDB_ORDER_ASC) {
H
Hongze Cheng 已提交
1277
    minKey = INT64_MAX;  // chosen the minimum value
1278
    if (minKey > tsLast && hasDataInLastBlock(pLastBlockReader)) {
1279 1280
      minKey = tsLast;
    }
1281

1282 1283 1284
    if (minKey > k.ts) {
      minKey = k.ts;
    }
1285

1286 1287 1288 1289 1290
    if (minKey > key && pBlockData->nRow > 0) {
      minKey = key;
    }
  } else {
    minKey = INT64_MIN;
1291
    if (minKey < tsLast && hasDataInLastBlock(pLastBlockReader)) {
1292 1293 1294 1295 1296 1297 1298 1299 1300 1301
      minKey = tsLast;
    }

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

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

  bool init = false;

1306
  // ASC: file block ---> last block -----> imem -----> mem
H
Hongze Cheng 已提交
1307
  // DESC: mem -----> imem -----> last block -----> file block
1308 1309
  if (pReader->order == TSDB_ORDER_ASC) {
    if (minKey == key) {
1310
      init = true;
1311 1312
      tRowMergerInit(&merge, &fRow, pReader->pSchema);
      doMergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pReader, &merge);
1313 1314
    }

1315
    if (minKey == tsLast) {
1316
      TSDBROW fRow1 = tMergeTreeGetRow(&pLastBlockReader->mergeTree);
H
Haojun Liao 已提交
1317 1318 1319
      if (init) {
        tRowMerge(&merge, &fRow1);
      } else {
1320 1321 1322
        init = true;
        tRowMergerInit(&merge, &fRow1, pReader->pSchema);
      }
H
Haojun Liao 已提交
1323
      doMergeRowsInLastBlock(pLastBlockReader, pBlockScanInfo, tsLast, &merge);
1324
    }
1325

1326
    if (minKey == k.ts) {
H
Haojun Liao 已提交
1327 1328 1329
      if (init) {
        tRowMerge(&merge, pRow);
      } else {
1330 1331 1332 1333 1334 1335 1336 1337 1338
        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;
1339 1340
      STSchema* pSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(pRow), pReader, pBlockScanInfo->uid);
      tRowMergerInit(&merge, pRow, pSchema);
1341
      doMergeRowsInBuf(pIter, pBlockScanInfo->uid, k.ts, pBlockScanInfo->delSkyline, &merge, pReader);
1342 1343
    }

1344
    if (minKey == tsLast) {
1345
      TSDBROW fRow1 = tMergeTreeGetRow(&pLastBlockReader->mergeTree);
H
Haojun Liao 已提交
1346 1347 1348
      if (init) {
        tRowMerge(&merge, &fRow1);
      } else {
1349 1350 1351
        init = true;
        tRowMergerInit(&merge, &fRow1, pReader->pSchema);
      }
H
Haojun Liao 已提交
1352
      doMergeRowsInLastBlock(pLastBlockReader, pBlockScanInfo, tsLast, &merge);
1353 1354 1355
    }

    if (minKey == key) {
H
Haojun Liao 已提交
1356 1357 1358
      if (init) {
        tRowMerge(&merge, &fRow);
      } else {
1359 1360 1361 1362 1363
        init = true;
        tRowMergerInit(&merge, &fRow, pReader->pSchema);
      }
      doMergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pReader, &merge);
    }
1364 1365
  }

1366 1367 1368 1369 1370
  int32_t code = tRowMergerGetRow(&merge, &pTSRow);
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

1371 1372 1373 1374 1375 1376 1377
  doAppendRowFromTSRow(pReader->pResBlock, pReader, pTSRow, pBlockScanInfo->uid);

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

1378 1379 1380
static int32_t doMergeFileBlockAndLastBlock(SLastBlockReader* pLastBlockReader, STsdbReader* pReader,
                                            STableBlockScanInfo* pBlockScanInfo, SBlockData* pBlockData,
                                            bool mergeBlockData) {
1381
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;
S
Shengliang Guan 已提交
1382
  // SBlockData* pLastBlockData = &pLastBlockReader->lastBlockData;
H
Hongze Cheng 已提交
1383
  int64_t tsLastBlock = getCurrentKeyInLastBlock(pLastBlockReader);
1384 1385 1386 1387

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

1388
  TSDBROW fRow = tMergeTreeGetRow(&pLastBlockReader->mergeTree);
1389 1390 1391 1392
  tRowMergerInit(&merge, &fRow, pReader->pSchema);
  doMergeRowsInLastBlock(pLastBlockReader, pBlockScanInfo, tsLastBlock, &merge);

  // merge with block data if ts == key
1393
  if (mergeBlockData && (tsLastBlock == pBlockData->aTSKEY[pDumpInfo->rowIndex])) {
1394 1395 1396
    doMergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pReader, &merge);
  }

1397 1398 1399 1400 1401
  int32_t code = tRowMergerGetRow(&merge, &pTSRow);
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

1402 1403 1404 1405 1406 1407 1408
  doAppendRowFromTSRow(pReader->pResBlock, pReader, pTSRow, pBlockScanInfo->uid);

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

1409 1410
static int32_t mergeFileBlockAndLastBlock(STsdbReader* pReader, SLastBlockReader* pLastBlockReader, int64_t key,
                                          STableBlockScanInfo* pBlockScanInfo, SBlockData* pBlockData) {
1411 1412
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;

1413 1414
  if (pBlockData->nRow > 0) {
    // no last block available, only data block exists
1415
    if (!hasDataInLastBlock(pLastBlockReader)) {
1416 1417 1418 1419 1420 1421 1422 1423 1424
      return mergeRowsInFileBlocks(pBlockData, pBlockScanInfo, key, pReader);
    }

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

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

1431 1432
        tRowMergerInit(&merge, &fRow, pReader->pSchema);
        doMergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pReader, &merge);
1433
        doMergeRowsInLastBlock(pLastBlockReader, pBlockScanInfo, ts, &merge);
1434

1435 1436 1437 1438 1439
        int32_t code = tRowMergerGetRow(&merge, &pTSRow);
        if (code != TSDB_CODE_SUCCESS) {
          return code;
        }

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

1442 1443
        taosMemoryFree(pTSRow);
        tRowMergerClear(&merge);
1444
        return code;
1445
      } else {
1446 1447
        ASSERT(0);
        return TSDB_CODE_SUCCESS;
1448
      }
1449
    } else {  // desc order
1450
      return doMergeFileBlockAndLastBlock(pLastBlockReader, pReader, pBlockScanInfo, pBlockData, true);
1451
    }
1452
  } else {  // only last block exists
1453
    return doMergeFileBlockAndLastBlock(pLastBlockReader, pReader, pBlockScanInfo, NULL, false);
H
Haojun Liao 已提交
1454
  }
1455 1456
}

1457 1458
static int32_t doMergeMultiLevelRows(STsdbReader* pReader, STableBlockScanInfo* pBlockScanInfo, SBlockData* pBlockData,
                                     SLastBlockReader* pLastBlockReader) {
1459 1460 1461 1462 1463 1464
  SRowMerger merge = {0};
  STSRow*    pTSRow = NULL;

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

1465 1466
  TSDBROW* pRow = getValidMemRow(&pBlockScanInfo->iter, pDelList, pReader);
  TSDBROW* piRow = getValidMemRow(&pBlockScanInfo->iiter, pDelList, pReader);
1467 1468
  ASSERT(pRow != NULL && piRow != NULL);

1469
  int64_t tsLast = INT64_MIN;
1470 1471 1472
  if (hasDataInLastBlock(pLastBlockReader)) {
    tsLast = getCurrentKeyInLastBlock(pLastBlockReader);
  }
1473 1474 1475 1476 1477 1478

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

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

1479
  int64_t minKey = 0;
1480 1481 1482 1483 1484
  if (ASCENDING_TRAVERSE(pReader->order)) {
    minKey = INT64_MAX;  // let's find the minimum
    if (minKey > k.ts) {
      minKey = k.ts;
    }
1485

1486 1487 1488
    if (minKey > ik.ts) {
      minKey = ik.ts;
    }
1489

1490 1491 1492
    if (minKey > key && pBlockData->nRow > 0) {
      minKey = key;
    }
1493

1494
    if (minKey > tsLast && hasDataInLastBlock(pLastBlockReader)) {
1495 1496 1497
      minKey = tsLast;
    }
  } else {
H
Hongze Cheng 已提交
1498
    minKey = INT64_MIN;  // let find the maximum ts value
1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510
    if (minKey < k.ts) {
      minKey = k.ts;
    }

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

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

1511
    if (minKey < tsLast && hasDataInLastBlock(pLastBlockReader)) {
1512 1513
      minKey = tsLast;
    }
1514 1515 1516 1517
  }

  bool init = false;

1518 1519 1520 1521
  // ASC: file block -----> last block -----> imem -----> mem
  // DESC: mem -----> imem -----> last block -----> file block
  if (ASCENDING_TRAVERSE(pReader->order)) {
    if (minKey == key) {
1522
      init = true;
1523 1524 1525
      TSDBROW fRow = tsdbRowFromBlockData(pBlockData, pDumpInfo->rowIndex);
      tRowMergerInit(&merge, &fRow, pReader->pSchema);
      doMergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pReader, &merge);
1526 1527
    }

1528
    if (minKey == tsLast) {
1529
      TSDBROW fRow1 = tMergeTreeGetRow(&pLastBlockReader->mergeTree);
H
Haojun Liao 已提交
1530 1531 1532
      if (init) {
        tRowMerge(&merge, &fRow1);
      } else {
1533 1534 1535
        init = true;
        tRowMergerInit(&merge, &fRow1, pReader->pSchema);
      }
H
Haojun Liao 已提交
1536
      doMergeRowsInLastBlock(pLastBlockReader, pBlockScanInfo, tsLast, &merge);
1537 1538 1539
    }

    if (minKey == ik.ts) {
H
Haojun Liao 已提交
1540 1541 1542
      if (init) {
        tRowMerge(&merge, piRow);
      } else {
1543 1544 1545 1546 1547
        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);
1548 1549
    }

1550
    if (minKey == k.ts) {
H
Haojun Liao 已提交
1551 1552 1553
      if (init) {
        tRowMerge(&merge, pRow);
      } else {
1554 1555 1556 1557 1558 1559 1560 1561
        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;
1562 1563
      STSchema* pSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(pRow), pReader, pBlockScanInfo->uid);
      tRowMergerInit(&merge, pRow, pSchema);
1564 1565 1566 1567
      doMergeRowsInBuf(&pBlockScanInfo->iter, pBlockScanInfo->uid, k.ts, pBlockScanInfo->delSkyline, &merge, pReader);
    }

    if (minKey == ik.ts) {
H
Haojun Liao 已提交
1568 1569 1570
      if (init) {
        tRowMerge(&merge, piRow);
      } else {
1571 1572 1573 1574 1575 1576 1577 1578
        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) {
1579
      TSDBROW fRow1 = tMergeTreeGetRow(&pLastBlockReader->mergeTree);
H
Haojun Liao 已提交
1580 1581 1582
      if (init) {
        tRowMerge(&merge, &fRow1);
      } else {
1583 1584 1585
        init = true;
        tRowMergerInit(&merge, &fRow1, pReader->pSchema);
      }
H
Haojun Liao 已提交
1586
      doMergeRowsInLastBlock(pLastBlockReader, pBlockScanInfo, tsLast, &merge);
1587 1588 1589
    }

    if (minKey == key) {
H
Haojun Liao 已提交
1590
      TSDBROW fRow = tsdbRowFromBlockData(pBlockData, pDumpInfo->rowIndex);
1591 1592
      if (!init) {
        tRowMergerInit(&merge, &fRow, pReader->pSchema);
H
Haojun Liao 已提交
1593 1594
      } else {
        tRowMerge(&merge, &fRow);
1595 1596
      }
      doMergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pReader, &merge);
1597 1598 1599
    }
  }

1600 1601 1602 1603 1604
  int32_t code = tRowMergerGetRow(&merge, &pTSRow);
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

1605 1606 1607 1608
  doAppendRowFromTSRow(pReader->pResBlock, pReader, pTSRow, pBlockScanInfo->uid);

  taosMemoryFree(pTSRow);
  tRowMergerClear(&merge);
1609
  return code;
1610 1611
}

1612
#if 0
1613
static int32_t doMergeThreeLevelRows(STsdbReader* pReader, STableBlockScanInfo* pBlockScanInfo, SBlockData* pBlockData) {
1614 1615 1616
  SRowMerger merge = {0};
  STSRow*    pTSRow = NULL;

1617
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;
dengyihao's avatar
dengyihao 已提交
1618
  SArray*             pDelList = pBlockScanInfo->delSkyline;
1619

1620 1621
  TSDBROW* pRow = getValidMemRow(&pBlockScanInfo->iter, pDelList, pReader);
  TSDBROW* piRow = getValidMemRow(&pBlockScanInfo->iiter, pDelList, pReader);
1622
  ASSERT(pRow != NULL && piRow != NULL);
H
Haojun Liao 已提交
1623

1624
  int64_t key = pBlockData->aTSKEY[pDumpInfo->rowIndex];
1625
  bool    freeTSRow = false;
H
Haojun Liao 已提交
1626

1627
  uint64_t uid = pBlockScanInfo->uid;
H
Haojun Liao 已提交
1628

1629 1630 1631
  TSDBKEY k = TSDBROW_KEY(pRow);
  TSDBKEY ik = TSDBROW_KEY(piRow);
  if (ASCENDING_TRAVERSE(pReader->order)) {
1632 1633
    // [1&2] key <= [k.ts && ik.ts]
    if (key <= k.ts && key <= ik.ts) {
1634 1635 1636
      TSDBROW fRow = tsdbRowFromBlockData(pBlockData, pDumpInfo->rowIndex);
      tRowMergerInit(&merge, &fRow, pReader->pSchema);

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

1639 1640
      if (ik.ts == key) {
        tRowMerge(&merge, piRow);
1641
        doMergeRowsInBuf(&pBlockScanInfo->iiter, uid, key, pBlockScanInfo->delSkyline, &merge, pReader);
1642 1643
      }

1644 1645
      if (k.ts == key) {
        tRowMerge(&merge, pRow);
1646
        doMergeRowsInBuf(&pBlockScanInfo->iter, uid, key, pBlockScanInfo->delSkyline, &merge, pReader);
1647 1648 1649
      }

      tRowMergerGetRow(&merge, &pTSRow);
H
Haojun Liao 已提交
1650
      doAppendRowFromTSRow(pReader->pResBlock, pReader, pTSRow, uid);
1651
      return TSDB_CODE_SUCCESS;
1652
    } else {  // key > ik.ts || key > k.ts
1653 1654
      ASSERT(key != ik.ts);

1655
      // [3] ik.ts < key <= k.ts
1656
      // [4] ik.ts < k.ts <= key
1657
      if (ik.ts < k.ts) {
1658
        doMergeMemTableMultiRows(piRow, uid, &pBlockScanInfo->iiter, pDelList, &pTSRow, pReader, &freeTSRow);
H
Haojun Liao 已提交
1659
        doAppendRowFromTSRow(pReader->pResBlock, pReader, pTSRow, uid);
1660 1661 1662
        if (freeTSRow) {
          taosMemoryFree(pTSRow);
        }
1663 1664 1665
        return TSDB_CODE_SUCCESS;
      }

1666 1667
      // [5] k.ts < key   <= ik.ts
      // [6] k.ts < ik.ts <= key
1668
      if (k.ts < ik.ts) {
1669
        doMergeMemTableMultiRows(pRow, uid, &pBlockScanInfo->iter, pDelList, &pTSRow, pReader, &freeTSRow);
H
Haojun Liao 已提交
1670
        doAppendRowFromTSRow(pReader->pResBlock, pReader, pTSRow, uid);
1671 1672 1673
        if (freeTSRow) {
          taosMemoryFree(pTSRow);
        }
1674 1675 1676
        return TSDB_CODE_SUCCESS;
      }

1677
      // [7] k.ts == ik.ts < key
1678
      if (k.ts == ik.ts) {
1679 1680
        ASSERT(key > ik.ts && key > k.ts);

1681
        doMergeMemIMemRows(pRow, piRow, pBlockScanInfo, pReader, &pTSRow);
H
Haojun Liao 已提交
1682
        doAppendRowFromTSRow(pReader->pResBlock, pReader, pTSRow, uid);
1683
        taosMemoryFree(pTSRow);
1684 1685 1686
        return TSDB_CODE_SUCCESS;
      }
    }
1687 1688 1689
  } else {  // descending order scan
    // [1/2] k.ts >= ik.ts && k.ts >= key
    if (k.ts >= ik.ts && k.ts >= key) {
H
Haojun Liao 已提交
1690
      STSchema* pSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(pRow), pReader, pBlockScanInfo->uid);
1691

H
Haojun Liao 已提交
1692
      tRowMergerInit(&merge, pRow, pSchema);
1693
      doMergeRowsInBuf(&pBlockScanInfo->iter, uid, key, pBlockScanInfo->delSkyline, &merge, pReader);
1694 1695 1696

      if (ik.ts == k.ts) {
        tRowMerge(&merge, piRow);
1697
        doMergeRowsInBuf(&pBlockScanInfo->iiter, uid, key, pBlockScanInfo->delSkyline, &merge, pReader);
1698 1699 1700 1701 1702 1703 1704 1705 1706
      }

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

      tRowMergerGetRow(&merge, &pTSRow);
H
Haojun Liao 已提交
1707
      doAppendRowFromTSRow(pReader->pResBlock, pReader, pTSRow, uid);
1708 1709
      return TSDB_CODE_SUCCESS;
    } else {
1710
      ASSERT(ik.ts != k.ts);  // this case has been included in the previous if branch
1711 1712 1713 1714

      // [3] ik.ts > k.ts >= Key
      // [4] ik.ts > key >= k.ts
      if (ik.ts > key) {
1715
        doMergeMemTableMultiRows(piRow, uid, &pBlockScanInfo->iiter, pDelList, &pTSRow, pReader, &freeTSRow);
H
Haojun Liao 已提交
1716
        doAppendRowFromTSRow(pReader->pResBlock, pReader, pTSRow, uid);
1717 1718 1719
        if (freeTSRow) {
          taosMemoryFree(pTSRow);
        }
1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730
        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 已提交
1731
        doAppendRowFromTSRow(pReader->pResBlock, pReader, pTSRow, uid);
1732
        taosMemoryFree(pTSRow);
1733 1734 1735 1736 1737
        return TSDB_CODE_SUCCESS;
      }

      //[7] key = ik.ts > k.ts
      if (key == ik.ts) {
1738
        doMergeMemTableMultiRows(piRow, uid, &pBlockScanInfo->iiter, pDelList, &pTSRow, pReader, &freeTSRow);
1739 1740 1741 1742 1743

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

        taosMemoryFree(pTSRow);
1747 1748 1749 1750 1751 1752
        return TSDB_CODE_SUCCESS;
      }
    }
  }

  ASSERT(0);
S
Shengliang Guan 已提交
1753
  return -1;
1754
}
1755
#endif
1756

1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781
static int32_t initMemDataIterator(STableBlockScanInfo* pBlockScanInfo, STsdbReader* pReader) {
  if (pBlockScanInfo->iterInit) {
    return TSDB_CODE_SUCCESS;
  }

  int32_t code = TSDB_CODE_SUCCESS;

  TSDBKEY startKey = {0};
  if (ASCENDING_TRAVERSE(pReader->order)) {
    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));

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

        tsdbDebug("%p uid:%" PRId64 ", check data in mem from skey:%" PRId64 ", order:%d, ts range in buf:%" PRId64
H
Hongze Cheng 已提交
1782
                  "-%" PRId64 " %s",
1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802
                  pReader, pBlockScanInfo->uid, startKey.ts, pReader->order, d->minKey, d->maxKey, pReader->idStr);
      } else {
        tsdbError("%p uid:%" PRId64 ", failed to create iterator for imem, code:%s, %s", pReader, pBlockScanInfo->uid,
                  tstrerror(code), pReader->idStr);
        return code;
      }
    }
  } else {
    tsdbDebug("%p uid:%" PRId64 ", no data in mem, %s", pReader, pBlockScanInfo->uid, pReader->idStr);
  }

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

        tsdbDebug("%p uid:%" PRId64 ", check data in imem from skey:%" PRId64 ", order:%d, ts range in buf:%" PRId64
H
Hongze Cheng 已提交
1803
                  "-%" PRId64 " %s",
1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820
                  pReader, pBlockScanInfo->uid, startKey.ts, pReader->order, di->minKey, di->maxKey, pReader->idStr);
      } else {
        tsdbError("%p uid:%" PRId64 ", failed to create iterator for mem, code:%s, %s", pReader, pBlockScanInfo->uid,
                  tstrerror(code), pReader->idStr);
        return code;
      }
    }
  } else {
    tsdbDebug("%p uid:%" PRId64 ", no data in imem, %s", pReader, pBlockScanInfo->uid, pReader->idStr);
  }

  initDelSkylineIterator(pBlockScanInfo, pReader, d, di);

  pBlockScanInfo->iterInit = true;
  return TSDB_CODE_SUCCESS;
}

dengyihao's avatar
dengyihao 已提交
1821 1822
static bool isValidFileBlockRow(SBlockData* pBlockData, SFileBlockDumpInfo* pDumpInfo,
                                STableBlockScanInfo* pBlockScanInfo, STsdbReader* pReader) {
1823 1824 1825 1826 1827 1828 1829 1830
  // 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;
    }
  }

1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841
  // 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;
  }

1842
  TSDBKEY k = {.ts = ts, .version = ver};
1843
  if (hasBeenDropped(pBlockScanInfo->delSkyline, &pBlockScanInfo->fileDelIndex, &k, pReader->order)) {
1844 1845 1846
    return false;
  }

1847 1848 1849
  return true;
}

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

1852
static bool nextRowFromLastBlocks(SLastBlockReader* pLastBlockReader, STableBlockScanInfo* pBlockScanInfo) {
H
Hongze Cheng 已提交
1853
  while (1) {
1854 1855 1856 1857
    bool hasVal = tMergeTreeNext(&pLastBlockReader->mergeTree);
    if (!hasVal) {
      return false;
    }
1858

1859 1860 1861 1862 1863
    TSDBROW row = tMergeTreeGetRow(&pLastBlockReader->mergeTree);
    TSDBKEY k = TSDBROW_KEY(&row);
    if (!hasBeenDropped(pBlockScanInfo->delSkyline, &pBlockScanInfo->lastBlockDelIndex, &k, pLastBlockReader->order)) {
      return true;
    }
1864 1865
  }

1866
#if 0
1867
  *(pLastBlockReader->rowIndex) += step;
1868 1869

  SBlockData* pBlockData = &pLastBlockReader->lastBlockData;
H
Hongze Cheng 已提交
1870
  for (int32_t i = *(pLastBlockReader->rowIndex); i < pBlockData->nRow && i >= 0; i += step) {
1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884
    if (pBlockData->aUid != NULL) {
      if (asc) {
        if (pBlockData->aUid[i] < pLastBlockReader->uid) {
          continue;
        } else if (pBlockData->aUid[i] > pLastBlockReader->uid) {
          break;
        }
      } else {
        if (pBlockData->aUid[i] > pLastBlockReader->uid) {
          continue;
        } else if (pBlockData->aUid[i] < pLastBlockReader->uid) {
          break;
        }
      }
1885 1886
    }

H
Haojun Liao 已提交
1887 1888
    int64_t ts = pBlockData->aTSKEY[i];
    if (ts < pLastBlockReader->window.skey) {
1889 1890 1891
      continue;
    }

H
Haojun Liao 已提交
1892 1893
    int64_t ver = pBlockData->aVersion[i];
    if (ver < pLastBlockReader->verRange.minVer) {
1894 1895 1896
      continue;
    }

H
Haojun Liao 已提交
1897
    // no data any more, todo opt handle desc case
H
Haojun Liao 已提交
1898
    if (ts > pLastBlockReader->window.ekey) {
H
Haojun Liao 已提交
1899
      continue;
1900 1901
    }

H
Haojun Liao 已提交
1902
    // todo opt handle desc case
H
Haojun Liao 已提交
1903 1904 1905 1906 1907
    if (ver > pLastBlockReader->verRange.maxVer) {
      continue;
    }

    TSDBKEY k = {.ts = ts, .version = ver};
1908
    if (hasBeenDropped(pBlockScanInfo->delSkyline, &pBlockScanInfo->lastBlockDelIndex, &k, pLastBlockReader->order)) {
H
Haojun Liao 已提交
1909
      continue;
1910 1911
    }

1912
    *(pLastBlockReader->rowIndex) = i;
1913 1914 1915
    return true;
  }

1916
  // set all data is consumed in last block
1917
  setAllRowsChecked(pLastBlockReader);
1918
  return false;
1919
#endif
1920 1921
}

1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936
static bool initLastBlockReader(SLastBlockReader* pLastBlockReader, STableBlockScanInfo* pBlockScanInfo,
                                STsdbReader* pReader) {
  // the last block reader has been initialized for this table.
  if (pLastBlockReader->uid == pBlockScanInfo->uid) {
    return true;
  }

  if (pLastBlockReader->uid != 0) {
    tMergeTreeClose(&pLastBlockReader->mergeTree);
  }

  initMemDataIterator(pBlockScanInfo, pReader);
  pLastBlockReader->uid = pBlockScanInfo->uid;
  int32_t code =
      tMergeTreeOpen(&pLastBlockReader->mergeTree, (pLastBlockReader->order == TSDB_ORDER_DESC), pReader->pFileReader,
1937
          pReader->suid, pBlockScanInfo->uid, &pLastBlockReader->window, &pLastBlockReader->verRange);
1938 1939 1940 1941 1942 1943 1944
  if (code != TSDB_CODE_SUCCESS) {
    return false;
  }

  return nextRowFromLastBlocks(pLastBlockReader, pBlockScanInfo);
}

1945
static int64_t getCurrentKeyInLastBlock(SLastBlockReader* pLastBlockReader) {
1946 1947 1948
  TSDBROW row = tMergeTreeGetRow(&pLastBlockReader->mergeTree);
  TSDBKEY key = TSDBROW_KEY(&row);
  return key.ts;
1949 1950
}

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

1953 1954
int32_t mergeRowsInFileBlocks(SBlockData* pBlockData, STableBlockScanInfo* pBlockScanInfo, int64_t key,
                              STsdbReader* pReader) {
1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;

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

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

    tRowMergerInit(&merge, &fRow, pReader->pSchema);
    doMergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pReader, &merge);
1967 1968 1969 1970 1971
    int32_t code = tRowMergerGetRow(&merge, &pTSRow);
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

1972 1973 1974 1975 1976 1977
    doAppendRowFromTSRow(pReader->pResBlock, pReader, pTSRow, pBlockScanInfo->uid);

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

1979 1980 1981
  return TSDB_CODE_SUCCESS;
}

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

H
Hongze Cheng 已提交
1986
  int64_t  key = (pBlockData->nRow > 0) ? pBlockData->aTSKEY[pDumpInfo->rowIndex] : INT64_MIN;
1987 1988
  TSDBROW* pRow = getValidMemRow(&pBlockScanInfo->iter, pBlockScanInfo->delSkyline, pReader);
  TSDBROW* piRow = getValidMemRow(&pBlockScanInfo->iiter, pBlockScanInfo->delSkyline, pReader);
1989

1990
  if (pBlockScanInfo->iter.hasVal && pBlockScanInfo->iiter.hasVal) {
1991
    return doMergeMultiLevelRows(pReader, pBlockScanInfo, pBlockData, pLastBlockReader);
1992
  } else {
1993
    // imem + file + last block
1994
    if (pBlockScanInfo->iiter.hasVal) {
1995
      return doMergeBufAndFileRows(pReader, pBlockScanInfo, piRow, &pBlockScanInfo->iiter, key, pLastBlockReader);
1996 1997
    }

1998
    // mem + file + last block
1999
    if (pBlockScanInfo->iter.hasVal) {
2000
      return doMergeBufAndFileRows(pReader, pBlockScanInfo, pRow, &pBlockScanInfo->iter, key, pLastBlockReader);
H
Haojun Liao 已提交
2001
    }
2002

2003 2004
    // files data blocks + last block
    return mergeFileBlockAndLastBlock(pReader, pLastBlockReader, key, pBlockScanInfo, pBlockData);
2005 2006 2007
  }
}

2008
static int32_t buildComposedDataBlock(STsdbReader* pReader) {
2009 2010
  SSDataBlock* pResBlock = pReader->pResBlock;

H
Hongze Cheng 已提交
2011
  SFileDataBlockInfo* pBlockInfo = getCurrentBlockInfo(&pReader->status.blockIter);
2012 2013 2014 2015 2016 2017 2018 2019

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

H
Haojun Liao 已提交
2020
  SLastBlockReader*   pLastBlockReader = pReader->status.fileIter.pLastBlockReader;
2021
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;
2022 2023
  SBlockData*         pBlockData = &pReader->status.fileBlockData;
  int32_t             step = ASCENDING_TRAVERSE(pReader->order) ? 1 : -1;
2024

2025 2026
  int64_t st = taosGetTimestampUs();

2027
  while (1) {
2028
    // todo check the validate of row in file block
2029
    bool hasBlockData = false;
2030
    {
H
Haojun Liao 已提交
2031
      while (pBlockData->nRow > 0) {  // find the first qualified row in data block
2032 2033 2034 2035 2036
        if (isValidFileBlockRow(pBlockData, pDumpInfo, pBlockScanInfo, pReader)) {
          hasBlockData = true;
          break;
        }

2037 2038
        pDumpInfo->rowIndex += step;

H
Hongze Cheng 已提交
2039
        SDataBlk* pBlock = getCurrentBlock(&pReader->status.blockIter);
2040
        if (pDumpInfo->rowIndex >= pBlock->nRow || pDumpInfo->rowIndex < 0) {
2041
          setBlockAllDumped(pDumpInfo, pBlock->maxKey.ts, pReader->order);
2042 2043 2044
          break;
        }
      }
2045
    }
2046

2047
    bool hasBlockLData = hasDataInLastBlock(pLastBlockReader);
2048

2049 2050 2051
    // no data in last block and block, no need to proceed.
    if ((hasBlockData == false) && (hasBlockLData == false)) {
      break;
2052 2053
    }

2054
    buildComposedDataBlockImpl(pReader, pBlockScanInfo, pBlockData, pLastBlockReader);
2055

2056
    // currently loaded file data block is consumed
2057
    if ((pBlockData->nRow > 0) && (pDumpInfo->rowIndex >= pBlockData->nRow || pDumpInfo->rowIndex < 0)) {
H
Hongze Cheng 已提交
2058
      SDataBlk* pBlock = getCurrentBlock(&pReader->status.blockIter);
2059
      setBlockAllDumped(pDumpInfo, pBlock->maxKey.ts, pReader->order);
2060 2061 2062 2063 2064
      break;
    }

    if (pResBlock->info.rows >= pReader->capacity) {
      break;
2065 2066 2067 2068
    }
  }

  pResBlock->info.uid = pBlockScanInfo->uid;
2069 2070
  blockDataUpdateTsWindow(pResBlock, 0);

2071
  setComposedBlockFlag(pReader, true);
2072
  int64_t et = taosGetTimestampUs();
2073

2074 2075 2076 2077 2078 2079
  if (pResBlock->info.rows > 0) {
    tsdbDebug("%p uid:%" PRIu64 ", composed data block created, brange:%" PRIu64 "-%" PRIu64
              " rows:%d, elapsed time:%.2f ms %s",
              pReader, pBlockScanInfo->uid, pResBlock->info.window.skey, pResBlock->info.window.ekey,
              pResBlock->info.rows, (et - st) / 1000.0, pReader->idStr);
  }
2080

2081 2082 2083 2084 2085
  return TSDB_CODE_SUCCESS;
}

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

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

2092 2093 2094
  int32_t code = 0;
  STsdb*  pTsdb = pReader->pTsdb;

2095 2096
  SArray* pDelData = taosArrayInit(4, sizeof(SDelData));

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

    SArray* aDelIdx = taosArrayInit(4, sizeof(SDelIdx));
    if (aDelIdx == NULL) {
2107
      tsdbDelFReaderClose(&pDelFReader);
2108 2109 2110
      goto _err;
    }

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

2118 2119 2120
    SDelIdx  idx = {.suid = pReader->suid, .uid = pBlockScanInfo->uid};
    SDelIdx* pIdx = taosArraySearch(aDelIdx, &idx, tCmprDelIdx, TD_EQ);

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

    taosArrayDestroy(aDelIdx);
    tsdbDelFReaderClose(&pDelFReader);

    if (code != TSDB_CODE_SUCCESS) {
      goto _err;
2130
    }
2131
  }
2132

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

2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155
  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 已提交
2156 2157
  pBlockScanInfo->iter.index =
      ASCENDING_TRAVERSE(pReader->order) ? 0 : taosArrayGetSize(pBlockScanInfo->delSkyline) - 1;
2158 2159
  pBlockScanInfo->iiter.index = pBlockScanInfo->iter.index;
  pBlockScanInfo->fileDelIndex = pBlockScanInfo->iter.index;
2160
  pBlockScanInfo->lastBlockDelIndex = pBlockScanInfo->iter.index;
2161 2162
  return code;

2163 2164 2165
_err:
  taosArrayDestroy(pDelData);
  return code;
2166 2167
}

2168
static TSDBKEY getCurrentKeyInBuf(STableBlockScanInfo* pScanInfo, STsdbReader* pReader) {
H
Hongze Cheng 已提交
2169
  TSDBKEY  key = {.ts = TSKEY_INITIAL_VAL};
2170
  TSDBROW* pRow = getValidMemRow(&pScanInfo->iter, pScanInfo->delSkyline, pReader);
2171
  if (pRow != NULL) {
2172 2173 2174
    key = TSDBROW_KEY(pRow);
  }

2175
  pRow = getValidMemRow(&pScanInfo->iiter, pScanInfo->delSkyline, pReader);
2176
  if (pRow != NULL) {
2177 2178 2179 2180 2181 2182 2183 2184 2185
    TSDBKEY k = TSDBROW_KEY(pRow);
    if (key.ts > k.ts) {
      key = k;
    }
  }

  return key;
}

2186
static int32_t moveToNextFile(STsdbReader* pReader, SBlockNumber* pBlockNum) {
H
Haojun Liao 已提交
2187
  SReaderStatus* pStatus = &pReader->status;
2188
  pBlockNum->numOfBlocks = 0;
2189
  pBlockNum->numOfLastFiles = 0;
2190

2191
  size_t  numOfTables = taosHashGetSize(pReader->status.pTableMap);
2192
  SArray* pIndexList = taosArrayInit(numOfTables, sizeof(SBlockIdx));
H
Haojun Liao 已提交
2193 2194

  while (1) {
2195
    bool hasNext = filesetIteratorNext(&pStatus->fileIter, pReader);
2196
    if (!hasNext) {  // no data files on disk
H
Haojun Liao 已提交
2197 2198 2199
      break;
    }

H
Haojun Liao 已提交
2200
    taosArrayClear(pIndexList);
H
Haojun Liao 已提交
2201 2202
    int32_t code = doLoadBlockIndex(pReader, pReader->pFileReader, pIndexList);
    if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
2203
      taosArrayDestroy(pIndexList);
H
Haojun Liao 已提交
2204 2205 2206
      return code;
    }

H
Hongze Cheng 已提交
2207
    if (taosArrayGetSize(pIndexList) > 0 || pReader->pFileReader->pSet->nSttF > 0) {
2208
      code = doLoadFileBlock(pReader, pIndexList, pBlockNum);
H
Haojun Liao 已提交
2209
      if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
2210
        taosArrayDestroy(pIndexList);
H
Haojun Liao 已提交
2211 2212 2213
        return code;
      }

2214
      if (pBlockNum->numOfBlocks + pBlockNum->numOfLastFiles > 0) {
H
Haojun Liao 已提交
2215 2216 2217
        break;
      }
    }
2218

H
Haojun Liao 已提交
2219 2220 2221
    // no blocks in current file, try next files
  }

H
Haojun Liao 已提交
2222
  taosArrayDestroy(pIndexList);
H
Haojun Liao 已提交
2223 2224 2225
  return TSDB_CODE_SUCCESS;
}

2226
static int32_t uidComparFunc(const void* p1, const void* p2) {
2227 2228
  uint64_t pu1 = *(uint64_t*)p1;
  uint64_t pu2 = *(uint64_t*)p2;
2229 2230 2231
  if (pu1 == pu2) {
    return 0;
  } else {
2232
    return (pu1 < pu2) ? -1 : 1;
2233 2234
  }
}
2235

2236
static void extractOrderedTableUidList(SUidOrderCheckInfo* pOrderCheckInfo, SReaderStatus* pStatus) {
2237 2238 2239 2240
  int32_t index = 0;
  int32_t total = taosHashGetSize(pStatus->pTableMap);

  void* p = taosHashIterate(pStatus->pTableMap, NULL);
2241
  while (p != NULL) {
2242 2243 2244 2245 2246 2247 2248 2249
    STableBlockScanInfo* pScanInfo = p;
    pOrderCheckInfo->tableUidList[index++] = pScanInfo->uid;
    p = taosHashIterate(pStatus->pTableMap, p);
  }

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

2250
static int32_t initOrderCheckInfo(SUidOrderCheckInfo* pOrderCheckInfo, SReaderStatus* pStatus) {
2251 2252 2253 2254
  int32_t total = taosHashGetSize(pStatus->pTableMap);
  if (total == 0) {
    return TSDB_CODE_SUCCESS;
  }
2255

2256
  if (pOrderCheckInfo->tableUidList == NULL) {
2257 2258 2259 2260 2261 2262
    pOrderCheckInfo->currentIndex = 0;
    pOrderCheckInfo->tableUidList = taosMemoryMalloc(total * sizeof(uint64_t));
    if (pOrderCheckInfo->tableUidList == NULL) {
      return TSDB_CODE_OUT_OF_MEMORY;
    }

2263
    extractOrderedTableUidList(pOrderCheckInfo, pStatus);
2264 2265 2266
    uint64_t uid = pOrderCheckInfo->tableUidList[0];
    pStatus->pTableIter = taosHashGet(pStatus->pTableMap, &uid, sizeof(uid));
  } else {
2267 2268
    if (pStatus->pTableIter == NULL) {  // it is the last block of a new file
      pOrderCheckInfo->currentIndex = 0;
2269 2270
      uint64_t uid = pOrderCheckInfo->tableUidList[pOrderCheckInfo->currentIndex];
      pStatus->pTableIter = taosHashGet(pStatus->pTableMap, &uid, sizeof(uid));
2271 2272

      // the tableMap has already updated
2273
      if (pStatus->pTableIter == NULL) {
2274
        void* p = taosMemoryRealloc(pOrderCheckInfo->tableUidList, total * sizeof(uint64_t));
2275 2276 2277 2278 2279 2280 2281 2282 2283
        if (p == NULL) {
          return TSDB_CODE_OUT_OF_MEMORY;
        }

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

        uid = pOrderCheckInfo->tableUidList[0];
        pStatus->pTableIter = taosHashGet(pStatus->pTableMap, &uid, sizeof(uid));
2284
      }
2285
    }
2286
  }
2287

2288 2289 2290
  return TSDB_CODE_SUCCESS;
}

2291
static bool moveToNextTable(SUidOrderCheckInfo* pOrderedCheckInfo, SReaderStatus* pStatus) {
2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303
  pOrderedCheckInfo->currentIndex += 1;
  if (pOrderedCheckInfo->currentIndex >= taosHashGetSize(pStatus->pTableMap)) {
    pStatus->pTableIter = NULL;
    return false;
  }

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

2304
static int32_t doLoadLastBlockSequentially(STsdbReader* pReader) {
2305
  SReaderStatus*    pStatus = &pReader->status;
2306 2307
  SLastBlockReader* pLastBlockReader = pStatus->fileIter.pLastBlockReader;

2308 2309
  SUidOrderCheckInfo* pOrderedCheckInfo = &pStatus->uidCheckInfo;
  int32_t             code = initOrderCheckInfo(pOrderedCheckInfo, pStatus);
2310
  if (code != TSDB_CODE_SUCCESS || (taosHashGetSize(pStatus->pTableMap) == 0)) {
2311 2312
    return code;
  }
2313

2314
  while (1) {
2315 2316
    // load the last data block of current table
    STableBlockScanInfo* pScanInfo = pStatus->pTableIter;
H
Hongze Cheng 已提交
2317
    bool                 hasVal = initLastBlockReader(pLastBlockReader, pScanInfo, pReader);
2318
    if (!hasVal) {
2319 2320
      bool hasNexTable = moveToNextTable(pOrderedCheckInfo, pStatus);
      if (!hasNexTable) {
2321 2322 2323
        return TSDB_CODE_SUCCESS;
      }
      continue;
2324 2325
    }

2326 2327 2328 2329 2330 2331 2332 2333
    code = doBuildDataBlock(pReader);
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

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

2335
    // current table is exhausted, let's try next table
2336 2337
    bool hasNexTable = moveToNextTable(pOrderedCheckInfo, pStatus);
    if (!hasNexTable) {
2338 2339
      return TSDB_CODE_SUCCESS;
    }
2340 2341 2342
  }
}

2343
static int32_t doBuildDataBlock(STsdbReader* pReader) {
H
Hongze Cheng 已提交
2344 2345
  int32_t   code = TSDB_CODE_SUCCESS;
  SDataBlk* pBlock = NULL;
2346 2347 2348

  SReaderStatus*       pStatus = &pReader->status;
  SDataBlockIter*      pBlockIter = &pStatus->blockIter;
2349 2350 2351
  STableBlockScanInfo* pScanInfo = NULL;
  SFileDataBlockInfo*  pBlockInfo = getCurrentBlockInfo(pBlockIter);
  SLastBlockReader*    pLastBlockReader = pReader->status.fileIter.pLastBlockReader;
2352

2353
  if (pBlockInfo != NULL) {
2354 2355 2356 2357 2358 2359
    pScanInfo = taosHashGet(pReader->status.pTableMap, &pBlockInfo->uid, sizeof(pBlockInfo->uid));
  } else {
    pScanInfo = pReader->status.pTableIter;
  }

  if (pBlockInfo != NULL) {
2360
    pBlock = getCurrentBlock(pBlockIter);
2361 2362
  }

2363
  initLastBlockReader(pLastBlockReader, pScanInfo, pReader);
2364
  TSDBKEY key = getCurrentKeyInBuf(pScanInfo, pReader);
2365

2366 2367 2368 2369 2370 2371 2372
  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) {
2373
      return code;
2374
    }
2375

2376 2377 2378
    code = doLoadFileBlockData(pReader, pBlockIter, &pStatus->fileBlockData);
    if (code != TSDB_CODE_SUCCESS) {
      return code;
2379 2380 2381
    }

    // build composed data block
2382
    code = buildComposedDataBlock(pReader);
2383 2384
  } else if (bufferDataInFileBlockGap(pReader->order, key, pBlock)) {
    // data in memory that are earlier than current file block
2385
    // todo rows in buffer should be less than the file block in asc, greater than file block in desc
2386
    int64_t endKey = (ASCENDING_TRAVERSE(pReader->order)) ? pBlock->minKey.ts : pBlock->maxKey.ts;
2387
    code = buildDataBlockFromBuf(pReader, pScanInfo, endKey);
2388 2389 2390 2391
  } else {
    if (hasDataInLastBlock(pLastBlockReader) && !ASCENDING_TRAVERSE(pReader->order)) {
      // only return the rows in last block
      int64_t tsLast = getCurrentKeyInLastBlock(pLastBlockReader);
H
Hongze Cheng 已提交
2392
      ASSERT(tsLast >= pBlock->maxKey.ts);
2393 2394 2395
      tBlockDataReset(&pReader->status.fileBlockData);

      code = buildComposedDataBlock(pReader);
H
Hongze Cheng 已提交
2396
    } else {  // whole block is required, return it directly
2397 2398 2399 2400 2401 2402 2403
      SDataBlockInfo* pInfo = &pReader->pResBlock->info;
      pInfo->rows = pBlock->nRow;
      pInfo->uid = pScanInfo->uid;
      pInfo->window = (STimeWindow){.skey = pBlock->minKey.ts, .ekey = pBlock->maxKey.ts};
      setComposedBlockFlag(pReader, false);
      setBlockAllDumped(&pStatus->fBlockDumpInfo, pBlock->maxKey.ts, pReader->order);
    }
2404 2405 2406 2407 2408
  }

  return code;
}

H
Haojun Liao 已提交
2409
static int32_t buildBlockFromBufferSequentially(STsdbReader* pReader) {
2410 2411
  SReaderStatus* pStatus = &pReader->status;

2412
  while (1) {
2413 2414 2415
    if (pStatus->pTableIter == NULL) {
      pStatus->pTableIter = taosHashIterate(pStatus->pTableMap, NULL);
      if (pStatus->pTableIter == NULL) {
H
Haojun Liao 已提交
2416
        return TSDB_CODE_SUCCESS;
2417 2418 2419 2420
      }
    }

    STableBlockScanInfo* pBlockScanInfo = pStatus->pTableIter;
2421
    initMemDataIterator(pBlockScanInfo, pReader);
2422

2423
    int64_t endKey = (ASCENDING_TRAVERSE(pReader->order)) ? INT64_MAX : INT64_MIN;
2424
    int32_t code = buildDataBlockFromBuf(pReader, pBlockScanInfo, endKey);
H
Haojun Liao 已提交
2425 2426 2427 2428
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

2429
    if (pReader->pResBlock->info.rows > 0) {
H
Haojun Liao 已提交
2430
      return TSDB_CODE_SUCCESS;
2431 2432 2433 2434 2435
    }

    // current table is exhausted, let's try the next table
    pStatus->pTableIter = taosHashIterate(pStatus->pTableMap, pStatus->pTableIter);
    if (pStatus->pTableIter == NULL) {
H
Haojun Liao 已提交
2436
      return TSDB_CODE_SUCCESS;
2437 2438 2439 2440
    }
  }
}

2441
// set the correct start position in case of the first/last file block, according to the query time window
2442
static void initBlockDumpInfo(STsdbReader* pReader, SDataBlockIter* pBlockIter) {
H
Hongze Cheng 已提交
2443
  SDataBlk* pBlock = getCurrentBlock(pBlockIter);
2444

2445 2446 2447
  SReaderStatus* pStatus = &pReader->status;

  SFileBlockDumpInfo* pDumpInfo = &pStatus->fBlockDumpInfo;
2448 2449 2450

  pDumpInfo->totalRows = pBlock->nRow;
  pDumpInfo->allDumped = false;
2451
  pDumpInfo->rowIndex = ASCENDING_TRAVERSE(pReader->order) ? 0 : pBlock->nRow - 1;
2452 2453
}

2454
static int32_t initForFirstBlockInFile(STsdbReader* pReader, SDataBlockIter* pBlockIter) {
2455 2456
  SBlockNumber num = {0};

2457
  int32_t code = moveToNextFile(pReader, &num);
2458 2459 2460 2461 2462
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

  // all data files are consumed, try data in buffer
2463
  if (num.numOfBlocks + num.numOfLastFiles == 0) {
2464 2465 2466 2467 2468
    pReader->status.loadFromFile = false;
    return code;
  }

  // initialize the block iterator for a new fileset
2469 2470
  if (num.numOfBlocks > 0) {
    code = initBlockIterator(pReader, pBlockIter, num.numOfBlocks);
H
Hongze Cheng 已提交
2471
  } else {  // no block data, only last block exists
2472
    tBlockDataReset(&pReader->status.fileBlockData);
2473
    resetDataBlockIterator(pBlockIter, pReader->order);
2474
  }
2475 2476

  // set the correct start position according to the query time window
2477
  initBlockDumpInfo(pReader, pBlockIter);
2478 2479 2480
  return code;
}

2481
static bool fileBlockPartiallyRead(SFileBlockDumpInfo* pDumpInfo, bool asc) {
2482 2483
  return (!pDumpInfo->allDumped) &&
         ((pDumpInfo->rowIndex > 0 && asc) || (pDumpInfo->rowIndex < (pDumpInfo->totalRows - 1) && (!asc)));
2484 2485
}

2486
static int32_t buildBlockFromFiles(STsdbReader* pReader) {
H
Haojun Liao 已提交
2487
  int32_t code = TSDB_CODE_SUCCESS;
2488 2489
  bool    asc = ASCENDING_TRAVERSE(pReader->order);

2490 2491
  SDataBlockIter* pBlockIter = &pReader->status.blockIter;

2492
  if (pBlockIter->numOfBlocks == 0) {
H
Hongze Cheng 已提交
2493
  _begin:
2494 2495 2496 2497 2498
    code = doLoadLastBlockSequentially(pReader);
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

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

2503
    // all data blocks are checked in this last block file, now let's try the next file
2504 2505 2506 2507 2508 2509 2510 2511
    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;
      }

2512
      // this file does not have data files, let's start check the last block file if exists
2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527
      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;
    }
  }

2528
  while (1) {
2529 2530
    SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;

2531
    if (fileBlockPartiallyRead(pDumpInfo, asc)) {  // file data block is partially loaded
2532
      code = buildComposedDataBlock(pReader);
2533 2534 2535 2536 2537 2538 2539
    } 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);
2540
        } else {
H
Haojun Liao 已提交
2541
          if (pReader->status.pCurrentFileset->nSttF > 0) {
2542 2543 2544 2545 2546 2547
            // data blocks in current file are exhausted, let's try the next file now
            tBlockDataReset(&pReader->status.fileBlockData);
            resetDataBlockIterator(pBlockIter, pReader->order);
            goto _begin;
          } else {
            code = initForFirstBlockInFile(pReader, pBlockIter);
2548

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

2554 2555 2556 2557
            // this file does not have blocks, let's start check the last block file
            if (pBlockIter->numOfBlocks == 0) {
              goto _begin;
            }
2558
          }
2559
        }
H
Haojun Liao 已提交
2560
      }
2561 2562

      code = doBuildDataBlock(pReader);
2563 2564
    }

2565 2566 2567 2568 2569 2570 2571 2572
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

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

2575 2576
static STsdb* getTsdbByRetentions(SVnode* pVnode, TSKEY winSKey, SRetention* retentions, const char* idStr,
                                  int8_t* pLevel) {
2577
  if (VND_IS_RSMA(pVnode)) {
2578
    int8_t  level = 0;
2579 2580
    int64_t now = taosGetTimestamp(pVnode->config.tsdbCfg.precision);

2581
    for (int8_t i = 0; i < TSDB_RETENTION_MAX; ++i) {
2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594
      SRetention* pRetention = retentions + level;
      if (pRetention->keep <= 0) {
        if (level > 0) {
          --level;
        }
        break;
      }
      if ((now - pRetention->keep) <= winSKey) {
        break;
      }
      ++level;
    }

2595
    const char* str = (idStr != NULL) ? idStr : "";
2596 2597

    if (level == TSDB_RETENTION_L0) {
2598
      *pLevel = TSDB_RETENTION_L0;
C
Cary Xu 已提交
2599
      tsdbDebug("vgId:%d, rsma level %d is selected to query %s", TD_VID(pVnode), TSDB_RETENTION_L0, str);
2600 2601
      return VND_RSMA0(pVnode);
    } else if (level == TSDB_RETENTION_L1) {
2602
      *pLevel = TSDB_RETENTION_L1;
C
Cary Xu 已提交
2603
      tsdbDebug("vgId:%d, rsma level %d is selected to query %s", TD_VID(pVnode), TSDB_RETENTION_L1, str);
2604 2605
      return VND_RSMA1(pVnode);
    } else {
2606
      *pLevel = TSDB_RETENTION_L2;
C
Cary Xu 已提交
2607
      tsdbDebug("vgId:%d, rsma level %d is selected to query %s", TD_VID(pVnode), TSDB_RETENTION_L2, str);
2608 2609 2610 2611 2612 2613 2614
      return VND_RSMA2(pVnode);
    }
  }

  return VND_TSDB(pVnode);
}

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

  int64_t endVer = 0;
L
Liu Jicong 已提交
2619 2620
  if (pCond->endVersion ==
      -1) {  // user not specified end version, set current maximum version of vnode as the endVersion
H
Haojun Liao 已提交
2621 2622
    endVer = pVnode->state.applied;
  } else {
L
Liu Jicong 已提交
2623
    endVer = (pCond->endVersion > pVnode->state.applied) ? pVnode->state.applied : pCond->endVersion;
2624 2625
  }

H
Haojun Liao 已提交
2626
  return (SVersionRange){.minVer = startVer, .maxVer = endVer};
2627 2628
}

2629
bool hasBeenDropped(const SArray* pDelList, int32_t* index, TSDBKEY* pKey, int32_t order) {
2630 2631 2632 2633
  ASSERT(pKey != NULL);
  if (pDelList == NULL) {
    return false;
  }
L
Liu Jicong 已提交
2634 2635 2636
  size_t  num = taosArrayGetSize(pDelList);
  bool    asc = ASCENDING_TRAVERSE(order);
  int32_t step = asc ? 1 : -1;
2637

2638 2639 2640 2641 2642 2643
  if (asc) {
    if (*index >= num - 1) {
      TSDBKEY* last = taosArrayGetLast(pDelList);
      ASSERT(pKey->ts >= last->ts);

      if (pKey->ts > last->ts) {
2644
        return false;
2645 2646 2647
      } else if (pKey->ts == last->ts) {
        TSDBKEY* prev = taosArrayGet(pDelList, num - 2);
        return (prev->version >= pKey->version);
2648 2649
      }
    } else {
2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679
      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;
2680 2681
    }
  } else {
2682 2683
    if (*index <= 0) {
      TSDBKEY* pFirst = taosArrayGet(pDelList, 0);
2684

2685 2686 2687 2688 2689 2690 2691
      if (pKey->ts < pFirst->ts) {
        return false;
      } else if (pKey->ts == pFirst->ts) {
        return pFirst->version >= pKey->version;
      } else {
        ASSERT(0);
      }
2692
    } else {
2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719
      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;
          }
        }
2720 2721 2722 2723 2724
      }

      return false;
    }
  }
2725 2726

  return false;
2727 2728
}

2729
TSDBROW* getValidMemRow(SIterInfo* pIter, const SArray* pDelList, STsdbReader* pReader) {
2730
  if (!pIter->hasVal) {
H
Haojun Liao 已提交
2731 2732
    return NULL;
  }
H
Hongze Cheng 已提交
2733

2734
  TSDBROW* pRow = tsdbTbDataIterGet(pIter->iter);
2735
  TSDBKEY  key = {.ts = pRow->pTSRow->ts, .version = pRow->version};
2736
  if (outOfTimeWindow(key.ts, &pReader->window)) {
2737
    pIter->hasVal = false;
H
Haojun Liao 已提交
2738 2739
    return NULL;
  }
H
Hongze Cheng 已提交
2740

2741
  // it is a valid data version
dengyihao's avatar
dengyihao 已提交
2742
  if ((key.version <= pReader->verRange.maxVer && key.version >= pReader->verRange.minVer) &&
2743
      (!hasBeenDropped(pDelList, &pIter->index, &key, pReader->order))) {
H
Haojun Liao 已提交
2744 2745
    return pRow;
  }
H
Hongze Cheng 已提交
2746

2747
  while (1) {
2748 2749
    pIter->hasVal = tsdbTbDataIterNext(pIter->iter);
    if (!pIter->hasVal) {
H
Haojun Liao 已提交
2750 2751
      return NULL;
    }
H
Hongze Cheng 已提交
2752

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

H
Haojun Liao 已提交
2755
    key = TSDBROW_KEY(pRow);
2756
    if (outOfTimeWindow(key.ts, &pReader->window)) {
2757
      pIter->hasVal = false;
H
Haojun Liao 已提交
2758 2759
      return NULL;
    }
H
Hongze Cheng 已提交
2760

dengyihao's avatar
dengyihao 已提交
2761
    if (key.version <= pReader->verRange.maxVer && key.version >= pReader->verRange.minVer &&
2762
        (!hasBeenDropped(pDelList, &pIter->index, &key, pReader->order))) {
H
Haojun Liao 已提交
2763 2764 2765 2766
      return pRow;
    }
  }
}
H
Hongze Cheng 已提交
2767

2768 2769
int32_t doMergeRowsInBuf(SIterInfo* pIter, uint64_t uid, int64_t ts, SArray* pDelList, SRowMerger* pMerger,
                         STsdbReader* pReader) {
H
Haojun Liao 已提交
2770
  while (1) {
2771 2772
    pIter->hasVal = tsdbTbDataIterNext(pIter->iter);
    if (!pIter->hasVal) {
H
Haojun Liao 已提交
2773 2774
      break;
    }
H
Hongze Cheng 已提交
2775

2776
    // data exists but not valid
2777
    TSDBROW* pRow = getValidMemRow(pIter, pDelList, pReader);
2778 2779 2780 2781 2782
    if (pRow == NULL) {
      break;
    }

    // ts is not identical, quit
H
Haojun Liao 已提交
2783
    TSDBKEY k = TSDBROW_KEY(pRow);
2784
    if (k.ts != ts) {
H
Haojun Liao 已提交
2785 2786 2787
      break;
    }

H
Haojun Liao 已提交
2788
    STSchema* pTSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(pRow), pReader, uid);
2789
    tRowMergerAdd(pMerger, pRow, pTSchema);
H
Haojun Liao 已提交
2790 2791 2792 2793 2794
  }

  return TSDB_CODE_SUCCESS;
}

2795
static int32_t doMergeRowsInFileBlockImpl(SBlockData* pBlockData, int32_t rowIndex, int64_t key, SRowMerger* pMerger,
2796
                                          SVersionRange* pVerRange, int32_t step) {
2797 2798
  while (pBlockData->aTSKEY[rowIndex] == key && rowIndex < pBlockData->nRow && rowIndex >= 0) {
    if (pBlockData->aVersion[rowIndex] > pVerRange->maxVer || pBlockData->aVersion[rowIndex] < pVerRange->minVer) {
2799
      rowIndex += step;
2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815
      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;

H
Hongze Cheng 已提交
2816
static int32_t checkForNeighborFileBlock(STsdbReader* pReader, STableBlockScanInfo* pScanInfo, SDataBlk* pBlock,
2817 2818
                                         SFileDataBlockInfo* pFBlock, SRowMerger* pMerger, int64_t key,
                                         CHECK_FILEBLOCK_STATE* state) {
2819
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;
2820
  SBlockData*         pBlockData = &pReader->status.fileBlockData;
2821

2822
  *state = CHECK_FILEBLOCK_QUIT;
2823
  int32_t step = ASCENDING_TRAVERSE(pReader->order) ? 1 : -1;
2824

H
Hongze Cheng 已提交
2825 2826
  int32_t   nextIndex = -1;
  SDataBlk* pNeighborBlock = getNeighborBlockOfSameTable(pFBlock, pScanInfo, &nextIndex, pReader->order);
2827
  if (pNeighborBlock == NULL) {  // do nothing
2828 2829 2830 2831
    return 0;
  }

  bool overlap = overlapWithNeighborBlock(pBlock, pNeighborBlock, pReader->order);
2832 2833
  taosMemoryFree(pNeighborBlock);

2834
  if (overlap) {  // load next block
2835
    SReaderStatus*  pStatus = &pReader->status;
2836 2837
    SDataBlockIter* pBlockIter = &pStatus->blockIter;

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

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

2845
    // 3. load the neighbor block, and set it to be the currently accessed file data block
H
Haojun Liao 已提交
2846
    tBlockDataReset(&pStatus->fileBlockData);
2847 2848 2849 2850 2851 2852
    int32_t code = tBlockDataInit(&pStatus->fileBlockData, pReader->suid, pFBlock->uid, pReader->pSchema);
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

    code = doLoadFileBlockData(pReader, pBlockIter, &pStatus->fileBlockData);
2853 2854 2855 2856
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

2857
    // 4. check the data values
2858 2859 2860 2861
    initBlockDumpInfo(pReader, pBlockIter);

    pDumpInfo->rowIndex =
        doMergeRowsInFileBlockImpl(pBlockData, pDumpInfo->rowIndex, key, pMerger, &pReader->verRange, step);
H
Haojun Liao 已提交
2862
    if (pDumpInfo->rowIndex >= pDumpInfo->totalRows) {
2863 2864 2865 2866 2867 2868 2869
      *state = CHECK_FILEBLOCK_CONT;
    }
  }

  return TSDB_CODE_SUCCESS;
}

2870 2871
int32_t doMergeRowsInFileBlocks(SBlockData* pBlockData, STableBlockScanInfo* pScanInfo, STsdbReader* pReader,
                                SRowMerger* pMerger) {
2872 2873
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;

2874
  bool    asc = ASCENDING_TRAVERSE(pReader->order);
2875
  int64_t key = pBlockData->aTSKEY[pDumpInfo->rowIndex];
2876
  int32_t step = asc ? 1 : -1;
2877

2878
  pDumpInfo->rowIndex += step;
2879
  if ((pDumpInfo->rowIndex <= pBlockData->nRow - 1 && asc) || (pDumpInfo->rowIndex >= 0 && !asc)) {
2880 2881 2882
    pDumpInfo->rowIndex =
        doMergeRowsInFileBlockImpl(pBlockData, pDumpInfo->rowIndex, key, pMerger, &pReader->verRange, step);
  }
2883

2884 2885 2886 2887
  // 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;
2888

2889
      SFileDataBlockInfo* pFileBlockInfo = getCurrentBlockInfo(&pReader->status.blockIter);
H
Hongze Cheng 已提交
2890
      SDataBlk*           pCurrentBlock = getCurrentBlock(&pReader->status.blockIter);
2891 2892 2893
      checkForNeighborFileBlock(pReader, pScanInfo, pCurrentBlock, pFileBlockInfo, pMerger, key, &st);
      if (st == CHECK_FILEBLOCK_QUIT) {
        break;
2894
      }
2895
    }
H
Haojun Liao 已提交
2896
  }
2897

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

H
Hongze Cheng 已提交
2901 2902
int32_t doMergeRowsInLastBlock(SLastBlockReader* pLastBlockReader, STableBlockScanInfo* pScanInfo, int64_t ts,
                               SRowMerger* pMerger) {
2903
  while (nextRowFromLastBlocks(pLastBlockReader, pScanInfo)) {
2904 2905
    int64_t next1 = getCurrentKeyInLastBlock(pLastBlockReader);
    if (next1 == ts) {
2906
      TSDBROW fRow1 = tMergeTreeGetRow(&pLastBlockReader->mergeTree);
2907 2908 2909 2910 2911 2912 2913 2914 2915
      tRowMerge(pMerger, &fRow1);
    } else {
      break;
    }
  }

  return TSDB_CODE_SUCCESS;
}

2916 2917
int32_t doMergeMemTableMultiRows(TSDBROW* pRow, uint64_t uid, SIterInfo* pIter, SArray* pDelList, STSRow** pTSRow,
                                 STsdbReader* pReader, bool* freeTSRow) {
H
Haojun Liao 已提交
2918
  TSDBROW* pNextRow = NULL;
2919
  TSDBROW  current = *pRow;
2920

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

2924 2925 2926
    if (!pIter->hasVal) {
      *pTSRow = current.pTSRow;
      *freeTSRow = false;
2927
      return TSDB_CODE_SUCCESS;
2928
    } else {  // has next point in mem/imem
2929
      pNextRow = getValidMemRow(pIter, pDelList, pReader);
2930 2931 2932
      if (pNextRow == NULL) {
        *pTSRow = current.pTSRow;
        *freeTSRow = false;
2933
        return TSDB_CODE_SUCCESS;
2934 2935
      }

H
Haojun Liao 已提交
2936
      if (current.pTSRow->ts != pNextRow->pTSRow->ts) {
2937 2938
        *pTSRow = current.pTSRow;
        *freeTSRow = false;
2939
        return TSDB_CODE_SUCCESS;
2940
      }
2941
    }
2942 2943
  }

2944 2945
  SRowMerger merge = {0};

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

2949 2950
  if (pReader->pSchema == NULL) {
    pReader->pSchema = pTSchema;
2951
  }
H
Haojun Liao 已提交
2952

H
Haojun Liao 已提交
2953 2954 2955 2956 2957 2958
  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);
2959 2960 2961 2962
  int32_t code = tRowMergerGetRow(&merge, pTSRow);
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }
M
Minglei Jin 已提交
2963

2964
  tRowMergerClear(&merge);
2965
  *freeTSRow = true;
2966
  return TSDB_CODE_SUCCESS;
2967 2968
}

2969
int32_t doMergeMemIMemRows(TSDBROW* pRow, TSDBROW* piRow, STableBlockScanInfo* pBlockScanInfo, STsdbReader* pReader,
H
Hongze Cheng 已提交
2970
                           STSRow** pTSRow) {
H
Haojun Liao 已提交
2971 2972
  SRowMerger merge = {0};

2973 2974 2975
  TSDBKEY k = TSDBROW_KEY(pRow);
  TSDBKEY ik = TSDBROW_KEY(piRow);

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

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

2982
    tRowMerge(&merge, pRow);
2983
    doMergeRowsInBuf(&pBlockScanInfo->iter, pBlockScanInfo->uid, k.ts, pBlockScanInfo->delSkyline, &merge, pReader);
2984
  } else {
H
Haojun Liao 已提交
2985
    STSchema* pSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(pRow), pReader, pBlockScanInfo->uid);
2986

H
Haojun Liao 已提交
2987
    tRowMergerInit(&merge, pRow, pSchema);
2988
    doMergeRowsInBuf(&pBlockScanInfo->iter, pBlockScanInfo->uid, k.ts, pBlockScanInfo->delSkyline, &merge, pReader);
2989 2990

    tRowMerge(&merge, piRow);
2991
    doMergeRowsInBuf(&pBlockScanInfo->iiter, pBlockScanInfo->uid, k.ts, pBlockScanInfo->delSkyline, &merge, pReader);
2992
  }
2993

2994 2995
  int32_t code = tRowMergerGetRow(&merge, pTSRow);
  return code;
2996 2997
}

2998 2999
int32_t tsdbGetNextRowInMem(STableBlockScanInfo* pBlockScanInfo, STsdbReader* pReader, STSRow** pTSRow, int64_t endKey,
                            bool* freeTSRow) {
3000 3001
  TSDBROW* pRow = getValidMemRow(&pBlockScanInfo->iter, pBlockScanInfo->delSkyline, pReader);
  TSDBROW* piRow = getValidMemRow(&pBlockScanInfo->iiter, pBlockScanInfo->delSkyline, pReader);
dengyihao's avatar
dengyihao 已提交
3002
  SArray*  pDelList = pBlockScanInfo->delSkyline;
3003
  uint64_t uid = pBlockScanInfo->uid;
H
Haojun Liao 已提交
3004

3005 3006
  // todo refactor
  bool asc = ASCENDING_TRAVERSE(pReader->order);
3007
  if (pBlockScanInfo->iter.hasVal) {
3008 3009 3010 3011 3012 3013
    TSDBKEY k = TSDBROW_KEY(pRow);
    if ((k.ts >= endKey && asc) || (k.ts <= endKey && !asc)) {
      pRow = NULL;
    }
  }

3014
  if (pBlockScanInfo->iiter.hasVal) {
3015 3016 3017 3018 3019 3020
    TSDBKEY k = TSDBROW_KEY(piRow);
    if ((k.ts >= endKey && asc) || (k.ts <= endKey && !asc)) {
      piRow = NULL;
    }
  }

3021
  if (pBlockScanInfo->iter.hasVal && pBlockScanInfo->iiter.hasVal && pRow != NULL && piRow != NULL) {
3022
    TSDBKEY k = TSDBROW_KEY(pRow);
3023
    TSDBKEY ik = TSDBROW_KEY(piRow);
H
Haojun Liao 已提交
3024

3025
    int32_t code = TSDB_CODE_SUCCESS;
3026 3027
    if (ik.ts != k.ts) {
      if (((ik.ts < k.ts) && asc) || ((ik.ts > k.ts) && (!asc))) {  // ik.ts < k.ts
3028
        code = doMergeMemTableMultiRows(piRow, uid, &pBlockScanInfo->iiter, pDelList, pTSRow, pReader, freeTSRow);
3029
      } else if (((k.ts < ik.ts) && asc) || ((k.ts > ik.ts) && (!asc))) {
3030
        code = doMergeMemTableMultiRows(pRow, uid, &pBlockScanInfo->iter, pDelList, pTSRow, pReader, freeTSRow);
3031
      }
3032
    } else {  // ik.ts == k.ts
3033
      *freeTSRow = true;
3034 3035 3036 3037
      code = doMergeMemIMemRows(pRow, piRow, pBlockScanInfo, pReader, pTSRow);
      if (code != TSDB_CODE_SUCCESS) {
        return code;
      }
H
Haojun Liao 已提交
3038
    }
3039

3040
    return code;
H
Haojun Liao 已提交
3041 3042
  }

3043
  if (pBlockScanInfo->iter.hasVal && pRow != NULL) {
H
Hongze Cheng 已提交
3044 3045
    return doMergeMemTableMultiRows(pRow, pBlockScanInfo->uid, &pBlockScanInfo->iter, pDelList, pTSRow, pReader,
                                    freeTSRow);
H
Haojun Liao 已提交
3046 3047
  }

3048
  if (pBlockScanInfo->iiter.hasVal && piRow != NULL) {
3049
    return doMergeMemTableMultiRows(piRow, uid, &pBlockScanInfo->iiter, pDelList, pTSRow, pReader, freeTSRow);
H
Haojun Liao 已提交
3050 3051 3052 3053 3054
  }

  return TSDB_CODE_SUCCESS;
}

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

3059
  SBlockLoadSuppInfo* pSupInfo = &pReader->suppInfo;
3060
  STSchema*           pSchema = doGetSchemaForTSRow(pTSRow->sver, pReader, uid);
3061

3062
  SColVal colVal = {0};
3063
  int32_t i = 0, j = 0;
H
Haojun Liao 已提交
3064

3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075
  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 已提交
3076
      tTSRowGetVal(pTSRow, pSchema, j, &colVal);
3077 3078 3079 3080 3081 3082 3083 3084
      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;
3085
    }
3086 3087
  }

3088
  // set null value since current column does not exist in the "pSchema"
3089
  while (i < numOfCols) {
3090 3091 3092 3093 3094
    pColInfoData = taosArrayGet(pBlock->pDataBlock, i);
    colDataAppendNULL(pColInfoData, numOfRows);
    i += 1;
  }

3095 3096 3097 3098
  pBlock->info.rows += 1;
  return TSDB_CODE_SUCCESS;
}

H
Hongze Cheng 已提交
3099 3100
int32_t doAppendRowFromFileBlock(SSDataBlock* pResBlock, STsdbReader* pReader, SBlockData* pBlockData,
                                 int32_t rowIndex) {
3101 3102 3103 3104 3105 3106 3107 3108
  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]);
3109
    i += 1;
3110 3111 3112 3113 3114 3115
  }

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

3116
  while (i < numOfOutputCols && j < numOfInputCols) {
3117
    SColumnInfoData* pCol = taosArrayGet(pResBlock->pDataBlock, i);
3118
    SColData*        pData = tBlockDataGetColDataByIdx(pBlockData, j);
3119 3120

    if (pData->cid == pCol->info.colId) {
3121 3122
      tColDataGetValue(pData, rowIndex, &cv);
      doCopyColVal(pCol, outputRowIndex, i, &cv, pSupInfo);
3123 3124 3125 3126 3127 3128 3129 3130 3131 3132
      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);
3133
    colDataAppendNULL(pCol, outputRowIndex);
3134 3135 3136 3137 3138 3139 3140
    i += 1;
  }

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

3141 3142
int32_t buildDataBlockFromBufImpl(STableBlockScanInfo* pBlockScanInfo, int64_t endKey, int32_t capacity,
                                  STsdbReader* pReader) {
H
Haojun Liao 已提交
3143 3144 3145 3146
  SSDataBlock* pBlock = pReader->pResBlock;

  do {
    STSRow* pTSRow = NULL;
3147
    bool    freeTSRow = false;
3148
    tsdbGetNextRowInMem(pBlockScanInfo, pReader, &pTSRow, endKey, &freeTSRow);
3149 3150
    if (pTSRow == NULL) {
      break;
H
Haojun Liao 已提交
3151 3152
    }

H
Haojun Liao 已提交
3153
    doAppendRowFromTSRow(pBlock, pReader, pTSRow, pBlockScanInfo->uid);
3154 3155 3156
    if (freeTSRow) {
      taosMemoryFree(pTSRow);
    }
H
Haojun Liao 已提交
3157 3158

    // no data in buffer, return immediately
3159
    if (!(pBlockScanInfo->iter.hasVal || pBlockScanInfo->iiter.hasVal)) {
H
Haojun Liao 已提交
3160 3161 3162
      break;
    }

3163
    if (pBlock->info.rows >= capacity) {
H
Haojun Liao 已提交
3164 3165 3166 3167
      break;
    }
  } while (1);

3168
  ASSERT(pBlock->info.rows <= capacity);
H
Haojun Liao 已提交
3169 3170
  return TSDB_CODE_SUCCESS;
}
H
Hongze Cheng 已提交
3171

3172
// todo refactor, use arraylist instead
H
Hongze Cheng 已提交
3173
int32_t tsdbSetTableId(STsdbReader* pReader, int64_t uid) {
3174 3175 3176
  ASSERT(pReader != NULL);
  taosHashClear(pReader->status.pTableMap);

3177
  STableBlockScanInfo info = {.lastKey = 0, .uid = uid};
3178
  taosHashPut(pReader->status.pTableMap, &info.uid, sizeof(uint64_t), &info, sizeof(info));
H
Hongze Cheng 已提交
3179 3180 3181
  return TDB_CODE_SUCCESS;
}

dengyihao's avatar
dengyihao 已提交
3182 3183 3184 3185 3186 3187
void* tsdbGetIdx(SMeta* pMeta) {
  if (pMeta == NULL) {
    return NULL;
  }
  return metaGetIdx(pMeta);
}
dengyihao's avatar
dengyihao 已提交
3188

dengyihao's avatar
dengyihao 已提交
3189 3190 3191 3192 3193 3194
void* tsdbGetIvtIdx(SMeta* pMeta) {
  if (pMeta == NULL) {
    return NULL;
  }
  return metaGetIvtIdx(pMeta);
}
L
Liu Jicong 已提交
3195

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

H
refact  
Hongze Cheng 已提交
3198
// ====================================== EXPOSED APIs ======================================
3199 3200
int32_t tsdbReaderOpen(SVnode* pVnode, SQueryTableDataCond* pCond, SArray* pTableList, STsdbReader** ppReader,
                       const char* idstr) {
3201 3202
  int32_t code = tsdbReaderCreate(pVnode, pCond, ppReader, 4096, idstr);
  if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
3203 3204
    goto _err;
  }
H
Hongze Cheng 已提交
3205

3206
  // check for query time window
H
Haojun Liao 已提交
3207
  STsdbReader* pReader = *ppReader;
3208
  if (isEmptyQueryTimeWindow(&pReader->window)) {
H
Haojun Liao 已提交
3209 3210 3211
    tsdbDebug("%p query window not overlaps with the data set, no result returned, %s", pReader, pReader->idStr);
    return TSDB_CODE_SUCCESS;
  }
H
Hongze Cheng 已提交
3212

3213 3214 3215
  if (pCond->type == TIMEWINDOW_RANGE_EXTERNAL) {
    // update the SQueryTableDataCond to create inner reader
    STimeWindow w = pCond->twindows;
3216
    int32_t     order = pCond->order;
3217 3218 3219 3220 3221 3222 3223 3224 3225 3226
    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;
    }

3227
    // here we only need one more row, so the capacity is set to be ONE.
3228 3229 3230 3231 3232 3233 3234 3235
    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;
3236
    } else {
3237 3238 3239 3240 3241 3242 3243 3244 3245 3246
      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) {
3247
    pReader->pSchema = metaGetTbTSchema(pReader->pTsdb->pVnode->pMeta, pReader->suid, pCond->endVersion);
3248 3249
  } else if (taosArrayGetSize(pTableList) > 0) {
    STableKeyInfo* pKey = taosArrayGet(pTableList, 0);
3250
    pReader->pSchema = metaGetTbTSchema(pReader->pTsdb->pVnode->pMeta, pKey->uid, pCond->endVersion);
3251 3252
  }

3253 3254
  int32_t numOfTables = taosArrayGetSize(pTableList);
  pReader->status.pTableMap = createDataBlockScanInfo(pReader, pTableList->pData, numOfTables);
H
Haojun Liao 已提交
3255 3256 3257
  if (pReader->status.pTableMap == NULL) {
    tsdbReaderClose(pReader);
    *ppReader = NULL;
H
Haojun Liao 已提交
3258

H
Haojun Liao 已提交
3259 3260 3261
    code = TSDB_CODE_TDB_OUT_OF_MEMORY;
    goto _err;
  }
H
Hongze Cheng 已提交
3262

H
Hongze Cheng 已提交
3263
  code = tsdbTakeReadSnap(pReader->pTsdb, &pReader->pReadSnap);
3264 3265 3266
  if (code != TSDB_CODE_SUCCESS) {
    goto _err;
  }
H
Hongze Cheng 已提交
3267

3268 3269
  if (pReader->type == TIMEWINDOW_RANGE_CONTAINED) {
    SDataBlockIter* pBlockIter = &pReader->status.blockIter;
3270

3271
    initFilesetIterator(&pReader->status.fileIter, pReader->pReadSnap->fs.aDFileSet, pReader);
3272
    resetDataBlockIterator(&pReader->status.blockIter, pReader->order);
3273 3274 3275 3276 3277 3278 3279 3280 3281 3282

    // 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;
      }
    }
3283
  } else {
3284
    STsdbReader*    pPrevReader = pReader->innerReader[0];
3285 3286
    SDataBlockIter* pBlockIter = &pPrevReader->status.blockIter;

3287 3288 3289 3290 3291
    code = tsdbTakeReadSnap(pPrevReader->pTsdb, &pPrevReader->pReadSnap);
    if (code != TSDB_CODE_SUCCESS) {
      goto _err;
    }

3292
    initFilesetIterator(&pPrevReader->status.fileIter, pPrevReader->pReadSnap->fs.aDFileSet, pPrevReader);
3293
    resetDataBlockIterator(&pPrevReader->status.blockIter, pPrevReader->order);
3294 3295 3296 3297 3298 3299 3300 3301 3302

    // 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;
      }
3303 3304 3305
    }
  }

3306
  tsdbDebug("%p total numOfTable:%d in this query %s", pReader, numOfTables, pReader->idStr);
H
Hongze Cheng 已提交
3307
  return code;
H
Hongze Cheng 已提交
3308 3309

_err:
S
Shengliang Guan 已提交
3310
  tsdbError("failed to create data reader, code:%s %s", tstrerror(code), pReader->idStr);
H
Hongze Cheng 已提交
3311
  return code;
H
refact  
Hongze Cheng 已提交
3312 3313 3314
}

void tsdbReaderClose(STsdbReader* pReader) {
3315 3316
  if (pReader == NULL) {
    return;
3317
  }
H
refact  
Hongze Cheng 已提交
3318

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

3321 3322 3323 3324
  taosMemoryFreeClear(pSupInfo->plist);
  taosMemoryFree(pSupInfo->colIds);

  taosArrayDestroy(pSupInfo->pColAgg);
L
Liu Jicong 已提交
3325
  for (int32_t i = 0; i < blockDataGetNumOfCols(pReader->pResBlock); ++i) {
3326 3327 3328 3329
    if (pSupInfo->buildBuf[i] != NULL) {
      taosMemoryFreeClear(pSupInfo->buildBuf[i]);
    }
  }
3330

3331
  taosMemoryFree(pSupInfo->buildBuf);
H
Hongze Cheng 已提交
3332
  tBlockDataDestroy(&pReader->status.fileBlockData, true);
3333 3334

  cleanupDataBlockIterator(&pReader->status.blockIter);
3335 3336

  size_t numOfTables = taosHashGetSize(pReader->status.pTableMap);
3337
  destroyBlockScanInfo(pReader->status.pTableMap);
3338
  blockDataDestroy(pReader->pResBlock);
3339

H
Haojun Liao 已提交
3340 3341 3342
  if (pReader->pFileReader != NULL) {
    tsdbDataFReaderClose(&pReader->pFileReader);
  }
H
refact  
Hongze Cheng 已提交
3343

3344 3345
  tsdbUntakeReadSnap(pReader->pTsdb, pReader->pReadSnap);

3346 3347
  taosMemoryFree(pReader->status.uidCheckInfo.tableUidList);

H
Haojun Liao 已提交
3348 3349
  SFilesetIter* pFilesetIter = &pReader->status.fileIter;
  if (pFilesetIter->pLastBlockReader != NULL) {
3350
    tMergeTreeClose(&pFilesetIter->pLastBlockReader->mergeTree);
H
Haojun Liao 已提交
3351 3352 3353
    taosMemoryFree(pFilesetIter->pLastBlockReader);
  }

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

3356
  tsdbDebug("%p :io-cost summary: head-file:%" PRIu64 ", head-file time:%.2f ms, SMA:%" PRId64
3357 3358
            " SMA-time:%.2f ms, fileBlocks:%" PRId64
            ", fileBlocks-time:%.2f ms, "
3359 3360 3361 3362 3363
            "build in-memory-block-time:%.2f ms, lastBlocks:%" PRId64
            ", lastBlocks-time:%.2f ms, STableBlockScanInfo size:%.2f Kb %s",
            pReader, pCost->headFileLoad, pCost->headFileLoadTime, pCost->smaDataLoad, pCost->smaLoadTime,
            pCost->numOfBlocks, pCost->blockLoadTime, pCost->buildmemBlock, pCost->lastBlockLoad,
            pCost->lastBlockLoadTime, numOfTables * sizeof(STableBlockScanInfo) / 1000.0, pReader->idStr);
H
refact  
Hongze Cheng 已提交
3364

3365 3366
  taosMemoryFree(pReader->idStr);
  taosMemoryFree(pReader->pSchema);
3367 3368 3369
  if (pReader->pMemSchema != pReader->pSchema) {
    taosMemoryFree(pReader->pMemSchema);
  }
3370
  taosMemoryFreeClear(pReader);
H
refact  
Hongze Cheng 已提交
3371 3372
}

3373
static bool doTsdbNextDataBlock(STsdbReader* pReader) {
H
Haojun Liao 已提交
3374
  // cleanup the data that belongs to the previous data block
3375 3376
  SSDataBlock* pBlock = pReader->pResBlock;
  blockDataCleanup(pBlock);
H
Hongze Cheng 已提交
3377

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

3380 3381 3382 3383 3384
  if (pStatus->loadFromFile) {
    int32_t code = buildBlockFromFiles(pReader);
    if (code != TSDB_CODE_SUCCESS) {
      return false;
    }
3385

3386 3387 3388
    if (pBlock->info.rows > 0) {
      return true;
    } else {
H
Haojun Liao 已提交
3389
      buildBlockFromBufferSequentially(pReader);
3390
      return pBlock->info.rows > 0;
H
Haojun Liao 已提交
3391
    }
3392 3393 3394
  } else {  // no data in files, let's try the buffer
    buildBlockFromBufferSequentially(pReader);
    return pBlock->info.rows > 0;
H
Haojun Liao 已提交
3395
  }
3396

3397
  return false;
H
refact  
Hongze Cheng 已提交
3398 3399
}

3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436
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) {
3437 3438 3439 3440
  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 已提交
3441 3442
}

3443 3444
void tsdbRetrieveDataBlockInfo(STsdbReader* pReader, SDataBlockInfo* pDataBlockInfo) {
  if (pReader->type == TIMEWINDOW_RANGE_EXTERNAL) {
3445
    if (pReader->step == EXTERNAL_ROWS_MAIN) {
3446
      setBlockInfo(pReader, pDataBlockInfo);
3447
    } else if (pReader->step == EXTERNAL_ROWS_PREV) {
3448 3449 3450 3451 3452 3453 3454 3455 3456
      setBlockInfo(pReader->innerReader[0], pDataBlockInfo);
    } else {
      setBlockInfo(pReader->innerReader[1], pDataBlockInfo);
    }
  } else {
    setBlockInfo(pReader, pDataBlockInfo);
  }
}

3457
int32_t tsdbRetrieveDatablockSMA(STsdbReader* pReader, SColumnDataAgg*** pBlockStatis, bool* allHave) {
H
Hongze Cheng 已提交
3458
  int32_t code = 0;
3459
  *allHave = false;
H
Hongze Cheng 已提交
3460

3461
  if (pReader->type == TIMEWINDOW_RANGE_EXTERNAL) {
3462 3463 3464 3465
    *pBlockStatis = NULL;
    return TSDB_CODE_SUCCESS;
  }

3466
  // there is no statistics data for composed block
3467 3468 3469 3470
  if (pReader->status.composedDataBlock) {
    *pBlockStatis = NULL;
    return TSDB_CODE_SUCCESS;
  }
H
Hongze Cheng 已提交
3471

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

H
Hongze Cheng 已提交
3474 3475
  SDataBlk* pBlock = getCurrentBlock(&pReader->status.blockIter);
  int64_t   stime = taosGetTimestampUs();
H
Hongze Cheng 已提交
3476

3477 3478
  SBlockLoadSuppInfo* pSup = &pReader->suppInfo;

H
Hongze Cheng 已提交
3479
  if (tDataBlkHasSma(pBlock)) {
H
Hongze Cheng 已提交
3480
    code = tsdbReadBlockSma(pReader->pFileReader, pBlock, pSup->pColAgg);
3481
    if (code != TSDB_CODE_SUCCESS) {
3482 3483
      tsdbDebug("vgId:%d, failed to load block SMA for uid %" PRIu64 ", code:%s, %s", 0, pFBlock->uid, tstrerror(code),
                pReader->idStr);
3484 3485
      return code;
    }
3486 3487 3488
  } else {
    *pBlockStatis = NULL;
    return TSDB_CODE_SUCCESS;
3489
  }
H
Hongze Cheng 已提交
3490

3491
  *allHave = true;
H
Hongze Cheng 已提交
3492

3493 3494
  // always load the first primary timestamp column data
  SColumnDataAgg* pTsAgg = &pSup->tsColAgg;
3495

3496 3497
  pTsAgg->numOfNull = 0;
  pTsAgg->colId = PRIMARYKEY_TIMESTAMP_COL_ID;
3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513
  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;
      }
3514 3515
      i += 1;
      j += 1;
3516 3517 3518 3519 3520 3521 3522
    } else if (pAgg->colId < pSup->colIds[j]) {
      i += 1;
    } else if (pSup->colIds[j] < pAgg->colId) {
      j += 1;
    }
  }

3523
  double elapsed = (taosGetTimestampUs() - stime) / 1000.0;
3524
  pReader->cost.smaLoadTime += elapsed;
3525
  pReader->cost.smaDataLoad += 1;
3526 3527 3528

  *pBlockStatis = pSup->plist;

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

H
Hongze Cheng 已提交
3532
  return code;
H
Hongze Cheng 已提交
3533 3534
}

3535
static SArray* doRetrieveDataBlock(STsdbReader* pReader) {
H
Haojun Liao 已提交
3536 3537 3538
  SReaderStatus* pStatus = &pReader->status;

  if (pStatus->composedDataBlock) {
3539
    return pReader->pResBlock->pDataBlock;
3540
  }
3541

3542
  SFileDataBlockInfo*  pFBlock = getCurrentBlockInfo(&pStatus->blockIter);
3543
  STableBlockScanInfo* pBlockScanInfo = taosHashGet(pStatus->pTableMap, &pFBlock->uid, sizeof(pFBlock->uid));
3544

H
Haojun Liao 已提交
3545
  tBlockDataReset(&pStatus->fileBlockData);
3546 3547
  int32_t code = tBlockDataInit(&pStatus->fileBlockData, pReader->suid, pBlockScanInfo->uid, pReader->pSchema);
  if (code != TSDB_CODE_SUCCESS) {
3548 3549
    terrno = code;
    return NULL;
3550 3551 3552
  }

  code = doLoadFileBlockData(pReader, &pStatus->blockIter, &pStatus->fileBlockData);
3553
  if (code != TSDB_CODE_SUCCESS) {
H
Hongze Cheng 已提交
3554
    tBlockDataDestroy(&pStatus->fileBlockData, 1);
3555 3556
    terrno = code;
    return NULL;
3557
  }
3558 3559 3560

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

3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574
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 已提交
3575
int32_t tsdbReaderReset(STsdbReader* pReader, SQueryTableDataCond* pCond) {
3576 3577 3578
  if (isEmptyQueryTimeWindow(&pReader->window)) {
    return TSDB_CODE_SUCCESS;
  }
H
Hongze Cheng 已提交
3579

L
Liu Jicong 已提交
3580
  pReader->order = pCond->order;
3581
  pReader->type = TIMEWINDOW_RANGE_CONTAINED;
3582
  pReader->status.loadFromFile = true;
dengyihao's avatar
dengyihao 已提交
3583
  pReader->status.pTableIter = NULL;
H
Haojun Liao 已提交
3584
  pReader->window = updateQueryTimeWindow(pReader->pTsdb, &pCond->twindows);
H
Hongze Cheng 已提交
3585

3586
  // allocate buffer in order to load data blocks from file
3587
  memset(&pReader->suppInfo.tsColAgg, 0, sizeof(SColumnDataAgg));
3588 3589
  memset(pReader->suppInfo.plist, 0, POINTER_BYTES);

3590
  pReader->suppInfo.tsColAgg.colId = PRIMARYKEY_TIMESTAMP_COL_ID;
3591
  tsdbDataFReaderClose(&pReader->pFileReader);
3592

3593
  int32_t numOfTables = taosHashGetSize(pReader->status.pTableMap);
L
Liu Jicong 已提交
3594 3595
  tsdbDataFReaderClose(&pReader->pFileReader);

3596
  initFilesetIterator(&pReader->status.fileIter, pReader->pReadSnap->fs.aDFileSet, pReader);
3597
  resetDataBlockIterator(&pReader->status.blockIter, pReader->order);
3598
  resetDataBlockScanInfo(pReader->status.pTableMap);
3599

3600
  int32_t         code = 0;
3601 3602
  SDataBlockIter* pBlockIter = &pReader->status.blockIter;

3603 3604 3605 3606 3607 3608
  // 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) {
3609 3610
      tsdbError("%p reset reader failed, numOfTables:%d, query range:%" PRId64 " - %" PRId64 " in query %s", pReader,
                numOfTables, pReader->window.skey, pReader->window.ekey, pReader->idStr);
3611 3612 3613
      return code;
    }
  }
H
Hongze Cheng 已提交
3614

dengyihao's avatar
dengyihao 已提交
3615 3616
  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);
3617

3618
  return code;
H
Hongze Cheng 已提交
3619
}
H
Hongze Cheng 已提交
3620

3621 3622 3623
static int32_t getBucketIndex(int32_t startRow, int32_t bucketRange, int32_t numOfRows) {
  return (numOfRows - startRow) / bucketRange;
}
H
Hongze Cheng 已提交
3624

3625 3626 3627 3628
int32_t tsdbGetFileBlocksDistInfo(STsdbReader* pReader, STableBlockDistInfo* pTableBlockInfo) {
  int32_t code = TSDB_CODE_SUCCESS;
  pTableBlockInfo->totalSize = 0;
  pTableBlockInfo->totalRows = 0;
H
Hongze Cheng 已提交
3629

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

3633 3634 3635
  STsdbCfg* pc = &pReader->pTsdb->pVnode->config.tsdbCfg;
  pTableBlockInfo->defMinRows = pc->minRows;
  pTableBlockInfo->defMaxRows = pc->maxRows;
H
Hongze Cheng 已提交
3636

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

3639
  pTableBlockInfo->numOfFiles += 1;
H
Hongze Cheng 已提交
3640

3641 3642
  int32_t numOfTables = (int32_t)taosHashGetSize(pStatus->pTableMap);
  int     defaultRows = 4096;
H
Hongze Cheng 已提交
3643

3644 3645
  SDataBlockIter* pBlockIter = &pStatus->blockIter;
  pTableBlockInfo->numOfFiles += pStatus->fileIter.numOfFiles;
H
Haojun Liao 已提交
3646

3647 3648
  if (pBlockIter->numOfBlocks > 0) {
    pTableBlockInfo->numOfBlocks += pBlockIter->numOfBlocks;
H
Haojun Liao 已提交
3649
  }
H
Hongze Cheng 已提交
3650

3651
  pTableBlockInfo->numOfTables = numOfTables;
3652
  bool hasNext = (pBlockIter->numOfBlocks > 0);
H
Hongze Cheng 已提交
3653

3654 3655
  while (true) {
    if (hasNext) {
H
Hongze Cheng 已提交
3656
      SDataBlk* pBlock = getCurrentBlock(pBlockIter);
H
Hongze Cheng 已提交
3657

3658 3659
      int32_t numOfRows = pBlock->nRow;
      pTableBlockInfo->totalRows += numOfRows;
H
Hongze Cheng 已提交
3660

3661 3662 3663
      if (numOfRows > pTableBlockInfo->maxRows) {
        pTableBlockInfo->maxRows = numOfRows;
      }
H
refact  
Hongze Cheng 已提交
3664

3665 3666 3667
      if (numOfRows < pTableBlockInfo->minRows) {
        pTableBlockInfo->minRows = numOfRows;
      }
H
refact  
Hongze Cheng 已提交
3668

3669 3670 3671
      if (numOfRows < defaultRows) {
        pTableBlockInfo->numOfSmallBlocks += 1;
      }
H
refact  
Hongze Cheng 已提交
3672

3673 3674
      int32_t bucketIndex = getBucketIndex(pTableBlockInfo->defMinRows, bucketRange, numOfRows);
      pTableBlockInfo->blockRowsHisto[bucketIndex]++;
3675 3676

      hasNext = blockIteratorNext(&pStatus->blockIter);
3677 3678 3679 3680 3681
    } else {
      code = initForFirstBlockInFile(pReader, pBlockIter);
      if ((code != TSDB_CODE_SUCCESS) || (pReader->status.loadFromFile == false)) {
        break;
      }
H
refact  
Hongze Cheng 已提交
3682

3683 3684
      pTableBlockInfo->numOfBlocks += pBlockIter->numOfBlocks;
      hasNext = (pBlockIter->numOfBlocks > 0);
3685
    }
H
refact  
Hongze Cheng 已提交
3686

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

H
refact  
Hongze Cheng 已提交
3691 3692
  return code;
}
H
Hongze Cheng 已提交
3693

H
refact  
Hongze Cheng 已提交
3694
int64_t tsdbGetNumOfRowsInMemTable(STsdbReader* pReader) {
3695
  int64_t rows = 0;
H
Hongze Cheng 已提交
3696

3697 3698
  SReaderStatus* pStatus = &pReader->status;
  pStatus->pTableIter = taosHashIterate(pStatus->pTableMap, NULL);
H
Hongze Cheng 已提交
3699

3700 3701 3702 3703 3704
  while (pStatus->pTableIter != NULL) {
    STableBlockScanInfo* pBlockScanInfo = pStatus->pTableIter;

    STbData* d = NULL;
    if (pReader->pTsdb->mem != NULL) {
H
Hongze Cheng 已提交
3705
      d = tsdbGetTbDataFromMemTable(pReader->pReadSnap->pMem, pReader->suid, pBlockScanInfo->uid);
3706 3707 3708 3709 3710 3711 3712
      if (d != NULL) {
        rows += tsdbGetNRowsInTbData(d);
      }
    }

    STbData* di = NULL;
    if (pReader->pTsdb->imem != NULL) {
H
Hongze Cheng 已提交
3713
      di = tsdbGetTbDataFromMemTable(pReader->pReadSnap->pIMem, pReader->suid, pBlockScanInfo->uid);
3714 3715 3716 3717 3718 3719 3720 3721
      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 已提交
3722

H
refact  
Hongze Cheng 已提交
3723
  return rows;
H
Hongze Cheng 已提交
3724
}
D
dapan1121 已提交
3725

L
Liu Jicong 已提交
3726
int32_t tsdbGetTableSchema(SVnode* pVnode, int64_t uid, STSchema** pSchema, int64_t* suid) {
D
dapan1121 已提交
3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738
  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 已提交
3739

D
dapan1121 已提交
3740
  if (mr.me.type == TSDB_CHILD_TABLE) {
D
dapan1121 已提交
3741
    tDecoderClear(&mr.coder);
D
dapan1121 已提交
3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756
    *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 已提交
3757

D
dapan1121 已提交
3758 3759
  return TSDB_CODE_SUCCESS;
}
H
Hongze Cheng 已提交
3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789

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 已提交
3790
  // fs
H
Hongze Cheng 已提交
3791 3792 3793 3794 3795
  code = tsdbFSRef(pTsdb, &(*ppSnap)->fs);
  if (code) {
    taosThreadRwlockUnlock(&pTsdb->rwLock);
    goto _exit;
  }
H
Hongze Cheng 已提交
3796 3797 3798 3799 3800 3801 3802 3803

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

S
Shengliang Guan 已提交
3804
  tsdbTrace("vgId:%d, take read snapshot", TD_VID(pTsdb->pVnode));
H
Hongze Cheng 已提交
3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818
_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 已提交
3819
    tsdbFSUnref(pTsdb, &pSnap->fs);
H
Hongze Cheng 已提交
3820
    taosMemoryFree(pSnap);
H
Hongze Cheng 已提交
3821
  }
H
Hongze Cheng 已提交
3822

S
Shengliang Guan 已提交
3823
  tsdbTrace("vgId:%d, untake read snapshot", TD_VID(pTsdb->pVnode));
3824
}