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

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

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

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

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

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

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

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

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

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

typedef struct SIOCostSummary {
70 71 72
  int64_t numOfBlocks;
  double  blockLoadTime;
  double  buildmemBlock;
73
  int64_t headFileLoad;
74
  double  headFileLoadTime;
75
  int64_t smaDataLoad;
76
  double  smaLoadTime;
77 78
  int64_t lastBlockLoad;
  double  lastBlockLoadTime;
H
Haojun Liao 已提交
79 80
  int64_t composedBlocks;
  double  buildComposedBlockTime;
H
Haojun Liao 已提交
81
  double  createScanInfoList;
H
Hongze Cheng 已提交
82 83 84
} SIOCostSummary;

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

94
typedef struct SLastBlockReader {
H
Hongze Cheng 已提交
95 96 97 98 99
  STimeWindow        window;
  SVersionRange      verRange;
  int32_t            order;
  uint64_t           uid;
  SMergeTree         mergeTree;
100
  SSttBlockLoadInfo* pInfo;
101 102
} SLastBlockReader;

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

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

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

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

133
typedef struct SUidOrderCheckInfo {
134 135
  uint64_t* tableUidList;  // access table uid list in uid ascending order list
  int32_t   currentIndex;  // index in table uid list
136 137
} SUidOrderCheckInfo;

H
Haojun Liao 已提交
138
typedef struct SReaderStatus {
H
Hongze Cheng 已提交
139 140 141
  bool                  loadFromFile;       // check file stage
  bool                  composedDataBlock;  // the returned data block is a composed block or not
  SHashObj*             pTableMap;          // SHash<STableBlockScanInfo>
142
  STableBlockScanInfo** pTableIter;         // table iterator used in building in-memory buffer data blocks.
H
Hongze Cheng 已提交
143 144 145 146 147 148
  SUidOrderCheckInfo    uidCheckInfo;       // check all table in uid order
  SFileBlockDumpInfo    fBlockDumpInfo;
  SDFileSet*            pCurrentFileset;  // current opened file set
  SBlockData            fileBlockData;
  SFilesetIter          fileIter;
  SDataBlockIter        blockIter;
H
Haojun Liao 已提交
149 150
} SReaderStatus;

151
typedef struct SBlockInfoBuf {
H
Hongze Cheng 已提交
152 153 154
  int32_t currentIndex;
  SArray* pData;
  int32_t numPerBucket;
155 156
} SBlockInfoBuf;

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

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

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

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

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

224 225
static int32_t setColumnIdSlotList(SBlockLoadSuppInfo* pSupInfo, SColumnInfo* pCols, const int32_t* pSlotIdList,
                                   int32_t numOfCols) {
226
  pSupInfo->smaValid = true;
227
  pSupInfo->numOfCols = numOfCols;
228
  pSupInfo->colId = taosMemoryMalloc(numOfCols * (sizeof(int16_t) * 2 + POINTER_BYTES));
H
Haojun Liao 已提交
229 230
  if (pSupInfo->colId == NULL) {
    taosMemoryFree(pSupInfo->colId);
H
Haojun Liao 已提交
231 232
    return TSDB_CODE_OUT_OF_MEMORY;
  }
H
Hongze Cheng 已提交
233

H
Haojun Liao 已提交
234
  pSupInfo->slotId = (int16_t*)((char*)pSupInfo->colId + (sizeof(int16_t) * numOfCols));
235
  pSupInfo->buildBuf = (char**)((char*)pSupInfo->slotId + (sizeof(int16_t) * numOfCols));
H
Haojun Liao 已提交
236
  for (int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
237 238
    pSupInfo->colId[i] = pCols[i].colId;
    pSupInfo->slotId[i] = pSlotIdList[i];
239

H
Haojun Liao 已提交
240 241
    if (IS_VAR_DATA_TYPE(pCols[i].type)) {
      pSupInfo->buildBuf[i] = taosMemoryMalloc(pCols[i].bytes);
H
Haojun Liao 已提交
242 243
    } else {
      pSupInfo->buildBuf[i] = NULL;
244
    }
H
Haojun Liao 已提交
245
  }
H
Hongze Cheng 已提交
246

H
Haojun Liao 已提交
247 248
  return TSDB_CODE_SUCCESS;
}
H
Hongze Cheng 已提交
249

H
Haojun Liao 已提交
250
static int32_t updateBlockSMAInfo(STSchema* pSchema, SBlockLoadSuppInfo* pSupInfo) {
251 252
  int32_t i = 0, j = 0;

H
Hongze Cheng 已提交
253
  while (i < pSchema->numOfCols && j < pSupInfo->numOfCols) {
254
    STColumn* pTCol = &pSchema->columns[i];
H
Haojun Liao 已提交
255
    if (pTCol->colId == pSupInfo->colId[j]) {
256 257
      if (!IS_BSMA_ON(pTCol)) {
        pSupInfo->smaValid = false;
H
Haojun Liao 已提交
258
        return TSDB_CODE_SUCCESS;
259 260 261 262
      }

      i += 1;
      j += 1;
H
Haojun Liao 已提交
263
    } else if (pTCol->colId < pSupInfo->colId[j]) {
264 265 266
      // do nothing
      i += 1;
    } else {
H
Haojun Liao 已提交
267
      return TSDB_CODE_INVALID_PARA;
268 269
    }
  }
H
Haojun Liao 已提交
270 271

  return TSDB_CODE_SUCCESS;
272 273
}

274
static int32_t initBlockScanInfoBuf(SBlockInfoBuf* pBuf, int32_t numOfTables) {
H
Hongze Cheng 已提交
275
  int32_t num = numOfTables / pBuf->numPerBucket;
276 277 278 279 280
  int32_t remainder = numOfTables % pBuf->numPerBucket;
  if (pBuf->pData == NULL) {
    pBuf->pData = taosArrayInit(num + 1, POINTER_BYTES);
  }

H
Hongze Cheng 已提交
281
  for (int32_t i = 0; i < num; ++i) {
282 283 284 285
    char* p = taosMemoryCalloc(pBuf->numPerBucket, sizeof(STableBlockScanInfo));
    if (p == NULL) {
      return TSDB_CODE_OUT_OF_MEMORY;
    }
286

287 288 289 290 291 292 293
    taosArrayPush(pBuf->pData, &p);
  }

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

H
Haojun Liao 已提交
298 299
  return TSDB_CODE_SUCCESS;
}
H
Hongze Cheng 已提交
300

301 302
static void clearBlockScanInfoBuf(SBlockInfoBuf* pBuf) {
  size_t num = taosArrayGetSize(pBuf->pData);
H
Hongze Cheng 已提交
303
  for (int32_t i = 0; i < num; ++i) {
304 305 306 307 308 309 310 311 312
    char** p = taosArrayGet(pBuf->pData, i);
    taosMemoryFree(*p);
  }

  taosArrayDestroy(pBuf->pData);
}

static void* getPosInBlockInfoBuf(SBlockInfoBuf* pBuf, int32_t index) {
  int32_t bucketIndex = index / pBuf->numPerBucket;
H
Hongze Cheng 已提交
313
  char**  pBucket = taosArrayGet(pBuf->pData, bucketIndex);
314 315 316 317
  return (*pBucket) + (index % pBuf->numPerBucket) * sizeof(STableBlockScanInfo);
}

// NOTE: speedup the whole processing by preparing the buffer for STableBlockScanInfo in batch model
H
Hongze Cheng 已提交
318 319
static SHashObj* createDataBlockScanInfo(STsdbReader* pTsdbReader, SBlockInfoBuf* pBuf, const STableKeyInfo* idList,
                                         int32_t numOfTables) {
H
Haojun Liao 已提交
320
  // allocate buffer in order to load data blocks from file
321
  // todo use simple hash instead, optimize the memory consumption
322 323 324
  SHashObj* pTableMap =
      taosHashInit(numOfTables, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT), false, HASH_NO_LOCK);
  if (pTableMap == NULL) {
H
Haojun Liao 已提交
325 326 327
    return NULL;
  }

H
Haojun Liao 已提交
328
  int64_t st = taosGetTimestampUs();
H
Haojun Liao 已提交
329
  initBlockScanInfoBuf(pBuf, numOfTables);
H
Haojun Liao 已提交
330

331
  for (int32_t j = 0; j < numOfTables; ++j) {
H
Haojun Liao 已提交
332
    STableBlockScanInfo* pScanInfo = getPosInBlockInfoBuf(pBuf, j);
333
    pScanInfo->uid = idList[j].uid;
334
    if (ASCENDING_TRAVERSE(pTsdbReader->order)) {
H
Haojun Liao 已提交
335
      int64_t skey = pTsdbReader->window.skey;
336
      pScanInfo->lastKey = (skey > INT64_MIN) ? (skey - 1) : skey;
wmmhello's avatar
wmmhello 已提交
337
    } else {
H
Haojun Liao 已提交
338
      int64_t ekey = pTsdbReader->window.ekey;
339
      pScanInfo->lastKey = (ekey < INT64_MAX) ? (ekey + 1) : ekey;
H
Haojun Liao 已提交
340
    }
wmmhello's avatar
wmmhello 已提交
341

342
    taosHashPut(pTableMap, &pScanInfo->uid, sizeof(uint64_t), &pScanInfo, POINTER_BYTES);
H
Hongze Cheng 已提交
343 344
    tsdbTrace("%p check table uid:%" PRId64 " from lastKey:%" PRId64 " %s", pTsdbReader, pScanInfo->uid,
              pScanInfo->lastKey, pTsdbReader->idStr);
H
Haojun Liao 已提交
345 346
  }

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

352
  return pTableMap;
H
Hongze Cheng 已提交
353
}
H
Hongze Cheng 已提交
354

355 356
static void resetAllDataBlockScanInfo(SHashObj* pTableMap, int64_t ts) {
  STableBlockScanInfo** p = NULL;
dengyihao's avatar
dengyihao 已提交
357
  while ((p = taosHashIterate(pTableMap, p)) != NULL) {
H
Hongze Cheng 已提交
358
    STableBlockScanInfo* pInfo = *(STableBlockScanInfo**)p;
359 360

    pInfo->iterInit = false;
H
Haojun Liao 已提交
361
    pInfo->iter.hasVal = false;
362
    pInfo->iiter.hasVal = false;
H
Haojun Liao 已提交
363

364 365
    if (pInfo->iter.iter != NULL) {
      pInfo->iter.iter = tsdbTbDataIterDestroy(pInfo->iter.iter);
366 367
    }

H
Haojun Liao 已提交
368 369
    if (pInfo->iiter.iter != NULL) {
      pInfo->iiter.iter = tsdbTbDataIterDestroy(pInfo->iiter.iter);
370 371
    }

372 373
    pInfo->delSkyline = taosArrayDestroy(pInfo->delSkyline);
    pInfo->lastKey = ts;
374 375 376
  }
}

377 378
static void clearBlockScanInfo(STableBlockScanInfo* p) {
  p->iterInit = false;
H
Haojun Liao 已提交
379 380

  p->iter.hasVal = false;
381
  p->iiter.hasVal = false;
382

383 384 385
  if (p->iter.iter != NULL) {
    p->iter.iter = tsdbTbDataIterDestroy(p->iter.iter);
  }
386

387 388 389
  if (p->iiter.iter != NULL) {
    p->iiter.iter = tsdbTbDataIterDestroy(p->iiter.iter);
  }
390

391 392 393 394
  p->delSkyline = taosArrayDestroy(p->delSkyline);
  p->pBlockList = taosArrayDestroy(p->pBlockList);
  tMapDataClear(&p->mapData);
}
395

H
Haojun Liao 已提交
396
static void destroyAllBlockScanInfo(SHashObj* pTableMap) {
397
  void* p = NULL;
398
  while ((p = taosHashIterate(pTableMap, p)) != NULL) {
399
    clearBlockScanInfo(*(STableBlockScanInfo**)p);
400 401 402 403 404
  }

  taosHashCleanup(pTableMap);
}

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

407 408 409
// 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 已提交
410
  STsdbKeepCfg* pCfg = &pTsdb->keepCfg;
H
Hongze Cheng 已提交
411

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

dengyihao's avatar
dengyihao 已提交
415
  STimeWindow win = *pWindow;
416 417 418 419 420 421
  if (win.skey < earilyTs) {
    win.skey = earilyTs;
  }

  return win;
}
H
Hongze Cheng 已提交
422

H
Haojun Liao 已提交
423
static void limitOutputBufferSize(const SQueryTableDataCond* pCond, int32_t* capacity) {
H
Haojun Liao 已提交
424 425 426 427 428 429
  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 已提交
430 431 432
  const int32_t TWOMB = 2 * 1024 * 1024;
  if ((*capacity) * rowLen > TWOMB) {
    (*capacity) = TWOMB / rowLen;
H
Haojun Liao 已提交
433 434 435 436
  }
}

// init file iterator
437
static int32_t initFilesetIterator(SFilesetIter* pIter, SArray* aDFileSet, STsdbReader* pReader) {
H
Hongze Cheng 已提交
438
  size_t numOfFileset = taosArrayGetSize(aDFileSet);
439

440 441
  pIter->index = ASCENDING_TRAVERSE(pReader->order) ? -1 : numOfFileset;
  pIter->order = pReader->order;
H
Hongze Cheng 已提交
442
  pIter->pFileList = aDFileSet;
443
  pIter->numOfFiles = numOfFileset;
H
Haojun Liao 已提交
444

445 446 447 448
  if (pIter->pLastBlockReader == NULL) {
    pIter->pLastBlockReader = taosMemoryCalloc(1, sizeof(struct SLastBlockReader));
    if (pIter->pLastBlockReader == NULL) {
      int32_t code = TSDB_CODE_OUT_OF_MEMORY;
449
      tsdbError("failed to prepare the last block iterator, since:%s %s", tstrerror(code), pReader->idStr);
450 451
      return code;
    }
452 453
  }

454 455 456 457 458 459 460 461
  SLastBlockReader* pLReader = pIter->pLastBlockReader;
  pLReader->order = pReader->order;
  pLReader->window = pReader->window;
  pLReader->verRange = pReader->verRange;

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

462
  if (pLReader->pInfo == NULL) {
463
    // here we ignore the first column, which is always be the primary timestamp column
464
    pLReader->pInfo =
H
Haojun Liao 已提交
465
        tCreateLastBlockLoadInfo(pReader->pSchema, &pReader->suppInfo.colId[1], pReader->suppInfo.numOfCols - 1);
H
Haojun Liao 已提交
466 467 468 469
    if (pLReader->pInfo == NULL) {
      tsdbDebug("init fileset iterator failed, code:%s %s", tstrerror(terrno), pReader->idStr);
      return terrno;
    }
470 471
  }

472
  tsdbDebug("init fileset iterator, total files:%d %s", pIter->numOfFiles, pReader->idStr);
H
Haojun Liao 已提交
473 474 475
  return TSDB_CODE_SUCCESS;
}

476
static bool filesetIteratorNext(SFilesetIter* pIter, STsdbReader* pReader) {
477 478
  bool    asc = ASCENDING_TRAVERSE(pIter->order);
  int32_t step = asc ? 1 : -1;
479 480 481
  pIter->index += step;

  if ((asc && pIter->index >= pIter->numOfFiles) || ((!asc) && pIter->index < 0)) {
H
Haojun Liao 已提交
482 483 484
    return false;
  }

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

488 489
  pIter->pLastBlockReader->uid = 0;
  tMergeTreeClose(&pIter->pLastBlockReader->mergeTree);
490
  resetLastBlockLoadInfo(pIter->pLastBlockReader->pInfo);
491

H
Haojun Liao 已提交
492 493
  // check file the time range of coverage
  STimeWindow win = {0};
H
Hongze Cheng 已提交
494

495
  while (1) {
H
Haojun Liao 已提交
496 497 498
    if (pReader->pFileReader != NULL) {
      tsdbDataFReaderClose(&pReader->pFileReader);
    }
499

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

502 503 504 505
    int32_t code = tsdbDataFReaderOpen(&pReader->pFileReader, pReader->pTsdb, pReader->status.pCurrentFileset);
    if (code != TSDB_CODE_SUCCESS) {
      goto _err;
    }
H
Haojun Liao 已提交
506

507 508
    pReader->cost.headFileLoad += 1;

509 510 511 512 513 514 515 516 517 518 519 520
    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;
521 522 523
      if ((asc && pIter->index >= pIter->numOfFiles) || ((!asc) && pIter->index < 0)) {
        return false;
      }
524 525
      continue;
    }
C
Cary Xu 已提交
526

527
    tsdbDebug("%p file found fid:%d for qrange:%" PRId64 "-%" PRId64 ", %s", pReader, fid, pReader->window.skey,
528
              pReader->window.ekey, pReader->idStr);
529 530
    return true;
  }
531

532
_err:
H
Haojun Liao 已提交
533 534 535
  return false;
}

536
static void resetDataBlockIterator(SDataBlockIter* pIter, int32_t order) {
537 538
  pIter->order = order;
  pIter->index = -1;
539
  pIter->numOfBlocks = 0;
540 541 542 543 544 545 546
  if (pIter->blockList == NULL) {
    pIter->blockList = taosArrayInit(4, sizeof(SFileDataBlockInfo));
  } else {
    taosArrayClear(pIter->blockList);
  }
}

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

H
Haojun Liao 已提交
549
static void initReaderStatus(SReaderStatus* pStatus) {
dengyihao's avatar
dengyihao 已提交
550 551
  pStatus->pTableIter = NULL;
  pStatus->loadFromFile = true;
H
Haojun Liao 已提交
552 553
}

554 555 556 557 558 559 560 561
static SSDataBlock* createResBlock(SQueryTableDataCond* pCond, int32_t capacity) {
  SSDataBlock* pResBlock = createDataBlock();
  if (pResBlock == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

  for (int32_t i = 0; i < pCond->numOfCols; ++i) {
H
Haojun Liao 已提交
562
    SColumnInfoData colInfo = {0};
563 564 565 566 567 568 569 570 571 572 573 574 575
    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;
}

576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630
static int32_t tsdbInitReaderLock(STsdbReader* pReader) {
  int32_t code = -1;
  qTrace("tsdb/read: %p, pre-init read mutex: %p, code: %d", pReader, &pReader->readerMutex, code);

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

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

  return code;
}

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

  code = taosThreadMutexDestroy(&pReader->readerMutex);

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

  return code;
}

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

  code = taosThreadMutexLock(&pReader->readerMutex);

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

  return code;
}

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

  code = taosThreadMutexTryLock(&pReader->readerMutex);

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

  return code;
}

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

  code = taosThreadMutexUnlock(&pReader->readerMutex);

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

  return code;
}

631 632 633 634 635 636
void tsdbReleaseDataBlock(STsdbReader* pReader) {
  SReaderStatus* pStatus = &pReader->status;
  if (!pStatus->composedDataBlock) {
    tsdbReleaseReader(pReader);
  }
}
637

638
static int32_t tsdbReaderCreate(SVnode* pVnode, SQueryTableDataCond* pCond, STsdbReader** ppReader, int32_t capacity,
H
Haojun Liao 已提交
639
                                SSDataBlock* pResBlock, const char* idstr) {
H
Haojun Liao 已提交
640
  int32_t      code = 0;
641
  int8_t       level = 0;
H
Haojun Liao 已提交
642
  STsdbReader* pReader = (STsdbReader*)taosMemoryCalloc(1, sizeof(*pReader));
H
Hongze Cheng 已提交
643 644
  if (pReader == NULL) {
    code = TSDB_CODE_OUT_OF_MEMORY;
H
Haojun Liao 已提交
645
    goto _end;
H
Hongze Cheng 已提交
646 647
  }

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

H
Haojun Liao 已提交
652
  initReaderStatus(&pReader->status);
653

L
Liu Jicong 已提交
654
  pReader->pTsdb = getTsdbByRetentions(pVnode, pCond->twindows.skey, pVnode->config.tsdbCfg.retentions, idstr, &level);
dengyihao's avatar
dengyihao 已提交
655 656
  pReader->suid = pCond->suid;
  pReader->order = pCond->order;
657
  pReader->capacity = capacity;
H
Haojun Liao 已提交
658
  pReader->pResBlock = pResBlock;
dengyihao's avatar
dengyihao 已提交
659 660
  pReader->idStr = (idstr != NULL) ? strdup(idstr) : NULL;
  pReader->verRange = getQueryVerRange(pVnode, pCond, level);
661
  pReader->type = pCond->type;
662
  pReader->window = updateQueryTimeWindow(pReader->pTsdb, &pCond->twindows);
H
Hongze Cheng 已提交
663
  pReader->blockInfoBuf.numPerBucket = 1000;  // 1000 tables per bucket
H
Hongze Cheng 已提交
664

H
Haojun Liao 已提交
665 666 667 668 669 670 671 672
  if (pReader->pResBlock == NULL) {
    pReader->freeBlock = true;
    pReader->pResBlock = createResBlock(pCond, pReader->capacity);
    if (pReader->pResBlock == NULL) {
      code = terrno;
      goto _end;
    }
  }
673

H
Haojun Liao 已提交
674 675 676 677 678
  if (pCond->numOfCols <= 0) {
    tsdbError("vgId:%d, invalid column number %d in query cond, %s", TD_VID(pVnode), pCond->numOfCols, idstr);
    code = TSDB_CODE_INVALID_PARA;
    goto _end;
  }
H
Hongze Cheng 已提交
679

H
Haojun Liao 已提交
680
  // todo refactor.
681
  limitOutputBufferSize(pCond, &pReader->capacity);
682

683 684
  // allocate buffer in order to load data blocks from file
  SBlockLoadSuppInfo* pSup = &pReader->suppInfo;
685
  pSup->pColAgg = taosArrayInit(pCond->numOfCols, sizeof(SColumnDataAgg));
H
Haojun Liao 已提交
686
  if (pSup->pColAgg == NULL) {
687 688 689
    code = TSDB_CODE_OUT_OF_MEMORY;
    goto _end;
  }
H
Haojun Liao 已提交
690

691 692
  pSup->tsColAgg.colId = PRIMARYKEY_TIMESTAMP_COL_ID;

H
Hongze Cheng 已提交
693
  code = tBlockDataCreate(&pReader->status.fileBlockData);
H
Haojun Liao 已提交
694 695 696 697 698
  if (code != TSDB_CODE_SUCCESS) {
    terrno = code;
    goto _end;
  }

H
Haojun Liao 已提交
699
  setColumnIdSlotList(&pReader->suppInfo, pCond->colList, pCond->pSlotList, pCond->numOfCols);
700

701
  tsdbInitReaderLock(pReader);
702

H
Hongze Cheng 已提交
703 704
  *ppReader = pReader;
  return code;
H
Hongze Cheng 已提交
705

H
Haojun Liao 已提交
706 707
_end:
  tsdbReaderClose(pReader);
H
Hongze Cheng 已提交
708 709 710
  *ppReader = NULL;
  return code;
}
H
Hongze Cheng 已提交
711

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

715
  int64_t st = taosGetTimestampUs();
H
Hongze Cheng 已提交
716
  int32_t code = tsdbReadBlockIdx(pFileReader, aBlockIdx);
H
Haojun Liao 已提交
717
  if (code != TSDB_CODE_SUCCESS) {
718
    goto _end;
H
Haojun Liao 已提交
719
  }
H
Hongze Cheng 已提交
720

721 722
  size_t num = taosArrayGetSize(aBlockIdx);
  if (num == 0) {
H
Haojun Liao 已提交
723
    taosArrayDestroy(aBlockIdx);
H
Haojun Liao 已提交
724 725
    return TSDB_CODE_SUCCESS;
  }
H
Hongze Cheng 已提交
726

727 728 729 730
  int64_t et1 = taosGetTimestampUs();

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

733
    // uid check
H
Hongze Cheng 已提交
734
    if (pBlockIdx->suid != pReader->suid) {
H
Haojun Liao 已提交
735 736 737 738
      continue;
    }

    // this block belongs to a table that is not queried.
H
Hongze Cheng 已提交
739
    void* p = taosHashGet(pReader->status.pTableMap, &pBlockIdx->uid, sizeof(uint64_t));
H
Haojun Liao 已提交
740 741 742 743
    if (p == NULL) {
      continue;
    }

H
Haojun Liao 已提交
744
    STableBlockScanInfo* pScanInfo = *(STableBlockScanInfo**)p;
H
Haojun Liao 已提交
745
    if (pScanInfo->pBlockList == NULL) {
746
      pScanInfo->pBlockList = taosArrayInit(4, sizeof(SBlockIndex));
H
Haojun Liao 已提交
747 748
    }

H
Hongze Cheng 已提交
749
    taosArrayPush(pIndexList, pBlockIdx);
H
Haojun Liao 已提交
750
  }
H
Hongze Cheng 已提交
751

752
  int64_t et2 = taosGetTimestampUs();
753
  tsdbDebug("load block index for %d tables completed, elapsed time:%.2f ms, set blockIdx:%.2f ms, size:%.2f Kb %s",
754
            (int32_t)num, (et1 - st) / 1000.0, (et2 - et1) / 1000.0, num * sizeof(SBlockIdx) / 1024.0, pReader->idStr);
755 756 757

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

758
_end:
H
Hongze Cheng 已提交
759
  taosArrayDestroy(aBlockIdx);
H
Haojun Liao 已提交
760 761
  return code;
}
H
Hongze Cheng 已提交
762

763
static void cleanupTableScanInfo(SHashObj* pTableMap) {
764
  STableBlockScanInfo** px = NULL;
dengyihao's avatar
dengyihao 已提交
765
  while (1) {
766
    px = taosHashIterate(pTableMap, px);
767 768 769 770
    if (px == NULL) {
      break;
    }

771
    // reset the index in last block when handing a new file
772 773
    tMapDataClear(&(*px)->mapData);
    taosArrayClear((*px)->pBlockList);
774
  }
775 776
}

777
static int32_t doLoadFileBlock(STsdbReader* pReader, SArray* pIndexList, SBlockNumber* pBlockNum) {
778 779 780 781 782 783
  int32_t numOfQTable = 0;
  size_t  sizeInDisk = 0;
  size_t  numOfTables = taosArrayGetSize(pIndexList);

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

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

H
Haojun Liao 已提交
788 789
    STableBlockScanInfo* pScanInfo =
        *(STableBlockScanInfo**)taosHashGet(pReader->status.pTableMap, &pBlockIdx->uid, sizeof(int64_t));
H
Hongze Cheng 已提交
790

791
    tMapDataReset(&pScanInfo->mapData);
H
Hongze Cheng 已提交
792
    tsdbReadDataBlk(pReader->pFileReader, pBlockIdx, &pScanInfo->mapData);
H
Haojun Liao 已提交
793
    taosArrayEnsureCap(pScanInfo->pBlockList, pScanInfo->mapData.nItem);
794

795
    sizeInDisk += pScanInfo->mapData.nData;
796 797 798 799 800 801 802 803 804 805 806 807 808

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

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

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

813
      // 1. time range check
814 815
      // if (block.minKey.ts > pReader->window.ekey || block.maxKey.ts < pReader->window.skey) {
      if (block.minKey.ts > w.ekey || block.maxKey.ts < w.skey) {
H
Haojun Liao 已提交
816 817
        continue;
      }
H
Hongze Cheng 已提交
818

819
      // 2. version range check
H
Hongze Cheng 已提交
820
      if (block.minVer > pReader->verRange.maxVer || block.maxVer < pReader->verRange.minVer) {
821 822
        continue;
      }
823

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

H
Haojun Liao 已提交
827 828
      void* p1 = taosArrayPush(pScanInfo->pBlockList, &bIndex);
      if (p1 == NULL) {
829
        tMapDataClear(&pScanInfo->mapData);
H
Haojun Liao 已提交
830 831
        return TSDB_CODE_OUT_OF_MEMORY;
      }
832

833
      pBlockNum->numOfBlocks += 1;
H
Haojun Liao 已提交
834
    }
H
Hongze Cheng 已提交
835

H
Haojun Liao 已提交
836
    if (pScanInfo->pBlockList != NULL && taosArrayGetSize(pScanInfo->pBlockList) > 0) {
837 838 839 840
      numOfQTable += 1;
    }
  }

H
Hongze Cheng 已提交
841
  pBlockNum->numOfLastFiles = pReader->pFileReader->pSet->nSttF;
842
  int32_t total = pBlockNum->numOfLastFiles + pBlockNum->numOfBlocks;
843

844
  double el = (taosGetTimestampUs() - st) / 1000.0;
H
Hongze Cheng 已提交
845
  tsdbDebug(
846
      "load block of %ld tables completed, blocks:%d in %d tables, last-files:%d, block-info-size:%.2f Kb, elapsed "
847
      "time:%.2f ms %s",
848
      numOfTables, pBlockNum->numOfBlocks, numOfQTable, pBlockNum->numOfLastFiles, sizeInDisk / 1000.0, el,
H
Hongze Cheng 已提交
849
      pReader->idStr);
850

851
  pReader->cost.numOfBlocks += total;
852
  pReader->cost.headFileLoadTime += el;
853

H
Haojun Liao 已提交
854 855
  return TSDB_CODE_SUCCESS;
}
H
Hongze Cheng 已提交
856

857
static void setBlockAllDumped(SFileBlockDumpInfo* pDumpInfo, int64_t maxKey, int32_t order) {
858
  int32_t step = ASCENDING_TRAVERSE(order) ? 1 : -1;
859
  pDumpInfo->allDumped = true;
860
  pDumpInfo->lastKey = maxKey + step;
H
Haojun Liao 已提交
861 862
}

863 864
static void doCopyColVal(SColumnInfoData* pColInfoData, int32_t rowIndex, int32_t colIndex, SColVal* pColVal,
                         SBlockLoadSuppInfo* pSup) {
H
Haojun Liao 已提交
865
  if (IS_VAR_DATA_TYPE(pColVal->type)) {
H
Hongze Cheng 已提交
866
    if (!COL_VAL_IS_VALUE(pColVal)) {
H
Haojun Liao 已提交
867 868 869
      colDataAppendNULL(pColInfoData, rowIndex);
    } else {
      varDataSetLen(pSup->buildBuf[colIndex], pColVal->value.nData);
H
Haojun Liao 已提交
870
      ASSERT(pColVal->value.nData <= pColInfoData->info.bytes);
871 872 873 874
      if (pColVal->value.nData > 0) {  // pData may be null, if nData is 0
        memcpy(varDataVal(pSup->buildBuf[colIndex]), pColVal->value.pData, pColVal->value.nData);
      }

H
Haojun Liao 已提交
875 876 877
      colDataAppend(pColInfoData, rowIndex, pSup->buildBuf[colIndex], false);
    }
  } else {
H
Hongze Cheng 已提交
878
    colDataAppend(pColInfoData, rowIndex, (const char*)&pColVal->value, !COL_VAL_IS_VALUE(pColVal));
H
Haojun Liao 已提交
879
  }
H
Haojun Liao 已提交
880 881
}

882
static SFileDataBlockInfo* getCurrentBlockInfo(SDataBlockIter* pBlockIter) {
H
Haojun Liao 已提交
883 884 885
  size_t num = taosArrayGetSize(pBlockIter->blockList);
  if (num == 0) {
    ASSERT(pBlockIter->numOfBlocks == num);
886 887
    return NULL;
  }
888 889 890

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

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

C
Cary Xu 已提交
895 896 897 898 899 900
static int doBinarySearchKey(TSKEY* keyList, int num, int pos, TSKEY key, int order) {
  // start end position
  int s, e;
  s = pos;

  // check
H
Hongze Cheng 已提交
901
  assert(pos >= 0 && pos < num);
C
Cary Xu 已提交
902 903 904 905
  assert(num > 0);

  if (order == TSDB_ORDER_ASC) {
    // find the first position which is smaller than the key
H
Hongze Cheng 已提交
906 907
    e = num - 1;
    if (key < keyList[pos]) return -1;
C
Cary Xu 已提交
908 909
    while (1) {
      // check can return
H
Hongze Cheng 已提交
910 911 912
      if (key >= keyList[e]) return e;
      if (key <= keyList[s]) return s;
      if (e - s <= 1) return s;
C
Cary Xu 已提交
913 914

      // change start or end position
H
Hongze Cheng 已提交
915
      int mid = s + (e - s + 1) / 2;
C
Cary Xu 已提交
916 917
      if (keyList[mid] > key)
        e = mid;
H
Hongze Cheng 已提交
918
      else if (keyList[mid] < key)
C
Cary Xu 已提交
919 920 921 922
        s = mid;
      else
        return mid;
    }
H
Hongze Cheng 已提交
923
  } else {  // DESC
C
Cary Xu 已提交
924
    // find the first position which is bigger than the key
H
Hongze Cheng 已提交
925 926
    e = 0;
    if (key > keyList[pos]) return -1;
C
Cary Xu 已提交
927 928
    while (1) {
      // check can return
H
Hongze Cheng 已提交
929 930 931
      if (key <= keyList[e]) return e;
      if (key >= keyList[s]) return s;
      if (s - e <= 1) return s;
C
Cary Xu 已提交
932 933

      // change start or end position
H
Hongze Cheng 已提交
934
      int mid = s - (s - e + 1) / 2;
C
Cary Xu 已提交
935 936
      if (keyList[mid] < key)
        e = mid;
H
Hongze Cheng 已提交
937
      else if (keyList[mid] > key)
C
Cary Xu 已提交
938 939 940 941 942 943 944
        s = mid;
      else
        return mid;
    }
  }
}

H
Haojun Liao 已提交
945
static int32_t getEndPosInDataBlock(STsdbReader* pReader, SBlockData* pBlockData, SDataBlk* pBlock, int32_t pos) {
C
Cary Xu 已提交
946 947
  // NOTE: reverse the order to find the end position in data block
  int32_t endPos = -1;
H
Hongze Cheng 已提交
948
  bool    asc = ASCENDING_TRAVERSE(pReader->order);
C
Cary Xu 已提交
949 950 951 952 953 954

  if (asc && pReader->window.ekey >= pBlock->maxKey.ts) {
    endPos = pBlock->nRow - 1;
  } else if (!asc && pReader->window.skey <= pBlock->minKey.ts) {
    endPos = 0;
  } else {
C
Cary Xu 已提交
955 956
    int64_t key = asc ? pReader->window.ekey : pReader->window.skey;
    endPos = doBinarySearchKey(pBlockData->aTSKEY, pBlock->nRow, pos, key, pReader->order);
C
Cary Xu 已提交
957 958 959 960 961
  }

  return endPos;
}

H
Haojun Liao 已提交
962
static void copyPrimaryTsCol(const SBlockData* pBlockData, SFileBlockDumpInfo* pDumpInfo, SColumnInfoData* pColData,
H
Haojun Liao 已提交
963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981
                             int32_t dumpedRows, bool asc) {
  if (asc) {
    memcpy(pColData->pData, &pBlockData->aTSKEY[pDumpInfo->rowIndex], dumpedRows * sizeof(int64_t));
  } else {
    int32_t startIndex = pDumpInfo->rowIndex - dumpedRows + 1;
    memcpy(pColData->pData, &pBlockData->aTSKEY[startIndex], dumpedRows * sizeof(int64_t));

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

H
Haojun Liao 已提交
982 983
// a faster version of copy procedure.
static void copyNumericCols(const SColData* pData, SFileBlockDumpInfo* pDumpInfo, SColumnInfoData* pColData,
H
Hongze Cheng 已提交
984
                            int32_t dumpedRows, bool asc) {
H
Haojun Liao 已提交
985 986 987 988 989 990 991 992
  uint8_t* p = NULL;
  if (asc) {
    p = pData->pData + tDataTypes[pData->type].bytes * pDumpInfo->rowIndex;
  } else {
    int32_t startIndex = pDumpInfo->rowIndex - dumpedRows + 1;
    p = pData->pData + tDataTypes[pData->type].bytes * startIndex;
  }

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

H
Haojun Liao 已提交
995
  // make sure it is aligned to 8bit, the allocated memory address is aligned to 256bit
996
  //  ASSERT((((uint64_t)pColData->pData) & (0x8 - 1)) == 0);
H
Haojun Liao 已提交
997 998 999 1000 1001 1002

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

  // 2. reverse the array list in case of descending order scan data block
  if (!asc) {
H
Hongze Cheng 已提交
1003
    switch (pColData->info.type) {
H
Haojun Liao 已提交
1004 1005 1006
      case TSDB_DATA_TYPE_TIMESTAMP:
      case TSDB_DATA_TYPE_DOUBLE:
      case TSDB_DATA_TYPE_BIGINT:
H
Hongze Cheng 已提交
1007
      case TSDB_DATA_TYPE_UBIGINT: {
H
Haojun Liao 已提交
1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
        int32_t  mid = dumpedRows >> 1u;
        int64_t* pts = (int64_t*)pColData->pData;
        for (int32_t j = 0; j < mid; ++j) {
          int64_t t = pts[j];
          pts[j] = pts[dumpedRows - j - 1];
          pts[dumpedRows - j - 1] = t;
        }
        break;
      }

      case TSDB_DATA_TYPE_BOOL:
      case TSDB_DATA_TYPE_TINYINT:
      case TSDB_DATA_TYPE_UTINYINT: {
H
Hongze Cheng 已提交
1021
        int32_t mid = dumpedRows >> 1u;
H
Haojun Liao 已提交
1022 1023
        int8_t* pts = (int8_t*)pColData->pData;
        for (int32_t j = 0; j < mid; ++j) {
H
Haojun Liao 已提交
1024
          int8_t t = pts[j];
H
Haojun Liao 已提交
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048
          pts[j] = pts[dumpedRows - j - 1];
          pts[dumpedRows - j - 1] = t;
        }
        break;
      }

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

      case TSDB_DATA_TYPE_FLOAT:
      case TSDB_DATA_TYPE_INT:
      case TSDB_DATA_TYPE_UINT: {
        int32_t  mid = dumpedRows >> 1u;
        int32_t* pts = (int32_t*)pColData->pData;
        for (int32_t j = 0; j < mid; ++j) {
H
Haojun Liao 已提交
1049
          int32_t t = pts[j];
H
Haojun Liao 已提交
1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
          pts[j] = pts[dumpedRows - j - 1];
          pts[dumpedRows - j - 1] = t;
        }
        break;
      }
    }
  }

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

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

1072
static int32_t copyBlockDataToSDataBlock(STsdbReader* pReader, STableBlockScanInfo* pBlockScanInfo) {
H
Haojun Liao 已提交
1073 1074 1075 1076
  SReaderStatus*      pStatus = &pReader->status;
  SDataBlockIter*     pBlockIter = &pStatus->blockIter;
  SBlockLoadSuppInfo* pSupInfo = &pReader->suppInfo;
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;
H
Hongze Cheng 已提交
1077

1078
  SBlockData*         pBlockData = &pStatus->fileBlockData;
C
Cary Xu 已提交
1079
  SFileDataBlockInfo* pBlockInfo = getCurrentBlockInfo(pBlockIter);
H
Hongze Cheng 已提交
1080
  SDataBlk*           pBlock = getCurrentBlock(pBlockIter);
H
Haojun Liao 已提交
1081
  SSDataBlock*        pResBlock = pReader->pResBlock;
H
Haojun Liao 已提交
1082
  int32_t             numOfOutputCols = pSupInfo->numOfCols;
H
Haojun Liao 已提交
1083

H
Haojun Liao 已提交
1084
  SColVal cv = {0};
1085
  int64_t st = taosGetTimestampUs();
1086 1087
  bool    asc = ASCENDING_TRAVERSE(pReader->order);
  int32_t step = asc ? 1 : -1;
1088

1089 1090
  if ((pDumpInfo->rowIndex == 0 && asc) || (pDumpInfo->rowIndex == pBlock->nRow - 1 && (!asc))) {
    if (asc && pReader->window.skey <= pBlock->minKey.ts) {
1091 1092 1093
      // pDumpInfo->rowIndex = 0;
    } else if (!asc && pReader->window.ekey >= pBlock->maxKey.ts) {
      // pDumpInfo->rowIndex = pBlock->nRow - 1;
H
Haojun Liao 已提交
1094
    } else {  // find the appropriate the start position in current block, and set it to be the current rowIndex
1095
      int32_t pos = asc ? pBlock->nRow - 1 : 0;
C
Cary Xu 已提交
1096 1097 1098
      int32_t order = asc ? TSDB_ORDER_DESC : TSDB_ORDER_ASC;
      int64_t key = asc ? pReader->window.skey : pReader->window.ekey;
      pDumpInfo->rowIndex = doBinarySearchKey(pBlockData->aTSKEY, pBlock->nRow, pos, key, order);
H
Haojun Liao 已提交
1099 1100 1101 1102 1103 1104 1105 1106 1107

      if (pDumpInfo->rowIndex < 0) {
        tsdbError(
            "%p failed to locate the start position in current block, global index:%d, table index:%d, brange:%" PRId64
            "-%" PRId64 ", minVer:%" PRId64 ", maxVer:%" PRId64 " %s",
            pReader, pBlockIter->index, pBlockInfo->tbBlockIdx, pBlock->minKey.ts, pBlock->maxKey.ts, pBlock->minVer,
            pBlock->maxVer, pReader->idStr);
        return TSDB_CODE_INVALID_PARA;
      }
1108
    }
C
Cary Xu 已提交
1109 1110 1111 1112 1113 1114 1115 1116 1117 1118
  }

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

  endIndex += step;
H
Haojun Liao 已提交
1119 1120 1121
  int32_t dumpedRows = asc ? (endIndex - pDumpInfo->rowIndex) : (pDumpInfo->rowIndex - endIndex);
  if (dumpedRows > pReader->capacity) {  // output buffer check
    dumpedRows = pReader->capacity;
1122 1123
  }

H
Haojun Liao 已提交
1124
  int32_t i = 0;
C
Cary Xu 已提交
1125 1126
  int32_t rowIndex = 0;

H
Haojun Liao 已提交
1127 1128
  SColumnInfoData* pColData = taosArrayGet(pResBlock->pDataBlock, pSupInfo->slotId[i]);
  if (pSupInfo->colId[i] == PRIMARYKEY_TIMESTAMP_COL_ID) {
H
Haojun Liao 已提交
1129
    copyPrimaryTsCol(pBlockData, pDumpInfo, pColData, dumpedRows, asc);
1130 1131 1132
    i += 1;
  }

1133
  int32_t colIndex = 0;
H
Hongze Cheng 已提交
1134
  int32_t num = pBlockData->nColData;
1135
  while (i < numOfOutputCols && colIndex < num) {
1136 1137
    rowIndex = 0;

H
Hongze Cheng 已提交
1138
    SColData* pData = tBlockDataGetColDataByIdx(pBlockData, colIndex);
H
Haojun Liao 已提交
1139
    if (pData->cid < pSupInfo->colId[i]) {
1140
      colIndex += 1;
H
Haojun Liao 已提交
1141 1142
    } else if (pData->cid == pSupInfo->colId[i]) {
      pColData = taosArrayGet(pResBlock->pDataBlock, pSupInfo->slotId[i]);
H
Haojun Liao 已提交
1143

H
Hongze Cheng 已提交
1144
      if (pData->flag == HAS_NONE || pData->flag == HAS_NULL || pData->flag == (HAS_NULL | HAS_NONE)) {
H
Haojun Liao 已提交
1145
        colDataAppendNNULL(pColData, 0, dumpedRows);
C
Cary Xu 已提交
1146
      } else {
H
Haojun Liao 已提交
1147
        if (IS_MATHABLE_TYPE(pColData->info.type)) {
H
Haojun Liao 已提交
1148 1149
          copyNumericCols(pData, pDumpInfo, pColData, dumpedRows, asc);
        } else {  // varchar/nchar type
H
Haojun Liao 已提交
1150
          for (int32_t j = pDumpInfo->rowIndex; rowIndex < dumpedRows; j += step) {
C
Cary Xu 已提交
1151 1152 1153 1154
            tColDataGetValue(pData, j, &cv);
            doCopyColVal(pColData, rowIndex++, i, &cv, pSupInfo);
          }
        }
H
Haojun Liao 已提交
1155
      }
C
Cary Xu 已提交
1156

1157
      colIndex += 1;
1158
      i += 1;
1159
    } else {  // the specified column does not exist in file block, fill with null data
H
Haojun Liao 已提交
1160
      pColData = taosArrayGet(pResBlock->pDataBlock, pSupInfo->slotId[i]);
H
Haojun Liao 已提交
1161
      colDataAppendNNULL(pColData, 0, dumpedRows);
1162
      i += 1;
H
Haojun Liao 已提交
1163
    }
1164 1165
  }

1166
  // fill the mis-matched columns with null value
1167
  while (i < numOfOutputCols) {
H
Haojun Liao 已提交
1168
    pColData = taosArrayGet(pResBlock->pDataBlock, pSupInfo->slotId[i]);
H
Haojun Liao 已提交
1169
    colDataAppendNNULL(pColData, 0, dumpedRows);
1170
    i += 1;
H
Haojun Liao 已提交
1171
  }
H
Haojun Liao 已提交
1172

1173
  pResBlock->info.dataLoad = 1;
H
Haojun Liao 已提交
1174 1175
  pResBlock->info.rows = dumpedRows;
  pDumpInfo->rowIndex += step * dumpedRows;
1176

1177
  // check if current block are all handled
C
Cary Xu 已提交
1178 1179
  if (pDumpInfo->rowIndex >= 0 && pDumpInfo->rowIndex < pBlock->nRow) {
    int64_t ts = pBlockData->aTSKEY[pDumpInfo->rowIndex];
1180 1181 1182
    if (outOfTimeWindow(ts, &pReader->window)) {  // the remain data has out of query time window, ignore current block
      setBlockAllDumped(pDumpInfo, ts, pReader->order);
    }
C
Cary Xu 已提交
1183
  } else {
1184 1185
    int64_t ts = asc ? pBlock->maxKey.ts : pBlock->minKey.ts;
    setBlockAllDumped(pDumpInfo, ts, pReader->order);
C
Cary Xu 已提交
1186
  }
H
Haojun Liao 已提交
1187

H
Haojun Liao 已提交
1188 1189
  pBlockScanInfo->lastKey = pDumpInfo->lastKey;

1190
  double elapsedTime = (taosGetTimestampUs() - st) / 1000.0;
H
Haojun Liao 已提交
1191
  pReader->cost.blockLoadTime += elapsedTime;
H
Haojun Liao 已提交
1192

1193
  int32_t unDumpedRows = asc ? pBlock->nRow - pDumpInfo->rowIndex : pDumpInfo->rowIndex + 1;
H
Haojun Liao 已提交
1194
  tsdbDebug("%p copy file block to sdatablock, global index:%d, table index:%d, brange:%" PRId64 "-%" PRId64
1195
            ", rows:%d, remain:%d, minVer:%" PRId64 ", maxVer:%" PRId64 ", elapsed time:%.2f ms, %s",
H
Haojun Liao 已提交
1196
            pReader, pBlockIter->index, pBlockInfo->tbBlockIdx, pBlock->minKey.ts, pBlock->maxKey.ts, dumpedRows,
H
Hongze Cheng 已提交
1197
            unDumpedRows, pBlock->minVer, pBlock->maxVer, elapsedTime, pReader->idStr);
1198 1199 1200 1201

  return TSDB_CODE_SUCCESS;
}

1202 1203
static int32_t doLoadFileBlockData(STsdbReader* pReader, SDataBlockIter* pBlockIter, SBlockData* pBlockData,
                                   uint64_t uid) {
1204 1205
  int64_t st = taosGetTimestampUs();

1206 1207
  tBlockDataReset(pBlockData);
  TABLEID tid = {.suid = pReader->suid, .uid = uid};
1208
  int32_t code =
H
Haojun Liao 已提交
1209
      tBlockDataInit(pBlockData, &tid, pReader->pSchema, &pReader->suppInfo.colId[1], pReader->suppInfo.numOfCols - 1);
1210 1211 1212 1213
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

1214
  SFileDataBlockInfo* pBlockInfo = getCurrentBlockInfo(pBlockIter);
1215
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;
1216

H
Hongze Cheng 已提交
1217
  SDataBlk* pBlock = getCurrentBlock(pBlockIter);
1218
  code = tsdbReadDataBlock(pReader->pFileReader, pBlock, pBlockData);
1219 1220 1221
  if (code != TSDB_CODE_SUCCESS) {
    tsdbError("%p error occurs in loading file block, global index:%d, table index:%d, brange:%" PRId64 "-%" PRId64
              ", rows:%d, code:%s %s",
1222
              pReader, pBlockIter->index, pBlockInfo->tbBlockIdx, pBlock->minKey.ts, pBlock->maxKey.ts, pBlock->nRow,
1223 1224 1225
              tstrerror(code), pReader->idStr);
    return code;
  }
1226

1227
  double elapsedTime = (taosGetTimestampUs() - st) / 1000.0;
1228

1229 1230 1231 1232
  tsdbDebug("%p load file block into buffer, global index:%d, index in table block list:%d, brange:%" PRId64 "-%" PRId64
            ", rows:%d, minVer:%" PRId64 ", maxVer:%" PRId64 ", elapsed time:%.2f ms, %s",
            pReader, pBlockIter->index, pBlockInfo->tbBlockIdx, pBlock->minKey.ts, pBlock->maxKey.ts, pBlock->nRow,
            pBlock->minVer, pBlock->maxVer, elapsedTime, pReader->idStr);
1233 1234 1235

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

H
Haojun Liao 已提交
1237
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
1238
}
H
Hongze Cheng 已提交
1239

H
Haojun Liao 已提交
1240 1241 1242
static void cleanupBlockOrderSupporter(SBlockOrderSupporter* pSup) {
  taosMemoryFreeClear(pSup->numOfBlocksPerTable);
  taosMemoryFreeClear(pSup->indexPerTable);
H
Hongze Cheng 已提交
1243

H
Haojun Liao 已提交
1244 1245 1246 1247
  for (int32_t i = 0; i < pSup->numOfTables; ++i) {
    SBlockOrderWrapper* pBlockInfo = pSup->pDataBlockInfo[i];
    taosMemoryFreeClear(pBlockInfo);
  }
H
Hongze Cheng 已提交
1248

H
Haojun Liao 已提交
1249 1250
  taosMemoryFreeClear(pSup->pDataBlockInfo);
}
H
Hongze Cheng 已提交
1251

H
Haojun Liao 已提交
1252 1253
static int32_t initBlockOrderSupporter(SBlockOrderSupporter* pSup, int32_t numOfTables) {
  pSup->numOfBlocksPerTable = taosMemoryCalloc(1, sizeof(int32_t) * numOfTables);
1254 1255
  pSup->indexPerTable = taosMemoryCalloc(1, sizeof(int32_t) * numOfTables);
  pSup->pDataBlockInfo = taosMemoryCalloc(1, POINTER_BYTES * numOfTables);
H
Hongze Cheng 已提交
1256

H
Haojun Liao 已提交
1257 1258 1259 1260
  if (pSup->numOfBlocksPerTable == NULL || pSup->indexPerTable == NULL || pSup->pDataBlockInfo == NULL) {
    cleanupBlockOrderSupporter(pSup);
    return TSDB_CODE_OUT_OF_MEMORY;
  }
H
Hongze Cheng 已提交
1261

H
Haojun Liao 已提交
1262 1263
  return TSDB_CODE_SUCCESS;
}
H
Hongze Cheng 已提交
1264

H
Haojun Liao 已提交
1265
static int32_t fileDataBlockOrderCompar(const void* pLeft, const void* pRight, void* param) {
1266
  int32_t leftIndex = *(int32_t*)pLeft;
H
Haojun Liao 已提交
1267
  int32_t rightIndex = *(int32_t*)pRight;
H
Hongze Cheng 已提交
1268

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

H
Haojun Liao 已提交
1271 1272
  int32_t leftTableBlockIndex = pSupporter->indexPerTable[leftIndex];
  int32_t rightTableBlockIndex = pSupporter->indexPerTable[rightIndex];
H
Hongze Cheng 已提交
1273

H
Haojun Liao 已提交
1274 1275 1276 1277 1278 1279 1280
  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 已提交
1281

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

1285 1286 1287
  return pLeftBlock->offset > pRightBlock->offset ? 1 : -1;
}

H
Haojun Liao 已提交
1288
static int32_t doSetCurrentBlock(SDataBlockIter* pBlockIter, const char* idStr) {
1289 1290
  SFileDataBlockInfo* pBlockInfo = getCurrentBlockInfo(pBlockIter);
  if (pBlockInfo != NULL) {
H
Haojun Liao 已提交
1291
    STableBlockScanInfo** pScanInfo = taosHashGet(pBlockIter->pTableMap, &pBlockInfo->uid, sizeof(pBlockInfo->uid));
H
Haojun Liao 已提交
1292
    if (pScanInfo == NULL) {
1293
      tsdbError("failed to locate the uid:%" PRIu64 " in query table uid list, %s", pBlockInfo->uid, idStr);
H
Haojun Liao 已提交
1294 1295 1296
      return TSDB_CODE_INVALID_PARA;
    }

H
Haojun Liao 已提交
1297 1298
    SBlockIndex* pIndex = taosArrayGet((*pScanInfo)->pBlockList, pBlockInfo->tbBlockIdx);
    tMapDataGetItemByIdx(&(*pScanInfo)->mapData, pIndex->ordinalIndex, &pBlockIter->block, tGetDataBlk);
1299
  }
1300 1301 1302 1303 1304 1305

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

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

1311
  SBlockOrderSupporter sup = {0};
1312
  pBlockIter->numOfBlocks = numOfBlocks;
1313
  taosArrayClear(pBlockIter->blockList);
1314
  pBlockIter->pTableMap = pReader->status.pTableMap;
1315

1316 1317
  // 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 已提交
1318

1319
  int64_t st = taosGetTimestampUs();
1320
  int32_t code = initBlockOrderSupporter(&sup, numOfTables);
1321 1322 1323
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }
H
Haojun Liao 已提交
1324

1325 1326 1327 1328 1329 1330 1331
  int32_t cnt = 0;
  void*   ptr = NULL;
  while (1) {
    ptr = taosHashIterate(pReader->status.pTableMap, ptr);
    if (ptr == NULL) {
      break;
    }
H
Haojun Liao 已提交
1332

1333
    STableBlockScanInfo* pTableScanInfo = *(STableBlockScanInfo**)ptr;
1334 1335 1336
    if (pTableScanInfo->pBlockList == NULL || taosArrayGetSize(pTableScanInfo->pBlockList) == 0) {
      continue;
    }
H
Haojun Liao 已提交
1337

1338 1339
    size_t num = taosArrayGetSize(pTableScanInfo->pBlockList);
    sup.numOfBlocksPerTable[sup.numOfTables] = num;
H
Haojun Liao 已提交
1340

1341 1342 1343
    char* buf = taosMemoryMalloc(sizeof(SBlockOrderWrapper) * num);
    if (buf == NULL) {
      cleanupBlockOrderSupporter(&sup);
S
Shengliang Guan 已提交
1344
      return TSDB_CODE_OUT_OF_MEMORY;
1345
    }
H
Haojun Liao 已提交
1346

1347
    sup.pDataBlockInfo[sup.numOfTables] = (SBlockOrderWrapper*)buf;
1348

1349 1350 1351
    for (int32_t k = 0; k < num; ++k) {
      SBlockIndex* pIndex = taosArrayGet(pTableScanInfo->pBlockList, k);
      sup.pDataBlockInfo[sup.numOfTables][k] =
1352
          (SBlockOrderWrapper){.uid = pTableScanInfo->uid, .offset = pIndex->inFileOffset};
1353 1354 1355 1356 1357
      cnt++;
    }

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

H
Haojun Liao 已提交
1359 1360 1361 1362
  if (numOfBlocks != cnt && sup.numOfTables != numOfTables) {
    cleanupBlockOrderSupporter(&sup);
    return TSDB_CODE_INVALID_PARA;
  }
H
Haojun Liao 已提交
1363

1364
  // since there is only one table qualified, blocks are not sorted
1365 1366
  if (sup.numOfTables == 1) {
    for (int32_t i = 0; i < numOfBlocks; ++i) {
1367 1368
      SFileDataBlockInfo blockInfo = {.uid = sup.pDataBlockInfo[0][i].uid, .tbBlockIdx = i};
      taosArrayPush(pBlockIter->blockList, &blockInfo);
1369
    }
1370

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

1375
    pBlockIter->index = asc ? 0 : (numOfBlocks - 1);
H
Haojun Liao 已提交
1376
    cleanupBlockOrderSupporter(&sup);
H
Haojun Liao 已提交
1377
    doSetCurrentBlock(pBlockIter, pReader->idStr);
1378
    return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
1379
  }
H
Haojun Liao 已提交
1380

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

1384
  SMultiwayMergeTreeInfo* pTree = NULL;
H
Haojun Liao 已提交
1385 1386

  uint8_t ret = tMergeTreeCreate(&pTree, sup.numOfTables, &sup, fileDataBlockOrderCompar);
1387 1388
  if (ret != TSDB_CODE_SUCCESS) {
    cleanupBlockOrderSupporter(&sup);
S
Shengliang Guan 已提交
1389
    return TSDB_CODE_OUT_OF_MEMORY;
H
Haojun Liao 已提交
1390
  }
H
Haojun Liao 已提交
1391

1392 1393 1394 1395
  int32_t numOfTotal = 0;
  while (numOfTotal < cnt) {
    int32_t pos = tMergeTreeGetChosenIndex(pTree);
    int32_t index = sup.indexPerTable[pos]++;
H
Haojun Liao 已提交
1396

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

1400 1401 1402 1403
    // 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 已提交
1404

1405 1406
    numOfTotal += 1;
    tMergeTreeAdjust(pTree, tMergeTreeGetAdjustIndex(pTree));
H
Haojun Liao 已提交
1407
  }
H
Haojun Liao 已提交
1408

1409
  int64_t et = taosGetTimestampUs();
H
Hongze Cheng 已提交
1410 1411
  tsdbDebug("%p %d data blocks access order completed, elapsed time:%.2f ms %s", pReader, numOfBlocks,
            (et - st) / 1000.0, pReader->idStr);
1412 1413
  cleanupBlockOrderSupporter(&sup);
  taosMemoryFree(pTree);
H
Haojun Liao 已提交
1414

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

1418
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
1419
}
H
Hongze Cheng 已提交
1420

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

1424
  int32_t step = asc ? 1 : -1;
1425
  if ((pBlockIter->index >= pBlockIter->numOfBlocks - 1 && asc) || (pBlockIter->index <= 0 && (!asc))) {
1426 1427 1428
    return false;
  }

1429
  pBlockIter->index += step;
H
Haojun Liao 已提交
1430
  doSetCurrentBlock(pBlockIter, idStr);
1431

1432 1433 1434
  return true;
}

1435 1436 1437
/**
 * This is an two rectangles overlap cases.
 */
H
Hongze Cheng 已提交
1438
static int32_t dataBlockPartiallyRequired(STimeWindow* pWindow, SVersionRange* pVerRange, SDataBlk* pBlock) {
1439 1440
  return (pWindow->ekey < pBlock->maxKey.ts && pWindow->ekey >= pBlock->minKey.ts) ||
         (pWindow->skey > pBlock->minKey.ts && pWindow->skey <= pBlock->maxKey.ts) ||
H
Hongze Cheng 已提交
1441 1442
         (pVerRange->minVer > pBlock->minVer && pVerRange->minVer <= pBlock->maxVer) ||
         (pVerRange->maxVer < pBlock->maxVer && pVerRange->maxVer >= pBlock->minVer);
H
Haojun Liao 已提交
1443
}
H
Hongze Cheng 已提交
1444

1445
static bool getNeighborBlockOfSameTable(SFileDataBlockInfo* pBlockInfo, STableBlockScanInfo* pTableBlockScanInfo,
1446
                                        int32_t* nextIndex, int32_t order, SBlockIndex* pBlockIndex) {
1447
  bool asc = ASCENDING_TRAVERSE(order);
H
Haojun Liao 已提交
1448
  if (asc && pBlockInfo->tbBlockIdx >= taosArrayGetSize(pTableBlockScanInfo->pBlockList) - 1) {
1449
    return false;
1450 1451
  }

H
Haojun Liao 已提交
1452
  if (!asc && pBlockInfo->tbBlockIdx == 0) {
1453
    return false;
1454 1455
  }

1456
  int32_t step = asc ? 1 : -1;
H
Haojun Liao 已提交
1457
  *nextIndex = pBlockInfo->tbBlockIdx + step;
1458 1459
  *pBlockIndex = *(SBlockIndex*)taosArrayGet(pTableBlockScanInfo->pBlockList, *nextIndex);
  //  tMapDataGetItemByIdx(&pTableBlockScanInfo->mapData, pIndex->ordinalIndex, pBlock, tGetDataBlk);
1460
  return true;
1461 1462 1463
}

static int32_t findFileBlockInfoIndex(SDataBlockIter* pBlockIter, SFileDataBlockInfo* pFBlockInfo) {
1464
  int32_t step = ASCENDING_TRAVERSE(pBlockIter->order) ? 1 : -1;
1465 1466
  int32_t index = pBlockIter->index;

1467
  while (index < pBlockIter->numOfBlocks && index >= 0) {
1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478
    SFileDataBlockInfo* pFBlock = taosArrayGet(pBlockIter->blockList, index);
    if (pFBlock->uid == pFBlockInfo->uid && pFBlock->tbBlockIdx == pFBlockInfo->tbBlockIdx) {
      return index;
    }

    index += step;
  }

  return -1;
}

1479
static int32_t setFileBlockActiveInBlockIter(SDataBlockIter* pBlockIter, int32_t index, int32_t step) {
1480
  if (index < 0 || index >= pBlockIter->numOfBlocks) {
1481 1482 1483 1484
    return -1;
  }

  SFileDataBlockInfo fblock = *(SFileDataBlockInfo*)taosArrayGet(pBlockIter->blockList, index);
1485 1486 1487 1488 1489
  pBlockIter->index += step;

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

1491 1492 1493
    SFileDataBlockInfo* pBlockInfo = taosArrayGet(pBlockIter->blockList, pBlockIter->index);
    ASSERT(pBlockInfo->uid == fblock.uid && pBlockInfo->tbBlockIdx == fblock.tbBlockIdx);
  }
1494

H
Haojun Liao 已提交
1495
  doSetCurrentBlock(pBlockIter, "");
1496 1497 1498
  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
1499
// todo: this attribute could be acquired during extractin the global ordered block list.
1500
static bool overlapWithNeighborBlock(SDataBlk* pBlock, SBlockIndex* pNeighborBlockIndex, int32_t order) {
1501 1502
  // it is the last block in current file, no chance to overlap with neighbor blocks.
  if (ASCENDING_TRAVERSE(order)) {
1503
    return pBlock->maxKey.ts == pNeighborBlockIndex->window.skey;
1504
  } else {
1505
    return pBlock->minKey.ts == pNeighborBlockIndex->window.ekey;
1506
  }
H
Haojun Liao 已提交
1507
}
H
Hongze Cheng 已提交
1508

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

1512
  return (ascScan && (key.ts != TSKEY_INITIAL_VAL && key.ts <= pBlock->minKey.ts)) ||
1513
         (!ascScan && (key.ts != TSKEY_INITIAL_VAL && key.ts >= pBlock->maxKey.ts));
H
Haojun Liao 已提交
1514
}
H
Hongze Cheng 已提交
1515

H
Hongze Cheng 已提交
1516
static bool keyOverlapFileBlock(TSDBKEY key, SDataBlk* pBlock, SVersionRange* pVerRange) {
H
Hongze Cheng 已提交
1517 1518
  return (key.ts >= pBlock->minKey.ts && key.ts <= pBlock->maxKey.ts) && (pBlock->maxVer >= pVerRange->minVer) &&
         (pBlock->minVer <= pVerRange->maxVer);
H
Haojun Liao 已提交
1519 1520
}

H
Hongze Cheng 已提交
1521 1522
static bool doCheckforDatablockOverlap(STableBlockScanInfo* pBlockScanInfo, const SDataBlk* pBlock,
                                       int32_t startIndex) {
1523 1524
  size_t num = taosArrayGetSize(pBlockScanInfo->delSkyline);

1525
  for (int32_t i = startIndex; i < num; i += 1) {
1526 1527
    TSDBKEY* p = taosArrayGet(pBlockScanInfo->delSkyline, i);
    if (p->ts >= pBlock->minKey.ts && p->ts <= pBlock->maxKey.ts) {
H
Hongze Cheng 已提交
1528
      if (p->version >= pBlock->minVer) {
1529 1530 1531
        return true;
      }
    } else if (p->ts < pBlock->minKey.ts) {  // p->ts < pBlock->minKey.ts
H
Hongze Cheng 已提交
1532
      if (p->version >= pBlock->minVer) {
1533 1534
        if (i < num - 1) {
          TSDBKEY* pnext = taosArrayGet(pBlockScanInfo->delSkyline, i + 1);
H
Hongze Cheng 已提交
1535 1536
          if (pnext->ts >= pBlock->minKey.ts) {
            return true;
1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549
          }
        } else {  // it must be the last point
          ASSERT(p->version == 0);
        }
      }
    } else {  // (p->ts > pBlock->maxKey.ts) {
      return false;
    }
  }

  return false;
}

H
Hongze Cheng 已提交
1550
static bool overlapWithDelSkyline(STableBlockScanInfo* pBlockScanInfo, const SDataBlk* pBlock, int32_t order) {
1551 1552 1553 1554
  if (pBlockScanInfo->delSkyline == NULL) {
    return false;
  }

1555
  // ts is not overlap
1556
  TSDBKEY* pFirst = taosArrayGet(pBlockScanInfo->delSkyline, 0);
L
Liu Jicong 已提交
1557
  TSDBKEY* pLast = taosArrayGetLast(pBlockScanInfo->delSkyline);
1558 1559 1560 1561 1562
  if (pBlock->minKey.ts > pLast->ts || pBlock->maxKey.ts < pFirst->ts) {
    return false;
  }

  // version is not overlap
1563
  if (ASCENDING_TRAVERSE(order)) {
1564
    return doCheckforDatablockOverlap(pBlockScanInfo, pBlock, pBlockScanInfo->fileDelIndex);
1565 1566
  } else {
    int32_t index = pBlockScanInfo->fileDelIndex;
1567
    while (1) {
1568 1569 1570 1571 1572
      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;
1573 1574 1575
      }
    }

1576
    return doCheckforDatablockOverlap(pBlockScanInfo, pBlock, index);
1577
  }
1578 1579
}

C
Cary Xu 已提交
1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592
typedef struct {
  bool overlapWithNeighborBlock;
  bool hasDupTs;
  bool overlapWithDelInfo;
  bool overlapWithLastBlock;
  bool overlapWithKeyInBuf;
  bool partiallyRequired;
  bool moreThanCapcity;
} SDataBlockToLoadInfo;

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

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

1598
  // overlap with neighbor
1599
  if (hasNeighbor) {
1600
    pInfo->overlapWithNeighborBlock = overlapWithNeighborBlock(pBlock, &bIndex, pReader->order);
1601 1602
  }

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

1607 1608 1609
  if (hasDataInLastBlock(pLastBlockReader)) {
    int64_t tsLast = getCurrentKeyInLastBlock(pLastBlockReader);
    pInfo->overlapWithLastBlock = !(pBlock->maxKey.ts < tsLast || pBlock->minKey.ts > tsLast);
1610 1611
  }

C
Cary Xu 已提交
1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626
  pInfo->moreThanCapcity = pBlock->nRow > pReader->capacity;
  pInfo->partiallyRequired = dataBlockPartiallyRequired(&pReader->window, &pReader->verRange, pBlock);
  pInfo->overlapWithKeyInBuf = keyOverlapFileBlock(keyInBuf, pBlock, &pReader->verRange);
}

// 1. the version of all rows should be less than the endVersion
// 2. current block should not overlap with next neighbor block
// 3. current timestamp should not be overlap with each other
// 4. output buffer should be large enough to hold all rows in current block
// 5. delete info should not overlap with current block data
// 6. current block should not contain the duplicated ts
static bool fileBlockShouldLoad(STsdbReader* pReader, SFileDataBlockInfo* pBlockInfo, SDataBlk* pBlock,
                                STableBlockScanInfo* pScanInfo, TSDBKEY keyInBuf, SLastBlockReader* pLastBlockReader) {
  SDataBlockToLoadInfo info = {0};
  getBlockToLoadInfo(&info, pBlockInfo, pBlock, pScanInfo, keyInBuf, pLastBlockReader, pReader);
1627

C
Cary Xu 已提交
1628 1629 1630
  bool loadDataBlock =
      (info.overlapWithNeighborBlock || info.hasDupTs || info.partiallyRequired || info.overlapWithKeyInBuf ||
       info.moreThanCapcity || info.overlapWithDelInfo || info.overlapWithLastBlock);
1631 1632 1633 1634

  // log the reason why load the datablock for profile
  if (loadDataBlock) {
    tsdbDebug("%p uid:%" PRIu64
1635
              " need to load the datablock, overlapwithneighborblock:%d, hasDup:%d, partiallyRequired:%d, "
1636
              "overlapWithKey:%d, greaterThanBuf:%d, overlapWithDel:%d, overlapWithlastBlock:%d, %s",
C
Cary Xu 已提交
1637 1638 1639
              pReader, pBlockInfo->uid, info.overlapWithNeighborBlock, info.hasDupTs, info.partiallyRequired,
              info.overlapWithKeyInBuf, info.moreThanCapcity, info.overlapWithDelInfo, info.overlapWithLastBlock,
              pReader->idStr);
1640 1641 1642
  }

  return loadDataBlock;
H
Haojun Liao 已提交
1643 1644
}

C
Cary Xu 已提交
1645 1646 1647 1648 1649 1650 1651 1652 1653
static bool isCleanFileDataBlock(STsdbReader* pReader, SFileDataBlockInfo* pBlockInfo, SDataBlk* pBlock,
                                 STableBlockScanInfo* pScanInfo, TSDBKEY keyInBuf, SLastBlockReader* pLastBlockReader) {
  SDataBlockToLoadInfo info = {0};
  getBlockToLoadInfo(&info, pBlockInfo, pBlock, pScanInfo, keyInBuf, pLastBlockReader, pReader);
  bool isCleanFileBlock = !(info.overlapWithNeighborBlock || info.hasDupTs || info.overlapWithKeyInBuf ||
                            info.overlapWithDelInfo || info.overlapWithLastBlock);
  return isCleanFileBlock;
}

1654
static int32_t buildDataBlockFromBuf(STsdbReader* pReader, STableBlockScanInfo* pBlockScanInfo, int64_t endKey) {
1655
  if (!(pBlockScanInfo->iiter.hasVal || pBlockScanInfo->iter.hasVal)) {
1656 1657
    return TSDB_CODE_SUCCESS;
  }
H
Haojun Liao 已提交
1658

1659 1660 1661
  SSDataBlock* pBlock = pReader->pResBlock;

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

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

1667
  setComposedBlockFlag(pReader, true);
1668

1669
  double elapsedTime = (taosGetTimestampUs() - st) / 1000.0;
S
Shengliang Guan 已提交
1670
  tsdbDebug("%p build data block from cache completed, elapsed time:%.2f ms, numOfRows:%d, brange:%" PRId64
1671 1672 1673
            " - %" PRId64 " %s",
            pReader, elapsedTime, pBlock->info.rows, pBlock->info.window.skey, pBlock->info.window.ekey,
            pReader->idStr);
1674 1675

  pReader->cost.buildmemBlock += elapsedTime;
H
Haojun Liao 已提交
1676 1677 1678
  return code;
}

1679 1680
static bool tryCopyDistinctRowFromFileBlock(STsdbReader* pReader, SBlockData* pBlockData, int64_t key,
                                            SFileBlockDumpInfo* pDumpInfo) {
1681 1682 1683
  // opt version
  // 1. it is not a border point
  // 2. the direct next point is not an duplicated timestamp
1684 1685
  bool asc = (pReader->order == TSDB_ORDER_ASC);
  if ((pDumpInfo->rowIndex < pDumpInfo->totalRows - 1 && asc) || (pDumpInfo->rowIndex > 0 && (!asc))) {
1686
    int32_t step = pReader->order == TSDB_ORDER_ASC ? 1 : -1;
1687 1688

    int64_t nextKey = pBlockData->aTSKEY[pDumpInfo->rowIndex + step];
1689
    if (nextKey != key) {  // merge is not needed
1690
      doAppendRowFromFileBlock(pReader->pResBlock, pReader, pBlockData, pDumpInfo->rowIndex);
1691 1692 1693 1694 1695 1696 1697 1698
      pDumpInfo->rowIndex += step;
      return true;
    }
  }

  return false;
}

1699 1700
static bool nextRowFromLastBlocks(SLastBlockReader* pLastBlockReader, STableBlockScanInfo* pBlockScanInfo,
                                  SVersionRange* pVerRange) {
1701 1702 1703 1704 1705 1706 1707 1708
  while (1) {
    bool hasVal = tMergeTreeNext(&pLastBlockReader->mergeTree);
    if (!hasVal) {
      return false;
    }

    TSDBROW row = tMergeTreeGetRow(&pLastBlockReader->mergeTree);
    TSDBKEY k = TSDBROW_KEY(&row);
1709 1710
    if (!hasBeenDropped(pBlockScanInfo->delSkyline, &pBlockScanInfo->lastBlockDelIndex, &k, pLastBlockReader->order,
                        pVerRange)) {
1711 1712 1713 1714 1715 1716 1717
      return true;
    }
  }
}

static bool tryCopyDistinctRowFromSttBlock(TSDBROW* fRow, SLastBlockReader* pLastBlockReader,
                                           STableBlockScanInfo* pScanInfo, int64_t ts, STsdbReader* pReader) {
1718
  bool hasVal = nextRowFromLastBlocks(pLastBlockReader, pScanInfo, &pReader->verRange);
1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732
  if (hasVal) {
    int64_t next1 = getCurrentKeyInLastBlock(pLastBlockReader);
    if (next1 != ts) {
      doAppendRowFromFileBlock(pReader->pResBlock, pReader, fRow->pBlockData, fRow->iRow);
      return true;
    }
  } else {
    doAppendRowFromFileBlock(pReader->pResBlock, pReader, fRow->pBlockData, fRow->iRow);
    return true;
  }

  return false;
}

H
Haojun Liao 已提交
1733 1734 1735
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) {
1736
    pReader->pSchema = metaGetTbTSchema(pReader->pTsdb->pVnode->pMeta, uid, -1, 1);
H
Haojun Liao 已提交
1737 1738
  }

1739
  if (pReader->pSchema && sversion == pReader->pSchema->version) {
H
Haojun Liao 已提交
1740 1741 1742 1743 1744 1745
    return pReader->pSchema;
  }

  if (pReader->pMemSchema == NULL) {
    int32_t code =
        metaGetTbTSchemaEx(pReader->pTsdb->pVnode->pMeta, pReader->suid, uid, sversion, &pReader->pMemSchema);
H
Haojun Liao 已提交
1746 1747 1748 1749 1750 1751
    if (code != TSDB_CODE_SUCCESS) {
      terrno = code;
      return NULL;
    } else {
      return pReader->pMemSchema;
    }
H
Haojun Liao 已提交
1752 1753 1754 1755 1756 1757
  }

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

H
Haojun Liao 已提交
1758
  taosMemoryFreeClear(pReader->pMemSchema);
H
Haojun Liao 已提交
1759
  int32_t code = metaGetTbTSchemaEx(pReader->pTsdb->pVnode->pMeta, pReader->suid, uid, sversion, &pReader->pMemSchema);
H
Haojun Liao 已提交
1760
  if (code != TSDB_CODE_SUCCESS || pReader->pMemSchema == NULL) {
H
Haojun Liao 已提交
1761 1762
    terrno = code;
    return NULL;
H
Haojun Liao 已提交
1763 1764
  } else {
    return pReader->pMemSchema;
H
Haojun Liao 已提交
1765
  }
H
Haojun Liao 已提交
1766 1767
}

1768
static int32_t doMergeBufAndFileRows(STsdbReader* pReader, STableBlockScanInfo* pBlockScanInfo, TSDBROW* pRow,
1769 1770
                                     SIterInfo* pIter, int64_t key, SLastBlockReader* pLastBlockReader) {
  SRowMerger          merge = {0};
H
Hongze Cheng 已提交
1771
  SRow*               pTSRow = NULL;
1772 1773 1774
  SBlockData*         pBlockData = &pReader->status.fileBlockData;
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;

1775
  int64_t tsLast = INT64_MIN;
1776
  if (hasDataInLastBlock(pLastBlockReader)) {
1777 1778
    tsLast = getCurrentKeyInLastBlock(pLastBlockReader);
  }
1779

H
Hongze Cheng 已提交
1780 1781
  TSDBKEY k = TSDBROW_KEY(pRow);
  TSDBROW fRow = tsdbRowFromBlockData(pBlockData, pDumpInfo->rowIndex);
1782

1783 1784
  int64_t minKey = 0;
  if (pReader->order == TSDB_ORDER_ASC) {
H
Hongze Cheng 已提交
1785
    minKey = INT64_MAX;  // chosen the minimum value
1786
    if (minKey > tsLast && hasDataInLastBlock(pLastBlockReader)) {
1787 1788
      minKey = tsLast;
    }
1789

1790 1791 1792
    if (minKey > k.ts) {
      minKey = k.ts;
    }
1793

1794
    if (minKey > key && hasDataInFileBlock(pBlockData, pDumpInfo)) {
1795 1796 1797 1798
      minKey = key;
    }
  } else {
    minKey = INT64_MIN;
1799
    if (minKey < tsLast && hasDataInLastBlock(pLastBlockReader)) {
1800 1801 1802 1803 1804 1805 1806
      minKey = tsLast;
    }

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

1807
    if (minKey < key && hasDataInFileBlock(pBlockData, pDumpInfo)) {
1808 1809
      minKey = key;
    }
1810 1811 1812 1813
  }

  bool init = false;

1814
  // ASC: file block ---> last block -----> imem -----> mem
H
Hongze Cheng 已提交
1815
  // DESC: mem -----> imem -----> last block -----> file block
1816 1817
  if (pReader->order == TSDB_ORDER_ASC) {
    if (minKey == key) {
1818
      init = true;
H
Hongze Cheng 已提交
1819
      int32_t code = tsdbRowMergerInit(&merge, &fRow, pReader->pSchema);
H
Haojun Liao 已提交
1820 1821 1822
      if (code != TSDB_CODE_SUCCESS) {
        return code;
      }
1823
      doMergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pReader, &merge);
1824 1825
    }

1826
    if (minKey == tsLast) {
1827
      TSDBROW fRow1 = tMergeTreeGetRow(&pLastBlockReader->mergeTree);
H
Haojun Liao 已提交
1828
      if (init) {
H
Hongze Cheng 已提交
1829
        tsdbRowMerge(&merge, &fRow1);
H
Haojun Liao 已提交
1830
      } else {
1831
        init = true;
H
Hongze Cheng 已提交
1832
        int32_t code = tsdbRowMergerInit(&merge, &fRow1, pReader->pSchema);
H
Haojun Liao 已提交
1833 1834 1835
        if (code != TSDB_CODE_SUCCESS) {
          return code;
        }
1836
      }
1837
      doMergeRowsInLastBlock(pLastBlockReader, pBlockScanInfo, tsLast, &merge, &pReader->verRange);
1838
    }
1839

1840
    if (minKey == k.ts) {
K
kailixu 已提交
1841 1842 1843 1844
      STSchema* pSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(pRow), pReader, pBlockScanInfo->uid);
      if (pSchema == NULL) {
        return terrno;
      }
H
Haojun Liao 已提交
1845
      if (init) {
X
Xiaoyu Wang 已提交
1846
        tsdbRowMergerAdd(&merge, pRow, pSchema);
H
Haojun Liao 已提交
1847
      } else {
1848
        init = true;
X
Xiaoyu Wang 已提交
1849
        int32_t code = tsdbRowMergerInit(&merge, pRow, pSchema);
H
Haojun Liao 已提交
1850 1851 1852 1853 1854 1855 1856
        if (code != TSDB_CODE_SUCCESS) {
          return code;
        }
      }
      int32_t code = doMergeRowsInBuf(pIter, pBlockScanInfo->uid, k.ts, pBlockScanInfo->delSkyline, &merge, pReader);
      if (code != TSDB_CODE_SUCCESS) {
        return code;
1857 1858 1859 1860 1861
      }
    }
  } else {
    if (minKey == k.ts) {
      init = true;
1862
      STSchema* pSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(pRow), pReader, pBlockScanInfo->uid);
H
Hongze Cheng 已提交
1863
      int32_t   code = tsdbRowMergerInit(&merge, pRow, pSchema);
H
Haojun Liao 已提交
1864 1865 1866 1867 1868
      if (code != TSDB_CODE_SUCCESS) {
        return code;
      }

      code = doMergeRowsInBuf(pIter, pBlockScanInfo->uid, k.ts, pBlockScanInfo->delSkyline, &merge, pReader);
1869
      if (code != TSDB_CODE_SUCCESS || merge.pTSchema == NULL) {
H
Haojun Liao 已提交
1870 1871
        return code;
      }
1872 1873
    }

1874
    if (minKey == tsLast) {
1875
      TSDBROW fRow1 = tMergeTreeGetRow(&pLastBlockReader->mergeTree);
H
Haojun Liao 已提交
1876
      if (init) {
H
Hongze Cheng 已提交
1877
        tsdbRowMerge(&merge, &fRow1);
H
Haojun Liao 已提交
1878
      } else {
1879
        init = true;
H
Hongze Cheng 已提交
1880
        int32_t code = tsdbRowMergerInit(&merge, &fRow1, pReader->pSchema);
H
Haojun Liao 已提交
1881 1882 1883
        if (code != TSDB_CODE_SUCCESS) {
          return code;
        }
1884
      }
1885
      doMergeRowsInLastBlock(pLastBlockReader, pBlockScanInfo, tsLast, &merge, &pReader->verRange);
1886 1887 1888
    }

    if (minKey == key) {
H
Haojun Liao 已提交
1889
      if (init) {
H
Hongze Cheng 已提交
1890
        tsdbRowMerge(&merge, &fRow);
H
Haojun Liao 已提交
1891
      } else {
1892
        init = true;
H
Hongze Cheng 已提交
1893
        int32_t code = tsdbRowMergerInit(&merge, &fRow, pReader->pSchema);
H
Haojun Liao 已提交
1894 1895 1896
        if (code != TSDB_CODE_SUCCESS) {
          return code;
        }
1897 1898 1899
      }
      doMergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pReader, &merge);
    }
1900 1901
  }

H
Hongze Cheng 已提交
1902
  int32_t code = tsdbRowMergerGetRow(&merge, &pTSRow);
1903 1904 1905 1906
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

1907
  doAppendRowFromTSRow(pReader->pResBlock, pReader, pTSRow, pBlockScanInfo);
1908 1909

  taosMemoryFree(pTSRow);
H
Hongze Cheng 已提交
1910
  tsdbRowMergerClear(&merge);
1911 1912 1913
  return TSDB_CODE_SUCCESS;
}

1914 1915 1916
static int32_t doMergeFileBlockAndLastBlock(SLastBlockReader* pLastBlockReader, STsdbReader* pReader,
                                            STableBlockScanInfo* pBlockScanInfo, SBlockData* pBlockData,
                                            bool mergeBlockData) {
1917
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;
H
Hongze Cheng 已提交
1918
  int64_t             tsLastBlock = getCurrentKeyInLastBlock(pLastBlockReader);
1919

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

1925 1926 1927
  // only last block exists
  if ((!mergeBlockData) || (tsLastBlock != pBlockData->aTSKEY[pDumpInfo->rowIndex])) {
    if (tryCopyDistinctRowFromSttBlock(&fRow, pLastBlockReader, pBlockScanInfo, tsLastBlock, pReader)) {
1928
      pBlockScanInfo->lastKey = tsLastBlock;
1929 1930
      return TSDB_CODE_SUCCESS;
    } else {
H
Hongze Cheng 已提交
1931
      int32_t code = tsdbRowMergerInit(&merge, &fRow, pReader->pSchema);
H
Haojun Liao 已提交
1932 1933 1934
      if (code != TSDB_CODE_SUCCESS) {
        return code;
      }
1935

1936
      TSDBROW fRow1 = tMergeTreeGetRow(&pLastBlockReader->mergeTree);
H
Hongze Cheng 已提交
1937
      tsdbRowMerge(&merge, &fRow1);
1938
      doMergeRowsInLastBlock(pLastBlockReader, pBlockScanInfo, tsLastBlock, &merge, &pReader->verRange);
1939

H
Hongze Cheng 已提交
1940
      code = tsdbRowMergerGetRow(&merge, &pTSRow);
1941 1942 1943
      if (code != TSDB_CODE_SUCCESS) {
        return code;
      }
1944

1945
      doAppendRowFromTSRow(pReader->pResBlock, pReader, pTSRow, pBlockScanInfo);
1946 1947

      taosMemoryFree(pTSRow);
H
Hongze Cheng 已提交
1948
      tsdbRowMergerClear(&merge);
1949 1950
    }
  } else {  // not merge block data
H
Hongze Cheng 已提交
1951
    int32_t code = tsdbRowMergerInit(&merge, &fRow, pReader->pSchema);
H
Haojun Liao 已提交
1952 1953 1954 1955
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

1956
    doMergeRowsInLastBlock(pLastBlockReader, pBlockScanInfo, tsLastBlock, &merge, &pReader->verRange);
1957 1958

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

H
Hongze Cheng 已提交
1963
    code = tsdbRowMergerGetRow(&merge, &pTSRow);
1964 1965 1966 1967
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

1968
    doAppendRowFromTSRow(pReader->pResBlock, pReader, pTSRow, pBlockScanInfo);
1969 1970

    taosMemoryFree(pTSRow);
H
Hongze Cheng 已提交
1971
    tsdbRowMergerClear(&merge);
1972
  }
1973 1974 1975 1976

  return TSDB_CODE_SUCCESS;
}

1977 1978
static int32_t mergeFileBlockAndLastBlock(STsdbReader* pReader, SLastBlockReader* pLastBlockReader, int64_t key,
                                          STableBlockScanInfo* pBlockScanInfo, SBlockData* pBlockData) {
1979 1980
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;

1981
  if (hasDataInFileBlock(pBlockData, pDumpInfo)) {
1982
    // no last block available, only data block exists
1983
    if (!hasDataInLastBlock(pLastBlockReader)) {
1984 1985 1986 1987 1988 1989 1990 1991 1992
      return mergeRowsInFileBlocks(pBlockData, pBlockScanInfo, key, pReader);
    }

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

    if (ASCENDING_TRAVERSE(pReader->order)) {
1993
      if (key < ts) {  // imem, mem are all empty, file blocks (data blocks and last block) exist
1994 1995
        return mergeRowsInFileBlocks(pBlockData, pBlockScanInfo, key, pReader);
      } else if (key == ts) {
H
Hongze Cheng 已提交
1996
        SRow*      pTSRow = NULL;
1997
        SRowMerger merge = {0};
1998

H
Hongze Cheng 已提交
1999
        int32_t code = tsdbRowMergerInit(&merge, &fRow, pReader->pSchema);
H
Haojun Liao 已提交
2000 2001 2002 2003
        if (code != TSDB_CODE_SUCCESS) {
          return code;
        }

2004
        doMergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pReader, &merge);
2005 2006

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

2009
        doMergeRowsInLastBlock(pLastBlockReader, pBlockScanInfo, ts, &merge, &pReader->verRange);
2010

H
Hongze Cheng 已提交
2011
        code = tsdbRowMergerGetRow(&merge, &pTSRow);
2012 2013 2014 2015
        if (code != TSDB_CODE_SUCCESS) {
          return code;
        }

2016
        doAppendRowFromTSRow(pReader->pResBlock, pReader, pTSRow, pBlockScanInfo);
2017

2018
        taosMemoryFree(pTSRow);
H
Hongze Cheng 已提交
2019
        tsdbRowMergerClear(&merge);
2020
        return code;
2021
      } else {
2022
        return TSDB_CODE_SUCCESS;
2023
      }
2024
    } else {  // desc order
2025
      return doMergeFileBlockAndLastBlock(pLastBlockReader, pReader, pBlockScanInfo, pBlockData, true);
2026
    }
2027
  } else {  // only last block exists
2028
    return doMergeFileBlockAndLastBlock(pLastBlockReader, pReader, pBlockScanInfo, NULL, false);
H
Haojun Liao 已提交
2029
  }
2030 2031
}

2032 2033
static int32_t doMergeMultiLevelRows(STsdbReader* pReader, STableBlockScanInfo* pBlockScanInfo, SBlockData* pBlockData,
                                     SLastBlockReader* pLastBlockReader) {
H
Haojun Liao 已提交
2034
  SRowMerger          merge = {0};
H
Hongze Cheng 已提交
2035
  SRow*               pTSRow = NULL;
H
Haojun Liao 已提交
2036
  int32_t             code = TSDB_CODE_SUCCESS;
2037 2038 2039
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;
  SArray*             pDelList = pBlockScanInfo->delSkyline;

2040 2041
  TSDBROW* pRow = getValidMemRow(&pBlockScanInfo->iter, pDelList, pReader);
  TSDBROW* piRow = getValidMemRow(&pBlockScanInfo->iiter, pDelList, pReader);
2042

2043
  int64_t tsLast = INT64_MIN;
2044 2045 2046
  if (hasDataInLastBlock(pLastBlockReader)) {
    tsLast = getCurrentKeyInLastBlock(pLastBlockReader);
  }
2047

H
Hongze Cheng 已提交
2048
  int64_t key = hasDataInFileBlock(pBlockData, pDumpInfo) ? pBlockData->aTSKEY[pDumpInfo->rowIndex] : INT64_MIN;
2049 2050 2051 2052

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

2053
  int64_t minKey = 0;
2054 2055 2056 2057 2058
  if (ASCENDING_TRAVERSE(pReader->order)) {
    minKey = INT64_MAX;  // let's find the minimum
    if (minKey > k.ts) {
      minKey = k.ts;
    }
2059

2060 2061 2062
    if (minKey > ik.ts) {
      minKey = ik.ts;
    }
2063

2064
    if (minKey > key && hasDataInFileBlock(pBlockData, pDumpInfo)) {
2065 2066
      minKey = key;
    }
2067

2068
    if (minKey > tsLast && hasDataInLastBlock(pLastBlockReader)) {
2069 2070 2071
      minKey = tsLast;
    }
  } else {
H
Hongze Cheng 已提交
2072
    minKey = INT64_MIN;  // let find the maximum ts value
2073 2074 2075 2076 2077 2078 2079 2080
    if (minKey < k.ts) {
      minKey = k.ts;
    }

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

2081
    if (minKey < key && hasDataInFileBlock(pBlockData, pDumpInfo)) {
2082 2083 2084
      minKey = key;
    }

2085
    if (minKey < tsLast && hasDataInLastBlock(pLastBlockReader)) {
2086 2087
      minKey = tsLast;
    }
2088 2089 2090 2091
  }

  bool init = false;

2092 2093 2094 2095
  // ASC: file block -----> last block -----> imem -----> mem
  // DESC: mem -----> imem -----> last block -----> file block
  if (ASCENDING_TRAVERSE(pReader->order)) {
    if (minKey == key) {
2096
      init = true;
2097
      TSDBROW fRow = tsdbRowFromBlockData(pBlockData, pDumpInfo->rowIndex);
H
Hongze Cheng 已提交
2098
      code = tsdbRowMergerInit(&merge, &fRow, pReader->pSchema);
H
Haojun Liao 已提交
2099 2100 2101 2102
      if (code != TSDB_CODE_SUCCESS) {
        return code;
      }

2103
      doMergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pReader, &merge);
2104 2105
    }

2106
    if (minKey == tsLast) {
2107
      TSDBROW fRow1 = tMergeTreeGetRow(&pLastBlockReader->mergeTree);
H
Haojun Liao 已提交
2108
      if (init) {
H
Hongze Cheng 已提交
2109
        tsdbRowMerge(&merge, &fRow1);
H
Haojun Liao 已提交
2110
      } else {
2111
        init = true;
H
Hongze Cheng 已提交
2112
        code = tsdbRowMergerInit(&merge, &fRow1, pReader->pSchema);
H
Haojun Liao 已提交
2113 2114 2115
        if (code != TSDB_CODE_SUCCESS) {
          return code;
        }
2116
      }
H
Haojun Liao 已提交
2117

2118
      doMergeRowsInLastBlock(pLastBlockReader, pBlockScanInfo, tsLast, &merge, &pReader->verRange);
2119 2120 2121
    }

    if (minKey == ik.ts) {
H
Haojun Liao 已提交
2122
      if (init) {
H
Hongze Cheng 已提交
2123
        tsdbRowMerge(&merge, piRow);
H
Haojun Liao 已提交
2124
      } else {
2125 2126
        init = true;
        STSchema* pSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(piRow), pReader, pBlockScanInfo->uid);
H
Haojun Liao 已提交
2127 2128 2129 2130
        if (pSchema == NULL) {
          return code;
        }

H
Hongze Cheng 已提交
2131
        code = tsdbRowMergerInit(&merge, piRow, pSchema);
H
Haojun Liao 已提交
2132 2133 2134
        if (code != TSDB_CODE_SUCCESS) {
          return code;
        }
2135
      }
H
Haojun Liao 已提交
2136

2137 2138
      code = doMergeRowsInBuf(&pBlockScanInfo->iiter, pBlockScanInfo->uid, ik.ts, pBlockScanInfo->delSkyline, &merge,
                              pReader);
H
Haojun Liao 已提交
2139 2140
      if (code != TSDB_CODE_SUCCESS) {
        return code;
2141
      }
2142 2143
    }

2144
    if (minKey == k.ts) {
H
Haojun Liao 已提交
2145
      if (init) {
2146 2147 2148 2149
        if (merge.pTSchema == NULL) {
          return code;
        }

H
Hongze Cheng 已提交
2150
        tsdbRowMerge(&merge, pRow);
H
Haojun Liao 已提交
2151
      } else {
2152
        STSchema* pSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(pRow), pReader, pBlockScanInfo->uid);
H
Hongze Cheng 已提交
2153
        code = tsdbRowMergerInit(&merge, pRow, pSchema);
H
Haojun Liao 已提交
2154 2155 2156
        if (code != TSDB_CODE_SUCCESS) {
          return code;
        }
2157
      }
H
Haojun Liao 已提交
2158 2159 2160 2161
      code = doMergeRowsInBuf(&pBlockScanInfo->iter, pBlockScanInfo->uid, k.ts, pBlockScanInfo->delSkyline, &merge,
                              pReader);
      if (code != TSDB_CODE_SUCCESS) {
        return code;
2162 2163 2164 2165 2166
      }
    }
  } else {
    if (minKey == k.ts) {
      init = true;
2167
      STSchema* pSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(pRow), pReader, pBlockScanInfo->uid);
H
Hongze Cheng 已提交
2168
      code = tsdbRowMergerInit(&merge, pRow, pSchema);
H
Haojun Liao 已提交
2169 2170 2171 2172
      if (code != TSDB_CODE_SUCCESS) {
        return code;
      }

H
Haojun Liao 已提交
2173 2174 2175 2176 2177
      code = doMergeRowsInBuf(&pBlockScanInfo->iter, pBlockScanInfo->uid, k.ts, pBlockScanInfo->delSkyline, &merge,
                              pReader);
      if (code != TSDB_CODE_SUCCESS) {
        return code;
      }
2178 2179 2180
    }

    if (minKey == ik.ts) {
H
Haojun Liao 已提交
2181
      if (init) {
H
Hongze Cheng 已提交
2182
        tsdbRowMerge(&merge, piRow);
H
Haojun Liao 已提交
2183
      } else {
2184 2185
        init = true;
        STSchema* pSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(piRow), pReader, pBlockScanInfo->uid);
H
Hongze Cheng 已提交
2186
        code = tsdbRowMergerInit(&merge, piRow, pSchema);
H
Haojun Liao 已提交
2187 2188 2189
        if (code != TSDB_CODE_SUCCESS) {
          return code;
        }
2190
      }
H
Haojun Liao 已提交
2191 2192 2193 2194
      code = doMergeRowsInBuf(&pBlockScanInfo->iiter, pBlockScanInfo->uid, ik.ts, pBlockScanInfo->delSkyline, &merge,
                              pReader);
      if (code != TSDB_CODE_SUCCESS) {
        return code;
2195 2196 2197 2198
      }
    }

    if (minKey == tsLast) {
2199
      TSDBROW fRow1 = tMergeTreeGetRow(&pLastBlockReader->mergeTree);
H
Haojun Liao 已提交
2200
      if (init) {
H
Hongze Cheng 已提交
2201
        tsdbRowMerge(&merge, &fRow1);
H
Haojun Liao 已提交
2202
      } else {
2203
        init = true;
H
Hongze Cheng 已提交
2204
        code = tsdbRowMergerInit(&merge, &fRow1, pReader->pSchema);
H
Haojun Liao 已提交
2205 2206 2207
        if (code != TSDB_CODE_SUCCESS) {
          return code;
        }
2208
      }
2209
      doMergeRowsInLastBlock(pLastBlockReader, pBlockScanInfo, tsLast, &merge, &pReader->verRange);
2210 2211 2212
    }

    if (minKey == key) {
H
Haojun Liao 已提交
2213
      TSDBROW fRow = tsdbRowFromBlockData(pBlockData, pDumpInfo->rowIndex);
2214
      if (!init) {
H
Hongze Cheng 已提交
2215
        code = tsdbRowMergerInit(&merge, &fRow, pReader->pSchema);
H
Haojun Liao 已提交
2216 2217 2218
        if (code != TSDB_CODE_SUCCESS) {
          return code;
        }
H
Haojun Liao 已提交
2219
      } else {
2220 2221 2222
        if (merge.pTSchema == NULL) {
          return code;
        }
H
Hongze Cheng 已提交
2223
        tsdbRowMerge(&merge, &fRow);
2224 2225
      }
      doMergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pReader, &merge);
2226 2227 2228
    }
  }

2229
  if (merge.pTSchema == NULL) {
2230 2231 2232
    return code;
  }

H
Hongze Cheng 已提交
2233
  code = tsdbRowMergerGetRow(&merge, &pTSRow);
2234 2235 2236 2237
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

2238
  doAppendRowFromTSRow(pReader->pResBlock, pReader, pTSRow, pBlockScanInfo);
2239 2240

  taosMemoryFree(pTSRow);
H
Hongze Cheng 已提交
2241
  tsdbRowMergerClear(&merge);
2242
  return code;
2243 2244
}

2245 2246 2247 2248 2249 2250 2251 2252 2253
static int32_t initMemDataIterator(STableBlockScanInfo* pBlockScanInfo, STsdbReader* pReader) {
  if (pBlockScanInfo->iterInit) {
    return TSDB_CODE_SUCCESS;
  }

  int32_t code = TSDB_CODE_SUCCESS;

  TSDBKEY startKey = {0};
  if (ASCENDING_TRAVERSE(pReader->order)) {
2254 2255
    // startKey = (TSDBKEY){.ts = pReader->window.skey, .version = pReader->verRange.minVer};
    startKey = (TSDBKEY){.ts = pBlockScanInfo->lastKey + 1, .version = pReader->verRange.minVer};
2256
  } else {
2257 2258
    // startKey = (TSDBKEY){.ts = pReader->window.ekey, .version = pReader->verRange.maxVer};
    startKey = (TSDBKEY){.ts = pBlockScanInfo->lastKey - 1, .version = pReader->verRange.maxVer};
2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271
  }

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

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

        tsdbDebug("%p uid:%" PRId64 ", check data in mem from skey:%" PRId64 ", order:%d, ts range in buf:%" PRId64
H
Hongze Cheng 已提交
2272
                  "-%" PRId64 " %s",
2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292
                  pReader, pBlockScanInfo->uid, startKey.ts, pReader->order, d->minKey, d->maxKey, pReader->idStr);
      } else {
        tsdbError("%p uid:%" PRId64 ", failed to create iterator for imem, code:%s, %s", pReader, pBlockScanInfo->uid,
                  tstrerror(code), pReader->idStr);
        return code;
      }
    }
  } else {
    tsdbDebug("%p uid:%" PRId64 ", no data in mem, %s", pReader, pBlockScanInfo->uid, pReader->idStr);
  }

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

        tsdbDebug("%p uid:%" PRId64 ", check data in imem from skey:%" PRId64 ", order:%d, ts range in buf:%" PRId64
H
Hongze Cheng 已提交
2293
                  "-%" PRId64 " %s",
2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310
                  pReader, pBlockScanInfo->uid, startKey.ts, pReader->order, di->minKey, di->maxKey, pReader->idStr);
      } else {
        tsdbError("%p uid:%" PRId64 ", failed to create iterator for mem, code:%s, %s", pReader, pBlockScanInfo->uid,
                  tstrerror(code), pReader->idStr);
        return code;
      }
    }
  } else {
    tsdbDebug("%p uid:%" PRId64 ", no data in imem, %s", pReader, pBlockScanInfo->uid, pReader->idStr);
  }

  initDelSkylineIterator(pBlockScanInfo, pReader, d, di);

  pBlockScanInfo->iterInit = true;
  return TSDB_CODE_SUCCESS;
}

dengyihao's avatar
dengyihao 已提交
2311 2312
static bool isValidFileBlockRow(SBlockData* pBlockData, SFileBlockDumpInfo* pDumpInfo,
                                STableBlockScanInfo* pBlockScanInfo, STsdbReader* pReader) {
2313 2314 2315 2316 2317 2318 2319 2320
  // it is an multi-table data block
  if (pBlockData->aUid != NULL) {
    uint64_t uid = pBlockData->aUid[pDumpInfo->rowIndex];
    if (uid != pBlockScanInfo->uid) {  // move to next row
      return false;
    }
  }

2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331
  // 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;
  }

2332
  TSDBKEY k = {.ts = ts, .version = ver};
2333 2334
  if (hasBeenDropped(pBlockScanInfo->delSkyline, &pBlockScanInfo->fileDelIndex, &k, pReader->order,
                     &pReader->verRange)) {
2335 2336 2337
    return false;
  }

2338 2339 2340
  return true;
}

2341
static bool initLastBlockReader(SLastBlockReader* pLBlockReader, STableBlockScanInfo* pScanInfo, STsdbReader* pReader) {
2342
  // the last block reader has been initialized for this table.
2343
  if (pLBlockReader->uid == pScanInfo->uid) {
2344
    return hasDataInLastBlock(pLBlockReader);
2345 2346
  }

2347 2348
  if (pLBlockReader->uid != 0) {
    tMergeTreeClose(&pLBlockReader->mergeTree);
2349 2350
  }

2351 2352
  initMemDataIterator(pScanInfo, pReader);
  pLBlockReader->uid = pScanInfo->uid;
2353

H
Hongze Cheng 已提交
2354
  int32_t     step = ASCENDING_TRAVERSE(pLBlockReader->order) ? 1 : -1;
2355 2356 2357
  STimeWindow w = pLBlockReader->window;
  if (ASCENDING_TRAVERSE(pLBlockReader->order)) {
    w.skey = pScanInfo->lastKey + step;
2358
  } else {
2359
    w.ekey = pScanInfo->lastKey + step;
2360 2361
  }

2362 2363 2364
  int32_t code = tMergeTreeOpen(&pLBlockReader->mergeTree, (pLBlockReader->order == TSDB_ORDER_DESC),
                                pReader->pFileReader, pReader->suid, pScanInfo->uid, &w, &pLBlockReader->verRange,
                                pLBlockReader->pInfo, false, pReader->idStr);
2365 2366 2367 2368
  if (code != TSDB_CODE_SUCCESS) {
    return false;
  }

2369
  return nextRowFromLastBlocks(pLBlockReader, pScanInfo, &pReader->verRange);
2370 2371
}

2372
static int64_t getCurrentKeyInLastBlock(SLastBlockReader* pLastBlockReader) {
2373
  TSDBROW row = tMergeTreeGetRow(&pLastBlockReader->mergeTree);
2374
  return TSDBROW_TS(&row);
2375 2376
}

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

2379
bool hasDataInFileBlock(const SBlockData* pBlockData, const SFileBlockDumpInfo* pDumpInfo) {
H
Haojun Liao 已提交
2380
  if ((pBlockData->nRow > 0) && (pBlockData->nRow != pDumpInfo->totalRows)) {
2381
    return false;  // this is an invalid result.
2382
  }
2383
  return pBlockData->nRow > 0 && (!pDumpInfo->allDumped);
2384
}
2385

2386 2387
int32_t mergeRowsInFileBlocks(SBlockData* pBlockData, STableBlockScanInfo* pBlockScanInfo, int64_t key,
                              STsdbReader* pReader) {
2388 2389
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;
  if (tryCopyDistinctRowFromFileBlock(pReader, pBlockData, key, pDumpInfo)) {
2390
    pBlockScanInfo->lastKey = key;
2391 2392
    return TSDB_CODE_SUCCESS;
  } else {
C
Cary Xu 已提交
2393 2394
    TSDBROW fRow = tsdbRowFromBlockData(pBlockData, pDumpInfo->rowIndex);

H
Hongze Cheng 已提交
2395
    SRow*      pTSRow = NULL;
2396 2397
    SRowMerger merge = {0};

H
Hongze Cheng 已提交
2398
    int32_t code = tsdbRowMergerInit(&merge, &fRow, pReader->pSchema);
H
Haojun Liao 已提交
2399 2400 2401 2402
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

2403
    doMergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pReader, &merge);
H
Hongze Cheng 已提交
2404
    code = tsdbRowMergerGetRow(&merge, &pTSRow);
2405 2406 2407 2408
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

2409
    doAppendRowFromTSRow(pReader->pResBlock, pReader, pTSRow, pBlockScanInfo);
2410 2411

    taosMemoryFree(pTSRow);
H
Hongze Cheng 已提交
2412
    tsdbRowMergerClear(&merge);
2413 2414 2415 2416
    return TSDB_CODE_SUCCESS;
  }
}

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

2421
  TSDBROW *pRow = NULL, *piRow = NULL;
2422
  int64_t key = (pBlockData->nRow > 0 && (!pDumpInfo->allDumped)) ? pBlockData->aTSKEY[pDumpInfo->rowIndex] : INT64_MIN;
2423 2424 2425
  if (pBlockScanInfo->iter.hasVal) {
    pRow = getValidMemRow(&pBlockScanInfo->iter, pBlockScanInfo->delSkyline, pReader);
  }
C
Cary Xu 已提交
2426

2427 2428 2429
  if (pBlockScanInfo->iiter.hasVal) {
    piRow = getValidMemRow(&pBlockScanInfo->iiter, pBlockScanInfo->delSkyline, pReader);
  }
C
Cary Xu 已提交
2430

2431 2432 2433 2434
  // two levels of mem-table does contain the valid rows
  if (pRow != NULL && piRow != NULL) {
    return doMergeMultiLevelRows(pReader, pBlockScanInfo, pBlockData, pLastBlockReader);
  }
2435

2436 2437 2438 2439
  // imem + file + last block
  if (pBlockScanInfo->iiter.hasVal) {
    return doMergeBufAndFileRows(pReader, pBlockScanInfo, piRow, &pBlockScanInfo->iiter, key, pLastBlockReader);
  }
2440

2441 2442 2443
  // mem + file + last block
  if (pBlockScanInfo->iter.hasVal) {
    return doMergeBufAndFileRows(pReader, pBlockScanInfo, pRow, &pBlockScanInfo->iter, key, pLastBlockReader);
2444
  }
2445 2446 2447

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

H
Haojun Liao 已提交
2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489
static int32_t loadNeighborIfOverlap(SFileDataBlockInfo* pBlockInfo, STableBlockScanInfo* pBlockScanInfo,
                                     STsdbReader* pReader, bool* loadNeighbor) {
  int32_t     code = TSDB_CODE_SUCCESS;
  int32_t     step = ASCENDING_TRAVERSE(pReader->order) ? 1 : -1;
  int32_t     nextIndex = -1;
  SBlockIndex nxtBIndex = {0};

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

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

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

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

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

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

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

  return code;
}

2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502
static void updateComposedBlockInfo(STsdbReader* pReader, double el, STableBlockScanInfo* pBlockScanInfo) {
  SSDataBlock* pResBlock = pReader->pResBlock;

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

  setComposedBlockFlag(pReader, true);

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

2503
static int32_t buildComposedDataBlock(STsdbReader* pReader) {
H
Haojun Liao 已提交
2504 2505
  int32_t code = TSDB_CODE_SUCCESS;

2506 2507
  SSDataBlock* pResBlock = pReader->pResBlock;

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

2511
  bool    asc = ASCENDING_TRAVERSE(pReader->order);
C
Cary Xu 已提交
2512
  int64_t st = taosGetTimestampUs();
2513
  int32_t step = asc ? 1 : -1;
2514
  double  el = 0;
2515 2516 2517

  STableBlockScanInfo* pBlockScanInfo = NULL;
  if (pBlockInfo != NULL) {
2518 2519
    void* p = taosHashGet(pReader->status.pTableMap, &pBlockInfo->uid, sizeof(pBlockInfo->uid));
    if (p == NULL) {
H
Haojun Liao 已提交
2520
      code = TSDB_CODE_INVALID_PARA;
2521 2522
      tsdbError("failed to locate the uid:%" PRIu64 " in query table uid list, total tables:%d, %s", pBlockInfo->uid,
                taosHashGetSize(pReader->status.pTableMap), pReader->idStr);
H
Haojun Liao 已提交
2523 2524 2525
      goto _end;
    }

H
Hongze Cheng 已提交
2526
    pBlockScanInfo = *(STableBlockScanInfo**)p;
2527

C
Cary Xu 已提交
2528
    SDataBlk* pBlock = getCurrentBlock(&pReader->status.blockIter);
H
Hongze Cheng 已提交
2529
    TSDBKEY   keyInBuf = getCurrentKeyInBuf(pBlockScanInfo, pReader);
C
Cary Xu 已提交
2530 2531

    // it is a clean block, load it directly
H
Hongze Cheng 已提交
2532
    if (isCleanFileDataBlock(pReader, pBlockInfo, pBlock, pBlockScanInfo, keyInBuf, pLastBlockReader) &&
2533
        pBlock->nRow <= pReader->capacity) {
2534
      if (asc || ((!asc) && (!hasDataInLastBlock(pLastBlockReader)))) {
H
Haojun Liao 已提交
2535
        copyBlockDataToSDataBlock(pReader, pBlockScanInfo);
2536 2537

        // record the last key value
H
Hongze Cheng 已提交
2538
        pBlockScanInfo->lastKey = asc ? pBlock->maxKey.ts : pBlock->minKey.ts;
H
Haojun Liao 已提交
2539 2540
        goto _end;
      }
C
Cary Xu 已提交
2541 2542
    }
  } else {  // file blocks not exist
2543
    pBlockScanInfo = *pReader->status.pTableIter;
2544 2545
  }

2546
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;
2547
  SBlockData*         pBlockData = &pReader->status.fileBlockData;
2548

2549
  while (1) {
2550
    bool hasBlockData = false;
2551
    {
2552 2553
      while (pBlockData->nRow > 0 &&
             pBlockData->uid == pBlockScanInfo->uid) {  // find the first qualified row in data block
2554 2555 2556 2557 2558
        if (isValidFileBlockRow(pBlockData, pDumpInfo, pBlockScanInfo, pReader)) {
          hasBlockData = true;
          break;
        }

2559 2560
        pDumpInfo->rowIndex += step;

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

H
Haojun Liao 已提交
2565 2566 2567 2568 2569
          // continue check for the next file block if the last ts in the current block
          // is overlapped with the next neighbor block
          bool loadNeighbor = false;
          code = loadNeighborIfOverlap(pBlockInfo, pBlockScanInfo, pReader, &loadNeighbor);
          if ((!loadNeighbor) || (code != 0)) {
2570 2571
            setBlockAllDumped(pDumpInfo, pBlock->maxKey.ts, pReader->order);
            break;
2572
          }
2573 2574
        }
      }
2575
    }
2576

2577
    // no data in last block and block, no need to proceed.
2578
    if (hasBlockData == false) {
2579
      break;
2580 2581
    }

2582
    buildComposedDataBlockImpl(pReader, pBlockScanInfo, pBlockData, pLastBlockReader);
2583

2584
    // currently loaded file data block is consumed
2585
    if ((pBlockData->nRow > 0) && (pDumpInfo->rowIndex >= pBlockData->nRow || pDumpInfo->rowIndex < 0)) {
H
Hongze Cheng 已提交
2586
      SDataBlk* pBlock = getCurrentBlock(&pReader->status.blockIter);
2587
      setBlockAllDumped(pDumpInfo, pBlock->maxKey.ts, pReader->order);
2588 2589 2590 2591 2592
      break;
    }

    if (pResBlock->info.rows >= pReader->capacity) {
      break;
2593 2594 2595
    }
  }

H
Hongze Cheng 已提交
2596
_end:
2597 2598
  el = (taosGetTimestampUs() - st) / 1000.0;
  updateComposedBlockInfo(pReader, el, pBlockScanInfo);
2599

2600 2601 2602
  if (pResBlock->info.rows > 0) {
    tsdbDebug("%p uid:%" PRIu64 ", composed data block created, brange:%" PRIu64 "-%" PRIu64
              " rows:%d, elapsed time:%.2f ms %s",
H
Haojun Liao 已提交
2603
              pReader, pResBlock->info.id.uid, pResBlock->info.window.skey, pResBlock->info.window.ekey,
H
Haojun Liao 已提交
2604
              pResBlock->info.rows, el, pReader->idStr);
2605
  }
2606

H
Haojun Liao 已提交
2607
  return code;
2608 2609 2610 2611
}

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

dengyihao's avatar
dengyihao 已提交
2612 2613
int32_t initDelSkylineIterator(STableBlockScanInfo* pBlockScanInfo, STsdbReader* pReader, STbData* pMemTbData,
                               STbData* piMemTbData) {
2614 2615 2616
  if (pBlockScanInfo->delSkyline != NULL) {
    return TSDB_CODE_SUCCESS;
  }
2617

2618
  int32_t code = 0;
2619 2620
  SArray* pDelData = taosArrayInit(4, sizeof(SDelData));

H
Hongze Cheng 已提交
2621
  SDelFile* pDelFile = pReader->pReadSnap->fs.pDelFile;
2622
  if (pDelFile && taosArrayGetSize(pReader->pDelIdx) > 0) {
2623
    SDelIdx  idx = {.suid = pReader->suid, .uid = pBlockScanInfo->uid};
2624
    SDelIdx* pIdx = taosArraySearch(pReader->pDelIdx, &idx, tCmprDelIdx, TD_EQ);
2625

H
Haojun Liao 已提交
2626
    if (pIdx != NULL) {
2627
      code = tsdbReadDelData(pReader->pDelFReader, pIdx, pDelData);
2628 2629 2630 2631
    }

    if (code != TSDB_CODE_SUCCESS) {
      goto _err;
2632
    }
2633
  }
2634

2635 2636 2637 2638 2639 2640 2641
  SDelData* p = NULL;
  if (pMemTbData != NULL) {
    p = pMemTbData->pHead;
    while (p) {
      taosArrayPush(pDelData, p);
      p = p->pNext;
    }
2642 2643
  }

2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657
  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 已提交
2658 2659
  pBlockScanInfo->iter.index =
      ASCENDING_TRAVERSE(pReader->order) ? 0 : taosArrayGetSize(pBlockScanInfo->delSkyline) - 1;
2660 2661
  pBlockScanInfo->iiter.index = pBlockScanInfo->iter.index;
  pBlockScanInfo->fileDelIndex = pBlockScanInfo->iter.index;
2662
  pBlockScanInfo->lastBlockDelIndex = pBlockScanInfo->iter.index;
2663 2664
  return code;

2665 2666 2667
_err:
  taosArrayDestroy(pDelData);
  return code;
2668 2669
}

C
Cary Xu 已提交
2670
TSDBKEY getCurrentKeyInBuf(STableBlockScanInfo* pScanInfo, STsdbReader* pReader) {
H
Hongze Cheng 已提交
2671
  TSDBKEY  key = {.ts = TSKEY_INITIAL_VAL};
2672
  TSDBROW* pRow = getValidMemRow(&pScanInfo->iter, pScanInfo->delSkyline, pReader);
2673
  if (pRow != NULL) {
2674 2675 2676
    key = TSDBROW_KEY(pRow);
  }

2677
  pRow = getValidMemRow(&pScanInfo->iiter, pScanInfo->delSkyline, pReader);
2678
  if (pRow != NULL) {
2679 2680 2681 2682 2683 2684 2685 2686 2687
    TSDBKEY k = TSDBROW_KEY(pRow);
    if (key.ts > k.ts) {
      key = k;
    }
  }

  return key;
}

2688
static int32_t moveToNextFile(STsdbReader* pReader, SBlockNumber* pBlockNum) {
H
Haojun Liao 已提交
2689
  SReaderStatus* pStatus = &pReader->status;
2690
  pBlockNum->numOfBlocks = 0;
2691
  pBlockNum->numOfLastFiles = 0;
2692

2693
  size_t  numOfTables = taosHashGetSize(pReader->status.pTableMap);
2694
  SArray* pIndexList = taosArrayInit(numOfTables, sizeof(SBlockIdx));
H
Haojun Liao 已提交
2695 2696

  while (1) {
2697
    bool hasNext = filesetIteratorNext(&pStatus->fileIter, pReader);
2698
    if (!hasNext) {  // no data files on disk
H
Haojun Liao 已提交
2699 2700 2701
      break;
    }

H
Haojun Liao 已提交
2702
    taosArrayClear(pIndexList);
H
Haojun Liao 已提交
2703 2704
    int32_t code = doLoadBlockIndex(pReader, pReader->pFileReader, pIndexList);
    if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
2705
      taosArrayDestroy(pIndexList);
H
Haojun Liao 已提交
2706 2707 2708
      return code;
    }

H
Hongze Cheng 已提交
2709
    if (taosArrayGetSize(pIndexList) > 0 || pReader->pFileReader->pSet->nSttF > 0) {
2710
      code = doLoadFileBlock(pReader, pIndexList, pBlockNum);
H
Haojun Liao 已提交
2711
      if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
2712
        taosArrayDestroy(pIndexList);
H
Haojun Liao 已提交
2713 2714 2715
        return code;
      }

2716
      if (pBlockNum->numOfBlocks + pBlockNum->numOfLastFiles > 0) {
H
Haojun Liao 已提交
2717 2718 2719
        break;
      }
    }
2720

H
Haojun Liao 已提交
2721 2722 2723
    // no blocks in current file, try next files
  }

H
Haojun Liao 已提交
2724
  taosArrayDestroy(pIndexList);
2725

H
Haojun Liao 已提交
2726 2727 2728 2729 2730 2731 2732
  if (pReader->pReadSnap != NULL) {
    SDelFile* pDelFile = pReader->pReadSnap->fs.pDelFile;
    if (pReader->pDelFReader == NULL && pDelFile != NULL) {
      int32_t code = tsdbDelFReaderOpen(&pReader->pDelFReader, pDelFile, pReader->pTsdb);
      if (code != TSDB_CODE_SUCCESS) {
        return code;
      }
2733

H
Haojun Liao 已提交
2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744
      pReader->pDelIdx = taosArrayInit(4, sizeof(SDelIdx));
      if (pReader->pDelIdx == NULL) {
        code = TSDB_CODE_OUT_OF_MEMORY;
        return code;
      }

      code = tsdbReadDelIdx(pReader->pDelFReader, pReader->pDelIdx);
      if (code != TSDB_CODE_SUCCESS) {
        taosArrayDestroy(pReader->pDelIdx);
        return code;
      }
2745 2746 2747
    }
  }

H
Haojun Liao 已提交
2748 2749 2750
  return TSDB_CODE_SUCCESS;
}

2751
static int32_t uidComparFunc(const void* p1, const void* p2) {
2752 2753
  uint64_t pu1 = *(uint64_t*)p1;
  uint64_t pu2 = *(uint64_t*)p2;
2754 2755 2756
  if (pu1 == pu2) {
    return 0;
  } else {
2757
    return (pu1 < pu2) ? -1 : 1;
2758 2759
  }
}
2760

2761
static void extractOrderedTableUidList(SUidOrderCheckInfo* pOrderCheckInfo, SReaderStatus* pStatus) {
2762 2763 2764 2765
  int32_t index = 0;
  int32_t total = taosHashGetSize(pStatus->pTableMap);

  void* p = taosHashIterate(pStatus->pTableMap, NULL);
2766
  while (p != NULL) {
H
Hongze Cheng 已提交
2767
    STableBlockScanInfo* pScanInfo = *(STableBlockScanInfo**)p;
2768 2769 2770 2771 2772 2773 2774
    pOrderCheckInfo->tableUidList[index++] = pScanInfo->uid;
    p = taosHashIterate(pStatus->pTableMap, p);
  }

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

2775
static int32_t initOrderCheckInfo(SUidOrderCheckInfo* pOrderCheckInfo, SReaderStatus* pStatus) {
2776 2777 2778 2779
  int32_t total = taosHashGetSize(pStatus->pTableMap);
  if (total == 0) {
    return TSDB_CODE_SUCCESS;
  }
2780

2781
  if (pOrderCheckInfo->tableUidList == NULL) {
2782 2783 2784 2785 2786 2787
    pOrderCheckInfo->currentIndex = 0;
    pOrderCheckInfo->tableUidList = taosMemoryMalloc(total * sizeof(uint64_t));
    if (pOrderCheckInfo->tableUidList == NULL) {
      return TSDB_CODE_OUT_OF_MEMORY;
    }

2788
    extractOrderedTableUidList(pOrderCheckInfo, pStatus);
2789 2790 2791
    uint64_t uid = pOrderCheckInfo->tableUidList[0];
    pStatus->pTableIter = taosHashGet(pStatus->pTableMap, &uid, sizeof(uid));
  } else {
2792 2793
    if (pStatus->pTableIter == NULL) {  // it is the last block of a new file
      pOrderCheckInfo->currentIndex = 0;
2794 2795
      uint64_t uid = pOrderCheckInfo->tableUidList[pOrderCheckInfo->currentIndex];
      pStatus->pTableIter = taosHashGet(pStatus->pTableMap, &uid, sizeof(uid));
2796 2797

      // the tableMap has already updated
2798
      if (pStatus->pTableIter == NULL) {
2799
        void* p = taosMemoryRealloc(pOrderCheckInfo->tableUidList, total * sizeof(uint64_t));
2800 2801 2802 2803 2804 2805 2806 2807 2808
        if (p == NULL) {
          return TSDB_CODE_OUT_OF_MEMORY;
        }

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

        uid = pOrderCheckInfo->tableUidList[0];
        pStatus->pTableIter = taosHashGet(pStatus->pTableMap, &uid, sizeof(uid));
2809
      }
2810
    }
2811
  }
2812

2813 2814 2815
  return TSDB_CODE_SUCCESS;
}

2816
static bool moveToNextTable(SUidOrderCheckInfo* pOrderedCheckInfo, SReaderStatus* pStatus) {
2817 2818 2819 2820 2821 2822 2823 2824
  pOrderedCheckInfo->currentIndex += 1;
  if (pOrderedCheckInfo->currentIndex >= taosHashGetSize(pStatus->pTableMap)) {
    pStatus->pTableIter = NULL;
    return false;
  }

  uint64_t uid = pOrderedCheckInfo->tableUidList[pOrderedCheckInfo->currentIndex];
  pStatus->pTableIter = taosHashGet(pStatus->pTableMap, &uid, sizeof(uid));
H
Haojun Liao 已提交
2825 2826 2827 2828
  if (pStatus->pTableIter == NULL) {
    return false;
  }

2829 2830 2831
  return true;
}

2832
static int32_t doLoadLastBlockSequentially(STsdbReader* pReader) {
2833
  SReaderStatus*    pStatus = &pReader->status;
2834 2835
  SLastBlockReader* pLastBlockReader = pStatus->fileIter.pLastBlockReader;

2836 2837
  SUidOrderCheckInfo* pOrderedCheckInfo = &pStatus->uidCheckInfo;
  int32_t             code = initOrderCheckInfo(pOrderedCheckInfo, pStatus);
2838
  if (code != TSDB_CODE_SUCCESS || (taosHashGetSize(pStatus->pTableMap) == 0)) {
2839 2840
    return code;
  }
2841

2842 2843
  SSDataBlock* pResBlock = pReader->pResBlock;

2844
  while (1) {
2845
    // load the last data block of current table
H
Hongze Cheng 已提交
2846
    STableBlockScanInfo* pScanInfo = *(STableBlockScanInfo**)pStatus->pTableIter;
2847 2848

    bool hasVal = initLastBlockReader(pLastBlockReader, pScanInfo, pReader);
2849
    if (!hasVal) {
2850 2851
      bool hasNexTable = moveToNextTable(pOrderedCheckInfo, pStatus);
      if (!hasNexTable) {
2852 2853
        return TSDB_CODE_SUCCESS;
      }
2854

2855
      continue;
2856 2857
    }

2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870
    int64_t st = taosGetTimestampUs();
    while (1) {
      bool hasBlockLData = hasDataInLastBlock(pLastBlockReader);

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

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

2873 2874 2875 2876 2877 2878 2879 2880
    double el = (taosGetTimestampUs() - st) / 1000.0;
    updateComposedBlockInfo(pReader, el, pScanInfo);

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

2884
    // current table is exhausted, let's try next table
2885 2886
    bool hasNexTable = moveToNextTable(pOrderedCheckInfo, pStatus);
    if (!hasNexTable) {
2887 2888
      return TSDB_CODE_SUCCESS;
    }
2889 2890 2891
  }
}

2892
static int32_t doBuildDataBlock(STsdbReader* pReader) {
H
Hongze Cheng 已提交
2893 2894
  int32_t   code = TSDB_CODE_SUCCESS;
  SDataBlk* pBlock = NULL;
2895 2896 2897

  SReaderStatus*       pStatus = &pReader->status;
  SDataBlockIter*      pBlockIter = &pStatus->blockIter;
2898 2899 2900
  STableBlockScanInfo* pScanInfo = NULL;
  SFileDataBlockInfo*  pBlockInfo = getCurrentBlockInfo(pBlockIter);
  SLastBlockReader*    pLastBlockReader = pReader->status.fileIter.pLastBlockReader;
2901

2902
  if (pBlockInfo != NULL) {
H
Hongze Cheng 已提交
2903 2904
    pScanInfo =
        *(STableBlockScanInfo**)taosHashGet(pReader->status.pTableMap, &pBlockInfo->uid, sizeof(pBlockInfo->uid));
2905
  } else {
2906
    pScanInfo = *pReader->status.pTableIter;
2907 2908
  }

H
Haojun Liao 已提交
2909
  if (pScanInfo == NULL) {
H
Haojun Liao 已提交
2910
    tsdbError("failed to get table scan-info, %s", pReader->idStr);
H
Haojun Liao 已提交
2911 2912 2913 2914
    code = TSDB_CODE_INVALID_PARA;
    return code;
  }

2915
  if (pBlockInfo != NULL) {
2916
    pBlock = getCurrentBlock(pBlockIter);
2917 2918
  }

2919
  initLastBlockReader(pLastBlockReader, pScanInfo, pReader);
C
Cary Xu 已提交
2920
  TSDBKEY keyInBuf = getCurrentKeyInBuf(pScanInfo, pReader);
2921

2922
  if (pBlockInfo == NULL) {  // build data block from last data file
2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949
    SBlockData* pBData = &pReader->status.fileBlockData;
    tBlockDataReset(pBData);

    SSDataBlock* pResBlock = pReader->pResBlock;
    tsdbDebug("load data in last block firstly, due to desc scan data, %s", pReader->idStr);

    int64_t st = taosGetTimestampUs();

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

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

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

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

    if (pResBlock->info.rows > 0) {
      tsdbDebug("%p uid:%" PRIu64 ", composed data block created, brange:%" PRIu64 "-%" PRIu64
X
Xiaoyu Wang 已提交
2950
                " rows:%d, elapsed time:%.2f ms %s",
2951 2952 2953
                pReader, pResBlock->info.id.uid, pResBlock->info.window.skey, pResBlock->info.window.ekey,
                pResBlock->info.rows, el, pReader->idStr);
    }
C
Cary Xu 已提交
2954
  } else if (fileBlockShouldLoad(pReader, pBlockInfo, pBlock, pScanInfo, keyInBuf, pLastBlockReader)) {
2955
    code = doLoadFileBlockData(pReader, pBlockIter, &pStatus->fileBlockData, pScanInfo->uid);
2956 2957
    if (code != TSDB_CODE_SUCCESS) {
      return code;
2958 2959 2960
    }

    // build composed data block
2961
    code = buildComposedDataBlock(pReader);
C
Cary Xu 已提交
2962
  } else if (bufferDataInFileBlockGap(pReader->order, keyInBuf, pBlock)) {
2963
    // data in memory that are earlier than current file block
2964
    // rows in buffer should be less than the file block in asc, greater than file block in desc
2965
    int64_t endKey = (ASCENDING_TRAVERSE(pReader->order)) ? pBlock->minKey.ts : pBlock->maxKey.ts;
2966
    code = buildDataBlockFromBuf(pReader, pScanInfo, endKey);
2967 2968 2969 2970
  } else {
    if (hasDataInLastBlock(pLastBlockReader) && !ASCENDING_TRAVERSE(pReader->order)) {
      // only return the rows in last block
      int64_t tsLast = getCurrentKeyInLastBlock(pLastBlockReader);
H
Hongze Cheng 已提交
2971
      ASSERT(tsLast >= pBlock->maxKey.ts);
2972

2973 2974 2975 2976
      SBlockData* pBData = &pReader->status.fileBlockData;
      tBlockDataReset(pBData);

      SSDataBlock* pResBlock = pReader->pResBlock;
2977
      tsdbDebug("load data in last block firstly, due to desc scan data, %s", pReader->idStr);
2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999

      int64_t st = taosGetTimestampUs();

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

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

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

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

      if (pResBlock->info.rows > 0) {
        tsdbDebug("%p uid:%" PRIu64 ", composed data block created, brange:%" PRIu64 "-%" PRIu64
X
Xiaoyu Wang 已提交
3000
                  " rows:%d, elapsed time:%.2f ms %s",
3001 3002 3003
                  pReader, pResBlock->info.id.uid, pResBlock->info.window.skey, pResBlock->info.window.ekey,
                  pResBlock->info.rows, el, pReader->idStr);
      }
H
Hongze Cheng 已提交
3004
    } else {  // whole block is required, return it directly
3005 3006
      SDataBlockInfo* pInfo = &pReader->pResBlock->info;
      pInfo->rows = pBlock->nRow;
H
Haojun Liao 已提交
3007
      pInfo->id.uid = pScanInfo->uid;
3008 3009 3010
      pInfo->window = (STimeWindow){.skey = pBlock->minKey.ts, .ekey = pBlock->maxKey.ts};
      setComposedBlockFlag(pReader, false);
      setBlockAllDumped(&pStatus->fBlockDumpInfo, pBlock->maxKey.ts, pReader->order);
3011

3012
      // update the last key for the corresponding table
H
Hongze Cheng 已提交
3013
      pScanInfo->lastKey = ASCENDING_TRAVERSE(pReader->order) ? pInfo->window.ekey : pInfo->window.skey;
3014
    }
3015 3016 3017 3018 3019
  }

  return code;
}

H
Haojun Liao 已提交
3020
static int32_t buildBlockFromBufferSequentially(STsdbReader* pReader) {
3021 3022
  SReaderStatus* pStatus = &pReader->status;

3023
  while (1) {
3024 3025 3026
    if (pStatus->pTableIter == NULL) {
      pStatus->pTableIter = taosHashIterate(pStatus->pTableMap, NULL);
      if (pStatus->pTableIter == NULL) {
H
Haojun Liao 已提交
3027
        return TSDB_CODE_SUCCESS;
3028 3029 3030
      }
    }

3031 3032
    STableBlockScanInfo** pBlockScanInfo = pStatus->pTableIter;
    initMemDataIterator(*pBlockScanInfo, pReader);
3033

3034
    int64_t endKey = (ASCENDING_TRAVERSE(pReader->order)) ? INT64_MAX : INT64_MIN;
3035
    int32_t code = buildDataBlockFromBuf(pReader, *pBlockScanInfo, endKey);
H
Haojun Liao 已提交
3036 3037 3038 3039
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

3040
    if (pReader->pResBlock->info.rows > 0) {
H
Haojun Liao 已提交
3041
      return TSDB_CODE_SUCCESS;
3042 3043 3044 3045 3046
    }

    // current table is exhausted, let's try the next table
    pStatus->pTableIter = taosHashIterate(pStatus->pTableMap, pStatus->pTableIter);
    if (pStatus->pTableIter == NULL) {
H
Haojun Liao 已提交
3047
      return TSDB_CODE_SUCCESS;
3048 3049 3050 3051
    }
  }
}

3052
// set the correct start position in case of the first/last file block, according to the query time window
3053
static void initBlockDumpInfo(STsdbReader* pReader, SDataBlockIter* pBlockIter) {
3054 3055 3056 3057 3058 3059 3060 3061
  int64_t             lastKey = ASCENDING_TRAVERSE(pReader->order) ? INT64_MIN : INT64_MAX;
  SDataBlk*           pBlock = getCurrentBlock(pBlockIter);
  SFileDataBlockInfo* pBlockInfo = getCurrentBlockInfo(pBlockIter);
  if (pBlockInfo) {
    STableBlockScanInfo* pScanInfo = taosHashGet(pBlockIter->pTableMap, &pBlockInfo->uid, sizeof(pBlockInfo->uid));
    if (pScanInfo) {
      lastKey = pScanInfo->lastKey;
    }
3062
  }
3063 3064 3065
  SReaderStatus* pStatus = &pReader->status;

  SFileBlockDumpInfo* pDumpInfo = &pStatus->fBlockDumpInfo;
3066 3067 3068

  pDumpInfo->totalRows = pBlock->nRow;
  pDumpInfo->allDumped = false;
3069
  pDumpInfo->rowIndex = ASCENDING_TRAVERSE(pReader->order) ? 0 : pBlock->nRow - 1;
3070
  pDumpInfo->lastKey = lastKey;
3071 3072
}

3073
static int32_t initForFirstBlockInFile(STsdbReader* pReader, SDataBlockIter* pBlockIter) {
3074 3075
  SBlockNumber num = {0};

3076
  int32_t code = moveToNextFile(pReader, &num);
3077 3078 3079 3080 3081
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

  // all data files are consumed, try data in buffer
3082
  if (num.numOfBlocks + num.numOfLastFiles == 0) {
3083 3084 3085 3086 3087
    pReader->status.loadFromFile = false;
    return code;
  }

  // initialize the block iterator for a new fileset
3088 3089
  if (num.numOfBlocks > 0) {
    code = initBlockIterator(pReader, pBlockIter, num.numOfBlocks);
H
Hongze Cheng 已提交
3090
  } else {  // no block data, only last block exists
3091
    tBlockDataReset(&pReader->status.fileBlockData);
3092
    resetDataBlockIterator(pBlockIter, pReader->order);
3093
  }
3094 3095

  // set the correct start position according to the query time window
3096
  initBlockDumpInfo(pReader, pBlockIter);
3097 3098 3099
  return code;
}

3100
static bool fileBlockPartiallyRead(SFileBlockDumpInfo* pDumpInfo, bool asc) {
3101 3102
  return (!pDumpInfo->allDumped) &&
         ((pDumpInfo->rowIndex > 0 && asc) || (pDumpInfo->rowIndex < (pDumpInfo->totalRows - 1) && (!asc)));
3103 3104
}

3105
static int32_t buildBlockFromFiles(STsdbReader* pReader) {
H
Haojun Liao 已提交
3106
  int32_t code = TSDB_CODE_SUCCESS;
3107 3108
  bool    asc = ASCENDING_TRAVERSE(pReader->order);

3109 3110
  SDataBlockIter* pBlockIter = &pReader->status.blockIter;

3111
  if (pBlockIter->numOfBlocks == 0) {
H
Hongze Cheng 已提交
3112
  _begin:
3113 3114 3115 3116 3117
    code = doLoadLastBlockSequentially(pReader);
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

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

3122
    // all data blocks are checked in this last block file, now let's try the next file
3123 3124 3125 3126 3127 3128 3129 3130
    if (pReader->status.pTableIter == NULL) {
      code = initForFirstBlockInFile(pReader, pBlockIter);

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

3131
      // this file does not have data files, let's start check the last block file if exists
3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146
      if (pBlockIter->numOfBlocks == 0) {
        goto _begin;
      }
    }

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

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

3147
  while (1) {
3148 3149
    SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;

3150
    if (fileBlockPartiallyRead(pDumpInfo, asc)) {  // file data block is partially loaded
3151
      code = buildComposedDataBlock(pReader);
3152 3153 3154 3155
    } else {
      // current block are exhausted, try the next file block
      if (pDumpInfo->allDumped) {
        // try next data block in current file
H
Haojun Liao 已提交
3156
        bool hasNext = blockIteratorNext(&pReader->status.blockIter, pReader->idStr);
3157 3158
        if (hasNext) {  // check for the next block in the block accessed order list
          initBlockDumpInfo(pReader, pBlockIter);
3159
        } else {
H
Haojun Liao 已提交
3160
          if (pReader->status.pCurrentFileset->nSttF > 0) {
3161
            // data blocks in current file are exhausted, let's try the next file now
H
Haojun Liao 已提交
3162 3163 3164 3165 3166 3167
            SBlockData* pBlockData = &pReader->status.fileBlockData;
            if (pBlockData->uid != 0) {
              tBlockDataClear(pBlockData);
            }

            tBlockDataReset(pBlockData);
3168 3169 3170 3171
            resetDataBlockIterator(pBlockIter, pReader->order);
            goto _begin;
          } else {
            code = initForFirstBlockInFile(pReader, pBlockIter);
3172

3173 3174 3175 3176
            // error happens or all the data files are completely checked
            if ((code != TSDB_CODE_SUCCESS) || (pReader->status.loadFromFile == false)) {
              return code;
            }
3177

3178 3179 3180 3181
            // this file does not have blocks, let's start check the last block file
            if (pBlockIter->numOfBlocks == 0) {
              goto _begin;
            }
3182
          }
3183
        }
H
Haojun Liao 已提交
3184
      }
3185 3186

      code = doBuildDataBlock(pReader);
3187 3188
    }

3189 3190 3191 3192 3193 3194 3195 3196
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

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

3199 3200
static STsdb* getTsdbByRetentions(SVnode* pVnode, TSKEY winSKey, SRetention* retentions, const char* idStr,
                                  int8_t* pLevel) {
3201
  if (VND_IS_RSMA(pVnode)) {
3202
    int8_t  level = 0;
3203 3204
    int8_t  precision = pVnode->config.tsdbCfg.precision;
    int64_t now = taosGetTimestamp(precision);
H
Haojun Liao 已提交
3205 3206 3207
    int64_t offset = tsQueryRsmaTolerance * ((precision == TSDB_TIME_PRECISION_MILLI)   ? 1L
                                             : (precision == TSDB_TIME_PRECISION_MICRO) ? 1000L
                                                                                        : 1000000L);
3208

3209
    for (int8_t i = 0; i < TSDB_RETENTION_MAX; ++i) {
3210 3211 3212 3213 3214 3215 3216
      SRetention* pRetention = retentions + level;
      if (pRetention->keep <= 0) {
        if (level > 0) {
          --level;
        }
        break;
      }
3217
      if ((now - pRetention->keep) <= (winSKey + offset)) {
3218 3219 3220 3221 3222
        break;
      }
      ++level;
    }

3223
    const char* str = (idStr != NULL) ? idStr : "";
3224 3225

    if (level == TSDB_RETENTION_L0) {
3226
      *pLevel = TSDB_RETENTION_L0;
C
Cary Xu 已提交
3227
      tsdbDebug("vgId:%d, rsma level %d is selected to query %s", TD_VID(pVnode), TSDB_RETENTION_L0, str);
3228 3229
      return VND_RSMA0(pVnode);
    } else if (level == TSDB_RETENTION_L1) {
3230
      *pLevel = TSDB_RETENTION_L1;
C
Cary Xu 已提交
3231
      tsdbDebug("vgId:%d, rsma level %d is selected to query %s", TD_VID(pVnode), TSDB_RETENTION_L1, str);
3232 3233
      return VND_RSMA1(pVnode);
    } else {
3234
      *pLevel = TSDB_RETENTION_L2;
C
Cary Xu 已提交
3235
      tsdbDebug("vgId:%d, rsma level %d is selected to query %s", TD_VID(pVnode), TSDB_RETENTION_L2, str);
3236 3237 3238 3239 3240 3241 3242
      return VND_RSMA2(pVnode);
    }
  }

  return VND_TSDB(pVnode);
}

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

  int64_t endVer = 0;
L
Liu Jicong 已提交
3247 3248
  if (pCond->endVersion ==
      -1) {  // user not specified end version, set current maximum version of vnode as the endVersion
H
Haojun Liao 已提交
3249 3250
    endVer = pVnode->state.applied;
  } else {
L
Liu Jicong 已提交
3251
    endVer = (pCond->endVersion > pVnode->state.applied) ? pVnode->state.applied : pCond->endVersion;
3252 3253
  }

H
Haojun Liao 已提交
3254
  return (SVersionRange){.minVer = startVer, .maxVer = endVer};
3255 3256
}

3257
bool hasBeenDropped(const SArray* pDelList, int32_t* index, TSDBKEY* pKey, int32_t order, SVersionRange* pVerRange) {
3258 3259 3260
  if (pDelList == NULL) {
    return false;
  }
H
Haojun Liao 已提交
3261

L
Liu Jicong 已提交
3262 3263 3264
  size_t  num = taosArrayGetSize(pDelList);
  bool    asc = ASCENDING_TRAVERSE(order);
  int32_t step = asc ? 1 : -1;
3265

3266 3267 3268 3269 3270 3271
  if (asc) {
    if (*index >= num - 1) {
      TSDBKEY* last = taosArrayGetLast(pDelList);
      ASSERT(pKey->ts >= last->ts);

      if (pKey->ts > last->ts) {
3272
        return false;
3273 3274
      } else if (pKey->ts == last->ts) {
        TSDBKEY* prev = taosArrayGet(pDelList, num - 2);
3275 3276
        return (prev->version >= pKey->version && prev->version <= pVerRange->maxVer &&
                prev->version >= pVerRange->minVer);
3277 3278
      }
    } else {
3279 3280 3281 3282 3283 3284 3285
      TSDBKEY* pCurrent = taosArrayGet(pDelList, *index);
      TSDBKEY* pNext = taosArrayGet(pDelList, (*index) + 1);

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

3286 3287
      if (pCurrent->ts <= pKey->ts && pNext->ts >= pKey->ts && pCurrent->version >= pKey->version &&
          pVerRange->maxVer >= pCurrent->version) {
3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302
        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;
          }

3303 3304
          if (pCurrent->ts <= pKey->ts && pNext->ts >= pKey->ts && pCurrent->version >= pKey->version &&
              pVerRange->maxVer >= pCurrent->version) {
3305 3306 3307 3308 3309 3310
            return true;
          }
        }
      }

      return false;
3311 3312
    }
  } else {
3313 3314
    if (*index <= 0) {
      TSDBKEY* pFirst = taosArrayGet(pDelList, 0);
3315

3316 3317 3318 3319 3320 3321 3322
      if (pKey->ts < pFirst->ts) {
        return false;
      } else if (pKey->ts == pFirst->ts) {
        return pFirst->version >= pKey->version;
      } else {
        ASSERT(0);
      }
3323
    } else {
3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350
      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;
          }
        }
3351 3352 3353 3354 3355
      }

      return false;
    }
  }
3356 3357

  return false;
3358 3359
}

3360
TSDBROW* getValidMemRow(SIterInfo* pIter, const SArray* pDelList, STsdbReader* pReader) {
3361
  if (!pIter->hasVal) {
H
Haojun Liao 已提交
3362 3363
    return NULL;
  }
H
Hongze Cheng 已提交
3364

3365
  TSDBROW* pRow = tsdbTbDataIterGet(pIter->iter);
H
Hongze Cheng 已提交
3366 3367
  TSDBKEY  key = TSDBROW_KEY(pRow);

3368
  if (outOfTimeWindow(key.ts, &pReader->window)) {
3369
    pIter->hasVal = false;
H
Haojun Liao 已提交
3370 3371
    return NULL;
  }
H
Hongze Cheng 已提交
3372

3373
  // it is a valid data version
dengyihao's avatar
dengyihao 已提交
3374
  if ((key.version <= pReader->verRange.maxVer && key.version >= pReader->verRange.minVer) &&
3375
      (!hasBeenDropped(pDelList, &pIter->index, &key, pReader->order, &pReader->verRange))) {
H
Haojun Liao 已提交
3376 3377
    return pRow;
  }
H
Hongze Cheng 已提交
3378

3379
  while (1) {
3380 3381
    pIter->hasVal = tsdbTbDataIterNext(pIter->iter);
    if (!pIter->hasVal) {
H
Haojun Liao 已提交
3382 3383
      return NULL;
    }
H
Hongze Cheng 已提交
3384

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

H
Haojun Liao 已提交
3387
    key = TSDBROW_KEY(pRow);
3388
    if (outOfTimeWindow(key.ts, &pReader->window)) {
3389
      pIter->hasVal = false;
H
Haojun Liao 已提交
3390 3391
      return NULL;
    }
H
Hongze Cheng 已提交
3392

dengyihao's avatar
dengyihao 已提交
3393
    if (key.version <= pReader->verRange.maxVer && key.version >= pReader->verRange.minVer &&
3394
        (!hasBeenDropped(pDelList, &pIter->index, &key, pReader->order, &pReader->verRange))) {
H
Haojun Liao 已提交
3395 3396 3397 3398
      return pRow;
    }
  }
}
H
Hongze Cheng 已提交
3399

3400 3401
int32_t doMergeRowsInBuf(SIterInfo* pIter, uint64_t uid, int64_t ts, SArray* pDelList, SRowMerger* pMerger,
                         STsdbReader* pReader) {
H
Haojun Liao 已提交
3402
  while (1) {
3403 3404
    pIter->hasVal = tsdbTbDataIterNext(pIter->iter);
    if (!pIter->hasVal) {
H
Haojun Liao 已提交
3405 3406
      break;
    }
H
Hongze Cheng 已提交
3407

3408
    // data exists but not valid
3409
    TSDBROW* pRow = getValidMemRow(pIter, pDelList, pReader);
3410 3411 3412 3413 3414
    if (pRow == NULL) {
      break;
    }

    // ts is not identical, quit
H
Haojun Liao 已提交
3415
    TSDBKEY k = TSDBROW_KEY(pRow);
3416
    if (k.ts != ts) {
H
Haojun Liao 已提交
3417 3418 3419
      break;
    }

3420 3421 3422 3423 3424
    if (pRow->type == TSDBROW_ROW_FMT) {
      STSchema* pTSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(pRow), pReader, uid);
      if (pTSchema == NULL) {
        return terrno;
      }
H
Haojun Liao 已提交
3425

3426 3427 3428 3429
      tsdbRowMergerAdd(pMerger, pRow, pTSchema);
    } else {  // column format
      tsdbRowMerge(pMerger, pRow);
    }
H
Haojun Liao 已提交
3430 3431 3432 3433 3434
  }

  return TSDB_CODE_SUCCESS;
}

3435
static int32_t doMergeRowsInFileBlockImpl(SBlockData* pBlockData, int32_t rowIndex, int64_t key, SRowMerger* pMerger,
3436
                                          SVersionRange* pVerRange, int32_t step) {
3437
  while (rowIndex < pBlockData->nRow && rowIndex >= 0 && pBlockData->aTSKEY[rowIndex] == key) {
3438
    if (pBlockData->aVersion[rowIndex] > pVerRange->maxVer || pBlockData->aVersion[rowIndex] < pVerRange->minVer) {
3439
      rowIndex += step;
3440 3441 3442 3443
      continue;
    }

    TSDBROW fRow = tsdbRowFromBlockData(pBlockData, rowIndex);
H
Hongze Cheng 已提交
3444
    tsdbRowMerge(pMerger, &fRow);
3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455
    rowIndex += step;
  }

  return rowIndex;
}

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

H
Hongze Cheng 已提交
3456
static int32_t checkForNeighborFileBlock(STsdbReader* pReader, STableBlockScanInfo* pScanInfo, SDataBlk* pBlock,
3457 3458
                                         SFileDataBlockInfo* pFBlock, SRowMerger* pMerger, int64_t key,
                                         CHECK_FILEBLOCK_STATE* state) {
3459
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;
3460
  SBlockData*         pBlockData = &pReader->status.fileBlockData;
3461

3462
  *state = CHECK_FILEBLOCK_QUIT;
3463
  int32_t step = ASCENDING_TRAVERSE(pReader->order) ? 1 : -1;
3464

3465
  bool    loadNeighbor = true;
H
Haojun Liao 已提交
3466
  int32_t code = loadNeighborIfOverlap(pFBlock, pScanInfo, pReader, &loadNeighbor);
3467

H
Haojun Liao 已提交
3468
  if (loadNeighbor && (code == TSDB_CODE_SUCCESS)) {
3469 3470
    pDumpInfo->rowIndex =
        doMergeRowsInFileBlockImpl(pBlockData, pDumpInfo->rowIndex, key, pMerger, &pReader->verRange, step);
H
Haojun Liao 已提交
3471
    if (pDumpInfo->rowIndex >= pDumpInfo->totalRows) {
3472 3473 3474 3475
      *state = CHECK_FILEBLOCK_CONT;
    }
  }

H
Haojun Liao 已提交
3476
  return code;
3477 3478
}

3479 3480
int32_t doMergeRowsInFileBlocks(SBlockData* pBlockData, STableBlockScanInfo* pScanInfo, STsdbReader* pReader,
                                SRowMerger* pMerger) {
3481 3482
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;

3483
  bool    asc = ASCENDING_TRAVERSE(pReader->order);
3484
  int64_t key = pBlockData->aTSKEY[pDumpInfo->rowIndex];
3485
  int32_t step = asc ? 1 : -1;
3486

3487
  pDumpInfo->rowIndex += step;
3488
  if ((pDumpInfo->rowIndex <= pBlockData->nRow - 1 && asc) || (pDumpInfo->rowIndex >= 0 && !asc)) {
3489 3490 3491
    pDumpInfo->rowIndex =
        doMergeRowsInFileBlockImpl(pBlockData, pDumpInfo->rowIndex, key, pMerger, &pReader->verRange, step);
  }
3492

3493 3494 3495 3496
  // 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;
3497

3498
      SFileDataBlockInfo* pFileBlockInfo = getCurrentBlockInfo(&pReader->status.blockIter);
H
Hongze Cheng 已提交
3499
      SDataBlk*           pCurrentBlock = getCurrentBlock(&pReader->status.blockIter);
H
Haojun Liao 已提交
3500 3501 3502 3503 3504
      if (pFileBlockInfo == NULL) {
        st = CHECK_FILEBLOCK_QUIT;
        break;
      }

3505 3506 3507
      checkForNeighborFileBlock(pReader, pScanInfo, pCurrentBlock, pFileBlockInfo, pMerger, key, &st);
      if (st == CHECK_FILEBLOCK_QUIT) {
        break;
3508
      }
3509
    }
H
Haojun Liao 已提交
3510
  }
3511

H
Haojun Liao 已提交
3512 3513 3514
  return TSDB_CODE_SUCCESS;
}

H
Hongze Cheng 已提交
3515
int32_t doMergeRowsInLastBlock(SLastBlockReader* pLastBlockReader, STableBlockScanInfo* pScanInfo, int64_t ts,
3516 3517
                               SRowMerger* pMerger, SVersionRange* pVerRange) {
  while (nextRowFromLastBlocks(pLastBlockReader, pScanInfo, pVerRange)) {
3518 3519
    int64_t next1 = getCurrentKeyInLastBlock(pLastBlockReader);
    if (next1 == ts) {
3520
      TSDBROW fRow1 = tMergeTreeGetRow(&pLastBlockReader->mergeTree);
H
Hongze Cheng 已提交
3521
      tsdbRowMerge(pMerger, &fRow1);
3522 3523 3524 3525 3526 3527 3528 3529
    } else {
      break;
    }
  }

  return TSDB_CODE_SUCCESS;
}

3530
int32_t doMergeMemTableMultiRows(TSDBROW* pRow, uint64_t uid, SIterInfo* pIter, SArray* pDelList, TSDBROW* pResRow,
3531
                                 STsdbReader* pReader, bool* freeTSRow) {
H
Haojun Liao 已提交
3532
  TSDBROW* pNextRow = NULL;
3533
  TSDBROW  current = *pRow;
3534

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

3538
    if (!pIter->hasVal) {
3539
      *pResRow = *pRow;
3540
      *freeTSRow = false;
3541
      return TSDB_CODE_SUCCESS;
3542
    } else {  // has next point in mem/imem
3543
      pNextRow = getValidMemRow(pIter, pDelList, pReader);
3544
      if (pNextRow == NULL) {
H
Haojun Liao 已提交
3545
        *pResRow = current;
3546
        *freeTSRow = false;
3547
        return TSDB_CODE_SUCCESS;
3548 3549
      }

H
Hongze Cheng 已提交
3550
      if (TSDBROW_TS(&current) != TSDBROW_TS(pNextRow)) {
H
Haojun Liao 已提交
3551
        *pResRow = current;
3552
        *freeTSRow = false;
3553
        return TSDB_CODE_SUCCESS;
3554
      }
3555
    }
3556 3557
  }

3558
  SRowMerger merge = {0};
H
Haojun Liao 已提交
3559
  terrno = 0;
3560
  int32_t code = 0;
H
Haojun Liao 已提交
3561

3562 3563 3564 3565 3566 3567 3568
  // start to merge duplicated rows
  if (current.type == TSDBROW_ROW_FMT) {
    // get the correct schema for data in memory
    STSchema* pTSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(&current), pReader, uid);
    if (pTSchema == NULL) {
      return terrno;
    }
H
Haojun Liao 已提交
3569

3570 3571 3572
    if (pReader->pSchema == NULL) {
      pReader->pSchema = pTSchema;
    }
H
Haojun Liao 已提交
3573

3574
    code = tsdbRowMergerInit2(&merge, pReader->pSchema, &current, pTSchema);
3575 3576 3577
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }
H
Haojun Liao 已提交
3578

3579 3580 3581 3582
    STSchema* pTSchema1 = doGetSchemaForTSRow(TSDBROW_SVERSION(pNextRow), pReader, uid);
    if (pTSchema1 == NULL) {
      return terrno;
    }
H
Haojun Liao 已提交
3583

3584
    tsdbRowMergerAdd(&merge, pNextRow, pTSchema1);
3585 3586
  } else {  // let's merge rows in file block
    code = tsdbRowMergerInit(&merge, &current, pReader->pSchema);
3587 3588 3589
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }
H
Haojun Liao 已提交
3590

3591 3592
    tsdbRowMerge(&merge, pNextRow);
  }
H
Haojun Liao 已提交
3593

wmmhello's avatar
wmmhello 已提交
3594
  code = doMergeRowsInBuf(pIter, uid, TSDBROW_TS(&current), pDelList, &merge, pReader);
H
Haojun Liao 已提交
3595 3596 3597 3598
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

3599
  code = tsdbRowMergerGetRow(&merge, &pResRow->pTSRow);
3600 3601 3602
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }
M
Minglei Jin 已提交
3603

wmmhello's avatar
wmmhello 已提交
3604
  pResRow->type = TSDBROW_ROW_FMT;
3605
  tsdbRowMergerClear(&merge);
3606
  *freeTSRow = true;
3607

3608
  return TSDB_CODE_SUCCESS;
3609 3610
}

3611
int32_t doMergeMemIMemRows(TSDBROW* pRow, TSDBROW* piRow, STableBlockScanInfo* pBlockScanInfo, STsdbReader* pReader,
H
Hongze Cheng 已提交
3612
                           SRow** pTSRow) {
H
Haojun Liao 已提交
3613 3614
  SRowMerger merge = {0};

3615 3616 3617
  TSDBKEY k = TSDBROW_KEY(pRow);
  TSDBKEY ik = TSDBROW_KEY(piRow);

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

H
Hongze Cheng 已提交
3621
    int32_t code = tsdbRowMergerInit(&merge, piRow, pSchema);
H
Haojun Liao 已提交
3622 3623 3624 3625 3626 3627 3628 3629 3630
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

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

H
Hongze Cheng 已提交
3632
    tsdbRowMerge(&merge, pRow);
H
Haojun Liao 已提交
3633 3634 3635 3636 3637 3638
    code =
        doMergeRowsInBuf(&pBlockScanInfo->iter, pBlockScanInfo->uid, k.ts, pBlockScanInfo->delSkyline, &merge, pReader);
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

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

H
Hongze Cheng 已提交
3642
    int32_t code = tsdbRowMergerInit(&merge, pRow, pSchema);
3643
    if (code != TSDB_CODE_SUCCESS || merge.pTSchema == NULL) {
H
Haojun Liao 已提交
3644 3645 3646 3647 3648 3649 3650 3651
      return code;
    }

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

H
Hongze Cheng 已提交
3653
    tsdbRowMerge(&merge, piRow);
H
Haojun Liao 已提交
3654 3655 3656 3657 3658
    code = doMergeRowsInBuf(&pBlockScanInfo->iiter, pBlockScanInfo->uid, ik.ts, pBlockScanInfo->delSkyline, &merge,
                            pReader);
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }
3659
  }
3660

H
Haojun Liao 已提交
3661 3662
  int32_t code = tsdbRowMergerGetRow(&merge, pTSRow);
  tsdbRowMergerClear(&merge);
3663
  return code;
3664 3665
}

3666
int32_t tsdbGetNextRowInMem(STableBlockScanInfo* pBlockScanInfo, STsdbReader* pReader, TSDBROW* pResRow, int64_t endKey,
3667
                            bool* freeTSRow) {
3668 3669
  TSDBROW* pRow = getValidMemRow(&pBlockScanInfo->iter, pBlockScanInfo->delSkyline, pReader);
  TSDBROW* piRow = getValidMemRow(&pBlockScanInfo->iiter, pBlockScanInfo->delSkyline, pReader);
dengyihao's avatar
dengyihao 已提交
3670
  SArray*  pDelList = pBlockScanInfo->delSkyline;
3671
  uint64_t uid = pBlockScanInfo->uid;
H
Haojun Liao 已提交
3672

3673 3674
  // todo refactor
  bool asc = ASCENDING_TRAVERSE(pReader->order);
3675
  if (pBlockScanInfo->iter.hasVal) {
3676 3677 3678 3679 3680 3681
    TSDBKEY k = TSDBROW_KEY(pRow);
    if ((k.ts >= endKey && asc) || (k.ts <= endKey && !asc)) {
      pRow = NULL;
    }
  }

3682
  if (pBlockScanInfo->iiter.hasVal) {
3683 3684 3685 3686 3687 3688
    TSDBKEY k = TSDBROW_KEY(piRow);
    if ((k.ts >= endKey && asc) || (k.ts <= endKey && !asc)) {
      piRow = NULL;
    }
  }

3689
  if (pBlockScanInfo->iter.hasVal && pBlockScanInfo->iiter.hasVal && pRow != NULL && piRow != NULL) {
3690
    TSDBKEY k = TSDBROW_KEY(pRow);
3691
    TSDBKEY ik = TSDBROW_KEY(piRow);
H
Haojun Liao 已提交
3692

3693
    int32_t code = TSDB_CODE_SUCCESS;
3694 3695
    if (ik.ts != k.ts) {
      if (((ik.ts < k.ts) && asc) || ((ik.ts > k.ts) && (!asc))) {  // ik.ts < k.ts
3696
        code = doMergeMemTableMultiRows(piRow, uid, &pBlockScanInfo->iiter, pDelList, pResRow, pReader, freeTSRow);
3697
      } else if (((k.ts < ik.ts) && asc) || ((k.ts > ik.ts) && (!asc))) {
3698
        code = doMergeMemTableMultiRows(pRow, uid, &pBlockScanInfo->iter, pDelList, pResRow, pReader, freeTSRow);
3699
      }
3700
    } else {  // ik.ts == k.ts
3701
      *freeTSRow = true;
3702 3703
      pResRow->type = TSDBROW_ROW_FMT;
      code = doMergeMemIMemRows(pRow, piRow, pBlockScanInfo, pReader, &pResRow->pTSRow);
3704 3705 3706
      if (code != TSDB_CODE_SUCCESS) {
        return code;
      }
H
Haojun Liao 已提交
3707
    }
3708

3709
    return code;
H
Haojun Liao 已提交
3710 3711
  }

3712
  if (pBlockScanInfo->iter.hasVal && pRow != NULL) {
3713
    return doMergeMemTableMultiRows(pRow, pBlockScanInfo->uid, &pBlockScanInfo->iter, pDelList, pResRow, pReader,
H
Hongze Cheng 已提交
3714
                                    freeTSRow);
H
Haojun Liao 已提交
3715 3716
  }

3717
  if (pBlockScanInfo->iiter.hasVal && piRow != NULL) {
3718
    return doMergeMemTableMultiRows(piRow, uid, &pBlockScanInfo->iiter, pDelList, pResRow, pReader, freeTSRow);
H
Haojun Liao 已提交
3719 3720 3721 3722 3723
  }

  return TSDB_CODE_SUCCESS;
}

H
Hongze Cheng 已提交
3724
int32_t doAppendRowFromTSRow(SSDataBlock* pBlock, STsdbReader* pReader, SRow* pTSRow, STableBlockScanInfo* pScanInfo) {
H
Haojun Liao 已提交
3725
  int32_t outputRowIndex = pBlock->info.rows;
3726
  int64_t uid = pScanInfo->uid;
3727 3728 3729

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

3730
  SBlockLoadSuppInfo* pSupInfo = &pReader->suppInfo;
3731
  STSchema*           pSchema = doGetSchemaForTSRow(pTSRow->sver, pReader, uid);
3732

3733
  SColVal colVal = {0};
3734
  int32_t i = 0, j = 0;
H
Haojun Liao 已提交
3735

3736
  if (pSupInfo->colId[i] == PRIMARYKEY_TIMESTAMP_COL_ID) {
H
Haojun Liao 已提交
3737
    SColumnInfoData* pColData = taosArrayGet(pBlock->pDataBlock, pSupInfo->slotId[i]);
H
Haojun Liao 已提交
3738
    ((int64_t*)pColData->pData)[outputRowIndex] = pTSRow->ts;
3739 3740 3741
    i += 1;
  }

H
Haojun Liao 已提交
3742
  while (i < pSupInfo->numOfCols && j < pSchema->numOfCols) {
H
Haojun Liao 已提交
3743
    col_id_t colId = pSupInfo->colId[i];
3744 3745

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

H
Hongze Cheng 已提交
3748
      tRowGet(pTSRow, pSchema, j, &colVal);
H
Haojun Liao 已提交
3749
      doCopyColVal(pColInfoData, outputRowIndex, i, &colVal, pSupInfo);
3750 3751 3752
      i += 1;
      j += 1;
    } else if (colId < pSchema->columns[j].colId) {
H
Haojun Liao 已提交
3753
      SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, pSupInfo->slotId[i]);
H
Haojun Liao 已提交
3754 3755

      colDataAppendNULL(pColInfoData, outputRowIndex);
3756 3757 3758
      i += 1;
    } else if (colId > pSchema->columns[j].colId) {
      j += 1;
3759
    }
3760 3761
  }

3762
  // set null value since current column does not exist in the "pSchema"
H
Haojun Liao 已提交
3763
  while (i < pSupInfo->numOfCols) {
H
Haojun Liao 已提交
3764
    SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, pSupInfo->slotId[i]);
H
Haojun Liao 已提交
3765
    colDataAppendNULL(pColInfoData, outputRowIndex);
3766 3767 3768
    i += 1;
  }

3769
  pBlock->info.dataLoad = 1;
3770
  pBlock->info.rows += 1;
3771
  pScanInfo->lastKey = pTSRow->ts;
3772 3773 3774
  return TSDB_CODE_SUCCESS;
}

H
Hongze Cheng 已提交
3775 3776
int32_t doAppendRowFromFileBlock(SSDataBlock* pResBlock, STsdbReader* pReader, SBlockData* pBlockData,
                                 int32_t rowIndex) {
3777 3778 3779 3780
  int32_t i = 0, j = 0;
  int32_t outputRowIndex = pResBlock->info.rows;

  SBlockLoadSuppInfo* pSupInfo = &pReader->suppInfo;
3781
  if (pReader->suppInfo.colId[i] == PRIMARYKEY_TIMESTAMP_COL_ID) {
H
Haojun Liao 已提交
3782
    SColumnInfoData* pColData = taosArrayGet(pResBlock->pDataBlock, pSupInfo->slotId[i]);
H
Haojun Liao 已提交
3783
    ((int64_t*)pColData->pData)[outputRowIndex] = pBlockData->aTSKEY[rowIndex];
3784
    i += 1;
3785 3786 3787
  }

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

3791
  while (i < numOfOutputCols && j < numOfInputCols) {
H
Haojun Liao 已提交
3792
    SColData* pData = tBlockDataGetColDataByIdx(pBlockData, j);
H
Haojun Liao 已提交
3793
    if (pData->cid < pSupInfo->colId[i]) {
3794 3795 3796 3797
      j += 1;
      continue;
    }

H
Haojun Liao 已提交
3798 3799
    SColumnInfoData* pCol = TARRAY_GET_ELEM(pResBlock->pDataBlock, pSupInfo->slotId[i]);
    if (pData->cid == pSupInfo->colId[i]) {
3800 3801
      tColDataGetValue(pData, rowIndex, &cv);
      doCopyColVal(pCol, outputRowIndex, i, &cv, pSupInfo);
3802
      j += 1;
H
Haojun Liao 已提交
3803 3804
    } else if (pData->cid > pCol->info.colId) {
      // the specified column does not exist in file block, fill with null data
3805 3806 3807 3808 3809 3810 3811
      colDataAppendNULL(pCol, outputRowIndex);
    }

    i += 1;
  }

  while (i < numOfOutputCols) {
H
Haojun Liao 已提交
3812
    SColumnInfoData* pCol = taosArrayGet(pResBlock->pDataBlock, pSupInfo->slotId[i]);
3813
    colDataAppendNULL(pCol, outputRowIndex);
3814 3815 3816
    i += 1;
  }

3817
  pResBlock->info.dataLoad = 1;
3818 3819 3820 3821
  pResBlock->info.rows += 1;
  return TSDB_CODE_SUCCESS;
}

3822 3823
int32_t buildDataBlockFromBufImpl(STableBlockScanInfo* pBlockScanInfo, int64_t endKey, int32_t capacity,
                                  STsdbReader* pReader) {
H
Haojun Liao 已提交
3824 3825 3826
  SSDataBlock* pBlock = pReader->pResBlock;

  do {
3827
    //    SRow* pTSRow = NULL;
3828
    TSDBROW row = {.type = -1};
3829
    bool    freeTSRow = false;
3830 3831
    tsdbGetNextRowInMem(pBlockScanInfo, pReader, &row, endKey, &freeTSRow);
    if (row.type == -1) {
3832
      break;
H
Haojun Liao 已提交
3833 3834
    }

3835 3836
    if (row.type == TSDBROW_ROW_FMT) {
      doAppendRowFromTSRow(pBlock, pReader, row.pTSRow, pBlockScanInfo);
3837

3838 3839 3840 3841 3842
      if (freeTSRow) {
        taosMemoryFree(row.pTSRow);
      }
    } else {
      doAppendRowFromFileBlock(pBlock, pReader, row.pBlockData, row.iRow);
3843
    }
H
Haojun Liao 已提交
3844 3845

    // no data in buffer, return immediately
3846
    if (!(pBlockScanInfo->iter.hasVal || pBlockScanInfo->iiter.hasVal)) {
H
Haojun Liao 已提交
3847 3848 3849
      break;
    }

3850
    if (pBlock->info.rows >= capacity) {
H
Haojun Liao 已提交
3851 3852 3853 3854 3855 3856
      break;
    }
  } while (1);

  return TSDB_CODE_SUCCESS;
}
H
Hongze Cheng 已提交
3857

3858 3859
// TODO refactor: with createDataBlockScanInfo
int32_t tsdbSetTableList(STsdbReader* pReader, const void* pTableList, int32_t num) {
3860
  int32_t size = taosHashGetSize(pReader->status.pTableMap);
3861

3862
  STableBlockScanInfo** p = NULL;
3863
  while ((p = taosHashIterate(pReader->status.pTableMap, p)) != NULL) {
3864
    clearBlockScanInfo(*p);
3865 3866
  }

3867 3868 3869
  // todo handle the case where size is less than the value of num
  ASSERT(size >= num);

3870 3871
  taosHashClear(pReader->status.pTableMap);

3872 3873
  STableKeyInfo* pList = (STableKeyInfo*)pTableList;
  for (int32_t i = 0; i < num; ++i) {
3874 3875 3876
    STableBlockScanInfo* pInfo = getPosInBlockInfoBuf(&pReader->blockInfoBuf, i);
    pInfo->uid = pList[i].uid;
    taosHashPut(pReader->status.pTableMap, &pInfo->uid, sizeof(uint64_t), &pInfo, POINTER_BYTES);
3877 3878
  }

H
Hongze Cheng 已提交
3879 3880 3881
  return TDB_CODE_SUCCESS;
}

dengyihao's avatar
dengyihao 已提交
3882 3883 3884 3885 3886 3887
void* tsdbGetIdx(SMeta* pMeta) {
  if (pMeta == NULL) {
    return NULL;
  }
  return metaGetIdx(pMeta);
}
dengyihao's avatar
dengyihao 已提交
3888

dengyihao's avatar
dengyihao 已提交
3889 3890 3891 3892 3893 3894
void* tsdbGetIvtIdx(SMeta* pMeta) {
  if (pMeta == NULL) {
    return NULL;
  }
  return metaGetIvtIdx(pMeta);
}
L
Liu Jicong 已提交
3895

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

3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912
static int32_t doOpenReaderImpl(STsdbReader* pReader) {
  SDataBlockIter* pBlockIter = &pReader->status.blockIter;

  initFilesetIterator(&pReader->status.fileIter, pReader->pReadSnap->fs.aDFileSet, pReader);
  resetDataBlockIterator(&pReader->status.blockIter, pReader->order);

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

H
refact  
Hongze Cheng 已提交
3913
// ====================================== EXPOSED APIs ======================================
3914
int32_t tsdbReaderOpen(SVnode* pVnode, SQueryTableDataCond* pCond, void* pTableList, int32_t numOfTables,
H
Haojun Liao 已提交
3915
                       SSDataBlock* pResBlock, STsdbReader** ppReader, const char* idstr) {
3916 3917 3918 3919 3920 3921
  STimeWindow window = pCond->twindows;
  if (pCond->type == TIMEWINDOW_RANGE_EXTERNAL) {
    pCond->twindows.skey += 1;
    pCond->twindows.ekey -= 1;
  }

H
Haojun Liao 已提交
3922 3923 3924 3925 3926 3927 3928 3929
  int32_t capacity = 0;
  if (pResBlock == NULL) {
    capacity = 4096;
  } else {
    capacity = pResBlock->info.capacity;
  }

  int32_t code = tsdbReaderCreate(pVnode, pCond, ppReader, capacity, pResBlock, idstr);
3930
  if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
3931 3932
    goto _err;
  }
H
Hongze Cheng 已提交
3933

3934
  // check for query time window
H
Haojun Liao 已提交
3935
  STsdbReader* pReader = *ppReader;
3936
  if (isEmptyQueryTimeWindow(&pReader->window) && pCond->type == TIMEWINDOW_RANGE_CONTAINED) {
H
Haojun Liao 已提交
3937 3938 3939
    tsdbDebug("%p query window not overlaps with the data set, no result returned, %s", pReader, pReader->idStr);
    return TSDB_CODE_SUCCESS;
  }
H
Hongze Cheng 已提交
3940

3941 3942
  if (pCond->type == TIMEWINDOW_RANGE_EXTERNAL) {
    // update the SQueryTableDataCond to create inner reader
3943
    int32_t order = pCond->order;
3944
    if (order == TSDB_ORDER_ASC) {
3945
      pCond->twindows.ekey = window.skey;
3946 3947 3948
      pCond->twindows.skey = INT64_MIN;
      pCond->order = TSDB_ORDER_DESC;
    } else {
3949
      pCond->twindows.skey = window.ekey;
3950 3951 3952 3953
      pCond->twindows.ekey = INT64_MAX;
      pCond->order = TSDB_ORDER_ASC;
    }

3954
    // here we only need one more row, so the capacity is set to be ONE.
H
Haojun Liao 已提交
3955
    code = tsdbReaderCreate(pVnode, pCond, &pReader->innerReader[0], 1, pResBlock, idstr);
3956 3957 3958 3959 3960
    if (code != TSDB_CODE_SUCCESS) {
      goto _err;
    }

    if (order == TSDB_ORDER_ASC) {
3961
      pCond->twindows.skey = window.ekey;
3962
      pCond->twindows.ekey = INT64_MAX;
3963
    } else {
3964
      pCond->twindows.skey = INT64_MIN;
3965
      pCond->twindows.ekey = window.ekey;
3966
    }
3967 3968
    pCond->order = order;

H
Haojun Liao 已提交
3969
    code = tsdbReaderCreate(pVnode, pCond, &pReader->innerReader[1], 1, pResBlock, idstr);
3970 3971 3972 3973 3974
    if (code != TSDB_CODE_SUCCESS) {
      goto _err;
    }
  }

H
Haojun Liao 已提交
3975
  // NOTE: the endVersion in pCond is the data version not schema version, so pCond->endVersion is not correct here.
3976 3977
  //  no valid error code set in metaGetTbTSchema, so let's set the error code here.
  //  we should proceed in case of tmq processing.
3978
  if (pCond->suid != 0) {
3979
    pReader->pSchema = metaGetTbTSchema(pReader->pTsdb->pVnode->pMeta, pReader->suid, -1, 1);
H
Haojun Liao 已提交
3980
    if (pReader->pSchema == NULL) {
H
Haojun Liao 已提交
3981
      tsdbError("failed to get table schema, suid:%" PRIu64 ", ver:-1, %s", pReader->suid, pReader->idStr);
H
Haojun Liao 已提交
3982
    }
3983 3984
  } else if (numOfTables > 0) {
    STableKeyInfo* pKey = pTableList;
3985
    pReader->pSchema = metaGetTbTSchema(pReader->pTsdb->pVnode->pMeta, pKey->uid, -1, 1);
H
Haojun Liao 已提交
3986
    if (pReader->pSchema == NULL) {
H
Haojun Liao 已提交
3987
      tsdbError("failed to get table schema, uid:%" PRIu64 ", ver:-1, %s", pKey->uid, pReader->idStr);
H
Haojun Liao 已提交
3988
    }
3989 3990
  }

3991
  if (pReader->pSchema != NULL) {
H
Haojun Liao 已提交
3992 3993 3994 3995
    code = updateBlockSMAInfo(pReader->pSchema, &pReader->suppInfo);
    if (code != TSDB_CODE_SUCCESS) {
      goto _err;
    }
3996
  }
3997

3998
  STsdbReader* p = (pReader->innerReader[0] != NULL) ? pReader->innerReader[0] : pReader;
H
Haojun Liao 已提交
3999
  pReader->status.pTableMap = createDataBlockScanInfo(p, &pReader->blockInfoBuf, pTableList, numOfTables);
H
Haojun Liao 已提交
4000 4001
  if (pReader->status.pTableMap == NULL) {
    *ppReader = NULL;
S
Shengliang Guan 已提交
4002
    code = TSDB_CODE_OUT_OF_MEMORY;
H
Haojun Liao 已提交
4003 4004
    goto _err;
  }
H
Hongze Cheng 已提交
4005

4006
  pReader->suspended = true;
4007

4008
  tsdbDebug("%p total numOfTable:%d in this query %s", pReader, numOfTables, pReader->idStr);
H
Hongze Cheng 已提交
4009
  return code;
H
Hongze Cheng 已提交
4010 4011

_err:
H
Haojun Liao 已提交
4012
  tsdbError("failed to create data reader, code:%s %s", tstrerror(code), idstr);
4013
  tsdbReaderClose(pReader);
H
Hongze Cheng 已提交
4014
  return code;
H
refact  
Hongze Cheng 已提交
4015 4016 4017
}

void tsdbReaderClose(STsdbReader* pReader) {
4018 4019
  if (pReader == NULL) {
    return;
4020
  }
H
refact  
Hongze Cheng 已提交
4021

4022
  tsdbAcquireReader(pReader);
4023
  {
H
Haojun Liao 已提交
4024
    if (pReader->innerReader[0] != NULL || pReader->innerReader[1] != NULL) {
4025
      STsdbReader* p = pReader->innerReader[0];
4026

4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037
      p->status.pTableMap = NULL;
      p->pReadSnap = NULL;
      p->pSchema = NULL;
      p->pMemSchema = NULL;

      p = pReader->innerReader[1];

      p->status.pTableMap = NULL;
      p->pReadSnap = NULL;
      p->pSchema = NULL;
      p->pMemSchema = NULL;
4038 4039 4040 4041 4042 4043

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

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

4046
  taosArrayDestroy(pSupInfo->pColAgg);
H
Haojun Liao 已提交
4047
  for (int32_t i = 0; i < pSupInfo->numOfCols; ++i) {
4048 4049 4050 4051
    if (pSupInfo->buildBuf[i] != NULL) {
      taosMemoryFreeClear(pSupInfo->buildBuf[i]);
    }
  }
4052

H
Haojun Liao 已提交
4053 4054 4055
  if (pReader->freeBlock) {
    pReader->pResBlock = blockDataDestroy(pReader->pResBlock);
  }
4056

H
Haojun Liao 已提交
4057
  taosMemoryFree(pSupInfo->colId);
H
Hongze Cheng 已提交
4058
  tBlockDataDestroy(&pReader->status.fileBlockData);
4059
  cleanupDataBlockIterator(&pReader->status.blockIter);
4060 4061

  size_t numOfTables = taosHashGetSize(pReader->status.pTableMap);
H
Haojun Liao 已提交
4062 4063 4064 4065
  if (pReader->status.pTableMap != NULL) {
    destroyAllBlockScanInfo(pReader->status.pTableMap);
    clearBlockScanInfoBuf(&pReader->blockInfoBuf);
  }
4066

H
Haojun Liao 已提交
4067 4068 4069
  if (pReader->pFileReader != NULL) {
    tsdbDataFReaderClose(&pReader->pFileReader);
  }
H
refact  
Hongze Cheng 已提交
4070

4071 4072 4073 4074 4075 4076 4077 4078 4079
  if (pReader->pDelFReader != NULL) {
    tsdbDelFReaderClose(&pReader->pDelFReader);
  }

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

4080
  qTrace("tsdb/reader-close: %p, untake snapshot", pReader);
4081
  tsdbUntakeReadSnap(pReader, pReader->pReadSnap, true);
4082
  pReader->pReadSnap = NULL;
4083

4084 4085
  tsdbReleaseReader(pReader);

4086
  tsdbUninitReaderLock(pReader);
4087

4088
  taosMemoryFree(pReader->status.uidCheckInfo.tableUidList);
H
Haojun Liao 已提交
4089
  SIOCostSummary* pCost = &pReader->cost;
4090

H
Haojun Liao 已提交
4091 4092
  SFilesetIter* pFilesetIter = &pReader->status.fileIter;
  if (pFilesetIter->pLastBlockReader != NULL) {
H
Haojun Liao 已提交
4093 4094
    SLastBlockReader* pLReader = pFilesetIter->pLastBlockReader;
    tMergeTreeClose(&pLReader->mergeTree);
H
Haojun Liao 已提交
4095

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

H
Haojun Liao 已提交
4098 4099 4100
    pLReader->pInfo = destroyLastBlockLoadInfo(pLReader->pInfo);
    taosMemoryFree(pLReader);
  }
H
refact  
Hongze Cheng 已提交
4101

H
Haojun Liao 已提交
4102 4103 4104 4105 4106 4107 4108 4109 4110 4111
  tsdbDebug("%p :io-cost summary: head-file:%" PRIu64 ", head-file time:%.2f ms, SMA:%" PRId64
            " SMA-time:%.2f ms, fileBlocks:%" PRId64
            ", fileBlocks-load-time:%.2f ms, "
            "build in-memory-block-time:%.2f ms, lastBlocks:%" PRId64
            ", lastBlocks-time:%.2f ms, composed-blocks:%" PRId64
            ", composed-blocks-time:%.2fms, STableBlockScanInfo size:%.2f Kb, creatTime:%.2f ms, %s",
            pReader, pCost->headFileLoad, pCost->headFileLoadTime, pCost->smaDataLoad, pCost->smaLoadTime,
            pCost->numOfBlocks, pCost->blockLoadTime, pCost->buildmemBlock, pCost->lastBlockLoad,
            pCost->lastBlockLoadTime, pCost->composedBlocks, pCost->buildComposedBlockTime,
            numOfTables * sizeof(STableBlockScanInfo) / 1000.0, pCost->createScanInfoList, pReader->idStr);
H
refact  
Hongze Cheng 已提交
4112

4113 4114
  taosMemoryFree(pReader->idStr);
  taosMemoryFree(pReader->pSchema);
4115 4116 4117
  if (pReader->pMemSchema != pReader->pSchema) {
    taosMemoryFree(pReader->pMemSchema);
  }
4118

4119
  taosMemoryFreeClear(pReader);
H
refact  
Hongze Cheng 已提交
4120 4121
}

4122 4123 4124 4125 4126 4127 4128 4129 4130 4131
int32_t tsdbReaderSuspend(STsdbReader* pReader) {
  int32_t code = 0;

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

  if (pStatus->loadFromFile) {
    SFileDataBlockInfo* pBlockInfo = getCurrentBlockInfo(&pReader->status.blockIter);
    if (pBlockInfo != NULL) {
4132 4133
      pBlockScanInfo =
          *(STableBlockScanInfo**)taosHashGet(pStatus->pTableMap, &pBlockInfo->uid, sizeof(pBlockInfo->uid));
4134 4135 4136 4137 4138 4139 4140
      if (pBlockScanInfo == NULL) {
        code = TSDB_CODE_INVALID_PARA;
        tsdbError("failed to locate the uid:%" PRIu64 " in query table uid list, total tables:%d, %s", pBlockInfo->uid,
                  taosHashGetSize(pReader->status.pTableMap), pReader->idStr);
        goto _err;
      }
    } else {
4141
      pBlockScanInfo = *pStatus->pTableIter;
4142 4143 4144 4145 4146
    }

    tsdbDataFReaderClose(&pReader->pFileReader);

    // resetDataBlockScanInfo excluding lastKey
4147
    STableBlockScanInfo** p = NULL;
4148 4149

    while ((p = taosHashIterate(pStatus->pTableMap, p)) != NULL) {
4150 4151 4152 4153 4154 4155 4156 4157
      STableBlockScanInfo* pInfo = *(STableBlockScanInfo**)p;

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

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

4160 4161 4162 4163 4164 4165
      if (pInfo->iiter.iter != NULL) {
        pInfo->iiter.iter = tsdbTbDataIterDestroy(pInfo->iiter.iter);
      }

      pInfo->delSkyline = taosArrayDestroy(pInfo->delSkyline);
      // pInfo->lastKey = ts;
4166 4167
    }
  } else {
4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189
    // resetDataBlockScanInfo excluding lastKey
    STableBlockScanInfo** p = NULL;

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

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

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

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

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

4190
    pBlockScanInfo = pStatus->pTableIter == NULL ? NULL : *pStatus->pTableIter;
4191 4192 4193 4194 4195 4196 4197
    if (pBlockScanInfo) {
      // save lastKey to restore memory iterator
      STimeWindow w = pReader->pResBlock->info.window;
      pBlockScanInfo->lastKey = ASCENDING_TRAVERSE(pReader->order) ? w.ekey : w.skey;

      // reset current current table's data block scan info,
      pBlockScanInfo->iterInit = false;
4198 4199
      pBlockScanInfo->iter.hasVal = false;
      pBlockScanInfo->iiter.hasVal = false;
4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214
      if (pBlockScanInfo->iter.iter != NULL) {
        pBlockScanInfo->iter.iter = tsdbTbDataIterDestroy(pBlockScanInfo->iter.iter);
      }

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

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

4215
  tsdbUntakeReadSnap(pReader, pReader->pReadSnap, false);
4216
  pReader->pReadSnap = NULL;
4217 4218 4219

  pReader->suspended = true;

4220 4221
  tsdbDebug("reader: %p suspended uid %" PRIu64 " in this query %s", pReader, pBlockScanInfo ? pBlockScanInfo->uid : 0,
            pReader->idStr);
4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232
  return code;

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

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

4233
  code = tsdbTryAcquireReader(pReader);
4234 4235
  if (code == 0) {
    if (pReader->suspended) {
4236
      tsdbReleaseReader(pReader);
4237 4238 4239 4240
      return code;
    }

    tsdbReaderSuspend(pReader);
4241

4242
    tsdbReleaseReader(pReader);
4243

4244
    return code;
4245 4246 4247
  } else if (code == EBUSY) {
    return TSDB_CODE_VND_QUERY_BUSY;
  } else {
4248 4249
    terrno = TAOS_SYSTEM_ERROR(code);
    return TSDB_CODE_FAILED;
4250 4251 4252 4253 4254 4255
  }
}

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

4256
  STableBlockScanInfo** pBlockScanInfo = pReader->status.pTableIter;
4257 4258 4259

  //  restore reader's state
  //  task snapshot
4260
  int32_t numOfTables = taosHashGetSize(pReader->status.pTableMap);
4261
  if (numOfTables > 0) {
4262
    qTrace("tsdb/reader: %p, take snapshot", pReader);
4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298
    code = tsdbTakeReadSnap(pReader, tsdbSetQueryReseek, &pReader->pReadSnap);
    if (code != TSDB_CODE_SUCCESS) {
      goto _err;
    }

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

      // we need only one row
      pPrevReader->capacity = 1;
      pPrevReader->status.pTableMap = pReader->status.pTableMap;
      pPrevReader->pSchema = pReader->pSchema;
      pPrevReader->pMemSchema = pReader->pMemSchema;
      pPrevReader->pReadSnap = pReader->pReadSnap;

      pNextReader->capacity = 1;
      pNextReader->status.pTableMap = pReader->status.pTableMap;
      pNextReader->pSchema = pReader->pSchema;
      pNextReader->pMemSchema = pReader->pMemSchema;
      pNextReader->pReadSnap = pReader->pReadSnap;

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

  pReader->suspended = false;

4299 4300
  tsdbDebug("reader: %p resumed uid %" PRIu64 ", numOfTable:%" PRId32 ", in this query %s", pReader,
            pBlockScanInfo ? (*pBlockScanInfo)->uid : 0, numOfTables, pReader->idStr);
4301 4302 4303 4304 4305 4306 4307
  return code;

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

4308
static bool doTsdbNextDataBlock(STsdbReader* pReader) {
H
Haojun Liao 已提交
4309
  // cleanup the data that belongs to the previous data block
4310 4311
  SSDataBlock* pBlock = pReader->pResBlock;
  blockDataCleanup(pBlock);
H
Hongze Cheng 已提交
4312

4313
  SReaderStatus* pStatus = &pReader->status;
4314
  if (taosHashGetSize(pStatus->pTableMap) == 0) {
4315 4316
    return false;
  }
H
Haojun Liao 已提交
4317

4318 4319 4320 4321 4322
  if (pStatus->loadFromFile) {
    int32_t code = buildBlockFromFiles(pReader);
    if (code != TSDB_CODE_SUCCESS) {
      return false;
    }
4323

4324 4325 4326
    if (pBlock->info.rows > 0) {
      return true;
    } else {
H
Haojun Liao 已提交
4327
      buildBlockFromBufferSequentially(pReader);
4328
      return pBlock->info.rows > 0;
H
Haojun Liao 已提交
4329
    }
4330 4331 4332
  } else {  // no data in files, let's try the buffer
    buildBlockFromBufferSequentially(pReader);
    return pBlock->info.rows > 0;
H
Haojun Liao 已提交
4333
  }
H
refact  
Hongze Cheng 已提交
4334 4335
}

4336 4337 4338 4339 4340
bool tsdbNextDataBlock(STsdbReader* pReader) {
  if (isEmptyQueryTimeWindow(&pReader->window)) {
    return false;
  }

4341 4342
  SReaderStatus* pStatus = &pReader->status;

4343 4344 4345
  int32_t code = tsdbAcquireReader(pReader);
  qTrace("tsdb/read: %p, take read mutex, code: %d", pReader, code);

4346 4347 4348 4349
  if (pReader->suspended) {
    tsdbReaderResume(pReader);
  }

4350
  if (pReader->innerReader[0] != NULL && pReader->step == 0) {
4351
    bool ret = doTsdbNextDataBlock(pReader->innerReader[0]);
4352
    pReader->step = EXTERNAL_ROWS_PREV;
4353
    if (ret) {
4354
      pStatus = &pReader->innerReader[0]->status;
4355
      if (pStatus->composedDataBlock) {
4356
        qTrace("tsdb/read: %p, unlock read mutex", pReader);
4357
        tsdbReleaseReader(pReader);
4358 4359
      }

4360 4361
      return ret;
    }
4362
  }
4363

4364
  if (pReader->step == EXTERNAL_ROWS_PREV) {
4365 4366
    // prepare for the main scan
    int32_t code = doOpenReaderImpl(pReader);
4367
    resetAllDataBlockScanInfo(pReader->status.pTableMap, pReader->innerReader[0]->window.ekey);
4368 4369 4370 4371 4372

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

4373
    pReader->step = EXTERNAL_ROWS_MAIN;
4374 4375 4376 4377
  }

  bool ret = doTsdbNextDataBlock(pReader);
  if (ret) {
4378
    if (pStatus->composedDataBlock) {
4379
      qTrace("tsdb/read: %p, unlock read mutex", pReader);
4380
      tsdbReleaseReader(pReader);
4381 4382
    }

4383 4384 4385
    return ret;
  }

4386
  if (pReader->innerReader[1] != NULL && pReader->step == EXTERNAL_ROWS_MAIN) {
4387 4388
    // prepare for the next row scan
    int32_t code = doOpenReaderImpl(pReader->innerReader[1]);
4389
    resetAllDataBlockScanInfo(pReader->innerReader[1]->status.pTableMap, pReader->window.ekey);
4390 4391 4392 4393
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

4394
    bool ret1 = doTsdbNextDataBlock(pReader->innerReader[1]);
4395
    pReader->step = EXTERNAL_ROWS_NEXT;
4396
    if (ret1) {
4397
      pStatus = &pReader->innerReader[1]->status;
4398
      if (pStatus->composedDataBlock) {
4399
        qTrace("tsdb/read: %p, unlock read mutex", pReader);
4400
        tsdbReleaseReader(pReader);
4401 4402
      }

4403 4404 4405 4406
      return ret1;
    }
  }

4407
  qTrace("tsdb/read: %p, unlock read mutex", pReader);
4408
  tsdbReleaseReader(pReader);
4409

4410 4411 4412
  return false;
}

H
Haojun Liao 已提交
4413 4414
static void setBlockInfo(const STsdbReader* pReader, int32_t* rows, uint64_t* uid, STimeWindow* pWindow) {
  *rows = pReader->pResBlock->info.rows;
H
Haojun Liao 已提交
4415
  *uid = pReader->pResBlock->info.id.uid;
H
Haojun Liao 已提交
4416
  *pWindow = pReader->pResBlock->info.window;
H
Hongze Cheng 已提交
4417 4418
}

H
Haojun Liao 已提交
4419
void tsdbRetrieveDataBlockInfo(const STsdbReader* pReader, int32_t* rows, uint64_t* uid, STimeWindow* pWindow) {
4420
  if (pReader->type == TIMEWINDOW_RANGE_EXTERNAL) {
4421
    if (pReader->step == EXTERNAL_ROWS_MAIN) {
H
Haojun Liao 已提交
4422
      setBlockInfo(pReader, rows, uid, pWindow);
4423
    } else if (pReader->step == EXTERNAL_ROWS_PREV) {
H
Haojun Liao 已提交
4424
      setBlockInfo(pReader->innerReader[0], rows, uid, pWindow);
4425
    } else {
H
Haojun Liao 已提交
4426
      setBlockInfo(pReader->innerReader[1], rows, uid, pWindow);
4427 4428
    }
  } else {
H
Haojun Liao 已提交
4429
    setBlockInfo(pReader, rows, uid, pWindow);
4430 4431 4432
  }
}

4433
static void doFillNullColSMA(SBlockLoadSuppInfo* pSup, int32_t numOfRows, int32_t numOfCols, SColumnDataAgg* pTsAgg) {
4434 4435
  // do fill all null column value SMA info
  int32_t i = 0, j = 0;
4436
  int32_t size = (int32_t)taosArrayGetSize(pSup->pColAgg);
4437
  taosArrayInsert(pSup->pColAgg, 0, pTsAgg);
4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448

  while (j < numOfCols && i < size) {
    SColumnDataAgg* pAgg = taosArrayGet(pSup->pColAgg, i);
    if (pAgg->colId == pSup->colId[j]) {
      i += 1;
      j += 1;
    } else if (pAgg->colId < pSup->colId[j]) {
      i += 1;
    } else if (pSup->colId[j] < pAgg->colId) {
      if (pSup->colId[j] != PRIMARYKEY_TIMESTAMP_COL_ID) {
        SColumnDataAgg nullColAgg = {.colId = pSup->colId[j], .numOfNull = numOfRows};
4449
        taosArrayInsert(pSup->pColAgg, i, &nullColAgg);
4450 4451 4452 4453 4454 4455
      }
      j += 1;
    }
  }
}

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

H
Hongze Cheng 已提交
4459
  int32_t code = 0;
4460
  *allHave = false;
H
Haojun Liao 已提交
4461
  *pBlockSMA = NULL;
H
Hongze Cheng 已提交
4462

4463
  if (pReader->type == TIMEWINDOW_RANGE_EXTERNAL) {
4464 4465 4466
    return TSDB_CODE_SUCCESS;
  }

4467
  // there is no statistics data for composed block
4468
  if (pReader->status.composedDataBlock || (!pReader->suppInfo.smaValid)) {
4469 4470
    return TSDB_CODE_SUCCESS;
  }
H
Hongze Cheng 已提交
4471

4472
  SFileDataBlockInfo* pFBlock = getCurrentBlockInfo(&pReader->status.blockIter);
4473 4474
  SBlockLoadSuppInfo* pSup = &pReader->suppInfo;

H
Haojun Liao 已提交
4475 4476 4477
  if (pReader->pResBlock->info.id.uid != pFBlock->uid) {
    return TSDB_CODE_SUCCESS;
  }
4478 4479

  SDataBlk* pBlock = getCurrentBlock(&pReader->status.blockIter);
H
Hongze Cheng 已提交
4480
  if (tDataBlkHasSma(pBlock)) {
H
Hongze Cheng 已提交
4481
    code = tsdbReadBlockSma(pReader->pFileReader, pBlock, pSup->pColAgg);
4482
    if (code != TSDB_CODE_SUCCESS) {
4483 4484
      tsdbDebug("vgId:%d, failed to load block SMA for uid %" PRIu64 ", code:%s, %s", 0, pFBlock->uid, tstrerror(code),
                pReader->idStr);
4485 4486
      return code;
    }
4487
  } else {
H
Haojun Liao 已提交
4488
    *pBlockSMA = NULL;
4489
    return TSDB_CODE_SUCCESS;
4490
  }
H
Hongze Cheng 已提交
4491

4492
  *allHave = true;
H
Hongze Cheng 已提交
4493

4494 4495
  // always load the first primary timestamp column data
  SColumnDataAgg* pTsAgg = &pSup->tsColAgg;
4496

4497 4498
  pTsAgg->numOfNull = 0;
  pTsAgg->colId = PRIMARYKEY_TIMESTAMP_COL_ID;
4499 4500 4501 4502
  pTsAgg->min = pReader->pResBlock->info.window.skey;
  pTsAgg->max = pReader->pResBlock->info.window.ekey;

  // update the number of NULL data rows
4503
  size_t numOfCols = pSup->numOfCols;
4504

4505
  // ensure capacity
H
Haojun Liao 已提交
4506 4507 4508
  if (pDataBlock->pDataBlock) {
    size_t colsNum = taosArrayGetSize(pDataBlock->pDataBlock);
    taosArrayEnsureCap(pSup->pColAgg, colsNum);
4509 4510
  }

4511 4512 4513 4514 4515
  SSDataBlock* pResBlock = pReader->pResBlock;
  if (pResBlock->pBlockAgg == NULL) {
    size_t num = taosArrayGetSize(pResBlock->pDataBlock);
    pResBlock->pBlockAgg = taosMemoryCalloc(num, sizeof(SColumnDataAgg));
  }
4516

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

H
Haojun Liao 已提交
4521
  int32_t i = 0, j = 0;
4522
  while (j < numOfCols && i < size) {
4523
    SColumnDataAgg* pAgg = taosArrayGet(pSup->pColAgg, i);
H
Haojun Liao 已提交
4524 4525
    if (pAgg->colId == pSup->colId[j]) {
      pResBlock->pBlockAgg[pSup->slotId[j]] = pAgg;
4526 4527
      i += 1;
      j += 1;
H
Haojun Liao 已提交
4528
    } else if (pAgg->colId < pSup->colId[j]) {
4529
      i += 1;
H
Haojun Liao 已提交
4530
    } else if (pSup->colId[j] < pAgg->colId) {
H
Haojun Liao 已提交
4531
      // ASSERT(pSup->colId[j] == PRIMARYKEY_TIMESTAMP_COL_ID);
4532
      pResBlock->pBlockAgg[pSup->slotId[j]] = &pSup->tsColAgg;
4533 4534 4535 4536
      j += 1;
    }
  }

H
Haojun Liao 已提交
4537
  *pBlockSMA = pResBlock->pBlockAgg;
4538
  pReader->cost.smaDataLoad += 1;
4539

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

H
Haojun Liao 已提交
4544
static SSDataBlock* doRetrieveDataBlock(STsdbReader* pReader) {
4545
  SReaderStatus*       pStatus = &pReader->status;
H
Haojun Liao 已提交
4546
  SFileDataBlockInfo*  pBlockInfo = getCurrentBlockInfo(&pStatus->blockIter);
H
Hongze Cheng 已提交
4547 4548
  STableBlockScanInfo* pBlockScanInfo =
      *(STableBlockScanInfo**)taosHashGet(pStatus->pTableMap, &pBlockInfo->uid, sizeof(pBlockInfo->uid));
H
Haojun Liao 已提交
4549 4550 4551 4552
  if (pBlockScanInfo == NULL) {
    terrno = TSDB_CODE_INVALID_PARA;
    tsdbError("failed to locate the uid:%" PRIu64 " in query table uid list, total tables:%d, %s", pBlockInfo->uid,
              taosHashGetSize(pReader->status.pTableMap), pReader->idStr);
4553
    return NULL;
4554 4555
  }

4556
  int32_t code = doLoadFileBlockData(pReader, &pStatus->blockIter, &pStatus->fileBlockData, pBlockScanInfo->uid);
4557
  if (code != TSDB_CODE_SUCCESS) {
H
Hongze Cheng 已提交
4558
    tBlockDataDestroy(&pStatus->fileBlockData);
4559 4560
    terrno = code;
    return NULL;
4561
  }
4562 4563

  copyBlockDataToSDataBlock(pReader, pBlockScanInfo);
H
Haojun Liao 已提交
4564
  return pReader->pResBlock;
H
Hongze Cheng 已提交
4565 4566
}

H
Haojun Liao 已提交
4567
SSDataBlock* tsdbRetrieveDataBlock(STsdbReader* pReader, SArray* pIdList) {
4568
  STsdbReader* pTReader = pReader;
4569 4570
  if (pReader->type == TIMEWINDOW_RANGE_EXTERNAL) {
    if (pReader->step == EXTERNAL_ROWS_PREV) {
4571
      pTReader = pReader->innerReader[0];
4572
    } else if (pReader->step == EXTERNAL_ROWS_NEXT) {
4573
      pTReader = pReader->innerReader[1];
4574 4575 4576
    }
  }

4577 4578 4579 4580 4581 4582 4583
  SReaderStatus* pStatus = &pTReader->status;
  if (pStatus->composedDataBlock) {
    return pTReader->pResBlock;
  }

  SSDataBlock* ret = doRetrieveDataBlock(pTReader);

4584
  qTrace("tsdb/read-retrieve: %p, unlock read mutex", pReader);
4585
  tsdbReleaseReader(pReader);
4586 4587

  return ret;
4588 4589
}

H
Haojun Liao 已提交
4590
int32_t tsdbReaderReset(STsdbReader* pReader, SQueryTableDataCond* pCond) {
L
Liu Jicong 已提交
4591 4592
  SReaderStatus* pStatus = &pReader->status;

4593
  qTrace("tsdb/reader-reset: %p, take read mutex", pReader);
4594
  tsdbAcquireReader(pReader);
L
Liu Jicong 已提交
4595 4596 4597 4598 4599

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

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

4603
    tsdbReleaseReader(pReader);
4604

4605 4606
    return TSDB_CODE_SUCCESS;
  }
H
Hongze Cheng 已提交
4607

4608 4609
  SDataBlockIter* pBlockIter = &pReader->status.blockIter;

L
Liu Jicong 已提交
4610
  pReader->order = pCond->order;
4611
  pReader->type = TIMEWINDOW_RANGE_CONTAINED;
4612
  pReader->status.loadFromFile = true;
dengyihao's avatar
dengyihao 已提交
4613
  pReader->status.pTableIter = NULL;
H
Haojun Liao 已提交
4614
  pReader->window = updateQueryTimeWindow(pReader->pTsdb, &pCond->twindows);
H
Hongze Cheng 已提交
4615

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

4619
  pReader->suppInfo.tsColAgg.colId = PRIMARYKEY_TIMESTAMP_COL_ID;
4620
  tsdbDataFReaderClose(&pReader->pFileReader);
4621

4622
  int32_t numOfTables = taosHashGetSize(pReader->status.pTableMap);
L
Liu Jicong 已提交
4623

4624
  initFilesetIterator(&pReader->status.fileIter, pReader->pReadSnap->fs.aDFileSet, pReader);
4625
  resetDataBlockIterator(pBlockIter, pReader->order);
H
Haojun Liao 已提交
4626

H
Hongze Cheng 已提交
4627
  int64_t ts = ASCENDING_TRAVERSE(pReader->order) ? pReader->window.skey - 1 : pReader->window.ekey + 1;
4628
  resetAllDataBlockScanInfo(pReader->status.pTableMap, ts);
4629

4630
  int32_t code = 0;
4631

4632 4633 4634 4635 4636 4637
  // 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) {
4638 4639
      tsdbError("%p reset reader failed, numOfTables:%d, query range:%" PRId64 " - %" PRId64 " in query %s", pReader,
                numOfTables, pReader->window.skey, pReader->window.ekey, pReader->idStr);
4640

4641
      tsdbReleaseReader(pReader);
4642

4643 4644 4645
      return code;
    }
  }
H
Hongze Cheng 已提交
4646

H
Hongze Cheng 已提交
4647 4648 4649 4650
  tsdbDebug("%p reset reader, suid:%" PRIu64 ", numOfTables:%d, skey:%" PRId64 ", query range:%" PRId64 " - %" PRId64
            " in query %s",
            pReader, pReader->suid, numOfTables, pCond->twindows.skey, pReader->window.skey, pReader->window.ekey,
            pReader->idStr);
4651

4652
  tsdbReleaseReader(pReader);
4653

4654
  return code;
H
Hongze Cheng 已提交
4655
}
H
Hongze Cheng 已提交
4656

4657 4658 4659
static int32_t getBucketIndex(int32_t startRow, int32_t bucketRange, int32_t numOfRows) {
  return (numOfRows - startRow) / bucketRange;
}
H
Hongze Cheng 已提交
4660

4661 4662 4663 4664
int32_t tsdbGetFileBlocksDistInfo(STsdbReader* pReader, STableBlockDistInfo* pTableBlockInfo) {
  int32_t code = TSDB_CODE_SUCCESS;
  pTableBlockInfo->totalSize = 0;
  pTableBlockInfo->totalRows = 0;
4665
  pTableBlockInfo->numOfVgroups = 1;
H
Hongze Cheng 已提交
4666

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

4670 4671 4672
  STsdbCfg* pc = &pReader->pTsdb->pVnode->config.tsdbCfg;
  pTableBlockInfo->defMinRows = pc->minRows;
  pTableBlockInfo->defMaxRows = pc->maxRows;
H
Hongze Cheng 已提交
4673

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

4676
  pTableBlockInfo->numOfFiles += 1;
H
Hongze Cheng 已提交
4677

4678 4679
  int32_t numOfTables = (int32_t)taosHashGetSize(pStatus->pTableMap);
  int     defaultRows = 4096;
H
Hongze Cheng 已提交
4680

4681 4682
  SDataBlockIter* pBlockIter = &pStatus->blockIter;
  pTableBlockInfo->numOfFiles += pStatus->fileIter.numOfFiles;
H
Haojun Liao 已提交
4683

4684 4685
  if (pBlockIter->numOfBlocks > 0) {
    pTableBlockInfo->numOfBlocks += pBlockIter->numOfBlocks;
H
Haojun Liao 已提交
4686
  }
H
Hongze Cheng 已提交
4687

4688
  pTableBlockInfo->numOfTables = numOfTables;
4689
  bool hasNext = (pBlockIter->numOfBlocks > 0);
H
Hongze Cheng 已提交
4690

4691 4692
  while (true) {
    if (hasNext) {
H
Hongze Cheng 已提交
4693
      SDataBlk* pBlock = getCurrentBlock(pBlockIter);
H
Hongze Cheng 已提交
4694

4695 4696
      int32_t numOfRows = pBlock->nRow;
      pTableBlockInfo->totalRows += numOfRows;
H
Hongze Cheng 已提交
4697

4698 4699 4700
      if (numOfRows > pTableBlockInfo->maxRows) {
        pTableBlockInfo->maxRows = numOfRows;
      }
H
refact  
Hongze Cheng 已提交
4701

4702 4703 4704
      if (numOfRows < pTableBlockInfo->minRows) {
        pTableBlockInfo->minRows = numOfRows;
      }
H
refact  
Hongze Cheng 已提交
4705

4706 4707 4708
      if (numOfRows < defaultRows) {
        pTableBlockInfo->numOfSmallBlocks += 1;
      }
H
refact  
Hongze Cheng 已提交
4709

4710
      pTableBlockInfo->totalSize += pBlock->aSubBlock[0].szBlock;
4711

4712 4713
      int32_t bucketIndex = getBucketIndex(pTableBlockInfo->defMinRows, bucketRange, numOfRows);
      pTableBlockInfo->blockRowsHisto[bucketIndex]++;
4714

H
Haojun Liao 已提交
4715
      hasNext = blockIteratorNext(&pStatus->blockIter, pReader->idStr);
4716 4717 4718 4719 4720
    } else {
      code = initForFirstBlockInFile(pReader, pBlockIter);
      if ((code != TSDB_CODE_SUCCESS) || (pReader->status.loadFromFile == false)) {
        break;
      }
H
refact  
Hongze Cheng 已提交
4721

4722 4723
      pTableBlockInfo->numOfBlocks += pBlockIter->numOfBlocks;
      hasNext = (pBlockIter->numOfBlocks > 0);
4724
    }
H
refact  
Hongze Cheng 已提交
4725

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

H
refact  
Hongze Cheng 已提交
4730 4731
  return code;
}
H
Hongze Cheng 已提交
4732

H
refact  
Hongze Cheng 已提交
4733
int64_t tsdbGetNumOfRowsInMemTable(STsdbReader* pReader) {
4734
  int64_t rows = 0;
H
Hongze Cheng 已提交
4735

4736
  SReaderStatus* pStatus = &pReader->status;
4737
  tsdbAcquireReader(pReader);
4738 4739 4740 4741
  if (pReader->suspended) {
    tsdbReaderResume(pReader);
  }

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

4744
  while (pStatus->pTableIter != NULL) {
4745
    STableBlockScanInfo* pBlockScanInfo = *(STableBlockScanInfo**)pStatus->pTableIter;
4746 4747

    STbData* d = NULL;
4748
    if (pReader->pReadSnap->pMem != NULL) {
H
Hongze Cheng 已提交
4749
      d = tsdbGetTbDataFromMemTable(pReader->pReadSnap->pMem, pReader->suid, pBlockScanInfo->uid);
4750 4751 4752 4753 4754 4755
      if (d != NULL) {
        rows += tsdbGetNRowsInTbData(d);
      }
    }

    STbData* di = NULL;
4756
    if (pReader->pReadSnap->pIMem != NULL) {
H
Hongze Cheng 已提交
4757
      di = tsdbGetTbDataFromMemTable(pReader->pReadSnap->pIMem, pReader->suid, pBlockScanInfo->uid);
4758 4759 4760 4761 4762 4763 4764 4765
      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 已提交
4766

4767
  tsdbReleaseReader(pReader);
4768

H
refact  
Hongze Cheng 已提交
4769
  return rows;
H
Hongze Cheng 已提交
4770
}
D
dapan1121 已提交
4771

L
Liu Jicong 已提交
4772
int32_t tsdbGetTableSchema(SVnode* pVnode, int64_t uid, STSchema** pSchema, int64_t* suid) {
D
dapan1121 已提交
4773 4774 4775 4776
  int32_t sversion = 1;

  SMetaReader mr = {0};
  metaReaderInit(&mr, pVnode->pMeta, 0);
H
Haojun Liao 已提交
4777
  int32_t code = metaGetTableEntryByUidCache(&mr, uid);
D
dapan1121 已提交
4778 4779 4780 4781 4782 4783 4784
  if (code != TSDB_CODE_SUCCESS) {
    terrno = TSDB_CODE_TDB_INVALID_TABLE_ID;
    metaReaderClear(&mr);
    return terrno;
  }

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

D
dapan1121 已提交
4786
  if (mr.me.type == TSDB_CHILD_TABLE) {
D
dapan1121 已提交
4787
    tDecoderClear(&mr.coder);
D
dapan1121 已提交
4788
    *suid = mr.me.ctbEntry.suid;
H
Haojun Liao 已提交
4789
    code = metaGetTableEntryByUidCache(&mr, *suid);
D
dapan1121 已提交
4790 4791 4792 4793 4794 4795
    if (code != TSDB_CODE_SUCCESS) {
      terrno = TSDB_CODE_TDB_INVALID_TABLE_ID;
      metaReaderClear(&mr);
      return terrno;
    }
    sversion = mr.me.stbEntry.schemaRow.version;
H
Haojun Liao 已提交
4796
  } else if (mr.me.type == TSDB_NORMAL_TABLE) {
D
dapan1121 已提交
4797
    sversion = mr.me.ntbEntry.schemaRow.version;
H
Haojun Liao 已提交
4798 4799 4800 4801
  } else {
    terrno = TSDB_CODE_INVALID_PARA;
    metaReaderClear(&mr);
    return terrno;
D
dapan1121 已提交
4802 4803 4804
  }

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

D
dapan1121 已提交
4807 4808
  return TSDB_CODE_SUCCESS;
}
H
Hongze Cheng 已提交
4809

H
Hongze Cheng 已提交
4810
int32_t tsdbTakeReadSnap(STsdbReader* pReader, _query_reseek_func_t reseek, STsdbReadSnap** ppSnap) {
H
Hongze Cheng 已提交
4811 4812 4813
  int32_t        code = 0;
  STsdb*         pTsdb = pReader->pTsdb;
  SVersionRange* pRange = &pReader->verRange;
H
Hongze Cheng 已提交
4814 4815

  // alloc
H
Hongze Cheng 已提交
4816 4817
  STsdbReadSnap* pSnap = (STsdbReadSnap*)taosMemoryCalloc(1, sizeof(*pSnap));
  if (pSnap == NULL) {
H
Hongze Cheng 已提交
4818 4819 4820 4821 4822
    code = TSDB_CODE_OUT_OF_MEMORY;
    goto _exit;
  }

  // lock
H
Hongze Cheng 已提交
4823
  taosThreadRwlockRdlock(&pTsdb->rwLock);
H
Hongze Cheng 已提交
4824 4825

  // take snapshot
H
Hongze Cheng 已提交
4826
  if (pTsdb->mem && (pRange->minVer <= pTsdb->mem->maxVer && pRange->maxVer >= pTsdb->mem->minVer)) {
H
Hongze Cheng 已提交
4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837
    pSnap->pMem = pTsdb->mem;
    pSnap->pNode = taosMemoryMalloc(sizeof(*pSnap->pNode));
    if (pSnap->pNode == NULL) {
      taosThreadRwlockUnlock(&pTsdb->rwLock);
      code = TSDB_CODE_OUT_OF_MEMORY;
      goto _exit;
    }
    pSnap->pNode->pQHandle = pReader;
    pSnap->pNode->reseek = reseek;

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

H
Hongze Cheng 已提交
4840
  if (pTsdb->imem && (pRange->minVer <= pTsdb->imem->maxVer && pRange->maxVer >= pTsdb->imem->minVer)) {
H
Hongze Cheng 已提交
4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851
    pSnap->pIMem = pTsdb->imem;
    pSnap->pINode = taosMemoryMalloc(sizeof(*pSnap->pINode));
    if (pSnap->pINode == NULL) {
      taosThreadRwlockUnlock(&pTsdb->rwLock);
      code = TSDB_CODE_OUT_OF_MEMORY;
      goto _exit;
    }
    pSnap->pINode->pQHandle = pReader;
    pSnap->pINode->reseek = reseek;

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

H
Hongze Cheng 已提交
4854
  // fs
H
Hongze Cheng 已提交
4855
  code = tsdbFSRef(pTsdb, &pSnap->fs);
H
Hongze Cheng 已提交
4856 4857 4858 4859
  if (code) {
    taosThreadRwlockUnlock(&pTsdb->rwLock);
    goto _exit;
  }
H
Hongze Cheng 已提交
4860 4861

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

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

H
Hongze Cheng 已提交
4866
_exit:
H
Hongze Cheng 已提交
4867 4868 4869 4870 4871 4872 4873 4874 4875 4876
  if (code) {
    *ppSnap = NULL;
    if (pSnap) {
      if (pSnap->pNode) taosMemoryFree(pSnap->pNode);
      if (pSnap->pINode) taosMemoryFree(pSnap->pINode);
      taosMemoryFree(pSnap);
    }
  } else {
    *ppSnap = pSnap;
  }
H
Hongze Cheng 已提交
4877 4878 4879
  return code;
}

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

H
Hongze Cheng 已提交
4883 4884
  if (pSnap) {
    if (pSnap->pMem) {
4885
      tsdbUnrefMemTable(pSnap->pMem, pSnap->pNode, proactive);
H
Hongze Cheng 已提交
4886 4887 4888
    }

    if (pSnap->pIMem) {
4889
      tsdbUnrefMemTable(pSnap->pIMem, pSnap->pINode, proactive);
H
Hongze Cheng 已提交
4890 4891
    }

H
Hongze Cheng 已提交
4892
    tsdbFSUnref(pTsdb, &pSnap->fs);
H
Hongze Cheng 已提交
4893 4894
    if (pSnap->pNode) taosMemoryFree(pSnap->pNode);
    if (pSnap->pINode) taosMemoryFree(pSnap->pINode);
H
Hongze Cheng 已提交
4895
    taosMemoryFree(pSnap);
H
Hongze Cheng 已提交
4896
  }
4897
  tsdbTrace("vgId:%d, untake read snapshot", TD_VID(pTsdb->pVnode));
H
Hongze Cheng 已提交
4898
}