• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

taosdata / TDengine / #3525

10 Nov 2024 03:50AM UTC coverage: 60.818% (-0.08%) from 60.898%
#3525

push

travis-ci

web-flow
Merge pull request #28709 from taosdata/main

merge: from main to 3.0 branch

118634 of 249004 branches covered (47.64%)

Branch coverage included in aggregate %.

136 of 169 new or added lines in 23 files covered. (80.47%)

542 existing lines in 129 files now uncovered.

199071 of 273386 relevant lines covered (72.82%)

15691647.46 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

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

16
#include "osDef.h"
17
#include "tsdb.h"
18
#include "tsdbDataFileRW.h"
19
#include "tsdbFS2.h"
20
#include "tsdbMerge.h"
21
#include "tsdbReadUtil.h"
22
#include "tsdbUtil2.h"
23
#include "tsimplehash.h"
24

25
#define ASCENDING_TRAVERSE(o)       (o == TSDB_ORDER_ASC)
26
#define getCurrentKeyInSttBlock(_r) (&((_r)->currentKey))
27
#define tColRowGetKeyDeepCopy(_pBlock, _irow, _slotId, _pKey)      \
28
  do {                                                             \
29
    (_pKey)->ts = (_pBlock)->aTSKEY[(_irow)];                      \
30
    (_pKey)->numOfPKs = 0;                                         \
31
    if ((_slotId) != -1) {                                         \
32
      tColRowGetPriamyKeyDeepCopy(_pBlock, _irow, _slotId, _pKey); \
33
    }                                                              \
34
  } while (0)
35

36
#define outOfTimeWindow(_ts, _window) (((_ts) > (_window)->ekey) || ((_ts) < (_window)->skey))
37

38
typedef struct {
39
  bool overlapWithNeighborBlock;
40
  bool hasDupTs;
41
  bool overlapWithDelInfo;
42
  bool overlapWithSttBlock;
43
  bool overlapWithKeyInBuf;
44
  bool partiallyRequired;
45
  bool moreThanCapcity;
46
} SDataBlockToLoadInfo;
47

48
static int32_t  getCurrentBlockInfo(SDataBlockIter* pBlockIter, SFileDataBlockInfo** pInfo, const char* idStr);
49
static int32_t  buildDataBlockFromBufImpl(STableBlockScanInfo* pBlockScanInfo, int64_t endKey, int32_t capacity,
50
                                          STsdbReader* pReader);
51
static void     getValidMemRow(SIterInfo* pIter, const SArray* pDelList, STsdbReader* pReader, TSDBROW** pRes);
52
static int32_t  doMergeRowsInFileBlocks(SBlockData* pBlockData, STableBlockScanInfo* pScanInfo, SRowKey* pKey,
53
                                        STsdbReader* pReader);
54
static int32_t  doMergeRowsInSttBlock(SSttBlockReader* pSttBlockReader, STableBlockScanInfo* pScanInfo,
55
                                      SRowMerger* pMerger, int32_t pkSrcSlot, SVersionRange* pVerRange, const char* id);
56
static int32_t  doMergeRowsInBuf(SIterInfo* pIter, uint64_t uid, SRowKey* pCurKey, SArray* pDelList,
57
                                 STsdbReader* pReader);
58
static int32_t  doAppendRowFromTSRow(SSDataBlock* pBlock, STsdbReader* pReader, SRow* pTSRow,
59
                                     STableBlockScanInfo* pScanInfo);
60
static int32_t  doAppendRowFromFileBlock(SSDataBlock* pResBlock, STsdbReader* pReader, SBlockData* pBlockData,
61
                                         int32_t rowIndex);
62
static void     setComposedBlockFlag(STsdbReader* pReader, bool composed);
63
static bool     hasBeenDropped(const SArray* pDelList, int32_t* index, int64_t key, int64_t ver, int32_t order,
64
                               SVersionRange* pVerRange, bool hasPk);
65

66
static int32_t doMergeMemTableMultiRows(TSDBROW* pRow, SRowKey* pKey, uint64_t uid, SIterInfo* pIter, SArray* pDelList,
67
                                        TSDBROW* pResRow, STsdbReader* pReader, bool* freeTSRow);
68
static int32_t doMergeMemIMemRows(TSDBROW* pRow, SRowKey* pRowKey, TSDBROW* piRow, SRowKey* piRowKey,
69
                                  STableBlockScanInfo* pBlockScanInfo, STsdbReader* pReader, SRow** pTSRow);
70
static int32_t mergeRowsInFileBlocks(SBlockData* pBlockData, STableBlockScanInfo* pBlockScanInfo, SRowKey* pKey,
71
                                     STsdbReader* pReader);
72
static int32_t mergeRowsInSttBlocks(SSttBlockReader* pSttBlockReader, STableBlockScanInfo* pScanInfo,
73
                                    STsdbReader* pReader);
74

75
static int32_t initDelSkylineIterator(STableBlockScanInfo* pBlockScanInfo, int32_t order, SReadCostSummary* pCost);
76
static void getTsdbByRetentions(SVnode* pVnode, SQueryTableDataCond* pCond, SRetention* retentions, const char* idstr,
77
                                int8_t* pLevel, STsdb** pTsdb);
78
static SVersionRange getQueryVerRange(SVnode* pVnode, SQueryTableDataCond* pCond, int8_t level);
79
static int32_t       doBuildDataBlock(STsdbReader* pReader);
80
static TSDBKEY       getCurrentKeyInBuf(STableBlockScanInfo* pScanInfo, STsdbReader* pReader);
81
static bool          hasDataInFileBlock(const SBlockData* pBlockData, const SFileBlockDumpInfo* pDumpInfo);
82
static bool          hasDataInSttBlock(STableBlockScanInfo* pInfo);
83
static void          initBlockDumpInfo(STsdbReader* pReader, SDataBlockIter* pBlockIter);
84
static int32_t       getInitialDelIndex(const SArray* pDelSkyline, int32_t order);
85
static int32_t       resetTableListIndex(SReaderStatus* pStatus, const char* id);
86
static void          getMemTableTimeRange(STsdbReader* pReader, int64_t* pMaxKey, int64_t* pMinKey);
87
static void          updateComposedBlockInfo(STsdbReader* pReader, double el, STableBlockScanInfo* pBlockScanInfo);
88
static int32_t       buildFromPreFilesetBuffer(STsdbReader* pReader);
89

90
static void resetPreFilesetMemTableListIndex(SReaderStatus* pStatus);
91

92
FORCE_INLINE int32_t pkCompEx(SRowKey* p1, SRowKey* p2) {
100,531✔
93
  if (p2 == NULL) {
1,900,385,487!
94
    return 1;
445,675,745✔
95
  }
96

97
  if (p1 == NULL) {
2,005,279,243!
98
    return -1;
×
99
  }
100

101
  if (p1->ts < p2->ts) {
2,005,279,243!
102
    return -1;
1,188,119,714✔
103
  } else if (p1->ts > p2->ts) {
817,159,529!
104
    return 1;
337,109,432✔
105
  }
106

107
  if (p1->numOfPKs == 0) {
480,050,097!
108
    return 0;
469,374,004✔
109
  } else {
110
    return tRowKeyCompare(p1, p2);
10,676,093✔
111
  }
112
}
113

114
static void tColRowGetPriamyKeyDeepCopy(SBlockData* pBlock, int32_t irow, int32_t slotId, SRowKey* pKey) {
49,887,400✔
115
  SColData* pColData = &pBlock->aColData[slotId];
49,887,400✔
116
  SColVal   cv;
117
  tColDataGetValue(pColData, irow, &cv);
49,887,400✔
118

119
  pKey->numOfPKs = 1;
54,195,981✔
120
  pKey->pks[0].type = cv.value.type;
54,195,981✔
121

122
  if (IS_NUMERIC_TYPE(cv.value.type)) {
54,195,981!
123
    pKey->pks[0].val = cv.value.val;
51,557,322✔
124
  } else {
125
    pKey->pks[0].nData = cv.value.nData;
2,638,659✔
126
    (void)memcpy(pKey->pks[0].pData, cv.value.pData, cv.value.nData);
2,638,659✔
127
  }
128
}
54,195,981✔
129

130
// for test purpose, todo remove it
131
static int32_t tGetPrimaryKeyIndex(uint8_t* p, SPrimaryKeyIndex* index) {
23,311,903✔
132
  int32_t n = 0;
23,311,903✔
133
  n += tGetI8(p + n, &index->type);
23,311,903!
134
  n += tGetU32v(p + n, &index->offset);
23,311,903✔
135
  return n;
23,311,903✔
136
}
137

138
static void tRowGetPrimaryKeyDeepCopy(SRow* pRow, SRowKey* pKey) {
23,311,244✔
139
  SPrimaryKeyIndex indices[TD_MAX_PK_COLS];
140

141
  uint8_t* data = pRow->data;
23,311,244✔
142
  for (int32_t i = 0; i < pRow->numOfPKs; i++) {
46,618,090✔
143
    data += tGetPrimaryKeyIndex(data, &indices[i]);
23,312,025✔
144
  }
145

146
  // primary keys
147
  for (int32_t i = 0; i < pRow->numOfPKs; i++) {
46,643,437✔
148
    pKey->pks[i].type = indices[i].type;
23,337,372✔
149

150
    uint8_t* tdata = data + indices[i].offset;
23,337,372✔
151
    if (pRow->flag >> 4) {
23,337,372✔
152
      tdata += tGetI16v(tdata, NULL);
5,864,036✔
153
    }
154

155
    if (IS_VAR_DATA_TYPE(indices[i].type)) {
23,337,372!
156
      tdata += tGetU32v(tdata, &pKey->pks[i].nData);
1,767,349!
157
      (void)memcpy(pKey->pks[i].pData, tdata, pKey->pks[i].nData);
1,767,349✔
158
    } else {
159
      (void)memcpy(&pKey->pks[i].val, data + indices[i].offset, tDataTypes[pKey->pks[i].type].bytes);
21,570,023✔
160
    }
161
  }
162
}
23,306,065✔
163

164
static int32_t setColumnIdSlotList(SBlockLoadSuppInfo* pSupInfo, SColumnInfo* pCols, const int32_t* pSlotIdList,
5,075,398✔
165
                                   int32_t numOfCols) {
166
  bool initSucc = true;
5,075,398✔
167

168
  pSupInfo->pk.pk = 0;
5,075,398✔
169
  pSupInfo->numOfPks = 0;
5,075,398✔
170
  pSupInfo->pkSrcSlot = -1;
5,075,398✔
171
  pSupInfo->pkDstSlot = -1;
5,075,398✔
172
  pSupInfo->smaValid = true;
5,075,398✔
173
  pSupInfo->numOfCols = numOfCols;
5,075,398✔
174

175
  pSupInfo->colId = taosMemoryMalloc(numOfCols * (sizeof(int16_t) * 2 + POINTER_BYTES));
5,075,398✔
176
  if (pSupInfo->colId == NULL) {
5,081,226!
177
    taosMemoryFree(pSupInfo->colId);
×
178
    return terrno;
×
179
  }
180

181
  pSupInfo->slotId = (int16_t*)((char*)pSupInfo->colId + (sizeof(int16_t) * numOfCols));
5,082,022✔
182
  pSupInfo->buildBuf = (char**)((char*)pSupInfo->slotId + (sizeof(int16_t) * numOfCols));
5,082,022✔
183
  for (int32_t i = 0; i < numOfCols; ++i) {
30,659,360✔
184
    pSupInfo->colId[i] = pCols[i].colId;
25,566,904✔
185
    pSupInfo->slotId[i] = pSlotIdList[i];
25,566,904✔
186

187
    if (IS_VAR_DATA_TYPE(pCols[i].type)) {
25,566,904!
188
      pSupInfo->buildBuf[i] = taosMemoryMalloc(pCols[i].bytes);
3,775,331✔
189
      if (pSupInfo->buildBuf[i] == NULL) {
3,785,638!
190
        tsdbError("failed to prepare memory for set columnId slot list, size:%d, code:out of memory", pCols[i].bytes);
×
191
        initSucc = false;
×
192
      }
193
    } else {
194
      pSupInfo->buildBuf[i] = NULL;
21,791,573✔
195
    }
196

197
    if (pCols[i].pk) {
25,577,338✔
198
      pSupInfo->pk = pCols[i];
252,582✔
199
      pSupInfo->pkSrcSlot = i - 1;
252,582✔
200
      pSupInfo->pkDstSlot = pSlotIdList[i];
252,582✔
201
      pSupInfo->numOfPks += 1;
252,582✔
202
    }
203
  }
204

205
  return (initSucc)? TSDB_CODE_SUCCESS:TSDB_CODE_OUT_OF_MEMORY;
5,092,456✔
206
}
207

208
static int32_t updateBlockSMAInfo(STSchema* pSchema, SBlockLoadSuppInfo* pSupInfo) {
5,024,207✔
209
  int32_t i = 0, j = 0;
5,024,207✔
210

211
  while (i < pSchema->numOfCols && j < pSupInfo->numOfCols) {
63,532,912✔
212
    STColumn* pTCol = &pSchema->columns[i];
58,534,843✔
213
    if (pTCol->colId == pSupInfo->colId[j]) {
58,534,843✔
214
      if (!IS_BSMA_ON(pTCol) && (PRIMARYKEY_TIMESTAMP_COL_ID != pTCol->colId)) {
24,970,439✔
215
        pSupInfo->smaValid = false;
31,835✔
216
        return TSDB_CODE_SUCCESS;
31,835✔
217
      }
218

219
      i += 1;
24,938,604✔
220
      j += 1;
24,938,604✔
221
    } else if (pTCol->colId < pSupInfo->colId[j]) {  // do nothing
33,564,404!
222
      i += 1;
33,570,101✔
223
    } else {
224
      return TSDB_CODE_TDB_INVALID_TABLE_SCHEMA_VER;
×
225
    }
226
  }
227

228
  return TSDB_CODE_SUCCESS;
4,998,069✔
229
}
230

231
static bool isEmptyQueryTimeWindow(STimeWindow* pWindow) { return pWindow->skey > pWindow->ekey; }
20,443,344✔
232

233
// Update the query time window according to the data time to live(TTL) information, in order to avoid to return
234
// the expired data to client, even it is queried already.
235
static STimeWindow updateQueryTimeWindow(STsdb* pTsdb, STimeWindow* pWindow) {
5,101,738✔
236
  int64_t     earlyTs = tsdbGetEarliestTs(pTsdb);
5,101,738✔
237
  STimeWindow win = *pWindow;
5,105,933✔
238
  if (win.skey < earlyTs) {
5,105,933✔
239
    win.skey = earlyTs;
2,896,098✔
240
  }
241

242
  return win;
5,105,933✔
243
}
244

245
// init file iterator
246
static int32_t initFilesetIterator(SFilesetIter* pIter, TFileSetArray* pFileSetArray, STsdbReader* pReader) {
4,950,412✔
247
  SBlockLoadSuppInfo* pInfo = &pReader->suppInfo;
4,950,412✔
248
  size_t              numOfFileset = TARRAY2_SIZE(pFileSetArray);
4,950,412✔
249
  bool                asc = ASCENDING_TRAVERSE(pReader->info.order);
4,950,412✔
250
  int32_t             code = TSDB_CODE_SUCCESS;
4,950,412✔
251

252
  pIter->index = asc ? -1 : numOfFileset;
4,950,412✔
253
  pIter->order = pReader->info.order;
4,950,412✔
254
  pIter->pFilesetList = pFileSetArray;
4,950,412✔
255
  pIter->numOfFiles = numOfFileset;
4,950,412✔
256

257
  if (pIter->pSttBlockReader == NULL) {
4,950,412✔
258
    pIter->pSttBlockReader = taosMemoryCalloc(1, sizeof(struct SSttBlockReader));
4,931,081✔
259
    if (pIter->pSttBlockReader == NULL) {
4,928,890!
260
      tsdbError("failed to prepare the last block iterator, since:%s %s", tstrerror(terrno), pReader->idStr);
×
261
      return terrno;
×
262
    }
263
  }
264

265
  SSttBlockReader* pSttReader = pIter->pSttBlockReader;
4,948,221✔
266
  pSttReader->order = pReader->info.order;
4,948,221✔
267
  pSttReader->window = pReader->info.window;
4,948,221✔
268
  pSttReader->verRange = pReader->info.verRange;
4,948,221✔
269
  pSttReader->numOfPks = pReader->suppInfo.numOfPks;
4,948,221✔
270
  pSttReader->uid = 0;
4,948,221✔
271

272
  tMergeTreeClose(&pSttReader->mergeTree);
4,948,221✔
273
  code = initRowKey(&pSttReader->currentKey, INT64_MIN, pInfo->numOfPks, pInfo->pk.type, pInfo->pk.bytes, asc);
4,950,387✔
274
  if (code != TSDB_CODE_SUCCESS) {
4,951,297!
275
    tsdbError("failed init row key, %s", pReader->idStr);
×
276
  } else {
277
    tsdbDebug("init fileset iterator, total files:%d %s", pIter->numOfFiles, pReader->idStr);
4,951,297✔
278
  }
279

280
  return code;
4,951,105✔
281
}
282

283
static int32_t filesetIteratorNext(SFilesetIter* pIter, STsdbReader* pReader, bool* hasNext) {
9,320,475✔
284
  bool    asc = ASCENDING_TRAVERSE(pIter->order);
9,320,475✔
285
  int32_t step = asc ? 1 : -1;
9,320,475✔
286
  int32_t code = 0;
9,320,475✔
287

288
  pIter->index += step;
9,320,475✔
289
  if ((asc && pIter->index >= pIter->numOfFiles) || ((!asc) && pIter->index < 0)) {
9,320,475✔
290
    *hasNext = false;
1,343,720✔
291
    return TSDB_CODE_SUCCESS;
1,343,720✔
292
  }
293

294
  SReadCostSummary* pCost = &pReader->cost;
7,976,755✔
295

296
  pIter->pSttBlockReader->uid = 0;
7,976,755✔
297
  tMergeTreeClose(&pIter->pSttBlockReader->mergeTree);
7,976,755✔
298
  destroySttBlockReader(pReader->status.pLDataIterArray, &pCost->sttCost);
7,978,939✔
299

300
  pReader->status.pLDataIterArray = taosArrayInit(4, POINTER_BYTES);
7,980,384✔
301
  if (pReader->status.pLDataIterArray == NULL) {
7,981,535!
302
    return terrno;
×
303
  }
304

305
  // check file the time range of coverage
306
  STimeWindow win = {0};
7,981,535✔
307

308
  while (1) {
1,002,085✔
309
    if (pReader->pFileReader != NULL) {
8,983,620✔
310
      tsdbDataFileReaderClose(&pReader->pFileReader);
132,569✔
311
    }
312

313
    pReader->status.pCurrentFileset = pIter->pFilesetList->data[pIter->index];
8,983,646✔
314

315
    STFileObj** pFileObj = pReader->status.pCurrentFileset->farr;
8,983,646✔
316
    if (pFileObj[0] != NULL || pFileObj[3] != NULL) {
8,983,646✔
317
      SDataFileReaderConfig conf = {.tsdb = pReader->pTsdb, .szPage = pReader->pTsdb->pVnode->config.tsdbPageSize};
155,139✔
318

319
      const char* filesName[4] = {0};
155,139✔
320

321
      if (pFileObj[0] != NULL) {
155,139✔
322
        conf.files[0].file = *pFileObj[0]->f;
145,956✔
323
        conf.files[0].exist = true;
145,956✔
324
        filesName[0] = pFileObj[0]->fname;
145,956✔
325

326
        conf.files[1].file = *pFileObj[1]->f;
145,956✔
327
        conf.files[1].exist = true;
145,956✔
328
        filesName[1] = pFileObj[1]->fname;
145,956✔
329

330
        conf.files[2].file = *pFileObj[2]->f;
145,956✔
331
        conf.files[2].exist = true;
145,956✔
332
        filesName[2] = pFileObj[2]->fname;
145,956✔
333
      }
334

335
      if (pFileObj[3] != NULL) {
155,139✔
336
        conf.files[3].exist = true;
23,613✔
337
        conf.files[3].file = *pFileObj[3]->f;
23,613✔
338
        filesName[3] = pFileObj[3]->fname;
23,613✔
339
      }
340

341
      code = tsdbDataFileReaderOpen(filesName, &conf, &pReader->pFileReader);
155,139✔
342
      if (code != TSDB_CODE_SUCCESS) {
154,398!
343
        goto _err;
×
344
      }
345

346
      pReader->cost.headFileLoad += 1;
154,398✔
347
    }
348

349
    int32_t fid = pReader->status.pCurrentFileset->fid;
8,982,905✔
350
    tsdbFidKeyRange(fid, pReader->pTsdb->keepCfg.days, pReader->pTsdb->keepCfg.precision, &win.skey, &win.ekey);
8,982,905✔
351

352
    // current file are no longer overlapped with query time window, ignore remain files
353
    if ((asc && win.skey > pReader->info.window.ekey) || (!asc && win.ekey < pReader->info.window.skey)) {
8,980,518✔
354
      tsdbDebug("%p remain files are not qualified for qrange:%" PRId64 "-%" PRId64 ", ignore, %s", pReader,
709,335✔
355
                pReader->info.window.skey, pReader->info.window.ekey, pReader->idStr);
356
      *hasNext = false;
709,848✔
357
      return TSDB_CODE_SUCCESS;
709,848✔
358
    }
359

360
    if ((asc && (win.ekey < pReader->info.window.skey)) || ((!asc) && (win.skey > pReader->info.window.ekey))) {
8,271,183✔
361
      pIter->index += step;
1,261,599✔
362
      if ((asc && pIter->index >= pIter->numOfFiles) || ((!asc) && pIter->index < 0)) {
1,261,599✔
363
        *hasNext = false;
259,514✔
364
        return TSDB_CODE_SUCCESS;
259,514✔
365
      }
366
      continue;
1,002,085✔
367
    }
368

369
    tsdbDebug("%p file found fid:%d for qrange:%" PRId64 "-%" PRId64 ", %s", pReader, fid, pReader->info.window.skey,
7,009,584✔
370
              pReader->info.window.ekey, pReader->idStr);
371

372
    *hasNext = true;
7,009,269✔
373
    return TSDB_CODE_SUCCESS;
7,009,269✔
374
  }
375

376
_err:
×
377
  *hasNext = false;
×
378
  return code;
×
379
}
380

381
bool shouldFreePkBuf(SBlockLoadSuppInfo* pSupp) { return (pSupp->numOfPks > 0) && IS_VAR_DATA_TYPE(pSupp->pk.type); }
17,153,049!
382

383
int32_t resetDataBlockIterator(SDataBlockIter* pIter, int32_t order, bool needFree, const char* id) {
11,949,802✔
384
  pIter->order = order;
11,949,802✔
385
  pIter->index = -1;
11,949,802✔
386
  pIter->numOfBlocks = 0;
11,949,802✔
387

388
  if (pIter->blockList == NULL) {
11,949,802✔
389
    pIter->blockList = taosArrayInit(4, sizeof(SFileDataBlockInfo));
4,929,866✔
390
    if (pIter->blockList == NULL) {
4,928,047!
391
      tsdbError("%s failed to reset block iter, func:%s at line:%d code:%s", id, __func__, __LINE__, tstrerror(terrno));
×
392
      return terrno;
×
393
    }
394
  } else {
395
    clearDataBlockIterator(pIter, needFree);
7,019,936✔
396
  }
397

398
  return TSDB_CODE_SUCCESS;
11,949,894✔
399
}
400

401
static void initReaderStatus(SReaderStatus* pStatus) {
5,081,656✔
402
  pStatus->pTableIter = NULL;
5,081,656✔
403
  pStatus->loadFromFile = true;
5,081,656✔
404
}
5,081,656✔
405

406
static int32_t createResBlock(SQueryTableDataCond* pCond, int32_t capacity, SSDataBlock** pResBlock) {
2,525✔
407
  QRY_PARAM_CHECK(pResBlock);
2,525!
408

409
  SSDataBlock* pBlock = NULL;
2,525✔
410
  int32_t code = createDataBlock(&pBlock);
2,525✔
411
  if (code != 0) {
2,527!
412
    return code;
×
413
  }
414

415
  for (int32_t i = 0; i < pCond->numOfCols; ++i) {
15,902✔
416
    SColumnInfoData colInfo = {0};
13,375✔
417
    colInfo.info = pCond->colList[i];
13,375✔
418
    code = blockDataAppendColInfo(pBlock, &colInfo);
13,375✔
419
    if (code != TSDB_CODE_SUCCESS) {
13,375!
420
      taosMemoryFree(pBlock);
×
421
      return code;
×
422
    }
423
  }
424

425
  code = blockDataEnsureCapacity(pBlock, capacity);
2,527✔
426
  if (code != TSDB_CODE_SUCCESS) {
2,526!
427
    taosMemoryFree(pBlock);
×
428
  }
429

430
  *pResBlock = pBlock;
2,526✔
431
  return code;
2,526✔
432
}
433

434
static int32_t tsdbInitReaderLock(STsdbReader* pReader) {
5,069,136✔
435
  int32_t code = taosThreadMutexInit(&pReader->readerMutex, NULL);
5,069,136✔
436
  tsdbTrace("tsdb/read: %p, post-init read mutex: %p, code: %d", pReader, &pReader->readerMutex, code);
5,073,665✔
437

438
  return code;
5,075,395✔
439
}
440

441
static int32_t tsdbUninitReaderLock(STsdbReader* pReader) {
5,086,579✔
442
  int32_t code = TSDB_CODE_SUCCESS;
5,086,579✔
443
  tsdbTrace("tsdb/read: %p, pre-uninit read mutex: %p, code: %d", pReader, &pReader->readerMutex, code);
5,086,579✔
444

445
  code = taosThreadMutexDestroy(&pReader->readerMutex);
5,086,579✔
446
  tsdbTrace("tsdb/read: %p, post-uninit read mutex: %p, code: %d", pReader, &pReader->readerMutex, code);
5,086,104✔
447

448
  return code;
5,086,375✔
449
}
450

451
static int32_t tsdbAcquireReader(STsdbReader* pReader) {
20,446,611✔
452
  int32_t code = -1;
20,446,611✔
453
  tsdbTrace("tsdb/read: %s, pre-take read mutex: %p, code: %d", pReader->idStr, &pReader->readerMutex, code);
20,446,611✔
454

455
  code = taosThreadMutexLock(&pReader->readerMutex);
20,446,616✔
456
  if (code != 0) {
20,456,453!
457
    tsdbError("tsdb/read:%p, failed to lock reader mutex, code:%s", pReader->idStr, tstrerror(code));
×
458
  } else {
459
    tsdbTrace("tsdb/read: %s, post-take read mutex: %p, code: %d", pReader->idStr, &pReader->readerMutex, code);
20,456,453✔
460
  }
461

462
  return code;
20,455,197✔
463
}
464

465
static int32_t tsdbTryAcquireReader(STsdbReader* pReader) {
2✔
466
  int32_t code = taosThreadMutexTryLock(&pReader->readerMutex);
2✔
467
  if (code != TSDB_CODE_SUCCESS) {
2!
468
    tsdbError("tsdb/read: %p, post-trytake read mutex: %p, code: %d", pReader, &pReader->readerMutex, code);
×
469
  } else {
470
    tsdbTrace("tsdb/read: %p, post-trytask read mutex: %p", pReader, &pReader->readerMutex);
2!
471
  }
472
  return code;
2✔
473
}
474

475
static int32_t tsdbReleaseReader(STsdbReader* pReader) {
20,450,008✔
476
  int32_t code = taosThreadMutexUnlock(&pReader->readerMutex);
20,450,008✔
477
  if (code != TSDB_CODE_SUCCESS) {
20,458,676!
478
    tsdbError("tsdb/read: %p post-untake read mutex:%p failed, code:%d", pReader, &pReader->readerMutex, code);
×
479
  } else {
480
    tsdbTrace("tsdb/read: %p, post-untake read mutex: %p", pReader, &pReader->readerMutex);
20,458,676✔
481
  }
482
  return code;
20,457,143✔
483
}
484

485
void tsdbReleaseDataBlock2(STsdbReader* pReader) {
388,562✔
486
  SReaderStatus* pStatus = &pReader->status;
388,562✔
487
  if (!pStatus->composedDataBlock) {
388,562✔
488
    (void) tsdbReleaseReader(pReader);
132,727✔
489
  }
490
}
388,726✔
491

492
static int32_t initResBlockInfo(SResultBlockInfo* pResBlockInfo, int64_t capacity, SSDataBlock* pResBlock,
5,072,943✔
493
                                SQueryTableDataCond* pCond, SBlockLoadSuppInfo* pSup) {
494
  pResBlockInfo->capacity = capacity;
5,072,943✔
495
  pResBlockInfo->pResBlock = pResBlock;
5,072,943✔
496
  int32_t code = 0;
5,072,943✔
497

498
  if (pResBlockInfo->pResBlock == NULL) {
5,072,943✔
499
    pResBlockInfo->freeBlock = true;
2,524✔
500
    pResBlockInfo->pResBlock = NULL;
2,524✔
501

502
    code = createResBlock(pCond, pResBlockInfo->capacity, &pResBlockInfo->pResBlock);
2,524✔
503
    if (code != TSDB_CODE_SUCCESS) {
2,526!
504
      return code;
×
505
    }
506

507
    if (pSup->numOfPks > 0) {
2,526✔
508
      SSDataBlock* p = pResBlockInfo->pResBlock;
4✔
509
      p->info.pks[0].type = pSup->pk.type;
4✔
510
      p->info.pks[1].type = pSup->pk.type;
4✔
511

512
      if (IS_VAR_DATA_TYPE(pSup->pk.type)) {
4!
513
        p->info.pks[0].pData = taosMemoryCalloc(1, pSup->pk.bytes);
2,154✔
514
        if (p->info.pks[0].pData == NULL) {
2!
515
          return terrno;
×
516
        }
517

518
        p->info.pks[1].pData = taosMemoryCalloc(1, pSup->pk.bytes);
2✔
519
        if (p->info.pks[1].pData == NULL) {
2!
520
          taosMemoryFreeClear(p->info.pks[0].pData);
×
521
          return terrno;
×
522
        }
523

524
        p->info.pks[0].nData = pSup->pk.bytes;
2✔
525
        p->info.pks[1].nData = pSup->pk.bytes;
2✔
526
      }
527
    }
528
  } else {
529
    pResBlockInfo->freeBlock = false;
5,070,419✔
530
  }
531

532
  return code;
5,070,793✔
533
}
534

535
static int32_t tsdbReaderCreate(SVnode* pVnode, SQueryTableDataCond* pCond, void** ppReader, int32_t capacity,
5,082,034✔
536
                                SSDataBlock* pResBlock, const char* idstr) {
537
  int32_t      code = 0;
5,082,034✔
538
  int8_t       level = 0;
5,082,034✔
539
  STsdbReader* pReader = (STsdbReader*)taosMemoryCalloc(1, sizeof(*pReader));
5,082,034✔
540
  if (pReader == NULL) {
5,079,068!
541
    code = terrno;
×
542
    goto _end;
×
543
  }
544

545
  if (VND_IS_TSMA(pVnode)) {
5,079,068!
546
    tsdbDebug("vgId:%d, tsma is selected to query, %s", TD_VID(pVnode), idstr);
×
547
  }
548

549
  initReaderStatus(&pReader->status);
5,079,068✔
550
  getTsdbByRetentions(pVnode, pCond, pVnode->config.tsdbCfg.retentions, idstr, &level, &pReader->pTsdb);
5,081,621✔
551

552
  pReader->info.suid = pCond->suid;
5,082,652✔
553
  pReader->info.order = pCond->order;
5,082,652✔
554
  pReader->info.verRange = getQueryVerRange(pVnode, pCond, level);
5,082,652✔
555
  pReader->info.window = updateQueryTimeWindow(pReader->pTsdb, &pCond->twindows);
5,083,481✔
556

557
  pReader->idStr = (idstr != NULL) ? taosStrdup(idstr) : NULL;
5,085,460✔
558
  if (idstr != NULL && pReader->idStr == NULL) {
5,080,804!
559
    code = terrno;
×
560
    goto _end;
×
561
  }
562

563
  pReader->type = pCond->type;
5,080,804✔
564
  pReader->bFilesetDelimited = false;
5,080,804✔
565
  pReader->blockInfoBuf.numPerBucket = 1000;  // 1000 tables per bucket
5,080,804✔
566

567
  if (pCond->numOfCols <= 0) {
5,080,804!
568
    tsdbError("vgId:%d, invalid column number %d in query cond, %s", TD_VID(pVnode), pCond->numOfCols, idstr);
×
569
    code = TSDB_CODE_INVALID_PARA;
×
570
    goto _end;
×
571
  }
572

573
  // allocate buffer in order to load data blocks from file
574
  SBlockLoadSuppInfo* pSup = &pReader->suppInfo;
5,080,804✔
575
  pSup->tsColAgg.colId = PRIMARYKEY_TIMESTAMP_COL_ID;
5,080,804✔
576
  code = setColumnIdSlotList(pSup, pCond->colList, pCond->pSlotList, pCond->numOfCols);
5,080,804✔
577
  if (code != TSDB_CODE_SUCCESS) {
5,082,671!
578
    goto _end;
×
579
  }
580

581
  code = initResBlockInfo(&pReader->resBlockInfo, capacity, pResBlock, pCond, pSup);
5,082,671✔
582
  if (code != TSDB_CODE_SUCCESS) {
5,070,964!
583
    goto _end;
×
584
  }
585

586
  code = tBlockDataCreate(&pReader->status.fileBlockData);
5,070,964✔
587
  if (code != TSDB_CODE_SUCCESS) {
5,069,188!
588
    goto _end;
×
589
  }
590

591
  if (pReader->suppInfo.colId[0] != PRIMARYKEY_TIMESTAMP_COL_ID) {
5,069,188!
592
    tsdbError("the first column isn't primary timestamp, %d, %s", pReader->suppInfo.colId[0], pReader->idStr);
×
593
    code = TSDB_CODE_INVALID_PARA;
×
594
    goto _end;
×
595
  }
596

597
  pReader->status.pPrimaryTsCol = taosArrayGet(pReader->resBlockInfo.pResBlock->pDataBlock, pSup->slotId[0]);
5,069,188✔
598
  if (pReader->status.pPrimaryTsCol == NULL) {
5,069,052!
599
    code = terrno;
×
600
    goto _end;
×
601
  }
602

603
  int32_t type = pReader->status.pPrimaryTsCol->info.type;
5,074,312✔
604
  if (type != TSDB_DATA_TYPE_TIMESTAMP) {
5,074,312!
605
    tsdbError("the first column isn't primary timestamp in result block, actual: %s, %s", tDataTypes[type].name,
×
606
              pReader->idStr);
607
    code = TSDB_CODE_INVALID_PARA;
×
608
    goto _end;
×
609
  }
610

611
  code = tsdbInitReaderLock(pReader);
5,074,312✔
612
  if (code != TSDB_CODE_SUCCESS) {
5,075,964!
613
    goto _end;
×
614
  }
615

616
  code = tsem_init(&pReader->resumeAfterSuspend, 0, 0);
5,075,964✔
617
  if (code != TSDB_CODE_SUCCESS) {
5,072,166!
618
    goto _end;
×
619
  }
620

621
  *ppReader = pReader;
5,072,166✔
622
  return code;
5,072,166✔
623

624
_end:
×
625
  tsdbReaderClose2(pReader);
×
626
  *ppReader = NULL;
×
627
  return code;
×
628
}
629

630
static int32_t doLoadBlockIndex(STsdbReader* pReader, SDataFileReader* pFileReader, SArray* pIndexList) {
7,007,225✔
631
  int64_t st = taosGetTimestampUs();
7,009,475✔
632
  int32_t numOfTables = tSimpleHashGetSize(pReader->status.pTableMap);
7,009,475✔
633
  if (pFileReader == NULL) {
7,009,443✔
634
    return TSDB_CODE_SUCCESS;
6,865,446✔
635
  }
636

637
  const TBrinBlkArray* pBlkArray = NULL;
143,997✔
638

639
  int32_t code = tsdbDataFileReadBrinBlk(pFileReader, &pBlkArray);
143,997✔
640
  if (code != TSDB_CODE_SUCCESS) {
143,924!
641
    return code;
×
642
  }
643

644
#if 0
645
  LRUHandle* handle = NULL;
646

647
  int32_t    code = tsdbCacheGetBlockIdx(pFileReader->pTsdb->biCache, pFileReader, &handle);
648
  if (code != TSDB_CODE_SUCCESS || handle == NULL) {
649
    goto _end;
650
  }
651

652

653
  SArray* aBlockIdx = (SArray*)taosLRUCacheValue(pFileReader->pTsdb->biCache, handle);
654
  size_t  num = taosArrayGetSize(aBlockIdx);
655
  if (num == 0) {
656
    tsdbBICacheRelease(pFileReader->pTsdb->biCache, handle);
657
    return TSDB_CODE_SUCCESS;
658
  }
659
#endif
660

661
  // todo binary search to the start position
662
  int64_t et1 = taosGetTimestampUs();
144,009✔
663

664
  SBrinBlk*      pBrinBlk = NULL;
144,009✔
665
  STableUidList* pList = &pReader->status.uidList;
144,009✔
666

667
  int32_t i = 0;
144,009✔
668
  while (i < TARRAY2_SIZE(pBlkArray)) {
277,141✔
669
    pBrinBlk = &pBlkArray->data[i];
135,750✔
670
    if (pBrinBlk->maxTbid.suid < pReader->info.suid) {
135,750✔
671
      i += 1;
1,445✔
672
      continue;
1,445✔
673
    }
674

675
    if (pBrinBlk->minTbid.suid > pReader->info.suid) {  // not include the queried table/super table, quit the loop
134,305✔
676
      break;
2,092✔
677
    }
678

679
    if (!(pBrinBlk->minTbid.suid <= pReader->info.suid && pBrinBlk->maxTbid.suid >= pReader->info.suid)) {
132,213!
680
      tsdbError("tsdb failed at: %s %d", __func__, __LINE__);
×
681
      return TSDB_CODE_INTERNAL_ERROR;
×
682
    }
683
    if (pBrinBlk->maxTbid.suid == pReader->info.suid && pBrinBlk->maxTbid.uid < pList->tableUidList[0]) {
132,334✔
684
      i += 1;
1,969✔
685
      continue;
1,969✔
686
    }
687

688
    if (pBrinBlk->minTbid.suid == pReader->info.suid && pBrinBlk->minTbid.uid > pList->tableUidList[numOfTables - 1]) {
130,365✔
689
      break;
487✔
690
    }
691

692
    void* p1 = taosArrayPush(pIndexList, pBrinBlk);
129,718✔
693
    if (p1 == NULL) {
129,718!
694
      return terrno;
×
695
    }
696

697
    i += 1;
129,718✔
698
  }
699

700
  int64_t et2 = taosGetTimestampUs();
144,153✔
701
  tsdbDebug("load block index for %d/%d tables completed, elapsed time:%.2f ms, set BrinBlk:%.2f ms, size:%.2f Kb %s",
144,153✔
702
            numOfTables, (int32_t)pBlkArray->size, (et1 - st) / 1000.0, (et2 - et1) / 1000.0,
703
            pBlkArray->size * sizeof(SBrinBlk) / 1024.0, pReader->idStr);
704

705
  pReader->cost.headFileLoadTime += (et1 - st) / 1000.0;
144,197✔
706

707
//_end:
708
  //  tsdbBICacheRelease(pFileReader->pTsdb->biCache, handle);
709
  return code;
144,197✔
710
}
711

712
static int32_t loadFileBlockBrinInfo(STsdbReader* pReader, SArray* pIndexList, SBlockNumber* pBlockNum,
7,004,997✔
713
                                     SArray* pTableScanInfoList) {
714
  int32_t         k = 0;
7,004,997✔
715
  size_t          sizeInDisk = 0;
7,004,997✔
716
  int64_t         st = taosGetTimestampUs();
7,007,061✔
717
  bool            asc = ASCENDING_TRAVERSE(pReader->info.order);
7,007,061✔
718
  STimeWindow     w = pReader->info.window;
7,007,061✔
719
  SBrinRecord*    pRecord = NULL;
7,007,061✔
720
  int32_t         numOfTables = tSimpleHashGetSize(pReader->status.pTableMap);
7,007,061✔
721
  SBrinRecordIter iter = {0};
7,007,576✔
722

723
  // clear info for the new file
724
  cleanupInfoForNextFileset(pReader->status.pTableMap);
7,007,576✔
725
  initBrinRecordIter(&iter, pReader->pFileReader, pIndexList);
7,008,701✔
726

727
  while (1) {
2,987,058✔
728
    int32_t code = getNextBrinRecord(&iter, &pRecord);
9,995,193✔
729
    if (code != TSDB_CODE_SUCCESS) {
9,995,017!
730
      clearBrinBlockIter(&iter);
×
731
      return code;
×
732
    }
733

734
    if (pRecord == NULL) {
9,995,507✔
735
      break;
6,995,390✔
736
    }
737

738
    if (pRecord->suid > pReader->info.suid) {
3,000,117✔
739
      break;
5,166✔
740
    }
741

742
    uint64_t uid = pReader->status.uidList.tableUidList[k];
2,994,951✔
743
    if (pRecord->suid < pReader->info.suid) {
2,994,951✔
744
      continue;
2,193,590✔
745
    }
746

747
    if (uid < pRecord->uid) {  // forward the table uid index
2,989,557✔
748
      while (k < numOfTables && pReader->status.uidList.tableUidList[k] < pRecord->uid) {
709,936✔
749
        k += 1;
361,286✔
750
      }
751

752
      if (k >= numOfTables) {
348,650✔
753
        break;
8,223✔
754
      }
755

756
      uid = pReader->status.uidList.tableUidList[k];
340,427✔
757
    }
758

759
    if (pRecord->uid < uid) {
2,981,334✔
760
      continue;
2,130,377✔
761
    }
762

763
    if (!(pRecord->suid == pReader->info.suid && uid == pRecord->uid)) {
850,957!
764
      tsdbError("tsdb failed at: %s:%d", __func__, __LINE__);
21!
765
      clearBrinBlockIter(&iter);
21✔
766
      return TSDB_CODE_INTERNAL_ERROR;
×
767
    }
768

769
    STableBlockScanInfo* pScanInfo = NULL;
850,936✔
770
    code = getTableBlockScanInfo(pReader->status.pTableMap, uid, &pScanInfo, pReader->idStr);
850,936✔
771
    if (code != TSDB_CODE_SUCCESS) {
850,789!
772
      clearBrinBlockIter(&iter);
×
773
      return code;
×
774
    }
775

776
    // here we should find the first timestamp that is greater than the lastProcKey
777
    // the window is an open interval NOW.
778
    if (asc) {
850,836✔
779
      w.skey = pScanInfo->lastProcKey.ts;
797,174✔
780
    } else {
781
      w.ekey = pScanInfo->lastProcKey.ts;
53,662✔
782
    }
783

784
    // NOTE: specialized for open interval
785
    if (((w.skey < INT64_MAX) && ((w.skey + 1) > w.ekey)) || (w.skey == INT64_MAX)) {
850,836!
786
      k += 1;
×
787
      if (k >= numOfTables) {
×
788
        break;
×
789
      } else {
790
        continue;
×
791
      }
792
    }
793

794
    // 1. time range check
795
    if (pRecord->firstKey.key.ts > w.ekey || pRecord->lastKey.key.ts < w.skey) {
850,894✔
796
      continue;
57,884✔
797
    }
798

799
    if (asc) {
793,010✔
800
      if (pkCompEx(&pRecord->lastKey.key, &pScanInfo->lastProcKey) <= 0) {
1,547,907!
801
        continue;
3✔
802
      }
803
    } else {
804
      if (pkCompEx(&pRecord->firstKey.key, &pScanInfo->lastProcKey) >= 0) {
38,007!
805
        continue;
×
806
      }
807
    }
808

809
    // 2. version range check, version range is an CLOSED interval
810
    if (pRecord->minVer > pReader->info.verRange.maxVer || pRecord->maxVer < pReader->info.verRange.minVer) {
792,901!
UNCOV
811
      continue;
×
812
    }
813

814
    if (pScanInfo->pBlockList == NULL) {
792,911✔
815
      pScanInfo->pBlockList = taosArrayInit(4, sizeof(SFileDataBlockInfo));
459,890✔
816
      if (pScanInfo->pBlockList == NULL) {
460,025!
817
        clearBrinBlockIter(&iter);
×
818
        return terrno;
×
819
      }
820
    }
821

822
    if (pScanInfo->pBlockIdxList == NULL) {
793,046✔
823
      pScanInfo->pBlockIdxList = taosArrayInit(4, sizeof(STableDataBlockIdx));
166,747✔
824
      if (pScanInfo->pBlockIdxList == NULL) {
166,764!
825
        clearBrinBlockIter(&iter);
×
826
        return terrno;
×
827
      }
828
    }
829

830
    SFileDataBlockInfo blockInfo = {.tbBlockIdx = TARRAY_SIZE(pScanInfo->pBlockList)};
793,063✔
831
    code = recordToBlockInfo(&blockInfo, pRecord);
793,063✔
832
    if (code != TSDB_CODE_SUCCESS) {
793,941!
833
      clearBrinBlockIter(&iter);
×
834
      return code;
×
835
    }
836
    void* p1 = taosArrayPush(pScanInfo->pBlockList, &blockInfo);
793,941✔
837
    if (p1 == NULL) {
794,018!
838
      clearBrinBlockIter(&iter);
×
839
      return terrno;
×
840
    }
841

842
    // todo: refactor to record the fileset skey/ekey
843
    if (pScanInfo->filesetWindow.skey > pRecord->firstKey.key.ts) {
794,018✔
844
      pScanInfo->filesetWindow.skey = pRecord->firstKey.key.ts;
459,957✔
845
    }
846

847
    if (pScanInfo->filesetWindow.ekey < pRecord->lastKey.key.ts) {
794,018!
848
      pScanInfo->filesetWindow.ekey = pRecord->lastKey.key.ts;
794,129✔
849
    }
850

851
    pBlockNum->numOfBlocks += 1;
794,018✔
852
    if (taosArrayGetSize(pTableScanInfoList) == 0) {
794,018✔
853
      p1 = taosArrayPush(pTableScanInfoList, &pScanInfo);
119,962✔
854
    } else {
855
      STableBlockScanInfo** p = taosArrayGetLast(pTableScanInfoList);
674,023✔
856
      if (p == NULL) {
674,121✔
857
        clearBrinBlockIter(&iter);
595✔
858
        tsdbError("invalid param, empty in tablescanInfoList, %s", pReader->idStr);
×
859
        return TSDB_CODE_INVALID_PARA;
×
860
      }
861

862
      if ((*p)->uid != uid) {
673,526✔
863
        p1 = taosArrayPush(pTableScanInfoList, &pScanInfo);
340,066✔
864
      }
865
    }
866

867
    if (p1 == NULL) {
793,468!
868
      clearBrinBlockIter(&iter);
×
869
      return terrno;
×
870
    }
871
  }
872

873
  clearBrinBlockIter(&iter);
7,008,779✔
874

875
  pBlockNum->numOfSttFiles = pReader->status.pCurrentFileset->lvlArr->size;
7,002,923✔
876
  int32_t total = pBlockNum->numOfSttFiles + pBlockNum->numOfBlocks;
7,002,923✔
877

878
  double el = (taosGetTimestampUs() - st) / 1000.0;
7,005,836✔
879
  tsdbDebug(
7,005,836✔
880
      "load block of %d tables completed, blocks:%d in %d tables, stt-files:%d, block-info-size:%.2f Kb, elapsed "
881
      "time:%.2f ms %s",
882
      numOfTables, pBlockNum->numOfBlocks, (int32_t)taosArrayGetSize(pTableScanInfoList), pBlockNum->numOfSttFiles,
883
      sizeInDisk / 1000.0, el, pReader->idStr);
884

885
  pReader->cost.numOfBlocks += total;
7,005,673✔
886
  pReader->cost.headFileLoadTime += el;
7,005,673✔
887

888
  return TSDB_CODE_SUCCESS;
7,005,673✔
889
}
890

891
static void setBlockAllDumped(SFileBlockDumpInfo* pDumpInfo, int64_t maxKey, int32_t order) {
1,342,105✔
892
  pDumpInfo->allDumped = true;
1,342,105✔
893
}
1,342,105✔
894

895
static void updateLastKeyInfo(SRowKey* pKey, SFileDataBlockInfo* pBlockInfo, SDataBlockInfo* pInfo, int32_t numOfPks,
722,161✔
896
                              bool asc) {
897
  pKey->ts = asc ? pInfo->window.ekey : pInfo->window.skey;
722,161✔
898
  pKey->numOfPKs = numOfPks;
722,161✔
899
  if (pKey->numOfPKs <= 0) {
722,161✔
900
    return;
392,806✔
901
  }
902

903
  if (IS_NUMERIC_TYPE(pKey->pks[0].type)) {
329,355!
904
    pKey->pks[0].val = asc ? pBlockInfo->lastPk.val : pBlockInfo->firstPk.val;
329,355!
905
  } else {
906
    uint8_t* p = asc ? pBlockInfo->lastPk.pData : pBlockInfo->firstPk.pData;
×
907
    pKey->pks[0].nData = asc ? varDataLen(pBlockInfo->lastPk.pData) : varDataLen(pBlockInfo->firstPk.pData);
×
908
    (void)memcpy(pKey->pks[0].pData, p, pKey->pks[0].nData);
×
909
  }
910
}
911

912
static int32_t doCopyColVal(SColumnInfoData* pColInfoData, int32_t rowIndex, int32_t colIndex, SColVal* pColVal,
2,147,483,647✔
913
                            SBlockLoadSuppInfo* pSup) {
914
  int32_t code = 0;
2,147,483,647✔
915

916
  if (IS_VAR_DATA_TYPE(pColVal->value.type)) {
2,147,483,647!
917
    if (!COL_VAL_IS_VALUE(pColVal)) {
781,939,194✔
918
      colDataSetNULL(pColInfoData, rowIndex);
101,259,362✔
919
    } else {
920
      varDataSetLen(pSup->buildBuf[colIndex], pColVal->value.nData);
680,679,832✔
921
      if ((pColVal->value.nData + VARSTR_HEADER_SIZE) > pColInfoData->info.bytes) {
680,679,832✔
922
        tsdbWarn("column cid:%d actual data len %d is bigger than schema len %d", pColVal->cid, pColVal->value.nData,
4!
923
                 pColInfoData->info.bytes);
924
        return TSDB_CODE_TDB_INVALID_TABLE_SCHEMA_VER;
4✔
925
      }
926

927
      if (pColVal->value.nData > 0) {  // pData may be null, if nData is 0
680,679,828!
928
        (void)memcpy(varDataVal(pSup->buildBuf[colIndex]), pColVal->value.pData, pColVal->value.nData);
741,017,434✔
929
      }
930

931
      code = colDataSetVal(pColInfoData, rowIndex, pSup->buildBuf[colIndex], false);
680,679,828✔
932
    }
933
  } else {
934
    code = colDataSetVal(pColInfoData, rowIndex, (const char*)&pColVal->value.val, !COL_VAL_IS_VALUE(pColVal));
2,147,483,647✔
935
  }
936

937
  return code;
2,147,483,647✔
938
}
939

940
static int32_t getCurrentBlockInfo(SDataBlockIter* pBlockIter, SFileDataBlockInfo** pInfo, const char* id) {
10,505,488✔
941
  *pInfo = NULL;
10,505,488✔
942

943
  if (pBlockIter->blockList == NULL) {
10,505,488!
944
    return TSDB_CODE_FAILED;
×
945
  }
946

947
  size_t num = TARRAY_SIZE(pBlockIter->blockList);
10,505,488✔
948
  if (num == 0) {
10,505,488✔
949
    if (num != pBlockIter->numOfBlocks) {
6,881,875!
950
      tsdbError("tsdb read failed at: %s:%d %s", __func__, __LINE__, id);
×
951
    }
952
    return TSDB_CODE_FAILED;
6,882,146✔
953
  }
954

955
  *pInfo = taosArrayGet(pBlockIter->blockList, pBlockIter->index);
3,623,613✔
956
  return (*pInfo) != NULL? TSDB_CODE_SUCCESS:TSDB_CODE_FAILED;
3,627,869!
957
}
958

959
static int32_t doBinarySearchKey(const TSKEY* keyList, int num, int pos, TSKEY key, int order) {
5,718✔
960
  // start end position
961
  int s, e;
962
  s = pos;
5,718✔
963

964
  // check
965
  if (!(pos >= 0 && pos < num && num > 0)) {
5,718!
966
    return -1;
×
967
  }
968
  if (order == TSDB_ORDER_ASC) {
5,718✔
969
    // find the first position which is smaller than the key
970
    e = num - 1;
4,040✔
971
    if (key < keyList[pos]) return -1;
4,040✔
972
    while (1) {
47,474✔
973
      // check can return
974
      if (key >= keyList[e]) return e;
51,506!
975
      if (key <= keyList[s]) return s;
51,506✔
976
      if (e - s <= 1) return s;
51,502✔
977

978
      // change start or end position
979
      int mid = s + (e - s + 1) / 2;
47,473✔
980
      if (keyList[mid] > key)
47,473✔
981
        e = mid;
29,828✔
982
      else if (keyList[mid] < key)
17,645!
983
        s = mid;
17,646✔
984
      else
985
        return mid;
×
986
    }
987
  } else {  // DESC
988
    // find the first position which is bigger than the key
989
    e = 0;
1,678✔
990
    if (key > keyList[pos]) return -1;
1,678!
991
    while (1) {
15,167✔
992
      // check can return
993
      if (key <= keyList[e]) return e;
16,845!
994
      if (key >= keyList[s]) return s;
16,845!
995
      if (s - e <= 1) return s;
16,845✔
996

997
      // change start or end position
998
      int mid = s - (s - e + 1) / 2;
16,809✔
999
      if (keyList[mid] < key)
16,809✔
1000
        e = mid;
8,457✔
1001
      else if (keyList[mid] > key)
8,352✔
1002
        s = mid;
6,710✔
1003
      else
1004
        return mid;
1,642✔
1005
    }
1006
  }
1007
}
1008

1009
// handle the repeat ts cases.
1010
static int32_t findFirstPos(const int64_t* pTsList, int32_t num, int32_t startPos, bool asc) {
5,711✔
1011
  int32_t i = startPos;
5,711✔
1012
  int64_t startTs = pTsList[startPos];
5,711✔
1013
  if (asc) {
5,711✔
1014
    while (i < num && (pTsList[i] == startTs)) {
8,066!
1015
      i++;
4,033✔
1016
    }
1017
    return i - 1;
4,033✔
1018
  } else {
1019
    while (i >= 0 && (pTsList[i] == startTs)) {
3,356!
1020
      i--;
1,678✔
1021
    }
1022
    return i + 1;
1,678✔
1023
  }
1024
}
1025

1026
static int32_t getEndPosInDataBlock(STsdbReader* pReader, SBlockData* pBlockData, SBrinRecord* pRecord, int32_t pos) {
594,754✔
1027
  // NOTE: reverse the order to find the end position in data block
1028
  int32_t endPos = -1;
594,754✔
1029
  bool    asc = ASCENDING_TRAVERSE(pReader->info.order);
594,754✔
1030

1031
  if (asc && pReader->info.window.ekey >= pRecord->lastKey.key.ts) {
594,754✔
1032
    endPos = pRecord->numRow - 1;
590,442✔
1033
  } else if (!asc && pReader->info.window.skey <= pRecord->firstKey.key.ts) {
4,312✔
1034
    endPos = 0;
1,759✔
1035
  } else {
1036
    int64_t key = asc ? pReader->info.window.ekey : pReader->info.window.skey;
2,553!
1037
    endPos = doBinarySearchKey(pBlockData->aTSKEY, pRecord->numRow, pos, key, pReader->info.order);
2,553✔
1038
    if (endPos == -1) {
2,857!
1039
      return endPos;
×
1040
    }
1041

1042
    endPos = findFirstPos(pBlockData->aTSKEY, pRecord->numRow, endPos, asc);
2,857✔
1043
  }
1044

1045
  if ((pReader->info.verRange.maxVer >= pRecord->minVer && pReader->info.verRange.maxVer < pRecord->maxVer) ||
594,987!
1046
      (pReader->info.verRange.minVer <= pRecord->maxVer && pReader->info.verRange.minVer > pRecord->minVer)) {
595,014!
1047
    int32_t i = endPos;
×
1048

1049
    if (asc) {
×
1050
      for (; i >= 0; --i) {
×
1051
        if (pBlockData->aVersion[i] <= pReader->info.verRange.maxVer) {
×
1052
          break;
×
1053
        }
1054
      }
1055
    } else {
1056
      for (; i < pRecord->numRow; ++i) {
×
1057
        if (pBlockData->aVersion[i] >= pReader->info.verRange.minVer) {
×
1058
          break;
×
1059
        }
1060
      }
1061
    }
1062

1063
    endPos = i;
×
1064
  }
1065

1066
  return endPos;
594,987✔
1067
}
1068

1069
static void copyPrimaryTsCol(const SBlockData* pBlockData, SFileBlockDumpInfo* pDumpInfo, SColumnInfoData* pColData,
594,907✔
1070
                             int32_t dumpedRows, bool asc) {
1071
  if (asc) {
594,907✔
1072
    (void)memcpy(pColData->pData, &pBlockData->aTSKEY[pDumpInfo->rowIndex], dumpedRows * sizeof(int64_t));
593,172✔
1073
  } else {
1074
    int32_t startIndex = pDumpInfo->rowIndex - dumpedRows + 1;
1,735✔
1075
    (void)memcpy(pColData->pData, &pBlockData->aTSKEY[startIndex], dumpedRows * sizeof(int64_t));
1,735✔
1076

1077
    // todo: opt perf by extract the loop
1078
    // reverse the array list
1079
    int32_t  mid = dumpedRows >> 1u;
1,735✔
1080
    int64_t* pts = (int64_t*)pColData->pData;
1,735✔
1081
    for (int32_t j = 0; j < mid; ++j) {
198,013✔
1082
      int64_t t = pts[j];
196,278✔
1083
      pts[j] = pts[dumpedRows - j - 1];
196,278✔
1084
      pts[dumpedRows - j - 1] = t;
196,278✔
1085
    }
1086
  }
1087
}
594,907✔
1088

1089
// a faster version of copy procedure.
1090
static void copyNumericCols(const SColData* pData, SFileBlockDumpInfo* pDumpInfo, SColumnInfoData* pColData,
1,097,792✔
1091
                            int32_t dumpedRows, bool asc) {
1092
  uint8_t* p = NULL;
1,097,792✔
1093
  if (asc) {
1,097,792✔
1094
    p = pData->pData + tDataTypes[pData->type].bytes * pDumpInfo->rowIndex;
1,097,782✔
1095
  } else {
1096
    int32_t startIndex = pDumpInfo->rowIndex - dumpedRows + 1;
10✔
1097
    p = pData->pData + tDataTypes[pData->type].bytes * startIndex;
10✔
1098
  }
1099

1100
  int32_t step = asc ? 1 : -1;
1,097,792!
1101

1102
  // make sure it is aligned to 8bit, the allocated memory address is aligned to 256bit
1103

1104
  // 1. copy data in a batch model
1105
  (void)memcpy(pColData->pData, p, dumpedRows * tDataTypes[pData->type].bytes);
1,097,792✔
1106

1107
  // 2. reverse the array list in case of descending order scan data block
1108
  if (!asc) {
1,097,792✔
1109
    switch (pColData->info.type) {
55!
1110
      case TSDB_DATA_TYPE_TIMESTAMP:
15✔
1111
      case TSDB_DATA_TYPE_DOUBLE:
1112
      case TSDB_DATA_TYPE_BIGINT:
1113
      case TSDB_DATA_TYPE_UBIGINT: {
1114
        int32_t  mid = dumpedRows >> 1u;
15✔
1115
        int64_t* pts = (int64_t*)pColData->pData;
15✔
1116
        for (int32_t j = 0; j < mid; ++j) {
26,664✔
1117
          int64_t t = pts[j];
26,649✔
1118
          pts[j] = pts[dumpedRows - j - 1];
26,649✔
1119
          pts[dumpedRows - j - 1] = t;
26,649✔
1120
        }
1121
        break;
15✔
1122
      }
1123

1124
      case TSDB_DATA_TYPE_BOOL:
15✔
1125
      case TSDB_DATA_TYPE_TINYINT:
1126
      case TSDB_DATA_TYPE_UTINYINT: {
1127
        int32_t mid = dumpedRows >> 1u;
15✔
1128
        int8_t* pts = (int8_t*)pColData->pData;
15✔
1129
        for (int32_t j = 0; j < mid; ++j) {
26,664✔
1130
          int8_t t = pts[j];
26,649✔
1131
          pts[j] = pts[dumpedRows - j - 1];
26,649✔
1132
          pts[dumpedRows - j - 1] = t;
26,649✔
1133
        }
1134
        break;
15✔
1135
      }
1136

1137
      case TSDB_DATA_TYPE_SMALLINT:
10✔
1138
      case TSDB_DATA_TYPE_USMALLINT: {
1139
        int32_t  mid = dumpedRows >> 1u;
10✔
1140
        int16_t* pts = (int16_t*)pColData->pData;
10✔
1141
        for (int32_t j = 0; j < mid; ++j) {
17,776✔
1142
          int64_t t = pts[j];
17,766✔
1143
          pts[j] = pts[dumpedRows - j - 1];
17,766✔
1144
          pts[dumpedRows - j - 1] = t;
17,766✔
1145
        }
1146
        break;
10✔
1147
      }
1148

1149
      case TSDB_DATA_TYPE_FLOAT:
15✔
1150
      case TSDB_DATA_TYPE_INT:
1151
      case TSDB_DATA_TYPE_UINT: {
1152
        int32_t  mid = dumpedRows >> 1u;
15✔
1153
        int32_t* pts = (int32_t*)pColData->pData;
15✔
1154
        for (int32_t j = 0; j < mid; ++j) {
26,664✔
1155
          int32_t t = pts[j];
26,649✔
1156
          pts[j] = pts[dumpedRows - j - 1];
26,649✔
1157
          pts[dumpedRows - j - 1] = t;
26,649✔
1158
        }
1159
        break;
15✔
1160
      }
1161
    }
1162
  }
1163

1164
  // 3. if the  null value exists, check items one-by-one
1165
  if (pData->flag != HAS_VALUE) {
1,097,792✔
1166
    int32_t rowIndex = 0;
30,883✔
1167

1168
    for (int32_t j = pDumpInfo->rowIndex; rowIndex < dumpedRows; j += step, rowIndex++) {
123,789,594✔
1169
      uint8_t v = tColDataGetBitValue(pData, j);
123,744,624✔
1170
      if (v == 0 || v == 1) {
123,758,711!
1171
        colDataSetNull_f(pColData->nullbitmap, rowIndex);
12,439,719✔
1172
        pColData->hasNull = true;
12,439,719✔
1173
      }
1174
    }
1175
  }
1176
}
1,111,879✔
1177

1178
static void blockInfoToRecord(SBrinRecord* record, SFileDataBlockInfo* pBlockInfo, SBlockLoadSuppInfo* pSupp) {
2,611,054✔
1179
  record->uid = pBlockInfo->uid;
2,611,054✔
1180
  record->firstKey = (STsdbRowKey){.key = {.ts = pBlockInfo->firstKey, .numOfPKs = pSupp->numOfPks}};
2,611,054✔
1181
  record->lastKey = (STsdbRowKey){.key = {.ts = pBlockInfo->lastKey, .numOfPKs = pSupp->numOfPks}};
2,611,054✔
1182

1183
  if (pSupp->numOfPks > 0) {
2,611,054✔
1184
    SValue* pFirst = &record->firstKey.key.pks[0];
1,275,449✔
1185
    SValue* pLast = &record->lastKey.key.pks[0];
1,275,449✔
1186

1187
    pFirst->type = pSupp->pk.type;
1,275,449✔
1188
    pLast->type = pSupp->pk.type;
1,275,449✔
1189

1190
    if (IS_VAR_DATA_TYPE(pFirst->type)) {
1,275,449!
1191
      pFirst->pData = (uint8_t*)varDataVal(pBlockInfo->firstPk.pData);
×
1192
      pFirst->nData = varDataLen(pBlockInfo->firstPk.pData);
×
1193

1194
      pLast->pData = (uint8_t*)varDataVal(pBlockInfo->lastPk.pData);
×
1195
      pLast->nData = varDataLen(pBlockInfo->lastPk.pData);
×
1196
    } else {
1197
      pFirst->val = pBlockInfo->firstPk.val;
1,275,468✔
1198
      pLast->val = pBlockInfo->lastPk.val;
1,275,468✔
1199
    }
1200
  }
1201

1202
  record->minVer = pBlockInfo->minVer;
2,611,054✔
1203
  record->maxVer = pBlockInfo->maxVer;
2,611,054✔
1204
  record->blockOffset = pBlockInfo->blockOffset;
2,611,054✔
1205
  record->smaOffset = pBlockInfo->smaOffset;
2,611,054✔
1206
  record->blockSize = pBlockInfo->blockSize;
2,611,054✔
1207
  record->blockKeySize = pBlockInfo->blockKeySize;
2,611,054✔
1208
  record->smaSize = pBlockInfo->smaSize;
2,611,054✔
1209
  record->numRow = pBlockInfo->numRow;
2,611,054✔
1210
  record->count = pBlockInfo->count;
2,611,054✔
1211
}
2,611,054✔
1212

1213
static int32_t copyBlockDataToSDataBlock(STsdbReader* pReader, SRowKey* pLastProcKey) {
594,756✔
1214
  SReaderStatus*      pStatus = &pReader->status;
594,756✔
1215
  SDataBlockIter*     pBlockIter = &pStatus->blockIter;
594,756✔
1216
  SBlockLoadSuppInfo* pSupInfo = &pReader->suppInfo;
594,756✔
1217
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;
594,756✔
1218

1219
  SBlockData*         pBlockData = &pStatus->fileBlockData;
594,756✔
1220
  SFileDataBlockInfo* pBlockInfo = NULL;
594,756✔
1221
  SSDataBlock*        pResBlock = pReader->resBlockInfo.pResBlock;
594,756✔
1222
  int32_t             numOfOutputCols = pSupInfo->numOfCols;
594,756✔
1223
  int32_t             code = TSDB_CODE_SUCCESS;
594,756✔
1224
  int64_t             st = taosGetTimestampUs();
595,028✔
1225
  bool                asc = ASCENDING_TRAVERSE(pReader->info.order);
595,028✔
1226
  int32_t             step = asc ? 1 : -1;
595,028✔
1227

1228
  code = getCurrentBlockInfo(pBlockIter, &pBlockInfo, pReader->idStr);
595,028✔
1229
  if (code != TSDB_CODE_SUCCESS) {
594,857!
1230
    return code;
×
1231
  }
1232

1233
  SColVal     cv = {0};
594,857✔
1234
  SBrinRecord tmp;
1235
  blockInfoToRecord(&tmp, pBlockInfo, pSupInfo);
594,857✔
1236
  SBrinRecord* pRecord = &tmp;
594,675✔
1237

1238
  // no data exists, return directly.
1239
  if (pBlockData->nRow == 0 || pBlockData->aTSKEY == 0) {
594,675!
1240
    tsdbWarn("%p no need to copy since no data in blockData, table uid:%" PRIu64 " has been dropped, %s", pReader,
×
1241
             pBlockInfo->uid, pReader->idStr);
1242
    pResBlock->info.rows = 0;
×
1243
    return 0;
×
1244
  }
1245

1246
  // row index of dump info remain the initial position, let's find the appropriate start position.
1247
  if (((pDumpInfo->rowIndex == 0) && asc) || ((pDumpInfo->rowIndex == (pRecord->numRow - 1)) && (!asc))) {
594,924!
1248
    if (asc && pReader->info.window.skey <= pRecord->firstKey.key.ts &&
594,243✔
1249
        pReader->info.verRange.minVer <= pRecord->minVer) {
590,749!
1250
      // pDumpInfo->rowIndex = 0;
1251
    } else if (!asc && pReader->info.window.ekey >= pRecord->lastKey.key.ts &&
3,445✔
1252
               pReader->info.verRange.maxVer >= pRecord->maxVer) {
583!
1253
      // pDumpInfo->rowIndex = pRecord->numRow - 1;
1254
    } else {  // find the appropriate the start position in current block, and set it to be the current rowIndex
1255
      int32_t pos = asc ? pRecord->numRow - 1 : 0;
2,862✔
1256
      int32_t order = asc ? TSDB_ORDER_DESC : TSDB_ORDER_ASC;
2,862✔
1257
      int64_t key = asc ? pReader->info.window.skey : pReader->info.window.ekey;
2,862✔
1258
      pDumpInfo->rowIndex = doBinarySearchKey(pBlockData->aTSKEY, pRecord->numRow, pos, key, order);
2,862✔
1259

1260
      if (pDumpInfo->rowIndex < 0) {
2,862✔
1261
        tsdbError(
8!
1262
            "%p failed to locate the start position in current block, global index:%d, table index:%d, brange:%" PRId64
1263
            "-%" PRId64 ", minVer:%" PRId64 ", maxVer:%" PRId64 " %s",
1264
            pReader, pBlockIter->index, pBlockInfo->tbBlockIdx, pRecord->firstKey.key.ts, pRecord->lastKey.key.ts,
1265
            pRecord->minVer, pRecord->maxVer, pReader->idStr);
1266
        return TSDB_CODE_INVALID_PARA;
8✔
1267
      }
1268

1269
      pDumpInfo->rowIndex = findFirstPos(pBlockData->aTSKEY, pRecord->numRow, pDumpInfo->rowIndex, (!asc));
2,854✔
1270
      if (!(pReader->info.verRange.minVer <= pRecord->maxVer && pReader->info.verRange.maxVer >= pRecord->minVer)) {
2,854!
1271
        tsdbError("tsdb failed at: %s:%d", __func__, __LINE__);
×
1272
        return TSDB_CODE_INVALID_PARA;
×
1273
      }
1274

1275
      // find the appropriate start position that satisfies the version requirement.
1276
      if ((pReader->info.verRange.maxVer >= pRecord->minVer && pReader->info.verRange.maxVer < pRecord->maxVer) ||
2,854!
1277
          (pReader->info.verRange.minVer <= pRecord->maxVer && pReader->info.verRange.minVer > pRecord->minVer)) {
2,854!
1278
        int32_t i = pDumpInfo->rowIndex;
×
1279
        if (asc) {
×
1280
          for (; i < pRecord->numRow; ++i) {
×
1281
            if (pBlockData->aVersion[i] >= pReader->info.verRange.minVer) {
×
1282
              break;
×
1283
            }
1284
          }
1285
        } else {
1286
          for (; i >= 0; --i) {
×
1287
            if (pBlockData->aVersion[i] <= pReader->info.verRange.maxVer) {
×
1288
              break;
×
1289
            }
1290
          }
1291
        }
1292

1293
        pDumpInfo->rowIndex = i;
×
1294
      }
1295
    }
1296
  }
1297

1298
  // time window check
1299
  int32_t endIndex = getEndPosInDataBlock(pReader, pBlockData, pRecord, pDumpInfo->rowIndex);
594,916✔
1300
  if (endIndex == -1) {
594,896!
1301
    setBlockAllDumped(pDumpInfo, pReader->info.window.ekey, pReader->info.order);
×
1302
    return TSDB_CODE_SUCCESS;
×
1303
  }
1304

1305
  endIndex += step;
595,011✔
1306
  int32_t dumpedRows = asc ? (endIndex - pDumpInfo->rowIndex) : (pDumpInfo->rowIndex - endIndex);
595,011✔
1307
  if (dumpedRows > pReader->resBlockInfo.capacity) {  // output buffer check
595,011!
1308
    dumpedRows = pReader->resBlockInfo.capacity;
×
1309
  } else if (dumpedRows <= 0) {  // no qualified rows in current data block, quit directly.
595,011!
1310
    setBlockAllDumped(pDumpInfo, pReader->info.window.ekey, pReader->info.order);
×
1311
    return TSDB_CODE_SUCCESS;
×
1312
  }
1313

1314
  int32_t i = 0;
595,011✔
1315
  int32_t rowIndex = 0;
595,011✔
1316

1317
  SColumnInfoData* pColData = taosArrayGet(pResBlock->pDataBlock, pSupInfo->slotId[i]);
595,011✔
1318
  if (pColData == NULL) {
595,003!
1319
    return TSDB_CODE_INVALID_PARA;
×
1320
  }
1321

1322
  if (pSupInfo->colId[i] == PRIMARYKEY_TIMESTAMP_COL_ID) {
595,003!
1323
    copyPrimaryTsCol(pBlockData, pDumpInfo, pColData, dumpedRows, asc);
595,036✔
1324
    i += 1;
594,732✔
1325
  }
1326

1327
  int32_t colIndex = 0;
594,699✔
1328
  int32_t num = pBlockData->nColData;
594,699✔
1329
  while (i < numOfOutputCols && colIndex < num) {
1,982,935!
1330
    rowIndex = 0;
1,388,072✔
1331

1332
    SColData* pData = tBlockDataGetColDataByIdx(pBlockData, colIndex);
1,388,072✔
1333
    if (pData->cid < pSupInfo->colId[i]) {
1,388,072!
1334
      colIndex += 1;
×
1335
    } else if (pData->cid == pSupInfo->colId[i]) {
1,388,072!
1336
      pColData = taosArrayGet(pResBlock->pDataBlock, pSupInfo->slotId[i]);
1,388,136✔
1337
      if (pColData == NULL) {
1,388,066!
1338
        return TSDB_CODE_INVALID_PARA;
×
1339
      }
1340

1341
      if (pData->flag == HAS_NONE || pData->flag == HAS_NULL || pData->flag == (HAS_NULL | HAS_NONE)) {
1,388,066!
1342
        colDataSetNNULL(pColData, 0, dumpedRows);
85,057!
1343
      } else {
1344
        if (IS_MATHABLE_TYPE(pColData->info.type)) {
1,303,009!
1345
          copyNumericCols(pData, pDumpInfo, pColData, dumpedRows, asc);
1,097,682✔
1346
        } else {  // varchar/nchar type
1347
          for (int32_t j = pDumpInfo->rowIndex; rowIndex < dumpedRows; j += step) {
50,680,699✔
1348
            tColDataGetValue(pData, j, &cv);
50,488,545✔
1349
            code = doCopyColVal(pColData, rowIndex++, i, &cv, pSupInfo);
51,185,626✔
1350
            if (code) {
50,475,372!
1351
              return code;
×
1352
            }
1353
          }
1354
        }
1355
      }
1356

1357
      colIndex += 1;
1,388,236✔
1358
      i += 1;
1,388,236✔
1359
    } else {  // the specified column does not exist in file block, fill with null data
1360
      pColData = taosArrayGet(pResBlock->pDataBlock, pSupInfo->slotId[i]);
×
1361
      if (pColData == NULL) {
×
1362
        return TSDB_CODE_INVALID_PARA;
×
1363
      }
1364

1365
      colDataSetNNULL(pColData, 0, dumpedRows);
×
1366
      i += 1;
×
1367
    }
1368
  }
1369

1370
  // fill the mis-matched columns with null value
1371
  while (i < numOfOutputCols) {
594,863!
1372
    pColData = taosArrayGet(pResBlock->pDataBlock, pSupInfo->slotId[i]);
×
1373
    if (pColData == NULL) {
×
1374
      return TSDB_CODE_INVALID_PARA;
×
1375
    }
1376

1377
    colDataSetNNULL(pColData, 0, dumpedRows);
×
1378
    i += 1;
×
1379
  }
1380

1381
  pResBlock->info.dataLoad = 1;
594,863✔
1382
  pResBlock->info.rows = dumpedRows;
594,863✔
1383
  pDumpInfo->rowIndex += step * dumpedRows;
594,863✔
1384

1385
  tColRowGetKeyDeepCopy(pBlockData, pDumpInfo->rowIndex - step, pSupInfo->pkSrcSlot, pLastProcKey);
594,863✔
1386

1387
  // check if current block are all handled
1388
  if (pDumpInfo->rowIndex >= 0 && pDumpInfo->rowIndex < pRecord->numRow) {
597,701✔
1389
    int64_t ts = pBlockData->aTSKEY[pDumpInfo->rowIndex];
2,856✔
1390

1391
    // the remain data has out of query time window, ignore current block
1392
    if (outOfTimeWindow(ts, &pReader->info.window)) {
2,856!
1393
      setBlockAllDumped(pDumpInfo, ts, pReader->info.order);
2,856✔
1394
    }
1395
  } else {
1396
    int64_t ts = asc ? pRecord->lastKey.key.ts : pRecord->firstKey.key.ts;
591,989✔
1397
    setBlockAllDumped(pDumpInfo, ts, pReader->info.order);
591,989✔
1398
  }
1399

1400
  double elapsedTime = (taosGetTimestampUs() - st) / 1000.0;
594,855✔
1401
  pReader->cost.blockLoadTime += elapsedTime;
594,855✔
1402

1403
  int32_t unDumpedRows = asc ? pRecord->numRow - pDumpInfo->rowIndex : pDumpInfo->rowIndex + 1;
594,855✔
1404
  tsdbDebug("%p copy file block to sdatablock, global index:%d, table index:%d, brange:%" PRId64 "-%" PRId64
594,855✔
1405
            ", rows:%d, remain:%d, minVer:%" PRId64 ", maxVer:%" PRId64 ", uid:%" PRIu64 " elapsed time:%.2f ms, %s",
1406
            pReader, pBlockIter->index, pBlockInfo->tbBlockIdx, pRecord->firstKey.key.ts, pRecord->lastKey.key.ts,
1407
            dumpedRows, unDumpedRows, pRecord->minVer, pRecord->maxVer, pBlockInfo->uid, elapsedTime, pReader->idStr);
1408

1409
  return TSDB_CODE_SUCCESS;
594,954✔
1410
}
1411

1412
static FORCE_INLINE STSchema* getTableSchemaImpl(STsdbReader* pReader, uint64_t uid) {
1413
  if (pReader->info.pSchema != NULL) {
×
1414
    terrno = TSDB_CODE_INVALID_PARA;
×
1415
    tsdbError("tsdb invalid input param at: %s:%d", __func__, __LINE__);
×
1416
    return NULL;
×
1417
  }
1418

1419
  int32_t code = metaGetTbTSchemaEx(pReader->pTsdb->pVnode->pMeta, pReader->info.suid, uid, -1, &pReader->info.pSchema);
×
1420
  if (code != TSDB_CODE_SUCCESS || pReader->info.pSchema == NULL) {
×
1421
    terrno = code;
×
1422
    tsdbError("failed to get table schema, uid:%" PRIu64 ", it may have been dropped, ver:-1, %s", uid, pReader->idStr);
×
1423
    return NULL;
×
1424
  }
1425

1426
  code = tsdbRowMergerInit(&pReader->status.merger, pReader->info.pSchema);
×
1427
  if (code != TSDB_CODE_SUCCESS) {
×
1428
    terrno = code;
×
1429
    tsdbError("failed to init merger, code:%s, %s", tstrerror(code), pReader->idStr);
×
1430
    return NULL;
×
1431
  }
1432

1433
  return pReader->info.pSchema;
×
1434
}
1435

1436
static int32_t doLoadFileBlockData(STsdbReader* pReader, SDataBlockIter* pBlockIter, SBlockData* pBlockData,
620,187✔
1437
                                   uint64_t uid) {
1438
  int32_t             code = 0;
620,187✔
1439
  STSchema*           pSchema = pReader->info.pSchema;
620,187✔
1440
  int64_t             st = taosGetTimestampUs();
620,319✔
1441
  SFileDataBlockInfo* pBlockInfo = NULL;
620,319✔
1442
  SBlockLoadSuppInfo* pSup = &pReader->suppInfo;
620,319✔
1443

1444
  tBlockDataReset(pBlockData);
620,319✔
1445

1446
  if (pReader->info.pSchema == NULL) {
620,388!
1447
    pSchema = getTableSchemaImpl(pReader, uid);
×
1448
    if (pSchema == NULL) {
×
1449
      code = terrno;
×
1450
      tsdbError("%p table uid:%" PRIu64 " failed to get tableschema, code:%s, %s", pReader, uid, tstrerror(code),
×
1451
                pReader->idStr);
1452
      return code;
×
1453
    }
1454
  }
1455

1456
  code = getCurrentBlockInfo(pBlockIter, &pBlockInfo, pReader->idStr);
620,388✔
1457
  if (code != TSDB_CODE_SUCCESS) {
620,422!
1458
    return code;
×
1459
  }
1460

1461
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;
620,422✔
1462

1463
  SBrinRecord tmp;
1464
  blockInfoToRecord(&tmp, pBlockInfo, pSup);
620,422✔
1465
  SBrinRecord* pRecord = &tmp;
620,658✔
1466
  code = tsdbDataFileReadBlockDataByColumn(pReader->pFileReader, pRecord, pBlockData, pSchema, &pSup->colId[1],
620,658✔
1467
                                           pSup->numOfCols - 1);
620,658✔
1468
  if (code != TSDB_CODE_SUCCESS) {
620,674!
1469
    tsdbError("%p error occurs in loading file block, global index:%d, table index:%d, brange:%" PRId64 "-%" PRId64
×
1470
              ", rows:%d, code:%s %s",
1471
              pReader, pBlockIter->index, pBlockInfo->tbBlockIdx, pBlockInfo->firstKey, pBlockInfo->lastKey,
1472
              pBlockInfo->numRow, tstrerror(code), pReader->idStr);
1473
    return code;
×
1474
  }
1475

1476
  double elapsedTime = (taosGetTimestampUs() - st) / 1000.0;
620,571✔
1477

1478
  tsdbDebug("%p load file block into buffer, global index:%d, index in table block list:%d, brange:%" PRId64 "-%" PRId64
620,571✔
1479
            ", rows:%d, minVer:%" PRId64 ", maxVer:%" PRId64 ", elapsed time:%.2f ms, %s",
1480
            pReader, pBlockIter->index, pBlockInfo->tbBlockIdx, pRecord->firstKey.key.ts, pRecord->lastKey.key.ts,
1481
            pRecord->numRow, pRecord->minVer, pRecord->maxVer, elapsedTime, pReader->idStr);
1482

1483
  pReader->cost.blockLoadTime += elapsedTime;
620,715✔
1484
  pDumpInfo->allDumped = false;
620,715✔
1485

1486
  return code;
620,715✔
1487
}
1488

1489
/**
1490
 * This is an two rectangles overlap cases.
1491
 */
1492
static int32_t dataBlockPartiallyRequired(STimeWindow* pWindow, SVersionRange* pVerRange, SFileDataBlockInfo* pBlock) {
788,602✔
1493
  return (pWindow->ekey < pBlock->lastKey && pWindow->ekey >= pBlock->firstKey) ||
10,913✔
1494
         (pWindow->skey > pBlock->firstKey && pWindow->skey <= pBlock->lastKey) ||
777,697!
1495
         (pVerRange->minVer > pBlock->minVer && pVerRange->minVer <= pBlock->maxVer) ||
2,354,705!
1496
         (pVerRange->maxVer < pBlock->maxVer && pVerRange->maxVer >= pBlock->minVer);
777,501!
1497
}
1498

1499
static bool getNeighborBlockOfTable(SDataBlockIter* pBlockIter, SFileDataBlockInfo* pBlockInfo,
814,543✔
1500
                                    STableBlockScanInfo* pScanInfo, int32_t* nextIndex, int32_t order,
1501
                                    SBrinRecord* pRecord, SBlockLoadSuppInfo* pSupInfo) {
1502
  bool    asc = ASCENDING_TRAVERSE(order);
814,543✔
1503
  int32_t step = asc ? 1 : -1;
814,543✔
1504

1505
  if (asc && pBlockInfo->tbBlockIdx >= taosArrayGetSize(pScanInfo->pBlockIdxList) - 1) {
814,543✔
1506
    return false;
448,865✔
1507
  }
1508

1509
  if (!asc && pBlockInfo->tbBlockIdx == 0) {
365,648✔
1510
    return false;
16,817✔
1511
  }
1512

1513
  STableDataBlockIdx* pTableDataBlockIdx = taosArrayGet(pScanInfo->pBlockIdxList, pBlockInfo->tbBlockIdx + step);
348,831✔
1514
  if (pTableDataBlockIdx == NULL) {
349,287!
1515
    return TSDB_CODE_INVALID_PARA;
×
1516
  }
1517

1518
  SFileDataBlockInfo* p = taosArrayGet(pBlockIter->blockList, pTableDataBlockIdx->globalIndex);
349,287✔
1519
  if (p == NULL) {
349,038!
1520
    return TSDB_CODE_INVALID_PARA;
×
1521
  }
1522

1523
  blockInfoToRecord(pRecord, p, pSupInfo);
349,038✔
1524

1525
  *nextIndex = pBlockInfo->tbBlockIdx + step;
349,043✔
1526
  return true;
349,043✔
1527
}
1528

1529
static int32_t setFileBlockActiveInBlockIter(STsdbReader* pReader, SDataBlockIter* pBlockIter, int32_t index,
×
1530
                                             int32_t step) {
1531
  int32_t code = TSDB_CODE_SUCCESS;
×
1532
  if (index < 0 || index >= pBlockIter->numOfBlocks) {
×
1533
    return TSDB_CODE_FAILED;
×
1534
  }
1535

1536
  void* p = taosArrayGet(pBlockIter->blockList, index);
×
1537
  if (p == NULL) {
×
1538
    return TSDB_CODE_INVALID_PARA;
×
1539
  }
1540

1541
  SFileDataBlockInfo fblock = *(SFileDataBlockInfo*) p;
×
1542
  pBlockIter->index += step;
×
1543

1544
  if (index != pBlockIter->index) {
×
1545
    if (index > pBlockIter->index) {
×
1546
      for (int32_t i = index - 1; i >= pBlockIter->index; --i) {
×
1547
        SFileDataBlockInfo* pBlockInfo = taosArrayGet(pBlockIter->blockList, i);
×
1548
        if (pBlockInfo == NULL) {
×
1549
          return TSDB_CODE_INVALID_PARA;
×
1550
        }
1551

1552
        STableBlockScanInfo* pBlockScanInfo = NULL;
×
1553
        code = getTableBlockScanInfo(pReader->status.pTableMap, pBlockInfo->uid, &pBlockScanInfo, pReader->idStr);
×
1554
        if (code != TSDB_CODE_SUCCESS) {
×
1555
          return code;
×
1556
        }
1557

1558
        STableDataBlockIdx* pTableDataBlockIdx = taosArrayGet(pBlockScanInfo->pBlockIdxList, pBlockInfo->tbBlockIdx);
×
1559
        if (pTableDataBlockIdx == NULL) {
×
1560
          return TSDB_CODE_INVALID_PARA;
×
1561
        }
1562

1563
        pTableDataBlockIdx->globalIndex = i + 1;
×
1564

1565
        taosArraySet(pBlockIter->blockList, i + 1, pBlockInfo);
×
1566
      }
1567
    } else if (index < pBlockIter->index) {
×
1568
      for (int32_t i = index + 1; i <= pBlockIter->index; ++i) {
×
1569
        SFileDataBlockInfo* pBlockInfo = taosArrayGet(pBlockIter->blockList, i);
×
1570
        if (pBlockInfo == NULL) {
×
1571
          return TSDB_CODE_INVALID_PARA;
×
1572
        }
1573

1574
        STableBlockScanInfo* pBlockScanInfo = NULL;
×
1575
        code = getTableBlockScanInfo(pReader->status.pTableMap, pBlockInfo->uid, &pBlockScanInfo, pReader->idStr);
×
1576
        if (code != TSDB_CODE_SUCCESS) {
×
1577
          return code;
×
1578
        }
1579

1580
        STableDataBlockIdx* pTableDataBlockIdx = taosArrayGet(pBlockScanInfo->pBlockIdxList, pBlockInfo->tbBlockIdx);
×
1581
        if (pTableDataBlockIdx == NULL) {
×
1582
          return TSDB_CODE_INVALID_PARA;
×
1583
        }
1584

1585
        pTableDataBlockIdx->globalIndex = i - 1;
×
1586
        taosArraySet(pBlockIter->blockList, i - 1, pBlockInfo);
×
1587
      }
1588
    }
1589

1590
    taosArraySet(pBlockIter->blockList, pBlockIter->index, &fblock);
×
1591
    STableBlockScanInfo* pBlockScanInfo = NULL;
×
1592
    code = getTableBlockScanInfo(pReader->status.pTableMap, fblock.uid, &pBlockScanInfo, pReader->idStr);
×
1593
    if (code != TSDB_CODE_SUCCESS) {
×
1594
      return code;
×
1595
    }
1596

1597
    STableDataBlockIdx* pTableDataBlockIdx = taosArrayGet(pBlockScanInfo->pBlockIdxList, fblock.tbBlockIdx);
×
1598
    if (pTableDataBlockIdx == NULL) {
×
1599
      return TSDB_CODE_INVALID_PARA;
×
1600
    }
1601

1602
    pTableDataBlockIdx->globalIndex = pBlockIter->index;
×
1603
  }
1604

1605
  return TSDB_CODE_SUCCESS;
×
1606
}
1607

1608
// todo: this attribute could be acquired during extractin the global ordered block list.
1609
static bool overlapWithNeighborBlock2(SFileDataBlockInfo* pBlock, SBrinRecord* pRec, int32_t order, int32_t pkType,
349,023✔
1610
                                      int32_t numOfPk) {
1611
  // it is the last block in current file, no chance to overlap with neighbor blocks.
1612
  if (ASCENDING_TRAVERSE(order)) {
349,023✔
1613
    if (pBlock->lastKey == pRec->firstKey.key.ts) {
347,392!
1614
      if (numOfPk > 0) {
×
1615
        SValue v1 = {.type = pkType};
×
1616
        if (IS_VAR_DATA_TYPE(pkType)) {
×
1617
          v1.pData = (uint8_t*)varDataVal(pBlock->lastPk.pData), v1.nData = varDataLen(pBlock->lastPk.pData);
×
1618
        } else {
1619
          v1.val = pBlock->lastPk.val;
×
1620
        }
1621
        return (tValueCompare(&v1, &pRec->firstKey.key.pks[0]) == 0);
×
1622
      } else {  // no pk
1623
        return true;
×
1624
      }
1625
    } else {
1626
      return false;
347,392✔
1627
    }
1628
  } else {
1629
    if (pBlock->firstKey == pRec->lastKey.key.ts) {
1,631!
1630
      if (numOfPk > 0) {
×
1631
        SValue v1 = {.type = pkType};
×
1632
        if (IS_VAR_DATA_TYPE(pkType)) {
×
1633
          v1.pData = (uint8_t*)varDataVal(pBlock->firstPk.pData), v1.nData = varDataLen(pBlock->firstPk.pData);
×
1634
        } else {
1635
          v1.val = pBlock->firstPk.val;
×
1636
        }
1637
        return (tValueCompare(&v1, &pRec->lastKey.key.pks[0]) == 0);
×
1638
      } else {  // no pk
1639
        return true;
×
1640
      }
1641
    } else {
1642
      return false;
1,631✔
1643
    }
1644
  }
1645
}
1646

1647
static int64_t getBoarderKeyInFiles(SFileDataBlockInfo* pBlock, STableBlockScanInfo* pScanInfo, int32_t order) {
722,436✔
1648
  bool ascScan = ASCENDING_TRAVERSE(order);
722,436✔
1649

1650
  int64_t key = 0;
722,436✔
1651
  if (pScanInfo->sttKeyInfo.status == STT_FILE_HAS_DATA) {
722,436✔
1652
    int64_t keyInStt = pScanInfo->sttKeyInfo.nextProcKey.ts;
14,577✔
1653
    key = ascScan ? TMIN(pBlock->firstKey, keyInStt) : TMAX(pBlock->lastKey, keyInStt);
14,577✔
1654
  } else {
1655
    key = ascScan ? pBlock->firstKey : pBlock->lastKey;
707,859✔
1656
  }
1657

1658
  return key;
722,436✔
1659
}
1660

1661
static bool bufferDataInFileBlockGap(TSDBKEY keyInBuf, SFileDataBlockInfo* pBlock, STableBlockScanInfo* pScanInfo,
722,387✔
1662
                                     int32_t order) {
1663
  bool    ascScan = ASCENDING_TRAVERSE(order);
722,387✔
1664
  int64_t key = getBoarderKeyInFiles(pBlock, pScanInfo, order);
722,387✔
1665

1666
  return (ascScan && (keyInBuf.ts != TSKEY_INITIAL_VAL && keyInBuf.ts < key)) ||
1,445,115✔
1667
         (!ascScan && (keyInBuf.ts != TSKEY_INITIAL_VAL && keyInBuf.ts > key));
722,525!
1668
}
1669

1670
static bool keyOverlapFileBlock(TSDBKEY key, SFileDataBlockInfo* pBlock, SVersionRange* pVerRange) {
788,437✔
1671
  return (key.ts >= pBlock->firstKey && key.ts <= pBlock->lastKey) && (pBlock->maxVer >= pVerRange->minVer) &&
802,431!
1672
         (pBlock->minVer <= pVerRange->maxVer);
13,994!
1673
}
1674

1675
static void getBlockToLoadInfo(SDataBlockToLoadInfo* pInfo, SFileDataBlockInfo* pBlockInfo,
788,599✔
1676
                               STableBlockScanInfo* pScanInfo, TSDBKEY keyInBuf, STsdbReader* pReader) {
1677
  SBrinRecord         rec = {0};
788,599✔
1678
  int32_t             neighborIndex = 0;
788,599✔
1679
  int32_t             order = pReader->info.order;
788,599✔
1680
  SBlockLoadSuppInfo* pSupInfo = &pReader->suppInfo;
788,599✔
1681

1682
  bool hasNeighbor =
1683
      getNeighborBlockOfTable(&pReader->status.blockIter, pBlockInfo, pScanInfo, &neighborIndex, order, &rec, pSupInfo);
788,599✔
1684

1685
  // overlap with neighbor
1686
  if (hasNeighbor) {
789,107✔
1687
    pInfo->overlapWithNeighborBlock =
335,282✔
1688
        overlapWithNeighborBlock2(pBlockInfo, &rec, order, pSupInfo->pk.type, pSupInfo->numOfPks);
335,290✔
1689
  }
1690

1691
  SBrinRecord pRecord;
1692
  blockInfoToRecord(&pRecord, pBlockInfo, pSupInfo);
789,099✔
1693

1694
  // has duplicated ts of different version in this block
1695
  pInfo->hasDupTs = (pBlockInfo->numRow > pBlockInfo->count) || (pBlockInfo->count <= 0);
788,640!
1696
  pInfo->overlapWithDelInfo = overlapWithDelSkyline(pScanInfo, &pRecord, order);
788,640✔
1697

1698
  // todo handle the primary key overlap case
1699
  if (pScanInfo->sttKeyInfo.status == STT_FILE_HAS_DATA) {
788,645✔
1700
    int64_t nextProcKeyInStt = pScanInfo->sttKeyInfo.nextProcKey.ts;
36,817✔
1701
    pInfo->overlapWithSttBlock = !(pBlockInfo->lastKey < nextProcKeyInStt || pBlockInfo->firstKey > nextProcKeyInStt);
36,817✔
1702
  }
1703

1704
  pInfo->moreThanCapcity = pBlockInfo->numRow > pReader->resBlockInfo.capacity;
788,645✔
1705
  pInfo->partiallyRequired = dataBlockPartiallyRequired(&pReader->info.window, &pReader->info.verRange, pBlockInfo);
788,645✔
1706
  pInfo->overlapWithKeyInBuf = keyOverlapFileBlock(keyInBuf, pBlockInfo, &pReader->info.verRange);
788,475✔
1707
}
788,503✔
1708

1709
// 1. the version of all rows should be less than the endVersion
1710
// 2. current block should not overlap with next neighbor block
1711
// 3. current timestamp should not be overlap with each other
1712
// 4. output buffer should be large enough to hold all rows in current block
1713
// 5. delete info should not overlap with current block data
1714
// 6. current block should not contain the duplicated ts
1715
static bool fileBlockShouldLoad(STsdbReader* pReader, SFileDataBlockInfo* pBlockInfo, STableBlockScanInfo* pScanInfo,
753,215✔
1716
                                TSDBKEY keyInBuf) {
1717
  SDataBlockToLoadInfo info = {0};
753,215✔
1718
  getBlockToLoadInfo(&info, pBlockInfo, pScanInfo, keyInBuf, pReader);
753,215✔
1719

1720
  bool loadDataBlock =
753,143✔
1721
      (info.overlapWithNeighborBlock || info.hasDupTs || info.partiallyRequired || info.overlapWithKeyInBuf ||
753,225!
1722
       info.moreThanCapcity || info.overlapWithDelInfo || info.overlapWithSttBlock);
1,506,368!
1723

1724
  // log the reason why load the datablock for profile
1725
  if (loadDataBlock) {
753,143✔
1726
    tsdbDebug("%p uid:%" PRIu64
30,723✔
1727
              " need to load the datablock, overlapneighbor:%d, hasDup:%d, partiallyRequired:%d, "
1728
              "overlapWithKey:%d, greaterThanBuf:%d, overlapWithDel:%d, overlapWithSttBlock:%d, %s",
1729
              pReader, pBlockInfo->uid, info.overlapWithNeighborBlock, info.hasDupTs, info.partiallyRequired,
1730
              info.overlapWithKeyInBuf, info.moreThanCapcity, info.overlapWithDelInfo, info.overlapWithSttBlock,
1731
              pReader->idStr);
1732
  }
1733

1734
  return loadDataBlock;
753,295✔
1735
}
1736

1737
static bool isCleanFileDataBlock(STsdbReader* pReader, SFileDataBlockInfo* pBlockInfo, STableBlockScanInfo* pScanInfo,
35,399✔
1738
                                 TSDBKEY keyInBuf) {
1739
  SDataBlockToLoadInfo info = {0};
35,399✔
1740
  getBlockToLoadInfo(&info, pBlockInfo, pScanInfo, keyInBuf, pReader);
35,399✔
1741
  bool isCleanFileBlock = !(info.overlapWithNeighborBlock || info.hasDupTs || info.overlapWithKeyInBuf ||
62,851!
1742
                            info.overlapWithDelInfo || info.overlapWithSttBlock);
27,451✔
1743
  return isCleanFileBlock;
35,400✔
1744
}
1745

1746
static int32_t initRowMergeIfNeeded(STsdbReader* pReader, int64_t uid) {
884,462,844✔
1747
  SRowMerger* pMerger = &pReader->status.merger;
884,462,844✔
1748
  int32_t     code = 0;
884,462,844✔
1749

1750
  if (pMerger->pArray == NULL) {
884,462,844!
1751
    STSchema* ps = getTableSchemaImpl(pReader, uid);
×
1752
    if (ps == NULL) {
×
1753
      return terrno;
×
1754
    }
1755
  }
1756

1757
  return code;
884,462,844✔
1758
}
1759

1760
static int32_t buildDataBlockFromBuf(STsdbReader* pReader, STableBlockScanInfo* pBlockScanInfo, int64_t endKey) {
18,441,395✔
1761
  if (!(pBlockScanInfo->iiter.hasVal || pBlockScanInfo->iter.hasVal)) {
18,441,395✔
1762
    return TSDB_CODE_SUCCESS;
13,030,178✔
1763
  }
1764

1765
  int32_t code = initRowMergeIfNeeded(pReader, pBlockScanInfo->uid);
5,411,217✔
1766
  if (code != 0) {
5,415,090!
1767
    return code;
×
1768
  }
1769

1770
  int64_t      st = taosGetTimestampUs();
5,415,913✔
1771
  SSDataBlock* pBlock = pReader->resBlockInfo.pResBlock;
5,415,913✔
1772
  code = buildDataBlockFromBufImpl(pBlockScanInfo, endKey, pReader->resBlockInfo.capacity, pReader);
5,415,913✔
1773

1774
  double el = (taosGetTimestampUs() - st) / 1000.0;
5,415,909✔
1775
  updateComposedBlockInfo(pReader, el, pBlockScanInfo);
5,415,909✔
1776

1777
  tsdbDebug("%p build data block from cache completed, elapsed time:%.2f ms, numOfRows:%" PRId64 ", brange:%" PRId64
5,415,706✔
1778
            " - %" PRId64 ", uid:%" PRIu64 ",  %s",
1779
            pReader, el, pBlock->info.rows, pBlock->info.window.skey, pBlock->info.window.ekey, pBlockScanInfo->uid,
1780
            pReader->idStr);
1781

1782
  pReader->cost.buildmemBlock += el;
5,416,113✔
1783
  return code;
5,416,113✔
1784
}
1785

1786
static bool tryCopyDistinctRowFromFileBlock(STsdbReader* pReader, SBlockData* pBlockData, SRowKey* pKey,
41,532,622✔
1787
                                            SFileBlockDumpInfo* pDumpInfo, bool* copied) {
1788
  // opt version
1789
  // 1. it is not a border point
1790
  // 2. the direct next point is not an duplicated timestamp
1791
  int32_t code = TSDB_CODE_SUCCESS;
41,532,622✔
1792

1793
  *copied = false;
41,532,622✔
1794
  bool asc = (pReader->info.order == TSDB_ORDER_ASC);
41,532,622✔
1795
  if ((pDumpInfo->rowIndex < pDumpInfo->totalRows - 1 && asc) || (pDumpInfo->rowIndex > 0 && (!asc))) {
41,532,622!
1796
    int32_t step = ASCENDING_TRAVERSE(pReader->info.order) ? 1 : -1;
41,589,060✔
1797

1798
    SRowKey nextRowKey;
1799
    tColRowGetKey(pBlockData, pDumpInfo->rowIndex + step, &nextRowKey);
41,589,060✔
1800

1801
    if (pkCompEx(pKey, &nextRowKey) != 0) {  // merge is not needed
41,609,792!
1802
      code = doAppendRowFromFileBlock(pReader->resBlockInfo.pResBlock, pReader, pBlockData, pDumpInfo->rowIndex);
41,611,953✔
1803
      if (code) {
41,705,773!
1804
        return code;
×
1805
      }
1806
      pDumpInfo->rowIndex += step;
41,705,773✔
1807
      *copied = true;
41,705,773✔
1808
    }
1809
  }
1810

1811
  return code;
41,647,174✔
1812
}
1813

1814
static int32_t nextRowFromSttBlocks(SSttBlockReader* pSttBlockReader, STableBlockScanInfo* pScanInfo, int32_t pkSrcSlot,
545,238,357✔
1815
                                    SVersionRange* pVerRange) {
1816
  int32_t  code = 0;
545,238,357✔
1817
  int32_t  order = pSttBlockReader->order;
545,238,357✔
1818
  int32_t  step = ASCENDING_TRAVERSE(order) ? 1 : -1;
545,238,357✔
1819
  SRowKey* pNextProc = &pScanInfo->sttKeyInfo.nextProcKey;
545,238,357✔
1820

1821
  while (1) {
2,550,275✔
1822
    bool hasVal = false;
547,788,632✔
1823
    code = tMergeTreeNext(&pSttBlockReader->mergeTree, &hasVal);
547,788,632✔
1824
    if (code) {
549,296,561!
1825
      tsdbError("failed to iter the next row in stt-file merge tree, code:%s, %s", tstrerror(code),
×
1826
                pSttBlockReader->mergeTree.idStr);
1827
      return code;
545,496,608✔
1828
    }
1829

1830
    if (!hasVal) {  // the next value will be the accessed key in stt
549,515,915✔
1831
      pScanInfo->sttKeyInfo.status = STT_FILE_NO_DATA;
14,923,508✔
1832

1833
      // next file, the timestamps in the next file must be greater than those in current
1834
      pNextProc->ts += step;
14,923,508✔
1835
      if (pSttBlockReader->numOfPks > 0) {
14,923,508✔
1836
        if (IS_NUMERIC_TYPE(pNextProc->pks[0].type)) {
2,455,913!
1837
          pNextProc->pks[0].val = INT64_MIN;
1,818,336✔
1838
        } else {
1839
          memset(pNextProc->pks[0].pData, 0, pNextProc->pks[0].nData);
637,577✔
1840
        }
1841
      }
1842
      return code;
14,923,508✔
1843
    }
1844

1845
    TSDBROW* pRow = tMergeTreeGetRow(&pSttBlockReader->mergeTree);
534,592,407✔
1846
    int64_t  key = pRow->pBlockData->aTSKEY[pRow->iRow];
534,592,407✔
1847
    int64_t  ver = pRow->pBlockData->aVersion[pRow->iRow];
534,592,407✔
1848

1849
    if (pSttBlockReader->numOfPks == 0) {
534,592,407✔
1850
      pSttBlockReader->currentKey.ts = key;
509,362,739✔
1851
    } else {
1852
      tColRowGetKeyDeepCopy(pRow->pBlockData, pRow->iRow, pkSrcSlot, &pSttBlockReader->currentKey);
25,229,668✔
1853
    }
1854

1855
    tColRowGetKeyDeepCopy(pRow->pBlockData, pRow->iRow, pkSrcSlot, pNextProc);
536,973,839✔
1856

1857
    if (pScanInfo->delSkyline != NULL && TARRAY_SIZE(pScanInfo->delSkyline) > 0) {
536,999,108!
1858
      if (!hasBeenDropped(pScanInfo->delSkyline, &pScanInfo->sttBlockDelIndex, key, ver, order, pVerRange,
39,594,005✔
1859
                          pSttBlockReader->numOfPks > 0)) {
43,469,738✔
1860
        pScanInfo->sttKeyInfo.status = STT_FILE_HAS_DATA;
37,043,730✔
1861
        return code;
37,043,730✔
1862
      }
1863
    } else {
1864
      pScanInfo->sttKeyInfo.status = STT_FILE_HAS_DATA;
493,529,370✔
1865
      return code;
493,529,370✔
1866
    }
1867
  }
1868

1869
  return code;
1870
}
1871

1872
static void doPinSttBlock(SSttBlockReader* pSttBlockReader) { tMergeTreePinSttBlock(&pSttBlockReader->mergeTree); }
340,452,423✔
1873

1874
static void doUnpinSttBlock(SSttBlockReader* pSttBlockReader) { tMergeTreeUnpinSttBlock(&pSttBlockReader->mergeTree); }
335,812,109✔
1875

1876
static int32_t tryCopyDistinctRowFromSttBlock(TSDBROW* fRow, SSttBlockReader* pSttBlockReader,
341,148,607✔
1877
                                              STableBlockScanInfo* pScanInfo, SRowKey* pSttKey, STsdbReader* pReader,
1878
                                              bool* copied) {
1879
  int32_t code = TSDB_CODE_SUCCESS;
341,148,607✔
1880
  *copied = false;
341,148,607✔
1881

1882
  // avoid the fetch next row replace the referenced stt block in buffer
1883
  doPinSttBlock(pSttBlockReader);
341,148,607✔
1884
  code = nextRowFromSttBlocks(pSttBlockReader, pScanInfo, pReader->suppInfo.pkSrcSlot, &pReader->info.verRange);
336,653,094✔
1885
  doUnpinSttBlock(pSttBlockReader);
337,916,197✔
1886

1887
  if (code) {
334,669,204!
1888
    return code;
×
1889
  }
1890

1891
  if (hasDataInSttBlock(pScanInfo)) {
334,669,204✔
1892
    SRowKey* pNext = getCurrentKeyInSttBlock(pSttBlockReader);
331,717,857!
1893
    if (pkCompEx(pSttKey, pNext) != 0) {
333,036,719✔
1894
      code = doAppendRowFromFileBlock(pReader->resBlockInfo.pResBlock, pReader, fRow->pBlockData, fRow->iRow);
329,211,433✔
1895
      *copied = (code == TSDB_CODE_SUCCESS);
346,499,613✔
1896
      return code;
346,499,613✔
1897
    }
1898
  } else {
1899
    code = doAppendRowFromFileBlock(pReader->resBlockInfo.pResBlock, pReader, fRow->pBlockData, fRow->iRow);
2,638,859✔
1900
    *copied = (code == TSDB_CODE_SUCCESS);
2,777,551✔
1901
    return code;
2,777,551✔
1902
  }
1903

1904
  return code;
3,825,286✔
1905
}
1906

1907
static FORCE_INLINE STSchema* doGetSchemaForTSRow(int32_t sversion, STsdbReader* pReader, uint64_t uid) {
1908
  // always set the newest schema version in pReader->info.pSchema
1909
  if (pReader->info.pSchema == NULL) {
460,558,181!
1910
    STSchema* ps = getTableSchemaImpl(pReader, uid);
×
1911
    if (ps == NULL) {
×
1912
      return NULL;
×
1913
    }
1914
  }
1915

1916
  if (pReader->info.pSchema && sversion == pReader->info.pSchema->version) {
1,991,587,239!
1917
    return pReader->info.pSchema;
1,956,112,580✔
1918
  }
1919

1920
  void** p = tSimpleHashGet(pReader->pSchemaMap, &sversion, sizeof(sversion));
35,474,659✔
1921
  if (p != NULL) {
36,317,415!
1922
    return *(STSchema**)p;
36,193,546✔
1923
  }
1924

1925
  STSchema* ptr = NULL;
123,869✔
1926
  int32_t   code = metaGetTbTSchemaEx(pReader->pTsdb->pVnode->pMeta, pReader->info.suid, uid, sversion, &ptr);
123,869✔
1927
  if (code != TSDB_CODE_SUCCESS) {
126,360!
1928
    terrno = code;
×
1929
    return NULL;
×
1930
  } else {
1931
    code = tSimpleHashPut(pReader->pSchemaMap, &sversion, sizeof(sversion), &ptr, POINTER_BYTES);
126,360✔
1932
    if (code != TSDB_CODE_SUCCESS) {
126,354!
1933
      terrno = code;
×
1934
      return NULL;
×
1935
    }
1936
    return ptr;
126,354✔
1937
  }
1938
}
1939

1940
static int32_t doMergeBufAndFileRows(STsdbReader* pReader, STableBlockScanInfo* pBlockScanInfo, TSDBROW* pRow,
445,144,840✔
1941
                                     SIterInfo* pIter, SSttBlockReader* pSttBlockReader) {
1942
  SRowMerger*         pMerger = &pReader->status.merger;
445,144,840✔
1943
  SRow*               pTSRow = NULL;
445,144,840✔
1944
  SBlockData*         pBlockData = &pReader->status.fileBlockData;
445,144,840✔
1945
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;
445,144,840✔
1946
  int32_t             pkSrcSlot = pReader->suppInfo.pkSrcSlot;
445,144,840✔
1947

1948
  SRowKey* pSttKey = NULL;
445,144,840✔
1949
  if (hasDataInSttBlock(pBlockScanInfo) && (!pBlockScanInfo->cleanSttBlocks)) {
445,144,840!
1950
    pSttKey = getCurrentKeyInSttBlock(pSttBlockReader);
426,232,324✔
1951
  }
1952

1953
  SRowKey k = {0};
444,926,562✔
1954
  tRowGetKeyEx(pRow, &k);
444,926,562!
1955

1956
  STSchema* pSchema = NULL;
445,055,747✔
1957
  if (pRow->type == TSDBROW_ROW_FMT) {
445,055,747!
1958
    pSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(pRow), pReader, pBlockScanInfo->uid);
445,140,066!
1959
    if (pSchema == NULL) {
445,199,170!
1960
      return terrno;
×
1961
    }
1962
  }
1963

1964
  SRowKey* pfKey = &(SRowKey){0};
445,114,851✔
1965
  if (hasDataInFileBlock(pBlockData, pDumpInfo)) {
445,114,851✔
1966
    tColRowGetKey(pBlockData, pDumpInfo->rowIndex, pfKey);
25,436,132✔
1967
  } else {
1968
    pfKey = NULL;
419,801,124✔
1969
  }
1970

1971
  TSDBROW fRow = tsdbRowFromBlockData(pBlockData, pDumpInfo->rowIndex);
445,233,848✔
1972

1973
  // merge is not initialized yet, due to the fact that the pReader->info.pSchema is not initialized
1974
  int32_t code = initRowMergeIfNeeded(pReader, pBlockScanInfo->uid);
445,233,848✔
1975
  if (code != 0) {
445,196,022!
1976
    return code;
×
1977
  }
1978

1979
  SRowKey minKey = k;
445,196,022✔
1980
  if (pReader->info.order == TSDB_ORDER_ASC) {
445,196,022✔
1981
    if (pfKey != NULL && pkCompEx(pfKey, &minKey) < 0) {
419,897,092✔
1982
      minKey = *pfKey;
23,316,504✔
1983
    }
1984

1985
    if (pSttKey != NULL && pkCompEx(pSttKey, &minKey) < 0) {
772,979,691✔
1986
      minKey = *pSttKey;
159,856,346✔
1987
    }
1988
  } else {
1989
    if (pfKey != NULL && pkCompEx(pfKey, &minKey) > 0) {
51,204,514✔
1990
      minKey = *pfKey;
966,645✔
1991
    }
1992

1993
    if (pSttKey != NULL && pkCompEx(pSttKey, &minKey) > 0) {
99,003,307!
1994
      minKey = *pSttKey;
18,074,556✔
1995
    }
1996
  }
1997

1998
  // copy the last key before the time of stt reader loading the next stt block, in which the underlying data block may
1999
  // be changed, resulting in the corresponding changing of the value of sttRowKey
2000
  tRowKeyAssign(&pBlockScanInfo->lastProcKey, &minKey);
445,609,081✔
2001

2002
  // file block ---> stt block -----> mem
2003
  if (pkCompEx(&minKey, pfKey) == 0) {
445,540,940✔
2004
    code = tsdbRowMergerAdd(pMerger, &fRow, NULL);
24,470,260✔
2005
    if (code != TSDB_CODE_SUCCESS) {
24,420,716!
2006
      return code;
×
2007
    }
2008

2009
    code = doMergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pfKey, pReader);
24,420,716✔
2010
    if (code != TSDB_CODE_SUCCESS) {
24,598,738!
2011
      return code;
×
2012
    }
2013
  }
2014

2015
  if (pkCompEx(&minKey, pSttKey) == 0) {
446,083,911✔
2016
    TSDBROW* fRow1 = tMergeTreeGetRow(&pSttBlockReader->mergeTree);
183,823,824✔
2017
    code = tsdbRowMergerAdd(pMerger, fRow1, NULL);
183,823,824✔
2018
    if (code != TSDB_CODE_SUCCESS) {
183,832,435!
2019
      return code;
×
2020
    }
2021
    code = doMergeRowsInSttBlock(pSttBlockReader, pBlockScanInfo, pMerger, pkSrcSlot, &pReader->info.verRange, pReader->idStr);
183,832,435✔
2022
    if (code != TSDB_CODE_SUCCESS) {
183,299,864!
2023
      return code;
×
2024
    }
2025
  }
2026

2027
  if (pkCompEx(&minKey, &k) == 0) {
445,175,758✔
2028
    code = tsdbRowMergerAdd(pMerger, pRow, pSchema);
243,962,269✔
2029
    if (code != TSDB_CODE_SUCCESS) {
243,898,316!
2030
      return code;
×
2031
    }
2032

2033
    code = doMergeRowsInBuf(pIter, pBlockScanInfo->uid, &k, pBlockScanInfo->delSkyline, pReader);
243,898,316✔
2034
    if (code != TSDB_CODE_SUCCESS) {
243,921,903!
2035
      return code;
×
2036
    }
2037
  }
2038

2039
  code = tsdbRowMergerGetRow(pMerger, &pTSRow);
445,135,392✔
2040
  if (code != TSDB_CODE_SUCCESS) {
447,199,373!
2041
    return code;
×
2042
  }
2043

2044
  code = doAppendRowFromTSRow(pReader->resBlockInfo.pResBlock, pReader, pTSRow, pBlockScanInfo);
447,199,373✔
2045

2046
  taosMemoryFree(pTSRow);
445,790,546✔
2047
  tsdbRowMergerClear(pMerger);
447,669,484✔
2048

2049
  return code;
442,874,034✔
2050
}
2051

2052
static int32_t mergeFileBlockAndSttBlock(STsdbReader* pReader, SSttBlockReader* pSttBlockReader, SRowKey* pKey,
388,432,455✔
2053
                                         STableBlockScanInfo* pBlockScanInfo, SBlockData* pBlockData) {
2054
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;
388,432,455✔
2055
  SRowMerger*         pMerger = &pReader->status.merger;
388,432,455✔
2056
  int32_t             code = TSDB_CODE_SUCCESS;
388,432,455✔
2057
  int32_t             pkSrcSlot = pReader->suppInfo.pkSrcSlot;
388,432,455✔
2058

2059
  // merge is not initialized yet, due to the fact that the pReader->info.pSchema is not initialized
2060
  code = initRowMergeIfNeeded(pReader, pBlockScanInfo->uid);
388,432,455✔
2061
  if (code != 0) {
387,698,437!
2062
    return code;
×
2063
  }
2064

2065
  bool dataInDataFile = hasDataInFileBlock(pBlockData, pDumpInfo);
387,698,437✔
2066
  bool dataInSttFile = hasDataInSttBlock(pBlockScanInfo);
384,723,175✔
2067

2068
  if (dataInDataFile && (!dataInSttFile)) {
384,681,363✔
2069
    // no stt file block available, only data block exists
2070
    return mergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pKey, pReader);
16,696,849✔
2071
  } else if ((!dataInDataFile) && dataInSttFile) {
367,984,514!
2072
    // no data in data file exists
2073
    return mergeRowsInSttBlocks(pSttBlockReader, pBlockScanInfo, pReader);
341,847,643✔
2074
  } else if (pBlockScanInfo->cleanSttBlocks && pReader->info.execMode == READER_EXEC_ROWS) {
26,136,871!
2075
    // opt model for count data in stt file, which is not overlap with data blocks in files.
2076
    return mergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pKey, pReader);
×
2077
  } else {
2078
    // row in both stt file blocks and data file blocks
2079
    TSDBROW  fRow = tsdbRowFromBlockData(pBlockData, pDumpInfo->rowIndex);
26,136,871✔
2080
    SRowKey* pSttKey = getCurrentKeyInSttBlock(pSttBlockReader);
26,136,871!
2081

2082
    int32_t ret = pkCompEx(pKey, pSttKey);
26,216,328✔
2083

2084
    if (ASCENDING_TRAVERSE(pReader->info.order)) {
26,216,328✔
2085
      if (ret < 0) {  // asc
25,476,004✔
2086
        return mergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pKey, pReader);
24,483,204✔
2087
      } else if (ret > 0) {
992,800✔
2088
        return mergeRowsInSttBlocks(pSttBlockReader, pBlockScanInfo, pReader);
39,025✔
2089
      }
2090
    } else {  // desc
2091
      if (ret > 0) {
740,324✔
2092
        return mergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pKey, pReader);
349,904✔
2093
      } else if (ret < 0) {
390,420✔
2094
        return mergeRowsInSttBlocks(pSttBlockReader, pBlockScanInfo, pReader);
270,621✔
2095
      }
2096
    }
2097

2098
    // pKey == pSttKey
2099
    tRowKeyAssign(&pBlockScanInfo->lastProcKey, pKey);
1,073,574✔
2100

2101
    // the following for key == sttKey->key.ts
2102
    // file block ------> stt  block
2103
    SRow* pTSRow = NULL;
1,078,073✔
2104
    code = tsdbRowMergerAdd(pMerger, &fRow, NULL);
1,078,073✔
2105
    if (code != TSDB_CODE_SUCCESS) {
1,084,848!
2106
      return code;
×
2107
    }
2108

2109
    code = doMergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pKey, pReader);
1,084,848✔
2110
    if (code != TSDB_CODE_SUCCESS) {
1,084,120!
2111
      return code;
×
2112
    }
2113

2114
    TSDBROW* pRow1 = tMergeTreeGetRow(&pSttBlockReader->mergeTree);
1,084,120✔
2115
    code = tsdbRowMergerAdd(pMerger, pRow1, NULL);
1,084,120✔
2116
    if (code != TSDB_CODE_SUCCESS) {
1,076,565!
2117
      return code;
×
2118
    }
2119

2120
    // pSttKey will be changed when sttBlockReader iterates to the next row, so use pKey instead.
2121
    code = doMergeRowsInSttBlock(pSttBlockReader, pBlockScanInfo, pMerger, pkSrcSlot, &pReader->info.verRange, pReader->idStr);
1,076,565✔
2122
    if (code != TSDB_CODE_SUCCESS) {
1,079,239!
2123
      return code;
×
2124
    }
2125

2126
    code = tsdbRowMergerGetRow(pMerger, &pTSRow);
1,079,239✔
2127
    if (code != TSDB_CODE_SUCCESS) {
1,088,401!
2128
      return code;
×
2129
    }
2130

2131
    code = doAppendRowFromTSRow(pReader->resBlockInfo.pResBlock, pReader, pTSRow, pBlockScanInfo);
1,088,401✔
2132

2133
    taosMemoryFree(pTSRow);
1,087,565✔
2134
    tsdbRowMergerClear(pMerger);
1,089,436✔
2135
    return code;
1,038,951✔
2136
  }
2137
}
2138

2139
static int32_t doMergeMultiLevelRows(STsdbReader* pReader, STableBlockScanInfo* pBlockScanInfo, SBlockData* pBlockData,
6,613,657✔
2140
                                     SSttBlockReader* pSttBlockReader) {
2141
  SRowMerger*         pMerger = &pReader->status.merger;
6,613,657✔
2142
  SRow*               pTSRow = NULL;
6,613,657✔
2143
  int32_t             code = TSDB_CODE_SUCCESS;
6,613,657✔
2144
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;
6,613,657✔
2145
  SArray*             pDelList = pBlockScanInfo->delSkyline;
6,613,657✔
2146
  int32_t             pkSrcSlot = pReader->suppInfo.pkSrcSlot;
6,613,657✔
2147
  TSDBROW*            pRow = NULL;
6,613,657✔
2148
  TSDBROW*            piRow = NULL;
6,613,657✔
2149

2150
  getValidMemRow(&pBlockScanInfo->iter, pDelList, pReader, &pRow);
6,613,657✔
2151
  getValidMemRow(&pBlockScanInfo->iiter, pDelList, pReader, &piRow);
6,612,565✔
2152

2153
  SRowKey* pSttKey = NULL;
6,611,397✔
2154
  if (hasDataInSttBlock(pBlockScanInfo) && (!pBlockScanInfo->cleanSttBlocks)) {
6,611,397!
2155
    pSttKey = getCurrentKeyInSttBlock(pSttBlockReader);
6,334,321✔
2156
  }
2157

2158
  SRowKey* pfKey = &(SRowKey){0};
6,613,192✔
2159
  if (hasDataInFileBlock(pBlockData, pDumpInfo)) {
6,613,192✔
2160
    tColRowGetKey(pBlockData, pDumpInfo->rowIndex, pfKey);
279,242!
2161
  } else {
2162
    pfKey = NULL;
6,334,784✔
2163
  }
2164

2165
  SRowKey k = {0}, ik = {0};
6,621,492✔
2166
  tRowGetKeyEx(pRow, &k);
6,621,492!
2167
  tRowGetKeyEx(piRow, &ik);
6,621,836!
2168

2169
  STSchema* pSchema = NULL;
6,621,836✔
2170
  if (pRow->type == TSDBROW_ROW_FMT) {
6,621,836✔
2171
    pSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(pRow), pReader, pBlockScanInfo->uid);
6,621,704!
2172
    if (pSchema == NULL) {
6,622,720!
2173
      return terrno;
×
2174
    }
2175
  }
2176

2177
  STSchema* piSchema = NULL;
6,622,852✔
2178
  if (piRow->type == TSDBROW_ROW_FMT) {
6,622,852✔
2179
    piSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(piRow), pReader, pBlockScanInfo->uid);
6,622,335!
2180
    if (piSchema == NULL) {
6,622,172!
2181
      return terrno;
×
2182
    }
2183
  }
2184

2185
  // merge is not initialized yet, due to the fact that the pReader->info.pSchema is not initialized
2186
  code = initRowMergeIfNeeded(pReader, pBlockScanInfo->uid);
6,622,689✔
2187
  if (code != 0) {
6,620,774!
2188
    return code;
×
2189
  }
2190

2191
  SRowKey minKey = k;
6,620,774✔
2192
  if (ASCENDING_TRAVERSE(pReader->info.order)) {
6,620,774!
2193
    if (pkCompEx(&ik, &minKey) < 0) {  // minKey > ik.key.ts) {
6,621,344✔
2194
      minKey = ik;
6,471,820✔
2195
    }
2196

2197
    if ((pfKey != NULL) && (pkCompEx(pfKey, &minKey) < 0)) {
6,902,301✔
2198
      minKey = *pfKey;
264,305✔
2199
    }
2200

2201
    if ((pSttKey != NULL) && (pkCompEx(pSttKey, &minKey) < 0)) {
12,960,721✔
2202
      minKey = *pSttKey;
6,152,644✔
2203
    }
2204
  } else {
UNCOV
2205
    if (pkCompEx(&ik, &minKey) > 0) {
×
2206
      minKey = ik;
×
2207
    }
2208

UNCOV
2209
    if ((pfKey != NULL) && (pkCompEx(pfKey, &minKey) > 0)) {
×
2210
      minKey = *pfKey;
×
2211
    }
2212

UNCOV
2213
    if ((pSttKey != NULL) && (pkCompEx(pSttKey, &minKey) > 0)) {
×
2214
      minKey = *pSttKey;
×
2215
    }
2216
  }
2217

2218
  tRowKeyAssign(&pBlockScanInfo->lastProcKey, &minKey);
6,621,606✔
2219

2220
  // file block -----> stt block -----> imem -----> mem
2221
  if (pkCompEx(&minKey, pfKey) == 0) {
6,619,546✔
2222
    TSDBROW fRow = tsdbRowFromBlockData(pBlockData, pDumpInfo->rowIndex);
264,975✔
2223
    code = tsdbRowMergerAdd(pMerger, &fRow, NULL);
264,975✔
2224
    if (code != TSDB_CODE_SUCCESS) {
264,334!
2225
      return code;
×
2226
    }
2227

2228
    code = doMergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pfKey, pReader);
264,334✔
2229
    if (code != TSDB_CODE_SUCCESS) {
264,449!
2230
      return code;
×
2231
    }
2232
  }
2233

2234
  if (pkCompEx(&minKey, pSttKey) == 0) {
6,618,913✔
2235
    TSDBROW* pRow1 = tMergeTreeGetRow(&pSttBlockReader->mergeTree);
6,312,871✔
2236
    code = tsdbRowMergerAdd(pMerger, pRow1, NULL);
6,312,871✔
2237
    if (code != TSDB_CODE_SUCCESS) {
6,305,644!
2238
      return code;
×
2239
    }
2240

2241
    code = doMergeRowsInSttBlock(pSttBlockReader, pBlockScanInfo, pMerger, pkSrcSlot, &pReader->info.verRange, pReader->idStr);
6,305,644✔
2242
    if (code != TSDB_CODE_SUCCESS) {
6,298,491!
2243
      return code;
×
2244
    }
2245
  }
2246

2247
  if (pkCompEx(&minKey, &ik) == 0) {
6,605,639✔
2248
    code = tsdbRowMergerAdd(pMerger, piRow, piSchema);
197,671✔
2249
    if (code != TSDB_CODE_SUCCESS) {
197,647!
2250
      return code;
×
2251
    }
2252

2253
    code = doMergeRowsInBuf(&pBlockScanInfo->iiter, pBlockScanInfo->uid, &ik, pBlockScanInfo->delSkyline, pReader);
197,647✔
2254
    if (code != TSDB_CODE_SUCCESS) {
197,650!
2255
      return code;
×
2256
    }
2257
  }
2258

2259
  if (pkCompEx(&minKey, &k) == 0) {
6,604,153✔
2260
    code = tsdbRowMergerAdd(pMerger, pRow, pSchema);
131,582✔
2261
    if (code != TSDB_CODE_SUCCESS) {
131,591!
2262
      return code;
×
2263
    }
2264

2265
    code = doMergeRowsInBuf(&pBlockScanInfo->iter, pBlockScanInfo->uid, &k, pBlockScanInfo->delSkyline, pReader);
131,591✔
2266
    if (code != TSDB_CODE_SUCCESS) {
131,589!
2267
      return code;
×
2268
    }
2269
  }
2270

2271
  code = tsdbRowMergerGetRow(pMerger, &pTSRow);
6,604,160✔
2272
  if (code != TSDB_CODE_SUCCESS) {
6,626,587!
2273
    return code;
×
2274
  }
2275

2276
  code = doAppendRowFromTSRow(pReader->resBlockInfo.pResBlock, pReader, pTSRow, pBlockScanInfo);
6,626,587✔
2277

2278
  taosMemoryFree(pTSRow);
6,620,792✔
2279
  tsdbRowMergerClear(pMerger);
6,628,123✔
2280
  return code;
6,597,500✔
2281
}
2282

2283
int32_t doInitMemDataIter(STsdbReader* pReader, STbData** pData, STableBlockScanInfo* pBlockScanInfo, STsdbRowKey* pKey,
25,634,433✔
2284
                          SMemTable* pMem, SIterInfo* pIter, const char* type) {
2285
  int32_t code = TSDB_CODE_SUCCESS;
25,634,433✔
2286
  int32_t backward = (!ASCENDING_TRAVERSE(pReader->info.order));
25,634,433✔
2287
  pIter->hasVal = false;
25,634,433✔
2288

2289
  if (pMem != NULL) {
25,634,433✔
2290
    *pData = tsdbGetTbDataFromMemTable(pMem, pReader->info.suid, pBlockScanInfo->uid);
11,588,266✔
2291

2292
    if ((*pData) != NULL) {
11,594,780✔
2293
      code = tsdbTbDataIterCreate((*pData), pKey, backward, &pIter->iter);
4,594,314✔
2294
      if (code == TSDB_CODE_SUCCESS) {
4,591,391!
2295
        pIter->hasVal = (tsdbTbDataIterGet(pIter->iter) != NULL);
4,591,433!
2296

2297
        tsdbDebug("%p uid:%" PRIu64 ", check data in %s from skey:%" PRId64 ", order:%d, ts range in buf:%" PRId64
4,591,433✔
2298
                  "-%" PRId64 " %s",
2299
                  pReader, pBlockScanInfo->uid, type, pKey->key.ts, pReader->info.order, (*pData)->minKey,
2300
                  (*pData)->maxKey, pReader->idStr);
2301
      } else {
2302
        tsdbError("%p uid:%" PRIu64 ", failed to create iterator for %s, code:%s, %s", pReader, pBlockScanInfo->uid,
×
2303
                  type, tstrerror(code), pReader->idStr);
2304
        return code;
×
2305
      }
2306
    }
2307
  } else {
2308
    tsdbDebug("%p uid:%" PRIu64 ", no data in %s, %s", pReader, pBlockScanInfo->uid, type, pReader->idStr);
14,046,167✔
2309
  }
2310

2311
  return code;
25,638,643✔
2312
}
2313

2314
static void doForwardDataIter(SRowKey* pKey, SIterInfo* pIter, STableBlockScanInfo* pBlockScanInfo,
1,299,621✔
2315
                              STsdbReader* pReader) {
2316
  SRowKey rowKey = {0};
1,299,621✔
2317
  TSDBROW* pRow = NULL;
1,299,621✔
2318

2319
  while (1) {
481✔
2320
    getValidMemRow(pIter, pBlockScanInfo->delSkyline, pReader, &pRow);
1,300,102✔
2321
    if (!pIter->hasVal) {
1,300,123✔
2322
      break;
997,792✔
2323
    }
2324

2325
    tRowGetKeyEx(pRow, &rowKey);
302,331✔
2326
    int32_t ret = pkCompEx(pKey, &rowKey);
302,204✔
2327
    if (ret == 0) {
302,204!
2328
      pIter->hasVal = tsdbTbDataIterNext(pIter->iter);
×
2329
    } else {
2330
      break;
302,204✔
2331
    }
2332
  }
2333
}
1,299,996✔
2334

2335
// handle the open interval issue. Find the first row key that is greater than the given one.
2336
static void forwardDataIter(SRowKey* pKey, STableBlockScanInfo* pBlockScanInfo, STsdbReader* pReader) {
650,214✔
2337
  doForwardDataIter(pKey, &pBlockScanInfo->iter, pBlockScanInfo, pReader);
650,214✔
2338
  doForwardDataIter(pKey, &pBlockScanInfo->iiter, pBlockScanInfo, pReader);
650,017✔
2339
}
649,984✔
2340

2341
static int32_t initMemDataIterator(STableBlockScanInfo* pBlockScanInfo, STsdbReader* pReader) {
33,395,366✔
2342
  STbData*       d = NULL;
33,395,366✔
2343
  STbData*       di = NULL;
33,395,366✔
2344
  bool           asc = ASCENDING_TRAVERSE(pReader->info.order);
33,395,366✔
2345
  bool           forward = true;
33,395,366✔
2346
  STsdbReadSnap* pSnap = pReader->pReadSnap;
33,395,366✔
2347
  STimeWindow*   pWindow = &pReader->info.window;
33,395,366✔
2348

2349
  if (pBlockScanInfo->iterInit) {
33,395,366✔
2350
    return TSDB_CODE_SUCCESS;
20,585,823✔
2351
  }
2352

2353
  STsdbRowKey startKey;
2354
  startKey.key = pBlockScanInfo->lastProcKey;
12,809,543✔
2355
  startKey.version = asc ? pReader->info.verRange.minVer : pReader->info.verRange.maxVer;
12,809,543✔
2356
  if ((asc && (startKey.key.ts < pWindow->skey)) || ((!asc) && startKey.key.ts > pWindow->ekey)) {
12,809,543!
2357
    startKey.key.ts = asc ? pWindow->skey : pWindow->ekey;
12,170,403✔
2358
    forward = false;
12,170,403✔
2359
  }
2360

2361
  int32_t code = doInitMemDataIter(pReader, &d, pBlockScanInfo, &startKey, pSnap->pMem, &pBlockScanInfo->iter, "mem");
12,809,543✔
2362
  if (code != TSDB_CODE_SUCCESS) {
12,823,208!
2363
    return code;
×
2364
  }
2365

2366
  code = doInitMemDataIter(pReader, &di, pBlockScanInfo, &startKey, pSnap->pIMem, &pBlockScanInfo->iiter, "imem");
12,823,208✔
2367
  if (code != TSDB_CODE_SUCCESS) {
12,822,001!
2368
    return code;
×
2369
  }
2370

2371
  code = loadMemTombData(&pBlockScanInfo->pMemDelData, d, di, pReader->info.verRange.maxVer);
12,822,001✔
2372
  if (code != TSDB_CODE_SUCCESS) {
12,824,700!
2373
    return code;
×
2374
  }
2375

2376
  if (forward) {
12,824,700✔
2377
    forwardDataIter(&startKey.key, pBlockScanInfo, pReader);
650,216✔
2378
  }
2379

2380
  pBlockScanInfo->iterInit = true;
12,825,092✔
2381
  return TSDB_CODE_SUCCESS;
12,825,092✔
2382
}
2383

2384
static bool isValidFileBlockRow(SBlockData* pBlockData, int32_t rowIndex, STableBlockScanInfo* pBlockScanInfo, bool asc,
78,864,728✔
2385
                                STsdbReaderInfo* pInfo, STsdbReader* pReader) {
2386
  // it is an multi-table data block
2387
  if (pBlockData->aUid != NULL) {
78,864,728!
2388
    uint64_t uid = pBlockData->aUid[rowIndex];
×
2389
    if (uid != pBlockScanInfo->uid) {  // move to next row
×
2390
      return false;
×
2391
    }
2392
  }
2393

2394
  // check for version and time range
2395
  int64_t ver = pBlockData->aVersion[rowIndex];
78,864,728✔
2396
  if (ver > pInfo->verRange.maxVer || ver < pInfo->verRange.minVer) {
78,864,728!
2397
    return false;
×
2398
  }
2399

2400
  int64_t ts = pBlockData->aTSKEY[rowIndex];
78,894,269✔
2401
  if (ts > pInfo->window.ekey || ts < pInfo->window.skey) {
78,894,269✔
2402
    return false;
5,496,286✔
2403
  }
2404

2405
  if ((asc && (ts < pBlockScanInfo->lastProcKey.ts)) || ((!asc) && (ts > pBlockScanInfo->lastProcKey.ts))) {
73,397,983!
2406
    return false;
×
2407
  }
2408

2409
  if (ts == pBlockScanInfo->lastProcKey.ts) {  // todo opt perf
73,397,983!
2410
    SRowKey nextRowKey;                        // lazy eval
2411
    tColRowGetKey(pBlockData, rowIndex, &nextRowKey);
×
2412
    if (pkCompEx(&pBlockScanInfo->lastProcKey, &nextRowKey) == 0) {
×
2413
      return false;
×
2414
    }
2415
  }
2416

2417
  if (pBlockScanInfo->delSkyline != NULL && TARRAY_SIZE(pBlockScanInfo->delSkyline) > 0) {
73,397,983!
2418
    bool dropped = hasBeenDropped(pBlockScanInfo->delSkyline, &pBlockScanInfo->fileDelIndex, ts, ver, pInfo->order,
40,587,623✔
2419
                                  &pInfo->verRange, pReader->suppInfo.numOfPks > 0);
40,587,623✔
2420
    if (dropped) {
40,584,877✔
2421
      return false;
4,818,710✔
2422
    }
2423
  }
2424

2425
  return true;
68,576,527✔
2426
}
2427

2428
static void initSttBlockReader(SSttBlockReader* pSttBlockReader, STableBlockScanInfo* pScanInfo, STsdbReader* pReader) {
20,759,778✔
2429
  int32_t order = pReader->info.order;
20,759,778✔
2430
  bool    asc = ASCENDING_TRAVERSE(order);
20,759,778✔
2431

2432
  // the stt block reader has been initialized for this table.
2433
  if (pSttBlockReader->uid == pScanInfo->uid) {
20,759,778✔
2434
    return;
5,806,692✔
2435
  }
2436

2437
  if (pSttBlockReader->uid != 0) {
14,953,122✔
2438
    tMergeTreeClose(&pSttBlockReader->mergeTree);
7,973,088✔
2439
  }
2440

2441
  pSttBlockReader->uid = pScanInfo->uid;
14,958,090✔
2442

2443
  // second or third time init stt block reader
2444
  if (pScanInfo->cleanSttBlocks && (pReader->info.execMode == READER_EXEC_ROWS)) {
14,958,090!
2445
    // only allowed to retrieve clean stt blocks for count once
2446
    if (pScanInfo->sttBlockReturned) {
36!
2447
      pScanInfo->sttKeyInfo.status = STT_FILE_NO_DATA;
×
2448
      tsdbDebug("uid:%" PRIu64 " set no stt-file data after stt-block retrieved, %s", pScanInfo->uid, pReader->idStr);
×
2449
    }
2450
    return;
36✔
2451
  }
2452

2453
  STimeWindow w = pSttBlockReader->window;
14,958,054✔
2454
  if (asc) {
14,958,054✔
2455
    w.skey = pScanInfo->sttKeyInfo.nextProcKey.ts;
12,999,513✔
2456
  } else {
2457
    w.ekey = pScanInfo->sttKeyInfo.nextProcKey.ts;
1,958,541✔
2458
  }
2459

2460
  int64_t st = taosGetTimestampUs();
14,961,842✔
2461
  tsdbDebug("init stt block reader, window:%" PRId64 "-%" PRId64 ", uid:%" PRIu64 ", %s", w.skey, w.ekey,
14,961,842✔
2462
            pScanInfo->uid, pReader->idStr);
2463

2464
  SMergeTreeConf conf = {
14,961,842✔
2465
      .uid = pScanInfo->uid,
14,961,842✔
2466
      .suid = pReader->info.suid,
14,961,842✔
2467
      .pTsdb = pReader->pTsdb,
14,961,842✔
2468
      .timewindow = w,
2469
      .verRange = pSttBlockReader->verRange,
2470
      .strictTimeRange = false,
2471
      .pSchema = pReader->info.pSchema,
14,961,842✔
2472
      .pCurrentFileset = pReader->status.pCurrentFileset,
14,961,842✔
2473
      .backward = (pSttBlockReader->order == TSDB_ORDER_DESC),
14,961,842✔
2474
      .pSttFileBlockIterArray = pReader->status.pLDataIterArray,
14,961,842✔
2475
      .pCols = pReader->suppInfo.colId,
14,961,842✔
2476
      .numOfCols = pReader->suppInfo.numOfCols,
14,961,842✔
2477
      .loadTombFn = loadSttTombDataForAll,
2478
      .pCurRowKey = &pScanInfo->sttKeyInfo.nextProcKey,
14,961,842✔
2479
      .pReader = pReader,
2480
      .idstr = pReader->idStr,
14,961,842✔
2481
      .rspRows = (pReader->info.execMode == READER_EXEC_ROWS),
14,961,842✔
2482
  };
2483

2484
  SSttDataInfoForTable info = {.pKeyRangeList = taosArrayInit(4, sizeof(SSttKeyRange))};
14,961,842✔
2485
  if (info.pKeyRangeList == NULL) {
14,969,466!
2486
    pReader->code = terrno;
×
2487
    return;
×
2488
  }
2489

2490
  int32_t code = tMergeTreeOpen2(&pSttBlockReader->mergeTree, &conf, &info);
14,969,466✔
2491
  if (code != TSDB_CODE_SUCCESS) {
14,960,212!
2492
    taosArrayDestroy(info.pKeyRangeList);
×
2493
    pReader->code = code;
×
2494
    return;
×
2495
  }
2496

2497
  code = initMemDataIterator(pScanInfo, pReader);
14,960,212✔
2498
  if (code != TSDB_CODE_SUCCESS) {
14,963,617!
2499
    taosArrayDestroy(info.pKeyRangeList);
×
2500
    pReader->code = code;
×
2501
    return;
×
2502
  }
2503

2504
  code = initDelSkylineIterator(pScanInfo, pReader->info.order, &pReader->cost);
14,963,617✔
2505
  if (code != TSDB_CODE_SUCCESS) {
14,963,152✔
2506
    taosArrayDestroy(info.pKeyRangeList);
614✔
2507
    pReader->code = code;
×
2508
    return;
×
2509
  }
2510

2511
  if (conf.rspRows) {
14,962,538✔
2512
    pScanInfo->cleanSttBlocks = isCleanSttBlock(info.pKeyRangeList, &pReader->info.window, pScanInfo, order);
274,659✔
2513
    if (pScanInfo->cleanSttBlocks) {
274,569✔
2514
      pScanInfo->numOfRowsInStt = info.numOfRows;
32,838✔
2515

2516
      // calculate the time window for data in stt files
2517
      for (int32_t i = 0; i < taosArrayGetSize(info.pKeyRangeList); ++i) {
65,640✔
2518
        SSttKeyRange* pKeyRange = taosArrayGet(info.pKeyRangeList, i);
32,837✔
2519
        if (pKeyRange == NULL) {
32,835!
2520
          continue;
×
2521
        }
2522

2523
        if (pkCompEx(&pScanInfo->sttRange.skey, &pKeyRange->skey) > 0) {
65,681!
2524
          tRowKeyAssign(&pScanInfo->sttRange.skey, &pKeyRange->skey);
32,826✔
2525
        }
2526

2527
        if (pkCompEx(&pScanInfo->sttRange.ekey, &pKeyRange->ekey) < 0) {
65,650!
2528
          tRowKeyAssign(&pScanInfo->sttRange.ekey, &pKeyRange->ekey);
32,828✔
2529
        }
2530
      }
2531

2532
      pScanInfo->sttKeyInfo.status = taosArrayGetSize(info.pKeyRangeList) ? STT_FILE_HAS_DATA : STT_FILE_NO_DATA;
32,706!
2533

2534
      SRowKey* p = asc ? &pScanInfo->sttRange.skey : &pScanInfo->sttRange.ekey;
32,788!
2535
      tRowKeyAssign(&pScanInfo->sttKeyInfo.nextProcKey, p);
32,788✔
2536
    } else {                                // not clean stt blocks
2537
      INIT_KEYRANGE(&pScanInfo->sttRange);  // reset the time window
241,731✔
2538
      code = nextRowFromSttBlocks(pSttBlockReader, pScanInfo, pReader->suppInfo.pkSrcSlot, &pReader->info.verRange);
241,731✔
2539
    }
2540
  } else {
2541
    pScanInfo->cleanSttBlocks = false;
14,687,879✔
2542
    INIT_KEYRANGE(&pScanInfo->sttRange);  // reset the time window
14,687,879✔
2543
    code = nextRowFromSttBlocks(pSttBlockReader, pScanInfo, pReader->suppInfo.pkSrcSlot, &pReader->info.verRange);
14,687,879✔
2544
  }
2545

2546
  pScanInfo->sttBlockReturned = false;
14,960,808✔
2547
  taosArrayDestroy(info.pKeyRangeList);
14,960,808✔
2548

2549
  int64_t el = taosGetTimestampUs() - st;
14,969,273✔
2550
  pReader->cost.initSttBlockReader += (el / 1000.0);
14,969,273✔
2551

2552
  tsdbDebug("init stt block reader completed, elapsed time:%" PRId64 "us %s", el, pReader->idStr);
14,969,273✔
2553
  if (code != 0) {
14,969,835!
2554
    pReader->code = code;
×
2555
  }
2556
}
2557

2558
static bool hasDataInSttBlock(STableBlockScanInfo* pInfo) { return pInfo->sttKeyInfo.status == STT_FILE_HAS_DATA; }
2,102,708,915✔
2559

2560
bool hasDataInFileBlock(const SBlockData* pBlockData, const SFileBlockDumpInfo* pDumpInfo) {
1,631,943,017✔
2561
  if ((pBlockData->nRow > 0) && (pBlockData->nRow != pDumpInfo->totalRows)) {
1,631,943,017!
2562
    return false;  // this is an invalid result.
×
2563
  }
2564
  return pBlockData->nRow > 0 && (!pDumpInfo->allDumped);
1,631,943,017✔
2565
}
2566

2567
int32_t mergeRowsInFileBlocks(SBlockData* pBlockData, STableBlockScanInfo* pBlockScanInfo, SRowKey* pKey,
41,526,948✔
2568
                              STsdbReader* pReader) {
2569
  SRowMerger*         pMerger = &pReader->status.merger;
41,526,948✔
2570
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;
41,526,948✔
2571
  bool                copied = false;
41,526,948✔
2572

2573
  int32_t code = tryCopyDistinctRowFromFileBlock(pReader, pBlockData, pKey, pDumpInfo, &copied);
41,526,948✔
2574
  if (code != TSDB_CODE_SUCCESS) {
41,564,215!
2575
    return code;
×
2576
  }
2577

2578
  // merge is not initialized yet, due to the fact that the pReader->info.pSchema is not initialized
2579
  code = initRowMergeIfNeeded(pReader, pBlockScanInfo->uid);
41,564,215✔
2580
  if (code != 0) {
41,529,201!
2581
    return code;
×
2582
  }
2583

2584
  tRowKeyAssign(&pBlockScanInfo->lastProcKey, pKey);
41,529,201✔
2585

2586
  if (copied) {
41,516,444✔
2587
    return TSDB_CODE_SUCCESS;
41,506,559✔
2588
  } else {
2589
    TSDBROW fRow = tsdbRowFromBlockData(pBlockData, pDumpInfo->rowIndex);
9,885✔
2590

2591
    SRow* pTSRow = NULL;
9,885✔
2592
    code = tsdbRowMergerAdd(pMerger, &fRow, NULL);
9,885✔
2593
    if (code != TSDB_CODE_SUCCESS) {
12,431!
2594
      return code;
×
2595
    }
2596

2597
    code = doMergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pKey, pReader);
12,431✔
2598
    if (code != TSDB_CODE_SUCCESS) {
12,431!
2599
      return code;
×
2600
    }
2601

2602
    code = tsdbRowMergerGetRow(pMerger, &pTSRow);
12,431✔
2603
    if (code != TSDB_CODE_SUCCESS) {
12,431!
2604
      return code;
×
2605
    }
2606

2607
    code = doAppendRowFromTSRow(pReader->resBlockInfo.pResBlock, pReader, pTSRow, pBlockScanInfo);
12,431✔
2608

2609
    taosMemoryFree(pTSRow);
12,430✔
2610
    tsdbRowMergerClear(pMerger);
12,431✔
2611
    return code;
12,430✔
2612
  }
2613
}
2614

2615
int32_t mergeRowsInSttBlocks(SSttBlockReader* pSttBlockReader, STableBlockScanInfo* pScanInfo, STsdbReader* pReader) {
341,997,694✔
2616
  bool        copied = false;
341,997,694✔
2617
  SRow*       pTSRow = NULL;
341,997,694✔
2618
  int32_t     pkSrcSlot = pReader->suppInfo.pkSrcSlot;
341,997,694✔
2619
  SRowMerger* pMerger = &pReader->status.merger;
341,997,694✔
2620

2621
  // let's record the last processed key
2622
  tRowKeyAssign(&pScanInfo->lastProcKey, getCurrentKeyInSttBlock(pSttBlockReader));
341,997,694✔
2623

2624
  TSDBROW* pRow = tMergeTreeGetRow(&pSttBlockReader->mergeTree);
341,089,002✔
2625
  TSDBROW  fRow = {.iRow = pRow->iRow, .type = TSDBROW_COL_FMT, .pBlockData = pRow->pBlockData};
341,089,002✔
2626

2627
  if (IS_VAR_DATA_TYPE(pScanInfo->lastProcKey.pks[0].type)) {
341,089,002!
2628
    tsdbTrace("fRow ptr:%p, %d, uid:%" PRIu64 ", ts:%" PRId64 " pk:%s %s", pRow->pBlockData, pRow->iRow,
1,085,164!
2629
              pSttBlockReader->uid, fRow.pBlockData->aTSKEY[fRow.iRow], pScanInfo->lastProcKey.pks[0].pData,
2630
              pReader->idStr);
2631
  }
2632

2633
  int32_t code =
2634
      tryCopyDistinctRowFromSttBlock(&fRow, pSttBlockReader, pScanInfo, &pScanInfo->lastProcKey, pReader, &copied);
341,089,002✔
2635
  if (code) {
350,619,171!
2636
    return code;
×
2637
  }
2638

2639
  if (copied) {
350,619,171✔
2640
    return TSDB_CODE_SUCCESS;
349,150,009✔
2641
  } else {
2642
    code = tsdbRowMergerAdd(pMerger, &fRow, NULL);
1,469,162✔
2643
    if (code != TSDB_CODE_SUCCESS) {
1,584,211!
2644
      return code;
×
2645
    }
2646

2647
    TSDBROW* pRow1 = tMergeTreeGetRow(&pSttBlockReader->mergeTree);
1,584,211✔
2648
    code = tsdbRowMergerAdd(pMerger, pRow1, NULL);
1,584,211✔
2649
    if (code != TSDB_CODE_SUCCESS) {
1,549,502!
2650
      return code;
×
2651
    }
2652

2653
    code = doMergeRowsInSttBlock(pSttBlockReader, pScanInfo, pMerger, pkSrcSlot, &pReader->info.verRange, pReader->idStr);
1,549,502✔
2654
    if (code != TSDB_CODE_SUCCESS) {
1,558,869!
2655
      return code;
×
2656
    }
2657

2658
    code = tsdbRowMergerGetRow(pMerger, &pTSRow);
1,558,869✔
2659
    if (code != TSDB_CODE_SUCCESS) {
1,597,524!
2660
      return code;
×
2661
    }
2662

2663
    code = doAppendRowFromTSRow(pReader->resBlockInfo.pResBlock, pReader, pTSRow, pScanInfo);
1,597,524✔
2664

2665
    taosMemoryFree(pTSRow);
1,594,386✔
2666
    tsdbRowMergerClear(pMerger);
1,602,222✔
2667
    return code;
1,456,517✔
2668
  }
2669
}
2670

2671
static int32_t buildComposedDataBlockImpl(STsdbReader* pReader, STableBlockScanInfo* pBlockScanInfo,
838,333,835✔
2672
                                          SBlockData* pBlockData, SSttBlockReader* pSttBlockReader) {
2673
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;
838,333,835✔
2674

2675
  TSDBROW *pRow = NULL, *piRow = NULL;
838,333,835✔
2676

2677
  SRowKey* pKey = &(SRowKey){0};
838,333,835✔
2678
  if (hasDataInFileBlock(pBlockData, pDumpInfo)) {
838,333,835✔
2679
    tColRowGetKey(pBlockData, pDumpInfo->rowIndex, pKey);
68,024,885✔
2680
  } else {
2681
    pKey = NULL;
768,496,957✔
2682
  }
2683

2684
  if (pBlockScanInfo->iter.hasVal) {
837,974,515✔
2685
    getValidMemRow(&pBlockScanInfo->iter, pBlockScanInfo->delSkyline, pReader, &pRow);
436,303,091✔
2686
  }
2687

2688
  if (pBlockScanInfo->iiter.hasVal) {
837,577,973✔
2689
    getValidMemRow(&pBlockScanInfo->iiter, pBlockScanInfo->delSkyline, pReader, &piRow);
20,949,034✔
2690
  }
2691

2692
  // two levels of mem-table does contain the valid rows
2693
  if (pRow != NULL && piRow != NULL) {
837,583,375✔
2694
    return doMergeMultiLevelRows(pReader, pBlockScanInfo, pBlockData, pSttBlockReader);
6,612,301✔
2695
  }
2696

2697
  // imem + file + stt block
2698
  if (pBlockScanInfo->iiter.hasVal) {
830,971,074✔
2699
    return doMergeBufAndFileRows(pReader, pBlockScanInfo, piRow, &pBlockScanInfo->iiter, pSttBlockReader);
14,525,673✔
2700
  }
2701

2702
  // mem + file + stt block
2703
  if (pBlockScanInfo->iter.hasVal) {
816,445,401✔
2704
    return doMergeBufAndFileRows(pReader, pBlockScanInfo, pRow, &pBlockScanInfo->iter, pSttBlockReader);
430,774,202✔
2705
  }
2706

2707
  // files data blocks + stt block
2708
  return mergeFileBlockAndSttBlock(pReader, pSttBlockReader, pKey, pBlockScanInfo, pBlockData);
385,671,199✔
2709
}
2710

2711
static int32_t loadNeighborIfOverlap(SFileDataBlockInfo* pBlockInfo, STableBlockScanInfo* pBlockScanInfo,
25,569✔
2712
                                     STsdbReader* pReader, bool* loadNeighbor) {
2713
  int32_t             code = TSDB_CODE_SUCCESS;
25,569✔
2714
  int32_t             order = pReader->info.order;
25,569✔
2715
  SDataBlockIter*     pIter = &pReader->status.blockIter;
25,569✔
2716
  SBlockLoadSuppInfo* pSupInfo = &pReader->suppInfo;
25,569✔
2717
  int32_t             step = ASCENDING_TRAVERSE(order) ? 1 : -1;
25,569✔
2718
  int32_t             nextIndex = -1;
25,569✔
2719
  SBrinRecord         rec = {0};
25,569✔
2720

2721
  *loadNeighbor = false;
25,569✔
2722
  bool hasNeighbor = getNeighborBlockOfTable(pIter, pBlockInfo, pBlockScanInfo, &nextIndex, order, &rec, pSupInfo);
25,569✔
2723
  if (!hasNeighbor) {  // do nothing
25,569✔
2724
    return code;
11,813✔
2725
  }
2726

2727
  // load next block
2728
  if (overlapWithNeighborBlock2(pBlockInfo, &rec, order, pReader->suppInfo.pk.type, pReader->suppInfo.numOfPks)) {
13,756!
2729
    SReaderStatus*  pStatus = &pReader->status;
×
2730
    SDataBlockIter* pBlockIter = &pStatus->blockIter;
×
2731

2732
    // 1. find the next neighbor block in the scan block list
2733
    STableDataBlockIdx* tableDataBlockIdx = taosArrayGet(pBlockScanInfo->pBlockIdxList, nextIndex);
×
2734
    if (tableDataBlockIdx == NULL) {
×
2735
      return TSDB_CODE_INVALID_PARA;
×
2736
    }
2737

2738
    // 2. remove it from the scan block list
2739
    int32_t neighborIndex = tableDataBlockIdx->globalIndex;
×
2740
    code = setFileBlockActiveInBlockIter(pReader, pBlockIter, neighborIndex, step);
×
2741
    if (code != TSDB_CODE_SUCCESS) {
×
2742
      return code;
×
2743
    }
2744

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

2751
    // 4. check the data values
2752
    initBlockDumpInfo(pReader, pBlockIter);
×
2753
    *loadNeighbor = true;
×
2754
  }
2755

2756
  return code;
13,756✔
2757
}
2758

2759
void updateComposedBlockInfo(STsdbReader* pReader, double el, STableBlockScanInfo* pBlockScanInfo) {
11,245,916✔
2760
  SSDataBlock* pResBlock = pReader->resBlockInfo.pResBlock;
11,245,916✔
2761

2762
  pResBlock->info.id.uid = (pBlockScanInfo != NULL) ? pBlockScanInfo->uid : 0;
11,245,916!
2763
  pResBlock->info.dataLoad = 1;
11,245,916✔
2764
  pResBlock->info.version = pReader->info.verRange.maxVer;
11,245,916✔
2765

2766
  int32_t code = blockDataUpdateTsWindow(pResBlock, pReader->suppInfo.slotId[0]);
11,245,916✔
2767
  code = blockDataUpdatePkRange(pResBlock, pReader->suppInfo.pkDstSlot, ASCENDING_TRAVERSE(pReader->info.order));
11,247,493✔
2768
  setComposedBlockFlag(pReader, true);
11,246,622✔
2769

2770
  pReader->cost.composedBlocks += 1;
11,245,036✔
2771
  pReader->cost.buildComposedBlockTime += el;
11,245,036✔
2772
}
11,245,036✔
2773

2774
static int32_t buildComposedDataBlock(STsdbReader* pReader) {
35,400✔
2775
  int32_t             code = TSDB_CODE_SUCCESS;
35,400✔
2776
  bool                asc = ASCENDING_TRAVERSE(pReader->info.order);
35,400✔
2777
  int64_t             st = taosGetTimestampUs();
35,400✔
2778
  int32_t             step = asc ? 1 : -1;
35,400✔
2779
  double              el = 0;
35,400✔
2780
  SSDataBlock*        pResBlock = pReader->resBlockInfo.pResBlock;
35,400✔
2781
  SFileDataBlockInfo* pBlockInfo = NULL;
35,400✔
2782
  SSttBlockReader*    pSttBlockReader = pReader->status.fileIter.pSttBlockReader;
35,400✔
2783
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;
35,400✔
2784

2785
  code = getCurrentBlockInfo(&pReader->status.blockIter, &pBlockInfo, pReader->idStr);
35,400✔
2786
  if (code != TSDB_CODE_SUCCESS) {
35,401!
2787
    return 0;
×
2788
  }
2789

2790
  if (pReader->pIgnoreTables && taosHashGet(*pReader->pIgnoreTables, &pBlockInfo->uid, sizeof(pBlockInfo->uid))) {
35,401!
2791
    setBlockAllDumped(pDumpInfo, pBlockInfo->lastKey, pReader->info.order);
×
2792
    return code;
×
2793
  }
2794

2795
  STableBlockScanInfo* pBlockScanInfo = NULL;
35,401✔
2796
  code = getTableBlockScanInfo(pReader->status.pTableMap, pBlockInfo->uid, &pBlockScanInfo, pReader->idStr);
35,401✔
2797
  if (code != TSDB_CODE_SUCCESS) {
35,400!
2798
    goto _end;
×
2799
  }
2800

2801
  TSDBKEY keyInBuf = getCurrentKeyInBuf(pBlockScanInfo, pReader);
35,400✔
2802

2803
  // it is a clean block, load it directly
2804
  int64_t cap = pReader->resBlockInfo.capacity;
35,399✔
2805
  bool    directCopy = isCleanFileDataBlock(pReader, pBlockInfo, pBlockScanInfo, keyInBuf) &&
35,399✔
2806
                    (pBlockInfo->numRow <= cap) && (pBlockScanInfo->sttKeyInfo.status == STT_FILE_NO_DATA) &&
40,295!
2807
                    ((asc && ((pBlockInfo->lastKey < keyInBuf.ts) || (keyInBuf.ts == INT64_MIN))) ||
3,702!
2808
                     (!asc && (pBlockInfo->lastKey > keyInBuf.ts)));
1,194!
2809
  if (directCopy) {
35,399✔
2810
    code = copyBlockDataToSDataBlock(pReader, &pBlockScanInfo->lastProcKey);
4,896✔
2811
    goto _end;
4,895✔
2812
  }
2813

2814
  SBlockData* pBlockData = &pReader->status.fileBlockData;
30,503✔
2815
  initSttBlockReader(pSttBlockReader, pBlockScanInfo, pReader);
30,503✔
2816
  if (pReader->code != 0) {
30,503!
2817
    code = pReader->code;
×
2818
    goto _end;
×
2819
  }
2820

2821
  while (1) {
68,490,462✔
2822
    bool hasBlockData = false;
68,520,965✔
2823
    {
2824
      while (pBlockData->nRow > 0 && pBlockData->uid == pBlockScanInfo->uid) {
78,788,503!
2825
        // find the first qualified row in data block
2826
        if (isValidFileBlockRow(pBlockData, pDumpInfo->rowIndex, pBlockScanInfo, asc, &pReader->info, pReader)) {
78,851,710✔
2827
          hasBlockData = true;
68,561,949✔
2828
          break;
68,561,949✔
2829
        }
2830

2831
        pDumpInfo->rowIndex += step;
10,333,663✔
2832

2833
        if (pDumpInfo->rowIndex >= pBlockData->nRow || pDumpInfo->rowIndex < 0) {
10,333,663!
2834
          // NOTE: get the new block info
2835
          code = getCurrentBlockInfo(&pReader->status.blockIter, &pBlockInfo, pReader->idStr);
66,125✔
2836
          if (code != TSDB_CODE_SUCCESS) {
6,854!
2837
            goto _end;
×
2838
          }
2839

2840
          // continue check for the next file block if the last ts in the current block
2841
          // is overlapped with the next neighbor block
2842
          bool loadNeighbor = false;
6,854✔
2843
          code = loadNeighborIfOverlap(pBlockInfo, pBlockScanInfo, pReader, &loadNeighbor);
6,854✔
2844
          if ((!loadNeighbor) || (code != 0)) {
6,854!
2845
            setBlockAllDumped(pDumpInfo, pBlockInfo->lastKey, pReader->info.order);
6,854✔
2846
            break;
6,854✔
2847
          }
2848
        }
2849
      }
2850
    }
2851

2852
    // no data in last block and block, no need to proceed.
2853
    if (hasBlockData == false) {
68,505,596✔
2854
      break;
6,854✔
2855
    }
2856

2857
    code = buildComposedDataBlockImpl(pReader, pBlockScanInfo, pBlockData, pSttBlockReader);
68,498,742✔
2858
    if (code) {
68,518,930!
2859
      goto _end;
×
2860
    }
2861

2862
    // currently loaded file data block is consumed
2863
    if ((pBlockData->nRow > 0) && (pDumpInfo->rowIndex >= pBlockData->nRow || pDumpInfo->rowIndex < 0)) {
68,518,930!
2864
      setBlockAllDumped(pDumpInfo, pBlockInfo->lastKey, pReader->info.order);
23,533✔
2865
      break;
18,714✔
2866
    }
2867

2868
    if (pResBlock->info.rows >= pReader->resBlockInfo.capacity) {
68,495,397✔
2869
      break;
4,935✔
2870
    }
2871
  }
2872

2873
_end:
35,398✔
2874
  el = (taosGetTimestampUs() - st) / 1000.0;
35,397✔
2875
  updateComposedBlockInfo(pReader, el, pBlockScanInfo);
35,397✔
2876

2877
  if (pResBlock->info.rows > 0) {
35,400✔
2878
    tsdbDebug("%p uid:%" PRIu64 ", composed data block created, brange:%" PRIu64 "-%" PRIu64 " rows:%" PRId64
29,598✔
2879
              ", elapsed time:%.2f ms %s",
2880
              pReader, pResBlock->info.id.uid, pResBlock->info.window.skey, pResBlock->info.window.ekey,
2881
              pResBlock->info.rows, el, pReader->idStr);
2882
  }
2883

2884
  return code;
35,400✔
2885
}
2886

2887
void setComposedBlockFlag(STsdbReader* pReader, bool composed) { pReader->status.composedDataBlock = composed; }
11,999,859✔
2888

2889
int32_t getInitialDelIndex(const SArray* pDelSkyline, int32_t order) {
208,013✔
2890
  if (pDelSkyline == NULL) {
208,013!
2891
    return 0;
×
2892
  }
2893

2894
  return ASCENDING_TRAVERSE(order) ? 0 : taosArrayGetSize(pDelSkyline) - 1;
208,013✔
2895
}
2896

2897
int32_t initDelSkylineIterator(STableBlockScanInfo* pBlockScanInfo, int32_t order, SReadCostSummary* pCost) {
33,402,736✔
2898
  int32_t code = 0;
33,402,736✔
2899
  int32_t newDelDataInFile = taosArrayGetSize(pBlockScanInfo->pFileDelData);
33,402,736✔
2900
  if (newDelDataInFile == 0 &&
33,403,641✔
2901
      ((pBlockScanInfo->delSkyline != NULL) || (TARRAY_SIZE(pBlockScanInfo->pMemDelData) == 0))) {
33,345,077✔
2902
    return code;
33,197,693✔
2903
  }
2904

2905
  int64_t st = taosGetTimestampUs();
208,017✔
2906

2907
  if (pBlockScanInfo->delSkyline != NULL) {
208,017✔
2908
    taosArrayClear(pBlockScanInfo->delSkyline);
35,246✔
2909
  } else {
2910
    pBlockScanInfo->delSkyline = taosArrayInit(4, sizeof(TSDBKEY));
172,771✔
2911
    if (pBlockScanInfo->delSkyline == NULL) {
172,773!
2912
      return terrno;
×
2913
    }
2914
  }
2915

2916
  SArray* pSource = pBlockScanInfo->pFileDelData;
208,017✔
2917
  if (pSource == NULL) {
208,017✔
2918
    pSource = pBlockScanInfo->pMemDelData;
139,835✔
2919
  } else {
2920
    void* p1 = taosArrayAddAll(pSource, pBlockScanInfo->pMemDelData);
68,182✔
2921
    if (p1 == NULL) {
68,181!
2922
      return terrno;
×
2923
    }
2924
  }
2925

2926
  code = tsdbBuildDeleteSkyline(pSource, 0, taosArrayGetSize(pSource) - 1, pBlockScanInfo->delSkyline);
208,016✔
2927

2928
  taosArrayClear(pBlockScanInfo->pFileDelData);
208,017✔
2929
  int32_t index = getInitialDelIndex(pBlockScanInfo->delSkyline, order);
208,017✔
2930

2931
  pBlockScanInfo->iter.index = index;
208,015✔
2932
  pBlockScanInfo->iiter.index = index;
208,015✔
2933
  pBlockScanInfo->fileDelIndex = index;
208,015✔
2934
  pBlockScanInfo->sttBlockDelIndex = index;
208,015✔
2935

2936
  double el = taosGetTimestampUs() - st;
208,016✔
2937
  pCost->createSkylineIterTime = el / 1000.0;
208,016✔
2938

2939
  return code;
208,016✔
2940
}
2941

2942
TSDBKEY getCurrentKeyInBuf(STableBlockScanInfo* pScanInfo, STsdbReader* pReader) {
788,825✔
2943
  bool    asc = ASCENDING_TRAVERSE(pReader->info.order);
788,825✔
2944
  TSDBKEY key = {.ts = TSKEY_INITIAL_VAL}, ikey = {.ts = TSKEY_INITIAL_VAL};
788,825✔
2945

2946
  bool     hasKey = false, hasIKey = false;
788,825✔
2947
  TSDBROW* pRow = NULL;
788,825✔
2948
  TSDBROW* pIRow = NULL;
788,825✔
2949

2950
  getValidMemRow(&pScanInfo->iter, pScanInfo->delSkyline, pReader, &pRow);
788,825✔
2951
  if (pRow != NULL) {
788,825✔
2952
    hasKey = true;
20,967✔
2953
    key = TSDBROW_KEY(pRow);
20,967!
2954
  }
2955

2956
  getValidMemRow(&pScanInfo->iiter, pScanInfo->delSkyline, pReader, &pIRow);
788,825✔
2957
  if (pIRow != NULL) {
788,825✔
2958
    hasIKey = true;
5,237✔
2959
    ikey = TSDBROW_KEY(pIRow);
5,237!
2960
  }
2961

2962
  if (hasKey) {
788,825✔
2963
    if (hasIKey) {  // has data in mem & imem
20,967✔
2964
      if (asc) {
188!
2965
        return key.ts <= ikey.ts ? key : ikey;
188✔
2966
      } else {
2967
        return key.ts <= ikey.ts ? ikey : key;
×
2968
      }
2969
    } else {  // no data in imem
2970
      return key;
20,779✔
2971
    }
2972
  } else {
2973
    // no data in mem & imem, return the initial value
2974
    // only imem has data, return ikey
2975
    return ikey;
767,858✔
2976
  }
2977
}
2978

2979
static void prepareDurationForNextFileSet(STsdbReader* pReader) {
2,516,338✔
2980
  if (pReader->status.bProcMemFirstFileset) {
2,516,338✔
2981
    pReader->status.prevFilesetStartKey = INT64_MIN;
779,456✔
2982
    pReader->status.prevFilesetEndKey = INT64_MAX;
779,456✔
2983
    pReader->status.bProcMemFirstFileset = false;
779,456✔
2984
  }
2985

2986
  int32_t     fid = pReader->status.pCurrentFileset->fid;
2,516,338✔
2987
  STimeWindow winFid = {0};
2,516,338✔
2988
  tsdbFidKeyRange(fid, pReader->pTsdb->keepCfg.days, pReader->pTsdb->keepCfg.precision, &winFid.skey, &winFid.ekey);
2,516,338✔
2989

2990
  if (ASCENDING_TRAVERSE(pReader->info.order)) {
2,516,871✔
2991
    pReader->status.bProcMemPreFileset = !(pReader->status.memTableMaxKey < pReader->status.prevFilesetStartKey ||
3,460,105✔
2992
                                           (winFid.skey - 1) < pReader->status.memTableMinKey);
1,332,896✔
2993
  } else {
2994
    pReader->status.bProcMemPreFileset = !(pReader->status.memTableMaxKey < (winFid.ekey + 1) ||
606,169✔
2995
                                           pReader->status.prevFilesetEndKey < pReader->status.memTableMinKey);
216,507!
2996
  }
2997

2998
  if (pReader->status.bProcMemPreFileset) {
2,516,871✔
2999
    tsdbDebug("will start pre-fileset %d buffer processing. %s", fid, pReader->idStr);
866,921!
3000
    pReader->status.procMemUidList.tableUidList = pReader->status.uidList.tableUidList;
866,921✔
3001
    resetPreFilesetMemTableListIndex(&pReader->status);
866,921✔
3002
  }
3003

3004
  if (!pReader->status.bProcMemPreFileset) {
2,516,866✔
3005
    if (pReader->notifyFn) {
1,649,440!
3006
      STsdReaderNotifyInfo info = {0};
1,649,681✔
3007
      info.duration.filesetId = fid;
1,649,681✔
3008
      pReader->notifyFn(TSD_READER_NOTIFY_DURATION_START, &info, pReader->notifyParam);
1,649,681✔
3009
      tsdbDebug("new duration %d start notification when no buffer preceeding fileset, %s", fid, pReader->idStr);
1,649,964✔
3010
    }
3011
  }
3012

3013
  pReader->status.prevFilesetStartKey = winFid.skey;
2,517,340✔
3014
  pReader->status.prevFilesetEndKey = winFid.ekey;
2,517,340✔
3015
}
2,517,340✔
3016

3017
static int32_t moveToNextFile(STsdbReader* pReader, SBlockNumber* pBlockNum, SArray* pTableList) {
9,315,853✔
3018
  SReaderStatus* pStatus = &pReader->status;
9,315,853✔
3019
  pBlockNum->numOfBlocks = 0;
9,315,853✔
3020
  pBlockNum->numOfSttFiles = 0;
9,315,853✔
3021

3022
  size_t  numOfTables = tSimpleHashGetSize(pReader->status.pTableMap);
9,315,853✔
3023
  SArray* pIndexList = taosArrayInit(numOfTables, sizeof(SBrinBlk));
9,317,268✔
3024
  if (pIndexList == NULL) {
9,316,379!
3025
    return terrno;
×
3026
  }
3027

3028
  while (1) {
5,075✔
3029
    // only check here, since the iterate data in memory is very fast.
3030
    if (pReader->code != TSDB_CODE_SUCCESS) {
9,321,454!
3031
      tsdbWarn("tsdb reader is stopped ASAP, code:%s, %s", tstrerror(pReader->code), pReader->idStr);
×
3032
      return pReader->code;
×
3033
    }
3034

3035
    bool    hasNext = false;
9,321,454✔
3036
    int32_t code = filesetIteratorNext(&pStatus->fileIter, pReader, &hasNext);
9,321,454✔
3037
    if (code != TSDB_CODE_SUCCESS) {
9,320,798!
3038
      taosArrayDestroy(pIndexList);
×
3039
      return code;
×
3040
    }
3041

3042
    if (!hasNext) {  // no data files on disk
9,322,055✔
3043
      break;
2,312,910✔
3044
    }
3045

3046
    taosArrayClear(pIndexList);
7,009,145✔
3047
    code = doLoadBlockIndex(pReader, pReader->pFileReader, pIndexList);
7,008,454✔
3048
    if (code != TSDB_CODE_SUCCESS) {
7,008,142!
3049
      taosArrayDestroy(pIndexList);
×
3050
      return code;
×
3051
    }
3052

3053
    if (taosArrayGetSize(pIndexList) > 0 || pReader->status.pCurrentFileset->lvlArr->size > 0) {
7,008,142✔
3054
      code = loadFileBlockBrinInfo(pReader, pIndexList, pBlockNum, pTableList);
7,004,325✔
3055
      if (code != TSDB_CODE_SUCCESS) {
7,005,664!
3056
        taosArrayDestroy(pIndexList);
×
3057
        return code;
×
3058
      }
3059

3060
      if (pBlockNum->numOfBlocks + pBlockNum->numOfSttFiles > 0) {
7,005,664✔
3061
        if (pReader->bFilesetDelimited) {
7,003,008✔
3062
          prepareDurationForNextFileSet(pReader);
2,517,596✔
3063
        }
3064
        break;
7,001,220✔
3065
      }
3066
    }
3067

3068
    // no blocks in current file, try next files
3069
  }
3070

3071
  taosArrayDestroy(pIndexList);
9,314,130✔
3072
  return loadDataFileTombDataForAll(pReader);
9,318,581✔
3073
}
3074

3075
// pTableIter can be NULL, no need to handle the return value
3076
static int32_t resetTableListIndex(SReaderStatus* pStatus, const char* id) {
16,853,702✔
3077
  STableUidList* pList = &pStatus->uidList;
16,853,702✔
3078

3079
  pList->currentIndex = 0;
16,853,702✔
3080
  uint64_t uid = pList->tableUidList[0];
16,853,702✔
3081
  pStatus->pTableIter = tSimpleHashGet(pStatus->pTableMap, &uid, sizeof(uid));
16,853,702✔
3082
  if (pStatus->pTableIter == NULL) {
16,858,779!
3083
    tsdbError("%s failed to load tableBlockScanInfo for uid:%"PRId64", code: internal error", id, uid);
×
3084
    return TSDB_CODE_INTERNAL_ERROR;
×
3085
  }
3086

3087
  return 0;
16,858,821✔
3088
}
3089

3090
static void resetPreFilesetMemTableListIndex(SReaderStatus* pStatus) {
866,915✔
3091
  STableUidList* pList = &pStatus->procMemUidList;
866,915✔
3092

3093
  pList->currentIndex = 0;
866,915✔
3094
  uint64_t uid = pList->tableUidList[0];
866,915✔
3095
  pStatus->pProcMemTableIter = tSimpleHashGet(pStatus->pTableMap, &uid, sizeof(uid));
866,915✔
3096
}
866,916✔
3097

3098
static bool moveToNextTable(STableUidList* pOrderedCheckInfo, SReaderStatus* pStatus) {
27,218,865✔
3099
  pOrderedCheckInfo->currentIndex += 1;
27,218,865✔
3100
  if (pOrderedCheckInfo->currentIndex >= tSimpleHashGetSize(pStatus->pTableMap)) {
27,218,865✔
3101
    pStatus->pTableIter = NULL;
11,722,454✔
3102
    return false;
11,722,454✔
3103
  }
3104

3105
  uint64_t uid = pOrderedCheckInfo->tableUidList[pOrderedCheckInfo->currentIndex];
15,497,206✔
3106
  pStatus->pTableIter = tSimpleHashGet(pStatus->pTableMap, &uid, sizeof(uid));
15,497,206✔
3107
  return (pStatus->pTableIter != NULL);
15,504,755✔
3108
}
3109

3110
static bool moveToNextTableForPreFileSetMem(SReaderStatus* pStatus) {
2,031,641✔
3111
  STableUidList* pUidList = &pStatus->procMemUidList;
2,031,641✔
3112
  pUidList->currentIndex += 1;
2,031,641✔
3113
  if (pUidList->currentIndex >= tSimpleHashGetSize(pStatus->pTableMap)) {
2,031,641✔
3114
    pStatus->pProcMemTableIter = NULL;
866,930✔
3115
    return false;
866,930✔
3116
  }
3117

3118
  uint64_t uid = pUidList->tableUidList[pUidList->currentIndex];
1,164,713✔
3119
  pStatus->pProcMemTableIter = tSimpleHashGet(pStatus->pTableMap, &uid, sizeof(uid));
1,164,713✔
3120
  return (pStatus->pProcMemTableIter != NULL);
1,164,730✔
3121
}
3122

3123
static int32_t buildCleanBlockFromSttFiles(STsdbReader* pReader, STableBlockScanInfo* pScanInfo) {
32,800✔
3124
  SReaderStatus*   pStatus = &pReader->status;
32,800✔
3125
  SSttBlockReader* pSttBlockReader = pStatus->fileIter.pSttBlockReader;
32,800✔
3126
  SSDataBlock*     pResBlock = pReader->resBlockInfo.pResBlock;
32,800✔
3127

3128
  bool asc = ASCENDING_TRAVERSE(pReader->info.order);
32,800✔
3129

3130
  SDataBlockInfo* pInfo = &pResBlock->info;
32,800✔
3131
  int32_t code = blockDataEnsureCapacity(pResBlock, pScanInfo->numOfRowsInStt);
32,800✔
3132
  if (code != TSDB_CODE_SUCCESS) {
32,800!
3133
    return code;
×
3134
  }
3135

3136
  pInfo->rows = pScanInfo->numOfRowsInStt;
32,800✔
3137
  pInfo->id.uid = pScanInfo->uid;
32,800✔
3138
  pInfo->dataLoad = 1;
32,800✔
3139
  pInfo->window.skey = pScanInfo->sttRange.skey.ts;
32,800✔
3140
  pInfo->window.ekey = pScanInfo->sttRange.ekey.ts;
32,800✔
3141

3142
  setComposedBlockFlag(pReader, true);
32,800✔
3143

3144
  pScanInfo->sttKeyInfo.nextProcKey.ts = asc ? pScanInfo->sttRange.ekey.ts + 1 : pScanInfo->sttRange.skey.ts - 1;
32,780!
3145
  pScanInfo->sttKeyInfo.status = STT_FILE_NO_DATA;
32,780✔
3146

3147
  if (asc) {
32,780!
3148
    tRowKeyAssign(&pScanInfo->lastProcKey, &pScanInfo->sttRange.ekey);
32,800✔
3149
  } else {
3150
    tRowKeyAssign(&pScanInfo->lastProcKey, &pScanInfo->sttRange.skey);
×
3151
  }
3152

3153
  pScanInfo->sttBlockReturned = true;
32,800✔
3154
  pSttBlockReader->mergeTree.pIter = NULL;
32,800✔
3155

3156
  tsdbDebug("%p uid:%" PRId64 " return clean stt block as one, brange:%" PRId64 "-%" PRId64 " rows:%" PRId64 " %s",
32,800✔
3157
            pReader, pResBlock->info.id.uid, pResBlock->info.window.skey, pResBlock->info.window.ekey,
3158
            pResBlock->info.rows, pReader->idStr);
3159
  return code;
32,800✔
3160
}
3161

3162
static void buildCleanBlockFromDataFiles(STsdbReader* pReader, STableBlockScanInfo* pScanInfo,
722,195✔
3163
                                         SFileDataBlockInfo* pBlockInfo, int32_t blockIndex) {
3164
  // whole data block is required, return it directly
3165
  SReaderStatus*  pStatus = &pReader->status;
722,195✔
3166
  SDataBlockInfo* pInfo = &pReader->resBlockInfo.pResBlock->info;
722,195✔
3167
  bool            asc = ASCENDING_TRAVERSE(pReader->info.order);
722,195✔
3168

3169
  pInfo->rows = pBlockInfo->numRow;
722,195✔
3170
  pInfo->id.uid = pScanInfo->uid;
722,195✔
3171
  pInfo->dataLoad = 0;
722,195✔
3172
  pInfo->version = pReader->info.verRange.maxVer;
722,195✔
3173
  pInfo->window = (STimeWindow){.skey = pBlockInfo->firstKey, .ekey = pBlockInfo->lastKey};
722,195✔
3174

3175
  if (pReader->suppInfo.numOfPks > 0) {
722,195✔
3176
    if (IS_NUMERIC_TYPE(pReader->suppInfo.pk.type)) {
329,511!
3177
      pInfo->pks[0].val = pBlockInfo->firstPk.val;
329,511✔
3178
      pInfo->pks[1].val = pBlockInfo->lastPk.val;
329,511✔
3179
    } else {
3180
      (void)memcpy(pInfo->pks[0].pData, varDataVal(pBlockInfo->firstPk.pData), varDataLen(pBlockInfo->firstPk.pData));
×
3181
      (void)memcpy(pInfo->pks[1].pData, varDataVal(pBlockInfo->lastPk.pData), varDataLen(pBlockInfo->lastPk.pData));
×
3182

3183
      pInfo->pks[0].nData = varDataLen(pBlockInfo->firstPk.pData);
×
3184
      pInfo->pks[1].nData = varDataLen(pBlockInfo->lastPk.pData);
×
3185
    }
3186
  }
3187

3188
  // update the last key for the corresponding table
3189
  setComposedBlockFlag(pReader, false);
722,195✔
3190
  setBlockAllDumped(&pStatus->fBlockDumpInfo, pBlockInfo->lastKey, pReader->info.order);
722,081✔
3191
  updateLastKeyInfo(&pScanInfo->lastProcKey, pBlockInfo, pInfo, pReader->suppInfo.numOfPks, asc);
722,157✔
3192

3193
  tsdbDebug("%p uid:%" PRIu64
722,325✔
3194
            " clean file block retrieved from file, global index:%d, "
3195
            "table index:%d, rows:%d, brange:%" PRId64 "-%" PRId64 ", %s",
3196
            pReader, pScanInfo->uid, blockIndex, pBlockInfo->tbBlockIdx, pBlockInfo->numRow, pBlockInfo->firstKey,
3197
            pBlockInfo->lastKey, pReader->idStr);
3198
}
722,325✔
3199

3200
static int32_t doLoadSttBlockSequentially(STsdbReader* pReader) {
12,739,643✔
3201
  SReaderStatus*   pStatus = &pReader->status;
12,739,643✔
3202
  SSttBlockReader* pSttBlockReader = pStatus->fileIter.pSttBlockReader;
12,739,643✔
3203
  STableUidList*   pUidList = &pStatus->uidList;
12,739,643✔
3204
  int32_t          code = TSDB_CODE_SUCCESS;
12,739,643✔
3205

3206
  if (tSimpleHashGetSize(pStatus->pTableMap) == 0) {
12,739,643!
3207
    return TSDB_CODE_SUCCESS;
×
3208
  }
3209

3210
  SSDataBlock* pResBlock = pReader->resBlockInfo.pResBlock;
12,740,639✔
3211

3212
  while (1) {
7,639,791✔
3213
    if (pReader->code != TSDB_CODE_SUCCESS) {
20,380,430!
3214
      tsdbWarn("tsdb reader is stopped ASAP, code:%s, %s", tstrerror(pReader->code), pReader->idStr);
×
3215
      return pReader->code;
×
3216
    }
3217

3218
    // load the last data block of current table
3219
    STableBlockScanInfo* pScanInfo = NULL;
20,380,430✔
3220
    if (pStatus->pTableIter == NULL) {
20,380,430!
3221
      tsdbError("table Iter is null, invalid pScanInfo, try next table %s", pReader->idStr);
×
3222
      bool hasNexTable = moveToNextTable(pUidList, pStatus);
×
3223
      if (!hasNexTable) {
×
3224
        return TSDB_CODE_SUCCESS;
×
3225
      }
3226

3227
      continue;
×
3228
    } else {
3229
      pScanInfo = *(STableBlockScanInfo**) pStatus->pTableIter;
20,380,430✔
3230
    }
3231

3232
    if (pReader->pIgnoreTables && taosHashGet(*pReader->pIgnoreTables, &pScanInfo->uid, sizeof(pScanInfo->uid))) {
20,380,430✔
3233
      // reset the index in last block when handing a new file
3234
      bool hasNexTable = moveToNextTable(pUidList, pStatus);
84,070✔
3235
      if (!hasNexTable) {
84,063✔
3236
        return TSDB_CODE_SUCCESS;
5,751✔
3237
      }
3238

3239
      continue;
78,312✔
3240
    }
3241

3242
    initSttBlockReader(pSttBlockReader, pScanInfo, pReader);
20,294,846✔
3243
    if (pReader->code != TSDB_CODE_SUCCESS) {
20,301,760!
3244
      return pReader->code;
×
3245
    }
3246
    
3247
    if (!hasDataInSttBlock(pScanInfo)) {
20,301,760✔
3248
      bool hasNexTable = moveToNextTable(pUidList, pStatus);
14,477,666✔
3249
      if (!hasNexTable) {
14,473,387✔
3250
        return TSDB_CODE_SUCCESS;
6,912,504✔
3251
      }
3252

3253
      continue;
7,560,883✔
3254
    }
3255

3256
    // if only require the total rows, no need to load data from stt file if it is clean stt blocks
3257
    if (pReader->info.execMode == READER_EXEC_ROWS && pScanInfo->cleanSttBlocks) {
5,824,146✔
3258
      code = buildCleanBlockFromSttFiles(pReader, pScanInfo);
32,815✔
3259
      return code;
32,798✔
3260
    }
3261

3262
    int64_t st = taosGetTimestampUs();
5,795,969✔
3263
    while (1) {
3264
      // no data in stt block and block, no need to proceed.
3265
      if (!hasDataInSttBlock(pScanInfo)) {
778,864,709✔
3266
        break;
5,728,170✔
3267
      }
3268

3269
      code = buildComposedDataBlockImpl(pReader, pScanInfo, &pReader->status.fileBlockData, pSttBlockReader);
771,566,786✔
3270
      if (code) {
773,136,671!
3271
        return code;
×
3272
      }
3273

3274
      if (pResBlock->info.rows >= pReader->resBlockInfo.capacity) {
773,136,671✔
3275
        break;
67,931✔
3276
      }
3277
    }
3278

3279
    double el = (taosGetTimestampUs() - st) / 1000.0;
5,795,728✔
3280
    updateComposedBlockInfo(pReader, el, pScanInfo);
5,795,728✔
3281

3282
    if (pResBlock->info.rows > 0) {
5,795,188!
3283
      tsdbDebug("%p uid:%" PRIu64 ", composed data block created, brange:%" PRIu64 "-%" PRIu64 " rows:%" PRId64
5,795,528✔
3284
                ", elapsed time:%.2f ms %s",
3285
                pReader, pResBlock->info.id.uid, pResBlock->info.window.skey, pResBlock->info.window.ekey,
3286
                pResBlock->info.rows, el, pReader->idStr);
3287
      return TSDB_CODE_SUCCESS;
5,795,698✔
3288
    }
3289

3290
    // current table is exhausted, let's try next table
3291
    bool hasNexTable = moveToNextTable(pUidList, pStatus);
×
3292
    if (!hasNexTable) {
×
UNCOV
3293
      return TSDB_CODE_SUCCESS;
×
3294
    }
3295
  }
3296
}
3297

3298
// current active data block not overlap with the stt-files/stt-blocks
3299
static bool notOverlapWithFiles(SFileDataBlockInfo* pBlockInfo, STableBlockScanInfo* pScanInfo, bool asc) {
722,358✔
3300
  if ((!hasDataInSttBlock(pScanInfo)) || (pScanInfo->cleanSttBlocks == true)) {
722,358✔
3301
    return true;
707,958✔
3302
  } else {
3303
    int64_t keyInStt = pScanInfo->sttKeyInfo.nextProcKey.ts;
14,491✔
3304
    return (asc && pBlockInfo->lastKey < keyInStt) || (!asc && pBlockInfo->firstKey > keyInStt);
14,491!
3305
  }
3306
}
3307

3308
static int32_t doBuildDataBlock(STsdbReader* pReader) {
753,468✔
3309
  SReaderStatus*       pStatus = &pReader->status;
753,468✔
3310
  SDataBlockIter*      pBlockIter = &pStatus->blockIter;
753,468✔
3311
  STableBlockScanInfo* pScanInfo = NULL;
753,468✔
3312
  SFileDataBlockInfo*  pBlockInfo = NULL;
753,468✔
3313
  SSttBlockReader*     pSttBlockReader = pReader->status.fileIter.pSttBlockReader;
753,468✔
3314
  bool                 asc = ASCENDING_TRAVERSE(pReader->info.order);
753,468✔
3315
  int32_t              code = TSDB_CODE_SUCCESS;
753,468✔
3316

3317
  code = getCurrentBlockInfo(pBlockIter, &pBlockInfo, pReader->idStr);
753,468✔
3318
  if (code != TSDB_CODE_SUCCESS) {
753,496!
3319
    return code;
×
3320
  }
3321

3322
  if (pReader->pIgnoreTables && taosHashGet(*pReader->pIgnoreTables, &pBlockInfo->uid, sizeof(pBlockInfo->uid))) {
753,496!
3323
    setBlockAllDumped(&pStatus->fBlockDumpInfo, pBlockInfo->lastKey, pReader->info.order);
×
3324
    return code;
18✔
3325
  }
3326

3327
  if (pReader->code != TSDB_CODE_SUCCESS) {
753,571!
3328
    return pReader->code;
×
3329
  }
3330

3331
  code = getTableBlockScanInfo(pReader->status.pTableMap, pBlockInfo->uid, &pScanInfo, pReader->idStr);
753,571✔
3332
  if (code != TSDB_CODE_SUCCESS) {
753,506!
3333
    return code;
×
3334
  }
3335

3336
  if (pScanInfo->sttKeyInfo.status == STT_FILE_READER_UNINIT) {
753,506✔
3337
    initSttBlockReader(pSttBlockReader, pScanInfo, pReader);
437,734✔
3338
    if (pReader->code != 0) {
437,912!
3339
      return pReader->code;
×
3340
    }
3341
  }
3342

3343
  TSDBKEY keyInBuf = getCurrentKeyInBuf(pScanInfo, pReader);
753,684✔
3344
  if (fileBlockShouldLoad(pReader, pBlockInfo, pScanInfo, keyInBuf)) {
753,303✔
3345
    code = doLoadFileBlockData(pReader, pBlockIter, &pStatus->fileBlockData, pScanInfo->uid);
30,723✔
3346
    if (code != TSDB_CODE_SUCCESS) {
30,724!
3347
      return code;
×
3348
    }
3349

3350
    // build composed data block
3351
    code = buildComposedDataBlock(pReader);
30,724✔
3352
  } else if (bufferDataInFileBlockGap(keyInBuf, pBlockInfo, pScanInfo, pReader->info.order)) {
722,557✔
3353
    // data in memory that are earlier than current file block and stt blocks
3354
    // rows in buffer should be less than the file block in asc, greater than file block in desc
3355
    int64_t endKey = getBoarderKeyInFiles(pBlockInfo, pScanInfo, pReader->info.order);
65✔
3356
    code = buildDataBlockFromBuf(pReader, pScanInfo, endKey);
65✔
3357
  } else {
3358
    if (notOverlapWithFiles(pBlockInfo, pScanInfo, asc)) {
722,584✔
3359
      int64_t keyInStt = pScanInfo->sttKeyInfo.nextProcKey.ts;
722,414✔
3360

3361
      if ((!hasDataInSttBlock(pScanInfo)) || (asc && pBlockInfo->lastKey < keyInStt) ||
722,414!
3362
          (!asc && pBlockInfo->firstKey > keyInStt)) {
8!
3363
        // the stt blocks may located in the gap of different data block, but the whole sttRange may overlap with the
3364
        // data block, so the overlap check is invalid actually.
3365
        buildCleanBlockFromDataFiles(pReader, pScanInfo, pBlockInfo, pBlockIter->index);
722,394✔
3366
      } else {  // clean stt block
3367
        if (!(pReader->info.execMode == READER_EXEC_ROWS && pSttBlockReader->mergeTree.pIter == NULL)) {
×
3368
          tsdbError("tsdb reader failed at: %s:%d", __func__, __LINE__);
×
3369
          return TSDB_CODE_INTERNAL_ERROR;
×
3370
        }
3371
        code = buildCleanBlockFromSttFiles(pReader, pScanInfo);
×
3372
        return code;
×
3373
      }
3374
    } else {
3375
      SBlockData* pBData = &pReader->status.fileBlockData;
94✔
3376
      tBlockDataReset(pBData);
94✔
3377

3378
      SSDataBlock* pResBlock = pReader->resBlockInfo.pResBlock;
143✔
3379

3380
      tsdbDebug("load data in stt block firstly %s", pReader->idStr);
143!
3381
      int64_t st = taosGetTimestampUs();
143✔
3382

3383
      // let's load data from stt files, make sure clear the cleanStt block flag before load the data from stt files
3384
      initSttBlockReader(pSttBlockReader, pScanInfo, pReader);
143✔
3385
      if (pReader->code != 0) {
143!
3386
        return pReader->code;
×
3387
      }
3388

3389
      // no data in stt block, no need to proceed.
3390
      while (hasDataInSttBlock(pScanInfo)) {
283✔
3391
        if (pScanInfo->sttKeyInfo.status != STT_FILE_HAS_DATA) {
143!
3392
          tsdbError("tsdb reader failed at: %s:%d", __func__, __LINE__);
×
3393
          return TSDB_CODE_INTERNAL_ERROR;
×
3394
        }
3395

3396
        code = buildComposedDataBlockImpl(pReader, pScanInfo, &pReader->status.fileBlockData, pSttBlockReader);
143✔
3397
        if (code != TSDB_CODE_SUCCESS) {
143!
3398
          return code;
×
3399
        }
3400

3401
        if (pResBlock->info.rows >= pReader->resBlockInfo.capacity) {
143!
UNCOV
3402
          break;
×
3403
        }
3404

3405
        // data in stt now overlaps with current active file data block, need to composed with file data block.
3406
        SRowKey* pSttKey = getCurrentKeyInSttBlock(pSttBlockReader);
143✔
3407
        if ((pSttKey->ts >= pBlockInfo->firstKey && asc) || (pSttKey->ts <= pBlockInfo->lastKey && (!asc))) {
143!
3408
          tsdbDebug("%p lastKeyInStt:%" PRId64 ", overlap with file block, brange:%" PRId64 "-%" PRId64 " %s", pReader,
3!
3409
                    pSttKey->ts, pBlockInfo->firstKey, pBlockInfo->lastKey, pReader->idStr);
3410
          break;
3✔
3411
        }
3412
      }
3413

3414
      double el = (taosGetTimestampUs() - st) / 1000.0;
143✔
3415
      updateComposedBlockInfo(pReader, el, pScanInfo);
143✔
3416

3417
      if (pResBlock->info.rows > 0) {
143!
3418
        tsdbDebug("%p uid:%" PRIu64 ", composed data block created, brange:%" PRIu64 "-%" PRIu64 " rows:%" PRId64
143!
3419
                  ", elapsed time:%.2f ms %s",
3420
                  pReader, pResBlock->info.id.uid, pResBlock->info.window.skey, pResBlock->info.window.ekey,
3421
                  pResBlock->info.rows, el, pReader->idStr);
3422
      }
3423
    }
3424
  }
3425

3426
  return (pReader->code != TSDB_CODE_SUCCESS) ? pReader->code : code;
753,232!
3427
}
3428

3429
static int32_t buildBlockFromBufferSeqForPreFileset(STsdbReader* pReader, int64_t endKey) {
1,098,087✔
3430
  SReaderStatus* pStatus = &pReader->status;
1,098,087✔
3431

3432
  tsdbDebug("seq load data blocks from cache that preceeds fileset %d, %s", pReader->status.pCurrentFileset->fid,
1,098,087!
3433
            pReader->idStr);
3434

3435
  while (1) {
1,164,717✔
3436
    if (pReader->code != TSDB_CODE_SUCCESS) {
2,262,815!
3437
      tsdbWarn("tsdb reader is stopped ASAP, code:%s, %s", tstrerror(pReader->code), pReader->idStr);
×
3438
      return pReader->code;
×
3439
    }
3440

3441
    STableBlockScanInfo** pBlockScanInfo = pStatus->pProcMemTableIter;
2,262,815✔
3442
    if (pReader->pIgnoreTables &&
4,525,627!
3443
        taosHashGet(*pReader->pIgnoreTables, &(*pBlockScanInfo)->uid, sizeof((*pBlockScanInfo)->uid))) {
2,262,819✔
3444
      bool hasNexTable = moveToNextTableForPreFileSetMem(pStatus);
18,490✔
3445
      if (!hasNexTable) {
18,490!
3446
        return TSDB_CODE_SUCCESS;
×
3447
      }
3448
      continue;
18,490✔
3449
    }
3450

3451
    int32_t code = initMemDataIterator(*pBlockScanInfo, pReader);
2,244,318✔
3452
    if (code != TSDB_CODE_SUCCESS) {
2,244,325!
3453
      return code;
×
3454
    }
3455

3456
    code = initDelSkylineIterator(*pBlockScanInfo, pReader->info.order, &pReader->cost);
2,244,325✔
3457
    if (code != TSDB_CODE_SUCCESS) {
2,244,314!
3458
      return code;
×
3459
    }
3460

3461
    code = buildDataBlockFromBuf(pReader, *pBlockScanInfo, endKey);
2,244,314✔
3462
    if (code != TSDB_CODE_SUCCESS) {
2,244,322!
3463
      return code;
×
3464
    }
3465

3466
    if (pReader->resBlockInfo.pResBlock->info.rows > 0) {
2,244,322✔
3467
      return TSDB_CODE_SUCCESS;
231,176✔
3468
    }
3469

3470
    // current table is exhausted, let's try next table
3471
    bool hasNexTable = moveToNextTableForPreFileSetMem(pStatus);
2,013,146✔
3472
    if (!hasNexTable) {
2,013,158✔
3473
      return TSDB_CODE_SUCCESS;
866,931✔
3474
    }
3475
  }
3476
}
3477

3478
static int32_t buildBlockFromBufferSequentially(STsdbReader* pReader, int64_t endKey) {
8,398,197✔
3479
  SReaderStatus* pStatus = &pReader->status;
8,398,197✔
3480
  STableUidList* pUidList = &pStatus->uidList;
8,398,197✔
3481

3482
  tsdbDebug("seq load data blocks from cache, %s", pReader->idStr);
8,398,197✔
3483

3484
  while (1) {
7,856,500✔
3485
    if (pReader->code != TSDB_CODE_SUCCESS) {
16,256,856!
3486
      tsdbWarn("tsdb reader is stopped ASAP, code:%s, %s", tstrerror(pReader->code), pReader->idStr);
×
3487
      return pReader->code;
×
3488
    }
3489

3490
    STableBlockScanInfo** pBlockScanInfo = pStatus->pTableIter;
16,256,856✔
3491
    if (pBlockScanInfo == NULL || *pBlockScanInfo == NULL) {
16,256,856!
UNCOV
3492
      return TSDB_CODE_SUCCESS;
×
3493
    }
3494

3495
    if (pReader->pIgnoreTables &&
32,464,983✔
3496
        taosHashGet(*pReader->pIgnoreTables, &(*pBlockScanInfo)->uid, sizeof((*pBlockScanInfo)->uid))) {
16,210,573✔
3497
      bool hasNexTable = moveToNextTable(pUidList, pStatus);
59,143✔
3498
      if (!hasNexTable) {
59,147✔
3499
        return TSDB_CODE_SUCCESS;
2,161✔
3500
      }
3501
      continue;
56,986✔
3502
    }
3503

3504
    int32_t code = initMemDataIterator(*pBlockScanInfo, pReader);
16,195,267✔
3505
    if (code != TSDB_CODE_SUCCESS) {
16,200,776!
3506
      return code;
×
3507
    }
3508

3509
    code = initDelSkylineIterator(*pBlockScanInfo, pReader->info.order, &pReader->cost);
16,200,776✔
3510
    if (code != TSDB_CODE_SUCCESS) {
16,199,114!
3511
      return code;
×
3512
    }
3513

3514
    code = buildDataBlockFromBuf(pReader, *pBlockScanInfo, endKey);
16,199,114✔
3515
    if (code != TSDB_CODE_SUCCESS) {
16,198,766✔
3516
      return code;
4✔
3517
    }
3518

3519
    if (pReader->resBlockInfo.pResBlock->info.rows > 0) {
16,198,762✔
3520
      return TSDB_CODE_SUCCESS;
3,599,655✔
3521
    }
3522

3523
    // current table is exhausted, let's try next table
3524
    bool hasNexTable = moveToNextTable(pUidList, pStatus);
12,599,107✔
3525
    if (!hasNexTable) {
12,601,784✔
3526
      return TSDB_CODE_SUCCESS;
4,802,270✔
3527
    }
3528
  }
3529
}
3530

3531
// set the correct start position in case of the first/last file block, according to the query time window
3532
static void initBlockDumpInfo(STsdbReader* pReader, SDataBlockIter* pBlockIter) {
7,633,868✔
3533
  SFileDataBlockInfo* pBlockInfo = NULL;
7,633,868✔
3534
  SReaderStatus*      pStatus = &pReader->status;
7,633,868✔
3535
  SFileBlockDumpInfo* pDumpInfo = &pStatus->fBlockDumpInfo;
7,633,868✔
3536

3537
  int32_t code = getCurrentBlockInfo(pBlockIter, &pBlockInfo, pReader->idStr);
7,633,868✔
3538
  if (code == TSDB_CODE_SUCCESS) {
7,634,563✔
3539
    pDumpInfo->totalRows = pBlockInfo->numRow;
753,133✔
3540
    pDumpInfo->rowIndex = ASCENDING_TRAVERSE(pReader->info.order) ? 0 : pBlockInfo->numRow - 1;
753,133✔
3541
  } else {
3542
    pDumpInfo->totalRows = 0;
6,881,430✔
3543
    pDumpInfo->rowIndex = 0;
6,881,430✔
3544
  }
3545

3546
  pDumpInfo->allDumped = false;
7,634,563✔
3547
}
7,634,563✔
3548

3549
static int32_t initForFirstBlockInFile(STsdbReader* pReader, SDataBlockIter* pBlockIter) {
9,312,927✔
3550
  SBlockNumber num = {0};
9,312,927✔
3551
  SArray*      pTableList = taosArrayInit(40, POINTER_BYTES);
9,312,927✔
3552
  if (pTableList == NULL) {
9,316,953!
3553
    return terrno;
×
3554
  }
3555

3556
  int32_t code = moveToNextFile(pReader, &num, pTableList);
9,316,953✔
3557
  if (code != TSDB_CODE_SUCCESS) {
9,315,976!
3558
    taosArrayDestroy(pTableList);
×
3559
    return code;
×
3560
  }
3561

3562
  // all data files are consumed, try data in buffer
3563
  if (num.numOfBlocks + num.numOfSttFiles == 0) {
9,316,605✔
3564
    pReader->status.loadFromFile = false;
2,313,152✔
3565
    taosArrayDestroy(pTableList);
2,313,152✔
3566
    return code;
2,312,741✔
3567
  }
3568

3569
  // initialize the block iterator for a new fileset
3570
  if (num.numOfBlocks > 0) {
7,003,453✔
3571
    code = initBlockIterator(pReader, pBlockIter, num.numOfBlocks, pTableList);
119,934✔
3572
  } else {  // no block data, only last block exists
3573
    tBlockDataReset(&pReader->status.fileBlockData);
6,883,519✔
3574
    code = resetDataBlockIterator(pBlockIter, pReader->info.order, shouldFreePkBuf(&pReader->suppInfo), pReader->idStr);
6,879,253✔
3575
    if (code) {
6,882,042!
3576
      return code;
×
3577
    }
3578

3579
    code = resetTableListIndex(&pReader->status, pReader->idStr);
6,882,042✔
3580
    if (code) {
6,883,837!
3581
      return code;
×
3582
    }
3583
  }
3584

3585
  if (code == TSDB_CODE_SUCCESS) { // set the correct start position according to the query time window
7,003,848✔
3586
    initBlockDumpInfo(pReader, pBlockIter);
7,001,177✔
3587
  }
3588

3589
  taosArrayDestroy(pTableList);
7,004,676✔
3590
  return code;
7,005,142✔
3591
}
3592

3593
static bool fileBlockPartiallyRead(SFileBlockDumpInfo* pDumpInfo, bool asc) {
763,271✔
3594
  return (!pDumpInfo->allDumped) &&
773,603✔
3595
         ((pDumpInfo->rowIndex > 0 && asc) || (pDumpInfo->rowIndex < (pDumpInfo->totalRows - 1) && (!asc)));
10,332✔
3596
}
3597

3598
typedef enum {
3599
  TSDB_READ_RETURN = 0x1,
3600
  TSDB_READ_CONTINUE = 0x2,
3601
} ERetrieveType;
3602

3603
static int32_t doReadDataFromSttFiles(STsdbReader* pReader, ERetrieveType* pReturnType) {
7,774,872✔
3604
  int32_t         code = TSDB_CODE_SUCCESS;
7,774,872✔
3605
  SSDataBlock*    pResBlock = pReader->resBlockInfo.pResBlock;
7,774,872✔
3606
  SDataBlockIter* pBlockIter = &pReader->status.blockIter;
7,774,872✔
3607

3608
  *pReturnType = TSDB_READ_RETURN;
7,774,872✔
3609

3610
  tsdbDebug("seq load data blocks from stt files %s", pReader->idStr);
7,774,872✔
3611

3612
  while (1) {
3613
    code = doLoadSttBlockSequentially(pReader);
12,744,748✔
3614
    if (code != TSDB_CODE_SUCCESS) {
12,743,004!
3615
      *pReturnType = TSDB_READ_RETURN;
×
3616
      return code;
×
3617
    }
3618

3619
    if (pResBlock->info.rows > 0) {
12,743,004✔
3620
      *pReturnType = TSDB_READ_RETURN;
5,827,510✔
3621
      return code;
5,827,510✔
3622
    }
3623

3624
    // all data blocks are checked in this stt file, now let's try the next file set
3625
    if (pReader->status.pTableIter != NULL) {
6,915,494!
3626
      code = TSDB_CODE_INTERNAL_ERROR;
×
3627
      tsdbError("tsdb reader failed at: %s:%d, code:%s", __func__, __LINE__, tstrerror(code));
×
3628
      return code;
×
3629
    }
3630

3631
    code = initForFirstBlockInFile(pReader, pBlockIter);
6,915,494✔
3632

3633
    // error happens or all the data files are completely checked
3634
    if ((code != TSDB_CODE_SUCCESS) || (pReader->status.loadFromFile == false)) {
6,918,669!
3635
      *pReturnType = TSDB_READ_RETURN;
1,717,878✔
3636
      return code;
1,717,878✔
3637
    }
3638

3639
    if (pReader->status.bProcMemPreFileset) {
5,200,791✔
3640
      code = buildFromPreFilesetBuffer(pReader);
801,841✔
3641
      if (code != TSDB_CODE_SUCCESS) {
801,840!
3642
        return code;
×
3643
      }
3644
      if (pResBlock->info.rows > 0) {
801,840✔
3645
        pReader->status.processingMemPreFileSet = true;
116,632✔
3646
        *pReturnType = TSDB_READ_RETURN;
116,632✔
3647
        return code;
116,632✔
3648
      }
3649
    }
3650

3651
    if (pBlockIter->numOfBlocks > 0) {  // there are data blocks existed.
5,084,158✔
3652
      *pReturnType = TSDB_READ_CONTINUE;
114,817✔
3653
      return code;
114,817✔
3654
    } else {  // all blocks in data file are checked, let's check the data in stt-files
3655
      code = resetTableListIndex(&pReader->status, pReader->idStr);
4,969,341✔
3656
      if (code) {
4,969,870!
3657
        return code;
×
3658
      }
3659
    }
3660
  }
3661
}
3662

3663
static int32_t buildBlockFromFiles(STsdbReader* pReader) {
8,412,441✔
3664
  int32_t code = TSDB_CODE_SUCCESS;
8,412,441✔
3665
  bool    asc = ASCENDING_TRAVERSE(pReader->info.order);
8,412,441✔
3666

3667
  SDataBlockIter*     pBlockIter = &pReader->status.blockIter;
8,412,441✔
3668
  SSDataBlock*        pResBlock = pReader->resBlockInfo.pResBlock;
8,412,441✔
3669
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;
8,412,441✔
3670
  SBlockData*         pBlockData = &pReader->status.fileBlockData;
8,412,441✔
3671
  const char*         id = pReader->idStr;
8,412,441✔
3672

3673
  if (pBlockIter->numOfBlocks == 0) {
8,412,441✔
3674
    // let's try to extract data from stt files.
3675
    ERetrieveType type = 0;
7,656,804✔
3676
    code = doReadDataFromSttFiles(pReader, &type);
7,656,804✔
3677
    if (code != 0 || type == TSDB_READ_RETURN) {
7,656,428!
3678
      return code;
7,656,211✔
3679
    }
3680

3681
    code = doBuildDataBlock(pReader);
464✔
3682
    if (code != TSDB_CODE_SUCCESS || pResBlock->info.rows > 0) {
464!
3683
      return code;
247✔
3684
    }
3685
  }
3686

3687
  while (1) {
3688
    if (fileBlockPartiallyRead(pDumpInfo, asc)) {  // file data block is partially loaded
761,457✔
3689
      code = buildComposedDataBlock(pReader);
4,677✔
3690
    } else {
3691
      // current block are exhausted, try the next file block
3692
      if (pDumpInfo->allDumped) {
758,594✔
3693
        // try next data block in current file
3694
        bool hasNext = blockIteratorNext(&pReader->status.blockIter, pReader->idStr);
752,993✔
3695
        if (hasNext) {  // check for the next block in the block accessed order list
753,026✔
3696
          initBlockDumpInfo(pReader, pBlockIter);
633,267✔
3697
        } else {
3698
          // all data blocks in files are checked, let's check the data in last files.
3699
          // data blocks in current file are exhausted, let's try the next file now
3700
          if (pBlockData->uid != 0) {
119,759!
3701
            tBlockDataClear(pBlockData);
119,779✔
3702
          }
3703

3704
          tBlockDataReset(pBlockData);
119,740✔
3705
          code = resetDataBlockIterator(pBlockIter, pReader->info.order, shouldFreePkBuf(&pReader->suppInfo), id);
120,041✔
3706
          if (code != TSDB_CODE_SUCCESS) {
119,944!
3707
            return code;
5,498✔
3708
          }
3709

3710
          code = resetTableListIndex(&pReader->status, id);
119,944✔
3711
          if (code != TSDB_CODE_SUCCESS) {
119,980!
3712
            return code;
×
3713
          }
3714

3715
          ERetrieveType type = 0;
119,980✔
3716
          code = doReadDataFromSttFiles(pReader, &type);
119,980✔
3717
          if (code != 0 || type == TSDB_READ_RETURN) {
119,890!
3718
            return code;
5,498✔
3719
          }
3720
        }
3721
      }
3722

3723
      code = doBuildDataBlock(pReader);
753,225✔
3724
    }
3725

3726
    if (code != TSDB_CODE_SUCCESS || pResBlock->info.rows > 0) {
757,512✔
3727
      return code;
751,909✔
3728
    }
3729
  }
3730
}
3731

3732
static void getTsdbByRetentions(SVnode* pVnode, SQueryTableDataCond* pCond, SRetention* retentions, const char* idStr,
5,081,003✔
3733
                                int8_t* pLevel, STsdb** pTsdb) {
3734
  if (pTsdb == NULL) {
5,081,003!
3735
    return;
×
3736
  }
3737

3738
  *pTsdb = NULL;
5,081,003✔
3739
  if (VND_IS_RSMA(pVnode) && !pCond->skipRollup) {
5,081,003✔
3740
    int8_t  level = 0;
38✔
3741
    int8_t  precision = pVnode->config.tsdbCfg.precision;
38✔
3742
    int64_t now = taosGetTimestamp(precision);
38!
3743
    int64_t offset = tsQueryRsmaTolerance * ((precision == TSDB_TIME_PRECISION_MILLI)   ? 1L
76✔
3744
                                             : (precision == TSDB_TIME_PRECISION_MICRO) ? 1000L
38!
3745
                                                                                        : 1000000L);
×
3746

3747
    for (int32_t i = 0; i < TSDB_RETENTION_MAX; ++i) {
91✔
3748
      SRetention* pRetention = retentions + level;
79✔
3749
      if (pRetention->keep <= 0) {
79!
3750
        if (level > 0) {
×
3751
          --level;
×
3752
        }
3753
        break;
×
3754
      }
3755
      if ((now - pRetention->keep) <= (pCond->twindows.skey + offset)) {
79✔
3756
        break;
26✔
3757
      }
3758
      ++level;
53✔
3759
    }
3760

3761
    const char* str = (idStr != NULL) ? idStr : "";
38!
3762

3763
    if (level == TSDB_RETENTION_L0) {
38✔
3764
      *pLevel = TSDB_RETENTION_L0;
11✔
3765
      tsdbDebug("vgId:%d, rsma level %d is selected to query %s", TD_VID(pVnode), TSDB_RETENTION_L0, str);
11!
3766
      *pTsdb = VND_RSMA0(pVnode);
11✔
3767
      return;
11✔
3768
    } else if (level == TSDB_RETENTION_L1) {
27✔
3769
      *pLevel = TSDB_RETENTION_L1;
13✔
3770
      tsdbDebug("vgId:%d, rsma level %d is selected to query %s", TD_VID(pVnode), TSDB_RETENTION_L1, str);
13!
3771
      *pTsdb =  VND_RSMA1(pVnode);
13✔
3772
      return;
13✔
3773
    } else {
3774
      *pLevel = TSDB_RETENTION_L2;
14✔
3775
      tsdbDebug("vgId:%d, rsma level %d is selected to query %s", TD_VID(pVnode), TSDB_RETENTION_L2, str);
14!
3776
      *pTsdb = VND_RSMA2(pVnode);
14✔
3777
      return;
14✔
3778
    }
3779
  }
3780

3781
  *pTsdb = VND_TSDB(pVnode);
5,080,965✔
3782
}
3783

3784
SVersionRange getQueryVerRange(SVnode* pVnode, SQueryTableDataCond* pCond, int8_t level) {
5,081,280✔
3785
  int64_t startVer = (pCond->startVersion == -1) ? 0 : pCond->startVersion;
5,081,280✔
3786

3787
  int64_t endVer = 0;
5,081,280✔
3788
  if (pCond->endVersion == -1) {
5,081,280✔
3789
    // user not specified end version, set current maximum version of vnode as the endVersion
3790
    endVer = pVnode->state.applied;
5,072,275✔
3791
  } else {
3792
    endVer = (pCond->endVersion > pVnode->state.applied) ? pVnode->state.applied : pCond->endVersion;
9,005✔
3793
  }
3794

3795
  return (SVersionRange){.minVer = startVer, .maxVer = endVer};
5,081,280✔
3796
}
3797

3798
static int32_t reverseSearchStartPos(const SArray* pDelList, int32_t index, int64_t key, bool asc) {
51,012,626✔
3799
  size_t  num = taosArrayGetSize(pDelList);
51,012,626✔
3800
  int32_t start = index;
49,427,336✔
3801

3802
  if (asc) {
49,427,336✔
3803
    if (start >= num - 1) {
42,931,777✔
3804
      start = num - 1;
19,822,008✔
3805
    }
3806

3807
    TSDBKEY* p = taosArrayGet(pDelList, start);
42,931,777✔
3808
    if (p == NULL) {
42,781,353!
3809
      return TSDB_CODE_INVALID_PARA;
×
3810
    }
3811

3812
    while (p->ts >= key && start > 0) {
42,834,326✔
3813
      start -= 1;
52,973✔
3814
    }
3815
  } else {
3816
    if (index <= 0) {
6,495,559!
3817
      start = 0;
×
3818
    }
3819

3820
    TSDBKEY* p = taosArrayGet(pDelList, start);
6,495,559✔
3821
    if (p == NULL) {
6,548,015!
3822
      return TSDB_CODE_INVALID_PARA;
×
3823
    }
3824

3825
    while (p->ts <= key && start < num - 1) {
6,550,155✔
3826
      start += 1;
2,140✔
3827
    }
3828
  }
3829

3830
  return start;
49,329,368✔
3831
}
3832

3833
bool hasBeenDropped(const SArray* pDelList, int32_t* index, int64_t key, int64_t ver, int32_t order,
283,167,584✔
3834
                    SVersionRange* pVerRange, bool hasPk) {
3835
  if (pDelList == NULL || (TARRAY_SIZE(pDelList) == 0)) {
283,167,584!
3836
    return false;
×
3837
  }
3838

3839
  size_t  num = taosArrayGetSize(pDelList);
283,381,552✔
3840
  bool    asc = ASCENDING_TRAVERSE(order);
282,235,103✔
3841
  int32_t step = asc ? 1 : -1;
282,235,103✔
3842

3843
  if (hasPk) {  // handle the case where duplicated timestamps existed.
282,235,103✔
3844
    *index = reverseSearchStartPos(pDelList, *index, key, asc);
51,156,296✔
3845
  }
3846

3847
  if (asc) {
280,466,816✔
3848
    if (*index >= num - 1) {
255,021,986✔
3849
      TSDBKEY* last = taosArrayGetLast(pDelList);
61,381,614✔
3850
      if (last == NULL) {
61,305,724!
3851
        return false;
×
3852
      }
3853

3854
      if (key > last->ts) {
61,305,724✔
3855
        return false;
61,304,828✔
3856
      } else if (key == last->ts) {
896!
3857
        TSDBKEY* prev = taosArrayGet(pDelList, num - 2);
4,721✔
3858
        if (prev == NULL) {
4,721!
3859
          return false;
×
3860
        }
3861

3862
        return (prev->version >= ver && prev->version <= pVerRange->maxVer && prev->version >= pVerRange->minVer);
4,721!
3863
      }
3864
    } else {
3865
      TSDBKEY* pCurrent = taosArrayGet(pDelList, *index);
193,640,372✔
3866
      TSDBKEY* pNext = taosArrayGet(pDelList, (*index) + 1);
194,893,899✔
3867
      if (pCurrent == NULL || pNext == NULL) {
191,855,272!
3868
        return false;
×
3869
      }
3870

3871
      if (key < pCurrent->ts) {
191,855,272✔
3872
        return false;
12,623,693✔
3873
      }
3874

3875
      if (pCurrent->ts <= key && pNext->ts >= key && pCurrent->version >= ver &&
179,231,579!
3876
          pVerRange->maxVer >= pCurrent->version) {
11,847,949!
3877
        return true;
11,848,268✔
3878
      }
3879

3880
      while (pNext->ts <= key && (*index) < num - 1) {
168,413,399✔
3881
        (*index) += 1;
1,251,682✔
3882

3883
        if ((*index) < num - 1) {
1,251,682✔
3884
          pCurrent = taosArrayGet(pDelList, *index);
1,192,759✔
3885
          pNext = taosArrayGet(pDelList, (*index) + 1);
1,192,758✔
3886
          if (pCurrent == NULL || pNext == NULL) {
1,192,758!
3887
            return false;
×
3888
          }
3889

3890
          // it is not a consecutive deletion range, ignore it
3891
          if (pCurrent->version == 0 && pNext->version > 0) {
1,192,758!
3892
            continue;
503,719✔
3893
          }
3894

3895
          if (pCurrent->ts <= key && pNext->ts >= key && pCurrent->version >= ver &&
689,039!
3896
              pVerRange->maxVer >= pCurrent->version) {
221,592!
3897
            return true;
221,593✔
3898
          }
3899
        }
3900
      }
3901

3902
      return false;
167,161,717✔
3903
    }
3904
  } else {
3905
    if (*index <= 0) {
25,444,830!
3906
      TSDBKEY* pFirst = taosArrayGet(pDelList, 0);
×
3907
      if (pFirst == NULL) {
×
3908
        return false;
×
3909
      }
3910

3911
      if (key < pFirst->ts) {
×
3912
        return false;
×
3913
      } else if (key == pFirst->ts) {
×
3914
        return pFirst->version >= ver;
×
3915
      } else {
3916
        tsdbError("unexpected error, key:%" PRId64 ", first:%" PRId64, key, pFirst->ts);
×
3917
      }
3918
    } else {
3919
      TSDBKEY* pCurrent = taosArrayGet(pDelList, *index);
25,444,830✔
3920
      TSDBKEY* pPrev = taosArrayGet(pDelList, (*index) - 1);
25,229,610✔
3921
      if (pCurrent == NULL || pPrev == NULL) {
25,119,593!
3922
        return false;
×
3923
      }
3924

3925
      if (key > pCurrent->ts) {
25,119,593✔
3926
        return false;
8,421,806✔
3927
      }
3928

3929
      if (pPrev->ts <= key && pCurrent->ts >= key && pPrev->version >= ver) {
16,697,787✔
3930
        return true;
757,904✔
3931
      }
3932

3933
      while (pPrev->ts >= key && (*index) > 1) {
16,025,527✔
3934
        (*index) += step;
186,118✔
3935

3936
        if ((*index) >= 1) {
186,118!
3937
          pCurrent = taosArrayGet(pDelList, *index);
186,118✔
3938
          pPrev = taosArrayGet(pDelList, (*index) - 1);
186,118✔
3939
          if (pCurrent == NULL || pPrev == NULL) {
186,118!
3940
            return false;
×
3941
          }
3942

3943
          // it is not a consecutive deletion range, ignore it
3944
          if (pCurrent->version > 0 && pPrev->version == 0) {
186,118✔
3945
            continue;
33,391✔
3946
          }
3947

3948
          if (pPrev->ts <= key && pCurrent->ts >= key && pPrev->version >= ver) {
152,727!
3949
            return true;
100,474✔
3950
          }
3951
        }
3952
      }
3953

3954
      return false;
15,839,409✔
3955
    }
3956
  }
3957

3958
  return false;
×
3959
}
3960

3961
FORCE_INLINE void getValidMemRow(SIterInfo* pIter, const SArray* pDelList, STsdbReader* pReader, TSDBROW** pRes) {
3962
  *pRes = NULL;
2,147,483,647✔
3963

3964
  if (!pIter->hasVal) {
1,539,234,961!
3965
    return;
1,045,855,731✔
3966
  }
3967

3968
  int32_t  order = pReader->info.order;
2,147,483,647✔
3969
  TSDBROW* pRow = tsdbTbDataIterGet(pIter->iter);
2,147,483,647!
3970

3971
  TSDBKEY key;
3972
  TSDBROW_INIT_KEY(pRow, key);
2,147,483,647!
3973
  if (outOfTimeWindow(key.ts, &pReader->info.window)) {
2,147,483,647!
3974
    pIter->hasVal = false;
×
3975
    return;
×
3976
  }
3977

3978
  // it is a valid data version
3979
  if (key.version <= pReader->info.verRange.maxVer && key.version >= pReader->info.verRange.minVer) {
2,147,483,647!
3980
    if (pDelList == NULL || TARRAY_SIZE(pDelList) == 0) {
2,147,483,647!
3981
      *pRes = pRow;
2,147,483,647✔
3982
      return;
2,147,483,647✔
3983
    } else {
3984
      bool dropped = hasBeenDropped(pDelList, &pIter->index, key.ts, key.version, order, &pReader->info.verRange,
199,516,055✔
3985
                                    pReader->suppInfo.numOfPks > 0);
199,516,055✔
3986
      if (!dropped) {
196,574,989!
3987
        *pRes = pRow;
196,413,868✔
3988
        return;
196,413,868✔
3989
      }
3990
    }
3991
  }
3992

3993
  while (1) {
3994
    pIter->hasVal = tsdbTbDataIterNext(pIter->iter);
×
3995
    if (!pIter->hasVal) {
5,439,805!
3996
      return;
9,576✔
3997
    }
3998

3999
    pRow = tsdbTbDataIterGet(pIter->iter);
5,430,229!
4000

4001
    TSDBROW_INIT_KEY(pRow, key);
5,430,229!
4002
    if (outOfTimeWindow(key.ts, &pReader->info.window)) {
5,430,229!
4003
      pIter->hasVal = false;
49,257✔
4004
      return;
49,257✔
4005
    }
4006

4007
    if (key.version <= pReader->info.verRange.maxVer && key.version >= pReader->info.verRange.minVer) {
5,380,972!
4008
      if (pDelList == NULL || TARRAY_SIZE(pDelList) == 0) {
5,143,229!
4009
        *pRes = pRow;
1,161✔
4010
        return;
1,161✔
4011
      } else {
4012
        bool dropped = hasBeenDropped(pDelList, &pIter->index, key.ts, key.version, order, &pReader->info.verRange,
5,142,068✔
4013
                                      pReader->suppInfo.numOfPks > 0);
5,142,068✔
4014
        if (!dropped) {
5,141,886!
4015
          *pRes = pRow;
151,510✔
4016
          return;
151,510✔
4017
        }
4018
      }
4019
    }
4020
  }
4021
}
4022

4023
int32_t doMergeRowsInBuf(SIterInfo* pIter, uint64_t uid, SRowKey* pCurKey, SArray* pDelList, STsdbReader* pReader) {
251,143,204✔
4024
  SRowMerger* pMerger = &pReader->status.merger;
251,143,204✔
4025
  int32_t code = 0;
251,143,204✔
4026

4027
  while (1) {
1,929,537✔
4028
    pIter->hasVal = tsdbTbDataIterNext(pIter->iter);
253,072,741✔
4029
    if (!pIter->hasVal) {
253,055,963✔
4030
      break;
280,978✔
4031
    }
4032

4033
    // data exists but not valid
4034
    TSDBROW* pRow = NULL;
252,774,985!
4035
    getValidMemRow(pIter, pDelList, pReader, &pRow);
4036
    if (pRow == NULL) {
252,752,275✔
4037
      break;
73,679✔
4038
    }
4039

4040
    // ts is not identical, quit
4041
    if (TSDBROW_TS(pRow) != pCurKey->ts) {
252,678,596!
4042
      break;
250,815,306✔
4043
    }
4044

4045
    if (pCurKey->numOfPKs > 0) {
1,863,290✔
4046
      SRowKey nextKey = {0};
726✔
4047
      tRowGetKeyEx(pRow, &nextKey);
726!
4048
      if (pkCompEx(pCurKey, &nextKey) != 0) {
726✔
4049
        break;
432✔
4050
      }
4051
    }
4052

4053
    STSchema* pTSchema = NULL;
1,862,858✔
4054
    if (pRow->type == TSDBROW_ROW_FMT) {
1,862,858!
4055
      pTSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(pRow), pReader, uid);
1,928,963!
4056
      if (pTSchema == NULL) {
1,928,983!
4057
        return terrno;
×
4058
      }
4059
    }
4060

4061
    code = tsdbRowMergerAdd(pMerger, pRow, pTSchema);
1,862,878✔
4062
    if (code != TSDB_CODE_SUCCESS) {
1,929,537!
4063
      return code;
×
4064
    }
4065
  }
4066

4067
  return code;
251,170,395✔
4068
}
4069

4070
static int32_t doMergeRowsInFileBlockImpl(SBlockData* pBlockData, int32_t* rowIndex, SRowKey* pKey, SRowMerger* pMerger,
25,755,929✔
4071
                                          SVersionRange* pVerRange, int32_t step) {
4072
  int32_t code = 0;
25,755,929✔
4073
  while ((*rowIndex) < pBlockData->nRow && (*rowIndex) >= 0) {
25,776,635!
4074
    SRowKey cur;
4075
    tColRowGetKey(pBlockData, (*rowIndex), &cur);
25,775,037✔
4076
    if (pkCompEx(&cur, pKey) != 0) {
25,847,868✔
4077
      break;
25,827,162✔
4078
    }
4079

4080
    if (pBlockData->aVersion[(*rowIndex)] > pVerRange->maxVer ||
20,706!
4081
        pBlockData->aVersion[(*rowIndex)] < pVerRange->minVer) {
×
4082
      (*rowIndex) += step;
20,706✔
4083
      continue;
20,706✔
4084
    }
4085

4086
    TSDBROW fRow = tsdbRowFromBlockData(pBlockData, (*rowIndex));
×
4087
    code = tsdbRowMergerAdd(pMerger, &fRow, NULL);
×
4088
    if (code != TSDB_CODE_SUCCESS) {
×
4089
      return code;
×
4090
    }
4091
    (*rowIndex) += step;
×
4092
  }
4093
  return code;
25,828,760✔
4094
}
4095

4096
typedef enum {
4097
  CHECK_FILEBLOCK_CONT = 0x1,
4098
  CHECK_FILEBLOCK_QUIT = 0x2,
4099
} CHECK_FILEBLOCK_STATE;
4100

4101
static int32_t checkForNeighborFileBlock(STsdbReader* pReader, STableBlockScanInfo* pScanInfo,
18,715✔
4102
                                         SFileDataBlockInfo* pFBlock, SRowMerger* pMerger, SRowKey* pKey,
4103
                                         CHECK_FILEBLOCK_STATE* state) {
4104
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;
18,715✔
4105
  SBlockData*         pBlockData = &pReader->status.fileBlockData;
18,715✔
4106
  bool                asc = ASCENDING_TRAVERSE(pReader->info.order);
18,715✔
4107
  SVersionRange*      pVerRange = &pReader->info.verRange;
18,715✔
4108
  bool                loadNeighbor = true;
18,715✔
4109
  int32_t             step = ASCENDING_TRAVERSE(pReader->info.order) ? 1 : -1;
18,715✔
4110

4111
  int32_t code = loadNeighborIfOverlap(pFBlock, pScanInfo, pReader, &loadNeighbor);
18,715✔
4112
  *state = CHECK_FILEBLOCK_QUIT;
18,715✔
4113

4114
  if (loadNeighbor && (code == TSDB_CODE_SUCCESS)) {
18,715!
4115
    code = doMergeRowsInFileBlockImpl(pBlockData, &pDumpInfo->rowIndex, pKey, pMerger, pVerRange, step);
×
4116
    if (code != TSDB_CODE_SUCCESS) {
×
4117
      return code;
×
4118
    }
4119
    if ((pDumpInfo->rowIndex >= pDumpInfo->totalRows && asc) || (pDumpInfo->rowIndex < 0 && !asc)) {
×
4120
      *state = CHECK_FILEBLOCK_CONT;
×
4121
    }
4122
  }
4123

4124
  return code;
18,715✔
4125
}
4126

4127
int32_t doMergeRowsInFileBlocks(SBlockData* pBlockData, STableBlockScanInfo* pScanInfo, SRowKey* pKey,
25,763,473✔
4128
                                STsdbReader* pReader) {
4129
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;
25,763,473✔
4130
  SRowMerger*         pMerger = &pReader->status.merger;
25,763,473✔
4131
  bool                asc = ASCENDING_TRAVERSE(pReader->info.order);
25,763,473✔
4132
  int32_t             step = asc ? 1 : -1;
25,763,473✔
4133
  SVersionRange*      pRange = &pReader->info.verRange;
25,763,473✔
4134
  int32_t             code = 0;
25,763,473✔
4135

4136
  pDumpInfo->rowIndex += step;
25,763,473✔
4137
  if ((pDumpInfo->rowIndex <= pBlockData->nRow - 1 && asc) || (pDumpInfo->rowIndex >= 0 && !asc)) {
25,763,473!
4138
    code = doMergeRowsInFileBlockImpl(pBlockData, &pDumpInfo->rowIndex, pKey, pMerger, pRange, step);
25,750,691✔
4139
    if (code != TSDB_CODE_SUCCESS) {
25,874,563!
4140
      return code;
×
4141
    }
4142
  }
4143

4144
  // all rows are consumed, let's try next file block
4145
  if ((pDumpInfo->rowIndex >= pBlockData->nRow && asc) || (pDumpInfo->rowIndex < 0 && !asc)) {
25,887,345!
4146
    while (1) {
×
4147
      CHECK_FILEBLOCK_STATE st;
4148

4149
      SFileDataBlockInfo* pFileBlockInfo = NULL;
×
4150
      code = getCurrentBlockInfo(&pReader->status.blockIter, &pFileBlockInfo, pReader->idStr);
×
4151
      if (code != TSDB_CODE_SUCCESS) {
18,715!
4152
        return code;
×
4153
      }
4154

4155
      if (pFileBlockInfo == NULL) {
18,715!
4156
        st = CHECK_FILEBLOCK_QUIT;
×
4157
        break;
18,715✔
4158
      }
4159

4160
      code = checkForNeighborFileBlock(pReader, pScanInfo, pFileBlockInfo, pMerger, pKey, &st);
18,715✔
4161
      if (st == CHECK_FILEBLOCK_QUIT || code != TSDB_CODE_SUCCESS) {
18,715!
4162
        break;
4163
      }
4164
    }
4165
  }
4166

4167
  return code;
25,978,560✔
4168
}
4169

4170
int32_t doMergeRowsInSttBlock(SSttBlockReader* pSttBlockReader, STableBlockScanInfo* pScanInfo, SRowMerger* pMerger,
192,665,642✔
4171
                              int32_t pkSrcSlot, SVersionRange* pVerRange, const char* idStr) {
4172
  SRowKey* pRowKey = &pScanInfo->lastProcKey;
192,665,642✔
4173
  int32_t code = TSDB_CODE_SUCCESS;
192,665,642✔
4174

4175
  while (1) {
2,721,585✔
4176
    code = nextRowFromSttBlocks(pSttBlockReader, pScanInfo, pkSrcSlot, pVerRange);
195,387,227✔
4177
    if (code || (!hasDataInSttBlock(pScanInfo))) {
194,863,310!
4178
      return code;
2,951,769✔
4179
    }
4180

4181
    SRowKey* pNextKey = getCurrentKeyInSttBlock(pSttBlockReader);
191,856,109!
4182

4183
    int32_t ret = pkCompEx(pRowKey, pNextKey);
191,933,682✔
4184
    if (ret == 0) {
191,933,682✔
4185
      TSDBROW* pRow1 = tMergeTreeGetRow(&pSttBlockReader->mergeTree);
2,727,878✔
4186
      code = tsdbRowMergerAdd(pMerger, pRow1, NULL);
2,727,878✔
4187
      if (code != TSDB_CODE_SUCCESS) {
2,721,585!
4188
        break;
×
4189
      }
4190
    } else {
4191
      tsdbTrace("uid:%" PRIu64 " last del index:%d, del range:%d, lastKeyInStt:%" PRId64 ", %s", pScanInfo->uid,
189,205,804!
4192
                pScanInfo->sttBlockDelIndex, (int32_t)taosArrayGetSize(pScanInfo->delSkyline),
4193
                pScanInfo->sttKeyInfo.nextProcKey.ts, idStr);
4194
      break;
189,184,160✔
4195
    }
4196
  }
4197

4198
  return code;
189,184,160✔
4199
}
4200

4201
int32_t doMergeMemTableMultiRows(TSDBROW* pRow, SRowKey* pKey, uint64_t uid, SIterInfo* pIter, SArray* pDelList,
1,075,931,753✔
4202
                                 TSDBROW* pResRow, STsdbReader* pReader, bool* freeTSRow) {
4203
  SRowMerger* pMerger = &pReader->status.merger;
1,075,931,753✔
4204
  TSDBROW*    pNextRow = NULL;
1,075,931,753✔
4205
  TSDBROW     current = *pRow;
1,075,931,753✔
4206

4207
  {  // if the timestamp of the next valid row has a different ts, return current row directly
4208
    pIter->hasVal = tsdbTbDataIterNext(pIter->iter);
1,075,931,753✔
4209

4210
    if (!pIter->hasVal) {
1,068,476,561✔
4211
      *pResRow = *pRow;
2,597,699✔
4212
      *freeTSRow = false;
2,597,699✔
4213
      return TSDB_CODE_SUCCESS;
2,597,699✔
4214
    } else {  // has next point in mem/imem
4215
      getValidMemRow(pIter, pDelList, pReader, &pNextRow);
4216
      if (pNextRow == NULL) {
1,065,576,336✔
4217
        *pResRow = current;
812,395✔
4218
        *freeTSRow = false;
812,395✔
4219
        return TSDB_CODE_SUCCESS;
812,395✔
4220
      }
4221

4222
      if (TSDBROW_TS(&current) != TSDBROW_TS(pNextRow)) {
1,064,763,941!
4223
        *pResRow = current;
1,062,834,430✔
4224
        *freeTSRow = false;
1,062,834,430✔
4225
        return TSDB_CODE_SUCCESS;
1,062,834,430✔
4226
      }
4227

4228
      if (pKey->numOfPKs > 0) {
1,929,511!
4229
        SRowKey nextRowKey = {0};
4,237,627✔
4230
        tRowGetKeyEx(pNextRow, &nextRowKey);
4,237,627!
4231
        if (pkCompEx(pKey, &nextRowKey) != 0) {
4,237,046✔
4232
          *pResRow = current;
4,236,414✔
4233
          *freeTSRow = false;
4,236,414✔
4234
          return TSDB_CODE_SUCCESS;
4,236,414✔
4235
        }
4236
      }
4237
    }
4238
  }
4239

4240
  terrno = 0;
×
4241
  int32_t code = 0;
6,696,016✔
4242

4243
  // start to merge duplicated rows
4244
  STSchema* pTSchema = NULL;
6,696,016✔
4245
  if (current.type == TSDBROW_ROW_FMT) {  // get the correct schema for row-wise data in memory
6,696,016!
4246
    pTSchema = doGetSchemaForTSRow(current.pTSRow->sver, pReader, uid);
6,696,151!
4247
    if (pTSchema == NULL) {
6,695,629!
4248
      return terrno;
×
4249
    }
4250
  }
4251

4252
  code = tsdbRowMergerAdd(pMerger, &current, pTSchema);
6,695,494✔
4253
  if (code != TSDB_CODE_SUCCESS) {
6,668,214!
4254
    return code;
×
4255
  }
4256

4257
  STSchema* pTSchema1 = NULL;
6,668,214✔
4258
  if (pNextRow->type == TSDBROW_ROW_FMT) {  // get the correct schema for row-wise data in memory
6,668,214!
4259
    pTSchema1 = doGetSchemaForTSRow(pNextRow->pTSRow->sver, pReader, uid);
6,668,420!
4260
    if (pTSchema1 == NULL) {
6,667,338!
4261
      return terrno;
×
4262
    }
4263
  }
4264

4265
  code = tsdbRowMergerAdd(pMerger, pNextRow, pTSchema1);
6,667,132✔
4266
  if (code != TSDB_CODE_SUCCESS) {
6,685,800!
4267
    return code;
×
4268
  }
4269

4270
  code = doMergeRowsInBuf(pIter, uid, pKey, pDelList, pReader);
6,685,800✔
4271
  if (code != TSDB_CODE_SUCCESS) {
6,656,456!
4272
    return code;
×
4273
  }
4274

4275
  code = tsdbRowMergerGetRow(pMerger, &pResRow->pTSRow);
6,656,456✔
4276
  if (code != TSDB_CODE_SUCCESS) {
6,704,741!
4277
    return code;
×
4278
  }
4279

4280
  pResRow->type = TSDBROW_ROW_FMT;
6,704,741✔
4281
  tsdbRowMergerClear(pMerger);
6,704,741✔
4282
  *freeTSRow = true;
6,667,815✔
4283

4284
  return TSDB_CODE_SUCCESS;
6,667,815✔
4285
}
4286

4287
int32_t doMergeMemIMemRows(TSDBROW* pRow, SRowKey* pRowKey, TSDBROW* piRow, SRowKey* piRowKey,
122,558✔
4288
                           STableBlockScanInfo* pBlockScanInfo, STsdbReader* pReader, SRow** pTSRow) {
4289
  SRowMerger* pMerger = &pReader->status.merger;
122,558✔
4290
  int32_t     code = TSDB_CODE_SUCCESS;
122,558✔
4291

4292
  STSchema* pSchema = NULL;
122,558✔
4293
  if (pRow->type == TSDBROW_ROW_FMT) {
122,558!
4294
    pSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(pRow), pReader, pBlockScanInfo->uid);
122,558!
4295
    if (pSchema == NULL) {
122,557!
4296
      return terrno;
×
4297
    }
4298
  }
4299

4300
  STSchema* piSchema = NULL;
122,557✔
4301
  if (piRow->type == TSDBROW_ROW_FMT) {
122,557✔
4302
    piSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(piRow), pReader, pBlockScanInfo->uid);
122,555!
4303
    if (piSchema == NULL) {
122,556!
4304
      return terrno;
×
4305
    }
4306
  }
4307

4308
  if (ASCENDING_TRAVERSE(pReader->info.order)) {  // ascending order imem --> mem
122,558✔
4309
    code = tsdbRowMergerAdd(pMerger, piRow, piSchema);
122,556✔
4310
    if (code != TSDB_CODE_SUCCESS) {
122,531!
4311
      return code;
×
4312
    }
4313

4314
    code = doMergeRowsInBuf(&pBlockScanInfo->iiter, pBlockScanInfo->uid, piRowKey, pBlockScanInfo->delSkyline, pReader);
122,531✔
4315
    if (code != TSDB_CODE_SUCCESS) {
122,555!
4316
      return code;
×
4317
    }
4318

4319
    code = tsdbRowMergerAdd(pMerger, pRow, pSchema);
122,555✔
4320
    if (code != TSDB_CODE_SUCCESS) {
122,565!
4321
      return code;
×
4322
    }
4323

4324
    code = doMergeRowsInBuf(&pBlockScanInfo->iter, pBlockScanInfo->uid, pRowKey, pBlockScanInfo->delSkyline, pReader);
122,565✔
4325
    if (code != TSDB_CODE_SUCCESS) {
122,547!
4326
      return code;
×
4327
    }
4328
  } else {
4329
    code = tsdbRowMergerAdd(pMerger, pRow, pSchema);
2✔
UNCOV
4330
    if (code != TSDB_CODE_SUCCESS) {
×
4331
      return code;
×
4332
    }
4333

UNCOV
4334
    code = doMergeRowsInBuf(&pBlockScanInfo->iter, pBlockScanInfo->uid, pRowKey, pBlockScanInfo->delSkyline, pReader);
×
UNCOV
4335
    if (code != TSDB_CODE_SUCCESS) {
×
4336
      return code;
×
4337
    }
4338

UNCOV
4339
    code = tsdbRowMergerAdd(pMerger, piRow, piSchema);
×
UNCOV
4340
    if (code != TSDB_CODE_SUCCESS) {
×
4341
      return code;
×
4342
    }
4343

UNCOV
4344
    code = doMergeRowsInBuf(&pBlockScanInfo->iiter, pBlockScanInfo->uid, piRowKey, pBlockScanInfo->delSkyline, pReader);
×
UNCOV
4345
    if (code != TSDB_CODE_SUCCESS) {
×
4346
      return code;
×
4347
    }
4348
  }
4349

4350
  tRowKeyAssign(&pBlockScanInfo->lastProcKey, pRowKey);
122,547✔
4351

4352
  code = tsdbRowMergerGetRow(pMerger, pTSRow);
122,545✔
4353
  tsdbRowMergerClear(pMerger);
122,548✔
4354
  return code;
122,548✔
4355
}
4356

4357
static int32_t tsdbGetNextRowInMem(STableBlockScanInfo* pBlockScanInfo, STsdbReader* pReader, TSDBROW* pResRow,
1,048,822,553✔
4358
                                   int64_t endKey, bool* freeTSRow) {
4359
  TSDBROW* pRow = NULL;
1,048,822,553✔
4360
  TSDBROW* piRow = NULL;
1,048,822,553✔
4361

4362
  getValidMemRow(&pBlockScanInfo->iter, pBlockScanInfo->delSkyline, pReader, &pRow);
1,048,822,553✔
4363
  getValidMemRow(&pBlockScanInfo->iiter, pBlockScanInfo->delSkyline, pReader, &piRow);
1,052,774,747✔
4364

4365
  SArray*    pDelList = pBlockScanInfo->delSkyline;
1,052,778,151✔
4366
  uint64_t   uid = pBlockScanInfo->uid;
1,052,778,151✔
4367
  SIterInfo* piter = &pBlockScanInfo->iter;
1,052,778,151✔
4368
  SIterInfo* piiter = &pBlockScanInfo->iiter;
1,052,778,151✔
4369
  SRowKey    rowKey = {0}, irowKey = {0};
1,052,778,151✔
4370

4371
  // todo refactor
4372
  bool asc = ASCENDING_TRAVERSE(pReader->info.order);
1,052,778,151✔
4373
  if (piter->hasVal) {
1,052,778,151!
4374
    tRowGetKeyEx(pRow, &rowKey);
1,055,537,911!
4375
    if ((rowKey.ts >= endKey && asc) || (rowKey.ts <= endKey && !asc)) {
1,063,325,455✔
4376
      pRow = NULL;
1,311,812✔
4377
    }
4378
  }
4379

4380
  if (piiter->hasVal) {
1,060,565,695✔
4381
    tRowGetKeyEx(piRow, &irowKey);
39,461,157!
4382
    if ((irowKey.ts >= endKey && asc) || (irowKey.ts <= endKey && !asc)) {
64,993,656!
4383
      piRow = NULL;
2✔
4384
    }
4385
  }
4386

4387
  if (pRow != NULL && piRow != NULL) {
1,086,098,194✔
4388
    int32_t code = TSDB_CODE_SUCCESS;
13,530,502✔
4389
    if (rowKey.numOfPKs == 0) {
13,530,502✔
4390
      if ((rowKey.ts > irowKey.ts && asc) || (rowKey.ts < irowKey.ts && (!asc))) {  // ik.ts < k.ts
13,500,883✔
4391
        code = doMergeMemTableMultiRows(piRow, &irowKey, uid, piiter, pDelList, pResRow, pReader, freeTSRow);
13,376,512✔
4392
      } else if ((rowKey.ts < irowKey.ts && asc) || (rowKey.ts > irowKey.ts && (!asc))) {
124,371!
4393
        code = doMergeMemTableMultiRows(pRow, &rowKey, uid, piter, pDelList, pResRow, pReader, freeTSRow);
5,939✔
4394
      } else {  // ik.ts == k.ts
4395
        *freeTSRow = true;
118,432✔
4396
        pResRow->type = TSDBROW_ROW_FMT;
118,432✔
4397
        code = doMergeMemIMemRows(pRow, &rowKey, piRow, &irowKey, pBlockScanInfo, pReader, &pResRow->pTSRow);
118,432✔
4398
        if (code != TSDB_CODE_SUCCESS) {
122,547!
4399
          return code;
×
4400
        }
4401
      }
4402
    } else {
4403
      int32_t ret = pkCompEx(&rowKey, &irowKey);
23,473✔
4404
      if (ret != 0) {
23,473✔
4405
        if ((ret > 0 && asc) || (ret < 0 && (!asc))) {  // ik.ts < k.ts
23,472✔
4406
          code = doMergeMemTableMultiRows(piRow, &irowKey, uid, piiter, pDelList, pResRow, pReader, freeTSRow);
14,781✔
4407
        } else if ((ret < 0 && asc) || (ret > 0 && (!asc))) {
8,691!
4408
          code = doMergeMemTableMultiRows(pRow, &rowKey, uid, piter, pDelList, pResRow, pReader, freeTSRow);
8,692✔
4409
        }
4410
      } else {  // ik.ts == k.ts
4411
        *freeTSRow = true;
1✔
4412
        pResRow->type = TSDBROW_ROW_FMT;
1✔
4413
        code = doMergeMemIMemRows(pRow, &rowKey, piRow, &irowKey, pBlockScanInfo, pReader, &pResRow->pTSRow);
1✔
4414
        if (code != TSDB_CODE_SUCCESS) {
×
4415
          return code;
×
4416
        }
4417
      }
4418
    }
4419

4420
    return code;
13,462,176✔
4421
  }
4422

4423
  if (piter->hasVal && pRow != NULL) {
1,072,567,692!
4424
    return doMergeMemTableMultiRows(pRow, &rowKey, uid, piter, pDelList, pResRow, pReader, freeTSRow);
1,044,562,079✔
4425
  }
4426

4427
  if (piiter->hasVal && piRow != NULL) {
28,005,613!
4428
    return doMergeMemTableMultiRows(piRow, &irowKey, uid, piiter, pDelList, pResRow, pReader, freeTSRow);
26,190,880✔
4429
  }
4430

4431
  return TSDB_CODE_SUCCESS;
1,814,733✔
4432
}
4433

4434
int32_t doAppendRowFromTSRow(SSDataBlock* pBlock, STsdbReader* pReader, SRow* pTSRow, STableBlockScanInfo* pScanInfo) {
1,517,664,487✔
4435
  int32_t outputRowIndex = pBlock->info.rows;
1,517,664,487✔
4436
  int64_t uid = pScanInfo->uid;
1,517,664,487✔
4437
  int32_t code = TSDB_CODE_SUCCESS;
1,517,664,487✔
4438

4439
  SBlockLoadSuppInfo* pSupInfo = &pReader->suppInfo;
1,517,664,487✔
4440
  STSchema*           pSchema = doGetSchemaForTSRow(pTSRow->sver, pReader, uid);
1,517,664,487!
4441
  if (pSchema == NULL) {
1,518,451,355!
4442
    return terrno;
×
4443
  }
4444

4445
  SColVal colVal = {0};
1,518,451,355✔
4446
  int32_t i = 0, j = 0;
1,518,451,355✔
4447

4448
  if (pSupInfo->colId[i] == PRIMARYKEY_TIMESTAMP_COL_ID) {
1,518,451,355!
4449
    SColumnInfoData* pColData = taosArrayGet(pBlock->pDataBlock, pSupInfo->slotId[i]);
1,522,414,584✔
4450
    if (pColData == NULL) {
1,509,501,357!
4451
      return TSDB_CODE_INVALID_PARA;
×
4452
    }
4453

4454
    ((int64_t*)pColData->pData)[outputRowIndex] = pTSRow->ts;
1,509,501,357✔
4455
    i += 1;
1,509,501,357✔
4456
  }
4457

4458
  while (i < pSupInfo->numOfCols && j < pSchema->numOfCols) {
2,147,483,647!
4459
    col_id_t colId = pSupInfo->colId[i];
2,147,483,647✔
4460

4461
    if (colId == pSchema->columns[j].colId) {
2,147,483,647✔
4462
      SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, pSupInfo->slotId[i]);
2,147,483,647✔
4463
      if (pColInfoData == NULL) {
2,147,483,647!
4464
        return TSDB_CODE_INVALID_PARA;
×
4465
      }
4466

4467
      code = tRowGet(pTSRow, pSchema, j, &colVal);
2,147,483,647✔
4468
      if (code) {
2,147,483,647!
4469
        return code;
×
4470
      }
4471

4472
      code = doCopyColVal(pColInfoData, outputRowIndex, i, &colVal, pSupInfo);
2,147,483,647✔
4473
      if (code) {
2,147,483,647✔
4474
        return code;
4✔
4475
      }
4476
      i += 1;
2,147,483,647✔
4477
      j += 1;
2,147,483,647✔
4478
    } else if (colId < pSchema->columns[j].colId) {
2,147,483,647!
4479
      SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, pSupInfo->slotId[i]);
×
4480
      if (pColInfoData == NULL) {
×
4481
        return TSDB_CODE_INVALID_PARA;
×
4482
      }
4483

4484
      colDataSetNULL(pColInfoData, outputRowIndex);
×
4485
      i += 1;
×
4486
    } else if (colId > pSchema->columns[j].colId) {
2,147,483,647!
4487
      j += 1;
2,147,483,647✔
4488
    }
4489
  }
4490

4491
  // set null value since current column does not exist in the "pSchema"
4492
  while (i < pSupInfo->numOfCols) {
1,539,448,609✔
4493
    SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, pSupInfo->slotId[i]);
41,121✔
4494
    if (pColInfoData == NULL) {
41,121!
4495
      return TSDB_CODE_INVALID_PARA;
×
4496
    }
4497

4498
    colDataSetNULL(pColInfoData, outputRowIndex);
41,121✔
4499
    i += 1;
41,121✔
4500
  }
4501

4502
  pBlock->info.dataLoad = 1;
1,539,407,488✔
4503
  pBlock->info.rows += 1;
1,539,407,488✔
4504
  return TSDB_CODE_SUCCESS;
1,539,407,488✔
4505
}
4506

4507
int32_t doAppendRowFromFileBlock(SSDataBlock* pResBlock, STsdbReader* pReader, SBlockData* pBlockData,
373,225,021✔
4508
                                 int32_t rowIndex) {
4509
  int32_t i = 0, j = 0;
373,225,021✔
4510
  int32_t outputRowIndex = pResBlock->info.rows;
373,225,021✔
4511
  int32_t code = TSDB_CODE_SUCCESS;
373,225,021✔
4512

4513
  SBlockLoadSuppInfo* pSupInfo = &pReader->suppInfo;
373,225,021✔
4514
  ((int64_t*)pReader->status.pPrimaryTsCol->pData)[outputRowIndex] = pBlockData->aTSKEY[rowIndex];
373,225,021✔
4515
  i += 1;
373,225,021✔
4516

4517
  SColVal cv = {0};
373,225,021✔
4518
  int32_t numOfInputCols = pBlockData->nColData;
373,225,021✔
4519
  int32_t numOfOutputCols = pSupInfo->numOfCols;
373,225,021✔
4520

4521
  while (i < numOfOutputCols && j < numOfInputCols) {
825,272,522✔
4522
    SColData* pData = tBlockDataGetColDataByIdx(pBlockData, j);
434,830,601✔
4523
    if (pData->cid < pSupInfo->colId[i]) {
434,830,601✔
4524
      j += 1;
150✔
4525
      continue;
150✔
4526
    }
4527

4528
    SColumnInfoData* pCol = TARRAY_GET_ELEM(pResBlock->pDataBlock, pSupInfo->slotId[i]);
434,830,451✔
4529
    if (pData->cid == pSupInfo->colId[i]) {
434,830,451!
4530
      tColDataGetValue(pData, rowIndex, &cv);
435,213,068✔
4531
      code = doCopyColVal(pCol, outputRowIndex, i, &cv, pSupInfo);
457,708,291✔
4532
      if (code) {
452,429,968!
4533
        return code;
×
4534
      }
4535
      j += 1;
452,429,968✔
4536
    } else if (pData->cid > pCol->info.colId) {
×
4537
      // the specified column does not exist in file block, fill with null data
4538
      colDataSetNULL(pCol, outputRowIndex);
×
4539
    }
4540

4541
    i += 1;
452,047,351✔
4542
  }
4543

4544
  while (i < numOfOutputCols) {
390,441,949✔
4545
    SColumnInfoData* pCol = taosArrayGet(pResBlock->pDataBlock, pSupInfo->slotId[i]);
28✔
4546
    if (pCol == NULL) {
28!
4547
      return TSDB_CODE_INVALID_PARA;
×
4548
    }
4549

4550
    colDataSetNULL(pCol, outputRowIndex);
28!
4551
    i += 1;
28✔
4552
  }
4553

4554
  pResBlock->info.dataLoad = 1;
390,441,921✔
4555
  pResBlock->info.rows += 1;
390,441,921✔
4556
  return TSDB_CODE_SUCCESS;
390,441,921✔
4557
}
4558

4559
int32_t buildDataBlockFromBufImpl(STableBlockScanInfo* pBlockScanInfo, int64_t endKey, int32_t capacity,
5,414,565✔
4560
                                  STsdbReader* pReader) {
4561
  SSDataBlock* pBlock = pReader->resBlockInfo.pResBlock;
5,414,565✔
4562
  int32_t      code = TSDB_CODE_SUCCESS;
5,414,565✔
4563

4564
  do {
1,044,392,454✔
4565
    TSDBROW row = {.type = -1};
1,049,807,019✔
4566
    bool    freeTSRow = false;
1,049,807,019✔
4567
    code = tsdbGetNextRowInMem(pBlockScanInfo, pReader, &row, endKey, &freeTSRow);
1,049,807,019✔
4568
    if (code != TSDB_CODE_SUCCESS) {
1,068,892,764!
4569
      return code;
4✔
4570
    }
4571

4572
    if (row.type == -1) {
1,068,892,764✔
4573
      break;
1,814,904✔
4574
    }
4575

4576
    if (row.type == TSDBROW_ROW_FMT) {
1,067,077,860✔
4577
      code = doAppendRowFromTSRow(pBlock, pReader, row.pTSRow, pBlockScanInfo);
1,063,179,263✔
4578
      if (code == TSDB_CODE_SUCCESS) {
1,047,336,498!
4579
        pBlockScanInfo->lastProcKey.ts = row.pTSRow->ts;
1,048,905,283✔
4580
        pBlockScanInfo->lastProcKey.numOfPKs = row.pTSRow->numOfPKs;
1,048,905,283✔
4581
        if (row.pTSRow->numOfPKs > 0) {
1,048,905,283✔
4582
          tRowGetPrimaryKeyDeepCopy(row.pTSRow, &pBlockScanInfo->lastProcKey);
23,313,593✔
4583
        }
4584
      }
4585

4586
      if (freeTSRow) {
1,047,356,423✔
4587
        taosMemoryFree(row.pTSRow);
6,793,724✔
4588
      }
4589

4590
      if (code) {
1,047,409,939✔
4591
        return code;
4✔
4592
      }
4593
    } else {
4594
      code = doAppendRowFromFileBlock(pBlock, pReader, row.pBlockData, row.iRow);
3,898,597✔
4595
      if (code) {
354!
4596
        return code;
×
4597
      }
4598

4599
      tColRowGetKeyDeepCopy(row.pBlockData, row.iRow, pReader->suppInfo.pkSrcSlot, &pBlockScanInfo->lastProcKey);
354✔
4600
    }
4601

4602
    // no data in buffer, return immediately
4603
    if (!(pBlockScanInfo->iter.hasVal || pBlockScanInfo->iiter.hasVal)) {
1,047,992,988✔
4604
      break;
3,487,016✔
4605
    }
4606

4607
    if (pBlock->info.rows >= capacity) {
1,044,505,972✔
4608
      break;
113,518✔
4609
    }
4610
  } while (1);
4611

4612
  return code;
5,415,438✔
4613
}
4614

4615
// TODO refactor: with createDataBlockScanInfo
4616
int32_t tsdbSetTableList2(STsdbReader* pReader, const void* pTableList, int32_t num) {
20,106✔
4617
  int32_t code = TSDB_CODE_SUCCESS;
20,106✔
4618
  int32_t size = tSimpleHashGetSize(pReader->status.pTableMap);
20,106✔
4619

4620
  STableBlockScanInfo** p = NULL;
20,105✔
4621
  int32_t               iter = 0;
20,105✔
4622

4623
  code = tsdbAcquireReader(pReader);
20,105✔
4624
  if (code) {
20,106!
4625
    return code;
×
4626
  }
4627

4628
  while ((p = tSimpleHashIterate(pReader->status.pTableMap, p, &iter)) != NULL) {
40,294✔
4629
    clearBlockScanInfo(*p);
20,189✔
4630
  }
4631

4632
  tSimpleHashClear(pReader->status.pTableMap);
20,102✔
4633

4634
  if (size < num) {
20,105✔
4635
    code = ensureBlockScanInfoBuf(&pReader->blockInfoBuf, num);
7✔
4636
    if (code) {
6!
4637
      (void) tsdbReleaseReader(pReader);
×
4638
      return code;
×
4639
    }
4640

4641
    char* p1 = taosMemoryRealloc(pReader->status.uidList.tableUidList, sizeof(uint64_t) * num);
6✔
4642
    if (p1 == NULL) {
6!
4643
      (void) tsdbReleaseReader(pReader);
×
4644
      return terrno;
×
4645
    }
4646

4647
    pReader->status.uidList.tableUidList = (uint64_t*)p1;
6✔
4648
  }
4649

4650
  STableUidList* pUidList = &pReader->status.uidList;
20,104✔
4651
  pUidList->currentIndex = 0;
20,104✔
4652

4653
  STableKeyInfo* pList = (STableKeyInfo*)pTableList;
20,104✔
4654
  for (int32_t i = 0; i < num; ++i) {
40,214✔
4655
    pUidList->tableUidList[i] = pList[i].uid;
20,112✔
4656

4657
    STableBlockScanInfo* pInfo = NULL;
20,112✔
4658
    code = getPosInBlockInfoBuf(&pReader->blockInfoBuf, i, &pInfo);
20,112✔
4659
    if (code != TSDB_CODE_SUCCESS) {
20,111!
4660
      (void) tsdbReleaseReader(pReader);
×
4661
      return code;
×
4662
    }
4663

4664
    code = initTableBlockScanInfo(pInfo, pList[i].uid, pReader->status.pTableMap, pReader);
20,111✔
4665
    if (code != TSDB_CODE_SUCCESS) {
20,110!
4666
      (void) tsdbReleaseReader(pReader);
×
4667
      return code;
×
4668
    }
4669
  }
4670

4671
  (void) tsdbReleaseReader(pReader);
20,102✔
4672
  return code;
20,105✔
4673
}
4674

4675
uint64_t tsdbGetReaderMaxVersion2(STsdbReader* pReader) { return pReader->info.verRange.maxVer; }
×
4676

4677
static int32_t doOpenReaderImpl(STsdbReader* pReader) {
4,928,022✔
4678
  SReaderStatus*  pStatus = &pReader->status;
4,928,022✔
4679
  SDataBlockIter* pBlockIter = &pStatus->blockIter;
4,928,022✔
4680
  int32_t         code = TSDB_CODE_SUCCESS;
4,928,022✔
4681

4682
  if (pReader->bFilesetDelimited) {
4,928,022✔
4683
    getMemTableTimeRange(pReader, &pReader->status.memTableMaxKey, &pReader->status.memTableMinKey);
1,996,136✔
4684
    pReader->status.bProcMemFirstFileset = true;
1,996,818✔
4685
  }
4686

4687
  code = initFilesetIterator(&pStatus->fileIter, pReader->pReadSnap->pfSetArray, pReader);
4,928,704✔
4688
  if (code != TSDB_CODE_SUCCESS) {
4,930,215!
4689
    return code;
×
4690
  }
4691

4692
  code = resetDataBlockIterator(&pStatus->blockIter, pReader->info.order, shouldFreePkBuf(&pReader->suppInfo),
4,928,801✔
4693
                                pReader->idStr);
4,930,215✔
4694
  if (code != TSDB_CODE_SUCCESS) {
4,928,822!
4695
    return code;
×
4696
  }
4697

4698
  if (pStatus->fileIter.numOfFiles == 0) {
4,928,822✔
4699
    pStatus->loadFromFile = false;
2,555,086✔
4700
  } else {
4701
    code = initForFirstBlockInFile(pReader, pBlockIter);
2,373,736✔
4702
  }
4703

4704
  if (!pStatus->loadFromFile) {
4,928,615✔
4705
    code = resetTableListIndex(pStatus, pReader->idStr);
3,146,895✔
4706
  }
4707

4708
  return code;
4,930,049✔
4709
}
4710

4711
static void freeSchemaFunc(void* param) {
126,362✔
4712
  void** p = (void**)param;
126,362✔
4713
  taosMemoryFreeClear(*p);
126,362!
4714
}
126,362✔
4715

4716
static void clearSharedPtr(STsdbReader* p) {
3,612✔
4717
  if (p) {
3,612!
4718
    p->status.pTableMap = NULL;
3,612✔
4719
    p->status.uidList.tableUidList = NULL;
3,612✔
4720
    p->info.pSchema = NULL;
3,612✔
4721
    p->pReadSnap = NULL;
3,612✔
4722
    p->pSchemaMap = NULL;
3,612✔
4723
  }
4724
}
3,612✔
4725

4726
static int32_t setSharedPtr(STsdbReader* pDst, const STsdbReader* pSrc) {
3,612✔
4727
  pDst->status.pTableMap = pSrc->status.pTableMap;
3,612✔
4728
  pDst->status.uidList = pSrc->status.uidList;
3,612✔
4729
  pDst->info.pSchema = pSrc->info.pSchema;
3,612✔
4730
  pDst->pSchemaMap = pSrc->pSchemaMap;
3,612✔
4731
  pDst->pReadSnap = pSrc->pReadSnap;
3,612✔
4732
  pDst->pReadSnap->pfSetArray = pSrc->pReadSnap->pfSetArray;
3,612✔
4733

4734
  if (pDst->info.pSchema) {
3,612!
4735
    return tsdbRowMergerInit(&pDst->status.merger, pDst->info.pSchema);
3,612✔
4736
  }
4737

4738
  return TSDB_CODE_SUCCESS;
×
4739
}
4740

4741
// ====================================== EXPOSED APIs ======================================
4742
int32_t tsdbReaderOpen2(void* pVnode, SQueryTableDataCond* pCond, void* pTableList, int32_t numOfTables,
5,064,978✔
4743
                        SSDataBlock* pResBlock, void** ppReader, const char* idstr, SHashObj** pIgnoreTables) {
4744
  STimeWindow window = pCond->twindows;
5,064,978✔
4745
  SVnodeCfg*  pConf = &(((SVnode*)pVnode)->config);
5,064,978✔
4746
  int32_t     code = 0;
5,064,978✔
4747
  int32_t     lino = 0;
5,064,978✔
4748

4749
  int32_t capacity = pConf->tsdbCfg.maxRows;
5,064,978✔
4750
  if (pResBlock != NULL) {
5,064,978!
4751
    code = blockDataEnsureCapacity(pResBlock, capacity);
5,077,774✔
4752
    TSDB_CHECK_CODE(code, lino, _err);
5,078,683!
4753
  }
4754

4755
  code = tsdbReaderCreate(pVnode, pCond, ppReader, capacity, pResBlock, idstr);
5,065,887✔
4756
  TSDB_CHECK_CODE(code, lino, _err);
5,071,303!
4757

4758
  // check for query time window
4759
  STsdbReader* pReader = *ppReader;
5,071,303✔
4760
  if (isEmptyQueryTimeWindow(&pReader->info.window) && pCond->type == TIMEWINDOW_RANGE_CONTAINED) {
5,071,303!
4761
    tsdbDebug("%p query window not overlaps with the data set, no result returned, %s", pReader, pReader->idStr);
47,811✔
4762
    return TSDB_CODE_SUCCESS;
47,814✔
4763
  }
4764

4765
  if (pCond->type == TIMEWINDOW_RANGE_EXTERNAL) {
5,014,678✔
4766
    // update the SQueryTableDataCond to create inner reader
4767
    int32_t order = pCond->order;
1,806✔
4768
    if (order == TSDB_ORDER_ASC) {
1,806!
4769
      pCond->twindows.ekey = window.skey - 1;
1,806✔
4770
      pCond->twindows.skey = INT64_MIN;
1,806✔
4771
      pCond->order = TSDB_ORDER_DESC;
1,806✔
4772
    } else {
4773
      pCond->twindows.skey = window.ekey + 1;
×
4774
      pCond->twindows.ekey = INT64_MAX;
×
4775
      pCond->order = TSDB_ORDER_ASC;
×
4776
    }
4777

4778
    // here we only need one more row, so the capacity is set to be ONE.
4779
    code = tsdbReaderCreate(pVnode, pCond, (void**)&((STsdbReader*)pReader)->innerReader[0], 1, pResBlock, idstr);
1,806✔
4780
    TSDB_CHECK_CODE(code, lino, _err);
1,806!
4781

4782
    if (order == TSDB_ORDER_ASC) {
1,806!
4783
      pCond->twindows.skey = window.ekey + 1;
1,806✔
4784
      pCond->twindows.ekey = INT64_MAX;
1,806✔
4785
    } else {
4786
      pCond->twindows.skey = INT64_MIN;
×
4787
      pCond->twindows.ekey = window.ekey - 1;
×
4788
    }
4789
    pCond->order = order;
1,806✔
4790

4791
    code = tsdbReaderCreate(pVnode, pCond, (void**)&((STsdbReader*)pReader)->innerReader[1], 1, pResBlock, idstr);
1,806✔
4792
    TSDB_CHECK_CODE(code, lino, _err);
1,806!
4793
  }
4794

4795
  // NOTE: the endVersion in pCond is the data version not schema version, so pCond->endVersion is not correct here.
4796
  //  no valid error code set in metaGetTbTSchema, so let's set the error code here.
4797
  //  we should proceed in case of tmq processing.
4798
  if (pCond->suid != 0) {
5,014,678✔
4799
    code = metaGetTbTSchemaMaybeNull(pReader->pTsdb->pVnode->pMeta, pReader->info.suid, -1, 1, &pReader->info.pSchema);
4,705,644✔
4800
    TSDB_CHECK_CODE(code, lino, _err);
4,721,041!
4801
    if (pReader->info.pSchema == NULL) {
4,721,041!
4802
      tsdbWarn("failed to get table schema, suid:%" PRIu64 ", ver:-1, %s", pReader->info.suid, pReader->idStr);
×
4803
    }
4804
  } else if (numOfTables > 0) {
309,034✔
4805
    STableKeyInfo* pKey = pTableList;
308,298✔
4806
    code = metaGetTbTSchemaMaybeNull(pReader->pTsdb->pVnode->pMeta, pKey->uid, -1, 1, &pReader->info.pSchema);
308,298✔
4807
    TSDB_CHECK_CODE(code, lino, _err);
308,402!
4808
    if (pReader->info.pSchema == NULL) {
308,402!
UNCOV
4809
      tsdbWarn("failed to get table schema, uid:%" PRIu64 ", ver:-1, %s", pKey->uid, pReader->idStr);
×
4810
    }
4811
  }
4812

4813
  if (pReader->info.pSchema != NULL) {
5,030,179✔
4814
    code = tsdbRowMergerInit(&pReader->status.merger, pReader->info.pSchema);
5,021,138✔
4815
    TSDB_CHECK_CODE(code, lino, _err);
5,029,252!
4816
  }
4817

4818
  pReader->pSchemaMap = tSimpleHashInit(8, taosFastHash);
5,038,293✔
4819
  if (pReader->pSchemaMap == NULL) {
5,029,389!
4820
    tsdbError("failed init schema hash for reader %s", pReader->idStr);
×
4821
    TSDB_CHECK_NULL(pReader->pSchemaMap, code, lino, _err, terrno);
×
4822
  }
4823

4824
  tSimpleHashSetFreeFp(pReader->pSchemaMap, freeSchemaFunc);
5,029,389✔
4825
  if (pReader->info.pSchema != NULL) {
5,027,189!
4826
    code = updateBlockSMAInfo(pReader->info.pSchema, &pReader->suppInfo);
5,027,602✔
4827
    TSDB_CHECK_CODE(code, lino, _err);
5,032,868✔
4828
  }
4829

4830
  STsdbReader* p = (pReader->innerReader[0] != NULL) ? pReader->innerReader[0] : pReader;
5,032,439✔
4831

4832
  code = createDataBlockScanInfo(p, &pReader->blockInfoBuf, pTableList, &pReader->status.uidList, numOfTables, &pReader->status.pTableMap);
5,032,439✔
4833
  TSDB_CHECK_CODE(code, lino, _err);
5,034,520!
4834

4835
  pReader->status.pLDataIterArray = taosArrayInit(4, POINTER_BYTES);
5,034,520✔
4836
  TSDB_CHECK_NULL(pReader->status.pLDataIterArray, code, lino, _err, terrno);
5,034,464✔
4837

4838
  pReader->flag = READER_STATUS_SUSPEND;
5,033,601✔
4839
  pReader->info.execMode = pCond->notLoadData ? READER_EXEC_ROWS : READER_EXEC_DATA;
5,033,601✔
4840

4841
  pReader->pIgnoreTables = pIgnoreTables;
5,033,601✔
4842
  tsdbDebug("%p total numOfTable:%d, window:%" PRId64 " - %" PRId64 ", verRange:%" PRId64 " - %" PRId64
5,033,601✔
4843
            " in this query %s",
4844
            pReader, numOfTables, pReader->info.window.skey, pReader->info.window.ekey, pReader->info.verRange.minVer,
4845
            pReader->info.verRange.maxVer, pReader->idStr);
4846

4847
  return code;
5,034,068✔
4848

4849
_err:
16✔
4850
  tsdbError("failed to create data reader, error at:%d code:%s %s", lino, tstrerror(code), idstr);
16!
4851
  tsdbReaderClose2(*ppReader);
16✔
4852
  *ppReader = NULL;  // reset the pointer value.
16✔
4853
  return code;
16✔
4854
}
4855

4856
void tsdbReaderClose2(STsdbReader* pReader) {
9,213,333✔
4857
  if (pReader == NULL) {
9,213,333✔
4858
    return;
4,127,207✔
4859
  }
4860

4861
  int32_t code = tsdbAcquireReader(pReader);
5,086,126✔
4862
  if (code) {
5,087,009!
4863
    return;
×
4864
  }
4865

4866
  {
4867
    if (pReader->innerReader[0] != NULL || pReader->innerReader[1] != NULL) {
5,087,009!
4868
      STsdbReader* p = pReader->innerReader[0];
1,779✔
4869
      clearSharedPtr(p);
1,779✔
4870

4871
      p = pReader->innerReader[1];
1,806✔
4872
      clearSharedPtr(p);
1,806✔
4873

4874
      tsdbReaderClose2(pReader->innerReader[0]);
1,806✔
4875
      tsdbReaderClose2(pReader->innerReader[1]);
1,806✔
4876
    }
4877
  }
4878

4879
  SBlockLoadSuppInfo* pSupInfo = &pReader->suppInfo;
5,086,519✔
4880
  TARRAY2_DESTROY(&pSupInfo->colAggArray, NULL);
5,086,519✔
4881

4882
  if (pSupInfo->buildBuf) {
5,086,519!
4883
    for (int32_t i = 0; i < pSupInfo->numOfCols; ++i) {
30,670,968✔
4884
      if (pSupInfo->buildBuf[i] != NULL) {
25,584,220✔
4885
        taosMemoryFreeClear(pSupInfo->buildBuf[i]);
3,784,573!
4886
      }
4887
    }
4888
  }
4889

4890
  if (pReader->resBlockInfo.freeBlock) {
5,086,490✔
4891
    blockDataDestroy(pReader->resBlockInfo.pResBlock);
2,527✔
4892
    pReader->resBlockInfo.pResBlock = NULL;
2,525✔
4893
  }
4894

4895
  taosMemoryFree(pSupInfo->colId);
5,086,488✔
4896
  tBlockDataDestroy(&pReader->status.fileBlockData);
5,087,025✔
4897
  cleanupDataBlockIterator(&pReader->status.blockIter, shouldFreePkBuf(&pReader->suppInfo));
5,086,367✔
4898

4899
  size_t numOfTables = tSimpleHashGetSize(pReader->status.pTableMap);
5,086,946✔
4900
  if (pReader->status.pTableMap != NULL) {
5,086,726✔
4901
    destroyAllBlockScanInfo(pReader->status.pTableMap);
5,035,127✔
4902
    pReader->status.pTableMap = NULL;
5,035,661✔
4903
  }
4904
  clearBlockScanInfoBuf(&pReader->blockInfoBuf);
5,087,260✔
4905

4906
  if (pReader->pFileReader != NULL) {
5,087,080✔
4907
    tsdbDataFileReaderClose(&pReader->pFileReader);
21,721✔
4908
  }
4909

4910
  SReadCostSummary* pCost = &pReader->cost;
5,087,080✔
4911
  SFilesetIter*     pFilesetIter = &pReader->status.fileIter;
5,087,080✔
4912
  if (pFilesetIter->pSttBlockReader != NULL) {
5,087,080✔
4913
    SSttBlockReader* pSttBlockReader = pFilesetIter->pSttBlockReader;
4,932,094✔
4914
    tMergeTreeClose(&pSttBlockReader->mergeTree);
4,932,094✔
4915

4916
    clearRowKey(&pSttBlockReader->currentKey);
4,931,544✔
4917
    taosMemoryFree(pSttBlockReader);
4,931,677✔
4918
  }
4919

4920
  destroySttBlockReader(pReader->status.pLDataIterArray, &pCost->sttCost);
5,087,106✔
4921
  taosMemoryFreeClear(pReader->status.uidList.tableUidList);
5,087,136✔
4922

4923
  tsdbTrace("tsdb/reader-close: %p, untake snapshot", pReader);
5,087,210✔
4924
  void* p = pReader->pReadSnap;
5,087,210✔
4925
  if ((p == atomic_val_compare_exchange_ptr((void**)&pReader->pReadSnap, p, NULL)) && (p != NULL)) {
5,087,210!
4926
    tsdbUntakeReadSnap2(pReader, p, true);
4,928,495✔
4927
    pReader->pReadSnap = NULL;
4,928,552✔
4928
  }
4929

4930
  (void) tsem_destroy(&pReader->resumeAfterSuspend);
5,087,284✔
4931
  (void) tsdbReleaseReader(pReader);
5,086,587✔
4932
  (void) tsdbUninitReaderLock(pReader);
5,087,037✔
4933

4934
  tsdbDebug(
5,086,401✔
4935
      "%p :io-cost summary: head-file:%" PRIu64 ", head-file time:%.2f ms, SMA:%" PRId64
4936
      " SMA-time:%.2f ms, fileBlocks:%" PRId64
4937
      ", fileBlocks-load-time:%.2f ms, "
4938
      "build in-memory-block-time:%.2f ms, sttBlocks:%" PRId64 ", sttBlocks-time:%.2f ms, sttStatisBlock:%" PRId64
4939
      ", stt-statis-Block-time:%.2f ms, composed-blocks:%" PRId64
4940
      ", composed-blocks-time:%.2fms, STableBlockScanInfo size:%.2f Kb, createTime:%.2f ms,createSkylineIterTime:%.2f "
4941
      "ms, initSttBlockReader:%.2fms, %s",
4942
      pReader, pCost->headFileLoad, pCost->headFileLoadTime, pCost->smaDataLoad, pCost->smaLoadTime, pCost->numOfBlocks,
4943
      pCost->blockLoadTime, pCost->buildmemBlock, pCost->sttCost.loadBlocks, pCost->sttCost.blockElapsedTime,
4944
      pCost->sttCost.loadStatisBlocks, pCost->sttCost.statisElapsedTime, pCost->composedBlocks,
4945
      pCost->buildComposedBlockTime, numOfTables * sizeof(STableBlockScanInfo) / 1000.0, pCost->createScanInfoList,
4946
      pCost->createSkylineIterTime, pCost->initSttBlockReader, pReader->idStr);
4947

4948
  taosMemoryFree(pReader->idStr);
5,086,403✔
4949

4950
  tsdbRowMergerCleanup(&pReader->status.merger);
5,087,177✔
4951
  taosMemoryFree(pReader->info.pSchema);
5,086,794✔
4952

4953
  tSimpleHashCleanup(pReader->pSchemaMap);
5,087,204✔
4954
  taosMemoryFreeClear(pReader);
5,087,159!
4955
}
4956

4957
static int32_t doSuspendCurrentReader(STsdbReader* pCurrentReader) {
2✔
4958
  SReaderStatus* pStatus = &pCurrentReader->status;
2✔
4959

4960
  if (pStatus->loadFromFile) {
2✔
4961
    tsdbDataFileReaderClose(&pCurrentReader->pFileReader);
1✔
4962

4963
    SReadCostSummary* pCost = &pCurrentReader->cost;
1✔
4964
    destroySttBlockReader(pStatus->pLDataIterArray, &pCost->sttCost);
1✔
4965
    pStatus->pLDataIterArray = taosArrayInit(4, POINTER_BYTES);
1✔
4966
    if (pStatus->pLDataIterArray == NULL) {
1!
4967
      return terrno;
×
4968
    }
4969
  }
4970

4971
  // resetDataBlockScanInfo excluding lastKey
4972
  STableBlockScanInfo** p = NULL;
2✔
4973

4974
  int32_t step = ASCENDING_TRAVERSE(pCurrentReader->info.order) ? 1 : -1;
2!
4975
  int32_t iter = 0;
2✔
4976
  while ((p = tSimpleHashIterate(pStatus->pTableMap, p, &iter)) != NULL) {
4✔
4977
    STableBlockScanInfo* pInfo = *(STableBlockScanInfo**)p;
2✔
4978
    clearBlockScanInfo(pInfo);
2✔
4979
    //    pInfo->sttKeyInfo.nextProcKey = pInfo->lastProcKey.ts + step;
4980
    //    pInfo->sttKeyInfo.nextProcKey = pInfo->lastProcKey + step;
4981
  }
4982

4983
  pStatus->uidList.currentIndex = 0;
2✔
4984
  initReaderStatus(pStatus);
2✔
4985

4986
  return TSDB_CODE_SUCCESS;
2✔
4987
}
4988

4989
int32_t tsdbReaderSuspend2(STsdbReader* pReader) {
2✔
4990
  // save reader's base state & reset top state to be reconstructed from base state
4991
  int32_t code = 0;
2✔
4992
  pReader->status.suspendInvoked = true;  // record the suspend status
2✔
4993

4994
  if (pReader->type == TIMEWINDOW_RANGE_EXTERNAL) {
2!
4995
    if (pReader->step == EXTERNAL_ROWS_PREV) {
×
4996
      code = doSuspendCurrentReader(pReader->innerReader[0]);
×
4997
    } else if (pReader->step == EXTERNAL_ROWS_MAIN) {
×
4998
      code = doSuspendCurrentReader(pReader);
×
4999
    } else {
5000
      code = doSuspendCurrentReader(pReader->innerReader[1]);
×
5001
    }
5002
  } else {
5003
    code = doSuspendCurrentReader(pReader);
2✔
5004
  }
5005

5006
  // make sure only release once
5007
  void* p = pReader->pReadSnap;
2✔
5008
  if ((p == atomic_val_compare_exchange_ptr((void**)&pReader->pReadSnap, p, NULL)) && (p != NULL)) {
2!
5009
    tsdbUntakeReadSnap2(pReader, p, false);
2✔
5010
    pReader->pReadSnap = NULL;
2✔
5011
  }
5012

5013
  if (pReader->bFilesetDelimited) {
2!
5014
    pReader->status.memTableMinKey = INT64_MAX;
×
5015
    pReader->status.memTableMaxKey = INT64_MIN;
×
5016
  }
5017
  pReader->flag = READER_STATUS_SUSPEND;
2✔
5018

5019
  if (pReader->type == TIMEWINDOW_RANGE_EXTERNAL) {
2!
5020
    clearSharedPtr(pReader->innerReader[0]);
×
5021
    clearSharedPtr(pReader->innerReader[1]);
×
5022
  }
5023

5024
#if SUSPEND_RESUME_TEST
5025
  tsem_post(&pReader->resumeAfterSuspend);
5026
#endif
5027

5028
  tsdbDebug("reader: %p suspended in this query %s, step:%d", pReader, pReader->idStr, pReader->step);
2!
5029
  return code;
2✔
5030
}
5031

5032
static int32_t tsdbSetQueryReseek(void* pQHandle) {
2✔
5033
  int32_t      code = 0;
2✔
5034
  STsdbReader* pReader = pQHandle;
2✔
5035

5036
  code = tsdbTryAcquireReader(pReader);
2✔
5037
  if (code == 0) {
2!
5038
    if (pReader->flag == READER_STATUS_SUSPEND) {
2!
5039
      code = tsdbReleaseReader(pReader);
×
5040
      return code;
×
5041
    }
5042

5043
    code = tsdbReaderSuspend2(pReader);
2✔
5044
    (void) tsdbReleaseReader(pReader);
2✔
5045
    return code;
2✔
5046
  } else if (code == EBUSY) {
×
5047
    return TSDB_CODE_VND_QUERY_BUSY;
×
5048
  } else {
5049
    terrno = TAOS_SYSTEM_ERROR(code);
×
5050
    return TSDB_CODE_FAILED;
×
5051
  }
5052
}
5053

5054
int32_t tsdbReaderResume2(STsdbReader* pReader) {
5,029,139✔
5055
  int32_t               code = 0;
5,029,139✔
5056
  STableBlockScanInfo** pBlockScanInfo = pReader->status.pTableIter;
5,029,139✔
5057

5058
  //  restore reader's state, task snapshot
5059
  int32_t numOfTables = tSimpleHashGetSize(pReader->status.pTableMap);
5,029,139✔
5060
  if (numOfTables > 0) {
5,031,453✔
5061
    tsdbTrace("tsdb/reader: %p, take snapshot", pReader);
4,925,268✔
5062
    code = tsdbTakeReadSnap2(pReader, tsdbSetQueryReseek, &pReader->pReadSnap, pReader->idStr);
4,925,268✔
5063
    if (code != TSDB_CODE_SUCCESS) {
4,927,460!
5064
      goto _err;
×
5065
    }
5066

5067
    // open reader failure may cause the flag still to be READER_STATUS_SUSPEND, which may cause suspend reader failure.
5068
    // So we need to set it A.S.A.P
5069
    pReader->flag = READER_STATUS_NORMAL;
4,927,460✔
5070

5071
    if (pReader->type == TIMEWINDOW_RANGE_CONTAINED) {
4,927,460✔
5072
      code = doOpenReaderImpl(pReader);
4,926,317✔
5073
      if (code != TSDB_CODE_SUCCESS) {
4,922,775!
5074
        return code;
×
5075
      }
5076
    } else {
5077
      STsdbReader* pPrevReader = pReader->innerReader[0];
1,143✔
5078
      STsdbReader* pNextReader = pReader->innerReader[1];
1,143✔
5079

5080
      // we need only one row
5081
      pPrevReader->resBlockInfo.capacity = 1;
1,143✔
5082
      code = setSharedPtr(pPrevReader, pReader);
1,143✔
5083
      if (code != TSDB_CODE_SUCCESS) {
1,806!
5084
        return code;
×
5085
      }
5086

5087
      pNextReader->resBlockInfo.capacity = 1;
1,806✔
5088
      code = setSharedPtr(pNextReader, pReader);
1,806✔
5089
      if (code != TSDB_CODE_SUCCESS) {
1,806!
5090
        return code;
×
5091
      }
5092

5093
      if (pReader->step == 0 || pReader->step == EXTERNAL_ROWS_PREV) {
1,806!
5094
        code = doOpenReaderImpl(pPrevReader);
1,806✔
5095
      } else if (pReader->step == EXTERNAL_ROWS_MAIN) {
×
5096
        code = doOpenReaderImpl(pReader);
×
5097
      } else {
5098
        code = doOpenReaderImpl(pNextReader);
×
5099
      }
5100

5101
      if (code != TSDB_CODE_SUCCESS) {
1,806!
5102
        return code;
×
5103
      }
5104
    }
5105
  }
5106

5107
  tsdbDebug("reader: %p resumed uid %" PRIu64 ", numOfTable:%" PRId32 ", in this query %s", pReader,
5,030,766!
5108
            pBlockScanInfo ? (*pBlockScanInfo)->uid : 0, numOfTables, pReader->idStr);
5109
  return code;
5,027,801✔
5110

5111
_err:
×
5112
  tsdbError("failed to resume data reader, code:%s %s", tstrerror(code), pReader->idStr);
×
5113
  return code;
×
5114
}
5115

5116
static int32_t buildFromPreFilesetBuffer(STsdbReader* pReader) {
1,098,094✔
5117
  int32_t        code = TSDB_CODE_SUCCESS;
1,098,094✔
5118
  SReaderStatus* pStatus = &pReader->status;
1,098,094✔
5119

5120
  SSDataBlock* pBlock = pReader->resBlockInfo.pResBlock;
1,098,094✔
5121

5122
  int32_t     fid = pReader->status.pCurrentFileset->fid;
1,098,094✔
5123
  STimeWindow win = {0};
1,098,094✔
5124
  tsdbFidKeyRange(fid, pReader->pTsdb->keepCfg.days, pReader->pTsdb->keepCfg.precision, &win.skey, &win.ekey);
1,098,094✔
5125

5126
  int64_t endKey = (ASCENDING_TRAVERSE(pReader->info.order)) ? win.skey : win.ekey;
1,098,095✔
5127
  code = buildBlockFromBufferSeqForPreFileset(pReader, endKey);
1,098,095✔
5128
  if (code != TSDB_CODE_SUCCESS || pBlock->info.rows > 0) {
1,098,104✔
5129
    return code;
231,175✔
5130
  } else {
5131
    tsdbDebug("finished pre-fileset %d buffer processing. %s", fid, pReader->idStr);
866,929!
5132
    pStatus->bProcMemPreFileset = false;
866,930✔
5133
    pStatus->processingMemPreFileSet = false;
866,930✔
5134
    if (pReader->notifyFn) {
866,930!
5135
      STsdReaderNotifyInfo info = {0};
866,930✔
5136
      info.duration.filesetId = fid;
866,930✔
5137
      pReader->notifyFn(TSD_READER_NOTIFY_DURATION_START, &info, pReader->notifyParam);
866,930✔
5138
      tsdbDebug("new duration %d start notification when buffer pre-fileset, %s", fid, pReader->idStr);
866,930!
5139
    }
5140
  }
5141
  return code;
866,931✔
5142
}
5143

5144
static int32_t doTsdbNextDataBlockFilesetDelimited(STsdbReader* pReader) {
5,940,931✔
5145
  SReaderStatus* pStatus = &pReader->status;
5,940,931✔
5146
  int32_t        code = TSDB_CODE_SUCCESS;
5,940,931✔
5147
  SSDataBlock*   pBlock = pReader->resBlockInfo.pResBlock;
5,940,931✔
5148

5149
  if (pStatus->loadFromFile) {
5,940,931✔
5150
    if (pStatus->bProcMemPreFileset) {
3,398,155✔
5151
      code = buildFromPreFilesetBuffer(pReader);
296,265✔
5152
      if (code != TSDB_CODE_SUCCESS || pBlock->info.rows > 0) {
296,267!
5153
        return code;
114,545✔
5154
      }
5155
    }
5156

5157
    code = buildBlockFromFiles(pReader);
3,283,612✔
5158
    if (code != TSDB_CODE_SUCCESS) {
3,284,056!
5159
      return code;
×
5160
    }
5161

5162
    tsdbTrace("block from file rows: %" PRId64 ", will process pre-file set buffer: %d. %s", pBlock->info.rows,
3,284,056!
5163
              pStatus->bProcMemFirstFileset, pReader->idStr);
5164
    if (pStatus->bProcMemPreFileset) {
3,284,056✔
5165
      if (pBlock->info.rows > 0) {
116,632!
5166
        if (pReader->notifyFn && !pReader->status.processingMemPreFileSet) {
116,632!
5167
          int32_t              fid = pReader->status.pCurrentFileset->fid;
×
5168
          STsdReaderNotifyInfo info = {0};
×
5169
          info.duration.filesetId = fid;
×
5170
          pReader->notifyFn(TSD_READER_NOTIFY_NEXT_DURATION_BLOCK, &info, pReader->notifyParam);
×
5171
        }
5172
      } else {
5173
        pStatus->bProcMemPreFileset = false;
×
5174
      }
5175
    }
5176

5177
    if (pBlock->info.rows <= 0) {
3,284,056✔
5178
      code = resetTableListIndex(&pReader->status, pReader->idStr);
778,789✔
5179
      if (code) {
778,786!
5180
        return code;
×
5181
      }
5182

5183
      int64_t endKey = (ASCENDING_TRAVERSE(pReader->info.order)) ? INT64_MAX : INT64_MIN;
778,786✔
5184
      code = buildBlockFromBufferSequentially(pReader, endKey);
778,786✔
5185
    }
5186
  } else {  // no data in files, let's try the buffer
5187
    int64_t endKey = (ASCENDING_TRAVERSE(pReader->info.order)) ? INT64_MAX : INT64_MIN;
2,542,776✔
5188
    code = buildBlockFromBufferSequentially(pReader, endKey);
2,542,776✔
5189
  }
5190
  return code;
5,829,218✔
5191
}
5192

5193
static int32_t doTsdbNextDataBlockFilesFirst(STsdbReader* pReader) {
9,267,776✔
5194
  SReaderStatus* pStatus = &pReader->status;
9,267,776✔
5195
  int32_t        code = TSDB_CODE_SUCCESS;
9,267,776✔
5196
  SSDataBlock*   pBlock = pReader->resBlockInfo.pResBlock;
9,267,776✔
5197

5198
  if (pStatus->loadFromFile) {
9,267,776✔
5199
    code = buildBlockFromFiles(pReader);
5,130,972✔
5200
    if (code != TSDB_CODE_SUCCESS) {
5,129,006!
5201
      return code;
×
5202
    }
5203

5204
    if (pBlock->info.rows <= 0) {
5,129,006✔
5205
      code = resetTableListIndex(&pReader->status, pReader->idStr);
939,188✔
5206
      if (code) {
939,202!
5207
        return code;
×
5208
      }
5209

5210
      int64_t endKey = (ASCENDING_TRAVERSE(pReader->info.order)) ? INT64_MAX : INT64_MIN;
939,202✔
5211
      code = buildBlockFromBufferSequentially(pReader, endKey);
939,202✔
5212
    }
5213
  } else {  // no data in files, let's try the buffer
5214
    int64_t endKey = (ASCENDING_TRAVERSE(pReader->info.order)) ? INT64_MAX : INT64_MIN;
4,136,804✔
5215
    code = buildBlockFromBufferSequentially(pReader, endKey);
4,136,804✔
5216
  }
5217
  return code;
9,269,237✔
5218
}
5219

5220
static int32_t doTsdbNextDataBlock2(STsdbReader* pReader, bool* hasNext) {
15,312,524✔
5221
  int32_t code = TSDB_CODE_SUCCESS;
15,312,524✔
5222

5223
  // cleanup the data that belongs to the previous data block
5224
  SSDataBlock* pBlock = pReader->resBlockInfo.pResBlock;
15,312,524✔
5225
  blockDataCleanup(pBlock);
15,312,524✔
5226

5227
  *hasNext = false;
15,320,233✔
5228

5229
  SReaderStatus* pStatus = &pReader->status;
15,320,233✔
5230
  if (tSimpleHashGetSize(pStatus->pTableMap) == 0) {
15,320,233✔
5231
    return code;
106,577✔
5232
  }
5233

5234
  if (!pReader->bFilesetDelimited) {
15,214,832✔
5235
    code = doTsdbNextDataBlockFilesFirst(pReader);
9,271,458✔
5236
  } else {
5237
    code = doTsdbNextDataBlockFilesetDelimited(pReader);
5,943,374✔
5238
  }
5239

5240
  *hasNext = pBlock->info.rows > 0;
15,213,794✔
5241

5242
  return code;
15,213,794✔
5243
}
5244

5245
int32_t tsdbNextDataBlock2(STsdbReader* pReader, bool* hasNext) {
15,361,247✔
5246
  int32_t code = TSDB_CODE_SUCCESS;
15,361,247✔
5247

5248
  *hasNext = false;
15,361,247✔
5249

5250
  if (isEmptyQueryTimeWindow(&pReader->info.window) || pReader->step == EXTERNAL_ROWS_NEXT ||
15,361,247!
5251
      pReader->code != TSDB_CODE_SUCCESS) {
15,319,480✔
5252
    return (pReader->code != TSDB_CODE_SUCCESS) ? pReader->code : code;
46,229!
5253
  }
5254

5255
  SReaderStatus* pStatus = &pReader->status;
15,318,575✔
5256

5257
  // NOTE: the following codes is used to perform test for suspend/resume for tsdbReader when it blocks the commit
5258
  // the data should be ingested in round-robin and all the child tables should be createted before ingesting data
5259
  // the version range of query will be used to identify the correctness of suspend/resume functions.
5260
  // this function will be blocked before loading the SECOND block from vnode-buffer, and restart itself from sst-files
5261
#if SUSPEND_RESUME_TEST
5262
  if (!pReader->status.suspendInvoked && !pReader->status.loadFromFile) {
5263
    tsem_wait(&pReader->resumeAfterSuspend);
5264
  }
5265
#endif
5266

5267
  code = tsdbAcquireReader(pReader);
15,318,575✔
5268
  if (code != TSDB_CODE_SUCCESS) {
15,320,552!
5269
    return code;
×
5270
  }
5271

5272
  tsdbTrace("tsdb/read: %p, take read mutex, code: %d", pReader, code);
15,320,552✔
5273

5274
  if (pReader->flag == READER_STATUS_SUSPEND) {
15,320,552✔
5275
    code = tsdbReaderResume2(pReader);
5,030,649✔
5276
    if (code != TSDB_CODE_SUCCESS) {
5,023,892!
5277
      // release reader failure should be suppressed here, to avoid over-write the original error code
5278
      (void) tsdbReleaseReader(pReader);
×
5279
      return code;
×
5280
    }
5281
  }
5282

5283
  if (pReader->innerReader[0] != NULL && pReader->step == 0) {
15,313,795✔
5284
    code = doTsdbNextDataBlock2(pReader->innerReader[0], hasNext);
1,806✔
5285
    if (code) {
1,806!
5286
      (void) tsdbReleaseReader(pReader);
×
5287
      return code;
×
5288
    }
5289

5290
    pReader->step = EXTERNAL_ROWS_PREV;
1,806✔
5291
    if (*hasNext) {
1,806✔
5292
      pStatus = &pReader->innerReader[0]->status;
647✔
5293
      if (pStatus->composedDataBlock) {
647!
5294
        tsdbTrace("tsdb/read: %p, unlock read mutex", pReader);
647!
5295
        code = tsdbReleaseReader(pReader);
647✔
5296
      }
5297

5298
      return code;
647✔
5299
    }
5300
  }
5301

5302
  if (pReader->step == EXTERNAL_ROWS_PREV) {
15,313,148✔
5303
    // prepare for the main scan
5304
    if (tSimpleHashGetSize(pReader->status.pTableMap) > 0) {
1,806!
5305
      code = doOpenReaderImpl(pReader);
1,806✔
5306
    }
5307

5308
    int32_t step = 1;
1,806✔
5309
    resetAllDataBlockScanInfo(pReader->status.pTableMap, pReader->innerReader[0]->info.window.ekey, step);
1,806✔
5310

5311
    if (code != TSDB_CODE_SUCCESS) {
1,806!
5312
      (void) tsdbReleaseReader(pReader);
×
5313
      return code;
×
5314
    }
5315

5316
    pReader->step = EXTERNAL_ROWS_MAIN;
1,806✔
5317
  }
5318

5319
  code = doTsdbNextDataBlock2(pReader, hasNext);
15,313,148✔
5320
  if (code != TSDB_CODE_SUCCESS) {
15,315,615!
5321
    (void) tsdbReleaseReader(pReader);
×
5322
    return code;
4✔
5323
  }
5324

5325
  if (*hasNext) {
15,317,272✔
5326
    if (pStatus->composedDataBlock) {
10,408,625✔
5327
      tsdbTrace("tsdb/read: %p, unlock read mutex", pReader);
9,687,272✔
5328
      code = tsdbReleaseReader(pReader);
9,687,272✔
5329
    }
5330
    return code;
10,412,715✔
5331
  }
5332

5333
  if (pReader->step == EXTERNAL_ROWS_MAIN && pReader->innerReader[1] != NULL) {
4,908,647!
5334
    // prepare for the next row scan
5335
    if (tSimpleHashGetSize(pReader->status.pTableMap) > 0) {
1,806!
5336
      code = doOpenReaderImpl(pReader->innerReader[1]);
1,806✔
5337
    }
5338

5339
    int32_t step = -1;
1,806✔
5340
    resetAllDataBlockScanInfo(pReader->innerReader[1]->status.pTableMap, pReader->info.window.ekey, step);
1,806✔
5341
    if (code != TSDB_CODE_SUCCESS) {
1,806!
5342
      (void) tsdbReleaseReader(pReader);
×
5343
      return code;
×
5344
    }
5345

5346
    code = doTsdbNextDataBlock2(pReader->innerReader[1], hasNext);
1,806✔
5347
    if (code != TSDB_CODE_SUCCESS) {
1,806!
5348
      (void) tsdbReleaseReader(pReader);
×
5349
      return code;
×
5350
    }
5351

5352
    pReader->step = EXTERNAL_ROWS_NEXT;
1,806✔
5353
    if (*hasNext) {
1,806✔
5354
      pStatus = &pReader->innerReader[1]->status;
733✔
5355
      if (pStatus->composedDataBlock) {
733!
5356
        tsdbTrace("tsdb/read: %p, unlock read mutex", pReader);
733!
5357
        code = tsdbReleaseReader(pReader);
733✔
5358
      }
5359

5360
      return code;
733✔
5361
    }
5362
  }
5363

5364
  tsdbTrace("tsdb/read: %p, unlock read mutex", pReader);
4,907,914✔
5365
  code = tsdbReleaseReader(pReader);
4,907,914✔
5366
  return code;
4,908,316✔
5367
}
5368

5369
static void doFillNullColSMA(SBlockLoadSuppInfo* pSup, int32_t numOfRows, int32_t numOfCols, SColumnDataAgg* pTsAgg) {
259,718✔
5370
  // do fill all null column value SMA info
5371
  int32_t i = 0, j = 0;
259,718✔
5372
  int32_t size = (int32_t)TARRAY2_SIZE(&pSup->colAggArray);
259,718✔
5373
  int32_t code = TARRAY2_INSERT_PTR(&pSup->colAggArray, 0, pTsAgg);
259,718!
5374
  if (code != TSDB_CODE_SUCCESS) {
259,718!
5375
    return;
×
5376
  }
5377

5378
  size++;
259,718✔
5379

5380
  while (j < numOfCols && i < size) {
1,037,263!
5381
    SColumnDataAgg* pAgg = &pSup->colAggArray.data[i];
777,545✔
5382
    if (pAgg->colId == pSup->colId[j]) {
777,545✔
5383
      i += 1;
743,210✔
5384
      j += 1;
743,210✔
5385
    } else if (pAgg->colId < pSup->colId[j]) {
34,335!
5386
      i += 1;
34,342✔
5387
    } else if (pSup->colId[j] < pAgg->colId) {
×
5388
      if (pSup->colId[j] != PRIMARYKEY_TIMESTAMP_COL_ID) {
×
5389
        SColumnDataAgg nullColAgg = {.colId = pSup->colId[j], .numOfNull = numOfRows};
×
5390
        code = TARRAY2_INSERT_PTR(&pSup->colAggArray, i, &nullColAgg);
×
5391
        if (code != TSDB_CODE_SUCCESS) {
×
5392
          return;
×
5393
        }
5394

5395
        i += 1;
×
5396
        size++;
×
5397
      }
5398
      j += 1;
×
5399
    }
5400
  }
5401

5402
  while (j < numOfCols) {
259,719✔
5403
    if (pSup->colId[j] != PRIMARYKEY_TIMESTAMP_COL_ID) {
1!
5404
      SColumnDataAgg nullColAgg = {.colId = pSup->colId[j], .numOfNull = numOfRows};
1✔
5405
      code = TARRAY2_INSERT_PTR(&pSup->colAggArray, i, &nullColAgg);
1!
5406
      if (code != TSDB_CODE_SUCCESS) {
1!
5407
        return;
×
5408
      }
5409

5410
      i += 1;
1✔
5411
    }
5412
    j++;
1✔
5413
  }
5414
}
5415

5416
int32_t tsdbRetrieveDatablockSMA2(STsdbReader* pReader, SSDataBlock* pDataBlock, bool* allHave, bool* hasNullSMA) {
5,271,081✔
5417
  SColumnDataAgg**    pBlockSMA = &pDataBlock->pBlockAgg;
5,271,081✔
5418
  SFileDataBlockInfo* pBlockInfo = NULL;
5,271,081✔
5419
  int32_t             code = 0;
5,271,081✔
5420
  *allHave = false;
5,271,081✔
5421
  *pBlockSMA = NULL;
5,271,081✔
5422

5423
  if (pReader->type == TIMEWINDOW_RANGE_EXTERNAL) {
5,271,081✔
5424
    return TSDB_CODE_SUCCESS;
25✔
5425
  }
5426

5427
  // there is no statistics data for composed block
5428
  if (pReader->status.composedDataBlock || (!pReader->suppInfo.smaValid)) {
5,271,056!
5429
    return TSDB_CODE_SUCCESS;
5,011,404✔
5430
  }
5431

5432
  code = getCurrentBlockInfo(&pReader->status.blockIter, &pBlockInfo, pReader->idStr);
259,652✔
5433
  if (code != TSDB_CODE_SUCCESS) {
259,654!
5434
    return code;
×
5435
  }
5436

5437
  SBlockLoadSuppInfo* pSup = &pReader->suppInfo;
259,654✔
5438

5439
  SSDataBlock* pResBlock = pReader->resBlockInfo.pResBlock;
259,654✔
5440
  if (pResBlock->info.id.uid != pBlockInfo->uid) {
259,654!
5441
    return TSDB_CODE_SUCCESS;
×
5442
  }
5443

5444
  //  int64_t st = taosGetTimestampUs();
5445
  TARRAY2_CLEAR(&pSup->colAggArray, 0);
259,654✔
5446

5447
  SBrinRecord pRecord;
5448
  blockInfoToRecord(&pRecord, pBlockInfo, pSup);
259,654✔
5449
  code = tsdbDataFileReadBlockSma(pReader->pFileReader, &pRecord, &pSup->colAggArray);
259,714✔
5450
  if (code != TSDB_CODE_SUCCESS) {
259,465!
5451
    tsdbDebug("vgId:%d, failed to load block SMA for uid %" PRIu64 ", code:%s, %s", 0, pBlockInfo->uid, tstrerror(code),
×
5452
              pReader->idStr);
5453
    return code;
×
5454
  }
5455

5456
  if (pSup->colAggArray.size > 0) {
259,465!
5457
    *allHave = true;
259,465✔
5458
  } else {
5459
    *pBlockSMA = NULL;
×
5460
    return TSDB_CODE_SUCCESS;
×
5461
  }
5462

5463
  // always load the first primary timestamp column data
5464
  SColumnDataAgg* pTsAgg = &pSup->tsColAgg;
259,465✔
5465

5466
  pTsAgg->numOfNull = 0;
259,465✔
5467
  pTsAgg->colId = PRIMARYKEY_TIMESTAMP_COL_ID;
259,465✔
5468
  pTsAgg->min = pResBlock->info.window.skey;
259,465✔
5469
  pTsAgg->max = pResBlock->info.window.ekey;
259,465✔
5470

5471
  // update the number of NULL data rows
5472
  size_t numOfCols = pSup->numOfCols;
259,465✔
5473

5474
  if (pResBlock->pBlockAgg == NULL) {
259,465!
5475
    size_t num = taosArrayGetSize(pResBlock->pDataBlock);
259,483✔
5476
    pResBlock->pBlockAgg = taosMemoryCalloc(num, sizeof(SColumnDataAgg));
259,483✔
5477
    if (pResBlock->pBlockAgg == NULL) {
259,724!
5478
      return terrno;
×
5479
    }
5480
    for (int i = 0; i < num; ++i) {
1,227,137✔
5481
      pResBlock->pBlockAgg[i].colId = -1;
967,413✔
5482
    }
5483
  }
5484

5485
  // do fill all null column value SMA info
5486
  doFillNullColSMA(pSup, pBlockInfo->numRow, numOfCols, pTsAgg);
259,706✔
5487

5488
  size_t size = pSup->colAggArray.size;
259,479✔
5489

5490
  int32_t i = 0, j = 0;
259,479✔
5491
  while (j < numOfCols && i < size) {
1,036,833!
5492
    SColumnDataAgg* pAgg = &pSup->colAggArray.data[i];
777,354✔
5493
    if (pAgg->colId == pSup->colId[j]) {
777,354✔
5494
      pResBlock->pBlockAgg[pSup->slotId[j]] = *pAgg;
743,090✔
5495
      i += 1;
743,090✔
5496
      j += 1;
743,090✔
5497
    } else if (pAgg->colId < pSup->colId[j]) {
34,264!
5498
      i += 1;
34,268✔
5499
    } else if (pSup->colId[j] < pAgg->colId) {
×
5500
      pResBlock->pBlockAgg[pSup->slotId[j]].colId = -1;
×
5501
      *allHave = false;
×
5502
      j += 1;
×
5503
    }
5504
  }
5505

5506
  *pBlockSMA = pResBlock->pBlockAgg;
259,479✔
5507
  pReader->cost.smaDataLoad += 1;
259,479✔
5508

5509
  //  double elapsedTime = (taosGetTimestampUs() - st) / 1000.0;
5510
  pReader->cost.smaLoadTime += 0;  // elapsedTime;
259,479✔
5511

5512
  tsdbDebug("vgId:%d, succeed to load block SMA for uid %" PRIu64 ", %s", 0, pBlockInfo->uid, pReader->idStr);
259,479✔
5513
  return code;
259,530✔
5514
}
5515

5516
static int32_t doRetrieveDataBlock(STsdbReader* pReader, SSDataBlock** pBlock) {
589,495✔
5517
  SReaderStatus*      pStatus = &pReader->status;
589,495✔
5518
  int32_t             code = TSDB_CODE_SUCCESS;
589,495✔
5519
  SFileDataBlockInfo* pBlockInfo = NULL;
589,495✔
5520
  *pBlock = NULL;
589,495✔
5521

5522
  code = getCurrentBlockInfo(&pStatus->blockIter, &pBlockInfo, pReader->idStr);
589,495✔
5523
  if (code != TSDB_CODE_SUCCESS) {
589,661!
5524
    return code;
×
5525
  }
5526

5527
  if (pReader->code != TSDB_CODE_SUCCESS) {
589,661!
5528
    return pReader->code;
×
5529
  }
5530

5531
  STableBlockScanInfo* pBlockScanInfo = NULL;
589,661✔
5532
  code = getTableBlockScanInfo(pStatus->pTableMap, pBlockInfo->uid, &pBlockScanInfo, pReader->idStr);
589,661✔
5533
  if (code != TSDB_CODE_SUCCESS) {
589,809!
5534
    return code;
×
5535
  }
5536

5537
  code = doLoadFileBlockData(pReader, &pStatus->blockIter, &pStatus->fileBlockData, pBlockScanInfo->uid);
589,809✔
5538
  if (code != TSDB_CODE_SUCCESS) {
589,889!
5539
    tBlockDataReset(&pStatus->fileBlockData);
×
5540
    return code;
×
5541
  }
5542

5543
  code = copyBlockDataToSDataBlock(pReader, &pBlockScanInfo->lastProcKey);
589,889✔
5544
  if (code != TSDB_CODE_SUCCESS) {
589,872✔
5545
    tBlockDataReset(&pStatus->fileBlockData);
8✔
5546
  }
5547

5548
  *pBlock = pReader->resBlockInfo.pResBlock;
589,949✔
5549
  return code;
589,949✔
5550
}
5551

5552
int32_t tsdbRetrieveDataBlock2(STsdbReader* pReader, SSDataBlock** pBlock, SArray* pIdList) {
10,021,481✔
5553
  *pBlock = NULL;
10,021,481✔
5554

5555
  STsdbReader* pTReader = pReader;
10,021,481✔
5556
  if (pReader->type == TIMEWINDOW_RANGE_EXTERNAL) {
10,021,481✔
5557
    if (pReader->step == EXTERNAL_ROWS_PREV) {
2,804✔
5558
      pTReader = pReader->innerReader[0];
647✔
5559
    } else if (pReader->step == EXTERNAL_ROWS_NEXT) {
2,157✔
5560
      pTReader = pReader->innerReader[1];
733✔
5561
    }
5562
  }
5563

5564
  SReaderStatus* pStatus = &pTReader->status;
10,021,481✔
5565
  if (pStatus->composedDataBlock || pReader->info.execMode == READER_EXEC_ROWS) {
10,021,481!
5566
    //    tsdbReaderSuspend2(pReader);
5567
    //    tsdbReaderResume2(pReader);
5568
    *pBlock = pTReader->resBlockInfo.pResBlock;
9,431,966✔
5569
    return TSDB_CODE_SUCCESS;
9,431,966✔
5570
  }
5571

5572
  int32_t code = doRetrieveDataBlock(pTReader, pBlock);
589,515✔
5573

5574
  tsdbTrace("tsdb/read-retrieve: %p, unlock read mutex", pReader);
589,889!
5575
  (void) tsdbReleaseReader(pReader);
589,889✔
5576

5577
  //  tsdbReaderSuspend2(pReader);
5578
  //  tsdbReaderResume2(pReader);
5579
  return code;
590,046✔
5580
}
5581

5582
int32_t tsdbReaderReset2(STsdbReader* pReader, SQueryTableDataCond* pCond) {
21,091✔
5583
  int32_t code = TSDB_CODE_SUCCESS;
21,091✔
5584

5585
  tsdbTrace("tsdb/reader-reset: %p, take read mutex", pReader);
21,091!
5586
  code = tsdbAcquireReader(pReader);
21,091✔
5587
  if (code != TSDB_CODE_SUCCESS) {
21,093!
5588
    return code;
×
5589
  }
5590

5591
  if (pReader->flag == READER_STATUS_SUSPEND) {
21,093✔
5592
    code = tsdbReaderResume2(pReader);
6✔
5593
    if (code != TSDB_CODE_SUCCESS) {
6!
5594
      (void) tsdbReleaseReader(pReader);
×
5595
      return code;
×
5596
    }
5597
  }
5598

5599
  if (isEmptyQueryTimeWindow(&pReader->info.window) || pReader->pReadSnap == NULL) {
21,093✔
5600
    tsdbDebug("tsdb reader reset return %p, %s", pReader->pReadSnap, pReader->idStr);
26✔
5601
    return tsdbReleaseReader(pReader);
26✔
5602
  }
5603

5604
  SReaderStatus*  pStatus = &pReader->status;
21,067✔
5605
  SDataBlockIter* pBlockIter = &pStatus->blockIter;
21,067✔
5606

5607
  pReader->info.order = pCond->order;
21,067✔
5608
  pReader->type = TIMEWINDOW_RANGE_CONTAINED;
21,067✔
5609
  pReader->info.window = updateQueryTimeWindow(pReader->pTsdb, &pCond->twindows);
21,067✔
5610
  pStatus->loadFromFile = true;
21,067✔
5611
  pStatus->pTableIter = NULL;
21,067✔
5612

5613
  // allocate buffer in order to load data blocks from file
5614
  memset(&pReader->suppInfo.tsColAgg, 0, sizeof(SColumnDataAgg));
21,067✔
5615

5616
  pReader->suppInfo.tsColAgg.colId = PRIMARYKEY_TIMESTAMP_COL_ID;
21,067✔
5617
  tsdbDataFileReaderClose(&pReader->pFileReader);
21,067✔
5618

5619
  int32_t numOfTables = tSimpleHashGetSize(pStatus->pTableMap);
21,065✔
5620

5621
  code = initFilesetIterator(&pStatus->fileIter, pReader->pReadSnap->pfSetArray, pReader);
21,065✔
5622
  if (code != TSDB_CODE_SUCCESS) {
21,064!
5623
    (void) tsdbReleaseReader(pReader);
×
5624
    return code;
×
5625
  }
5626

5627
  code = resetDataBlockIterator(pBlockIter, pReader->info.order, shouldFreePkBuf(&pReader->suppInfo), pReader->idStr);
21,064✔
5628
  if (code != TSDB_CODE_SUCCESS) {
21,062!
5629
    (void) tsdbReleaseReader(pReader);
×
5630
    return code;
×
5631
  }
5632

5633
  code = resetTableListIndex(&pReader->status, pReader->idStr);
21,062✔
5634
  if (code != TSDB_CODE_SUCCESS) {
21,065!
5635
    (void) tsdbReleaseReader(pReader);
×
5636
    return code;
×
5637
  }
5638

5639
  bool    asc = ASCENDING_TRAVERSE(pReader->info.order);
21,065✔
5640
  int32_t step = asc ? 1 : -1;
21,065✔
5641
  int64_t ts = 0;
21,065✔
5642
  if (asc) {
21,065✔
5643
    ts = (pReader->info.window.skey > INT64_MIN) ? pReader->info.window.skey - 1 : pReader->info.window.skey;
20,514!
5644
  } else {
5645
    ts = (pReader->info.window.ekey < INT64_MAX) ? pReader->info.window.ekey + 1 : pReader->info.window.ekey;
551✔
5646
  }
5647
  resetAllDataBlockScanInfo(pStatus->pTableMap, ts, step);
21,065✔
5648

5649
  // no data in files, let's try buffer in memory
5650
  if (pStatus->fileIter.numOfFiles == 0) {
21,060✔
5651
    pStatus->loadFromFile = false;
3,791✔
5652
    code = resetTableListIndex(pStatus, pReader->idStr);
3,791✔
5653
    if (code != TSDB_CODE_SUCCESS) {
3,791!
5654
      (void) tsdbReleaseReader(pReader);
×
5655
      return code;
×
5656
    }
5657
  } else {
5658
    code = initForFirstBlockInFile(pReader, pBlockIter);
17,269✔
5659
    if (code != TSDB_CODE_SUCCESS) {
17,250!
5660
      tsdbError("%p reset reader failed, numOfTables:%d, query range:%" PRId64 " - %" PRId64 " in query %s", pReader,
×
5661
                numOfTables, pReader->info.window.skey, pReader->info.window.ekey, pReader->idStr);
5662

5663
      (void) tsdbReleaseReader(pReader);
×
5664
      return code;
×
5665
    }
5666
  }
5667

5668
  tsdbDebug("%p reset reader, suid:%" PRIu64 ", numOfTables:%d, skey:%" PRId64 ", query range:%" PRId64 " - %" PRId64
21,041✔
5669
            " in query %s",
5670
            pReader, pReader->info.suid, numOfTables, pCond->twindows.skey, pReader->info.window.skey,
5671
            pReader->info.window.ekey, pReader->idStr);
5672

5673
  code = tsdbReleaseReader(pReader);
21,041✔
5674
  return code;
21,059✔
5675
}
5676

5677
static int32_t getBucketIndex(int32_t startRow, int32_t bucketRange, int32_t numOfRows, int32_t numOfBucket) {
1✔
5678
  if (numOfRows < startRow) {
1!
5679
    return 0;
×
5680
  }
5681
  int32_t bucketIndex = ((numOfRows - startRow) / bucketRange);
1✔
5682
  if (bucketIndex == numOfBucket) {
1!
5683
    bucketIndex -= 1;
×
5684
  }
5685
  return bucketIndex;
1✔
5686
}
5687

5688
int32_t tsdbGetFileBlocksDistInfo2(STsdbReader* pReader, STableBlockDistInfo* pTableBlockInfo) {
3,241✔
5689
  int32_t       code = TSDB_CODE_SUCCESS;
3,241✔
5690
  const int32_t numOfBuckets = 20.0;
3,241✔
5691

5692
  pTableBlockInfo->totalSize = 0;
3,241✔
5693
  pTableBlockInfo->totalRows = 0;
3,241✔
5694
  pTableBlockInfo->numOfVgroups = 1;
3,241✔
5695

5696
  // find the start data block in file
5697
  code = tsdbAcquireReader(pReader);
3,241✔
5698
  if (code != TSDB_CODE_SUCCESS) {
3,246!
5699
    return code;
×
5700
  }
5701

5702
  if (pReader->flag == READER_STATUS_SUSPEND) {
3,246!
5703
    code = tsdbReaderResume2(pReader);
3,249✔
5704
    if (code != TSDB_CODE_SUCCESS) {
3,244!
5705
      return tsdbReleaseReader(pReader);
×
5706
    }
5707
  }
5708

5709
  SMergeTreeConf conf = {
3,241✔
5710
      .pReader = pReader,
5711
      .pSchema = pReader->info.pSchema,
3,241✔
5712
      .pCols = pReader->suppInfo.colId,
3,241✔
5713
      .numOfCols = pReader->suppInfo.numOfCols,
3,241✔
5714
      .suid = pReader->info.suid,
3,241✔
5715
  };
5716

5717
  SReaderStatus* pStatus = &pReader->status;
3,241✔
5718
  if (pStatus->pCurrentFileset != NULL) {
3,241✔
5719
    pTableBlockInfo->numOfSttRows += tsdbGetRowsInSttFiles(pStatus->pCurrentFileset, pStatus->pLDataIterArray,
1,890✔
5720
                                                           pReader->pTsdb, &conf, pReader->idStr);
1,889✔
5721
  }
5722

5723
  STsdbCfg* pc = &pReader->pTsdb->pVnode->config.tsdbCfg;
3,242✔
5724
  pTableBlockInfo->defMinRows = pc->minRows;
3,242✔
5725
  pTableBlockInfo->defMaxRows = pc->maxRows;
3,242✔
5726

5727
  int32_t bucketRange = ceil(((double)(pc->maxRows - pc->minRows)) / numOfBuckets);
3,242✔
5728

5729
  pTableBlockInfo->numOfFiles += 1;
3,242✔
5730

5731
  int32_t numOfTables = (int32_t)tSimpleHashGetSize(pStatus->pTableMap);
3,242✔
5732

5733
  SDataBlockIter* pBlockIter = &pStatus->blockIter;
3,245✔
5734
  pTableBlockInfo->numOfFiles += pStatus->fileIter.numOfFiles;
3,245✔
5735

5736
  if (pBlockIter->numOfBlocks > 0) {
3,245✔
5737
    pTableBlockInfo->numOfBlocks += pBlockIter->numOfBlocks;
1✔
5738
  }
5739

5740
  pTableBlockInfo->numOfTables = numOfTables;
3,245✔
5741
  bool hasNext = (pBlockIter->numOfBlocks > 0);
3,245✔
5742

5743
  while (true) {
5744
    if (hasNext) {
7,023✔
5745
      SFileDataBlockInfo* pBlockInfo = NULL;
1✔
5746
      code = getCurrentBlockInfo(pBlockIter, &pBlockInfo, pReader->idStr);
1✔
5747
      if (code != TSDB_CODE_SUCCESS) {
1!
5748
        break;
×
5749
      }
5750

5751
      int32_t numOfRows = pBlockInfo->numRow;
1✔
5752

5753
      pTableBlockInfo->totalRows += numOfRows;
1✔
5754

5755
      if (numOfRows > pTableBlockInfo->maxRows) {
1!
5756
        pTableBlockInfo->maxRows = numOfRows;
1✔
5757
      }
5758

5759
      if (numOfRows < pTableBlockInfo->minRows) {
1!
5760
        pTableBlockInfo->minRows = numOfRows;
1✔
5761
      }
5762

5763
      pTableBlockInfo->totalSize += pBlockInfo->blockSize;
1✔
5764

5765
      int32_t bucketIndex = getBucketIndex(pTableBlockInfo->defMinRows, bucketRange, numOfRows, numOfBuckets);
1✔
5766
      pTableBlockInfo->blockRowsHisto[bucketIndex]++;
1✔
5767

5768
      hasNext = blockIteratorNext(&pStatus->blockIter, pReader->idStr);
1✔
5769
    } else {
5770
      code = initForFirstBlockInFile(pReader, pBlockIter);
7,022✔
5771
      if ((code != TSDB_CODE_SUCCESS) || (pStatus->loadFromFile == false)) {
7,016!
5772
        break;
5773
      }
5774

5775
      // add the data in stt files of new fileset
5776
      if (pStatus->pCurrentFileset != NULL) {
3,774!
5777
        pTableBlockInfo->numOfSttRows += tsdbGetRowsInSttFiles(pStatus->pCurrentFileset, pStatus->pLDataIterArray,
3,779✔
5778
                                                               pReader->pTsdb, &conf, pReader->idStr);
3,775✔
5779
      }
5780

5781
      pTableBlockInfo->numOfBlocks += pBlockIter->numOfBlocks;
3,778✔
5782
      hasNext = (pBlockIter->numOfBlocks > 0);
3,778✔
5783
    }
5784
  }
5785

5786
  // record the data in stt files
5787
  (void) tsdbReleaseReader(pReader);
3,242✔
5788
  return code;
3,249✔
5789
}
5790

5791
static void getMemTableTimeRange(STsdbReader* pReader, int64_t* pMaxKey, int64_t* pMinKey) {
1,994,727✔
5792
  int32_t code = TSDB_CODE_SUCCESS;
1,994,727✔
5793
  int64_t rows = 0;
1,994,727✔
5794

5795
  SReaderStatus* pStatus = &pReader->status;
1,994,727✔
5796

5797
  int32_t iter = 0;
1,994,727✔
5798
  int64_t maxKey = INT64_MIN;
1,994,727✔
5799
  int64_t minKey = INT64_MAX;
1,994,727✔
5800

5801
  void* pHashIter = tSimpleHashIterate(pStatus->pTableMap, NULL, &iter);
1,994,727✔
5802
  while (pHashIter != NULL) {
7,053,572✔
5803
    STableBlockScanInfo* pBlockScanInfo = *(STableBlockScanInfo**)pHashIter;
5,056,751✔
5804

5805
    STbData* d = NULL;
5,056,751✔
5806
    if (pReader->pReadSnap->pMem != NULL) {
5,056,751✔
5807
      d = tsdbGetTbDataFromMemTable(pReader->pReadSnap->pMem, pReader->info.suid, pBlockScanInfo->uid);
4,611,402✔
5808
      if (d != NULL) {
4,613,894✔
5809
        if (d->maxKey > maxKey) {
1,781,361✔
5810
          maxKey = d->maxKey;
1,470,764✔
5811
        }
5812
        if (d->minKey < minKey) {
1,781,361✔
5813
          minKey = d->minKey;
1,455,263✔
5814
        }
5815
      }
5816
    }
5817

5818
    STbData* di = NULL;
5,059,243✔
5819
    if (pReader->pReadSnap->pIMem != NULL) {
5,059,243✔
5820
      di = tsdbGetTbDataFromMemTable(pReader->pReadSnap->pIMem, pReader->info.suid, pBlockScanInfo->uid);
10✔
5821
      if (di != NULL) {
10!
5822
        if (di->maxKey > maxKey) {
10✔
5823
          maxKey = di->maxKey;
6✔
5824
        }
5825
        if (di->minKey < minKey) {
10✔
5826
          minKey = di->minKey;
3✔
5827
        }
5828
      }
5829
    }
5830

5831
    // current table is exhausted, let's try the next table
5832
    pHashIter = tSimpleHashIterate(pStatus->pTableMap, pHashIter, &iter);
5,059,243✔
5833
  }
5834

5835
  *pMaxKey = maxKey;
1,996,821✔
5836
  *pMinKey = minKey;
1,996,821✔
5837
}
1,996,821✔
5838

5839
int64_t tsdbGetNumOfRowsInMemTable2(STsdbReader* pReader) {
3,249✔
5840
  int32_t code = TSDB_CODE_SUCCESS;
3,249✔
5841
  int64_t rows = 0;
3,249✔
5842

5843
  SReaderStatus* pStatus = &pReader->status;
3,249✔
5844
  code = tsdbAcquireReader(pReader);
3,249✔
5845
  if (code != TSDB_CODE_SUCCESS) {
3,250!
5846
    return code;
×
5847
  }
5848

5849
  if (pReader->flag == READER_STATUS_SUSPEND) {
3,250✔
5850
    code = tsdbReaderResume2(pReader);
544✔
5851
    if (code != TSDB_CODE_SUCCESS) {
544!
5852
      (void) tsdbReleaseReader(pReader);
×
5853
      return code;
×
5854
    }
5855
  }
5856

5857
  int32_t iter = 0;
3,250✔
5858
  pStatus->pTableIter = tSimpleHashIterate(pStatus->pTableMap, NULL, &iter);
3,250✔
5859

5860
  while (pStatus->pTableIter != NULL) {
10,270✔
5861
    STableBlockScanInfo* pBlockScanInfo = *(STableBlockScanInfo**)pStatus->pTableIter;
7,018✔
5862

5863
    STbData* d = NULL;
7,018✔
5864
    if (pReader->pReadSnap->pMem != NULL) {
7,018✔
5865
      d = tsdbGetTbDataFromMemTable(pReader->pReadSnap->pMem, pReader->info.suid, pBlockScanInfo->uid);
7,014✔
5866
      if (d != NULL) {
7,021✔
5867
        rows += tsdbGetNRowsInTbData(d);
1,621✔
5868
      }
5869
    }
5870

5871
    STbData* di = NULL;
7,025✔
5872
    if (pReader->pReadSnap->pIMem != NULL) {
7,025✔
5873
      di = tsdbGetTbDataFromMemTable(pReader->pReadSnap->pIMem, pReader->info.suid, pBlockScanInfo->uid);
2✔
5874
      if (di != NULL) {
2!
5875
        rows += tsdbGetNRowsInTbData(di);
2✔
5876
      }
5877
    }
5878

5879
    // current table is exhausted, let's try the next table
5880
    pStatus->pTableIter = tSimpleHashIterate(pStatus->pTableMap, pStatus->pTableIter, &iter);
7,025✔
5881
  }
5882

5883
  (void) tsdbReleaseReader(pReader);
3,252✔
5884

5885
  return rows;
3,250✔
5886
}
5887

5888
int32_t tsdbGetTableSchema(SMeta* pMeta, int64_t uid, STSchema** pSchema, int64_t* suid) {
313✔
5889
  SMetaReader mr = {0};
313✔
5890
  metaReaderDoInit(&mr, pMeta, META_READER_LOCK);
313✔
5891
  int32_t code = metaReaderGetTableEntryByUidCache(&mr, uid);
313✔
5892
  if (code != TSDB_CODE_SUCCESS) {
313!
5893
    code = TSDB_CODE_TDB_INVALID_TABLE_ID;
×
5894
    metaReaderClear(&mr);
×
5895
    return code;
×
5896
  }
5897

5898
  *suid = 0;
313✔
5899

5900
  // only child table and ordinary table is allowed, super table is not allowed.
5901
  if (mr.me.type == TSDB_CHILD_TABLE) {
313✔
5902
    tDecoderClear(&mr.coder);
187✔
5903
    *suid = mr.me.ctbEntry.suid;
187✔
5904
    code = metaReaderGetTableEntryByUidCache(&mr, *suid);
187✔
5905
    if (code != TSDB_CODE_SUCCESS) {
187!
5906
      code = TSDB_CODE_TDB_INVALID_TABLE_ID;
×
5907
      metaReaderClear(&mr);
×
5908
      return code;
×
5909
    }
5910
  } else if (mr.me.type == TSDB_NORMAL_TABLE) {  // do nothing
126!
5911
  } else {
5912
    code = TSDB_CODE_INVALID_PARA;
×
5913
    tsdbError("invalid mr.me.type:%d, code:%s", mr.me.type, tstrerror(code));
×
5914
    metaReaderClear(&mr);
×
5915
    return code;
×
5916
  }
5917

5918
  metaReaderClear(&mr);
313✔
5919

5920
  // get the newest table schema version
5921
  code = metaGetTbTSchemaEx(pMeta, *suid, uid, -1, pSchema);
313✔
5922
  return code;
313✔
5923
}
5924

5925
int32_t tsdbTakeReadSnap2(STsdbReader* pReader, _query_reseek_func_t reseek, STsdbReadSnap** ppSnap, const char* id) {
4,938,068✔
5926
  int32_t        code = 0;
4,938,068✔
5927
  STsdb*         pTsdb = pReader->pTsdb;
4,938,068✔
5928
  SVersionRange* pRange = &pReader->info.verRange;
4,938,068✔
5929
  int32_t        lino = 0;
4,938,068✔
5930
  *ppSnap = NULL;
4,938,068✔
5931

5932
  // lock
5933
  code = taosThreadMutexLock(&pTsdb->mutex);
4,938,068✔
5934
  if (code != TSDB_CODE_SUCCESS) {
4,945,360!
5935
    tsdbError("%s failed to lock tsdb, code:%s", id, tstrerror(code));
×
5936
    return code;
×
5937
  }
5938

5939
  // alloc
5940
  STsdbReadSnap* pSnap = (STsdbReadSnap*)taosMemoryCalloc(1, sizeof(STsdbReadSnap));
4,945,360✔
5941
  if (pSnap == NULL) {
4,945,089!
5942
    (void) taosThreadMutexUnlock(&pTsdb->mutex);
×
5943
    TSDB_CHECK_NULL(pSnap, code, lino, _exit, terrno);
×
5944
  }
5945

5946
  // take snapshot
5947
  if (pTsdb->mem && (pRange->minVer <= pTsdb->mem->maxVer && pRange->maxVer >= pTsdb->mem->minVer)) {
4,945,089!
5948
    pSnap->pMem = pTsdb->mem;
4,314,551✔
5949
    pSnap->pNode = taosMemoryMalloc(sizeof(*pSnap->pNode));
4,314,551✔
5950
    if (pSnap->pNode == NULL) {
4,314,226!
5951
      (void) taosThreadMutexUnlock(&pTsdb->mutex);
×
5952
      TSDB_CHECK_NULL(pSnap->pNode, code, lino, _exit, terrno);
×
5953
    }
5954

5955
    pSnap->pNode->pQHandle = pReader;
4,314,226✔
5956
    pSnap->pNode->reseek = reseek;
4,314,226✔
5957

5958
    code = tsdbRefMemTable(pTsdb->mem, pSnap->pNode);
4,314,226✔
5959
    TSDB_CHECK_CODE(code, lino, _exit);
4,314,248!
5960
  }
5961

5962
  if (pTsdb->imem && (pRange->minVer <= pTsdb->imem->maxVer && pRange->maxVer >= pTsdb->imem->minVer)) {
4,944,786!
5963
    pSnap->pIMem = pTsdb->imem;
13,590✔
5964
    pSnap->pINode = taosMemoryMalloc(sizeof(*pSnap->pINode));
13,590✔
5965
    if (pSnap->pINode == NULL) {
13,592!
5966
      code = terrno;
×
5967

5968
      if (pTsdb->mem && pSnap->pNode) {
×
5969
        tsdbUnrefMemTable(pTsdb->mem, pSnap->pNode, true);  // unref the previous refed mem
×
5970
      }
5971

5972
      (void) taosThreadMutexUnlock(&pTsdb->mutex);
×
5973
      goto _exit;
×
5974
    }
5975

5976
    pSnap->pINode->pQHandle = pReader;
13,592✔
5977
    pSnap->pINode->reseek = reseek;
13,592✔
5978

5979
    code = tsdbRefMemTable(pTsdb->imem, pSnap->pINode);
13,592✔
5980
    TSDB_CHECK_CODE(code, lino, _exit);
13,592!
5981
  }
5982

5983
  // fs
5984
  code = tsdbFSCreateRefSnapshotWithoutLock(pTsdb->pFS, &pSnap->pfSetArray);
4,944,788✔
5985
  if (code) {
4,942,927!
5986
    if (pSnap->pNode) {
×
5987
      tsdbUnrefMemTable(pTsdb->mem, pSnap->pNode, true);  // unref the previous refed mem
×
5988
    }
5989

5990
    if (pSnap->pINode) {
×
5991
      tsdbUnrefMemTable(pTsdb->imem, pSnap->pINode, true);
×
5992
    }
5993

5994
    (void) taosThreadMutexUnlock(&pTsdb->mutex);
×
5995
    TSDB_CHECK_CODE(code, lino, _exit);
×
5996
  }
5997

5998
  // unlock
5999
  (void) taosThreadMutexUnlock(&pTsdb->mutex);
4,942,927✔
6000
  *ppSnap = pSnap;
4,945,181✔
6001

6002
  tsdbTrace("%s vgId:%d, take read snapshot", id, TD_VID(pTsdb->pVnode));
4,945,181✔
6003
  return code;
4,945,401✔
6004

6005
_exit:
×
6006
  tsdbError("%s vgId:%d take read snapshot failed, line:%d code:%s", id, TD_VID(pTsdb->pVnode), lino, tstrerror(code));
×
6007

6008
  if (pSnap) {
×
6009
    if (pSnap->pNode) taosMemoryFree(pSnap->pNode);
×
6010
    if (pSnap->pINode) taosMemoryFree(pSnap->pINode);
×
6011
    taosMemoryFree(pSnap);
×
6012
  }
6013
  return code;
×
6014
}
6015

6016
void tsdbUntakeReadSnap2(STsdbReader* pReader, STsdbReadSnap* pSnap, bool proactive) {
4,945,216✔
6017
  STsdb* pTsdb = pReader->pTsdb;
4,945,216✔
6018

6019
  if (pSnap) {
4,945,216!
6020
    if (pSnap->pMem) {
4,945,366✔
6021
      tsdbUnrefMemTable(pSnap->pMem, pSnap->pNode, proactive);
4,314,797✔
6022
    }
6023

6024
    if (pSnap->pIMem) {
4,945,419✔
6025
      tsdbUnrefMemTable(pSnap->pIMem, pSnap->pINode, proactive);
13,593✔
6026
    }
6027

6028
    if (pSnap->pNode) taosMemoryFree(pSnap->pNode);
4,945,419✔
6029
    if (pSnap->pINode) taosMemoryFree(pSnap->pINode);
4,945,492✔
6030

6031
    tsdbFSDestroyRefSnapshot(&pSnap->pfSetArray);
4,945,492✔
6032

6033
    taosMemoryFree(pSnap);
4,945,466✔
6034
  }
6035
  tsdbTrace("vgId:%d, untake read snapshot", TD_VID(pTsdb->pVnode));
4,945,579✔
6036
}
4,945,579✔
6037

6038
// if failed, do nothing
6039
int32_t tsdbReaderSetId(void* p, const char* idstr) {
960✔
6040
  STsdbReader* pReader = (STsdbReader*) p;
960✔
6041
  taosMemoryFreeClear(pReader->idStr);
960!
6042

6043
  pReader->idStr = taosStrdup(idstr);
960✔
6044
  if (pReader->idStr == NULL) {
960!
6045
    tsdbError("%s failed to build reader id, code:%s", idstr, tstrerror(terrno));
×
6046
    return terrno;
×
6047
  }
6048

6049
  pReader->status.fileIter.pSttBlockReader->mergeTree.idStr = pReader->idStr;
960✔
6050
  return 0;
960✔
6051
}
6052

6053
void tsdbReaderSetCloseFlag(STsdbReader* pReader) { /*pReader->code = TSDB_CODE_TSC_QUERY_CANCELLED;*/ }
80✔
6054

6055
void tsdbSetFilesetDelimited(STsdbReader* pReader) { pReader->bFilesetDelimited = true; }
1,993,765✔
6056

6057
void tsdbReaderSetNotifyCb(STsdbReader* pReader, TsdReaderNotifyCbFn notifyFn, void* param) {
1,994,393✔
6058
  pReader->notifyFn = notifyFn;
1,994,393✔
6059
  pReader->notifyParam = param;
1,994,393✔
6060
}
1,994,393✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc