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

H
Hongze Cheng 已提交
16
#include "tsdb.h"
H
Haojun Liao 已提交
17
#include "osDef.h"
18
#define ASCENDING_TRAVERSE(o) (o == TSDB_ORDER_ASC)
H
Hongze Cheng 已提交
19

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

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

H
Haojun Liao 已提交
32
typedef struct STableBlockScanInfo {
dengyihao's avatar
dengyihao 已提交
33 34
  uint64_t  uid;
  TSKEY     lastKey;
35
  SMapData  mapData;     // block info (compressed)
dengyihao's avatar
dengyihao 已提交
36 37 38 39 40 41
  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;
  bool      iterInit;  // whether to initialize the in-memory skip list iterator or not
H
Haojun Liao 已提交
42 43 44
} STableBlockScanInfo;

typedef struct SBlockOrderWrapper {
dengyihao's avatar
dengyihao 已提交
45
  int64_t uid;
46
  int64_t offset;
H
Haojun Liao 已提交
47
} SBlockOrderWrapper;
H
Hongze Cheng 已提交
48 49

typedef struct SBlockOrderSupporter {
50 51 52 53
  SBlockOrderWrapper** pDataBlockInfo;
  int32_t*             indexPerTable;
  int32_t*             numOfBlocksPerTable;
  int32_t              numOfTables;
H
Hongze Cheng 已提交
54 55 56
} SBlockOrderSupporter;

typedef struct SIOCostSummary {
57 58 59
  int64_t numOfBlocks;
  double  blockLoadTime;
  double  buildmemBlock;
60
  int64_t headFileLoad;
61 62 63
  double  headFileLoadTime;
  int64_t smaData;
  double  smaLoadTime;
H
Hongze Cheng 已提交
64 65 66
} SIOCostSummary;

typedef struct SBlockLoadSuppInfo {
67
  SArray*          pColAgg;
68
  SColumnDataAgg   tsColAgg;
C
Cary Xu 已提交
69
  SColumnDataAgg** plist;
70 71
  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 已提交
72 73
} SBlockLoadSuppInfo;

74
typedef struct SFilesetIter {
H
Hongze Cheng 已提交
75 76 77 78
  int32_t numOfFiles;  // number of total files
  int32_t index;       // current accessed index in the list
  SArray* pFileList;   // data file list
  int32_t order;
79
} SFilesetIter;
H
Haojun Liao 已提交
80 81

typedef struct SFileDataBlockInfo {
82
  // index position in STableBlockScanInfo in order to check whether neighbor block overlaps with it
dengyihao's avatar
dengyihao 已提交
83
  uint64_t uid;
84
  int32_t  tbBlockIdx;
H
Haojun Liao 已提交
85 86 87
} SFileDataBlockInfo;

typedef struct SDataBlockIter {
88 89 90 91 92
  int32_t   numOfBlocks;
  int32_t   index;
  SArray*   blockList;  // SArray<SFileDataBlockInfo>
  int32_t   order;
  SBlock    block;  // current SBlock data
93
  SHashObj* pTableMap;
H
Haojun Liao 已提交
94 95 96
} SDataBlockIter;

typedef struct SFileBlockDumpInfo {
dengyihao's avatar
dengyihao 已提交
97 98 99 100
  int32_t totalRows;
  int32_t rowIndex;
  int64_t lastKey;
  bool    allDumped;
H
Haojun Liao 已提交
101 102
} SFileBlockDumpInfo;

H
Haojun Liao 已提交
103
typedef struct SVersionRange {
dengyihao's avatar
dengyihao 已提交
104 105
  uint64_t minVer;
  uint64_t maxVer;
H
Haojun Liao 已提交
106 107
} SVersionRange;

H
Haojun Liao 已提交
108
typedef struct SReaderStatus {
dengyihao's avatar
dengyihao 已提交
109 110
  bool                 loadFromFile;  // check file stage
  SHashObj*            pTableMap;     // SHash<STableBlockScanInfo>
111
  STableBlockScanInfo* pTableIter;    // table iterator used in building in-memory buffer data blocks.
112
  SFileBlockDumpInfo   fBlockDumpInfo;
113 114 115 116 117
  SDFileSet*           pCurrentFileset;  // current opened file set
  SBlockData           fileBlockData;
  SFilesetIter         fileIter;
  SDataBlockIter       blockIter;
  bool                 composedDataBlock;  // the returned data block is a composed block or not
H
Haojun Liao 已提交
118 119
} SReaderStatus;

H
Hongze Cheng 已提交
120
struct STsdbReader {
H
Haojun Liao 已提交
121 122 123 124 125 126 127
  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;
128 129
  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 已提交
130
  SBlockLoadSuppInfo suppInfo;
H
Hongze Cheng 已提交
131
  STsdbReadSnap*     pReadSnap;
132
  SIOCostSummary     cost;
H
Haojun Liao 已提交
133 134
  STSchema*          pSchema;// the newest version schema
  STSchema*          pMemSchema;// the previous schema for in-memory data, to avoid load schema too many times
135 136
  SDataFReader*      pFileReader;
  SVersionRange      verRange;
137

138 139
  int32_t      step;
  STsdbReader* innerReader[2];
H
Hongze Cheng 已提交
140
};
H
Hongze Cheng 已提交
141

H
Haojun Liao 已提交
142
static SFileDataBlockInfo* getCurrentBlockInfo(SDataBlockIter* pBlockIter);
143 144
static int      buildDataBlockFromBufImpl(STableBlockScanInfo* pBlockScanInfo, int64_t endKey, int32_t capacity,
                                          STsdbReader* pReader);
145
static TSDBROW* getValidRow(SIterInfo* pIter, const SArray* pDelList, STsdbReader* pReader);
146 147
static int32_t  doMergeRowsInFileBlocks(SBlockData* pBlockData, STableBlockScanInfo* pScanInfo, STsdbReader* pReader,
                                        SRowMerger* pMerger);
148
static int32_t  doMergeRowsInBuf(SIterInfo* pIter, uint64_t uid, int64_t ts, SArray* pDelList, SRowMerger* pMerger,
dengyihao's avatar
dengyihao 已提交
149
                                 STsdbReader* pReader);
H
Haojun Liao 已提交
150
static int32_t  doAppendRowFromTSRow(SSDataBlock* pBlock, STsdbReader* pReader, STSRow* pTSRow, uint64_t uid);
151 152
static int32_t  doAppendRowFromBlock(SSDataBlock* pResBlock, STsdbReader* pReader, SBlockData* pBlockData,
                                     int32_t rowIndex);
153
static void     setComposedBlockFlag(STsdbReader* pReader, bool composed);
154
static bool     hasBeenDropped(const SArray* pDelList, int32_t* index, TSDBKEY* pKey, int32_t order);
155

dengyihao's avatar
dengyihao 已提交
156
static void doMergeMultiRows(TSDBROW* pRow, uint64_t uid, SIterInfo* pIter, SArray* pDelList, STSRow** pTSRow,
157
                             STsdbReader* pReader, bool* freeTSRow);
158 159
static void doMergeMemIMemRows(TSDBROW* pRow, TSDBROW* piRow, STableBlockScanInfo* pBlockScanInfo, STsdbReader* pReader,
                               STSRow** pTSRow);
dengyihao's avatar
dengyihao 已提交
160 161 162 163
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);
164
static SVersionRange getQueryVerRange(SVnode* pVnode, SQueryTableDataCond* pCond, int8_t level);
H
Haojun Liao 已提交
165

166 167 168
static int32_t setColumnIdSlotList(STsdbReader* pReader, SSDataBlock* pBlock) {
  SBlockLoadSuppInfo* pSupInfo = &pReader->suppInfo;

169
  size_t numOfCols = blockDataGetNumOfCols(pBlock);
170

171
  pSupInfo->colIds = taosMemoryMalloc(numOfCols * sizeof(int16_t));
172
  pSupInfo->buildBuf = taosMemoryCalloc(numOfCols, POINTER_BYTES);
173 174 175
  if (pSupInfo->buildBuf == NULL || pSupInfo->colIds == NULL) {
    taosMemoryFree(pSupInfo->colIds);
    taosMemoryFree(pSupInfo->buildBuf);
H
Haojun Liao 已提交
176 177
    return TSDB_CODE_OUT_OF_MEMORY;
  }
H
Hongze Cheng 已提交
178

H
Haojun Liao 已提交
179 180
  for (int32_t i = 0; i < numOfCols; ++i) {
    SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, i);
181
    pSupInfo->colIds[i] = pCol->info.colId;
182 183 184

    if (IS_VAR_DATA_TYPE(pCol->info.type)) {
      pSupInfo->buildBuf[i] = taosMemoryMalloc(pCol->info.bytes);
H
Haojun Liao 已提交
185
      tsdbInfo("-------------------%d\n", pCol->info.bytes);
186
    }
H
Haojun Liao 已提交
187
  }
H
Hongze Cheng 已提交
188

H
Haojun Liao 已提交
189 190
  return TSDB_CODE_SUCCESS;
}
H
Hongze Cheng 已提交
191

192
static SHashObj* createDataBlockScanInfo(STsdbReader* pTsdbReader, const STableKeyInfo* idList, int32_t numOfTables) {
H
Haojun Liao 已提交
193
  // allocate buffer in order to load data blocks from file
194
  // todo use simple hash instead, optimize the memory consumption
195 196 197
  SHashObj* pTableMap =
      taosHashInit(numOfTables, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT), false, HASH_NO_LOCK);
  if (pTableMap == NULL) {
H
Haojun Liao 已提交
198 199 200
    return NULL;
  }

201 202 203 204 205
  for (int32_t j = 0; j < numOfTables; ++j) {
    STableBlockScanInfo info = {.lastKey = 0, .uid = idList[j].uid};
    if (ASCENDING_TRAVERSE(pTsdbReader->order)) {
      if (info.lastKey == INT64_MIN || info.lastKey < pTsdbReader->window.skey) {
        info.lastKey = pTsdbReader->window.skey;
H
Haojun Liao 已提交
206 207
      }

208
      ASSERT(info.lastKey >= pTsdbReader->window.skey && info.lastKey <= pTsdbReader->window.ekey);
wmmhello's avatar
wmmhello 已提交
209
    } else {
210
      info.lastKey = pTsdbReader->window.skey;
H
Haojun Liao 已提交
211
    }
wmmhello's avatar
wmmhello 已提交
212

213 214 215
    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 已提交
216 217
  }

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

221
  return pTableMap;
H
Hongze Cheng 已提交
222
}
H
Hongze Cheng 已提交
223

224 225 226
static void resetDataBlockScanInfo(SHashObj* pTableMap) {
  STableBlockScanInfo* p = NULL;

dengyihao's avatar
dengyihao 已提交
227
  while ((p = taosHashIterate(pTableMap, p)) != NULL) {
228 229
    p->iterInit = false;
    p->iiter.hasVal = false;
dengyihao's avatar
dengyihao 已提交
230
    if (p->iter.iter != NULL) {
231
      p->iter.iter = tsdbTbDataIterDestroy(p->iter.iter);
232 233
    }

234
    p->delSkyline = taosArrayDestroy(p->delSkyline);
235 236 237
  }
}

238 239 240 241 242 243 244 245
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) {
246
      p->iter.iter = tsdbTbDataIterDestroy(p->iter.iter);
247 248 249
    }

    if (p->iiter.iter != NULL) {
250
      p->iiter.iter = tsdbTbDataIterDestroy(p->iiter.iter);
251 252
    }

253 254
    p->delSkyline = taosArrayDestroy(p->delSkyline);
    p->pBlockList = taosArrayDestroy(p->pBlockList);
255
    tMapDataClear(&p->mapData);
256 257 258 259 260
  }

  taosHashCleanup(pTableMap);
}

261
static bool isEmptyQueryTimeWindow(STimeWindow* pWindow) {
262 263
  ASSERT(pWindow != NULL);
  return pWindow->skey > pWindow->ekey;
H
Haojun Liao 已提交
264
}
H
Hongze Cheng 已提交
265

266 267 268
// 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 已提交
269
  STsdbKeepCfg* pCfg = &pTsdb->keepCfg;
H
Hongze Cheng 已提交
270

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

dengyihao's avatar
dengyihao 已提交
274
  STimeWindow win = *pWindow;
275 276 277 278 279 280
  if (win.skey < earilyTs) {
    win.skey = earilyTs;
  }

  return win;
}
H
Hongze Cheng 已提交
281

H
Haojun Liao 已提交
282
static void limitOutputBufferSize(const SQueryTableDataCond* pCond, int32_t* capacity) {
H
Haojun Liao 已提交
283 284 285 286 287 288
  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 已提交
289 290 291
  const int32_t TWOMB = 2 * 1024 * 1024;
  if ((*capacity) * rowLen > TWOMB) {
    (*capacity) = TWOMB / rowLen;
H
Haojun Liao 已提交
292 293 294 295
  }
}

// init file iterator
H
Hongze Cheng 已提交
296 297
static int32_t initFilesetIterator(SFilesetIter* pIter, SArray* aDFileSet, int32_t order, const char* idstr) {
  size_t numOfFileset = taosArrayGetSize(aDFileSet);
298

299 300
  pIter->index = ASCENDING_TRAVERSE(order) ? -1 : numOfFileset;
  pIter->order = order;
H
Hongze Cheng 已提交
301
  pIter->pFileList = aDFileSet;
302
  pIter->numOfFiles = numOfFileset;
H
Haojun Liao 已提交
303

H
Haojun Liao 已提交
304
  tsdbDebug("init fileset iterator, total files:%d %s", pIter->numOfFiles, idstr);
H
Haojun Liao 已提交
305 306 307
  return TSDB_CODE_SUCCESS;
}

308
static bool filesetIteratorNext(SFilesetIter* pIter, STsdbReader* pReader) {
309 310
  bool    asc = ASCENDING_TRAVERSE(pIter->order);
  int32_t step = asc ? 1 : -1;
311 312 313
  pIter->index += step;

  if ((asc && pIter->index >= pIter->numOfFiles) || ((!asc) && pIter->index < 0)) {
H
Haojun Liao 已提交
314 315 316 317 318
    return false;
  }

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

320
  while (1) {
H
Haojun Liao 已提交
321 322 323
    if (pReader->pFileReader != NULL) {
      tsdbDataFReaderClose(&pReader->pFileReader);
    }
324

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

327 328 329 330
    int32_t code = tsdbDataFReaderOpen(&pReader->pFileReader, pReader->pTsdb, pReader->status.pCurrentFileset);
    if (code != TSDB_CODE_SUCCESS) {
      goto _err;
    }
H
Haojun Liao 已提交
331

332 333
    pReader->cost.headFileLoad += 1;

334 335 336 337 338 339 340 341 342 343 344 345
    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;
346 347 348
      if ((asc && pIter->index >= pIter->numOfFiles) || ((!asc) && pIter->index < 0)) {
        return false;
      }
349 350
      continue;
    }
C
Cary Xu 已提交
351

352
    tsdbDebug("%p file found fid:%d for qrange:%" PRId64 "-%" PRId64 ", %s", pReader, fid, pReader->window.skey,
353
              pReader->window.ekey, pReader->idStr);
354 355
    return true;
  }
356

357
_err:
H
Haojun Liao 已提交
358 359 360
  return false;
}

361
static void resetDataBlockIterator(SDataBlockIter* pIter, int32_t order, SHashObj* pTableMap) {
362 363
  pIter->order = order;
  pIter->index = -1;
H
Haojun Liao 已提交
364
  pIter->numOfBlocks = -1;
365 366 367 368 369
  if (pIter->blockList == NULL) {
    pIter->blockList = taosArrayInit(4, sizeof(SFileDataBlockInfo));
  } else {
    taosArrayClear(pIter->blockList);
  }
370
  pIter->pTableMap = pTableMap;
371 372
}

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

H
Haojun Liao 已提交
375
static void initReaderStatus(SReaderStatus* pStatus) {
dengyihao's avatar
dengyihao 已提交
376 377
  pStatus->pTableIter = NULL;
  pStatus->loadFromFile = true;
H
Haojun Liao 已提交
378 379
}

380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
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;
}

403 404
static int32_t tsdbReaderCreate(SVnode* pVnode, SQueryTableDataCond* pCond, STsdbReader** ppReader, int32_t capacity,
                                const char* idstr) {
H
Haojun Liao 已提交
405
  int32_t      code = 0;
406
  int8_t       level = 0;
H
Haojun Liao 已提交
407
  STsdbReader* pReader = (STsdbReader*)taosMemoryCalloc(1, sizeof(*pReader));
H
Hongze Cheng 已提交
408 409
  if (pReader == NULL) {
    code = TSDB_CODE_OUT_OF_MEMORY;
H
Haojun Liao 已提交
410
    goto _end;
H
Hongze Cheng 已提交
411 412
  }

C
Cary Xu 已提交
413 414 415 416
  if (VND_IS_TSMA(pVnode)) {
    tsdbDebug("vgId:%d, tsma is selected to query", TD_VID(pVnode));
  }

H
Haojun Liao 已提交
417
  initReaderStatus(&pReader->status);
418

L
Liu Jicong 已提交
419
  pReader->pTsdb = getTsdbByRetentions(pVnode, pCond->twindows.skey, pVnode->config.tsdbCfg.retentions, idstr, &level);
dengyihao's avatar
dengyihao 已提交
420 421
  pReader->suid = pCond->suid;
  pReader->order = pCond->order;
422
  pReader->capacity = capacity;
dengyihao's avatar
dengyihao 已提交
423 424
  pReader->idStr = (idstr != NULL) ? strdup(idstr) : NULL;
  pReader->verRange = getQueryVerRange(pVnode, pCond, level);
425
  pReader->type = pCond->type;
426
  pReader->window = updateQueryTimeWindow(pReader->pTsdb, &pCond->twindows);
427

428
  ASSERT(pCond->numOfCols > 0);
H
Hongze Cheng 已提交
429

430
  limitOutputBufferSize(pCond, &pReader->capacity);
431

432 433
  // allocate buffer in order to load data blocks from file
  SBlockLoadSuppInfo* pSup = &pReader->suppInfo;
434
  pSup->pColAgg = taosArrayInit(4, sizeof(SColumnDataAgg));
435
  pSup->plist = taosMemoryCalloc(pCond->numOfCols, POINTER_BYTES);
436
  if (pSup->pColAgg == NULL || pSup->plist == NULL) {
437 438 439
    code = TSDB_CODE_OUT_OF_MEMORY;
    goto _end;
  }
H
Haojun Liao 已提交
440

441 442
  pSup->tsColAgg.colId = PRIMARYKEY_TIMESTAMP_COL_ID;

H
Haojun Liao 已提交
443 444 445 446 447 448
  code = tBlockDataInit(&pReader->status.fileBlockData);
  if (code != TSDB_CODE_SUCCESS) {
    terrno = code;
    goto _end;
  }

449 450 451 452
  pReader->pResBlock = createResBlock(pCond, pReader->capacity);
  if (pReader->pResBlock == NULL) {
    code = terrno;
    goto _end;
H
Hongze Cheng 已提交
453
  }
H
Hongze Cheng 已提交
454

455 456
  setColumnIdSlotList(pReader, pReader->pResBlock);

H
Hongze Cheng 已提交
457 458
  *ppReader = pReader;
  return code;
H
Hongze Cheng 已提交
459

H
Haojun Liao 已提交
460 461
_end:
  tsdbReaderClose(pReader);
H
Hongze Cheng 已提交
462 463 464
  *ppReader = NULL;
  return code;
}
H
Hongze Cheng 已提交
465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497

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

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

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

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

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

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

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

H
Haojun Liao 已提交
498
//   pTsdbReadHandle->pTableCheckInfo = NULL;  // createDataBlockScanInfo(pTsdbReadHandle, groupList, pMeta,
H
Hongze Cheng 已提交
499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521
//                                             // &pTable);
//   if (pTsdbReadHandle->pTableCheckInfo == NULL) {
//     //    tsdbReaderClose(pTsdbReadHandle);
//     terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
//   }

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

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

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

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

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

H
Hongze Cheng 已提交
523
//   int32_t midSlot = firstSlot;
H
Hongze Cheng 已提交
524

H
Hongze Cheng 已提交
525 526 527
//   while (1) {
//     numOfBlocks = lastSlot - firstSlot + 1;
//     midSlot = (firstSlot + (numOfBlocks >> 1));
H
Hongze Cheng 已提交
528

H
Hongze Cheng 已提交
529
//     if (numOfBlocks == 1) break;
H
Hongze Cheng 已提交
530

H
Hongze Cheng 已提交
531 532 533 534 535 536 537 538 539 540 541
//     if (skey > pBlock[midSlot].maxKey.ts) {
//       if (numOfBlocks == 2) break;
//       if ((order == TSDB_ORDER_DESC) && (skey < pBlock[midSlot + 1].minKey.ts)) break;
//       firstSlot = midSlot + 1;
//     } else if (skey < pBlock[midSlot].minKey.ts) {
//       if ((order == TSDB_ORDER_ASC) && (skey > pBlock[midSlot - 1].maxKey.ts)) break;
//       lastSlot = midSlot - 1;
//     } else {
//       break;  // got the slot
//     }
//   }
H
Hongze Cheng 已提交
542

H
Hongze Cheng 已提交
543 544
//   return midSlot;
// }
H
Hongze Cheng 已提交
545

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

549
  int64_t st = taosGetTimestampUs();
550
  int32_t code = tsdbReadBlockIdx(pFileReader, aBlockIdx, NULL);
H
Haojun Liao 已提交
551
  if (code != TSDB_CODE_SUCCESS) {
552
    goto _end;
H
Haojun Liao 已提交
553
  }
H
Hongze Cheng 已提交
554

555 556
  size_t num = taosArrayGetSize(aBlockIdx);
  if (num == 0) {
H
Hongze Cheng 已提交
557
    taosArrayClear(aBlockIdx);
H
Haojun Liao 已提交
558 559
    return TSDB_CODE_SUCCESS;
  }
H
Hongze Cheng 已提交
560

561 562 563 564
  int64_t et1 = taosGetTimestampUs();

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

567
    // uid check
H
Hongze Cheng 已提交
568
    if (pBlockIdx->suid != pReader->suid) {
H
Haojun Liao 已提交
569 570 571 572
      continue;
    }

    // this block belongs to a table that is not queried.
H
Hongze Cheng 已提交
573
    void* p = taosHashGet(pReader->status.pTableMap, &pBlockIdx->uid, sizeof(uint64_t));
H
Haojun Liao 已提交
574 575 576 577 578 579
    if (p == NULL) {
      continue;
    }

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

H
Hongze Cheng 已提交
583
    taosArrayPush(pIndexList, pBlockIdx);
H
Haojun Liao 已提交
584
  }
H
Hongze Cheng 已提交
585

586
  int64_t et2 = taosGetTimestampUs();
587
  tsdbDebug("load block index for %d tables completed, elapsed time:%.2f ms, set blockIdx:%.2f ms, size:%.2f Kb %s",
588
            (int32_t)num, (et1 - st) / 1000.0, (et2 - et1) / 1000.0, num * sizeof(SBlockIdx) / 1024.0, pReader->idStr);
589 590 591

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

592
_end:
H
Hongze Cheng 已提交
593
  taosArrayDestroy(aBlockIdx);
H
Haojun Liao 已提交
594 595
  return code;
}
H
Hongze Cheng 已提交
596

597 598
static int32_t doLoadFileBlock(STsdbReader* pReader, SArray* pIndexList, uint32_t* numOfValidTables,
                               int32_t* numOfBlocks) {
H
Haojun Liao 已提交
599 600
  size_t numOfTables = taosArrayGetSize(pIndexList);
  *numOfValidTables = 0;
H
Hongze Cheng 已提交
601

602
  int64_t st = taosGetTimestampUs();
603
  size_t  size = 0;
604

605
  STableBlockScanInfo* px = NULL;
dengyihao's avatar
dengyihao 已提交
606
  while (1) {
607 608 609 610 611
    px = taosHashIterate(pReader->status.pTableMap, px);
    if (px == NULL) {
      break;
    }

612
    tMapDataClear(&px->mapData);
613 614 615
    taosArrayClear(px->pBlockList);
  }

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

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

621 622
    tMapDataReset(&pScanInfo->mapData);
    tsdbReadBlock(pReader->pFileReader, pBlockIdx, &pScanInfo->mapData, NULL);
623

624 625
    size += pScanInfo->mapData.nData;
    for (int32_t j = 0; j < pScanInfo->mapData.nItem; ++j) {
H
Haojun Liao 已提交
626
      SBlock block = {0};
627
      tMapDataGetItemByIdx(&pScanInfo->mapData, j, &block, tGetBlock);
H
Hongze Cheng 已提交
628

629
      // 1. time range check
630
      if (block.minKey.ts > pReader->window.ekey || block.maxKey.ts < pReader->window.skey) {
H
Haojun Liao 已提交
631 632
        continue;
      }
H
Hongze Cheng 已提交
633

634
      // 2. version range check
635 636 637
      if (block.minVersion > pReader->verRange.maxVer || block.maxVersion < pReader->verRange.minVer) {
        continue;
      }
638

639
      void* p = taosArrayPush(pScanInfo->pBlockList, &j);
H
Haojun Liao 已提交
640
      if (p == NULL) {
641
        tMapDataClear(&pScanInfo->mapData);
H
Haojun Liao 已提交
642 643
        return TSDB_CODE_OUT_OF_MEMORY;
      }
644 645

      (*numOfBlocks) += 1;
H
Haojun Liao 已提交
646
    }
H
Hongze Cheng 已提交
647

H
Haojun Liao 已提交
648 649 650 651
    if (pScanInfo->pBlockList != NULL && taosArrayGetSize(pScanInfo->pBlockList) > 0) {
      (*numOfValidTables) += 1;
    }
  }
H
Hongze Cheng 已提交
652

653
  double el = (taosGetTimestampUs() - st) / 1000.0;
654
  tsdbDebug("load block of %d tables completed, blocks:%d in %d tables, size:%.2f Kb, elapsed time:%.2f ms %s",
655
            numOfTables, *numOfBlocks, *numOfValidTables, size / 1000.0, el, pReader->idStr);
656 657 658

  pReader->cost.numOfBlocks += (*numOfBlocks);
  pReader->cost.headFileLoadTime += el;
659

H
Haojun Liao 已提交
660 661
  return TSDB_CODE_SUCCESS;
}
H
Hongze Cheng 已提交
662

663 664
// todo remove pblock parameter
static void setBlockAllDumped(SFileBlockDumpInfo* pDumpInfo, SBlock* pBlock, int32_t order) {
665
  int32_t step = ASCENDING_TRAVERSE(order) ? 1 : -1;
H
Haojun Liao 已提交
666

667
  pDumpInfo->allDumped = true;
668
  pDumpInfo->lastKey = pBlock->maxKey.ts + step;
H
Haojun Liao 已提交
669 670
}

671 672
static void doCopyColVal(SColumnInfoData* pColInfoData, int32_t rowIndex, int32_t colIndex, SColVal* pColVal,
                         SBlockLoadSuppInfo* pSup) {
H
Haojun Liao 已提交
673
  if (IS_VAR_DATA_TYPE(pColVal->type)) {
674
    if (pColVal->isNull || pColVal->isNone) {
H
Haojun Liao 已提交
675 676 677
      colDataAppendNULL(pColInfoData, rowIndex);
    } else {
      varDataSetLen(pSup->buildBuf[colIndex], pColVal->value.nData);
H
Haojun Liao 已提交
678
      ASSERT(pColVal->value.nData <= pColInfoData->info.bytes);
H
Haojun Liao 已提交
679 680 681 682
      memcpy(varDataVal(pSup->buildBuf[colIndex]), pColVal->value.pData, pColVal->value.nData);
      colDataAppend(pColInfoData, rowIndex, pSup->buildBuf[colIndex], false);
    }
  } else {
683
    colDataAppend(pColInfoData, rowIndex, (const char*)&pColVal->value, pColVal->isNull || pColVal->isNone);
H
Haojun Liao 已提交
684
  }
H
Haojun Liao 已提交
685 686
}

687 688 689 690 691
static SFileDataBlockInfo* getCurrentBlockInfo(SDataBlockIter* pBlockIter) {
  SFileDataBlockInfo* pFBlockInfo = taosArrayGet(pBlockIter->blockList, pBlockIter->index);
  return pFBlockInfo;
}

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

694
static int32_t copyBlockDataToSDataBlock(STsdbReader* pReader, STableBlockScanInfo* pBlockScanInfo) {
695
  SReaderStatus*  pStatus = &pReader->status;
696
  SDataBlockIter* pBlockIter = &pStatus->blockIter;
H
Hongze Cheng 已提交
697

698
  SBlockData*         pBlockData = &pStatus->fileBlockData;
H
Haojun Liao 已提交
699
  SFileDataBlockInfo* pFBlock = getCurrentBlockInfo(pBlockIter);
700
  SBlock*             pBlock = getCurrentBlock(pBlockIter);
H
Haojun Liao 已提交
701
  SSDataBlock*        pResBlock = pReader->pResBlock;
702
  int32_t             numOfOutputCols = blockDataGetNumOfCols(pResBlock);
H
Haojun Liao 已提交
703

H
Haojun Liao 已提交
704
  SBlockLoadSuppInfo* pSupInfo = &pReader->suppInfo;
705
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;
H
Haojun Liao 已提交
706

H
Haojun Liao 已提交
707
  SColVal cv = {0};
708
  int64_t st = taosGetTimestampUs();
709 710
  bool    asc = ASCENDING_TRAVERSE(pReader->order);
  int32_t step = asc ? 1 : -1;
711

712
  int32_t rowIndex = 0;
713 714
  int32_t remain = asc ? (pBlockData->nRow - pDumpInfo->rowIndex) : (pDumpInfo->rowIndex + 1);

715 716 717 718 719 720 721 722
  int32_t endIndex = 0;
  if (remain <= pReader->capacity) {
    endIndex = pBlockData->nRow;
  } else {
    endIndex = pDumpInfo->rowIndex + step * pReader->capacity;
    remain = pReader->capacity;
  }

723
  int32_t          i = 0;
724 725
  SColumnInfoData* pColData = taosArrayGet(pResBlock->pDataBlock, i);
  if (pColData->info.colId == PRIMARYKEY_TIMESTAMP_COL_ID) {
726
    for (int32_t j = pDumpInfo->rowIndex; j < endIndex && j >= 0; j += step) {
727 728 729 730 731
      colDataAppend(pColData, rowIndex++, (const char*)&pBlockData->aTSKEY[j], false);
    }
    i += 1;
  }

732 733 734
  int32_t colIndex = 0;
  int32_t num = taosArrayGetSize(pBlockData->aIdx);
  while (i < numOfOutputCols && colIndex < num) {
735 736 737
    rowIndex = 0;
    pColData = taosArrayGet(pResBlock->pDataBlock, i);

H
Hongze Cheng 已提交
738
    SColData* pData = tBlockDataGetColDataByIdx(pBlockData, colIndex);
739 740

    if (pData->cid == pColData->info.colId) {
741
      for (int32_t j = pDumpInfo->rowIndex; j < endIndex && j >= 0; j += step) {
742 743
        tColDataGetValue(pData, j, &cv);
        doCopyColVal(pColData, rowIndex++, i, &cv, pSupInfo);
H
Haojun Liao 已提交
744
      }
745
      colIndex += 1;
746
      ASSERT(rowIndex == remain);
747 748
    } else {  // the specified column does not exist in file block, fill with null data
      colDataAppendNNULL(pColData, 0, remain);
H
Haojun Liao 已提交
749
    }
750 751 752 753

    i += 1;
  }

754
  while (i < numOfOutputCols) {
755 756 757
    pColData = taosArrayGet(pResBlock->pDataBlock, i);
    colDataAppendNNULL(pColData, 0, remain);
    i += 1;
H
Haojun Liao 已提交
758
  }
H
Haojun Liao 已提交
759

760
  pResBlock->info.rows = remain;
761
  pDumpInfo->rowIndex += step * remain;
762 763

  setBlockAllDumped(pDumpInfo, pBlock, pReader->order);
H
Haojun Liao 已提交
764

765
  double elapsedTime = (taosGetTimestampUs() - st) / 1000.0;
H
Haojun Liao 已提交
766
  pReader->cost.blockLoadTime += elapsedTime;
H
Haojun Liao 已提交
767

768
  int32_t unDumpedRows = asc ? pBlock->nRow - pDumpInfo->rowIndex : pDumpInfo->rowIndex + 1;
H
Haojun Liao 已提交
769
  tsdbDebug("%p copy file block to sdatablock, global index:%d, table index:%d, brange:%" PRId64 "-%" PRId64
770
            ", rows:%d, remain:%d, minVer:%" PRId64 ", maxVer:%" PRId64 ", elapsed time:%.2f ms, %s",
771 772 773 774 775 776
            pReader, pBlockIter->index, pFBlock->tbBlockIdx, pBlock->minKey.ts, pBlock->maxKey.ts, remain, unDumpedRows,
            pBlock->minVersion, pBlock->maxVersion, elapsedTime, pReader->idStr);

  return TSDB_CODE_SUCCESS;
}

777 778
static int32_t doLoadFileBlockData(STsdbReader* pReader, SDataBlockIter* pBlockIter,
                                   STableBlockScanInfo* pBlockScanInfo, SBlockData* pBlockData) {
779 780 781
  int64_t st = taosGetTimestampUs();

  SFileDataBlockInfo* pFBlock = getCurrentBlockInfo(pBlockIter);
782
  SBlock*             pBlock = getCurrentBlock(pBlockIter);
783

784 785
  SSDataBlock* pResBlock = pReader->pResBlock;
  int32_t      numOfCols = blockDataGetNumOfCols(pResBlock);
786 787 788 789

  SBlockLoadSuppInfo* pSupInfo = &pReader->suppInfo;
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;

790 791 792
  SBlockIdx blockIdx = {.suid = pReader->suid, .uid = pBlockScanInfo->uid};
  int32_t   code =
      tsdbReadColData(pReader->pFileReader, &blockIdx, pBlock, pSupInfo->colIds, numOfCols, pBlockData, NULL, NULL);
793 794 795 796
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }

797
  double elapsedTime = (taosGetTimestampUs() - st) / 1000.0;
798 799 800 801
  pReader->cost.blockLoadTime += elapsedTime;

  pDumpInfo->allDumped = false;
  tsdbDebug("%p load file block into buffer, global index:%d, table index:%d, brange:%" PRId64 "-%" PRId64
802
            ", rows:%d, minVer:%" PRId64 ", maxVer:%" PRId64 ", elapsed time:%.2f ms, %s",
803
            pReader, pBlockIter->index, pFBlock->tbBlockIdx, pBlock->minKey.ts, pBlock->maxKey.ts, pBlock->nRow,
H
Haojun Liao 已提交
804
            pBlock->minVersion, pBlock->maxVersion, elapsedTime, pReader->idStr);
805

H
Haojun Liao 已提交
806
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
807 808

_error:
H
Haojun Liao 已提交
809 810 811 812 813
  tsdbError("%p error occurs in loading file block, global index:%d, table index:%d, brange:%" PRId64 "-%" PRId64
            ", rows:%d, %s",
            pReader, pBlockIter->index, pFBlock->tbBlockIdx, pBlock->minKey.ts, pBlock->maxKey.ts, pBlock->nRow,
            pReader->idStr);
  return code;
H
Haojun Liao 已提交
814
}
H
Hongze Cheng 已提交
815

H
Haojun Liao 已提交
816 817 818
static void cleanupBlockOrderSupporter(SBlockOrderSupporter* pSup) {
  taosMemoryFreeClear(pSup->numOfBlocksPerTable);
  taosMemoryFreeClear(pSup->indexPerTable);
H
Hongze Cheng 已提交
819

H
Haojun Liao 已提交
820 821 822 823
  for (int32_t i = 0; i < pSup->numOfTables; ++i) {
    SBlockOrderWrapper* pBlockInfo = pSup->pDataBlockInfo[i];
    taosMemoryFreeClear(pBlockInfo);
  }
H
Hongze Cheng 已提交
824

H
Haojun Liao 已提交
825 826
  taosMemoryFreeClear(pSup->pDataBlockInfo);
}
H
Hongze Cheng 已提交
827

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

H
Haojun Liao 已提交
831
  pSup->numOfBlocksPerTable = taosMemoryCalloc(1, sizeof(int32_t) * numOfTables);
832 833
  pSup->indexPerTable = taosMemoryCalloc(1, sizeof(int32_t) * numOfTables);
  pSup->pDataBlockInfo = taosMemoryCalloc(1, POINTER_BYTES * numOfTables);
H
Hongze Cheng 已提交
834

H
Haojun Liao 已提交
835 836 837 838
  if (pSup->numOfBlocksPerTable == NULL || pSup->indexPerTable == NULL || pSup->pDataBlockInfo == NULL) {
    cleanupBlockOrderSupporter(pSup);
    return TSDB_CODE_OUT_OF_MEMORY;
  }
H
Hongze Cheng 已提交
839

H
Haojun Liao 已提交
840 841
  return TSDB_CODE_SUCCESS;
}
H
Hongze Cheng 已提交
842

H
Haojun Liao 已提交
843
static int32_t fileDataBlockOrderCompar(const void* pLeft, const void* pRight, void* param) {
844
  int32_t leftIndex = *(int32_t*)pLeft;
H
Haojun Liao 已提交
845
  int32_t rightIndex = *(int32_t*)pRight;
H
Hongze Cheng 已提交
846

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

H
Haojun Liao 已提交
849 850
  int32_t leftTableBlockIndex = pSupporter->indexPerTable[leftIndex];
  int32_t rightTableBlockIndex = pSupporter->indexPerTable[rightIndex];
H
Hongze Cheng 已提交
851

H
Haojun Liao 已提交
852 853 854 855 856 857 858
  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 已提交
859

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

863 864 865 866
  return pLeftBlock->offset > pRightBlock->offset ? 1 : -1;
}

static int32_t doSetCurrentBlock(SDataBlockIter* pBlockIter) {
867
  SFileDataBlockInfo*  pFBlock = getCurrentBlockInfo(pBlockIter);
868 869 870 871 872 873 874 875 876 877
  STableBlockScanInfo* pScanInfo = taosHashGet(pBlockIter->pTableMap, &pFBlock->uid, sizeof(pFBlock->uid));

  int32_t* mapDataIndex = taosArrayGet(pScanInfo->pBlockList, pFBlock->tbBlockIdx);
  tMapDataGetItemByIdx(&pScanInfo->mapData, *mapDataIndex, &pBlockIter->block, tGetBlock);

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

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

883
  pBlockIter->numOfBlocks = numOfBlocks;
884 885
  taosArrayClear(pBlockIter->blockList);

886 887
  // 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 已提交
888

889
  int64_t st = taosGetTimestampUs();
H
Haojun Liao 已提交
890

891
  SBlockOrderSupporter sup = {0};
892
  int32_t              code = initBlockOrderSupporter(&sup, numOfTables);
893 894 895
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }
H
Haojun Liao 已提交
896

897 898 899 900 901 902 903
  int32_t cnt = 0;
  void*   ptr = NULL;
  while (1) {
    ptr = taosHashIterate(pReader->status.pTableMap, ptr);
    if (ptr == NULL) {
      break;
    }
H
Haojun Liao 已提交
904

905 906 907 908
    STableBlockScanInfo* pTableScanInfo = (STableBlockScanInfo*)ptr;
    if (pTableScanInfo->pBlockList == NULL || taosArrayGetSize(pTableScanInfo->pBlockList) == 0) {
      continue;
    }
H
Haojun Liao 已提交
909

910 911
    size_t num = taosArrayGetSize(pTableScanInfo->pBlockList);
    sup.numOfBlocksPerTable[sup.numOfTables] = num;
H
Haojun Liao 已提交
912

913 914 915 916 917
    char* buf = taosMemoryMalloc(sizeof(SBlockOrderWrapper) * num);
    if (buf == NULL) {
      cleanupBlockOrderSupporter(&sup);
      return TSDB_CODE_TDB_OUT_OF_MEMORY;
    }
H
Haojun Liao 已提交
918

919
    sup.pDataBlockInfo[sup.numOfTables] = (SBlockOrderWrapper*)buf;
920
    SBlock block = {0};
921 922
    for (int32_t k = 0; k < num; ++k) {
      SBlockOrderWrapper wrapper = {0};
923 924 925 926

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

927
      wrapper.uid = pTableScanInfo->uid;
928
      wrapper.offset = block.aSubBlock[0].offset;
H
Haojun Liao 已提交
929

930 931 932 933 934 935
      sup.pDataBlockInfo[sup.numOfTables][k] = wrapper;
      cnt++;
    }

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

937
  ASSERT(numOfBlocks == cnt);
H
Haojun Liao 已提交
938

939 940 941 942 943
  // since there is only one table qualified, blocks are not sorted
  if (sup.numOfTables == 1) {
    for (int32_t i = 0; i < numOfBlocks; ++i) {
      SFileDataBlockInfo blockInfo = {.uid = sup.pDataBlockInfo[0][i].uid, .tbBlockIdx = i};
      taosArrayPush(pBlockIter->blockList, &blockInfo);
944
    }
945

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

950
    pBlockIter->index = asc ? 0 : (numOfBlocks - 1);
H
Haojun Liao 已提交
951
    cleanupBlockOrderSupporter(&sup);
952
    doSetCurrentBlock(pBlockIter);
953
    return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
954
  }
H
Haojun Liao 已提交
955

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

959
  assert(cnt <= numOfBlocks && sup.numOfTables <= numOfTables);
H
Haojun Liao 已提交
960

961 962 963 964 965
  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 已提交
966
  }
H
Haojun Liao 已提交
967

968 969 970 971
  int32_t numOfTotal = 0;
  while (numOfTotal < cnt) {
    int32_t pos = tMergeTreeGetChosenIndex(pTree);
    int32_t index = sup.indexPerTable[pos]++;
H
Haojun Liao 已提交
972

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

976 977 978 979
    // 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 已提交
980

981 982
    numOfTotal += 1;
    tMergeTreeAdjust(pTree, tMergeTreeGetAdjustIndex(pTree));
H
Haojun Liao 已提交
983
  }
H
Haojun Liao 已提交
984

985
  int64_t et = taosGetTimestampUs();
986 987
  tsdbDebug("%p %d data blocks access order completed, elapsed time:%.2f ms %s", pReader, cnt, (et - st) / 1000.0,
            pReader->idStr);
988 989
  cleanupBlockOrderSupporter(&sup);
  taosMemoryFree(pTree);
H
Haojun Liao 已提交
990

991
  pBlockIter->index = asc ? 0 : (numOfBlocks - 1);
992 993
  doSetCurrentBlock(pBlockIter);

994
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
995
}
H
Hongze Cheng 已提交
996

H
Haojun Liao 已提交
997
static bool blockIteratorNext(SDataBlockIter* pBlockIter) {
998 999
  bool asc = ASCENDING_TRAVERSE(pBlockIter->order);

1000
  int32_t step = asc ? 1 : -1;
1001
  if ((pBlockIter->index >= pBlockIter->numOfBlocks - 1 && asc) || (pBlockIter->index <= 0 && (!asc))) {
1002 1003 1004
    return false;
  }

1005
  pBlockIter->index += step;
1006 1007
  doSetCurrentBlock(pBlockIter);

1008 1009 1010
  return true;
}

1011 1012 1013
/**
 * This is an two rectangles overlap cases.
 */
1014
static int32_t dataBlockPartiallyRequired(STimeWindow* pWindow, SVersionRange* pVerRange, SBlock* pBlock) {
1015 1016 1017 1018
  return (pWindow->ekey < pBlock->maxKey.ts && pWindow->ekey >= pBlock->minKey.ts) ||
         (pWindow->skey > pBlock->minKey.ts && pWindow->skey <= pBlock->maxKey.ts) ||
         (pVerRange->minVer > pBlock->minVersion && pVerRange->minVer <= pBlock->maxVersion) ||
         (pVerRange->maxVer < pBlock->maxVersion && pVerRange->maxVer >= pBlock->minVersion);
H
Haojun Liao 已提交
1019
}
H
Hongze Cheng 已提交
1020

1021 1022
static SBlock* getNeighborBlockOfSameTable(SFileDataBlockInfo* pFBlockInfo, STableBlockScanInfo* pTableBlockScanInfo,
                                           int32_t* nextIndex, int32_t order) {
1023 1024 1025
  bool asc = ASCENDING_TRAVERSE(order);
  if (asc && pFBlockInfo->tbBlockIdx >= taosArrayGetSize(pTableBlockScanInfo->pBlockList) - 1) {
    return NULL;
1026 1027
  }

1028
  if (!asc && pFBlockInfo->tbBlockIdx == 0) {
1029 1030 1031
    return NULL;
  }

1032
  int32_t step = asc ? 1 : -1;
1033
  *nextIndex = pFBlockInfo->tbBlockIdx + step;
1034

1035
  SBlock*  pBlock = taosMemoryCalloc(1, sizeof(SBlock));
1036 1037 1038 1039
  int32_t* indexInMapdata = taosArrayGet(pTableBlockScanInfo->pBlockList, *nextIndex);

  tMapDataGetItemByIdx(&pTableBlockScanInfo->mapData, *indexInMapdata, pBlock, tGetBlock);
  return pBlock;
1040 1041 1042 1043 1044
}

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

1045
  int32_t step = ASCENDING_TRAVERSE(pBlockIter->order) ? 1 : -1;
1046 1047
  int32_t index = pBlockIter->index;

1048
  while (index < pBlockIter->numOfBlocks && index >= 0) {
1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060
    SFileDataBlockInfo* pFBlock = taosArrayGet(pBlockIter->blockList, index);
    if (pFBlock->uid == pFBlockInfo->uid && pFBlock->tbBlockIdx == pFBlockInfo->tbBlockIdx) {
      return index;
    }

    index += step;
  }

  ASSERT(0);
  return -1;
}

1061
static int32_t setFileBlockActiveInBlockIter(SDataBlockIter* pBlockIter, int32_t index, int32_t step) {
1062 1063 1064 1065 1066
  if (index < 0 || index >= pBlockIter->numOfBlocks) {
    return -1;
  }

  SFileDataBlockInfo fblock = *(SFileDataBlockInfo*)taosArrayGet(pBlockIter->blockList, index);
1067 1068 1069 1070 1071
  pBlockIter->index += step;

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

1073 1074 1075
    SFileDataBlockInfo* pBlockInfo = taosArrayGet(pBlockIter->blockList, pBlockIter->index);
    ASSERT(pBlockInfo->uid == fblock.uid && pBlockInfo->tbBlockIdx == fblock.tbBlockIdx);
  }
1076

1077
  doSetCurrentBlock(pBlockIter);
1078 1079 1080 1081 1082 1083 1084 1085 1086 1087
  return TSDB_CODE_SUCCESS;
}

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

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

1093
  return (ascScan && (key.ts != TSKEY_INITIAL_VAL && key.ts <= pBlock->minKey.ts)) ||
1094
         (!ascScan && (key.ts != TSKEY_INITIAL_VAL && key.ts >= pBlock->maxKey.ts));
H
Haojun Liao 已提交
1095
}
H
Hongze Cheng 已提交
1096

H
Haojun Liao 已提交
1097
static bool keyOverlapFileBlock(TSDBKEY key, SBlock* pBlock, SVersionRange* pVerRange) {
1098 1099
  return (key.ts >= pBlock->minKey.ts && key.ts <= pBlock->maxKey.ts) && (pBlock->maxVersion >= pVerRange->minVer) &&
         (pBlock->minVersion <= pVerRange->maxVer);
H
Haojun Liao 已提交
1100 1101
}

1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135
static bool doCheckforDatablockOverlap(STableBlockScanInfo* pBlockScanInfo, const SBlock* pBlock) {
  size_t num = taosArrayGetSize(pBlockScanInfo->delSkyline);

  for (int32_t i = pBlockScanInfo->fileDelIndex; i < num; i += 1) {
    TSDBKEY* p = taosArrayGet(pBlockScanInfo->delSkyline, i);
    if (p->ts >= pBlock->minKey.ts && p->ts <= pBlock->maxKey.ts) {
      if (p->version >= pBlock->minVersion) {
        return true;
      }
    } else if (p->ts < pBlock->minKey.ts) {  // p->ts < pBlock->minKey.ts
      if (p->version >= pBlock->minVersion) {
        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 {
            if (pnext->ts >= pBlock->minKey.ts && pnext->version >= pBlock->minVersion) {
              return true;
            }
          }
        } else {  // it must be the last point
          ASSERT(p->version == 0);
        }
      }
    } else {  // (p->ts > pBlock->maxKey.ts) {
      return false;
    }
  }

  return false;
}

1136
static bool overlapWithDelSkyline(STableBlockScanInfo* pBlockScanInfo, const SBlock* pBlock, int32_t order) {
1137 1138 1139 1140
  if (pBlockScanInfo->delSkyline == NULL) {
    return false;
  }

1141
  // ts is not overlap
1142
  TSDBKEY* pFirst = taosArrayGet(pBlockScanInfo->delSkyline, 0);
L
Liu Jicong 已提交
1143
  TSDBKEY* pLast = taosArrayGetLast(pBlockScanInfo->delSkyline);
1144 1145 1146 1147 1148
  if (pBlock->minKey.ts > pLast->ts || pBlock->maxKey.ts < pFirst->ts) {
    return false;
  }

  // version is not overlap
1149 1150 1151 1152
  if (ASCENDING_TRAVERSE(order)) {
    return doCheckforDatablockOverlap(pBlockScanInfo, pBlock);
  } else {
    int32_t index = pBlockScanInfo->fileDelIndex;
1153
    while (1) {
1154 1155 1156 1157 1158
      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;
1159 1160 1161
      }
    }

1162 1163
    return doCheckforDatablockOverlap(pBlockScanInfo, pBlock);
  }
1164 1165
}

1166 1167 1168 1169
// 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
1170
// 5. delete info should not overlap with current block data
1171 1172
static bool fileBlockShouldLoad(STsdbReader* pReader, SFileDataBlockInfo* pFBlock, SBlock* pBlock,
                                STableBlockScanInfo* pScanInfo, TSDBKEY key) {
1173 1174 1175
  int32_t neighborIndex = 0;
  SBlock* pNeighbor = getNeighborBlockOfSameTable(pFBlock, pScanInfo, &neighborIndex, pReader->order);

1176
  // overlap with neighbor
1177 1178 1179
  bool overlapWithNeighbor = false;
  if (pNeighbor) {
    overlapWithNeighbor = overlapWithNeighborBlock(pBlock, pNeighbor, pReader->order);
1180
    taosMemoryFree(pNeighbor);
1181 1182
  }

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

1187
  return (overlapWithNeighbor || hasDup || dataBlockPartiallyRequired(&pReader->window, &pReader->verRange, pBlock) ||
1188
          keyOverlapFileBlock(key, pBlock, &pReader->verRange) || (pBlock->nRow > pReader->capacity) || overlapWithDel);
H
Haojun Liao 已提交
1189 1190
}

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

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

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

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

1204
  setComposedBlockFlag(pReader, true);
1205

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

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

1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235
static bool tryCopyDistinctRowFromFileBlock(STsdbReader* pReader, SBlockData* pBlockData, int64_t key, SFileBlockDumpInfo* pDumpInfo) {

  // 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)) {
    int32_t step = pReader->order == TSDB_ORDER_ASC? 1:-1;

    int64_t nextKey = pBlockData->aTSKEY[pDumpInfo->rowIndex + step];
    if (nextKey != key) { // merge is not needed
      doAppendRowFromBlock(pReader->pResBlock, pReader, pBlockData, pDumpInfo->rowIndex);
      pDumpInfo->rowIndex += step;
      return true;
    }
  }

  return false;
}

H
Haojun Liao 已提交
1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260
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);
  }

  if (sversion == pReader->pSchema->version) {
    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;
}

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

  TSDBKEY k = TSDBROW_KEY(pRow);
1269
  TSDBROW fRow = tsdbRowFromBlockData(pBlockData, pDumpInfo->rowIndex);
1270
  SArray* pDelList = pBlockScanInfo->delSkyline;
1271
  bool freeTSRow = false;
H
Haojun Liao 已提交
1272
  uint64_t uid = pBlockScanInfo->uid;
1273

1274 1275 1276
  // ascending order traverse
  if (ASCENDING_TRAVERSE(pReader->order)) {
    if (key < k.ts) {
1277 1278 1279 1280 1281 1282 1283
      // imem & mem are all empty, only file exist
      if (tryCopyDistinctRowFromFileBlock(pReader, pBlockData, key, pDumpInfo)) {
        return TSDB_CODE_SUCCESS;
      } else {
        tRowMergerInit(&merge, &fRow, pReader->pSchema);
        doMergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pReader, &merge);
        tRowMergerGetRow(&merge, &pTSRow);
H
Haojun Liao 已提交
1284
        freeTSRow = true;
1285
      }
1286
    } else if (k.ts < key) {  // k.ts < key
1287
      doMergeMultiRows(pRow, pBlockScanInfo->uid, pIter, pDelList, &pTSRow, pReader, &freeTSRow);
1288 1289 1290
    } else {  // k.ts == key, ascending order: file block ----> imem rows -----> mem rows
      tRowMergerInit(&merge, &fRow, pReader->pSchema);
      doMergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pReader, &merge);
1291 1292

      tRowMerge(&merge, pRow);
1293
      doMergeRowsInBuf(pIter, pBlockScanInfo->uid, k.ts, pBlockScanInfo->delSkyline, &merge, pReader);
1294 1295

      tRowMergerGetRow(&merge, &pTSRow);
H
Haojun Liao 已提交
1296
      freeTSRow = true;
1297
    }
1298 1299
  } else {  // descending order scan
    if (key < k.ts) {
1300
      doMergeMultiRows(pRow, pBlockScanInfo->uid, pIter, pDelList, &pTSRow, pReader, &freeTSRow);
1301
    } else if (k.ts < key) {
1302 1303 1304 1305 1306 1307
      if (tryCopyDistinctRowFromFileBlock(pReader, pBlockData, key, pDumpInfo)) {
        return TSDB_CODE_SUCCESS;
      } else {
        tRowMergerInit(&merge, &fRow, pReader->pSchema);
        doMergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pReader, &merge);
        tRowMergerGetRow(&merge, &pTSRow);
H
Haojun Liao 已提交
1308
        freeTSRow = true;
1309
      }
1310
    } else {  // descending order: mem rows -----> imem rows ------> file block
H
Haojun Liao 已提交
1311
      STSchema* pSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(pRow), pReader, pBlockScanInfo->uid);
1312

H
Haojun Liao 已提交
1313
      tRowMergerInit(&merge, pRow, pSchema);
1314
      doMergeRowsInBuf(pIter, pBlockScanInfo->uid, k.ts, pBlockScanInfo->delSkyline, &merge, pReader);
1315 1316 1317 1318 1319

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

      tRowMergerGetRow(&merge, &pTSRow);
H
Haojun Liao 已提交
1320
      freeTSRow = true;
1321
    }
1322 1323
  }

1324
  tRowMergerClear(&merge);
H
Haojun Liao 已提交
1325
  doAppendRowFromTSRow(pReader->pResBlock, pReader, pTSRow, uid);
H
Haojun Liao 已提交
1326

H
Haojun Liao 已提交
1327 1328 1329 1330
  if (freeTSRow) {
    taosMemoryFree(pTSRow);
  }

1331 1332 1333
  return TSDB_CODE_SUCCESS;
}

1334 1335 1336 1337
static int32_t doMergeThreeLevelRows(STsdbReader* pReader, STableBlockScanInfo* pBlockScanInfo) {
  SRowMerger merge = {0};
  STSRow*    pTSRow = NULL;

1338 1339
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;
  SBlockData*         pBlockData = &pReader->status.fileBlockData;
dengyihao's avatar
dengyihao 已提交
1340
  SArray*             pDelList = pBlockScanInfo->delSkyline;
1341

1342 1343
  TSDBROW* pRow = getValidRow(&pBlockScanInfo->iter, pDelList, pReader);
  TSDBROW* piRow = getValidRow(&pBlockScanInfo->iiter, pDelList, pReader);
1344
  ASSERT(pRow != NULL && piRow != NULL);
H
Haojun Liao 已提交
1345

1346
  int64_t key = pBlockData->aTSKEY[pDumpInfo->rowIndex];
1347
  bool    freeTSRow = false;
H
Haojun Liao 已提交
1348

1349
  uint64_t uid = pBlockScanInfo->uid;
H
Haojun Liao 已提交
1350

1351 1352 1353
  TSDBKEY k = TSDBROW_KEY(pRow);
  TSDBKEY ik = TSDBROW_KEY(piRow);
  if (ASCENDING_TRAVERSE(pReader->order)) {
1354 1355
    // [1&2] key <= [k.ts && ik.ts]
    if (key <= k.ts && key <= ik.ts) {
1356 1357 1358
      TSDBROW fRow = tsdbRowFromBlockData(pBlockData, pDumpInfo->rowIndex);
      tRowMergerInit(&merge, &fRow, pReader->pSchema);

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

1361 1362
      if (ik.ts == key) {
        tRowMerge(&merge, piRow);
1363
        doMergeRowsInBuf(&pBlockScanInfo->iiter, uid, key, pBlockScanInfo->delSkyline, &merge, pReader);
1364 1365
      }

1366 1367
      if (k.ts == key) {
        tRowMerge(&merge, pRow);
1368
        doMergeRowsInBuf(&pBlockScanInfo->iter, uid, key, pBlockScanInfo->delSkyline, &merge, pReader);
1369 1370 1371
      }

      tRowMergerGetRow(&merge, &pTSRow);
H
Haojun Liao 已提交
1372
      doAppendRowFromTSRow(pReader->pResBlock, pReader, pTSRow, uid);
1373
      return TSDB_CODE_SUCCESS;
1374
    } else {  // key > ik.ts || key > k.ts
1375 1376
      ASSERT(key != ik.ts);

1377
      // [3] ik.ts < key <= k.ts
1378
      // [4] ik.ts < k.ts <= key
1379
      if (ik.ts < k.ts) {
1380
        doMergeMultiRows(piRow, uid, &pBlockScanInfo->iiter, pDelList, &pTSRow, pReader, &freeTSRow);
H
Haojun Liao 已提交
1381
        doAppendRowFromTSRow(pReader->pResBlock, pReader, pTSRow, uid);
1382 1383 1384
        if (freeTSRow) {
          taosMemoryFree(pTSRow);
        }
1385 1386 1387
        return TSDB_CODE_SUCCESS;
      }

1388 1389
      // [5] k.ts < key   <= ik.ts
      // [6] k.ts < ik.ts <= key
1390
      if (k.ts < ik.ts) {
1391
        doMergeMultiRows(pRow, uid, &pBlockScanInfo->iter, pDelList, &pTSRow, pReader, &freeTSRow);
H
Haojun Liao 已提交
1392
        doAppendRowFromTSRow(pReader->pResBlock, pReader, pTSRow, uid);
1393 1394 1395
        if (freeTSRow) {
          taosMemoryFree(pTSRow);
        }
1396 1397 1398
        return TSDB_CODE_SUCCESS;
      }

1399
      // [7] k.ts == ik.ts < key
1400
      if (k.ts == ik.ts) {
1401 1402
        ASSERT(key > ik.ts && key > k.ts);

1403
        doMergeMemIMemRows(pRow, piRow, pBlockScanInfo, pReader, &pTSRow);
H
Haojun Liao 已提交
1404
        doAppendRowFromTSRow(pReader->pResBlock, pReader, pTSRow, uid);
1405
        taosMemoryFree(pTSRow);
1406 1407 1408
        return TSDB_CODE_SUCCESS;
      }
    }
1409 1410 1411
  } else {  // descending order scan
    // [1/2] k.ts >= ik.ts && k.ts >= key
    if (k.ts >= ik.ts && k.ts >= key) {
H
Haojun Liao 已提交
1412
      STSchema* pSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(pRow), pReader, pBlockScanInfo->uid);
1413

H
Haojun Liao 已提交
1414
      tRowMergerInit(&merge, pRow, pSchema);
1415
      doMergeRowsInBuf(&pBlockScanInfo->iter, uid, key, pBlockScanInfo->delSkyline, &merge, pReader);
1416 1417 1418

      if (ik.ts == k.ts) {
        tRowMerge(&merge, piRow);
1419
        doMergeRowsInBuf(&pBlockScanInfo->iiter, uid, key, pBlockScanInfo->delSkyline, &merge, pReader);
1420 1421 1422 1423 1424 1425 1426 1427 1428
      }

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

      tRowMergerGetRow(&merge, &pTSRow);
H
Haojun Liao 已提交
1429
      doAppendRowFromTSRow(pReader->pResBlock, pReader, pTSRow, uid);
1430 1431
      return TSDB_CODE_SUCCESS;
    } else {
1432
      ASSERT(ik.ts != k.ts);  // this case has been included in the previous if branch
1433 1434 1435 1436

      // [3] ik.ts > k.ts >= Key
      // [4] ik.ts > key >= k.ts
      if (ik.ts > key) {
1437
        doMergeMultiRows(piRow, uid, &pBlockScanInfo->iiter, pDelList, &pTSRow, pReader, &freeTSRow);
H
Haojun Liao 已提交
1438
        doAppendRowFromTSRow(pReader->pResBlock, pReader, pTSRow, uid);
1439 1440 1441
        if (freeTSRow) {
          taosMemoryFree(pTSRow);
        }
1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452
        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 已提交
1453
        doAppendRowFromTSRow(pReader->pResBlock, pReader, pTSRow, uid);
1454
        taosMemoryFree(pTSRow);
1455 1456 1457 1458 1459
        return TSDB_CODE_SUCCESS;
      }

      //[7] key = ik.ts > k.ts
      if (key == ik.ts) {
1460
        doMergeMultiRows(piRow, uid, &pBlockScanInfo->iiter, pDelList, &pTSRow, pReader, &freeTSRow);
1461 1462 1463 1464 1465

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

        taosMemoryFree(pTSRow);
1469 1470 1471 1472 1473 1474
        return TSDB_CODE_SUCCESS;
      }
    }
  }

  ASSERT(0);
S
Shengliang Guan 已提交
1475
  return -1;
1476 1477
}

dengyihao's avatar
dengyihao 已提交
1478 1479
static bool isValidFileBlockRow(SBlockData* pBlockData, SFileBlockDumpInfo* pDumpInfo,
                                STableBlockScanInfo* pBlockScanInfo, STsdbReader* pReader) {
1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490
  // 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;
  }

1491
  TSDBKEY k = {.ts = ts, .version = ver};
1492
  if (hasBeenDropped(pBlockScanInfo->delSkyline, &pBlockScanInfo->fileDelIndex, &k, pReader->order)) {
1493 1494 1495
    return false;
  }

1496 1497 1498
  return true;
}

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

1501 1502 1503 1504 1505
static int32_t buildComposedDataBlockImpl(STsdbReader* pReader, STableBlockScanInfo* pBlockScanInfo) {
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;
  SBlockData*         pBlockData = &pReader->status.fileBlockData;

  int64_t  key = pBlockData->aTSKEY[pDumpInfo->rowIndex];
1506 1507
  TSDBROW* pRow = getValidRow(&pBlockScanInfo->iter, pBlockScanInfo->delSkyline, pReader);
  TSDBROW* piRow = getValidRow(&pBlockScanInfo->iiter, pBlockScanInfo->delSkyline, pReader);
1508

1509
  if (pBlockScanInfo->iter.hasVal && pBlockScanInfo->iiter.hasVal) {
1510
    return doMergeThreeLevelRows(pReader, pBlockScanInfo);
1511
  } else {
1512
    // imem + file
1513
    if (pBlockScanInfo->iiter.hasVal) {
H
Haojun Liao 已提交
1514
      return doMergeBufAndFileRows(pReader, pBlockScanInfo, piRow, &pBlockScanInfo->iiter, key);
1515 1516
    }

1517
    // mem + file
1518
    if (pBlockScanInfo->iter.hasVal) {
H
Haojun Liao 已提交
1519
      return doMergeBufAndFileRows(pReader, pBlockScanInfo, pRow, &pBlockScanInfo->iter, key);
H
Haojun Liao 已提交
1520
    }
1521

1522
    // imem & mem are all empty, only file exist
1523 1524 1525 1526
    if (tryCopyDistinctRowFromFileBlock(pReader, pBlockData, key, pDumpInfo)) {
      return TSDB_CODE_SUCCESS;
    } else {
      TSDBROW fRow = tsdbRowFromBlockData(pBlockData, pDumpInfo->rowIndex);
1527

1528 1529
      STSRow*    pTSRow = NULL;
      SRowMerger merge = {0};
H
Haojun Liao 已提交
1530

1531 1532 1533
      tRowMergerInit(&merge, &fRow, pReader->pSchema);
      doMergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pReader, &merge);
      tRowMergerGetRow(&merge, &pTSRow);
H
Haojun Liao 已提交
1534
      doAppendRowFromTSRow(pReader->pResBlock, pReader, pTSRow, pBlockScanInfo->uid);
1535

1536 1537 1538 1539
      taosMemoryFree(pTSRow);
      tRowMergerClear(&merge);
      return TSDB_CODE_SUCCESS;
    }
1540 1541 1542
  }
}

1543
static int32_t buildComposedDataBlock(STsdbReader* pReader, STableBlockScanInfo* pBlockScanInfo) {
1544 1545
  SSDataBlock* pResBlock = pReader->pResBlock;

1546
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;
1547 1548
  SBlockData*         pBlockData = &pReader->status.fileBlockData;
  int32_t             step = ASCENDING_TRAVERSE(pReader->order) ? 1 : -1;
1549

1550 1551
  int64_t st = taosGetTimestampUs();

1552
  while (1) {
1553 1554
    // todo check the validate of row in file block
    {
1555
      if (!isValidFileBlockRow(pBlockData, pDumpInfo, pBlockScanInfo, pReader)) {
1556 1557
        pDumpInfo->rowIndex += step;

1558
        SBlock* pBlock = getCurrentBlock(&pReader->status.blockIter);
1559 1560 1561 1562 1563 1564 1565 1566 1567
        if (pDumpInfo->rowIndex >= pBlock->nRow || pDumpInfo->rowIndex < 0) {
          setBlockAllDumped(pDumpInfo, pBlock, pReader->order);
          break;
        }

        continue;
      }
    }

1568
    buildComposedDataBlockImpl(pReader, pBlockScanInfo);
1569
    SBlock* pBlock = getCurrentBlock(&pReader->status.blockIter);
1570

1571 1572 1573 1574 1575 1576 1577 1578
    // currently loaded file data block is consumed
    if (pDumpInfo->rowIndex >= pBlock->nRow || pDumpInfo->rowIndex < 0) {
      setBlockAllDumped(pDumpInfo, pBlock, pReader->order);
      break;
    }

    if (pResBlock->info.rows >= pReader->capacity) {
      break;
1579 1580 1581 1582
    }
  }

  pResBlock->info.uid = pBlockScanInfo->uid;
1583 1584
  blockDataUpdateTsWindow(pResBlock, 0);

1585
  setComposedBlockFlag(pReader, true);
1586
  int64_t et = taosGetTimestampUs();
1587

1588 1589 1590 1591
  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);
1592

1593 1594 1595 1596 1597
  return TSDB_CODE_SUCCESS;
}

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

1598
static int32_t initMemDataIterator(STableBlockScanInfo* pBlockScanInfo, STsdbReader* pReader) {
1599 1600 1601 1602
  if (pBlockScanInfo->iterInit) {
    return TSDB_CODE_SUCCESS;
  }

1603
  int32_t code = TSDB_CODE_SUCCESS;
1604 1605 1606 1607 1608 1609 1610 1611 1612

  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));
1613 1614

  STbData* d = NULL;
H
Hongze Cheng 已提交
1615 1616
  if (pReader->pReadSnap->pMem != NULL) {
    tsdbGetTbDataFromMemTable(pReader->pReadSnap->pMem, pReader->suid, pBlockScanInfo->uid, &d);
1617
    if (d != NULL) {
1618
      code = tsdbTbDataIterCreate(d, &startKey, backward, &pBlockScanInfo->iter.iter);
1619
      if (code == TSDB_CODE_SUCCESS) {
1620
        pBlockScanInfo->iter.hasVal = (tsdbTbDataIterGet(pBlockScanInfo->iter.iter) != NULL);
1621

H
Haojun Liao 已提交
1622
        tsdbDebug("%p uid:%" PRId64 ", check data in mem from skey:%" PRId64 ", order:%d, ts range in buf:%" PRId64
1623 1624
                  "-%" PRId64 " %s",
                  pReader, pBlockScanInfo->uid, startKey.ts, pReader->order, d->minKey, d->maxKey, pReader->idStr);
1625
      } else {
1626 1627
        tsdbError("%p uid:%" PRId64 ", failed to create iterator for imem, code:%s, %s", pReader, pBlockScanInfo->uid,
                  tstrerror(code), pReader->idStr);
1628
        return code;
1629 1630
      }
    }
H
Haojun Liao 已提交
1631
  } else {
1632
    tsdbDebug("%p uid:%" PRId64 ", no data in mem, %s", pReader, pBlockScanInfo->uid, pReader->idStr);
H
Haojun Liao 已提交
1633 1634
  }

1635
  STbData* di = NULL;
H
Hongze Cheng 已提交
1636 1637
  if (pReader->pReadSnap->pIMem != NULL) {
    tsdbGetTbDataFromMemTable(pReader->pReadSnap->pIMem, pReader->suid, pBlockScanInfo->uid, &di);
1638
    if (di != NULL) {
1639
      code = tsdbTbDataIterCreate(di, &startKey, backward, &pBlockScanInfo->iiter.iter);
1640
      if (code == TSDB_CODE_SUCCESS) {
1641
        pBlockScanInfo->iiter.hasVal = (tsdbTbDataIterGet(pBlockScanInfo->iiter.iter) != NULL);
1642

H
Haojun Liao 已提交
1643
        tsdbDebug("%p uid:%" PRId64 ", check data in imem from skey:%" PRId64 ", order:%d, ts range in buf:%" PRId64
1644
                  "-%" PRId64 " %s",
1645
                  pReader, pBlockScanInfo->uid, startKey.ts, pReader->order, di->minKey, di->maxKey, pReader->idStr);
1646
      } else {
1647 1648
        tsdbError("%p uid:%" PRId64 ", failed to create iterator for mem, code:%s, %s", pReader, pBlockScanInfo->uid,
                  tstrerror(code), pReader->idStr);
1649
        return code;
1650 1651
      }
    }
H
Haojun Liao 已提交
1652 1653
  } else {
    tsdbDebug("%p uid:%" PRId64 ", no data in imem, %s", pReader, pBlockScanInfo->uid, pReader->idStr);
1654 1655
  }

1656 1657
  initDelSkylineIterator(pBlockScanInfo, pReader, d, di);

1658
  pBlockScanInfo->iterInit = true;
H
Haojun Liao 已提交
1659 1660 1661
  return TSDB_CODE_SUCCESS;
}

dengyihao's avatar
dengyihao 已提交
1662 1663
int32_t initDelSkylineIterator(STableBlockScanInfo* pBlockScanInfo, STsdbReader* pReader, STbData* pMemTbData,
                               STbData* piMemTbData) {
1664 1665 1666
  if (pBlockScanInfo->delSkyline != NULL) {
    return TSDB_CODE_SUCCESS;
  }
1667

1668 1669 1670
  int32_t code = 0;
  STsdb*  pTsdb = pReader->pTsdb;

1671 1672
  SArray* pDelData = taosArrayInit(4, sizeof(SDelData));

H
Hongze Cheng 已提交
1673
  SDelFile* pDelFile = pReader->pReadSnap->fs.pDelFile;
1674 1675 1676
  if (pDelFile) {
    SDelFReader* pDelFReader = NULL;
    code = tsdbDelFReaderOpen(&pDelFReader, pDelFile, pTsdb, NULL);
1677
    if (code != TSDB_CODE_SUCCESS) {
1678 1679 1680 1681 1682
      goto _err;
    }

    SArray* aDelIdx = taosArrayInit(4, sizeof(SDelIdx));
    if (aDelIdx == NULL) {
1683
      tsdbDelFReaderClose(&pDelFReader);
1684 1685 1686
      goto _err;
    }

1687
    code = tsdbReadDelIdx(pDelFReader, aDelIdx, NULL);
1688 1689 1690
    if (code != TSDB_CODE_SUCCESS) {
      taosArrayDestroy(aDelIdx);
      tsdbDelFReaderClose(&pDelFReader);
1691 1692
      goto _err;
    }
1693

1694 1695 1696
    SDelIdx  idx = {.suid = pReader->suid, .uid = pBlockScanInfo->uid};
    SDelIdx* pIdx = taosArraySearch(aDelIdx, &idx, tCmprDelIdx, TD_EQ);

H
Haojun Liao 已提交
1697 1698
    if (pIdx != NULL) {
      code = tsdbReadDelData(pDelFReader, pIdx, pDelData, NULL);
1699 1700 1701 1702 1703 1704 1705
    }

    taosArrayDestroy(aDelIdx);
    tsdbDelFReaderClose(&pDelFReader);

    if (code != TSDB_CODE_SUCCESS) {
      goto _err;
1706
    }
1707
  }
1708

1709 1710 1711 1712 1713 1714 1715
  SDelData* p = NULL;
  if (pMemTbData != NULL) {
    p = pMemTbData->pHead;
    while (p) {
      taosArrayPush(pDelData, p);
      p = p->pNext;
    }
1716 1717
  }

1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731
  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 已提交
1732 1733
  pBlockScanInfo->iter.index =
      ASCENDING_TRAVERSE(pReader->order) ? 0 : taosArrayGetSize(pBlockScanInfo->delSkyline) - 1;
1734 1735
  pBlockScanInfo->iiter.index = pBlockScanInfo->iter.index;
  pBlockScanInfo->fileDelIndex = pBlockScanInfo->iter.index;
1736 1737
  return code;

1738 1739 1740
_err:
  taosArrayDestroy(pDelData);
  return code;
1741 1742
}

1743 1744 1745
static TSDBKEY getCurrentKeyInBuf(SDataBlockIter* pBlockIter, STsdbReader* pReader) {
  TSDBKEY key = {.ts = TSKEY_INITIAL_VAL};

1746
  SFileDataBlockInfo*  pFBlock = getCurrentBlockInfo(pBlockIter);
1747 1748
  STableBlockScanInfo* pScanInfo = taosHashGet(pReader->status.pTableMap, &pFBlock->uid, sizeof(pFBlock->uid));

1749 1750
  initMemDataIterator(pScanInfo, pReader);
  TSDBROW* pRow = getValidRow(&pScanInfo->iter, pScanInfo->delSkyline, pReader);
1751
  if (pRow != NULL) {
1752 1753 1754
    key = TSDBROW_KEY(pRow);
  }

1755
  pRow = getValidRow(&pScanInfo->iiter, pScanInfo->delSkyline, pReader);
1756
  if (pRow != NULL) {
1757 1758 1759 1760 1761 1762 1763 1764 1765
    TSDBKEY k = TSDBROW_KEY(pRow);
    if (key.ts > k.ts) {
      key = k;
    }
  }

  return key;
}

H
Haojun Liao 已提交
1766 1767
static int32_t moveToNextFile(STsdbReader* pReader, int32_t* numOfBlocks) {
  SReaderStatus* pStatus = &pReader->status;
1768

1769
  size_t  numOfTables = taosHashGetSize(pReader->status.pTableMap);
1770
  SArray* pIndexList = taosArrayInit(numOfTables, sizeof(SBlockIdx));
H
Haojun Liao 已提交
1771 1772

  while (1) {
1773
    bool hasNext = filesetIteratorNext(&pStatus->fileIter, pReader);
1774
    if (!hasNext) {  // no data files on disk
H
Haojun Liao 已提交
1775 1776 1777
      break;
    }

H
Haojun Liao 已提交
1778
    taosArrayClear(pIndexList);
H
Haojun Liao 已提交
1779 1780
    int32_t code = doLoadBlockIndex(pReader, pReader->pFileReader, pIndexList);
    if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
1781
      taosArrayDestroy(pIndexList);
H
Haojun Liao 已提交
1782 1783 1784 1785 1786 1787 1788
      return code;
    }

    if (taosArrayGetSize(pIndexList) > 0) {
      uint32_t numOfValidTable = 0;
      code = doLoadFileBlock(pReader, pIndexList, &numOfValidTable, numOfBlocks);
      if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
1789
        taosArrayDestroy(pIndexList);
H
Haojun Liao 已提交
1790 1791 1792 1793 1794 1795 1796 1797 1798 1799
        return code;
      }

      if (numOfValidTable > 0) {
        break;
      }
    }
    // no blocks in current file, try next files
  }

H
Haojun Liao 已提交
1800
  taosArrayDestroy(pIndexList);
H
Haojun Liao 已提交
1801 1802 1803
  return TSDB_CODE_SUCCESS;
}

1804 1805 1806
static int32_t doBuildDataBlock(STsdbReader* pReader) {
  int32_t code = TSDB_CODE_SUCCESS;

1807
  SReaderStatus*  pStatus = &pReader->status;
1808 1809
  SDataBlockIter* pBlockIter = &pStatus->blockIter;

1810 1811
  SFileDataBlockInfo*  pFBlock = getCurrentBlockInfo(pBlockIter);
  STableBlockScanInfo* pScanInfo = taosHashGet(pStatus->pTableMap, &pFBlock->uid, sizeof(pFBlock->uid));
1812

1813
  SBlock* pBlock = getCurrentBlock(pBlockIter);
1814 1815 1816

  TSDBKEY key = getCurrentKeyInBuf(pBlockIter, pReader);
  if (fileBlockShouldLoad(pReader, pFBlock, pBlock, pScanInfo, key)) {
H
Haojun Liao 已提交
1817 1818
    tBlockDataReset(&pStatus->fileBlockData);
    tBlockDataClearData(&pStatus->fileBlockData);
1819
    code = doLoadFileBlockData(pReader, pBlockIter, pScanInfo, &pStatus->fileBlockData);
1820 1821 1822 1823 1824
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

    // build composed data block
1825
    code = buildComposedDataBlock(pReader, pScanInfo);
1826 1827
  } else if (bufferDataInFileBlockGap(pReader->order, key, pBlock)) {
    // data in memory that are earlier than current file block
1828
    // todo rows in buffer should be less than the file block in asc, greater than file block in desc
1829
    int64_t endKey = (ASCENDING_TRAVERSE(pReader->order)) ? pBlock->minKey.ts : pBlock->maxKey.ts;
1830
    code = buildDataBlockFromBuf(pReader, pScanInfo, endKey);
1831
  } else {  // whole block is required, return it directly
1832
    SDataBlockInfo* pInfo = &pReader->pResBlock->info;
1833 1834 1835
    pInfo->rows = pBlock->nRow;
    pInfo->uid = pScanInfo->uid;
    pInfo->window = (STimeWindow){.skey = pBlock->minKey.ts, .ekey = pBlock->maxKey.ts};
1836
    setComposedBlockFlag(pReader, false);
1837
    setBlockAllDumped(&pStatus->fBlockDumpInfo, pBlock, pReader->order);
1838 1839 1840 1841 1842
  }

  return code;
}

H
Haojun Liao 已提交
1843
static int32_t buildBlockFromBufferSequentially(STsdbReader* pReader) {
1844 1845
  SReaderStatus* pStatus = &pReader->status;

1846
  while (1) {
1847 1848 1849
    if (pStatus->pTableIter == NULL) {
      pStatus->pTableIter = taosHashIterate(pStatus->pTableMap, NULL);
      if (pStatus->pTableIter == NULL) {
H
Haojun Liao 已提交
1850
        return TSDB_CODE_SUCCESS;
1851 1852 1853 1854
      }
    }

    STableBlockScanInfo* pBlockScanInfo = pStatus->pTableIter;
1855
    initMemDataIterator(pBlockScanInfo, pReader);
1856

1857
    int64_t endKey = (ASCENDING_TRAVERSE(pReader->order)) ? INT64_MAX : INT64_MIN;
1858
    int32_t code = buildDataBlockFromBuf(pReader, pBlockScanInfo, endKey);
H
Haojun Liao 已提交
1859 1860 1861 1862
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

1863
    if (pReader->pResBlock->info.rows > 0) {
H
Haojun Liao 已提交
1864
      return TSDB_CODE_SUCCESS;
1865 1866 1867 1868 1869
    }

    // current table is exhausted, let's try the next table
    pStatus->pTableIter = taosHashIterate(pStatus->pTableMap, pStatus->pTableIter);
    if (pStatus->pTableIter == NULL) {
H
Haojun Liao 已提交
1870
      return TSDB_CODE_SUCCESS;
1871 1872 1873 1874
    }
  }
}

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

1879 1880 1881
  SReaderStatus* pStatus = &pReader->status;

  SFileBlockDumpInfo* pDumpInfo = &pStatus->fBlockDumpInfo;
1882 1883 1884

  pDumpInfo->totalRows = pBlock->nRow;
  pDumpInfo->allDumped = false;
1885
  pDumpInfo->rowIndex = ASCENDING_TRAVERSE(pReader->order) ? 0 : pBlock->nRow - 1;
1886 1887
}

1888
static int32_t initForFirstBlockInFile(STsdbReader* pReader, SDataBlockIter* pBlockIter) {
1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902
  int32_t numOfBlocks = 0;
  int32_t code = moveToNextFile(pReader, &numOfBlocks);
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

  // all data files are consumed, try data in buffer
  if (numOfBlocks == 0) {
    pReader->status.loadFromFile = false;
    return code;
  }

  // initialize the block iterator for a new fileset
  code = initBlockIterator(pReader, pBlockIter, numOfBlocks);
1903 1904

  // set the correct start position according to the query time window
1905
  initBlockDumpInfo(pReader, pBlockIter);
1906 1907 1908
  return code;
}

1909
static bool fileBlockPartiallyRead(SFileBlockDumpInfo* pDumpInfo, bool asc) {
1910 1911
  return (!pDumpInfo->allDumped) &&
         ((pDumpInfo->rowIndex > 0 && asc) || (pDumpInfo->rowIndex < (pDumpInfo->totalRows - 1) && (!asc)));
1912 1913
}

1914
static int32_t buildBlockFromFiles(STsdbReader* pReader) {
H
Haojun Liao 已提交
1915
  int32_t code = TSDB_CODE_SUCCESS;
1916 1917
  bool    asc = ASCENDING_TRAVERSE(pReader->order);

1918 1919
  SDataBlockIter* pBlockIter = &pReader->status.blockIter;

1920
  while (1) {
1921
    SFileDataBlockInfo*  pFBlock = getCurrentBlockInfo(&pReader->status.blockIter);
1922 1923
    STableBlockScanInfo* pScanInfo = taosHashGet(pReader->status.pTableMap, &pFBlock->uid, sizeof(pFBlock->uid));

1924 1925
    SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;

1926
    if (fileBlockPartiallyRead(pDumpInfo, asc)) {  // file data block is partially loaded
1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941
      code = buildComposedDataBlock(pReader, pScanInfo);
    } 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);
        } else {  // data blocks in current file are exhausted, let's try the next file now
          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;
          }
1942
        }
H
Haojun Liao 已提交
1943
      }
1944 1945 1946

      // current block is not loaded yet, or data in buffer may overlap with the file block.
      code = doBuildDataBlock(pReader);
1947 1948
    }

1949 1950 1951 1952 1953 1954 1955 1956
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

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

1959 1960
static STsdb* getTsdbByRetentions(SVnode* pVnode, TSKEY winSKey, SRetention* retentions, const char* idStr,
                                  int8_t* pLevel) {
1961
  if (VND_IS_RSMA(pVnode)) {
1962
    int8_t  level = 0;
1963 1964
    int64_t now = taosGetTimestamp(pVnode->config.tsdbCfg.precision);

1965
    for (int8_t i = 0; i < TSDB_RETENTION_MAX; ++i) {
1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978
      SRetention* pRetention = retentions + level;
      if (pRetention->keep <= 0) {
        if (level > 0) {
          --level;
        }
        break;
      }
      if ((now - pRetention->keep) <= winSKey) {
        break;
      }
      ++level;
    }

1979
    const char* str = (idStr != NULL) ? idStr : "";
1980 1981

    if (level == TSDB_RETENTION_L0) {
1982
      *pLevel = TSDB_RETENTION_L0;
C
Cary Xu 已提交
1983
      tsdbDebug("vgId:%d, rsma level %d is selected to query %s", TD_VID(pVnode), TSDB_RETENTION_L0, str);
1984 1985
      return VND_RSMA0(pVnode);
    } else if (level == TSDB_RETENTION_L1) {
1986
      *pLevel = TSDB_RETENTION_L1;
C
Cary Xu 已提交
1987
      tsdbDebug("vgId:%d, rsma level %d is selected to query %s", TD_VID(pVnode), TSDB_RETENTION_L1, str);
1988 1989
      return VND_RSMA1(pVnode);
    } else {
1990
      *pLevel = TSDB_RETENTION_L2;
C
Cary Xu 已提交
1991
      tsdbDebug("vgId:%d, rsma level %d is selected to query %s", TD_VID(pVnode), TSDB_RETENTION_L2, str);
1992 1993 1994 1995 1996 1997 1998
      return VND_RSMA2(pVnode);
    }
  }

  return VND_TSDB(pVnode);
}

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

  int64_t endVer = 0;
L
Liu Jicong 已提交
2003 2004
  if (pCond->endVersion ==
      -1) {  // user not specified end version, set current maximum version of vnode as the endVersion
H
Haojun Liao 已提交
2005 2006
    endVer = pVnode->state.applied;
  } else {
L
Liu Jicong 已提交
2007
    endVer = (pCond->endVersion > pVnode->state.applied) ? pVnode->state.applied : pCond->endVersion;
2008 2009
  }

H
Haojun Liao 已提交
2010
  return (SVersionRange){.minVer = startVer, .maxVer = endVer};
2011 2012
}

H
Hongze Cheng 已提交
2013 2014 2015 2016
// // todo not unref yet, since it is not support multi-group interpolation query
// static UNUSED_FUNC void changeQueryHandleForInterpQuery(STsdbReader* pHandle) {
//   // filter the queried time stamp in the first place
//   STsdbReader* pTsdbReadHandle = (STsdbReader*)pHandle;
H
refact  
Hongze Cheng 已提交
2017

H
Hongze Cheng 已提交
2018 2019
//   // starts from the buffer in case of descending timestamp order check data blocks
//   size_t numOfTables = taosArrayGetSize(pTsdbReadHandle->pTableCheckInfo);
H
refact  
Hongze Cheng 已提交
2020

H
Hongze Cheng 已提交
2021 2022
//   int32_t i = 0;
//   while (i < numOfTables) {
H
Haojun Liao 已提交
2023
//     STableBlockScanInfo* pCheckInfo = taosArrayGet(pTsdbReadHandle->pTableCheckInfo, i);
H
refact  
Hongze Cheng 已提交
2024

H
Hongze Cheng 已提交
2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038
//     // the first qualified table for interpolation query
//     //    if ((pTsdbReadHandle->window.skey <= pCheckInfo->pTableObj->lastKey) &&
//     //        (pCheckInfo->pTableObj->lastKey != TSKEY_INITIAL_VAL)) {
//     //      break;
//     //    }

//     i++;
//   }

//   // there are no data in all the tables
//   if (i == numOfTables) {
//     return;
//   }

H
Haojun Liao 已提交
2039
//   STableBlockScanInfo info = *(STableBlockScanInfo*)taosArrayGet(pTsdbReadHandle->pTableCheckInfo, i);
H
Hongze Cheng 已提交
2040 2041 2042 2043 2044 2045
//   taosArrayClear(pTsdbReadHandle->pTableCheckInfo);

//   info.lastKey = pTsdbReadHandle->window.skey;
//   taosArrayPush(pTsdbReadHandle->pTableCheckInfo, &info);
// }

2046
bool hasBeenDropped(const SArray* pDelList, int32_t* index, TSDBKEY* pKey, int32_t order) {
2047 2048 2049 2050
  ASSERT(pKey != NULL);
  if (pDelList == NULL) {
    return false;
  }
L
Liu Jicong 已提交
2051 2052 2053
  size_t  num = taosArrayGetSize(pDelList);
  bool    asc = ASCENDING_TRAVERSE(order);
  int32_t step = asc ? 1 : -1;
2054

2055 2056 2057 2058 2059 2060
  if (asc) {
    if (*index >= num - 1) {
      TSDBKEY* last = taosArrayGetLast(pDelList);
      ASSERT(pKey->ts >= last->ts);

      if (pKey->ts > last->ts) {
2061
        return false;
2062 2063 2064
      } else if (pKey->ts == last->ts) {
        TSDBKEY* prev = taosArrayGet(pDelList, num - 2);
        return (prev->version >= pKey->version);
2065 2066
      }
    } else {
2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096
      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;
2097 2098
    }
  } else {
2099 2100
    if (*index <= 0) {
      TSDBKEY* pFirst = taosArrayGet(pDelList, 0);
2101

2102 2103 2104 2105 2106 2107 2108
      if (pKey->ts < pFirst->ts) {
        return false;
      } else if (pKey->ts == pFirst->ts) {
        return pFirst->version >= pKey->version;
      } else {
        ASSERT(0);
      }
2109
    } else {
2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136
      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;
          }
        }
2137 2138 2139 2140 2141
      }

      return false;
    }
  }
2142 2143

  return false;
2144 2145 2146 2147
}

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

2151
  TSDBROW* pRow = tsdbTbDataIterGet(pIter->iter);
H
Haojun Liao 已提交
2152
  TSDBKEY key = {.ts = pRow->pTSRow->ts, .version = pRow->version};
2153
  if (outOfTimeWindow(key.ts, &pReader->window)) {
2154
    pIter->hasVal = false;
H
Haojun Liao 已提交
2155 2156
    return NULL;
  }
H
Hongze Cheng 已提交
2157

2158
  // it is a valid data version
dengyihao's avatar
dengyihao 已提交
2159
  if ((key.version <= pReader->verRange.maxVer && key.version >= pReader->verRange.minVer) &&
2160
      (!hasBeenDropped(pDelList, &pIter->index, &key, pReader->order))) {
H
Haojun Liao 已提交
2161 2162
    return pRow;
  }
H
Hongze Cheng 已提交
2163

2164
  while (1) {
2165 2166
    pIter->hasVal = tsdbTbDataIterNext(pIter->iter);
    if (!pIter->hasVal) {
H
Haojun Liao 已提交
2167 2168
      return NULL;
    }
H
Hongze Cheng 已提交
2169

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

H
Haojun Liao 已提交
2172
    key = TSDBROW_KEY(pRow);
2173
    if (outOfTimeWindow(key.ts, &pReader->window)) {
2174
      pIter->hasVal = false;
H
Haojun Liao 已提交
2175 2176
      return NULL;
    }
H
Hongze Cheng 已提交
2177

dengyihao's avatar
dengyihao 已提交
2178
    if (key.version <= pReader->verRange.maxVer && key.version >= pReader->verRange.minVer &&
2179
        (!hasBeenDropped(pDelList, &pIter->index, &key, pReader->order))) {
H
Haojun Liao 已提交
2180 2181 2182 2183
      return pRow;
    }
  }
}
H
Hongze Cheng 已提交
2184

H
Haojun Liao 已提交
2185

2186 2187
int32_t doMergeRowsInBuf(SIterInfo* pIter, uint64_t uid, int64_t ts, SArray* pDelList, SRowMerger* pMerger,
                         STsdbReader* pReader) {
H
Haojun Liao 已提交
2188
  while (1) {
2189 2190
    pIter->hasVal = tsdbTbDataIterNext(pIter->iter);
    if (!pIter->hasVal) {
H
Haojun Liao 已提交
2191 2192
      break;
    }
H
Hongze Cheng 已提交
2193

2194
    // data exists but not valid
2195
    TSDBROW* pRow = getValidRow(pIter, pDelList, pReader);
2196 2197 2198 2199 2200
    if (pRow == NULL) {
      break;
    }

    // ts is not identical, quit
H
Haojun Liao 已提交
2201
    TSDBKEY k = TSDBROW_KEY(pRow);
2202
    if (k.ts != ts) {
H
Haojun Liao 已提交
2203 2204 2205
      break;
    }

H
Haojun Liao 已提交
2206
    STSchema* pTSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(pRow), pReader, uid);
2207
    tRowMergerAdd(pMerger, pRow, pTSchema);
H
Haojun Liao 已提交
2208 2209 2210 2211 2212
  }

  return TSDB_CODE_SUCCESS;
}

2213
static int32_t doMergeRowsInFileBlockImpl(SBlockData* pBlockData, int32_t rowIndex, int64_t key, SRowMerger* pMerger,
2214
                                          SVersionRange* pVerRange, int32_t step) {
2215 2216
  while (pBlockData->aTSKEY[rowIndex] == key && rowIndex < pBlockData->nRow && rowIndex >= 0) {
    if (pBlockData->aVersion[rowIndex] > pVerRange->maxVer || pBlockData->aVersion[rowIndex] < pVerRange->minVer) {
2217
      rowIndex += step;
2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234
      continue;
    }

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

  return rowIndex;
}

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

static int32_t checkForNeighborFileBlock(STsdbReader* pReader, STableBlockScanInfo* pScanInfo, SBlock* pBlock,
2235 2236
                                         SFileDataBlockInfo* pFBlock, SRowMerger* pMerger, int64_t key,
                                         CHECK_FILEBLOCK_STATE* state) {
2237
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;
2238
  SBlockData*         pBlockData = &pReader->status.fileBlockData;
2239

2240
  *state = CHECK_FILEBLOCK_QUIT;
2241
  int32_t step = ASCENDING_TRAVERSE(pReader->order) ? 1 : -1;
2242 2243 2244

  int32_t nextIndex = -1;
  SBlock* pNeighborBlock = getNeighborBlockOfSameTable(pFBlock, pScanInfo, &nextIndex, pReader->order);
2245
  if (pNeighborBlock == NULL) {  // do nothing
2246 2247 2248 2249
    return 0;
  }

  bool overlap = overlapWithNeighborBlock(pBlock, pNeighborBlock, pReader->order);
2250 2251
  taosMemoryFree(pNeighborBlock);

2252
  if (overlap) {  // load next block
2253
    SReaderStatus*  pStatus = &pReader->status;
2254 2255
    SDataBlockIter* pBlockIter = &pStatus->blockIter;

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

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

2263
    // 3. load the neighbor block, and set it to be the currently accessed file data block
H
Haojun Liao 已提交
2264 2265
    tBlockDataReset(&pStatus->fileBlockData);
    tBlockDataClearData(&pStatus->fileBlockData);
2266 2267 2268 2269 2270
    int32_t code = doLoadFileBlockData(pReader, pBlockIter, pScanInfo, &pStatus->fileBlockData);
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

2271
    // 4. check the data values
2272 2273 2274 2275
    initBlockDumpInfo(pReader, pBlockIter);

    pDumpInfo->rowIndex =
        doMergeRowsInFileBlockImpl(pBlockData, pDumpInfo->rowIndex, key, pMerger, &pReader->verRange, step);
H
Haojun Liao 已提交
2276
    if (pDumpInfo->rowIndex >= pDumpInfo->totalRows) {
2277 2278 2279 2280 2281 2282 2283
      *state = CHECK_FILEBLOCK_CONT;
    }
  }

  return TSDB_CODE_SUCCESS;
}

2284 2285
int32_t doMergeRowsInFileBlocks(SBlockData* pBlockData, STableBlockScanInfo* pScanInfo, STsdbReader* pReader,
                                SRowMerger* pMerger) {
2286 2287
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;

2288
  bool    asc = ASCENDING_TRAVERSE(pReader->order);
2289
  int64_t key = pBlockData->aTSKEY[pDumpInfo->rowIndex];
2290
  int32_t step = asc ? 1 : -1;
2291

2292
  pDumpInfo->rowIndex += step;
2293
  if ((pDumpInfo->rowIndex <= pBlockData->nRow - 1 && asc) || (pDumpInfo->rowIndex >= 0 && !asc)) {
2294 2295 2296
    pDumpInfo->rowIndex =
        doMergeRowsInFileBlockImpl(pBlockData, pDumpInfo->rowIndex, key, pMerger, &pReader->verRange, step);
  }
2297

2298 2299 2300 2301
  // 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;
2302

2303
      SFileDataBlockInfo* pFileBlockInfo = getCurrentBlockInfo(&pReader->status.blockIter);
2304
      SBlock*             pCurrentBlock = getCurrentBlock(&pReader->status.blockIter);
2305 2306 2307
      checkForNeighborFileBlock(pReader, pScanInfo, pCurrentBlock, pFileBlockInfo, pMerger, key, &st);
      if (st == CHECK_FILEBLOCK_QUIT) {
        break;
2308
      }
2309
    }
H
Haojun Liao 已提交
2310
  }
2311

H
Haojun Liao 已提交
2312 2313 2314
  return TSDB_CODE_SUCCESS;
}

dengyihao's avatar
dengyihao 已提交
2315
void doMergeMultiRows(TSDBROW* pRow, uint64_t uid, SIterInfo* pIter, SArray* pDelList, STSRow** pTSRow,
2316
                      STsdbReader* pReader, bool* freeTSRow) {
H
Haojun Liao 已提交
2317 2318 2319 2320

  TSDBROW* pNextRow = NULL;
  TSDBROW current = *pRow;

2321 2322 2323 2324 2325 2326 2327 2328
  {  // if the timestamp of the next valid row has a different ts, return current row directly
    pIter->hasVal = tsdbTbDataIterNext(pIter->iter);

    if (!pIter->hasVal) {
      *pTSRow = current.pTSRow;
      *freeTSRow = false;
      return;
    } else {  // has next point in mem/imem
H
Haojun Liao 已提交
2329
      pNextRow = getValidRow(pIter, pDelList, pReader);
2330 2331 2332 2333 2334 2335
      if (pNextRow == NULL) {
        *pTSRow = current.pTSRow;
        *freeTSRow = false;
        return;
      }

H
Haojun Liao 已提交
2336
      if (current.pTSRow->ts != pNextRow->pTSRow->ts) {
2337 2338 2339 2340 2341 2342 2343
        *pTSRow = current.pTSRow;
        *freeTSRow = false;
        return;
      }
    }
  }

2344 2345
  SRowMerger merge = {0};

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

H
Haojun Liao 已提交
2349 2350 2351 2352 2353 2354
  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);
2355
  tRowMergerGetRow(&merge, pTSRow);
2356
  tRowMergerClear(&merge);
M
Minglei Jin 已提交
2357

2358
  *freeTSRow = true;
2359 2360
}

2361 2362
void doMergeMemIMemRows(TSDBROW* pRow, TSDBROW* piRow, STableBlockScanInfo* pBlockScanInfo, STsdbReader* pReader,
                        STSRow** pTSRow) {
H
Haojun Liao 已提交
2363 2364
  SRowMerger merge = {0};

2365 2366 2367
  TSDBKEY k = TSDBROW_KEY(pRow);
  TSDBKEY ik = TSDBROW_KEY(piRow);

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

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

2374
    tRowMerge(&merge, pRow);
2375
    doMergeRowsInBuf(&pBlockScanInfo->iter, pBlockScanInfo->uid, k.ts, pBlockScanInfo->delSkyline, &merge, pReader);
2376
  } else {
H
Haojun Liao 已提交
2377
    STSchema* pSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(pRow), pReader, pBlockScanInfo->uid);
2378

H
Haojun Liao 已提交
2379
    tRowMergerInit(&merge, pRow, pSchema);
2380
    doMergeRowsInBuf(&pBlockScanInfo->iter, pBlockScanInfo->uid, k.ts, pBlockScanInfo->delSkyline, &merge, pReader);
2381 2382

    tRowMerge(&merge, piRow);
2383
    doMergeRowsInBuf(&pBlockScanInfo->iiter, pBlockScanInfo->uid, k.ts, pBlockScanInfo->delSkyline, &merge, pReader);
2384
  }
2385 2386 2387 2388

  tRowMergerGetRow(&merge, pTSRow);
}

2389
int32_t tsdbGetNextRowInMem(STableBlockScanInfo* pBlockScanInfo, STsdbReader* pReader, STSRow** pTSRow,
2390
                            int64_t endKey, bool* freeTSRow) {
2391 2392
  TSDBROW* pRow = getValidRow(&pBlockScanInfo->iter, pBlockScanInfo->delSkyline, pReader);
  TSDBROW* piRow = getValidRow(&pBlockScanInfo->iiter, pBlockScanInfo->delSkyline, pReader);
dengyihao's avatar
dengyihao 已提交
2393
  SArray*  pDelList = pBlockScanInfo->delSkyline;
H
Haojun Liao 已提交
2394

2395 2396
  // todo refactor
  bool asc = ASCENDING_TRAVERSE(pReader->order);
2397
  if (pBlockScanInfo->iter.hasVal) {
2398 2399 2400 2401 2402 2403
    TSDBKEY k = TSDBROW_KEY(pRow);
    if ((k.ts >= endKey && asc) || (k.ts <= endKey && !asc)) {
      pRow = NULL;
    }
  }

2404
  if (pBlockScanInfo->iiter.hasVal) {
2405 2406 2407 2408 2409 2410
    TSDBKEY k = TSDBROW_KEY(piRow);
    if ((k.ts >= endKey && asc) || (k.ts <= endKey && !asc)) {
      piRow = NULL;
    }
  }

2411
  if (pBlockScanInfo->iter.hasVal && pBlockScanInfo->iiter.hasVal && pRow != NULL && piRow != NULL) {
2412
    TSDBKEY k = TSDBROW_KEY(pRow);
2413
    TSDBKEY ik = TSDBROW_KEY(piRow);
H
Haojun Liao 已提交
2414

2415
    if (ik.ts < k.ts) {  // ik.ts < k.ts
2416
      doMergeMultiRows(piRow, pBlockScanInfo->uid, &pBlockScanInfo->iiter, pDelList, pTSRow, pReader, freeTSRow);
2417
    } else if (k.ts < ik.ts) {
2418
      doMergeMultiRows(pRow, pBlockScanInfo->uid, &pBlockScanInfo->iter, pDelList, pTSRow, pReader, freeTSRow);
2419 2420
    } else {  // ik.ts == k.ts
      doMergeMemIMemRows(pRow, piRow, pBlockScanInfo, pReader, pTSRow);
2421
      *freeTSRow = true;
H
Haojun Liao 已提交
2422
    }
2423 2424

    return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
2425 2426
  }

2427
  if (pBlockScanInfo->iter.hasVal && pRow != NULL) {
2428
    doMergeMultiRows(pRow, pBlockScanInfo->uid, &pBlockScanInfo->iter, pDelList, pTSRow, pReader, freeTSRow);
H
Haojun Liao 已提交
2429 2430 2431
    return TSDB_CODE_SUCCESS;
  }

2432
  if (pBlockScanInfo->iiter.hasVal && piRow != NULL) {
2433
    doMergeMultiRows(piRow, pBlockScanInfo->uid, &pBlockScanInfo->iiter, pDelList, pTSRow, pReader, freeTSRow);
H
Haojun Liao 已提交
2434 2435 2436 2437 2438 2439
    return TSDB_CODE_SUCCESS;
  }

  return TSDB_CODE_SUCCESS;
}

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

2444
  SBlockLoadSuppInfo* pSupInfo = &pReader->suppInfo;
H
Haojun Liao 已提交
2445
  STSchema* pSchema = doGetSchemaForTSRow(pTSRow->sver, pReader, uid);
2446

2447
  SColVal colVal = {0};
2448
  int32_t i = 0, j = 0;
H
Haojun Liao 已提交
2449

2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460
  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 已提交
2461
      tTSRowGetVal(pTSRow, pSchema, j, &colVal);
2462 2463 2464 2465 2466 2467 2468 2469
      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;
2470
    }
2471 2472
  }

2473
  // set null value since current column does not exist in the "pSchema"
2474
  while (i < numOfCols) {
2475 2476 2477 2478 2479
    pColInfoData = taosArrayGet(pBlock->pDataBlock, i);
    colDataAppendNULL(pColInfoData, numOfRows);
    i += 1;
  }

2480 2481 2482 2483
  pBlock->info.rows += 1;
  return TSDB_CODE_SUCCESS;
}

2484 2485 2486 2487 2488 2489 2490 2491 2492
int32_t doAppendRowFromBlock(SSDataBlock* pResBlock, STsdbReader* pReader, SBlockData* pBlockData, int32_t rowIndex) {
  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]);
2493
    i += 1;
2494 2495 2496 2497 2498 2499
  }

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

2500
  while (i < numOfOutputCols && j < numOfInputCols) {
2501
    SColumnInfoData* pCol = taosArrayGet(pResBlock->pDataBlock, i);
2502
    SColData*        pData = tBlockDataGetColDataByIdx(pBlockData, j);
2503 2504

    if (pData->cid == pCol->info.colId) {
2505 2506
      tColDataGetValue(pData, rowIndex, &cv);
      doCopyColVal(pCol, outputRowIndex, i, &cv, pSupInfo);
2507 2508 2509 2510 2511 2512 2513 2514 2515 2516
      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);
2517
    colDataAppendNULL(pCol, outputRowIndex);
2518 2519 2520 2521 2522 2523 2524
    i += 1;
  }

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

2525 2526
int32_t buildDataBlockFromBufImpl(STableBlockScanInfo* pBlockScanInfo, int64_t endKey, int32_t capacity,
                                  STsdbReader* pReader) {
H
Haojun Liao 已提交
2527 2528 2529 2530
  SSDataBlock* pBlock = pReader->pResBlock;

  do {
    STSRow* pTSRow = NULL;
2531 2532
    bool freeTSRow = false;
    tsdbGetNextRowInMem(pBlockScanInfo, pReader, &pTSRow, endKey, &freeTSRow);
2533 2534
    if (pTSRow == NULL) {
      break;
H
Haojun Liao 已提交
2535 2536
    }

H
Haojun Liao 已提交
2537
    doAppendRowFromTSRow(pBlock, pReader, pTSRow, pBlockScanInfo->uid);
2538 2539 2540
    if (freeTSRow) {
      taosMemoryFree(pTSRow);
    }
H
Haojun Liao 已提交
2541 2542

    // no data in buffer, return immediately
2543
    if (!(pBlockScanInfo->iter.hasVal || pBlockScanInfo->iiter.hasVal)) {
H
Haojun Liao 已提交
2544 2545 2546
      break;
    }

2547
    if (pBlock->info.rows >= capacity) {
H
Haojun Liao 已提交
2548 2549 2550 2551
      break;
    }
  } while (1);

2552
  ASSERT(pBlock->info.rows <= capacity);
H
Haojun Liao 已提交
2553 2554
  return TSDB_CODE_SUCCESS;
}
H
Hongze Cheng 已提交
2555

2556
// todo refactor, use arraylist instead
H
Hongze Cheng 已提交
2557
int32_t tsdbSetTableId(STsdbReader* pReader, int64_t uid) {
2558 2559 2560 2561 2562
  ASSERT(pReader != NULL);
  taosHashClear(pReader->status.pTableMap);

  STableBlockScanInfo info = {.lastKey = 0, .uid = uid};
  taosHashPut(pReader->status.pTableMap, &info.uid, sizeof(uint64_t), &info, sizeof(info));
H
Hongze Cheng 已提交
2563 2564 2565
  return TDB_CODE_SUCCESS;
}

dengyihao's avatar
dengyihao 已提交
2566 2567 2568 2569 2570 2571
void* tsdbGetIdx(SMeta* pMeta) {
  if (pMeta == NULL) {
    return NULL;
  }
  return metaGetIdx(pMeta);
}
dengyihao's avatar
dengyihao 已提交
2572

dengyihao's avatar
dengyihao 已提交
2573 2574 2575 2576 2577 2578
void* tsdbGetIvtIdx(SMeta* pMeta) {
  if (pMeta == NULL) {
    return NULL;
  }
  return metaGetIvtIdx(pMeta);
}
L
Liu Jicong 已提交
2579

2580 2581 2582 2583
uint64_t getReaderMaxVersion(STsdbReader *pReader) {
  return pReader->verRange.maxVer;
}

C
Cary Xu 已提交
2584 2585 2586 2587 2588 2589 2590 2591 2592 2593
/**
 * @brief Get all suids since suid
 *
 * @param pMeta
 * @param suid return all suids in one vnode if suid is 0
 * @param list
 * @return int32_t
 */
int32_t tsdbGetStbIdList(SMeta* pMeta, int64_t suid, SArray* list) {
  SMStbCursor* pCur = metaOpenStbCursor(pMeta, suid);
L
Liu Jicong 已提交
2594
  if (!pCur) {
C
Cary Xu 已提交
2595 2596
    return TSDB_CODE_FAILED;
  }
C
Cary Xu 已提交
2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610

  while (1) {
    tb_uid_t id = metaStbCursorNext(pCur);
    if (id == 0) {
      break;
    }

    taosArrayPush(list, &id);
  }

  metaCloseStbCursor(pCur);
  return TSDB_CODE_SUCCESS;
}

H
refact  
Hongze Cheng 已提交
2611
// ====================================== EXPOSED APIs ======================================
2612 2613
int32_t tsdbReaderOpen(SVnode* pVnode, SQueryTableDataCond* pCond, SArray* pTableList, STsdbReader** ppReader,
                       const char* idstr) {
2614 2615
  int32_t code = tsdbReaderCreate(pVnode, pCond, ppReader, 4096, idstr);
  if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
2616 2617
    goto _err;
  }
H
Hongze Cheng 已提交
2618

2619
  // check for query time window
H
Haojun Liao 已提交
2620
  STsdbReader* pReader = *ppReader;
2621
  if (isEmptyQueryTimeWindow(&pReader->window)) {
H
Haojun Liao 已提交
2622 2623 2624
    tsdbDebug("%p query window not overlaps with the data set, no result returned, %s", pReader, pReader->idStr);
    return TSDB_CODE_SUCCESS;
  }
H
Hongze Cheng 已提交
2625

2626 2627 2628
  if (pCond->type == TIMEWINDOW_RANGE_EXTERNAL) {
    // update the SQueryTableDataCond to create inner reader
    STimeWindow w = pCond->twindows;
2629
    int32_t     order = pCond->order;
2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647
    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;
    }

    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;
2648
    } else {
2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664
      pCond->twindows.skey = INT64_MIN;
      pCond->twindows.ekey = w.ekey;
    }
    code = tsdbReaderCreate(pVnode, pCond, &pReader->innerReader[1], 1, idstr);
    if (code != TSDB_CODE_SUCCESS) {
      goto _err;
    }
  }

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

2665 2666
  int32_t numOfTables = taosArrayGetSize(pTableList);
  pReader->status.pTableMap = createDataBlockScanInfo(pReader, pTableList->pData, numOfTables);
H
Haojun Liao 已提交
2667 2668 2669
  if (pReader->status.pTableMap == NULL) {
    tsdbReaderClose(pReader);
    *ppReader = NULL;
H
Haojun Liao 已提交
2670

H
Haojun Liao 已提交
2671 2672 2673
    code = TSDB_CODE_TDB_OUT_OF_MEMORY;
    goto _err;
  }
H
Hongze Cheng 已提交
2674

H
Hongze Cheng 已提交
2675
  code = tsdbTakeReadSnap(pReader->pTsdb, &pReader->pReadSnap);
2676 2677 2678
  if (code != TSDB_CODE_SUCCESS) {
    goto _err;
  }
H
Hongze Cheng 已提交
2679

2680 2681
  if (pReader->type == TIMEWINDOW_RANGE_CONTAINED) {
    SDataBlockIter* pBlockIter = &pReader->status.blockIter;
2682

2683
    initFilesetIterator(&pReader->status.fileIter, pReader->pReadSnap->fs.aDFileSet, pReader->order, pReader->idStr);
2684
    resetDataBlockIterator(&pReader->status.blockIter, pReader->order, pReader->status.pTableMap);
2685 2686 2687 2688 2689 2690 2691 2692 2693 2694

    // 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;
      }
    }
2695
  } else {
2696
    STsdbReader*    pPrevReader = pReader->innerReader[0];
2697 2698
    SDataBlockIter* pBlockIter = &pPrevReader->status.blockIter;

2699 2700
    initFilesetIterator(&pPrevReader->status.fileIter, pPrevReader->pReadSnap->fs.aDFileSet, pPrevReader->order,
                        pPrevReader->idStr);
2701
    resetDataBlockIterator(&pPrevReader->status.blockIter, pPrevReader->order, pReader->status.pTableMap);
2702 2703 2704 2705 2706 2707 2708 2709 2710

    // 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;
      }
2711 2712 2713
    }
  }

2714
  tsdbDebug("%p total numOfTable:%d in this query %s", pReader, numOfTables, pReader->idStr);
H
Hongze Cheng 已提交
2715
  return code;
H
Hongze Cheng 已提交
2716 2717

_err:
S
Shengliang Guan 已提交
2718
  tsdbError("failed to create data reader, code:%s %s", tstrerror(code), pReader->idStr);
H
Hongze Cheng 已提交
2719
  return code;
H
refact  
Hongze Cheng 已提交
2720 2721 2722
}

void tsdbReaderClose(STsdbReader* pReader) {
2723 2724
  if (pReader == NULL) {
    return;
2725
  }
H
refact  
Hongze Cheng 已提交
2726

2727
  SBlockLoadSuppInfo* pSupInfo = &pReader->suppInfo;
H
Hongze Cheng 已提交
2728
  tsdbUntakeReadSnap(pReader->pTsdb, pReader->pReadSnap);
H
Hongze Cheng 已提交
2729

2730 2731 2732 2733
  taosMemoryFreeClear(pSupInfo->plist);
  taosMemoryFree(pSupInfo->colIds);

  taosArrayDestroy(pSupInfo->pColAgg);
L
Liu Jicong 已提交
2734
  for (int32_t i = 0; i < blockDataGetNumOfCols(pReader->pResBlock); ++i) {
2735 2736 2737 2738 2739
    if (pSupInfo->buildBuf[i] != NULL) {
      taosMemoryFreeClear(pSupInfo->buildBuf[i]);
    }
  }
  taosMemoryFree(pSupInfo->buildBuf);
H
Haojun Liao 已提交
2740
  tBlockDataClear(&pReader->status.fileBlockData, true);
2741 2742

  cleanupDataBlockIterator(&pReader->status.blockIter);
2743 2744

  size_t numOfTables = taosHashGetSize(pReader->status.pTableMap);
2745
  destroyBlockScanInfo(pReader->status.pTableMap);
2746
  blockDataDestroy(pReader->pResBlock);
2747

H
Haojun Liao 已提交
2748 2749 2750
  if (pReader->pFileReader != NULL) {
    tsdbDataFReaderClose(&pReader->pFileReader);
  }
H
refact  
Hongze Cheng 已提交
2751

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

2754
  tsdbDebug("%p :io-cost summary: head-file:%" PRIu64 ", head-file time:%.2f ms, SMA:%" PRId64
2755 2756
            " SMA-time:%.2f ms, fileBlocks:%" PRId64 ", fileBlocks-time:%.2f ms, "
            "build in-memory-block-time:%.2f ms, STableBlockScanInfo size:%.2f Kb %s",
2757
            pReader, pCost->headFileLoad, pCost->headFileLoadTime, pCost->smaData, pCost->smaLoadTime,
2758
            pCost->numOfBlocks, pCost->blockLoadTime, pCost->buildmemBlock,
2759
            numOfTables * sizeof(STableBlockScanInfo) / 1000.0, pReader->idStr);
H
refact  
Hongze Cheng 已提交
2760

2761 2762
  taosMemoryFree(pReader->idStr);
  taosMemoryFree(pReader->pSchema);
H
Haojun Liao 已提交
2763
  taosMemoryFree(pReader->pMemSchema);
2764
  taosMemoryFreeClear(pReader);
H
refact  
Hongze Cheng 已提交
2765 2766
}

2767
static bool doTsdbNextDataBlock(STsdbReader* pReader) {
H
Haojun Liao 已提交
2768
  // cleanup the data that belongs to the previous data block
2769 2770
  SSDataBlock* pBlock = pReader->pResBlock;
  blockDataCleanup(pBlock);
H
Hongze Cheng 已提交
2771

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

2774 2775 2776 2777 2778
  if (pStatus->loadFromFile) {
    int32_t code = buildBlockFromFiles(pReader);
    if (code != TSDB_CODE_SUCCESS) {
      return false;
    }
2779

2780 2781 2782
    if (pBlock->info.rows > 0) {
      return true;
    } else {
H
Haojun Liao 已提交
2783
      buildBlockFromBufferSequentially(pReader);
2784
      return pBlock->info.rows > 0;
H
Haojun Liao 已提交
2785
    }
2786 2787 2788
  } else {  // no data in files, let's try the buffer
    buildBlockFromBufferSequentially(pReader);
    return pBlock->info.rows > 0;
H
Haojun Liao 已提交
2789
  }
2790

2791
  return false;
H
refact  
Hongze Cheng 已提交
2792 2793
}

2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830
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) {
2831 2832 2833 2834
  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 已提交
2835 2836
}

2837 2838
void tsdbRetrieveDataBlockInfo(STsdbReader* pReader, SDataBlockInfo* pDataBlockInfo) {
  if (pReader->type == TIMEWINDOW_RANGE_EXTERNAL) {
2839
    if (pReader->step == EXTERNAL_ROWS_MAIN) {
2840
      setBlockInfo(pReader, pDataBlockInfo);
2841
    } else if (pReader->step == EXTERNAL_ROWS_PREV) {
2842 2843 2844 2845 2846 2847 2848 2849 2850
      setBlockInfo(pReader->innerReader[0], pDataBlockInfo);
    } else {
      setBlockInfo(pReader->innerReader[1], pDataBlockInfo);
    }
  } else {
    setBlockInfo(pReader, pDataBlockInfo);
  }
}

2851
int32_t tsdbRetrieveDatablockSMA(STsdbReader* pReader, SColumnDataAgg*** pBlockStatis, bool* allHave) {
H
Hongze Cheng 已提交
2852
  int32_t code = 0;
2853
  *allHave = false;
H
Hongze Cheng 已提交
2854

2855
  if (pReader->type == TIMEWINDOW_RANGE_EXTERNAL) {
2856 2857 2858 2859
    *pBlockStatis = NULL;
    return TSDB_CODE_SUCCESS;
  }

2860
  // there is no statistics data for composed block
2861 2862 2863 2864
  if (pReader->status.composedDataBlock) {
    *pBlockStatis = NULL;
    return TSDB_CODE_SUCCESS;
  }
H
Hongze Cheng 已提交
2865

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

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

2871 2872
  SBlockLoadSuppInfo* pSup = &pReader->suppInfo;

2873
  if (tBlockHasSma(pBlock)) {
2874
    code = tsdbReadBlockSma(pReader->pFileReader, pBlock, pSup->pColAgg, NULL);
2875
    if (code != TSDB_CODE_SUCCESS) {
2876 2877
      tsdbDebug("vgId:%d, failed to load block SMA for uid %" PRIu64 ", code:%s, %s", 0, pFBlock->uid, tstrerror(code),
                pReader->idStr);
2878 2879
      return code;
    }
2880 2881 2882
  } else {
    *pBlockStatis = NULL;
    return TSDB_CODE_SUCCESS;
2883
  }
H
Hongze Cheng 已提交
2884

2885
  *allHave = true;
H
Hongze Cheng 已提交
2886

2887 2888
  // always load the first primary timestamp column data
  SColumnDataAgg* pTsAgg = &pSup->tsColAgg;
2889

2890 2891
  pTsAgg->numOfNull = 0;
  pTsAgg->colId = PRIMARYKEY_TIMESTAMP_COL_ID;
2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907
  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;
      }
2908 2909
      i += 1;
      j += 1;
2910 2911 2912 2913 2914 2915 2916
    } else if (pAgg->colId < pSup->colIds[j]) {
      i += 1;
    } else if (pSup->colIds[j] < pAgg->colId) {
      j += 1;
    }
  }

2917
  double elapsed = (taosGetTimestampUs() - stime) / 1000.0;
2918
  pReader->cost.smaLoadTime += elapsed;
2919
  pReader->cost.smaData += 1;
2920 2921 2922

  *pBlockStatis = pSup->plist;

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

H
Hongze Cheng 已提交
2926
  return code;
H
Hongze Cheng 已提交
2927 2928
}

2929
static SArray* doRetrieveDataBlock(STsdbReader* pReader) {
H
Haojun Liao 已提交
2930 2931 2932
  SReaderStatus* pStatus = &pReader->status;

  if (pStatus->composedDataBlock) {
2933
    return pReader->pResBlock->pDataBlock;
2934
  }
2935

2936
  SFileDataBlockInfo*  pFBlock = getCurrentBlockInfo(&pStatus->blockIter);
2937
  STableBlockScanInfo* pBlockScanInfo = taosHashGet(pStatus->pTableMap, &pFBlock->uid, sizeof(pFBlock->uid));
2938

H
Haojun Liao 已提交
2939 2940 2941
  tBlockDataReset(&pStatus->fileBlockData);
  tBlockDataClearData(&pStatus->fileBlockData);
  int32_t code = doLoadFileBlockData(pReader, &pStatus->blockIter, pBlockScanInfo, &pStatus->fileBlockData);
2942
  if (code != TSDB_CODE_SUCCESS) {
H
Hongze Cheng 已提交
2943
    tBlockDataClear(&pStatus->fileBlockData, 1);
H
Haojun Liao 已提交
2944

2945 2946
    terrno = code;
    return NULL;
2947
  }
2948 2949 2950

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

2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964
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 已提交
2965
int32_t tsdbReaderReset(STsdbReader* pReader, SQueryTableDataCond* pCond) {
2966 2967 2968
  if (isEmptyQueryTimeWindow(&pReader->window)) {
    return TSDB_CODE_SUCCESS;
  }
H
Hongze Cheng 已提交
2969

L
Liu Jicong 已提交
2970
  pReader->order = pCond->order;
2971
  pReader->type = TIMEWINDOW_RANGE_CONTAINED;
2972
  pReader->status.loadFromFile = true;
dengyihao's avatar
dengyihao 已提交
2973
  pReader->status.pTableIter = NULL;
H
Haojun Liao 已提交
2974
  pReader->window = updateQueryTimeWindow(pReader->pTsdb, &pCond->twindows);
H
Hongze Cheng 已提交
2975

2976
  // allocate buffer in order to load data blocks from file
2977
  memset(&pReader->suppInfo.tsColAgg, 0, sizeof(SColumnDataAgg));
2978 2979
  memset(pReader->suppInfo.plist, 0, POINTER_BYTES);

2980
  pReader->suppInfo.tsColAgg.colId = PRIMARYKEY_TIMESTAMP_COL_ID;
2981
  tsdbDataFReaderClose(&pReader->pFileReader);
2982

2983
  int32_t numOfTables = taosHashGetSize(pReader->status.pTableMap);
L
Liu Jicong 已提交
2984 2985
  tsdbDataFReaderClose(&pReader->pFileReader);

H
Hongze Cheng 已提交
2986
  initFilesetIterator(&pReader->status.fileIter, pReader->pReadSnap->fs.aDFileSet, pReader->order, pReader->idStr);
2987
  resetDataBlockIterator(&pReader->status.blockIter, pReader->order, pReader->status.pTableMap);
2988
  resetDataBlockScanInfo(pReader->status.pTableMap);
2989

2990
  int32_t         code = 0;
2991 2992
  SDataBlockIter* pBlockIter = &pReader->status.blockIter;

2993 2994 2995 2996 2997 2998
  // 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) {
2999 3000
      tsdbError("%p reset reader failed, numOfTables:%d, query range:%" PRId64 " - %" PRId64 " in query %s", pReader,
                numOfTables, pReader->window.skey, pReader->window.ekey, pReader->idStr);
3001 3002 3003
      return code;
    }
  }
H
Hongze Cheng 已提交
3004

dengyihao's avatar
dengyihao 已提交
3005 3006
  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);
3007

3008
  return code;
H
Hongze Cheng 已提交
3009
}
H
Hongze Cheng 已提交
3010

3011 3012 3013
static int32_t getBucketIndex(int32_t startRow, int32_t bucketRange, int32_t numOfRows) {
  return (numOfRows - startRow) / bucketRange;
}
H
Hongze Cheng 已提交
3014

3015 3016 3017 3018
int32_t tsdbGetFileBlocksDistInfo(STsdbReader* pReader, STableBlockDistInfo* pTableBlockInfo) {
  int32_t code = TSDB_CODE_SUCCESS;
  pTableBlockInfo->totalSize = 0;
  pTableBlockInfo->totalRows = 0;
H
Hongze Cheng 已提交
3019

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

3023 3024 3025
  STsdbCfg* pc = &pReader->pTsdb->pVnode->config.tsdbCfg;
  pTableBlockInfo->defMinRows = pc->minRows;
  pTableBlockInfo->defMaxRows = pc->maxRows;
H
Hongze Cheng 已提交
3026

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

3029
  pTableBlockInfo->numOfFiles += 1;
H
Hongze Cheng 已提交
3030

3031 3032
  int32_t numOfTables = (int32_t)taosHashGetSize(pStatus->pTableMap);
  int     defaultRows = 4096;
H
Hongze Cheng 已提交
3033

3034 3035
  SDataBlockIter* pBlockIter = &pStatus->blockIter;
  pTableBlockInfo->numOfFiles += pStatus->fileIter.numOfFiles;
H
Haojun Liao 已提交
3036 3037 3038 3039

  if (pBlockIter->numOfBlocks > 0) {
    pTableBlockInfo->numOfBlocks += pBlockIter->numOfBlocks;
  }
H
Hongze Cheng 已提交
3040

3041
  pTableBlockInfo->numOfTables = numOfTables;
H
Haojun Liao 已提交
3042
  bool hasNext = (pBlockIter->numOfBlocks > 0);
H
Hongze Cheng 已提交
3043

3044 3045
  while (true) {
    if (hasNext) {
H
Haojun Liao 已提交
3046
      SBlock* pBlock = getCurrentBlock(pBlockIter);
H
Hongze Cheng 已提交
3047

3048 3049
      int32_t numOfRows = pBlock->nRow;
      pTableBlockInfo->totalRows += numOfRows;
H
Hongze Cheng 已提交
3050

3051 3052 3053
      if (numOfRows > pTableBlockInfo->maxRows) {
        pTableBlockInfo->maxRows = numOfRows;
      }
H
refact  
Hongze Cheng 已提交
3054

3055 3056 3057
      if (numOfRows < pTableBlockInfo->minRows) {
        pTableBlockInfo->minRows = numOfRows;
      }
H
refact  
Hongze Cheng 已提交
3058

3059 3060 3061
      if (numOfRows < defaultRows) {
        pTableBlockInfo->numOfSmallBlocks += 1;
      }
H
refact  
Hongze Cheng 已提交
3062

3063 3064
      int32_t bucketIndex = getBucketIndex(pTableBlockInfo->defMinRows, bucketRange, numOfRows);
      pTableBlockInfo->blockRowsHisto[bucketIndex]++;
3065 3066

      hasNext = blockIteratorNext(&pStatus->blockIter);
3067 3068 3069 3070 3071
    } else {
      code = initForFirstBlockInFile(pReader, pBlockIter);
      if ((code != TSDB_CODE_SUCCESS) || (pReader->status.loadFromFile == false)) {
        break;
      }
H
refact  
Hongze Cheng 已提交
3072

3073
      pTableBlockInfo->numOfBlocks += pBlockIter->numOfBlocks;
3074
      hasNext = (pBlockIter->numOfBlocks > 0);
3075
    }
H
refact  
Hongze Cheng 已提交
3076

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

H
refact  
Hongze Cheng 已提交
3081 3082
  return code;
}
H
Hongze Cheng 已提交
3083

H
refact  
Hongze Cheng 已提交
3084
int64_t tsdbGetNumOfRowsInMemTable(STsdbReader* pReader) {
3085
  int64_t rows = 0;
H
Hongze Cheng 已提交
3086

3087 3088
  SReaderStatus* pStatus = &pReader->status;
  pStatus->pTableIter = taosHashIterate(pStatus->pTableMap, NULL);
H
Hongze Cheng 已提交
3089

3090 3091 3092 3093 3094
  while (pStatus->pTableIter != NULL) {
    STableBlockScanInfo* pBlockScanInfo = pStatus->pTableIter;

    STbData* d = NULL;
    if (pReader->pTsdb->mem != NULL) {
3095
      tsdbGetTbDataFromMemTable(pReader->pReadSnap->pMem, pReader->suid, pBlockScanInfo->uid, &d);
3096 3097 3098 3099 3100 3101 3102
      if (d != NULL) {
        rows += tsdbGetNRowsInTbData(d);
      }
    }

    STbData* di = NULL;
    if (pReader->pTsdb->imem != NULL) {
3103
      tsdbGetTbDataFromMemTable(pReader->pReadSnap->pIMem, pReader->suid, pBlockScanInfo->uid, &di);
3104 3105 3106 3107 3108 3109 3110 3111
      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 已提交
3112

H
refact  
Hongze Cheng 已提交
3113
  return rows;
H
Hongze Cheng 已提交
3114
}
D
dapan1121 已提交
3115

L
Liu Jicong 已提交
3116
int32_t tsdbGetTableSchema(SVnode* pVnode, int64_t uid, STSchema** pSchema, int64_t* suid) {
D
dapan1121 已提交
3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128
  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 已提交
3129

D
dapan1121 已提交
3130
  if (mr.me.type == TSDB_CHILD_TABLE) {
D
dapan1121 已提交
3131
    tDecoderClear(&mr.coder);
D
dapan1121 已提交
3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146
    *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 已提交
3147

D
dapan1121 已提交
3148 3149
  return TSDB_CODE_SUCCESS;
}
H
Hongze Cheng 已提交
3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179

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 已提交
3180
  // fs
H
Hongze Cheng 已提交
3181 3182 3183 3184 3185
  code = tsdbFSRef(pTsdb, &(*ppSnap)->fs);
  if (code) {
    taosThreadRwlockUnlock(&pTsdb->rwLock);
    goto _exit;
  }
H
Hongze Cheng 已提交
3186 3187 3188 3189 3190 3191 3192 3193

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

S
Shengliang Guan 已提交
3194
  tsdbTrace("vgId:%d, take read snapshot", TD_VID(pTsdb->pVnode));
H
Hongze Cheng 已提交
3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208
_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 已提交
3209
    tsdbFSUnref(pTsdb, &pSnap->fs);
H
Hongze Cheng 已提交
3210
    taosMemoryFree(pSnap);
H
Hongze Cheng 已提交
3211
  }
H
Hongze Cheng 已提交
3212

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