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

taosdata / TDengine / #3528

13 Nov 2024 02:14AM UTC coverage: 60.905% (+0.09%) from 60.819%
#3528

push

travis-ci

web-flow
Merge pull request #28748 from taosdata/test/chr-3.0-TD14758

test:add docs ci in jenkinsfile2

118800 of 249004 branches covered (47.71%)

Branch coverage included in aggregate %.

199361 of 273386 relevant lines covered (72.92%)

14738389.65 hits per line

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

71.4
/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,464✔
93
  if (p2 == NULL) {
1,526,909,777!
94
    return 1;
357,126,802✔
95
  }
96

97
  if (p1 == NULL) {
1,672,360,723!
98
    return -1;
×
99
  }
100

101
  if (p1->ts < p2->ts) {
1,672,360,723!
102
    return -1;
1,036,043,047✔
103
  } else if (p1->ts > p2->ts) {
636,317,676!
104
    return 1;
247,357,192✔
105
  }
106

107
  if (p1->numOfPKs == 0) {
388,960,484!
108
    return 0;
380,143,484✔
109
  } else {
110
    return tRowKeyCompare(p1, p2);
8,817,000✔
111
  }
112
}
113

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

119
  pKey->numOfPKs = 1;
57,673,048✔
120
  pKey->pks[0].type = cv.value.type;
57,673,048✔
121

122
  if (IS_NUMERIC_TYPE(cv.value.type)) {
57,673,048!
123
    pKey->pks[0].val = cv.value.val;
55,512,801✔
124
  } else {
125
    pKey->pks[0].nData = cv.value.nData;
2,160,247✔
126
    (void)memcpy(pKey->pks[0].pData, cv.value.pData, cv.value.nData);
2,160,247✔
127
  }
128
}
57,673,048✔
129

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

138
static void tRowGetPrimaryKeyDeepCopy(SRow* pRow, SRowKey* pKey) {
21,643,150✔
139
  SPrimaryKeyIndex indices[TD_MAX_PK_COLS];
140

141
  uint8_t* data = pRow->data;
21,643,150✔
142
  for (int32_t i = 0; i < pRow->numOfPKs; i++) {
43,275,706✔
143
    data += tGetPrimaryKeyIndex(data, &indices[i]);
21,644,936✔
144
  }
145

146
  // primary keys
147
  for (int32_t i = 0; i < pRow->numOfPKs; i++) {
43,304,306✔
148
    pKey->pks[i].type = indices[i].type;
21,673,536✔
149

150
    uint8_t* tdata = data + indices[i].offset;
21,673,536✔
151
    if (pRow->flag >> 4) {
21,673,536✔
152
      tdata += tGetI16v(tdata, NULL);
6,900,692✔
153
    }
154

155
    if (IS_VAR_DATA_TYPE(indices[i].type)) {
21,673,536!
156
      tdata += tGetU32v(tdata, &pKey->pks[i].nData);
2,042,700!
157
      (void)memcpy(pKey->pks[i].pData, tdata, pKey->pks[i].nData);
2,042,700✔
158
    } else {
159
      (void)memcpy(&pKey->pks[i].val, data + indices[i].offset, tDataTypes[pKey->pks[i].type].bytes);
19,630,836✔
160
    }
161
  }
162
}
21,630,770✔
163

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

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

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

181
  pSupInfo->slotId = (int16_t*)((char*)pSupInfo->colId + (sizeof(int16_t) * numOfCols));
5,094,670✔
182
  pSupInfo->buildBuf = (char**)((char*)pSupInfo->slotId + (sizeof(int16_t) * numOfCols));
5,094,670✔
183
  for (int32_t i = 0; i < numOfCols; ++i) {
31,377,712✔
184
    pSupInfo->colId[i] = pCols[i].colId;
26,272,116✔
185
    pSupInfo->slotId[i] = pSlotIdList[i];
26,272,116✔
186

187
    if (IS_VAR_DATA_TYPE(pCols[i].type)) {
26,272,116!
188
      pSupInfo->buildBuf[i] = taosMemoryMalloc(pCols[i].bytes);
3,599,262✔
189
      if (pSupInfo->buildBuf[i] == NULL) {
3,610,067!
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;
22,672,854✔
195
    }
196

197
    if (pCols[i].pk) {
26,283,042✔
198
      pSupInfo->pk = pCols[i];
267,506✔
199
      pSupInfo->pkSrcSlot = i - 1;
267,506✔
200
      pSupInfo->pkDstSlot = pSlotIdList[i];
267,506✔
201
      pSupInfo->numOfPks += 1;
267,506✔
202
    }
203
  }
204

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

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

211
  while (i < pSchema->numOfCols && j < pSupInfo->numOfCols) {
62,623,419✔
212
    STColumn* pTCol = &pSchema->columns[i];
57,614,090✔
213
    if (pTCol->colId == pSupInfo->colId[j]) {
57,614,090✔
214
      if (!IS_BSMA_ON(pTCol) && (PRIMARYKEY_TIMESTAMP_COL_ID != pTCol->colId)) {
25,673,836✔
215
        pSupInfo->smaValid = false;
32,585✔
216
        return TSDB_CODE_SUCCESS;
32,585✔
217
      }
218

219
      i += 1;
25,641,251✔
220
      j += 1;
25,641,251✔
221
    } else if (pTCol->colId < pSupInfo->colId[j]) {  // do nothing
31,940,254!
222
      i += 1;
31,946,387✔
223
    } else {
224
      return TSDB_CODE_TDB_INVALID_TABLE_SCHEMA_VER;
×
225
    }
226
  }
227

228
  return TSDB_CODE_SUCCESS;
5,009,329✔
229
}
230

231
static bool isEmptyQueryTimeWindow(STimeWindow* pWindow) { return pWindow->skey > pWindow->ekey; }
19,567,997✔
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,113,300✔
236
  int64_t     earlyTs = tsdbGetEarliestTs(pTsdb);
5,113,300✔
237
  STimeWindow win = *pWindow;
5,117,901✔
238
  if (win.skey < earlyTs) {
5,117,901✔
239
    win.skey = earlyTs;
2,979,950✔
240
  }
241

242
  return win;
5,117,901✔
243
}
244

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

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

257
  if (pIter->pSttBlockReader == NULL) {
4,931,540✔
258
    pIter->pSttBlockReader = taosMemoryCalloc(1, sizeof(struct SSttBlockReader));
4,913,288✔
259
    if (pIter->pSttBlockReader == NULL) {
4,910,854!
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,929,106✔
266
  pSttReader->order = pReader->info.order;
4,929,106✔
267
  pSttReader->window = pReader->info.window;
4,929,106✔
268
  pSttReader->verRange = pReader->info.verRange;
4,929,106✔
269
  pSttReader->numOfPks = pReader->suppInfo.numOfPks;
4,929,106✔
270
  pSttReader->uid = 0;
4,929,106✔
271

272
  tMergeTreeClose(&pSttReader->mergeTree);
4,929,106✔
273
  code = initRowKey(&pSttReader->currentKey, INT64_MIN, pInfo->numOfPks, pInfo->pk.type, pInfo->pk.bytes, asc);
4,932,511✔
274
  if (code != TSDB_CODE_SUCCESS) {
4,933,843!
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,933,843✔
278
  }
279

280
  return code;
4,933,652✔
281
}
282

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

288
  pIter->index += step;
8,802,695✔
289
  if ((asc && pIter->index >= pIter->numOfFiles) || ((!asc) && pIter->index < 0)) {
8,802,695✔
290
    *hasNext = false;
1,385,465✔
291
    return TSDB_CODE_SUCCESS;
1,385,465✔
292
  }
293

294
  SReadCostSummary* pCost = &pReader->cost;
7,417,230✔
295

296
  pIter->pSttBlockReader->uid = 0;
7,417,230✔
297
  tMergeTreeClose(&pIter->pSttBlockReader->mergeTree);
7,417,230✔
298
  destroySttBlockReader(pReader->status.pLDataIterArray, &pCost->sttCost);
7,419,626✔
299

300
  pReader->status.pLDataIterArray = taosArrayInit(4, POINTER_BYTES);
7,421,396✔
301
  if (pReader->status.pLDataIterArray == NULL) {
7,422,346!
302
    return terrno;
×
303
  }
304

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

308
  while (1) {
697,306✔
309
    if (pReader->pFileReader != NULL) {
8,119,652✔
310
      tsdbDataFileReaderClose(&pReader->pFileReader);
125,140✔
311
    }
312

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

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

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

321
      if (pFileObj[0] != NULL) {
141,063✔
322
        conf.files[0].file = *pFileObj[0]->f;
131,621✔
323
        conf.files[0].exist = true;
131,621✔
324
        filesName[0] = pFileObj[0]->fname;
131,621✔
325

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

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

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

341
      code = tsdbDataFileReaderOpen(filesName, &conf, &pReader->pFileReader);
141,063✔
342
      if (code != TSDB_CODE_SUCCESS) {
140,099!
343
        goto _err;
×
344
      }
345

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

349
    int32_t fid = pReader->status.pCurrentFileset->fid;
8,118,693✔
350
    tsdbFidKeyRange(fid, pReader->pTsdb->keepCfg.days, pReader->pTsdb->keepCfg.precision, &win.skey, &win.ekey);
8,118,693✔
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,116,211✔
354
      tsdbDebug("%p remain files are not qualified for qrange:%" PRId64 "-%" PRId64 ", ignore, %s", pReader,
587,247✔
355
                pReader->info.window.skey, pReader->info.window.ekey, pReader->idStr);
356
      *hasNext = false;
587,732✔
357
      return TSDB_CODE_SUCCESS;
587,732✔
358
    }
359

360
    if ((asc && (win.ekey < pReader->info.window.skey)) || ((!asc) && (win.skey > pReader->info.window.ekey))) {
7,528,964✔
361
      pIter->index += step;
907,330✔
362
      if ((asc && pIter->index >= pIter->numOfFiles) || ((!asc) && pIter->index < 0)) {
907,330✔
363
        *hasNext = false;
210,024✔
364
        return TSDB_CODE_SUCCESS;
210,024✔
365
      }
366
      continue;
697,306✔
367
    }
368

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

372
    *hasNext = true;
6,621,406✔
373
    return TSDB_CODE_SUCCESS;
6,621,406✔
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); }
16,761,843!
382

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

388
  if (pIter->blockList == NULL) {
11,545,739✔
389
    pIter->blockList = taosArrayInit(4, sizeof(SFileDataBlockInfo));
4,912,023✔
390
    if (pIter->blockList == NULL) {
4,910,231!
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);
6,633,716✔
396
  }
397

398
  return TSDB_CODE_SUCCESS;
11,545,980✔
399
}
400

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

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

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

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

425
  code = blockDataEnsureCapacity(pBlock, capacity);
2,524✔
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,081,085✔
435
  int32_t code = taosThreadMutexInit(&pReader->readerMutex, NULL);
5,081,085✔
436
  tsdbTrace("tsdb/read: %p, post-init read mutex: %p, code: %d", pReader, &pReader->readerMutex, code);
5,086,560✔
437

438
  return code;
5,088,823✔
439
}
440

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

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

448
  return code;
5,098,967✔
449
}
450

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

455
  code = taosThreadMutexLock(&pReader->readerMutex);
19,573,760✔
456
  if (code != 0) {
19,584,863!
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);
19,584,863✔
460
  }
461

462
  return code;
19,582,591✔
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) {
19,579,981✔
476
  int32_t code = taosThreadMutexUnlock(&pReader->readerMutex);
19,579,981✔
477
  if (code != TSDB_CODE_SUCCESS) {
19,588,498!
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);
19,588,498✔
481
  }
482
  return code;
19,586,704✔
483
}
484

485
void tsdbReleaseDataBlock2(STsdbReader* pReader) {
343,985✔
486
  SReaderStatus* pStatus = &pReader->status;
343,985✔
487
  if (!pStatus->composedDataBlock) {
343,985✔
488
    (void) tsdbReleaseReader(pReader);
107,526✔
489
  }
490
}
344,143✔
491

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

498
  if (pResBlockInfo->pResBlock == NULL) {
5,085,774✔
499
    pResBlockInfo->freeBlock = true;
2,527✔
500
    pResBlockInfo->pResBlock = NULL;
2,527✔
501

502
    code = createResBlock(pCond, pResBlockInfo->capacity, &pResBlockInfo->pResBlock);
2,527✔
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,139✔
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,083,247✔
530
  }
531

532
  return code;
5,083,636✔
533
}
534

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

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

549
  initReaderStatus(&pReader->status);
5,091,515✔
550
  getTsdbByRetentions(pVnode, pCond, pVnode->config.tsdbCfg.retentions, idstr, &level, &pReader->pTsdb);
5,094,179✔
551

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

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

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

567
  if (pCond->numOfCols <= 0) {
5,092,784!
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,092,784✔
575
  pSup->tsColAgg.colId = PRIMARYKEY_TIMESTAMP_COL_ID;
5,092,784✔
576
  code = setColumnIdSlotList(pSup, pCond->colList, pCond->pSlotList, pCond->numOfCols);
5,092,784✔
577
  if (code != TSDB_CODE_SUCCESS) {
5,095,151!
578
    goto _end;
×
579
  }
580

581
  code = initResBlockInfo(&pReader->resBlockInfo, capacity, pResBlock, pCond, pSup);
5,095,151✔
582
  if (code != TSDB_CODE_SUCCESS) {
5,083,823!
583
    goto _end;
×
584
  }
585

586
  code = tBlockDataCreate(&pReader->status.fileBlockData);
5,083,823✔
587
  if (code != TSDB_CODE_SUCCESS) {
5,081,670!
588
    goto _end;
×
589
  }
590

591
  if (pReader->suppInfo.colId[0] != PRIMARYKEY_TIMESTAMP_COL_ID) {
5,081,670!
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,081,670✔
598
  if (pReader->status.pPrimaryTsCol == NULL) {
5,081,570!
599
    code = terrno;
×
600
    goto _end;
×
601
  }
602

603
  int32_t type = pReader->status.pPrimaryTsCol->info.type;
5,085,780✔
604
  if (type != TSDB_DATA_TYPE_TIMESTAMP) {
5,085,780!
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,085,780✔
612
  if (code != TSDB_CODE_SUCCESS) {
5,089,143!
613
    goto _end;
×
614
  }
615

616
  code = tsem_init(&pReader->resumeAfterSuspend, 0, 0);
5,089,143✔
617
  if (code != TSDB_CODE_SUCCESS) {
5,084,743!
618
    goto _end;
×
619
  }
620

621
  *ppReader = pReader;
5,084,743✔
622
  return code;
5,084,743✔
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) {
6,619,383✔
631
  int64_t st = taosGetTimestampUs();
6,621,626✔
632
  int32_t numOfTables = tSimpleHashGetSize(pReader->status.pTableMap);
6,621,626✔
633
  if (pFileReader == NULL) {
6,621,590✔
634
    return TSDB_CODE_SUCCESS;
6,482,117✔
635
  }
636

637
  const TBrinBlkArray* pBlkArray = NULL;
139,473✔
638

639
  int32_t code = tsdbDataFileReadBrinBlk(pFileReader, &pBlkArray);
139,473✔
640
  if (code != TSDB_CODE_SUCCESS) {
139,802!
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();
139,852✔
663

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

667
  int32_t i = 0;
139,852✔
668
  while (i < TARRAY2_SIZE(pBlkArray)) {
268,962✔
669
    pBrinBlk = &pBlkArray->data[i];
131,490✔
670
    if (pBrinBlk->maxTbid.suid < pReader->info.suid) {
131,490✔
671
      i += 1;
1,430✔
672
      continue;
1,430✔
673
    }
674

675
    if (pBrinBlk->minTbid.suid > pReader->info.suid) {  // not include the queried table/super table, quit the loop
130,060✔
676
      break;
1,858✔
677
    }
678

679
    if (!(pBrinBlk->minTbid.suid <= pReader->info.suid && pBrinBlk->maxTbid.suid >= pReader->info.suid)) {
128,202!
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]) {
128,232✔
684
      i += 1;
1,934✔
685
      continue;
1,934✔
686
    }
687

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

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

697
    i += 1;
125,746✔
698
  }
699

700
  int64_t et2 = taosGetTimestampUs();
139,908✔
701
  tsdbDebug("load block index for %d/%d tables completed, elapsed time:%.2f ms, set BrinBlk:%.2f ms, size:%.2f Kb %s",
139,908✔
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;
139,931✔
706

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

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

723
  // clear info for the new file
724
  cleanupInfoForNextFileset(pReader->status.pTableMap);
6,619,877✔
725
  initBrinRecordIter(&iter, pReader->pFileReader, pIndexList);
6,620,946✔
726

727
  while (1) {
1,165,135✔
728
    int32_t code = getNextBrinRecord(&iter, &pRecord);
7,785,376✔
729
    if (code != TSDB_CODE_SUCCESS) {
7,785,906!
730
      clearBrinBlockIter(&iter);
×
731
      return code;
×
732
    }
733

734
    if (pRecord == NULL) {
7,786,468✔
735
      break;
6,611,393✔
736
    }
737

738
    if (pRecord->suid > pReader->info.suid) {
1,175,075✔
739
      break;
5,193✔
740
    }
741

742
    uint64_t uid = pReader->status.uidList.tableUidList[k];
1,169,882✔
743
    if (pRecord->suid < pReader->info.suid) {
1,169,882✔
744
      continue;
506,012✔
745
    }
746

747
    if (uid < pRecord->uid) {  // forward the table uid index
1,164,661✔
748
      while (k < numOfTables && pReader->status.uidList.tableUidList[k] < pRecord->uid) {
584,027✔
749
        k += 1;
294,926✔
750
      }
751

752
      if (k >= numOfTables) {
289,101✔
753
        break;
4,291✔
754
      }
755

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

759
    if (pRecord->uid < uid) {
1,160,370✔
760
      continue;
448,645✔
761
    }
762

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

769
    STableBlockScanInfo* pScanInfo = NULL;
711,743✔
770
    code = getTableBlockScanInfo(pReader->status.pTableMap, uid, &pScanInfo, pReader->idStr);
711,743✔
771
    if (code != TSDB_CODE_SUCCESS) {
710,956!
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) {
710,980✔
779
      w.skey = pScanInfo->lastProcKey.ts;
665,065✔
780
    } else {
781
      w.ekey = pScanInfo->lastProcKey.ts;
45,915✔
782
    }
783

784
    // NOTE: specialized for open interval
785
    if (((w.skey < INT64_MAX) && ((w.skey + 1) > w.ekey)) || (w.skey == INT64_MAX)) {
710,980!
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) {
711,006✔
796
      continue;
52,222✔
797
    }
798

799
    if (asc) {
658,784✔
800
      if (pkCompEx(&pRecord->lastKey.key, &pScanInfo->lastProcKey) <= 0) {
1,285,419!
801
        continue;
3✔
802
      }
803
    } else {
804
      if (pkCompEx(&pRecord->firstKey.key, &pScanInfo->lastProcKey) >= 0) {
31,961!
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) {
658,593!
811
      continue;
×
812
    }
813

814
    if (pScanInfo->pBlockList == NULL) {
658,646✔
815
      pScanInfo->pBlockList = taosArrayInit(4, sizeof(SFileDataBlockInfo));
404,285✔
816
      if (pScanInfo->pBlockList == NULL) {
404,677!
817
        clearBrinBlockIter(&iter);
×
818
        return terrno;
×
819
      }
820
    }
821

822
    if (pScanInfo->pBlockIdxList == NULL) {
659,038✔
823
      pScanInfo->pBlockIdxList = taosArrayInit(4, sizeof(STableDataBlockIdx));
123,252✔
824
      if (pScanInfo->pBlockIdxList == NULL) {
123,329!
825
        clearBrinBlockIter(&iter);
×
826
        return terrno;
×
827
      }
828
    }
829

830
    SFileDataBlockInfo blockInfo = {.tbBlockIdx = TARRAY_SIZE(pScanInfo->pBlockList)};
659,115✔
831
    code = recordToBlockInfo(&blockInfo, pRecord);
659,115✔
832
    if (code != TSDB_CODE_SUCCESS) {
660,439!
833
      clearBrinBlockIter(&iter);
×
834
      return code;
×
835
    }
836
    void* p1 = taosArrayPush(pScanInfo->pBlockList, &blockInfo);
660,439✔
837
    if (p1 == NULL) {
660,168!
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) {
660,168✔
844
      pScanInfo->filesetWindow.skey = pRecord->firstKey.key.ts;
404,647✔
845
    }
846

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

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

862
      if ((*p)->uid != uid) {
539,389✔
863
        p1 = taosArrayPush(pTableScanInfoList, &pScanInfo);
284,718✔
864
      }
865
    }
866

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

873
  clearBrinBlockIter(&iter);
6,620,877✔
874

875
  pBlockNum->numOfSttFiles = pReader->status.pCurrentFileset->lvlArr->size;
6,615,003✔
876
  int32_t total = pBlockNum->numOfSttFiles + pBlockNum->numOfBlocks;
6,615,003✔
877

878
  double el = (taosGetTimestampUs() - st) / 1000.0;
6,618,101✔
879
  tsdbDebug(
6,618,101✔
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;
6,618,359✔
886
  pReader->cost.headFileLoadTime += el;
6,618,359✔
887

888
  return TSDB_CODE_SUCCESS;
6,618,359✔
889
}
890

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

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

903
  if (IS_NUMERIC_TYPE(pKey->pks[0].type)) {
226,538!
904
    pKey->pks[0].val = asc ? pBlockInfo->lastPk.val : pBlockInfo->firstPk.val;
226,538!
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)) {
618,183,503✔
918
      colDataSetNULL(pColInfoData, rowIndex);
116,041,107✔
919
    } else {
920
      varDataSetLen(pSup->buildBuf[colIndex], pColVal->value.nData);
502,142,396✔
921
      if ((pColVal->value.nData + VARSTR_HEADER_SIZE) > pColInfoData->info.bytes) {
502,142,396✔
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
502,142,392!
928
        (void)memcpy(varDataVal(pSup->buildBuf[colIndex]), pColVal->value.pData, pColVal->value.nData);
568,943,052✔
929
      }
930

931
      code = colDataSetVal(pColInfoData, rowIndex, pSup->buildBuf[colIndex], false);
502,142,392✔
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) {
9,528,722✔
941
  *pInfo = NULL;
9,528,722✔
942

943
  if (pBlockIter->blockList == NULL) {
9,528,722!
944
    return TSDB_CODE_FAILED;
×
945
  }
946

947
  size_t num = TARRAY_SIZE(pBlockIter->blockList);
9,528,722✔
948
  if (num == 0) {
9,528,722✔
949
    if (num != pBlockIter->numOfBlocks) {
6,496,027!
950
      tsdbError("tsdb read failed at: %s:%d %s", __func__, __LINE__, id);
×
951
    }
952
    return TSDB_CODE_FAILED;
6,496,396✔
953
  }
954

955
  *pInfo = taosArrayGet(pBlockIter->blockList, pBlockIter->index);
3,032,695✔
956
  return (*pInfo) != NULL? TSDB_CODE_SUCCESS:TSDB_CODE_FAILED;
3,036,896!
957
}
958

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

964
  // check
965
  if (!(pos >= 0 && pos < num && num > 0)) {
2,018!
966
    return -1;
×
967
  }
968
  if (order == TSDB_ORDER_ASC) {
2,019✔
969
    // find the first position which is smaller than the key
970
    e = num - 1;
1,988✔
971
    if (key < keyList[pos]) return -1;
1,988✔
972
    while (1) {
23,736✔
973
      // check can return
974
      if (key >= keyList[e]) return e;
25,721!
975
      if (key <= keyList[s]) return s;
25,721✔
976
      if (e - s <= 1) return s;
25,717✔
977

978
      // change start or end position
979
      int mid = s + (e - s + 1) / 2;
23,736✔
980
      if (keyList[mid] > key)
23,736✔
981
        e = mid;
14,762✔
982
      else if (keyList[mid] < key)
8,974!
983
        s = mid;
8,974✔
984
      else
985
        return mid;
×
986
    }
987
  } else {  // DESC
988
    // find the first position which is bigger than the key
989
    e = 0;
31✔
990
    if (key > keyList[pos]) return -1;
31!
991
    while (1) {
357✔
992
      // check can return
993
      if (key <= keyList[e]) return e;
388!
994
      if (key >= keyList[s]) return s;
388!
995
      if (s - e <= 1) return s;
388✔
996

997
      // change start or end position
998
      int mid = s - (s - e + 1) / 2;
358✔
999
      if (keyList[mid] < key)
358✔
1000
        e = mid;
227✔
1001
      else if (keyList[mid] > key)
131✔
1002
        s = mid;
130✔
1003
      else
1004
        return mid;
1✔
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) {
2,016✔
1011
  int32_t i = startPos;
2,016✔
1012
  int64_t startTs = pTsList[startPos];
2,016✔
1013
  if (asc) {
2,016✔
1014
    while (i < num && (pTsList[i] == startTs)) {
3,970!
1015
      i++;
1,985✔
1016
    }
1017
    return i - 1;
1,985✔
1018
  } else {
1019
    while (i >= 0 && (pTsList[i] == startTs)) {
62!
1020
      i--;
31✔
1021
    }
1022
    return i + 1;
31✔
1023
  }
1024
}
1025

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

1031
  if (asc && pReader->info.window.ekey >= pRecord->lastKey.key.ts) {
506,153✔
1032
    endPos = pRecord->numRow - 1;
503,733✔
1033
  } else if (!asc && pReader->info.window.skey <= pRecord->firstKey.key.ts) {
2,420✔
1034
    endPos = 0;
1,556✔
1035
  } else {
1036
    int64_t key = asc ? pReader->info.window.ekey : pReader->info.window.skey;
864!
1037
    endPos = doBinarySearchKey(pBlockData->aTSKEY, pRecord->numRow, pos, key, pReader->info.order);
864✔
1038
    if (endPos == -1) {
1,009!
1039
      return endPos;
×
1040
    }
1041

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

1045
  if ((pReader->info.verRange.maxVer >= pRecord->minVer && pReader->info.verRange.maxVer < pRecord->maxVer) ||
506,261!
1046
      (pReader->info.verRange.minVer <= pRecord->maxVer && pReader->info.verRange.minVer > pRecord->minVer)) {
506,270!
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;
506,261✔
1067
}
1068

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

1077
    // todo: opt perf by extract the loop
1078
    // reverse the array list
1079
    int32_t  mid = dumpedRows >> 1u;
1,557✔
1080
    int64_t* pts = (int64_t*)pColData->pData;
1,557✔
1081
    for (int32_t j = 0; j < mid; ++j) {
168,697✔
1082
      int64_t t = pts[j];
167,140✔
1083
      pts[j] = pts[dumpedRows - j - 1];
167,140✔
1084
      pts[dumpedRows - j - 1] = t;
167,140✔
1085
    }
1086
  }
1087
}
506,240✔
1088

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

1100
  int32_t step = asc ? 1 : -1;
923,538✔
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);
923,538✔
1106

1107
  // 2. reverse the array list in case of descending order scan data block
1108
  if (!asc) {
923,538✔
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) {
28,866✔
1117
          int64_t t = pts[j];
28,851✔
1118
          pts[j] = pts[dumpedRows - j - 1];
28,851✔
1119
          pts[dumpedRows - j - 1] = t;
28,851✔
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) {
28,866✔
1130
          int8_t t = pts[j];
28,851✔
1131
          pts[j] = pts[dumpedRows - j - 1];
28,851✔
1132
          pts[dumpedRows - j - 1] = t;
28,851✔
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) {
19,244✔
1142
          int64_t t = pts[j];
19,234✔
1143
          pts[j] = pts[dumpedRows - j - 1];
19,234✔
1144
          pts[dumpedRows - j - 1] = t;
19,234✔
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) {
28,866✔
1155
          int32_t t = pts[j];
28,851✔
1156
          pts[j] = pts[dumpedRows - j - 1];
28,851✔
1157
          pts[dumpedRows - j - 1] = t;
28,851✔
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) {
923,538✔
1166
    int32_t rowIndex = 0;
30,884✔
1167

1168
    for (int32_t j = pDumpInfo->rowIndex; rowIndex < dumpedRows; j += step, rowIndex++) {
125,466,069✔
1169
      uint8_t v = tColDataGetBitValue(pData, j);
125,435,185✔
1170
      if (v == 0 || v == 1) {
125,435,185✔
1171
        colDataSetNull_f(pColData->nullbitmap, rowIndex);
12,545,398✔
1172
        pColData->hasNull = true;
12,545,398✔
1173
      }
1174
    }
1175
  }
1176
}
923,538✔
1177

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

1183
  if (pSupp->numOfPks > 0) {
2,155,775✔
1184
    SValue* pFirst = &record->firstKey.key.pks[0];
836,681✔
1185
    SValue* pLast = &record->lastKey.key.pks[0];
836,681✔
1186

1187
    pFirst->type = pSupp->pk.type;
836,681✔
1188
    pLast->type = pSupp->pk.type;
836,681✔
1189

1190
    if (IS_VAR_DATA_TYPE(pFirst->type)) {
836,681!
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;
836,839✔
1198
      pLast->val = pBlockInfo->lastPk.val;
836,839✔
1199
    }
1200
  }
1201

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

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

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

1228
  code = getCurrentBlockInfo(pBlockIter, &pBlockInfo, pReader->idStr);
506,274✔
1229
  if (code != TSDB_CODE_SUCCESS) {
506,205!
1230
    return code;
×
1231
  }
1232

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

1238
  // no data exists, return directly.
1239
  if (pBlockData->nRow == 0 || pBlockData->aTSKEY == 0) {
506,125!
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))) {
506,238!
1248
    if (asc && pReader->info.window.skey <= pRecord->firstKey.key.ts &&
505,464!
1249
        pReader->info.verRange.minVer <= pRecord->minVer) {
503,862!
1250
      // pDumpInfo->rowIndex = 0;
1251
    } else if (!asc && pReader->info.window.ekey >= pRecord->lastKey.key.ts &&
1,590✔
1252
               pReader->info.verRange.maxVer >= pRecord->maxVer) {
580!
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;
1,010✔
1256
      int32_t order = asc ? TSDB_ORDER_DESC : TSDB_ORDER_ASC;
1,010✔
1257
      int64_t key = asc ? pReader->info.window.skey : pReader->info.window.ekey;
1,010✔
1258
      pDumpInfo->rowIndex = doBinarySearchKey(pBlockData->aTSKEY, pRecord->numRow, pos, key, order);
1,010✔
1259

1260
      if (pDumpInfo->rowIndex < 0) {
1,010✔
1261
        tsdbError(
3!
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;
3✔
1267
      }
1268

1269
      pDumpInfo->rowIndex = findFirstPos(pBlockData->aTSKEY, pRecord->numRow, pDumpInfo->rowIndex, (!asc));
1,007✔
1270
      if (!(pReader->info.verRange.minVer <= pRecord->maxVer && pReader->info.verRange.maxVer >= pRecord->minVer)) {
1,007!
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) ||
1,007!
1277
          (pReader->info.verRange.minVer <= pRecord->maxVer && pReader->info.verRange.minVer > pRecord->minVer)) {
1,007!
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);
506,235✔
1300
  if (endIndex == -1) {
506,243!
1301
    setBlockAllDumped(pDumpInfo, pReader->info.window.ekey, pReader->info.order);
×
1302
    return TSDB_CODE_SUCCESS;
×
1303
  }
1304

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

1314
  int32_t i = 0;
506,274✔
1315
  int32_t rowIndex = 0;
506,274✔
1316

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

1322
  if (pSupInfo->colId[i] == PRIMARYKEY_TIMESTAMP_COL_ID) {
506,268!
1323
    copyPrimaryTsCol(pBlockData, pDumpInfo, pColData, dumpedRows, asc);
506,283✔
1324
    i += 1;
506,073✔
1325
  }
1326

1327
  int32_t colIndex = 0;
506,058✔
1328
  int32_t num = pBlockData->nColData;
506,058✔
1329
  while (i < numOfOutputCols && colIndex < num) {
1,720,079!
1330
    rowIndex = 0;
1,213,842✔
1331

1332
    SColData* pData = tBlockDataGetColDataByIdx(pBlockData, colIndex);
1,213,842✔
1333
    if (pData->cid < pSupInfo->colId[i]) {
1,213,842!
1334
      colIndex += 1;
×
1335
    } else if (pData->cid == pSupInfo->colId[i]) {
1,213,842!
1336
      pColData = taosArrayGet(pResBlock->pDataBlock, pSupInfo->slotId[i]);
1,213,883✔
1337
      if (pColData == NULL) {
1,213,770!
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,213,770!
1342
        colDataSetNNULL(pColData, 0, dumpedRows);
85,140!
1343
      } else {
1344
        if (IS_MATHABLE_TYPE(pColData->info.type)) {
1,128,630!
1345
          copyNumericCols(pData, pDumpInfo, pColData, dumpedRows, asc);
923,358✔
1346
        } else {  // varchar/nchar type
1347
          for (int32_t j = pDumpInfo->rowIndex; rowIndex < dumpedRows; j += step) {
50,303,510✔
1348
            tColDataGetValue(pData, j, &cv);
50,103,055✔
1349
            code = doCopyColVal(pColData, rowIndex++, i, &cv, pSupInfo);
50,702,545✔
1350
            if (code) {
50,098,238!
1351
              return code;
×
1352
            }
1353
          }
1354
        }
1355
      }
1356

1357
      colIndex += 1;
1,214,021✔
1358
      i += 1;
1,214,021✔
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) {
506,237!
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;
506,237✔
1382
  pResBlock->info.rows = dumpedRows;
506,237✔
1383
  pDumpInfo->rowIndex += step * dumpedRows;
506,237✔
1384

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

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

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

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

1403
  int32_t unDumpedRows = asc ? pRecord->numRow - pDumpInfo->rowIndex : pDumpInfo->rowIndex + 1;
506,149✔
1404
  tsdbDebug("%p copy file block to sdatablock, global index:%d, table index:%d, brange:%" PRId64 "-%" PRId64
506,149✔
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;
506,197✔
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);
1✔
1420
  if (code != TSDB_CODE_SUCCESS || pReader->info.pSchema == NULL) {
1!
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);
1✔
1427
  if (code != TSDB_CODE_SUCCESS) {
1!
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;
1✔
1434
}
1435

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

1444
  tBlockDataReset(pBlockData);
529,617✔
1445

1446
  if (pReader->info.pSchema == NULL) {
529,641!
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);
529,641✔
1457
  if (code != TSDB_CODE_SUCCESS) {
529,681!
1458
    return code;
×
1459
  }
1460

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

1463
  SBrinRecord tmp;
1464
  blockInfoToRecord(&tmp, pBlockInfo, pSup);
529,681✔
1465
  SBrinRecord* pRecord = &tmp;
529,825✔
1466
  code = tsdbDataFileReadBlockDataByColumn(pReader->pFileReader, pRecord, pBlockData, pSchema, &pSup->colId[1],
529,825✔
1467
                                           pSup->numOfCols - 1);
529,825✔
1468
  if (code != TSDB_CODE_SUCCESS) {
529,902!
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;
529,848✔
1477

1478
  tsdbDebug("%p load file block into buffer, global index:%d, index in table block list:%d, brange:%" PRId64 "-%" PRId64
529,848✔
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;
529,898✔
1484
  pDumpInfo->allDumped = false;
529,898✔
1485

1486
  return code;
529,898✔
1487
}
1488

1489
/**
1490
 * This is an two rectangles overlap cases.
1491
 */
1492
static int32_t dataBlockPartiallyRequired(STimeWindow* pWindow, SVersionRange* pVerRange, SFileDataBlockInfo* pBlock) {
669,476✔
1493
  return (pWindow->ekey < pBlock->lastKey && pWindow->ekey >= pBlock->firstKey) ||
6,629✔
1494
         (pWindow->skey > pBlock->firstKey && pWindow->skey <= pBlock->lastKey) ||
662,850!
1495
         (pVerRange->minVer > pBlock->minVer && pVerRange->minVer <= pBlock->maxVer) ||
2,001,584!
1496
         (pVerRange->maxVer < pBlock->maxVer && pVerRange->maxVer >= pBlock->minVer);
662,632!
1497
}
1498

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

1505
  if (asc && pBlockInfo->tbBlockIdx >= taosArrayGetSize(pScanInfo->pBlockIdxList) - 1) {
693,200✔
1506
    return false;
397,158✔
1507
  }
1508

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

1513
  STableDataBlockIdx* pTableDataBlockIdx = taosArrayGet(pScanInfo->pBlockIdxList, pBlockInfo->tbBlockIdx + step);
279,867✔
1514
  if (pTableDataBlockIdx == NULL) {
280,090!
1515
    return TSDB_CODE_INVALID_PARA;
×
1516
  }
1517

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

1523
  blockInfoToRecord(pRecord, p, pSupInfo);
280,024✔
1524

1525
  *nextIndex = pBlockInfo->tbBlockIdx + step;
280,074✔
1526
  return true;
280,074✔
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,
280,073✔
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)) {
280,073✔
1613
    if (pBlock->lastKey == pRec->firstKey.key.ts) {
278,628!
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;
278,628✔
1627
    }
1628
  } else {
1629
    if (pBlock->firstKey == pRec->lastKey.key.ts) {
1,445!
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,445✔
1643
    }
1644
  }
1645
}
1646

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

1650
  int64_t key = 0;
611,279✔
1651
  if (pScanInfo->sttKeyInfo.status == STT_FILE_HAS_DATA) {
611,279✔
1652
    int64_t keyInStt = pScanInfo->sttKeyInfo.nextProcKey.ts;
16,533✔
1653
    key = ascScan ? TMIN(pBlock->firstKey, keyInStt) : TMAX(pBlock->lastKey, keyInStt);
16,533✔
1654
  } else {
1655
    key = ascScan ? pBlock->firstKey : pBlock->lastKey;
594,746✔
1656
  }
1657

1658
  return key;
611,279✔
1659
}
1660

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

1666
  return (ascScan && (keyInBuf.ts != TSKEY_INITIAL_VAL && keyInBuf.ts < key)) ||
1,222,491✔
1667
         (!ascScan && (keyInBuf.ts != TSKEY_INITIAL_VAL && keyInBuf.ts > key));
611,233✔
1668
}
1669

1670
static bool keyOverlapFileBlock(TSDBKEY key, SFileDataBlockInfo* pBlock, SVersionRange* pVerRange) {
669,417✔
1671
  return (key.ts >= pBlock->firstKey && key.ts <= pBlock->lastKey) && (pBlock->maxVer >= pVerRange->minVer) &&
683,683!
1672
         (pBlock->minVer <= pVerRange->maxVer);
14,266!
1673
}
1674

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

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

1685
  // overlap with neighbor
1686
  if (hasNeighbor) {
669,607✔
1687
    pInfo->overlapWithNeighborBlock =
266,889✔
1688
        overlapWithNeighborBlock2(pBlockInfo, &rec, order, pSupInfo->pk.type, pSupInfo->numOfPks);
266,895✔
1689
  }
1690

1691
  SBrinRecord pRecord;
1692
  blockInfoToRecord(&pRecord, pBlockInfo, pSupInfo);
669,601✔
1693

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

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

1704
  pInfo->moreThanCapcity = pBlockInfo->numRow > pReader->resBlockInfo.capacity;
669,499✔
1705
  pInfo->partiallyRequired = dataBlockPartiallyRequired(&pReader->info.window, &pReader->info.verRange, pBlockInfo);
669,499✔
1706
  pInfo->overlapWithKeyInBuf = keyOverlapFileBlock(keyInBuf, pBlockInfo, &pReader->info.verRange);
669,427✔
1707
}
669,419✔
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,
637,469✔
1716
                                TSDBKEY keyInBuf) {
1717
  SDataBlockToLoadInfo info = {0};
637,469✔
1718
  getBlockToLoadInfo(&info, pBlockInfo, pScanInfo, keyInBuf, pReader);
637,469✔
1719

1720
  bool loadDataBlock =
637,732✔
1721
      (info.overlapWithNeighborBlock || info.hasDupTs || info.partiallyRequired || info.overlapWithKeyInBuf ||
637,779!
1722
       info.moreThanCapcity || info.overlapWithDelInfo || info.overlapWithSttBlock);
1,275,511!
1723

1724
  // log the reason why load the datablock for profile
1725
  if (loadDataBlock) {
637,732✔
1726
    tsdbDebug("%p uid:%" PRIu64
26,559✔
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;
637,818✔
1735
}
1736

1737
static bool isCleanFileDataBlock(STsdbReader* pReader, SFileDataBlockInfo* pBlockInfo, STableBlockScanInfo* pScanInfo,
31,707✔
1738
                                 TSDBKEY keyInBuf) {
1739
  SDataBlockToLoadInfo info = {0};
31,707✔
1740
  getBlockToLoadInfo(&info, pBlockInfo, pScanInfo, keyInBuf, pReader);
31,707✔
1741
  bool isCleanFileBlock = !(info.overlapWithNeighborBlock || info.hasDupTs || info.overlapWithKeyInBuf ||
55,229!
1742
                            info.overlapWithDelInfo || info.overlapWithSttBlock);
23,520✔
1743
  return isCleanFileBlock;
31,709✔
1744
}
1745

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

1750
  if (pMerger->pArray == NULL) {
749,391,613✔
1751
    STSchema* ps = getTableSchemaImpl(pReader, uid);
1!
1752
    if (ps == NULL) {
1!
1753
      return terrno;
×
1754
    }
1755
  }
1756

1757
  return code;
749,391,613✔
1758
}
1759

1760
static int32_t buildDataBlockFromBuf(STsdbReader* pReader, STableBlockScanInfo* pBlockScanInfo, int64_t endKey) {
19,137,501✔
1761
  if (!(pBlockScanInfo->iiter.hasVal || pBlockScanInfo->iter.hasVal)) {
19,137,501✔
1762
    return TSDB_CODE_SUCCESS;
13,636,731✔
1763
  }
1764

1765
  int32_t code = initRowMergeIfNeeded(pReader, pBlockScanInfo->uid);
5,500,770✔
1766
  if (code != 0) {
5,504,302!
1767
    return code;
×
1768
  }
1769

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

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

1777
  tsdbDebug("%p build data block from cache completed, elapsed time:%.2f ms, numOfRows:%" PRId64 ", brange:%" PRId64
5,505,987✔
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,506,249✔
1783
  return code;
5,506,249✔
1784
}
1785

1786
static bool tryCopyDistinctRowFromFileBlock(STsdbReader* pReader, SBlockData* pBlockData, SRowKey* pKey,
38,583,649✔
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;
38,583,649✔
1792

1793
  *copied = false;
38,583,649✔
1794
  bool asc = (pReader->info.order == TSDB_ORDER_ASC);
38,583,649✔
1795
  if ((pDumpInfo->rowIndex < pDumpInfo->totalRows - 1 && asc) || (pDumpInfo->rowIndex > 0 && (!asc))) {
38,583,649!
1796
    int32_t step = ASCENDING_TRAVERSE(pReader->info.order) ? 1 : -1;
38,695,582✔
1797

1798
    SRowKey nextRowKey;
1799
    tColRowGetKey(pBlockData, pDumpInfo->rowIndex + step, &nextRowKey);
38,695,582✔
1800

1801
    if (pkCompEx(pKey, &nextRowKey) != 0) {  // merge is not needed
38,723,852!
1802
      code = doAppendRowFromFileBlock(pReader->resBlockInfo.pResBlock, pReader, pBlockData, pDumpInfo->rowIndex);
38,725,753✔
1803
      if (code) {
38,905,734!
1804
        return code;
×
1805
      }
1806
      pDumpInfo->rowIndex += step;
38,905,734✔
1807
      *copied = true;
38,905,734✔
1808
    }
1809
  }
1810

1811
  return code;
38,791,900✔
1812
}
1813

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

1821
  while (1) {
2,532,369✔
1822
    bool hasVal = false;
496,658,393✔
1823
    code = tMergeTreeNext(&pSttBlockReader->mergeTree, &hasVal);
496,658,393✔
1824
    if (code) {
498,227,979!
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;
494,572,148✔
1828
    }
1829

1830
    if (!hasVal) {  // the next value will be the accessed key in stt
498,397,463✔
1831
      pScanInfo->sttKeyInfo.status = STT_FILE_NO_DATA;
13,691,849✔
1832

1833
      // next file, the timestamps in the next file must be greater than those in current
1834
      pNextProc->ts += step;
13,691,849✔
1835
      if (pSttBlockReader->numOfPks > 0) {
13,691,849✔
1836
        if (IS_NUMERIC_TYPE(pNextProc->pks[0].type)) {
1,860,118!
1837
          pNextProc->pks[0].val = INT64_MIN;
1,348,003✔
1838
        } else {
1839
          memset(pNextProc->pks[0].pData, 0, pNextProc->pks[0].nData);
512,115✔
1840
        }
1841
      }
1842
      return code;
13,691,849✔
1843
    }
1844

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

1849
    if (pSttBlockReader->numOfPks == 0) {
484,705,614✔
1850
      pSttBlockReader->currentKey.ts = key;
458,283,404✔
1851
    } else {
1852
      tColRowGetKeyDeepCopy(pRow->pBlockData, pRow->iRow, pkSrcSlot, &pSttBlockReader->currentKey);
26,422,210✔
1853
    }
1854

1855
    tColRowGetKeyDeepCopy(pRow->pBlockData, pRow->iRow, pkSrcSlot, pNextProc);
487,898,175✔
1856

1857
    if (pScanInfo->delSkyline != NULL && TARRAY_SIZE(pScanInfo->delSkyline) > 0) {
487,601,695!
1858
      if (!hasBeenDropped(pScanInfo->delSkyline, &pScanInfo->sttBlockDelIndex, key, ver, order, pVerRange,
38,524,020✔
1859
                          pSttBlockReader->numOfPks > 0)) {
42,713,047✔
1860
        pScanInfo->sttKeyInfo.status = STT_FILE_HAS_DATA;
35,991,651✔
1861
        return code;
35,991,651✔
1862
      }
1863
    } else {
1864
      pScanInfo->sttKeyInfo.status = STT_FILE_HAS_DATA;
444,888,648✔
1865
      return code;
444,888,648✔
1866
    }
1867
  }
1868

1869
  return code;
1870
}
1871

1872
static void doPinSttBlock(SSttBlockReader* pSttBlockReader) { tMergeTreePinSttBlock(&pSttBlockReader->mergeTree); }
300,984,246✔
1873

1874
static void doUnpinSttBlock(SSttBlockReader* pSttBlockReader) { tMergeTreeUnpinSttBlock(&pSttBlockReader->mergeTree); }
296,410,942✔
1875

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

1882
  // avoid the fetch next row replace the referenced stt block in buffer
1883
  doPinSttBlock(pSttBlockReader);
301,473,063✔
1884
  code = nextRowFromSttBlocks(pSttBlockReader, pScanInfo, pReader->suppInfo.pkSrcSlot, &pReader->info.verRange);
296,940,752✔
1885
  doUnpinSttBlock(pSttBlockReader);
298,252,612✔
1886

1887
  if (code) {
295,317,990!
1888
    return code;
×
1889
  }
1890

1891
  if (hasDataInSttBlock(pScanInfo)) {
295,317,990✔
1892
    SRowKey* pNext = getCurrentKeyInSttBlock(pSttBlockReader);
293,017,348!
1893
    if (pkCompEx(pSttKey, pNext) != 0) {
294,464,063✔
1894
      code = doAppendRowFromFileBlock(pReader->resBlockInfo.pResBlock, pReader, fRow->pBlockData, fRow->iRow);
290,666,019✔
1895
      *copied = (code == TSDB_CODE_SUCCESS);
309,215,990✔
1896
      return code;
309,215,990✔
1897
    }
1898
  } else {
1899
    code = doAppendRowFromFileBlock(pReader->resBlockInfo.pResBlock, pReader, fRow->pBlockData, fRow->iRow);
1,886,581✔
1900
    *copied = (code == TSDB_CODE_SUCCESS);
1,992,610✔
1901
    return code;
1,992,610✔
1902
  }
1903

1904
  return code;
3,798,044✔
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) {
367,136,208!
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,937,053,179!
1917
    return pReader->info.pSchema;
1,901,704,731✔
1918
  }
1919

1920
  void** p = tSimpleHashGet(pReader->pSchemaMap, &sversion, sizeof(sversion));
35,348,448✔
1921
  if (p != NULL) {
36,274,234!
1922
    return *(STSchema**)p;
36,150,649✔
1923
  }
1924

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

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

1948
  SRowKey* pSttKey = NULL;
357,894,214✔
1949
  if (hasDataInSttBlock(pBlockScanInfo) && (!pBlockScanInfo->cleanSttBlocks)) {
357,894,214!
1950
    pSttKey = getCurrentKeyInSttBlock(pSttBlockReader);
338,686,739✔
1951
  }
1952

1953
  SRowKey k = {0};
357,674,386✔
1954
  tRowGetKeyEx(pRow, &k);
357,674,386!
1955

1956
  STSchema* pSchema = NULL;
357,819,175✔
1957
  if (pRow->type == TSDBROW_ROW_FMT) {
357,819,175!
1958
    pSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(pRow), pReader, pBlockScanInfo->uid);
357,902,161!
1959
    if (pSchema == NULL) {
357,957,678!
1960
      return terrno;
×
1961
    }
1962
  }
1963

1964
  SRowKey* pfKey = &(SRowKey){0};
357,874,692✔
1965
  if (hasDataInFileBlock(pBlockData, pDumpInfo)) {
357,874,692✔
1966
    tColRowGetKey(pBlockData, pDumpInfo->rowIndex, pfKey);
23,872,734✔
1967
  } else {
1968
    pfKey = NULL;
334,188,896✔
1969
  }
1970

1971
  TSDBROW fRow = tsdbRowFromBlockData(pBlockData, pDumpInfo->rowIndex);
358,060,467✔
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);
358,060,467✔
1975
  if (code != 0) {
357,985,666!
1976
    return code;
×
1977
  }
1978

1979
  SRowKey minKey = k;
357,985,666✔
1980
  if (pReader->info.order == TSDB_ORDER_ASC) {
357,985,666✔
1981
    if (pfKey != NULL && pkCompEx(pfKey, &minKey) < 0) {
339,455,885✔
1982
      minKey = *pfKey;
22,772,390✔
1983
    }
1984

1985
    if (pSttKey != NULL && pkCompEx(pSttKey, &minKey) < 0) {
612,929,524✔
1986
      minKey = *pSttKey;
156,370,477✔
1987
    }
1988
  } else {
1989
    if (pfKey != NULL && pkCompEx(pfKey, &minKey) > 0) {
42,801,968✔
1990
      minKey = *pfKey;
624,252✔
1991
    }
1992

1993
    if (pSttKey != NULL && pkCompEx(pSttKey, &minKey) > 0) {
84,252,618!
1994
      minKey = *pSttKey;
14,547,838✔
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);
358,368,040✔
2001

2002
  // file block ---> stt block -----> mem
2003
  if (pkCompEx(&minKey, pfKey) == 0) {
358,301,711✔
2004
    code = tsdbRowMergerAdd(pMerger, &fRow, NULL);
23,532,376✔
2005
    if (code != TSDB_CODE_SUCCESS) {
23,575,491!
2006
      return code;
×
2007
    }
2008

2009
    code = doMergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pfKey, pReader);
23,575,491✔
2010
    if (code != TSDB_CODE_SUCCESS) {
23,733,840!
2011
      return code;
×
2012
    }
2013
  }
2014

2015
  if (pkCompEx(&minKey, pSttKey) == 0) {
358,812,367✔
2016
    TSDBROW* fRow1 = tMergeTreeGetRow(&pSttBlockReader->mergeTree);
176,896,405✔
2017
    code = tsdbRowMergerAdd(pMerger, fRow1, NULL);
176,896,405✔
2018
    if (code != TSDB_CODE_SUCCESS) {
177,013,423!
2019
      return code;
×
2020
    }
2021
    code = doMergeRowsInSttBlock(pSttBlockReader, pBlockScanInfo, pMerger, pkSrcSlot, &pReader->info.verRange, pReader->idStr);
177,013,423✔
2022
    if (code != TSDB_CODE_SUCCESS) {
176,279,185!
2023
      return code;
×
2024
    }
2025
  }
2026

2027
  if (pkCompEx(&minKey, &k) == 0) {
357,921,135✔
2028
    code = tsdbRowMergerAdd(pMerger, pRow, pSchema);
164,496,370✔
2029
    if (code != TSDB_CODE_SUCCESS) {
164,429,037!
2030
      return code;
×
2031
    }
2032

2033
    code = doMergeRowsInBuf(pIter, pBlockScanInfo->uid, &k, pBlockScanInfo->delSkyline, pReader);
164,429,037✔
2034
    if (code != TSDB_CODE_SUCCESS) {
164,458,630!
2035
      return code;
×
2036
    }
2037
  }
2038

2039
  code = tsdbRowMergerGetRow(pMerger, &pTSRow);
357,883,395✔
2040
  if (code != TSDB_CODE_SUCCESS) {
360,214,820!
2041
    return code;
×
2042
  }
2043

2044
  code = doAppendRowFromTSRow(pReader->resBlockInfo.pResBlock, pReader, pTSRow, pBlockScanInfo);
360,214,820✔
2045

2046
  taosMemoryFree(pTSRow);
358,599,175✔
2047
  tsdbRowMergerClear(pMerger);
360,691,355✔
2048

2049
  return code;
355,164,415✔
2050
}
2051

2052
static int32_t mergeFileBlockAndSttBlock(STsdbReader* pReader, SSttBlockReader* pSttBlockReader, SRowKey* pKey,
346,105,934✔
2053
                                         STableBlockScanInfo* pBlockScanInfo, SBlockData* pBlockData) {
2054
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;
346,105,934✔
2055
  SRowMerger*         pMerger = &pReader->status.merger;
346,105,934✔
2056
  int32_t             code = TSDB_CODE_SUCCESS;
346,105,934✔
2057
  int32_t             pkSrcSlot = pReader->suppInfo.pkSrcSlot;
346,105,934✔
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);
346,105,934✔
2061
  if (code != 0) {
345,625,661!
2062
    return code;
×
2063
  }
2064

2065
  bool dataInDataFile = hasDataInFileBlock(pBlockData, pDumpInfo);
345,625,661✔
2066
  bool dataInSttFile = hasDataInSttBlock(pBlockScanInfo);
342,342,347✔
2067

2068
  if (dataInDataFile && (!dataInSttFile)) {
342,048,755✔
2069
    // no stt file block available, only data block exists
2070
    return mergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pKey, pReader);
12,373,837✔
2071
  } else if ((!dataInDataFile) && dataInSttFile) {
329,674,918!
2072
    // no data in data file exists
2073
    return mergeRowsInSttBlocks(pSttBlockReader, pBlockScanInfo, pReader);
302,205,444✔
2074
  } else if (pBlockScanInfo->cleanSttBlocks && pReader->info.execMode == READER_EXEC_ROWS) {
27,469,474!
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);
27,469,474✔
2080
    SRowKey* pSttKey = getCurrentKeyInSttBlock(pSttBlockReader);
27,469,474!
2081

2082
    int32_t ret = pkCompEx(pKey, pSttKey);
27,579,691✔
2083

2084
    if (ASCENDING_TRAVERSE(pReader->info.order)) {
27,579,691✔
2085
      if (ret < 0) {  // asc
26,576,437✔
2086
        return mergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pKey, pReader);
25,577,960✔
2087
      } else if (ret > 0) {
998,477✔
2088
        return mergeRowsInSttBlocks(pSttBlockReader, pBlockScanInfo, pReader);
22,801✔
2089
      }
2090
    } else {  // desc
2091
      if (ret > 0) {
1,003,254✔
2092
        return mergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pKey, pReader);
624,438✔
2093
      } else if (ret < 0) {
378,816✔
2094
        return mergeRowsInSttBlocks(pSttBlockReader, pBlockScanInfo, pReader);
225,815✔
2095
      }
2096
    }
2097

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

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

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

2114
    TSDBROW* pRow1 = tMergeTreeGetRow(&pSttBlockReader->mergeTree);
1,141,020✔
2115
    code = tsdbRowMergerAdd(pMerger, pRow1, NULL);
1,141,020✔
2116
    if (code != TSDB_CODE_SUCCESS) {
1,133,122!
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,133,122✔
2122
    if (code != TSDB_CODE_SUCCESS) {
1,135,131!
2123
      return code;
×
2124
    }
2125

2126
    code = tsdbRowMergerGetRow(pMerger, &pTSRow);
1,135,131✔
2127
    if (code != TSDB_CODE_SUCCESS) {
1,145,730!
2128
      return code;
×
2129
    }
2130

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

2133
    taosMemoryFree(pTSRow);
1,144,882✔
2134
    tsdbRowMergerClear(pMerger);
1,147,090✔
2135
    return code;
1,076,368✔
2136
  }
2137
}
2138

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

2150
  getValidMemRow(&pBlockScanInfo->iter, pDelList, pReader, &pRow);
3,335,669✔
2151
  getValidMemRow(&pBlockScanInfo->iiter, pDelList, pReader, &piRow);
3,335,256✔
2152

2153
  SRowKey* pSttKey = NULL;
3,334,563✔
2154
  if (hasDataInSttBlock(pBlockScanInfo) && (!pBlockScanInfo->cleanSttBlocks)) {
3,334,563!
2155
    pSttKey = getCurrentKeyInSttBlock(pSttBlockReader);
2,899,752✔
2156
  }
2157

2158
  SRowKey* pfKey = &(SRowKey){0};
3,336,064✔
2159
  if (hasDataInFileBlock(pBlockData, pDumpInfo)) {
3,336,064✔
2160
    tColRowGetKey(pBlockData, pDumpInfo->rowIndex, pfKey);
436,567!
2161
  } else {
2162
    pfKey = NULL;
2,899,426✔
2163
  }
2164

2165
  SRowKey k = {0}, ik = {0};
3,339,978✔
2166
  tRowGetKeyEx(pRow, &k);
3,339,978!
2167
  tRowGetKeyEx(piRow, &ik);
3,340,341!
2168

2169
  STSchema* pSchema = NULL;
3,340,341✔
2170
  if (pRow->type == TSDBROW_ROW_FMT) {
3,340,341✔
2171
    pSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(pRow), pReader, pBlockScanInfo->uid);
3,340,226!
2172
    if (pSchema == NULL) {
3,340,561!
2173
      return terrno;
×
2174
    }
2175
  }
2176

2177
  STSchema* piSchema = NULL;
3,340,676✔
2178
  if (piRow->type == TSDBROW_ROW_FMT) {
3,340,676✔
2179
    piSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(piRow), pReader, pBlockScanInfo->uid);
3,340,530!
2180
    if (piSchema == NULL) {
3,340,291!
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);
3,340,437✔
2187
  if (code != 0) {
3,338,911!
2188
    return code;
×
2189
  }
2190

2191
  SRowKey minKey = k;
3,338,911✔
2192
  if (ASCENDING_TRAVERSE(pReader->info.order)) {
3,338,911!
2193
    if (pkCompEx(&ik, &minKey) < 0) {  // minKey > ik.key.ts) {
3,339,316✔
2194
      minKey = ik;
3,249,450✔
2195
    }
2196

2197
    if ((pfKey != NULL) && (pkCompEx(pfKey, &minKey) < 0)) {
3,777,944✔
2198
      minKey = *pfKey;
411,971✔
2199
    }
2200

2201
    if ((pSttKey != NULL) && (pkCompEx(pSttKey, &minKey) < 0)) {
6,238,200✔
2202
      minKey = *pSttKey;
2,803,869✔
2203
    }
2204
  } else {
2205
    if (pkCompEx(&ik, &minKey) > 0) {
×
2206
      minKey = ik;
×
2207
    }
2208

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

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

2218
  tRowKeyAssign(&pBlockScanInfo->lastProcKey, &minKey);
3,339,104✔
2219

2220
  // file block -----> stt block -----> imem -----> mem
2221
  if (pkCompEx(&minKey, pfKey) == 0) {
3,337,523✔
2222
    TSDBROW fRow = tsdbRowFromBlockData(pBlockData, pDumpInfo->rowIndex);
412,532✔
2223
    code = tsdbRowMergerAdd(pMerger, &fRow, NULL);
412,532✔
2224
    if (code != TSDB_CODE_SUCCESS) {
413,294!
2225
      return code;
×
2226
    }
2227

2228
    code = doMergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pfKey, pReader);
413,294✔
2229
    if (code != TSDB_CODE_SUCCESS) {
412,327!
2230
      return code;
×
2231
    }
2232
  }
2233

2234
  if (pkCompEx(&minKey, pSttKey) == 0) {
3,337,115✔
2235
    TSDBROW* pRow1 = tMergeTreeGetRow(&pSttBlockReader->mergeTree);
2,884,310✔
2236
    code = tsdbRowMergerAdd(pMerger, pRow1, NULL);
2,884,310✔
2237
    if (code != TSDB_CODE_SUCCESS) {
2,884,853!
2238
      return code;
×
2239
    }
2240

2241
    code = doMergeRowsInSttBlock(pSttBlockReader, pBlockScanInfo, pMerger, pkSrcSlot, &pReader->info.verRange, pReader->idStr);
2,884,853✔
2242
    if (code != TSDB_CODE_SUCCESS) {
2,876,056!
2243
      return code;
×
2244
    }
2245
  }
2246

2247
  if (pkCompEx(&minKey, &ik) == 0) {
3,329,259✔
2248
    code = tsdbRowMergerAdd(pMerger, piRow, piSchema);
116,883✔
2249
    if (code != TSDB_CODE_SUCCESS) {
116,882!
2250
      return code;
×
2251
    }
2252

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

2259
  if (pkCompEx(&minKey, &k) == 0) {
3,328,886✔
2260
    code = tsdbRowMergerAdd(pMerger, pRow, pSchema);
68,495✔
2261
    if (code != TSDB_CODE_SUCCESS) {
68,495!
2262
      return code;
×
2263
    }
2264

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

2271
  code = tsdbRowMergerGetRow(pMerger, &pTSRow);
3,328,886✔
2272
  if (code != TSDB_CODE_SUCCESS) {
3,342,252!
2273
    return code;
×
2274
  }
2275

2276
  code = doAppendRowFromTSRow(pReader->resBlockInfo.pResBlock, pReader, pTSRow, pBlockScanInfo);
3,342,252✔
2277

2278
  taosMemoryFree(pTSRow);
3,339,794✔
2279
  tsdbRowMergerClear(pMerger);
3,343,417✔
2280
  return code;
3,313,358✔
2281
}
2282

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

2289
  if (pMem != NULL) {
25,565,139✔
2290
    *pData = tsdbGetTbDataFromMemTable(pMem, pReader->info.suid, pBlockScanInfo->uid);
11,706,956✔
2291

2292
    if ((*pData) != NULL) {
11,714,663✔
2293
      code = tsdbTbDataIterCreate((*pData), pKey, backward, &pIter->iter);
4,478,307✔
2294
      if (code == TSDB_CODE_SUCCESS) {
4,475,038!
2295
        pIter->hasVal = (tsdbTbDataIterGet(pIter->iter) != NULL);
4,475,096!
2296

2297
        tsdbDebug("%p uid:%" PRIu64 ", check data in %s from skey:%" PRId64 ", order:%d, ts range in buf:%" PRId64
4,475,096✔
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);
13,858,183✔
2309
  }
2310

2311
  return code;
25,570,799✔
2312
}
2313

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

2319
  while (1) {
625✔
2320
    getValidMemRow(pIter, pBlockScanInfo->delSkyline, pReader, &pRow);
1,413,055✔
2321
    if (!pIter->hasVal) {
1,413,134✔
2322
      break;
1,088,734✔
2323
    }
2324

2325
    tRowGetKeyEx(pRow, &rowKey);
324,400✔
2326
    int32_t ret = pkCompEx(pKey, &rowKey);
324,083✔
2327
    if (ret == 0) {
324,083!
2328
      pIter->hasVal = tsdbTbDataIterNext(pIter->iter);
×
2329
    } else {
2330
      break;
324,083✔
2331
    }
2332
  }
2333
}
1,412,817✔
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) {
706,815✔
2337
  doForwardDataIter(pKey, &pBlockScanInfo->iter, pBlockScanInfo, pReader);
706,815✔
2338
  doForwardDataIter(pKey, &pBlockScanInfo->iiter, pBlockScanInfo, pReader);
706,336✔
2339
}
706,458✔
2340

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

2349
  if (pBlockScanInfo->iterInit) {
32,852,899✔
2350
    return TSDB_CODE_SUCCESS;
20,079,689✔
2351
  }
2352

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

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

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

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

2376
  if (forward) {
12,790,753✔
2377
    forwardDataIter(&startKey.key, pBlockScanInfo, pReader);
706,872✔
2378
  }
2379

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

2384
static bool isValidFileBlockRow(SBlockData* pBlockData, int32_t rowIndex, STableBlockScanInfo* pBlockScanInfo, bool asc,
73,958,704✔
2385
                                STsdbReaderInfo* pInfo, STsdbReader* pReader) {
2386
  // it is an multi-table data block
2387
  if (pBlockData->aUid != NULL) {
73,958,704!
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];
73,958,704✔
2396
  if (ver > pInfo->verRange.maxVer || ver < pInfo->verRange.minVer) {
73,958,704!
2397
    return false;
×
2398
  }
2399

2400
  int64_t ts = pBlockData->aTSKEY[rowIndex];
73,992,378✔
2401
  if (ts > pInfo->window.ekey || ts < pInfo->window.skey) {
73,992,378✔
2402
    return false;
5,161,913✔
2403
  }
2404

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

2409
  if (ts == pBlockScanInfo->lastProcKey.ts) {  // todo opt perf
68,830,465!
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) {
68,830,465!
2418
    bool dropped = hasBeenDropped(pBlockScanInfo->delSkyline, &pBlockScanInfo->fileDelIndex, ts, ver, pInfo->order,
34,833,858✔
2419
                                  &pInfo->verRange, pReader->suppInfo.numOfPks > 0);
34,833,858✔
2420
    if (dropped) {
34,835,087✔
2421
      return false;
4,722,968✔
2422
    }
2423
  }
2424

2425
  return true;
64,108,726✔
2426
}
2427

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

2432
  // the stt block reader has been initialized for this table.
2433
  if (pSttBlockReader->uid == pScanInfo->uid) {
18,728,829✔
2434
    return;
5,011,941✔
2435
  }
2436

2437
  if (pSttBlockReader->uid != 0) {
13,716,888✔
2438
    tMergeTreeClose(&pSttBlockReader->mergeTree);
7,121,704✔
2439
  }
2440

2441
  pSttBlockReader->uid = pScanInfo->uid;
13,722,093✔
2442

2443
  // second or third time init stt block reader
2444
  if (pScanInfo->cleanSttBlocks && (pReader->info.execMode == READER_EXEC_ROWS)) {
13,722,093!
2445
    // only allowed to retrieve clean stt blocks for count once
2446
    if (pScanInfo->sttBlockReturned) {
×
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;
×
2451
  }
2452

2453
  STimeWindow w = pSttBlockReader->window;
13,722,093✔
2454
  if (asc) {
13,722,093✔
2455
    w.skey = pScanInfo->sttKeyInfo.nextProcKey.ts;
11,887,150✔
2456
  } else {
2457
    w.ekey = pScanInfo->sttKeyInfo.nextProcKey.ts;
1,834,943✔
2458
  }
2459

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

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

2484
  SSttDataInfoForTable info = {.pKeyRangeList = taosArrayInit(4, sizeof(SSttKeyRange))};
13,726,638✔
2485
  if (info.pKeyRangeList == NULL) {
13,731,520!
2486
    pReader->code = terrno;
×
2487
    return;
×
2488
  }
2489

2490
  int32_t code = tMergeTreeOpen2(&pSttBlockReader->mergeTree, &conf, &info);
13,731,520✔
2491
  if (code != TSDB_CODE_SUCCESS) {
13,723,471!
2492
    taosArrayDestroy(info.pKeyRangeList);
×
2493
    pReader->code = code;
×
2494
    return;
×
2495
  }
2496

2497
  code = initMemDataIterator(pScanInfo, pReader);
13,723,471✔
2498
  if (code != TSDB_CODE_SUCCESS) {
13,727,453!
2499
    taosArrayDestroy(info.pKeyRangeList);
×
2500
    pReader->code = code;
×
2501
    return;
×
2502
  }
2503

2504
  code = initDelSkylineIterator(pScanInfo, pReader->info.order, &pReader->cost);
13,727,453✔
2505
  if (code != TSDB_CODE_SUCCESS) {
13,727,065✔
2506
    taosArrayDestroy(info.pKeyRangeList);
594✔
2507
    pReader->code = code;
×
2508
    return;
×
2509
  }
2510

2511
  if (conf.rspRows) {
13,726,471✔
2512
    pScanInfo->cleanSttBlocks = isCleanSttBlock(info.pKeyRangeList, &pReader->info.window, pScanInfo, order);
231,638✔
2513
    if (pScanInfo->cleanSttBlocks) {
231,648✔
2514
      pScanInfo->numOfRowsInStt = info.numOfRows;
27,977✔
2515

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

2523
        if (pkCompEx(&pScanInfo->sttRange.skey, &pKeyRange->skey) > 0) {
55,929!
2524
          tRowKeyAssign(&pScanInfo->sttRange.skey, &pKeyRange->skey);
27,957✔
2525
        }
2526

2527
        if (pkCompEx(&pScanInfo->sttRange.ekey, &pKeyRange->ekey) < 0) {
55,916!
2528
          tRowKeyAssign(&pScanInfo->sttRange.ekey, &pKeyRange->ekey);
27,959✔
2529
        }
2530
      }
2531

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

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

2546
  pScanInfo->sttBlockReturned = false;
13,723,159✔
2547
  taosArrayDestroy(info.pKeyRangeList);
13,723,159✔
2548

2549
  int64_t el = taosGetTimestampUs() - st;
13,733,165✔
2550
  pReader->cost.initSttBlockReader += (el / 1000.0);
13,733,165✔
2551

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

2558
static bool hasDataInSttBlock(STableBlockScanInfo* pInfo) { return pInfo->sttKeyInfo.status == STT_FILE_HAS_DATA; }
1,792,815,985✔
2559

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

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

2573
  int32_t code = tryCopyDistinctRowFromFileBlock(pReader, pBlockData, pKey, pDumpInfo, &copied);
38,572,627✔
2574
  if (code != TSDB_CODE_SUCCESS) {
38,720,325!
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);
38,720,325✔
2580
  if (code != 0) {
38,651,149!
2581
    return code;
×
2582
  }
2583

2584
  tRowKeyAssign(&pBlockScanInfo->lastProcKey, pKey);
38,651,149✔
2585

2586
  if (copied) {
38,616,131✔
2587
    return TSDB_CODE_SUCCESS;
38,611,260✔
2588
  } else {
2589
    TSDBROW fRow = tsdbRowFromBlockData(pBlockData, pDumpInfo->rowIndex);
4,871✔
2590

2591
    SRow* pTSRow = NULL;
4,871✔
2592
    code = tsdbRowMergerAdd(pMerger, &fRow, NULL);
4,871✔
2593
    if (code != TSDB_CODE_SUCCESS) {
11,128!
2594
      return code;
×
2595
    }
2596

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

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

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

2609
    taosMemoryFree(pTSRow);
11,128✔
2610
    tsdbRowMergerClear(pMerger);
11,128✔
2611
    return code;
11,128✔
2612
  }
2613
}
2614

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

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

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

2627
  if (IS_VAR_DATA_TYPE(pScanInfo->lastProcKey.pks[0].type)) {
301,290,356!
2628
    tsdbTrace("fRow ptr:%p, %d, uid:%" PRIu64 ", ts:%" PRId64 " pk:%s %s", pRow->pBlockData, pRow->iRow,
816,980!
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);
301,290,356✔
2635
  if (code) {
312,442,424!
2636
    return code;
×
2637
  }
2638

2639
  if (copied) {
312,442,424✔
2640
    return TSDB_CODE_SUCCESS;
311,068,899✔
2641
  } else {
2642
    code = tsdbRowMergerAdd(pMerger, &fRow, NULL);
1,373,525✔
2643
    if (code != TSDB_CODE_SUCCESS) {
1,476,651!
2644
      return code;
×
2645
    }
2646

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

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

2658
    code = tsdbRowMergerGetRow(pMerger, &pTSRow);
1,453,155✔
2659
    if (code != TSDB_CODE_SUCCESS) {
1,490,487!
2660
      return code;
×
2661
    }
2662

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

2665
    taosMemoryFree(pTSRow);
1,487,742✔
2666
    tsdbRowMergerClear(pMerger);
1,495,390✔
2667
    return code;
1,306,028✔
2668
  }
2669
}
2670

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

2675
  TSDBROW *pRow = NULL, *piRow = NULL;
705,422,188✔
2676

2677
  SRowKey* pKey = &(SRowKey){0};
705,422,188✔
2678
  if (hasDataInFileBlock(pBlockData, pDumpInfo)) {
705,422,188✔
2679
    tColRowGetKey(pBlockData, pDumpInfo->rowIndex, pKey);
63,836,083✔
2680
  } else {
2681
    pKey = NULL;
639,940,566✔
2682
  }
2683

2684
  if (pBlockScanInfo->iter.hasVal) {
705,574,907✔
2685
    getValidMemRow(&pBlockScanInfo->iter, pBlockScanInfo->delSkyline, pReader, &pRow);
337,890,734✔
2686
  }
2687

2688
  if (pBlockScanInfo->iiter.hasVal) {
705,213,184✔
2689
    getValidMemRow(&pBlockScanInfo->iiter, pBlockScanInfo->delSkyline, pReader, &piRow);
25,163,205✔
2690
  }
2691

2692
  // two levels of mem-table does contain the valid rows
2693
  if (pRow != NULL && piRow != NULL) {
705,235,712✔
2694
    return doMergeMultiLevelRows(pReader, pBlockScanInfo, pBlockData, pSttBlockReader);
3,335,277✔
2695
  }
2696

2697
  // imem + file + stt block
2698
  if (pBlockScanInfo->iiter.hasVal) {
701,900,435✔
2699
    return doMergeBufAndFileRows(pReader, pBlockScanInfo, piRow, &pBlockScanInfo->iiter, pSttBlockReader);
22,491,733✔
2700
  }
2701

2702
  // mem + file + stt block
2703
  if (pBlockScanInfo->iter.hasVal) {
679,408,702✔
2704
    return doMergeBufAndFileRows(pReader, pBlockScanInfo, pRow, &pBlockScanInfo->iter, pSttBlockReader);
335,558,256✔
2705
  }
2706

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

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

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

2727
  // load next block
2728
  if (overlapWithNeighborBlock2(pBlockInfo, &rec, order, pReader->suppInfo.pk.type, pReader->suppInfo.numOfPks)) {
13,182!
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,182✔
2757
}
2758

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

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

2766
  int32_t code = blockDataUpdateTsWindow(pResBlock, pReader->suppInfo.slotId[0]);
10,515,869✔
2767
  code = blockDataUpdatePkRange(pResBlock, pReader->suppInfo.pkDstSlot, ASCENDING_TRAVERSE(pReader->info.order));
10,517,574✔
2768
  setComposedBlockFlag(pReader, true);
10,516,951✔
2769

2770
  pReader->cost.composedBlocks += 1;
10,515,412✔
2771
  pReader->cost.buildComposedBlockTime += el;
10,515,412✔
2772
}
10,515,412✔
2773

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

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

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

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

2801
  TSDBKEY keyInBuf = getCurrentKeyInBuf(pBlockScanInfo, pReader);
31,707✔
2802

2803
  // it is a clean block, load it directly
2804
  int64_t cap = pReader->resBlockInfo.capacity;
31,708✔
2805
  bool    directCopy = isCleanFileDataBlock(pReader, pBlockInfo, pBlockScanInfo, keyInBuf) &&
31,708✔
2806
                    (pBlockInfo->numRow <= cap) && (pBlockScanInfo->sttKeyInfo.status == STT_FILE_NO_DATA) &&
34,556!
2807
                    ((asc && ((pBlockInfo->lastKey < keyInBuf.ts) || (keyInBuf.ts == INT64_MIN))) ||
1,856!
2808
                     (!asc && (pBlockInfo->lastKey > keyInBuf.ts)));
991!
2809
  if (directCopy) {
31,709✔
2810
    code = copyBlockDataToSDataBlock(pReader, &pBlockScanInfo->lastProcKey);
2,847✔
2811
    goto _end;
2,845✔
2812
  }
2813

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

2821
  while (1) {
64,026,918✔
2822
    bool hasBlockData = false;
64,055,780✔
2823
    {
2824
      while (pBlockData->nRow > 0 && pBlockData->uid == pBlockScanInfo->uid) {
73,827,639!
2825
        // find the first qualified row in data block
2826
        if (isValidFileBlockRow(pBlockData, pDumpInfo->rowIndex, pBlockScanInfo, asc, &pReader->info, pReader)) {
73,945,487✔
2827
          hasBlockData = true;
64,095,363✔
2828
          break;
64,095,363✔
2829
        }
2830

2831
        pDumpInfo->rowIndex += step;
9,901,092✔
2832

2833
        if (pDumpInfo->rowIndex >= pBlockData->nRow || pDumpInfo->rowIndex < 0) {
9,901,092!
2834
          // NOTE: get the new block info
2835
          code = getCurrentBlockInfo(&pReader->status.blockIter, &pBlockInfo, pReader->idStr);
129,233✔
2836
          if (code != TSDB_CODE_SUCCESS) {
6,590!
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,590✔
2843
          code = loadNeighborIfOverlap(pBlockInfo, pBlockScanInfo, pReader, &loadNeighbor);
6,590✔
2844
          if ((!loadNeighbor) || (code != 0)) {
6,590!
2845
            setBlockAllDumped(pDumpInfo, pBlockInfo->lastKey, pReader->info.order);
6,590✔
2846
            break;
6,590✔
2847
          }
2848
        }
2849
      }
2850
    }
2851

2852
    // no data in last block and block, no need to proceed.
2853
    if (hasBlockData == false) {
63,984,105✔
2854
      break;
6,590✔
2855
    }
2856

2857
    code = buildComposedDataBlockImpl(pReader, pBlockScanInfo, pBlockData, pSttBlockReader);
63,977,515✔
2858
    if (code) {
64,055,064!
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)) {
64,055,064!
2864
      setBlockAllDumped(pDumpInfo, pBlockInfo->lastKey, pReader->info.order);
22,931✔
2865
      break;
17,057✔
2866
    }
2867

2868
    if (pResBlock->info.rows >= pReader->resBlockInfo.capacity) {
64,032,133✔
2869
      break;
5,215✔
2870
    }
2871
  }
2872

2873
_end:
31,707✔
2874
  el = (taosGetTimestampUs() - st) / 1000.0;
31,705✔
2875
  updateComposedBlockInfo(pReader, el, pBlockScanInfo);
31,705✔
2876

2877
  if (pResBlock->info.rows > 0) {
31,706✔
2878
    tsdbDebug("%p uid:%" PRIu64 ", composed data block created, brange:%" PRIu64 "-%" PRIu64 " rows:%" PRId64
26,050✔
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;
31,707✔
2885
}
2886

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

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

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

2897
int32_t initDelSkylineIterator(STableBlockScanInfo* pBlockScanInfo, int32_t order, SReadCostSummary* pCost) {
32,861,948✔
2898
  int32_t code = 0;
32,861,948✔
2899
  int32_t newDelDataInFile = taosArrayGetSize(pBlockScanInfo->pFileDelData);
32,861,948✔
2900
  if (newDelDataInFile == 0 &&
32,863,397✔
2901
      ((pBlockScanInfo->delSkyline != NULL) || (TARRAY_SIZE(pBlockScanInfo->pMemDelData) == 0))) {
32,807,842✔
2902
    return code;
32,663,511✔
2903
  }
2904

2905
  int64_t st = taosGetTimestampUs();
202,382✔
2906

2907
  if (pBlockScanInfo->delSkyline != NULL) {
202,382✔
2908
    taosArrayClear(pBlockScanInfo->delSkyline);
35,123✔
2909
  } else {
2910
    pBlockScanInfo->delSkyline = taosArrayInit(4, sizeof(TSDBKEY));
167,259✔
2911
    if (pBlockScanInfo->delSkyline == NULL) {
167,260!
2912
      return terrno;
×
2913
    }
2914
  }
2915

2916
  SArray* pSource = pBlockScanInfo->pFileDelData;
202,382✔
2917
  if (pSource == NULL) {
202,382✔
2918
    pSource = pBlockScanInfo->pMemDelData;
138,221✔
2919
  } else {
2920
    void* p1 = taosArrayAddAll(pSource, pBlockScanInfo->pMemDelData);
64,161✔
2921
    if (p1 == NULL) {
64,159!
2922
      return terrno;
×
2923
    }
2924
  }
2925

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

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

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

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

2939
  return code;
202,382✔
2940
}
2941

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

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

2950
  getValidMemRow(&pScanInfo->iter, pScanInfo->delSkyline, pReader, &pRow);
669,252✔
2951
  if (pRow != NULL) {
669,251✔
2952
    hasKey = true;
17,883✔
2953
    key = TSDBROW_KEY(pRow);
17,883!
2954
  }
2955

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

2962
  if (hasKey) {
669,251✔
2963
    if (hasIKey) {  // has data in mem & imem
17,886✔
2964
      if (asc) {
315!
2965
        return key.ts <= ikey.ts ? key : ikey;
315✔
2966
      } else {
2967
        return key.ts <= ikey.ts ? ikey : key;
×
2968
      }
2969
    } else {  // no data in imem
2970
      return key;
17,571✔
2971
    }
2972
  } else {
2973
    // no data in mem & imem, return the initial value
2974
    // only imem has data, return ikey
2975
    return ikey;
651,365✔
2976
  }
2977
}
2978

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

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

2990
  if (ASCENDING_TRAVERSE(pReader->info.order)) {
2,356,217✔
2991
    pReader->status.bProcMemPreFileset = !(pReader->status.memTableMaxKey < pReader->status.prevFilesetStartKey ||
3,720,498✔
2992
                                           (winFid.skey - 1) < pReader->status.memTableMinKey);
1,656,615✔
2993
  } else {
2994
    pReader->status.bProcMemPreFileset = !(pReader->status.memTableMaxKey < (winFid.ekey + 1) ||
463,180✔
2995
                                           pReader->status.prevFilesetEndKey < pReader->status.memTableMinKey);
170,846!
2996
  }
2997

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

3004
  if (!pReader->status.bProcMemPreFileset) {
2,356,226✔
3005
    if (pReader->notifyFn) {
1,197,874!
3006
      STsdReaderNotifyInfo info = {0};
1,198,230✔
3007
      info.duration.filesetId = fid;
1,198,230✔
3008
      pReader->notifyFn(TSD_READER_NOTIFY_DURATION_START, &info, pReader->notifyParam);
1,198,230✔
3009
      tsdbDebug("new duration %d start notification when no buffer preceeding fileset, %s", fid, pReader->idStr);
1,198,555✔
3010
    }
3011
  }
3012

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

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

3022
  size_t  numOfTables = tSimpleHashGetSize(pReader->status.pTableMap);
8,799,659✔
3023
  SArray* pIndexList = taosArrayInit(numOfTables, sizeof(SBrinBlk));
8,801,200✔
3024
  if (pIndexList == NULL) {
8,800,556!
3025
    return terrno;
×
3026
  }
3027

3028
  while (1) {
3,370✔
3029
    // only check here, since the iterate data in memory is very fast.
3030
    if (pReader->code != TSDB_CODE_SUCCESS) {
8,803,926!
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;
8,803,926✔
3036
    int32_t code = filesetIteratorNext(&pStatus->fileIter, pReader, &hasNext);
8,803,926✔
3037
    if (code != TSDB_CODE_SUCCESS) {
8,803,180!
3038
      taosArrayDestroy(pIndexList);
×
3039
      return code;
×
3040
    }
3041

3042
    if (!hasNext) {  // no data files on disk
8,804,410✔
3043
      break;
2,183,062✔
3044
    }
3045

3046
    taosArrayClear(pIndexList);
6,621,348✔
3047
    code = doLoadBlockIndex(pReader, pReader->pFileReader, pIndexList);
6,620,772✔
3048
    if (code != TSDB_CODE_SUCCESS) {
6,620,572!
3049
      taosArrayDestroy(pIndexList);
×
3050
      return code;
×
3051
    }
3052

3053
    if (taosArrayGetSize(pIndexList) > 0 || pReader->status.pCurrentFileset->lvlArr->size > 0) {
6,620,572✔
3054
      code = loadFileBlockBrinInfo(pReader, pIndexList, pBlockNum, pTableList);
6,616,518✔
3055
      if (code != TSDB_CODE_SUCCESS) {
6,618,367!
3056
        taosArrayDestroy(pIndexList);
×
3057
        return code;
×
3058
      }
3059

3060
      if (pBlockNum->numOfBlocks + pBlockNum->numOfSttFiles > 0) {
6,618,367✔
3061
        if (pReader->bFilesetDelimited) {
6,617,363✔
3062
          prepareDurationForNextFileSet(pReader);
2,357,193✔
3063
        }
3064
        break;
6,615,382✔
3065
      }
3066
    }
3067

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

3071
  taosArrayDestroy(pIndexList);
8,798,444✔
3072
  return loadDataFileTombDataForAll(pReader);
8,803,173✔
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,117,788✔
3077
  STableUidList* pList = &pStatus->uidList;
16,117,788✔
3078

3079
  pList->currentIndex = 0;
16,117,788✔
3080
  uint64_t uid = pList->tableUidList[0];
16,117,788✔
3081
  pStatus->pTableIter = tSimpleHashGet(pStatus->pTableMap, &uid, sizeof(uid));
16,117,788✔
3082
  if (pStatus->pTableIter == NULL) {
16,123,428!
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,123,442✔
3088
}
3089

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

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

3098
static bool moveToNextTable(STableUidList* pOrderedCheckInfo, SReaderStatus* pStatus) {
26,043,192✔
3099
  pOrderedCheckInfo->currentIndex += 1;
26,043,192✔
3100
  if (pOrderedCheckInfo->currentIndex >= tSimpleHashGetSize(pStatus->pTableMap)) {
26,043,192✔
3101
    pStatus->pTableIter = NULL;
11,353,516✔
3102
    return false;
11,353,516✔
3103
  }
3104

3105
  uint64_t uid = pOrderedCheckInfo->tableUidList[pOrderedCheckInfo->currentIndex];
14,690,621✔
3106
  pStatus->pTableIter = tSimpleHashGet(pStatus->pTableMap, &uid, sizeof(uid));
14,690,621✔
3107
  return (pStatus->pTableIter != NULL);
14,698,206✔
3108
}
3109

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

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

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

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

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

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

3142
  setComposedBlockFlag(pReader, true);
27,930✔
3143

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

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

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

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

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

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

3175
  if (pReader->suppInfo.numOfPks > 0) {
610,715✔
3176
    if (IS_NUMERIC_TYPE(pReader->suppInfo.pk.type)) {
226,607!
3177
      pInfo->pks[0].val = pBlockInfo->firstPk.val;
226,607✔
3178
      pInfo->pks[1].val = pBlockInfo->lastPk.val;
226,607✔
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);
610,715✔
3190
  setBlockAllDumped(&pStatus->fBlockDumpInfo, pBlockInfo->lastKey, pReader->info.order);
610,640✔
3191
  updateLastKeyInfo(&pScanInfo->lastProcKey, pBlockInfo, pInfo, pReader->suppInfo.numOfPks, asc);
610,665✔
3192

3193
  tsdbDebug("%p uid:%" PRIu64
610,676✔
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
}
610,676✔
3199

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

3206
  if (tSimpleHashGetSize(pStatus->pTableMap) == 0) {
11,557,727!
3207
    return TSDB_CODE_SUCCESS;
×
3208
  }
3209

3210
  SSDataBlock* pResBlock = pReader->resBlockInfo.pResBlock;
11,558,831✔
3211

3212
  while (1) {
6,837,834✔
3213
    if (pReader->code != TSDB_CODE_SUCCESS) {
18,396,665!
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;
18,396,665✔
3220
    if (pStatus->pTableIter == NULL) {
18,396,665!
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;
18,396,665✔
3230
    }
3231

3232
    if (pReader->pIgnoreTables && taosHashGet(*pReader->pIgnoreTables, &pScanInfo->uid, sizeof(pScanInfo->uid))) {
18,396,665✔
3233
      // reset the index in last block when handing a new file
3234
      bool hasNexTable = moveToNextTable(pUidList, pStatus);
81,454✔
3235
      if (!hasNexTable) {
81,442✔
3236
        return TSDB_CODE_SUCCESS;
1,834✔
3237
      }
3238

3239
      continue;
79,608✔
3240
    }
3241

3242
    initSttBlockReader(pSttBlockReader, pScanInfo, pReader);
18,313,221✔
3243
    if (pReader->code != TSDB_CODE_SUCCESS) {
18,319,398!
3244
      return pReader->code;
×
3245
    }
3246
    
3247
    if (!hasDataInSttBlock(pScanInfo)) {
18,319,398✔
3248
      bool hasNexTable = moveToNextTable(pUidList, pStatus);
13,316,879✔
3249
      if (!hasNexTable) {
13,315,281✔
3250
        return TSDB_CODE_SUCCESS;
6,556,471✔
3251
      }
3252

3253
      continue;
6,758,810✔
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,002,793✔
3258
      code = buildCleanBlockFromSttFiles(pReader, pScanInfo);
27,940✔
3259
      return code;
27,930✔
3260
    }
3261

3262
    int64_t st = taosGetTimestampUs();
4,979,256✔
3263
    while (1) {
3264
      // no data in stt block and block, no need to proceed.
3265
      if (!hasDataInSttBlock(pScanInfo)) {
650,085,869✔
3266
        break;
4,913,007✔
3267
      }
3268

3269
      code = buildComposedDataBlockImpl(pReader, pScanInfo, &pReader->status.fileBlockData, pSttBlockReader);
642,854,686✔
3270
      if (code) {
645,173,197!
3271
        return code;
×
3272
      }
3273

3274
      if (pResBlock->info.rows >= pReader->resBlockInfo.capacity) {
645,173,197✔
3275
        break;
66,584✔
3276
      }
3277
    }
3278

3279
    double el = (taosGetTimestampUs() - st) / 1000.0;
4,979,145✔
3280
    updateComposedBlockInfo(pReader, el, pScanInfo);
4,979,145✔
3281

3282
    if (pResBlock->info.rows > 0) {
4,978,847!
3283
      tsdbDebug("%p uid:%" PRIu64 ", composed data block created, brange:%" PRIu64 "-%" PRIu64 " rows:%" PRId64
4,979,175✔
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;
4,979,316✔
3288
    }
3289

3290
    // current table is exhausted, let's try next table
3291
    bool hasNexTable = moveToNextTable(pUidList, pStatus);
×
3292
    if (!hasNexTable) {
×
3293
      return TSDB_CODE_SUCCESS;
584✔
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) {
611,042✔
3300
  if ((!hasDataInSttBlock(pScanInfo)) || (pScanInfo->cleanSttBlocks == true)) {
611,042✔
3301
    return true;
594,727✔
3302
  } else {
3303
    int64_t keyInStt = pScanInfo->sttKeyInfo.nextProcKey.ts;
16,346✔
3304
    return (asc && pBlockInfo->lastKey < keyInStt) || (!asc && pBlockInfo->firstKey > keyInStt);
16,346✔
3305
  }
3306
}
3307

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

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

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

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

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

3336
  if (pScanInfo->sttKeyInfo.status == STT_FILE_READER_UNINIT) {
637,452✔
3337
    initSttBlockReader(pSttBlockReader, pScanInfo, pReader);
390,130✔
3338
    if (pReader->code != 0) {
390,336!
3339
      return pReader->code;
×
3340
    }
3341
  }
3342

3343
  TSDBKEY keyInBuf = getCurrentKeyInBuf(pScanInfo, pReader);
637,658✔
3344
  if (fileBlockShouldLoad(pReader, pBlockInfo, pScanInfo, keyInBuf)) {
637,499✔
3345
    code = doLoadFileBlockData(pReader, pBlockIter, &pStatus->fileBlockData, pScanInfo->uid);
26,559✔
3346
    if (code != TSDB_CODE_SUCCESS) {
26,558!
3347
      return code;
×
3348
    }
3349

3350
    // build composed data block
3351
    code = buildComposedDataBlock(pReader);
26,558✔
3352
  } else if (bufferDataInFileBlockGap(keyInBuf, pBlockInfo, pScanInfo, pReader->info.order)) {
611,266✔
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);
119✔
3356
    code = buildDataBlockFromBuf(pReader, pScanInfo, endKey);
119✔
3357
  } else {
3358
    if (notOverlapWithFiles(pBlockInfo, pScanInfo, asc)) {
611,149✔
3359
      int64_t keyInStt = pScanInfo->sttKeyInfo.nextProcKey.ts;
610,878✔
3360

3361
      if ((!hasDataInSttBlock(pScanInfo)) || (asc && pBlockInfo->lastKey < keyInStt) ||
610,878!
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);
610,803✔
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;
221✔
3376
      tBlockDataReset(pBData);
221✔
3377

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

3380
      tsdbDebug("load data in stt block firstly %s", pReader->idStr);
255!
3381
      int64_t st = taosGetTimestampUs();
255✔
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);
255✔
3385
      if (pReader->code != 0) {
255!
3386
        return pReader->code;
×
3387
      }
3388

3389
      // no data in stt block, no need to proceed.
3390
      while (hasDataInSttBlock(pScanInfo)) {
421,187✔
3391
        if (pScanInfo->sttKeyInfo.status != STT_FILE_HAS_DATA) {
421,047!
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);
421,047✔
3397
        if (code != TSDB_CODE_SUCCESS) {
421,047!
3398
          return code;
×
3399
        }
3400

3401
        if (pResBlock->info.rows >= pReader->resBlockInfo.capacity) {
421,047✔
3402
          break;
100✔
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);
420,947✔
3407
        if ((pSttKey->ts >= pBlockInfo->firstKey && asc) || (pSttKey->ts <= pBlockInfo->lastKey && (!asc))) {
420,947✔
3408
          tsdbDebug("%p lastKeyInStt:%" PRId64 ", overlap with file block, brange:%" PRId64 "-%" PRId64 " %s", pReader,
15!
3409
                    pSttKey->ts, pBlockInfo->firstKey, pBlockInfo->lastKey, pReader->idStr);
3410
          break;
15✔
3411
        }
3412
      }
3413

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

3417
      if (pResBlock->info.rows > 0) {
255!
3418
        tsdbDebug("%p uid:%" PRIu64 ", composed data block created, brange:%" PRIu64 "-%" PRIu64 " rows:%" PRId64
255!
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;
637,566!
3427
}
3428

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

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

3435
  while (1) {
1,568,590✔
3436
    if (pReader->code != TSDB_CODE_SUCCESS) {
2,955,212!
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,955,212✔
3442
    if (pReader->pIgnoreTables &&
5,910,424!
3443
        taosHashGet(*pReader->pIgnoreTables, &(*pBlockScanInfo)->uid, sizeof((*pBlockScanInfo)->uid))) {
2,955,218✔
3444
      bool hasNexTable = moveToNextTableForPreFileSetMem(pStatus);
32,839✔
3445
      if (!hasNexTable) {
32,839!
3446
        return TSDB_CODE_SUCCESS;
×
3447
      }
3448
      continue;
32,839✔
3449
    }
3450

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

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

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

3466
    if (pReader->resBlockInfo.pResBlock->info.rows > 0) {
2,922,384✔
3467
      return TSDB_CODE_SUCCESS;
228,843✔
3468
    }
3469

3470
    // current table is exhausted, let's try next table
3471
    bool hasNexTable = moveToNextTableForPreFileSetMem(pStatus);
2,693,541✔
3472
    if (!hasNexTable) {
2,693,565✔
3473
      return TSDB_CODE_SUCCESS;
1,157,814✔
3474
    }
3475
  }
3476
}
3477

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

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

3484
  while (1) {
7,853,139✔
3485
    if (pReader->code != TSDB_CODE_SUCCESS) {
16,278,307!
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,278,307✔
3491
    if (pBlockScanInfo == NULL || *pBlockScanInfo == NULL) {
16,278,307!
3492
      return TSDB_CODE_SUCCESS;
×
3493
    }
3494

3495
    if (pReader->pIgnoreTables &&
32,508,542✔
3496
        taosHashGet(*pReader->pIgnoreTables, &(*pBlockScanInfo)->uid, sizeof((*pBlockScanInfo)->uid))) {
16,232,852✔
3497
      bool hasNexTable = moveToNextTable(pUidList, pStatus);
63,433✔
3498
      if (!hasNexTable) {
63,426✔
3499
        return TSDB_CODE_SUCCESS;
1,837✔
3500
      }
3501
      continue;
61,589✔
3502
    }
3503

3504
    int32_t code = initMemDataIterator(*pBlockScanInfo, pReader);
16,212,257✔
3505
    if (code != TSDB_CODE_SUCCESS) {
16,218,881!
3506
      return code;
×
3507
    }
3508

3509
    code = initDelSkylineIterator(*pBlockScanInfo, pReader->info.order, &pReader->cost);
16,218,881✔
3510
    if (code != TSDB_CODE_SUCCESS) {
16,217,262!
3511
      return code;
×
3512
    }
3513

3514
    code = buildDataBlockFromBuf(pReader, *pBlockScanInfo, endKey);
16,217,262✔
3515
    if (code != TSDB_CODE_SUCCESS) {
16,217,279✔
3516
      return code;
4✔
3517
    }
3518

3519
    if (pReader->resBlockInfo.pResBlock->info.rows > 0) {
16,217,275✔
3520
      return TSDB_CODE_SUCCESS;
3,634,805✔
3521
    }
3522

3523
    // current table is exhausted, let's try next table
3524
    bool hasNexTable = moveToNextTable(pUidList, pStatus);
12,582,470✔
3525
    if (!hasNexTable) {
12,585,178✔
3526
      return TSDB_CODE_SUCCESS;
4,793,628✔
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,132,364✔
3533
  SFileDataBlockInfo* pBlockInfo = NULL;
7,132,364✔
3534
  SReaderStatus*      pStatus = &pReader->status;
7,132,364✔
3535
  SFileBlockDumpInfo* pDumpInfo = &pStatus->fBlockDumpInfo;
7,132,364✔
3536

3537
  int32_t code = getCurrentBlockInfo(pBlockIter, &pBlockInfo, pReader->idStr);
7,132,364✔
3538
  if (code == TSDB_CODE_SUCCESS) {
7,132,425✔
3539
    pDumpInfo->totalRows = pBlockInfo->numRow;
637,193✔
3540
    pDumpInfo->rowIndex = ASCENDING_TRAVERSE(pReader->info.order) ? 0 : pBlockInfo->numRow - 1;
637,193✔
3541
  } else {
3542
    pDumpInfo->totalRows = 0;
6,495,232✔
3543
    pDumpInfo->rowIndex = 0;
6,495,232✔
3544
  }
3545

3546
  pDumpInfo->allDumped = false;
7,132,425✔
3547
}
7,132,425✔
3548

3549
static int32_t initForFirstBlockInFile(STsdbReader* pReader, SDataBlockIter* pBlockIter) {
8,796,160✔
3550
  SBlockNumber num = {0};
8,796,160✔
3551
  SArray*      pTableList = taosArrayInit(40, POINTER_BYTES);
8,796,160✔
3552
  if (pTableList == NULL) {
8,801,220!
3553
    return terrno;
×
3554
  }
3555

3556
  int32_t code = moveToNextFile(pReader, &num, pTableList);
8,801,220✔
3557
  if (code != TSDB_CODE_SUCCESS) {
8,800,164!
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) {
8,800,900✔
3564
    pReader->status.loadFromFile = false;
2,183,289✔
3565
    taosArrayDestroy(pTableList);
2,183,289✔
3566
    return code;
2,182,927✔
3567
  }
3568

3569
  // initialize the block iterator for a new fileset
3570
  if (num.numOfBlocks > 0) {
6,617,611✔
3571
    code = initBlockIterator(pReader, pBlockIter, num.numOfBlocks, pTableList);
119,842✔
3572
  } else {  // no block data, only last block exists
3573
    tBlockDataReset(&pReader->status.fileBlockData);
6,497,769✔
3574
    code = resetDataBlockIterator(pBlockIter, pReader->info.order, shouldFreePkBuf(&pReader->suppInfo), pReader->idStr);
6,493,502✔
3575
    if (code) {
6,496,332!
3576
      return code;
×
3577
    }
3578

3579
    code = resetTableListIndex(&pReader->status, pReader->idStr);
6,496,332✔
3580
    if (code) {
6,497,770!
3581
      return code;
×
3582
    }
3583
  }
3584

3585
  if (code == TSDB_CODE_SUCCESS) { // set the correct start position according to the query time window
6,617,669✔
3586
    initBlockDumpInfo(pReader, pBlockIter);
6,614,810✔
3587
  }
3588

3589
  taosArrayDestroy(pTableList);
6,618,743✔
3590
  return code;
6,619,307✔
3591
}
3592

3593
static bool fileBlockPartiallyRead(SFileBlockDumpInfo* pDumpInfo, bool asc) {
647,763✔
3594
  return (!pDumpInfo->allDumped) &&
658,401✔
3595
         ((pDumpInfo->rowIndex > 0 && asc) || (pDumpInfo->rowIndex < (pDumpInfo->totalRows - 1) && (!asc)));
10,638✔
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) {
6,950,396✔
3604
  int32_t         code = TSDB_CODE_SUCCESS;
6,950,396✔
3605
  SSDataBlock*    pResBlock = pReader->resBlockInfo.pResBlock;
6,950,396✔
3606
  SDataBlockIter* pBlockIter = &pReader->status.blockIter;
6,950,396✔
3607

3608
  *pReturnType = TSDB_READ_RETURN;
6,950,396✔
3609

3610
  tsdbDebug("seq load data blocks from stt files %s", pReader->idStr);
6,950,396✔
3611

3612
  while (1) {
3613
    code = doLoadSttBlockSequentially(pReader);
11,563,242✔
3614
    if (code != TSDB_CODE_SUCCESS) {
11,561,304!
3615
      *pReturnType = TSDB_READ_RETURN;
×
3616
      return code;
×
3617
    }
3618

3619
    if (pResBlock->info.rows > 0) {
11,561,304✔
3620
      *pReturnType = TSDB_READ_RETURN;
5,006,160✔
3621
      return code;
5,006,160✔
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,555,144!
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,555,144✔
3632

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

3639
    if (pReader->status.bProcMemPreFileset) {
4,881,671✔
3640
      code = buildFromPreFilesetBuffer(pReader);
1,101,108✔
3641
      if (code != TSDB_CODE_SUCCESS) {
1,101,103!
3642
        return code;
×
3643
      }
3644
      if (pResBlock->info.rows > 0) {
1,101,103✔
3645
        pReader->status.processingMemPreFileSet = true;
154,749✔
3646
        *pReturnType = TSDB_READ_RETURN;
154,749✔
3647
        return code;
154,749✔
3648
      }
3649
    }
3650

3651
    if (pBlockIter->numOfBlocks > 0) {  // there are data blocks existed.
4,726,917✔
3652
      *pReturnType = TSDB_READ_CONTINUE;
114,848✔
3653
      return code;
114,848✔
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,612,069✔
3656
      if (code) {
4,612,843!
3657
        return code;
×
3658
      }
3659
    }
3660
  }
3661
}
3662

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

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

3673
  if (pBlockIter->numOfBlocks == 0) {
7,472,542✔
3674
    // let's try to extract data from stt files.
3675
    ERetrieveType type = 0;
6,832,693✔
3676
    code = doReadDataFromSttFiles(pReader, &type);
6,832,693✔
3677
    if (code != 0 || type == TSDB_READ_RETURN) {
6,832,323!
3678
      return code;
6,832,098✔
3679
    }
3680

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

3687
  while (1) {
3688
    if (fileBlockPartiallyRead(pDumpInfo, asc)) {  // file data block is partially loaded
645,514✔
3689
      code = buildComposedDataBlock(pReader);
5,151✔
3690
    } else {
3691
      // current block are exhausted, try the next file block
3692
      if (pDumpInfo->allDumped) {
642,602✔
3693
        // try next data block in current file
3694
        bool hasNext = blockIteratorNext(&pReader->status.blockIter, pReader->idStr);
637,151✔
3695
        if (hasNext) {  // check for the next block in the block accessed order list
637,151✔
3696
          initBlockDumpInfo(pReader, pBlockIter);
517,501✔
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,650!
3701
            tBlockDataClear(pBlockData);
119,738✔
3702
          }
3703

3704
          tBlockDataReset(pBlockData);
119,644✔
3705
          code = resetDataBlockIterator(pBlockIter, pReader->info.order, shouldFreePkBuf(&pReader->suppInfo), id);
119,855✔
3706
          if (code != TSDB_CODE_SUCCESS) {
119,792!
3707
            return code;
5,437✔
3708
          }
3709

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

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

3723
      code = doBuildDataBlock(pReader);
637,194✔
3724
    }
3725

3726
    if (code != TSDB_CODE_SUCCESS || pResBlock->info.rows > 0) {
642,299✔
3727
      return code;
636,859✔
3728
    }
3729
  }
3730
}
3731

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

3738
  *pTsdb = NULL;
5,093,674✔
3739
  if (VND_IS_RSMA(pVnode) && !pCond->skipRollup) {
5,093,674✔
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,093,636✔
3782
}
3783

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

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

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

3798
static int32_t reverseSearchStartPos(const SArray* pDelList, int32_t index, int64_t key, bool asc) {
37,741,295✔
3799
  size_t  num = taosArrayGetSize(pDelList);
37,741,295✔
3800
  int32_t start = index;
36,085,835✔
3801

3802
  if (asc) {
36,085,835✔
3803
    if (start >= num - 1) {
29,634,842✔
3804
      start = num - 1;
10,416,709✔
3805
    }
3806

3807
    TSDBKEY* p = taosArrayGet(pDelList, start);
29,634,842✔
3808
    if (p == NULL) {
29,445,539!
3809
      return TSDB_CODE_INVALID_PARA;
×
3810
    }
3811

3812
    while (p->ts >= key && start > 0) {
29,497,056✔
3813
      start -= 1;
51,517✔
3814
    }
3815
  } else {
3816
    if (index <= 0) {
6,450,993!
3817
      start = 0;
×
3818
    }
3819

3820
    TSDBKEY* p = taosArrayGet(pDelList, start);
6,450,993✔
3821
    if (p == NULL) {
6,479,585!
3822
      return TSDB_CODE_INVALID_PARA;
×
3823
    }
3824

3825
    while (p->ts <= key && start < num - 1) {
6,481,575✔
3826
      start += 1;
1,990✔
3827
    }
3828
  }
3829

3830
  return start;
35,925,124✔
3831
}
3832

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

3839
  size_t  num = taosArrayGetSize(pDelList);
272,066,774✔
3840
  bool    asc = ASCENDING_TRAVERSE(order);
270,872,498✔
3841
  int32_t step = asc ? 1 : -1;
270,872,498✔
3842

3843
  if (hasPk) {  // handle the case where duplicated timestamps existed.
270,872,498✔
3844
    *index = reverseSearchStartPos(pDelList, *index, key, asc);
37,852,955✔
3845
  }
3846

3847
  if (asc) {
268,991,787✔
3848
    if (*index >= num - 1) {
244,733,844✔
3849
      TSDBKEY* last = taosArrayGetLast(pDelList);
50,532,098✔
3850
      if (last == NULL) {
50,459,263!
3851
        return false;
×
3852
      }
3853

3854
      if (key > last->ts) {
50,459,263✔
3855
        return false;
50,457,877✔
3856
      } else if (key == last->ts) {
1,386!
3857
        TSDBKEY* prev = taosArrayGet(pDelList, num - 2);
4,643✔
3858
        if (prev == NULL) {
4,643!
3859
          return false;
×
3860
        }
3861

3862
        return (prev->version >= ver && prev->version <= pVerRange->maxVer && prev->version >= pVerRange->minVer);
4,643!
3863
      }
3864
    } else {
3865
      TSDBKEY* pCurrent = taosArrayGet(pDelList, *index);
194,201,746✔
3866
      TSDBKEY* pNext = taosArrayGet(pDelList, (*index) + 1);
195,633,095✔
3867
      if (pCurrent == NULL || pNext == NULL) {
192,488,126!
3868
        return false;
×
3869
      }
3870

3871
      if (key < pCurrent->ts) {
192,488,126✔
3872
        return false;
9,358,288✔
3873
      }
3874

3875
      if (pCurrent->ts <= key && pNext->ts >= key && pCurrent->version >= ver &&
183,129,838!
3876
          pVerRange->maxVer >= pCurrent->version) {
11,605,719!
3877
        return true;
11,606,012✔
3878
      }
3879

3880
      while (pNext->ts <= key && (*index) < num - 1) {
172,545,696✔
3881
        (*index) += 1;
1,245,624✔
3882

3883
        if ((*index) < num - 1) {
1,245,624✔
3884
          pCurrent = taosArrayGet(pDelList, *index);
1,190,711✔
3885
          pNext = taosArrayGet(pDelList, (*index) + 1);
1,190,711✔
3886
          if (pCurrent == NULL || pNext == NULL) {
1,190,709!
3887
            return false;
×
3888
          }
3889

3890
          // it is not a consecutive deletion range, ignore it
3891
          if (pCurrent->version == 0 && pNext->version > 0) {
1,190,709✔
3892
            continue;
502,110✔
3893
          }
3894

3895
          if (pCurrent->ts <= key && pNext->ts >= key && pCurrent->version >= ver &&
688,599!
3896
              pVerRange->maxVer >= pCurrent->version) {
223,752!
3897
            return true;
223,752✔
3898
          }
3899
        }
3900
      }
3901

3902
      return false;
171,300,072✔
3903
    }
3904
  } else {
3905
    if (*index <= 0) {
24,257,943!
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);
24,257,943✔
3920
      TSDBKEY* pPrev = taosArrayGet(pDelList, (*index) - 1);
23,995,209✔
3921
      if (pCurrent == NULL || pPrev == NULL) {
23,883,802!
3922
        return false;
×
3923
      }
3924

3925
      if (key > pCurrent->ts) {
23,883,802✔
3926
        return false;
8,837,385✔
3927
      }
3928

3929
      if (pPrev->ts <= key && pCurrent->ts >= key && pPrev->version >= ver) {
15,046,417✔
3930
        return true;
753,993✔
3931
      }
3932

3933
      while (pPrev->ts >= key && (*index) > 1) {
14,376,582✔
3934
        (*index) += step;
184,858✔
3935

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

3943
          // it is not a consecutive deletion range, ignore it
3944
          if (pCurrent->version > 0 && pPrev->version == 0) {
184,858✔
3945
            continue;
32,619✔
3946
          }
3947

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

3954
      return false;
14,191,724✔
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,567,903,088!
3965
    return;
1,177,334,544✔
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,
194,887,562✔
3985
                                    pReader->suppInfo.numOfPks > 0);
194,887,562✔
3986
      if (!dropped) {
192,041,844!
3987
        *pRes = pRow;
191,879,972✔
3988
        return;
191,879,972✔
3989
      }
3990
    }
3991
  }
3992

3993
  while (1) {
3994
    pIter->hasVal = tsdbTbDataIterNext(pIter->iter);
×
3995
    if (!pIter->hasVal) {
5,324,028!
3996
      return;
10,187✔
3997
    }
3998

3999
    pRow = tsdbTbDataIterGet(pIter->iter);
5,313,841!
4000

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

4007
    if (key.version <= pReader->info.verRange.maxVer && key.version >= pReader->info.verRange.minVer) {
5,267,678!
4008
      if (pDelList == NULL || TARRAY_SIZE(pDelList) == 0) {
5,007,315!
4009
        *pRes = pRow;
768✔
4010
        return;
768✔
4011
      } else {
4012
        bool dropped = hasBeenDropped(pDelList, &pIter->index, key.ts, key.version, order, &pReader->info.verRange,
5,006,547✔
4013
                                      pReader->suppInfo.numOfPks > 0);
5,006,547✔
4014
        if (!dropped) {
5,004,810!
4015
          *pRes = pRow;
152,232✔
4016
          return;
152,232✔
4017
        }
4018
      }
4019
    }
4020
  }
4021
}
4022

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

4027
  while (1) {
2,260,020✔
4028
    pIter->hasVal = tsdbTbDataIterNext(pIter->iter);
173,807,328✔
4029
    if (!pIter->hasVal) {
173,799,322✔
4030
      break;
282,144✔
4031
    }
4032

4033
    // data exists but not valid
4034
    TSDBROW* pRow = NULL;
173,517,178!
4035
    getValidMemRow(pIter, pDelList, pReader, &pRow);
4036
    if (pRow == NULL) {
173,498,279✔
4037
      break;
45,620✔
4038
    }
4039

4040
    // ts is not identical, quit
4041
    if (TSDBROW_TS(pRow) != pCurKey->ts) {
173,452,659!
4042
      break;
171,249,751✔
4043
    }
4044

4045
    if (pCurKey->numOfPKs > 0) {
2,202,908✔
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;
2,202,476✔
4054
    if (pRow->type == TSDBROW_ROW_FMT) {
2,202,476!
4055
      pTSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(pRow), pReader, uid);
2,259,302!
4056
      if (pTSchema == NULL) {
2,259,320!
4057
        return terrno;
×
4058
      }
4059
    }
4060

4061
    code = tsdbRowMergerAdd(pMerger, pRow, pTSchema);
2,202,494✔
4062
    if (code != TSDB_CODE_SUCCESS) {
2,260,020!
4063
      return code;
×
4064
    }
4065
  }
4066

4067
  return code;
171,577,947✔
4068
}
4069

4070
static int32_t doMergeRowsInFileBlockImpl(SBlockData* pBlockData, int32_t* rowIndex, SRowKey* pKey, SRowMerger* pMerger,
25,118,857✔
4071
                                          SVersionRange* pVerRange, int32_t step) {
4072
  int32_t code = 0;
25,118,857✔
4073
  while ((*rowIndex) < pBlockData->nRow && (*rowIndex) >= 0) {
25,139,837!
4074
    SRowKey cur;
4075
    tColRowGetKey(pBlockData, (*rowIndex), &cur);
25,135,688✔
4076
    if (pkCompEx(&cur, pKey) != 0) {
25,206,477✔
4077
      break;
25,185,497✔
4078
    }
4079

4080
    if (pBlockData->aVersion[(*rowIndex)] > pVerRange->maxVer ||
20,980!
4081
        pBlockData->aVersion[(*rowIndex)] < pVerRange->minVer) {
×
4082
      (*rowIndex) += step;
20,980✔
4083
      continue;
20,980✔
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,189,646✔
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,
17,058✔
4102
                                         SFileDataBlockInfo* pFBlock, SRowMerger* pMerger, SRowKey* pKey,
4103
                                         CHECK_FILEBLOCK_STATE* state) {
4104
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;
17,058✔
4105
  SBlockData*         pBlockData = &pReader->status.fileBlockData;
17,058✔
4106
  bool                asc = ASCENDING_TRAVERSE(pReader->info.order);
17,058✔
4107
  SVersionRange*      pVerRange = &pReader->info.verRange;
17,058✔
4108
  bool                loadNeighbor = true;
17,058✔
4109
  int32_t             step = ASCENDING_TRAVERSE(pReader->info.order) ? 1 : -1;
17,058✔
4110

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

4114
  if (loadNeighbor && (code == TSDB_CODE_SUCCESS)) {
17,058!
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;
17,058✔
4125
}
4126

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

4136
  pDumpInfo->rowIndex += step;
25,122,056✔
4137
  if ((pDumpInfo->rowIndex <= pBlockData->nRow - 1 && asc) || (pDumpInfo->rowIndex >= 0 && !asc)) {
25,122,056!
4138
    code = doMergeRowsInFileBlockImpl(pBlockData, &pDumpInfo->rowIndex, pKey, pMerger, pRange, step);
25,114,035✔
4139
    if (code != TSDB_CODE_SUCCESS) {
25,220,429!
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,228,450!
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) {
17,058!
4152
        return code;
×
4153
      }
4154

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

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

4167
  return code;
25,330,729✔
4168
}
4169

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

4175
  while (1) {
2,638,645✔
4176
    code = nextRowFromSttBlocks(pSttBlockReader, pScanInfo, pkSrcSlot, pVerRange);
185,045,886✔
4177
    if (code || (!hasDataInSttBlock(pScanInfo))) {
184,358,771!
4178
      return code;
2,921,483✔
4179
    }
4180

4181
    SRowKey* pNextKey = getCurrentKeyInSttBlock(pSttBlockReader);
181,376,224!
4182

4183
    int32_t ret = pkCompEx(pRowKey, pNextKey);
181,434,223✔
4184
    if (ret == 0) {
181,434,223✔
4185
      TSDBROW* pRow1 = tMergeTreeGetRow(&pSttBlockReader->mergeTree);
2,645,191✔
4186
      code = tsdbRowMergerAdd(pMerger, pRow1, NULL);
2,645,191✔
4187
      if (code != TSDB_CODE_SUCCESS) {
2,638,645!
4188
        break;
×
4189
      }
4190
    } else {
4191
      tsdbTrace("uid:%" PRIu64 " last del index:%d, del range:%d, lastKeyInStt:%" PRId64 ", %s", pScanInfo->uid,
178,789,032!
4192
                pScanInfo->sttBlockDelIndex, (int32_t)taosArrayGetSize(pScanInfo->delSkyline),
4193
                pScanInfo->sttKeyInfo.nextProcKey.ts, idStr);
4194
      break;
178,775,163✔
4195
    }
4196
  }
4197

4198
  return code;
178,775,163✔
4199
}
4200

4201
int32_t doMergeMemTableMultiRows(TSDBROW* pRow, SRowKey* pKey, uint64_t uid, SIterInfo* pIter, SArray* pDelList,
1,206,256,056✔
4202
                                 TSDBROW* pResRow, STsdbReader* pReader, bool* freeTSRow) {
4203
  SRowMerger* pMerger = &pReader->status.merger;
1,206,256,056✔
4204
  TSDBROW*    pNextRow = NULL;
1,206,256,056✔
4205
  TSDBROW     current = *pRow;
1,206,256,056✔
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,206,256,056✔
4209

4210
    if (!pIter->hasVal) {
1,198,093,415✔
4211
      *pResRow = *pRow;
2,666,749✔
4212
      *freeTSRow = false;
2,666,749✔
4213
      return TSDB_CODE_SUCCESS;
2,666,749✔
4214
    } else {  // has next point in mem/imem
4215
      getValidMemRow(pIter, pDelList, pReader, &pNextRow);
4216
      if (pNextRow == NULL) {
1,195,045,555✔
4217
        *pResRow = current;
730,955✔
4218
        *freeTSRow = false;
730,955✔
4219
        return TSDB_CODE_SUCCESS;
730,955✔
4220
      }
4221

4222
      if (TSDBROW_TS(&current) != TSDBROW_TS(pNextRow)) {
1,194,314,600!
4223
        *pResRow = current;
1,192,002,583✔
4224
        *freeTSRow = false;
1,192,002,583✔
4225
        return TSDB_CODE_SUCCESS;
1,192,002,583✔
4226
      }
4227

4228
      if (pKey->numOfPKs > 0) {
2,312,017!
4229
        SRowKey nextRowKey = {0};
4,843,899✔
4230
        tRowGetKeyEx(pNextRow, &nextRowKey);
4,843,899!
4231
        if (pkCompEx(pKey, &nextRowKey) != 0) {
4,844,679✔
4232
          *pResRow = current;
4,844,145✔
4233
          *freeTSRow = false;
4,844,145✔
4234
          return TSDB_CODE_SUCCESS;
4,844,145✔
4235
        }
4236
      }
4237
    }
4238
  }
4239

4240
  terrno = 0;
×
4241
  int32_t code = 0;
6,664,823✔
4242

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

4252
  code = tsdbRowMergerAdd(pMerger, &current, pTSchema);
6,664,456✔
4253
  if (code != TSDB_CODE_SUCCESS) {
6,638,920!
4254
    return code;
×
4255
  }
4256

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

4265
  code = tsdbRowMergerAdd(pMerger, pNextRow, pTSchema1);
6,637,950✔
4266
  if (code != TSDB_CODE_SUCCESS) {
6,655,285!
4267
    return code;
×
4268
  }
4269

4270
  code = doMergeRowsInBuf(pIter, uid, pKey, pDelList, pReader);
6,655,285✔
4271
  if (code != TSDB_CODE_SUCCESS) {
6,627,399!
4272
    return code;
×
4273
  }
4274

4275
  code = tsdbRowMergerGetRow(pMerger, &pResRow->pTSRow);
6,627,399✔
4276
  if (code != TSDB_CODE_SUCCESS) {
6,673,485!
4277
    return code;
×
4278
  }
4279

4280
  pResRow->type = TSDBROW_ROW_FMT;
6,673,485✔
4281
  tsdbRowMergerClear(pMerger);
6,673,485✔
4282
  *freeTSRow = true;
6,637,446✔
4283

4284
  return TSDB_CODE_SUCCESS;
6,637,446✔
4285
}
4286

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

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

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

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

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

4319
    code = tsdbRowMergerAdd(pMerger, pRow, pSchema);
146,947✔
4320
    if (code != TSDB_CODE_SUCCESS) {
146,932!
4321
      return code;
×
4322
    }
4323

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

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

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

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

4350
  tRowKeyAssign(&pBlockScanInfo->lastProcKey, pRowKey);
146,903✔
4351

4352
  code = tsdbRowMergerGetRow(pMerger, pTSRow);
146,902✔
4353
  tsdbRowMergerClear(pMerger);
146,953✔
4354
  return code;
146,945✔
4355
}
4356

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

4362
  getValidMemRow(&pBlockScanInfo->iter, pBlockScanInfo->delSkyline, pReader, &pRow);
1,178,493,357✔
4363
  getValidMemRow(&pBlockScanInfo->iiter, pBlockScanInfo->delSkyline, pReader, &piRow);
1,182,302,144✔
4364

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

4371
  // todo refactor
4372
  bool asc = ASCENDING_TRAVERSE(pReader->info.order);
1,182,294,070✔
4373
  if (piter->hasVal) {
1,182,294,070✔
4374
    tRowGetKeyEx(pRow, &rowKey);
1,178,953,927!
4375
    if ((rowKey.ts >= endKey && asc) || (rowKey.ts <= endKey && !asc)) {
1,187,201,139✔
4376
      pRow = NULL;
1,410,566✔
4377
    }
4378
  }
4379

4380
  if (piiter->hasVal) {
1,190,541,282✔
4381
    tRowGetKeyEx(piRow, &irowKey);
43,508,062!
4382
    if ((irowKey.ts >= endKey && asc) || (irowKey.ts <= endKey && !asc)) {
69,577,655!
4383
      piRow = NULL;
×
4384
    }
4385
  }
4386

4387
  if (pRow != NULL && piRow != NULL) {
1,216,610,875✔
4388
    int32_t code = TSDB_CODE_SUCCESS;
10,704,497✔
4389
    if (rowKey.numOfPKs == 0) {
10,704,497✔
4390
      if ((rowKey.ts > irowKey.ts && asc) || (rowKey.ts < irowKey.ts && (!asc))) {  // ik.ts < k.ts
10,669,781!
4391
        code = doMergeMemTableMultiRows(piRow, &irowKey, uid, piiter, pDelList, pResRow, pReader, freeTSRow);
10,521,582✔
4392
      } else if ((rowKey.ts < irowKey.ts && asc) || (rowKey.ts > irowKey.ts && (!asc))) {
148,199!
4393
        code = doMergeMemTableMultiRows(pRow, &rowKey, uid, piter, pDelList, pResRow, pReader, freeTSRow);
5,777✔
4394
      } else {  // ik.ts == k.ts
4395
        *freeTSRow = true;
142,422✔
4396
        pResRow->type = TSDBROW_ROW_FMT;
142,422✔
4397
        code = doMergeMemIMemRows(pRow, &rowKey, piRow, &irowKey, pBlockScanInfo, pReader, &pResRow->pTSRow);
142,422✔
4398
        if (code != TSDB_CODE_SUCCESS) {
146,945!
4399
          return code;
×
4400
        }
4401
      }
4402
    } else {
4403
      int32_t ret = pkCompEx(&rowKey, &irowKey);
32,836✔
4404
      if (ret != 0) {
32,836✔
4405
        if ((ret > 0 && asc) || (ret < 0 && (!asc))) {  // ik.ts < k.ts
32,832✔
4406
          code = doMergeMemTableMultiRows(piRow, &irowKey, uid, piiter, pDelList, pResRow, pReader, freeTSRow);
25,038✔
4407
        } else if ((ret < 0 && asc) || (ret > 0 && (!asc))) {
7,794!
4408
          code = doMergeMemTableMultiRows(pRow, &rowKey, uid, piter, pDelList, pResRow, pReader, freeTSRow);
7,797✔
4409
        }
4410
      } else {  // ik.ts == k.ts
4411
        *freeTSRow = true;
4✔
4412
        pResRow->type = TSDBROW_ROW_FMT;
4✔
4413
        code = doMergeMemIMemRows(pRow, &rowKey, piRow, &irowKey, pBlockScanInfo, pReader, &pResRow->pTSRow);
4✔
4414
        if (code != TSDB_CODE_SUCCESS) {
×
4415
          return code;
×
4416
        }
4417
      }
4418
    }
4419

4420
    return code;
10,689,854✔
4421
  }
4422

4423
  if (piter->hasVal && pRow != NULL) {
1,205,906,378!
4424
    return doMergeMemTableMultiRows(pRow, &rowKey, uid, piter, pDelList, pResRow, pReader, freeTSRow);
1,171,083,957✔
4425
  }
4426

4427
  if (piiter->hasVal && piRow != NULL) {
34,822,421!
4428
    return doMergeMemTableMultiRows(piRow, &irowKey, uid, piiter, pDelList, pResRow, pReader, freeTSRow);
32,952,791✔
4429
  }
4430

4431
  return TSDB_CODE_SUCCESS;
1,869,630✔
4432
}
4433

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

4439
  SBlockLoadSuppInfo* pSupInfo = &pReader->suppInfo;
1,556,612,929✔
4440
  STSchema*           pSchema = doGetSchemaForTSRow(pTSRow->sver, pReader, uid);
1,556,612,929!
4441
  if (pSchema == NULL) {
1,557,487,198!
4442
    return terrno;
×
4443
  }
4444

4445
  SColVal colVal = {0};
1,557,487,198✔
4446
  int32_t i = 0, j = 0;
1,557,487,198✔
4447

4448
  if (pSupInfo->colId[i] == PRIMARYKEY_TIMESTAMP_COL_ID) {
1,557,487,198!
4449
    SColumnInfoData* pColData = taosArrayGet(pBlock->pDataBlock, pSupInfo->slotId[i]);
1,561,672,541✔
4450
    if (pColData == NULL) {
1,548,270,187!
4451
      return TSDB_CODE_INVALID_PARA;
×
4452
    }
4453

4454
    ((int64_t*)pColData->pData)[outputRowIndex] = pTSRow->ts;
1,548,270,187✔
4455
    i += 1;
1,548,270,187✔
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,582,613,904✔
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,582,572,783✔
4503
  pBlock->info.rows += 1;
1,582,572,783✔
4504
  return TSDB_CODE_SUCCESS;
1,582,572,783✔
4505
}
4506

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

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

4517
  SColVal cv = {0};
331,016,866✔
4518
  int32_t numOfInputCols = pBlockData->nColData;
331,016,866✔
4519
  int32_t numOfOutputCols = pSupInfo->numOfCols;
331,016,866✔
4520

4521
  while (i < numOfOutputCols && j < numOfInputCols) {
724,700,219✔
4522
    SColData* pData = tBlockDataGetColDataByIdx(pBlockData, j);
374,862,192✔
4523
    if (pData->cid < pSupInfo->colId[i]) {
374,862,192✔
4524
      j += 1;
142✔
4525
      continue;
142✔
4526
    }
4527

4528
    SColumnInfoData* pCol = TARRAY_GET_ELEM(pResBlock->pDataBlock, pSupInfo->slotId[i]);
374,862,050✔
4529
    if (pData->cid == pSupInfo->colId[i]) {
374,862,050!
4530
      tColDataGetValue(pData, rowIndex, &cv);
375,245,845✔
4531
      code = doCopyColVal(pCol, outputRowIndex, i, &cv, pSupInfo);
399,713,983✔
4532
      if (code) {
394,067,006!
4533
        return code;
×
4534
      }
4535
      j += 1;
394,067,006✔
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;
393,683,211✔
4542
  }
4543

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

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

4554
  pResBlock->info.dataLoad = 1;
349,838,027✔
4555
  pResBlock->info.rows += 1;
349,838,027✔
4556
  return TSDB_CODE_SUCCESS;
349,838,027✔
4557
}
4558

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

4564
  do {
1,174,475,182✔
4565
    TSDBROW row = {.type = -1};
1,179,979,024✔
4566
    bool    freeTSRow = false;
1,179,979,024✔
4567
    code = tsdbGetNextRowInMem(pBlockScanInfo, pReader, &row, endKey, &freeTSRow);
1,179,979,024✔
4568
    if (code != TSDB_CODE_SUCCESS) {
1,198,779,676!
4569
      return code;
4✔
4570
    }
4571

4572
    if (row.type == -1) {
1,198,779,676✔
4573
      break;
1,869,849✔
4574
    }
4575

4576
    if (row.type == TSDBROW_ROW_FMT) {
1,196,909,827✔
4577
      code = doAppendRowFromTSRow(pBlock, pReader, row.pTSRow, pBlockScanInfo);
1,192,933,710✔
4578
      if (code == TSDB_CODE_SUCCESS) {
1,177,088,912!
4579
        pBlockScanInfo->lastProcKey.ts = row.pTSRow->ts;
1,178,770,862✔
4580
        pBlockScanInfo->lastProcKey.numOfPKs = row.pTSRow->numOfPKs;
1,178,770,862✔
4581
        if (row.pTSRow->numOfPKs > 0) {
1,178,770,862✔
4582
          tRowGetPrimaryKeyDeepCopy(row.pTSRow, &pBlockScanInfo->lastProcKey);
21,649,613✔
4583
        }
4584
      }
4585

4586
      if (freeTSRow) {
1,177,102,566✔
4587
        taosMemoryFree(row.pTSRow);
6,785,551✔
4588
      }
4589

4590
      if (code) {
1,177,154,299✔
4591
        return code;
4✔
4592
      }
4593
    } else {
4594
      code = doAppendRowFromFileBlock(pBlock, pReader, row.pBlockData, row.iRow);
3,976,117✔
4595
      if (code) {
360!
4596
        return code;
×
4597
      }
4598

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

4602
    // no data in buffer, return immediately
4603
    if (!(pBlockScanInfo->iter.hasVal || pBlockScanInfo->iiter.hasVal)) {
1,178,111,251✔
4604
      break;
3,497,283✔
4605
    }
4606

4607
    if (pBlock->info.rows >= capacity) {
1,174,613,968✔
4608
      break;
138,786✔
4609
    }
4610
  } while (1);
4611

4612
  return code;
5,505,918✔
4613
}
4614

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

4620
  STableBlockScanInfo** p = NULL;
19,954✔
4621
  int32_t               iter = 0;
19,954✔
4622

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

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

4632
  tSimpleHashClear(pReader->status.pTableMap);
19,951✔
4633

4634
  if (size < num) {
19,950✔
4635
    code = ensureBlockScanInfoBuf(&pReader->blockInfoBuf, num);
8✔
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;
19,948✔
4651
  pUidList->currentIndex = 0;
19,948✔
4652

4653
  STableKeyInfo* pList = (STableKeyInfo*)pTableList;
19,948✔
4654
  for (int32_t i = 0; i < num; ++i) {
39,904✔
4655
    pUidList->tableUidList[i] = pList[i].uid;
19,954✔
4656

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

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

4671
  (void) tsdbReleaseReader(pReader);
19,950✔
4672
  return code;
19,953✔
4673
}
4674

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

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

4682
  if (pReader->bFilesetDelimited) {
4,910,163✔
4683
    getMemTableTimeRange(pReader, &pReader->status.memTableMaxKey, &pReader->status.memTableMinKey);
1,975,209✔
4684
    pReader->status.bProcMemFirstFileset = true;
1,975,846✔
4685
  }
4686

4687
  code = initFilesetIterator(&pStatus->fileIter, pReader->pReadSnap->pfSetArray, pReader);
4,910,800✔
4688
  if (code != TSDB_CODE_SUCCESS) {
4,912,959!
4689
    return code;
×
4690
  }
4691

4692
  code = resetDataBlockIterator(&pStatus->blockIter, pReader->info.order, shouldFreePkBuf(&pReader->suppInfo),
4,910,756✔
4693
                                pReader->idStr);
4,912,959✔
4694
  if (code != TSDB_CODE_SUCCESS) {
4,910,913!
4695
    return code;
×
4696
  }
4697

4698
  if (pStatus->fileIter.numOfFiles == 0) {
4,910,913✔
4699
    pStatus->loadFromFile = false;
2,693,210✔
4700
  } else {
4701
    code = initForFirstBlockInFile(pReader, pBlockIter);
2,217,703✔
4702
  }
4703

4704
  if (!pStatus->loadFromFile) {
4,910,792✔
4705
    code = resetTableListIndex(pStatus, pReader->idStr);
3,196,191✔
4706
  }
4707

4708
  return code;
4,913,074✔
4709
}
4710

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

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

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

4734
  if (pDst->info.pSchema) {
3,634!
4735
    return tsdbRowMergerInit(&pDst->status.merger, pDst->info.pSchema);
3,634✔
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,075,957✔
4743
                        SSDataBlock* pResBlock, void** ppReader, const char* idstr, SHashObj** pIgnoreTables) {
4744
  STimeWindow window = pCond->twindows;
5,075,957✔
4745
  SVnodeCfg*  pConf = &(((SVnode*)pVnode)->config);
5,075,957✔
4746
  int32_t     code = 0;
5,075,957✔
4747
  int32_t     lino = 0;
5,075,957✔
4748

4749
  int32_t capacity = pConf->tsdbCfg.maxRows;
5,075,957✔
4750
  if (pResBlock != NULL) {
5,075,957!
4751
    code = blockDataEnsureCapacity(pResBlock, capacity);
5,089,491✔
4752
    TSDB_CHECK_CODE(code, lino, _err);
5,091,840!
4753
  }
4754

4755
  code = tsdbReaderCreate(pVnode, pCond, ppReader, capacity, pResBlock, idstr);
5,078,306✔
4756
  TSDB_CHECK_CODE(code, lino, _err);
5,081,998!
4757

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

4765
  if (pCond->type == TIMEWINDOW_RANGE_EXTERNAL) {
5,027,990✔
4766
    // update the SQueryTableDataCond to create inner reader
4767
    int32_t order = pCond->order;
1,817✔
4768
    if (order == TSDB_ORDER_ASC) {
1,817!
4769
      pCond->twindows.ekey = window.skey - 1;
1,817✔
4770
      pCond->twindows.skey = INT64_MIN;
1,817✔
4771
      pCond->order = TSDB_ORDER_DESC;
1,817✔
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,817✔
4780
    TSDB_CHECK_CODE(code, lino, _err);
1,817!
4781

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

4791
    code = tsdbReaderCreate(pVnode, pCond, (void**)&((STsdbReader*)pReader)->innerReader[1], 1, pResBlock, idstr);
1,817✔
4792
    TSDB_CHECK_CODE(code, lino, _err);
1,817!
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,027,990✔
4799
    code = metaGetTbTSchemaMaybeNull(pReader->pTsdb->pVnode->pMeta, pReader->info.suid, -1, 1, &pReader->info.pSchema);
4,719,353✔
4800
    TSDB_CHECK_CODE(code, lino, _err);
4,734,329!
4801
    if (pReader->info.pSchema == NULL) {
4,734,329✔
4802
      tsdbWarn("failed to get table schema, suid:%" PRIu64 ", ver:-1, %s", pReader->info.suid, pReader->idStr);
1!
4803
    }
4804
  } else if (numOfTables > 0) {
308,637✔
4805
    STableKeyInfo* pKey = pTableList;
308,194✔
4806
    code = metaGetTbTSchemaMaybeNull(pReader->pTsdb->pVnode->pMeta, pKey->uid, -1, 1, &pReader->info.pSchema);
308,194✔
4807
    TSDB_CHECK_CODE(code, lino, _err);
308,298!
4808
    if (pReader->info.pSchema == NULL) {
308,298!
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,043,070✔
4814
    code = tsdbRowMergerInit(&pReader->status.merger, pReader->info.pSchema);
5,034,199✔
4815
    TSDB_CHECK_CODE(code, lino, _err);
5,042,052!
4816
  }
4817

4818
  pReader->pSchemaMap = tSimpleHashInit(8, taosFastHash);
5,050,923✔
4819
  if (pReader->pSchemaMap == NULL) {
5,041,511!
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,041,511✔
4825
  if (pReader->info.pSchema != NULL) {
5,040,206!
4826
    code = updateBlockSMAInfo(pReader->info.pSchema, &pReader->suppInfo);
5,040,882✔
4827
    TSDB_CHECK_CODE(code, lino, _err);
5,045,785✔
4828
  }
4829

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

4832
  code = createDataBlockScanInfo(p, &pReader->blockInfoBuf, pTableList, &pReader->status.uidList, numOfTables, &pReader->status.pTableMap);
5,045,093✔
4833
  TSDB_CHECK_CODE(code, lino, _err);
5,047,998!
4834

4835
  pReader->status.pLDataIterArray = taosArrayInit(4, POINTER_BYTES);
5,047,998✔
4836
  TSDB_CHECK_NULL(pReader->status.pLDataIterArray, code, lino, _err, terrno);
5,047,140✔
4837

4838
  pReader->flag = READER_STATUS_SUSPEND;
5,046,072✔
4839
  pReader->info.execMode = pCond->notLoadData ? READER_EXEC_ROWS : READER_EXEC_DATA;
5,046,072✔
4840

4841
  pReader->pIgnoreTables = pIgnoreTables;
5,046,072✔
4842
  tsdbDebug("%p total numOfTable:%d, window:%" PRId64 " - %" PRId64 ", verRange:%" PRId64 " - %" PRId64
5,046,072✔
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,046,619✔
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,190,226✔
4857
  if (pReader == NULL) {
9,190,226✔
4858
    return;
4,091,286✔
4859
  }
4860

4861
  int32_t code = tsdbAcquireReader(pReader);
5,098,940✔
4862
  if (code) {
5,099,700!
4863
    return;
×
4864
  }
4865

4866
  {
4867
    if (pReader->innerReader[0] != NULL || pReader->innerReader[1] != NULL) {
5,099,700!
4868
      STsdbReader* p = pReader->innerReader[0];
1,777✔
4869
      clearSharedPtr(p);
1,777✔
4870

4871
      p = pReader->innerReader[1];
1,817✔
4872
      clearSharedPtr(p);
1,817✔
4873

4874
      tsdbReaderClose2(pReader->innerReader[0]);
1,817✔
4875
      tsdbReaderClose2(pReader->innerReader[1]);
1,817✔
4876
    }
4877
  }
4878

4879
  SBlockLoadSuppInfo* pSupInfo = &pReader->suppInfo;
5,099,251✔
4880
  TARRAY2_DESTROY(&pSupInfo->colAggArray, NULL);
5,099,251✔
4881

4882
  if (pSupInfo->buildBuf) {
5,099,251!
4883
    for (int32_t i = 0; i < pSupInfo->numOfCols; ++i) {
31,386,812✔
4884
      if (pSupInfo->buildBuf[i] != NULL) {
26,287,427✔
4885
        taosMemoryFreeClear(pSupInfo->buildBuf[i]);
3,607,187!
4886
      }
4887
    }
4888
  }
4889

4890
  if (pReader->resBlockInfo.freeBlock) {
5,099,182✔
4891
    blockDataDestroy(pReader->resBlockInfo.pResBlock);
2,528✔
4892
    pReader->resBlockInfo.pResBlock = NULL;
2,528✔
4893
  }
4894

4895
  taosMemoryFree(pSupInfo->colId);
5,099,182✔
4896
  tBlockDataDestroy(&pReader->status.fileBlockData);
5,099,756✔
4897
  cleanupDataBlockIterator(&pReader->status.blockIter, shouldFreePkBuf(&pReader->suppInfo));
5,099,120✔
4898

4899
  size_t numOfTables = tSimpleHashGetSize(pReader->status.pTableMap);
5,099,702✔
4900
  if (pReader->status.pTableMap != NULL) {
5,099,478✔
4901
    destroyAllBlockScanInfo(pReader->status.pTableMap);
5,048,592✔
4902
    pReader->status.pTableMap = NULL;
5,049,148✔
4903
  }
4904
  clearBlockScanInfoBuf(&pReader->blockInfoBuf);
5,100,034✔
4905

4906
  if (pReader->pFileReader != NULL) {
5,099,863✔
4907
    tsdbDataFileReaderClose(&pReader->pFileReader);
14,875✔
4908
  }
4909

4910
  SReadCostSummary* pCost = &pReader->cost;
5,099,863✔
4911
  SFilesetIter*     pFilesetIter = &pReader->status.fileIter;
5,099,863✔
4912
  if (pFilesetIter->pSttBlockReader != NULL) {
5,099,863✔
4913
    SSttBlockReader* pSttBlockReader = pFilesetIter->pSttBlockReader;
4,915,329✔
4914
    tMergeTreeClose(&pSttBlockReader->mergeTree);
4,915,329✔
4915

4916
    clearRowKey(&pSttBlockReader->currentKey);
4,914,693✔
4917
    taosMemoryFree(pSttBlockReader);
4,914,782✔
4918
  }
4919

4920
  destroySttBlockReader(pReader->status.pLDataIterArray, &pCost->sttCost);
5,099,761✔
4921
  taosMemoryFreeClear(pReader->status.uidList.tableUidList);
5,099,844✔
4922

4923
  tsdbTrace("tsdb/reader-close: %p, untake snapshot", pReader);
5,099,943✔
4924
  void* p = pReader->pReadSnap;
5,099,945✔
4925
  if ((p == atomic_val_compare_exchange_ptr((void**)&pReader->pReadSnap, p, NULL)) && (p != NULL)) {
5,099,945!
4926
    tsdbUntakeReadSnap2(pReader, p, true);
4,911,633✔
4927
    pReader->pReadSnap = NULL;
4,911,715✔
4928
  }
4929

4930
  (void) tsem_destroy(&pReader->resumeAfterSuspend);
5,100,079✔
4931
  (void) tsdbReleaseReader(pReader);
5,099,115✔
4932
  (void) tsdbUninitReaderLock(pReader);
5,099,740✔
4933

4934
  tsdbDebug(
5,098,990✔
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,098,991✔
4949

4950
  tsdbRowMergerCleanup(&pReader->status.merger);
5,099,929✔
4951
  taosMemoryFree(pReader->info.pSchema);
5,099,444✔
4952

4953
  tSimpleHashCleanup(pReader->pSchemaMap);
5,099,926✔
4954
  taosMemoryFreeClear(pReader);
5,099,855!
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);
2✔
4962

4963
    SReadCostSummary* pCost = &pCurrentReader->cost;
2✔
4964
    destroySttBlockReader(pStatus->pLDataIterArray, &pCost->sttCost);
2✔
4965
    pStatus->pLDataIterArray = taosArrayInit(4, POINTER_BYTES);
2✔
4966
    if (pStatus->pLDataIterArray == NULL) {
2!
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,039,344✔
5055
  int32_t               code = 0;
5,039,344✔
5056
  STableBlockScanInfo** pBlockScanInfo = pReader->status.pTableIter;
5,039,344✔
5057

5058
  //  restore reader's state, task snapshot
5059
  int32_t numOfTables = tSimpleHashGetSize(pReader->status.pTableMap);
5,039,344✔
5060
  if (numOfTables > 0) {
5,042,641✔
5061
    tsdbTrace("tsdb/reader: %p, take snapshot", pReader);
4,906,816✔
5062
    code = tsdbTakeReadSnap2(pReader, tsdbSetQueryReseek, &pReader->pReadSnap, pReader->idStr);
4,906,816✔
5063
    if (code != TSDB_CODE_SUCCESS) {
4,910,462!
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,910,462✔
5070

5071
    if (pReader->type == TIMEWINDOW_RANGE_CONTAINED) {
4,910,462✔
5072
      code = doOpenReaderImpl(pReader);
4,909,154✔
5073
      if (code != TSDB_CODE_SUCCESS) {
4,905,844!
5074
        return code;
×
5075
      }
5076
    } else {
5077
      STsdbReader* pPrevReader = pReader->innerReader[0];
1,308✔
5078
      STsdbReader* pNextReader = pReader->innerReader[1];
1,308✔
5079

5080
      // we need only one row
5081
      pPrevReader->resBlockInfo.capacity = 1;
1,308✔
5082
      code = setSharedPtr(pPrevReader, pReader);
1,308✔
5083
      if (code != TSDB_CODE_SUCCESS) {
1,817!
5084
        return code;
×
5085
      }
5086

5087
      pNextReader->resBlockInfo.capacity = 1;
1,817✔
5088
      code = setSharedPtr(pNextReader, pReader);
1,817✔
5089
      if (code != TSDB_CODE_SUCCESS) {
1,817!
5090
        return code;
×
5091
      }
5092

5093
      if (pReader->step == 0 || pReader->step == EXTERNAL_ROWS_PREV) {
1,817!
5094
        code = doOpenReaderImpl(pPrevReader);
1,817✔
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,817!
5102
        return code;
×
5103
      }
5104
    }
5105
  }
5106

5107
  tsdbDebug("reader: %p resumed uid %" PRIu64 ", numOfTable:%" PRId32 ", in this query %s", pReader,
5,043,486!
5108
            pBlockScanInfo ? (*pBlockScanInfo)->uid : 0, numOfTables, pReader->idStr);
5109
  return code;
5,040,621✔
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,386,643✔
5117
  int32_t        code = TSDB_CODE_SUCCESS;
1,386,643✔
5118
  SReaderStatus* pStatus = &pReader->status;
1,386,643✔
5119

5120
  SSDataBlock* pBlock = pReader->resBlockInfo.pResBlock;
1,386,643✔
5121

5122
  int32_t     fid = pReader->status.pCurrentFileset->fid;
1,386,643✔
5123
  STimeWindow win = {0};
1,386,643✔
5124
  tsdbFidKeyRange(fid, pReader->pTsdb->keepCfg.days, pReader->pTsdb->keepCfg.precision, &win.skey, &win.ekey);
1,386,643✔
5125

5126
  int64_t endKey = (ASCENDING_TRAVERSE(pReader->info.order)) ? win.skey : win.ekey;
1,386,643✔
5127
  code = buildBlockFromBufferSeqForPreFileset(pReader, endKey);
1,386,643✔
5128
  if (code != TSDB_CODE_SUCCESS || pBlock->info.rows > 0) {
1,386,650✔
5129
    return code;
228,840✔
5130
  } else {
5131
    tsdbDebug("finished pre-fileset %d buffer processing. %s", fid, pReader->idStr);
1,157,810!
5132
    pStatus->bProcMemPreFileset = false;
1,157,808✔
5133
    pStatus->processingMemPreFileSet = false;
1,157,808✔
5134
    if (pReader->notifyFn) {
1,157,808!
5135
      STsdReaderNotifyInfo info = {0};
1,157,808✔
5136
      info.duration.filesetId = fid;
1,157,808✔
5137
      pReader->notifyFn(TSD_READER_NOTIFY_DURATION_START, &info, pReader->notifyParam);
1,157,808✔
5138
      tsdbDebug("new duration %d start notification when buffer pre-fileset, %s", fid, pReader->idStr);
1,157,815!
5139
    }
5140
  }
5141
  return code;
1,157,817✔
5142
}
5143

5144
static int32_t doTsdbNextDataBlockFilesetDelimited(STsdbReader* pReader) {
5,509,680✔
5145
  SReaderStatus* pStatus = &pReader->status;
5,509,680✔
5146
  int32_t        code = TSDB_CODE_SUCCESS;
5,509,680✔
5147
  SSDataBlock*   pBlock = pReader->resBlockInfo.pResBlock;
5,509,680✔
5148

5149
  if (pStatus->loadFromFile) {
5,509,680✔
5150
    if (pStatus->bProcMemPreFileset) {
2,961,342✔
5151
      code = buildFromPreFilesetBuffer(pReader);
285,550✔
5152
      if (code != TSDB_CODE_SUCCESS || pBlock->info.rows > 0) {
285,554✔
5153
        return code;
74,095✔
5154
      }
5155
    }
5156

5157
    code = buildBlockFromFiles(pReader);
2,887,251✔
5158
    if (code != TSDB_CODE_SUCCESS) {
2,887,777!
5159
      return code;
×
5160
    }
5161

5162
    tsdbTrace("block from file rows: %" PRId64 ", will process pre-file set buffer: %d. %s", pBlock->info.rows,
2,887,777!
5163
              pStatus->bProcMemFirstFileset, pReader->idStr);
5164
    if (pStatus->bProcMemPreFileset) {
2,887,777✔
5165
      if (pBlock->info.rows > 0) {
154,749!
5166
        if (pReader->notifyFn && !pReader->status.processingMemPreFileSet) {
154,749!
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) {
2,887,777✔
5178
      code = resetTableListIndex(&pReader->status, pReader->idStr);
756,505✔
5179
      if (code) {
756,521!
5180
        return code;
×
5181
      }
5182

5183
      int64_t endKey = (ASCENDING_TRAVERSE(pReader->info.order)) ? INT64_MAX : INT64_MIN;
756,521✔
5184
      code = buildBlockFromBufferSequentially(pReader, endKey);
756,521✔
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,548,338✔
5188
    code = buildBlockFromBufferSequentially(pReader, endKey);
2,548,338✔
5189
  }
5190
  return code;
5,439,197✔
5191
}
5192

5193
static int32_t doTsdbNextDataBlockFilesFirst(STsdbReader* pReader) {
8,784,349✔
5194
  SReaderStatus* pStatus = &pReader->status;
8,784,349✔
5195
  int32_t        code = TSDB_CODE_SUCCESS;
8,784,349✔
5196
  SSDataBlock*   pBlock = pReader->resBlockInfo.pResBlock;
8,784,349✔
5197

5198
  if (pStatus->loadFromFile) {
8,784,349✔
5199
    code = buildBlockFromFiles(pReader);
4,587,646✔
5200
    if (code != TSDB_CODE_SUCCESS) {
4,586,062!
5201
      return code;
×
5202
    }
5203

5204
    if (pBlock->info.rows <= 0) {
4,586,062✔
5205
      code = resetTableListIndex(&pReader->status, pReader->idStr);
920,478✔
5206
      if (code) {
920,489!
5207
        return code;
×
5208
      }
5209

5210
      int64_t endKey = (ASCENDING_TRAVERSE(pReader->info.order)) ? INT64_MAX : INT64_MIN;
920,489✔
5211
      code = buildBlockFromBufferSequentially(pReader, endKey);
920,489✔
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,196,703✔
5215
    code = buildBlockFromBufferSequentially(pReader, endKey);
4,196,703✔
5216
  }
5217
  return code;
8,787,306✔
5218
}
5219

5220
static int32_t doTsdbNextDataBlock2(STsdbReader* pReader, bool* hasNext) {
14,428,579✔
5221
  int32_t code = TSDB_CODE_SUCCESS;
14,428,579✔
5222

5223
  // cleanup the data that belongs to the previous data block
5224
  SSDataBlock* pBlock = pReader->resBlockInfo.pResBlock;
14,428,579✔
5225
  blockDataCleanup(pBlock);
14,428,579✔
5226

5227
  *hasNext = false;
14,436,949✔
5228

5229
  SReaderStatus* pStatus = &pReader->status;
14,436,949✔
5230
  if (tSimpleHashGetSize(pStatus->pTableMap) == 0) {
14,436,949✔
5231
    return code;
136,886✔
5232
  }
5233

5234
  if (!pReader->bFilesetDelimited) {
14,301,216✔
5235
    code = doTsdbNextDataBlockFilesFirst(pReader);
8,788,791✔
5236
  } else {
5237
    code = doTsdbNextDataBlockFilesetDelimited(pReader);
5,512,425✔
5238
  }
5239

5240
  *hasNext = pBlock->info.rows > 0;
14,301,526✔
5241

5242
  return code;
14,301,526✔
5243
}
5244

5245
int32_t tsdbNextDataBlock2(STsdbReader* pReader, bool* hasNext) {
14,473,917✔
5246
  int32_t code = TSDB_CODE_SUCCESS;
14,473,917✔
5247

5248
  *hasNext = false;
14,473,917✔
5249

5250
  if (isEmptyQueryTimeWindow(&pReader->info.window) || pReader->step == EXTERNAL_ROWS_NEXT ||
14,473,917!
5251
      pReader->code != TSDB_CODE_SUCCESS) {
14,435,793✔
5252
    return (pReader->code != TSDB_CODE_SUCCESS) ? pReader->code : code;
44,337!
5253
  }
5254

5255
  SReaderStatus* pStatus = &pReader->status;
14,434,459✔
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);
14,434,459✔
5268
  if (code != TSDB_CODE_SUCCESS) {
14,435,893!
5269
    return code;
×
5270
  }
5271

5272
  tsdbTrace("tsdb/read: %p, take read mutex, code: %d", pReader, code);
14,435,893✔
5273

5274
  if (pReader->flag == READER_STATUS_SUSPEND) {
14,435,893✔
5275
    code = tsdbReaderResume2(pReader);
5,042,912✔
5276
    if (code != TSDB_CODE_SUCCESS) {
5,036,966!
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) {
14,429,947✔
5284
    code = doTsdbNextDataBlock2(pReader->innerReader[0], hasNext);
1,817✔
5285
    if (code) {
1,817!
5286
      (void) tsdbReleaseReader(pReader);
×
5287
      return code;
×
5288
    }
5289

5290
    pReader->step = EXTERNAL_ROWS_PREV;
1,817✔
5291
    if (*hasNext) {
1,817✔
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) {
14,429,300✔
5303
    // prepare for the main scan
5304
    if (tSimpleHashGetSize(pReader->status.pTableMap) > 0) {
1,817!
5305
      code = doOpenReaderImpl(pReader);
1,817✔
5306
    }
5307

5308
    int32_t step = 1;
1,817✔
5309
    resetAllDataBlockScanInfo(pReader->status.pTableMap, pReader->innerReader[0]->info.window.ekey, step);
1,817✔
5310

5311
    if (code != TSDB_CODE_SUCCESS) {
1,817!
5312
      (void) tsdbReleaseReader(pReader);
×
5313
      return code;
×
5314
    }
5315

5316
    pReader->step = EXTERNAL_ROWS_MAIN;
1,817✔
5317
  }
5318

5319
  code = doTsdbNextDataBlock2(pReader, hasNext);
14,429,300✔
5320
  if (code != TSDB_CODE_SUCCESS) {
14,433,447!
5321
    (void) tsdbReleaseReader(pReader);
×
5322
    return code;
4✔
5323
  }
5324

5325
  if (*hasNext) {
14,435,013✔
5326
    if (pStatus->composedDataBlock) {
9,505,173✔
5327
      tsdbTrace("tsdb/read: %p, unlock read mutex", pReader);
8,895,587✔
5328
      code = tsdbReleaseReader(pReader);
8,895,587✔
5329
    }
5330
    return code;
9,508,952✔
5331
  }
5332

5333
  if (pReader->step == EXTERNAL_ROWS_MAIN && pReader->innerReader[1] != NULL) {
4,929,840!
5334
    // prepare for the next row scan
5335
    if (tSimpleHashGetSize(pReader->status.pTableMap) > 0) {
1,817!
5336
      code = doOpenReaderImpl(pReader->innerReader[1]);
1,817✔
5337
    }
5338

5339
    int32_t step = -1;
1,817✔
5340
    resetAllDataBlockScanInfo(pReader->innerReader[1]->status.pTableMap, pReader->info.window.ekey, step);
1,817✔
5341
    if (code != TSDB_CODE_SUCCESS) {
1,817!
5342
      (void) tsdbReleaseReader(pReader);
×
5343
      return code;
×
5344
    }
5345

5346
    code = doTsdbNextDataBlock2(pReader->innerReader[1], hasNext);
1,817✔
5347
    if (code != TSDB_CODE_SUCCESS) {
1,817!
5348
      (void) tsdbReleaseReader(pReader);
×
5349
      return code;
×
5350
    }
5351

5352
    pReader->step = EXTERNAL_ROWS_NEXT;
1,817✔
5353
    if (*hasNext) {
1,817✔
5354
      pStatus = &pReader->innerReader[1]->status;
744✔
5355
      if (pStatus->composedDataBlock) {
744!
5356
        tsdbTrace("tsdb/read: %p, unlock read mutex", pReader);
744!
5357
        code = tsdbReleaseReader(pReader);
744✔
5358
      }
5359

5360
      return code;
744✔
5361
    }
5362
  }
5363

5364
  tsdbTrace("tsdb/read: %p, unlock read mutex", pReader);
4,929,096✔
5365
  code = tsdbReleaseReader(pReader);
4,929,096✔
5366
  return code;
4,929,502✔
5367
}
5368

5369
static void doFillNullColSMA(SBlockLoadSuppInfo* pSup, int32_t numOfRows, int32_t numOfCols, SColumnDataAgg* pTsAgg) {
171,788✔
5370
  // do fill all null column value SMA info
5371
  int32_t i = 0, j = 0;
171,788✔
5372
  int32_t size = (int32_t)TARRAY2_SIZE(&pSup->colAggArray);
171,788✔
5373
  int32_t code = TARRAY2_INSERT_PTR(&pSup->colAggArray, 0, pTsAgg);
171,788!
5374
  if (code != TSDB_CODE_SUCCESS) {
171,788!
5375
    return;
×
5376
  }
5377

5378
  size++;
171,788✔
5379

5380
  while (j < numOfCols && i < size) {
683,812✔
5381
    SColumnDataAgg* pAgg = &pSup->colAggArray.data[i];
512,024✔
5382
    if (pAgg->colId == pSup->colId[j]) {
512,024✔
5383
      i += 1;
482,940✔
5384
      j += 1;
482,940✔
5385
    } else if (pAgg->colId < pSup->colId[j]) {
29,084!
5386
      i += 1;
29,084✔
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) {
171,789✔
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) {
4,569,749✔
5417
  SColumnDataAgg**    pBlockSMA = &pDataBlock->pBlockAgg;
4,569,749✔
5418
  SFileDataBlockInfo* pBlockInfo = NULL;
4,569,749✔
5419
  int32_t             code = 0;
4,569,749✔
5420
  *allHave = false;
4,569,749✔
5421
  *pBlockSMA = NULL;
4,569,749✔
5422

5423
  if (pReader->type == TIMEWINDOW_RANGE_EXTERNAL) {
4,569,749✔
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)) {
4,569,724!
5429
    return TSDB_CODE_SUCCESS;
4,397,939✔
5430
  }
5431

5432
  code = getCurrentBlockInfo(&pReader->status.blockIter, &pBlockInfo, pReader->idStr);
171,785✔
5433
  if (code != TSDB_CODE_SUCCESS) {
171,783!
5434
    return code;
×
5435
  }
5436

5437
  SBlockLoadSuppInfo* pSup = &pReader->suppInfo;
171,783✔
5438

5439
  SSDataBlock* pResBlock = pReader->resBlockInfo.pResBlock;
171,783✔
5440
  if (pResBlock->info.id.uid != pBlockInfo->uid) {
171,783!
5441
    return TSDB_CODE_SUCCESS;
×
5442
  }
5443

5444
  //  int64_t st = taosGetTimestampUs();
5445
  TARRAY2_CLEAR(&pSup->colAggArray, 0);
171,783✔
5446

5447
  SBrinRecord pRecord;
5448
  blockInfoToRecord(&pRecord, pBlockInfo, pSup);
171,783✔
5449
  code = tsdbDataFileReadBlockSma(pReader->pFileReader, &pRecord, &pSup->colAggArray);
171,784✔
5450
  if (code != TSDB_CODE_SUCCESS) {
171,775!
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) {
171,775!
5457
    *allHave = true;
171,775✔
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;
171,775✔
5465

5466
  pTsAgg->numOfNull = 0;
171,775✔
5467
  pTsAgg->colId = PRIMARYKEY_TIMESTAMP_COL_ID;
171,775✔
5468
  pTsAgg->min = pResBlock->info.window.skey;
171,775✔
5469
  pTsAgg->max = pResBlock->info.window.ekey;
171,775✔
5470

5471
  // update the number of NULL data rows
5472
  size_t numOfCols = pSup->numOfCols;
171,775✔
5473

5474
  if (pResBlock->pBlockAgg == NULL) {
171,775!
5475
    size_t num = taosArrayGetSize(pResBlock->pDataBlock);
171,775✔
5476
    pResBlock->pBlockAgg = taosMemoryCalloc(num, sizeof(SColumnDataAgg));
171,775✔
5477
    if (pResBlock->pBlockAgg == NULL) {
171,788!
5478
      return terrno;
×
5479
    }
5480
    for (int i = 0; i < num; ++i) {
792,330✔
5481
      pResBlock->pBlockAgg[i].colId = -1;
620,542✔
5482
    }
5483
  }
5484

5485
  // do fill all null column value SMA info
5486
  doFillNullColSMA(pSup, pBlockInfo->numRow, numOfCols, pTsAgg);
171,788✔
5487

5488
  size_t size = pSup->colAggArray.size;
171,781✔
5489

5490
  int32_t i = 0, j = 0;
171,781✔
5491
  while (j < numOfCols && i < size) {
683,799!
5492
    SColumnDataAgg* pAgg = &pSup->colAggArray.data[i];
512,018✔
5493
    if (pAgg->colId == pSup->colId[j]) {
512,018✔
5494
      pResBlock->pBlockAgg[pSup->slotId[j]] = *pAgg;
482,934✔
5495
      i += 1;
482,934✔
5496
      j += 1;
482,934✔
5497
    } else if (pAgg->colId < pSup->colId[j]) {
29,084✔
5498
      i += 1;
29,083✔
5499
    } else if (pSup->colId[j] < pAgg->colId) {
1!
5500
      pResBlock->pBlockAgg[pSup->slotId[j]].colId = -1;
×
5501
      *allHave = false;
×
5502
      j += 1;
×
5503
    }
5504
  }
5505

5506
  *pBlockSMA = pResBlock->pBlockAgg;
171,781✔
5507
  pReader->cost.smaDataLoad += 1;
171,781✔
5508

5509
  //  double elapsedTime = (taosGetTimestampUs() - st) / 1000.0;
5510
  pReader->cost.smaLoadTime += 0;  // elapsedTime;
171,781✔
5511

5512
  tsdbDebug("vgId:%d, succeed to load block SMA for uid %" PRIu64 ", %s", 0, pBlockInfo->uid, pReader->idStr);
171,781✔
5513
  return code;
171,783✔
5514
}
5515

5516
static int32_t doRetrieveDataBlock(STsdbReader* pReader, SSDataBlock** pBlock) {
503,087✔
5517
  SReaderStatus*      pStatus = &pReader->status;
503,087✔
5518
  int32_t             code = TSDB_CODE_SUCCESS;
503,087✔
5519
  SFileDataBlockInfo* pBlockInfo = NULL;
503,087✔
5520
  *pBlock = NULL;
503,087✔
5521

5522
  code = getCurrentBlockInfo(&pStatus->blockIter, &pBlockInfo, pReader->idStr);
503,087✔
5523
  if (code != TSDB_CODE_SUCCESS) {
503,127!
5524
    return code;
×
5525
  }
5526

5527
  if (pReader->code != TSDB_CODE_SUCCESS) {
503,127!
5528
    return pReader->code;
×
5529
  }
5530

5531
  STableBlockScanInfo* pBlockScanInfo = NULL;
503,127✔
5532
  code = getTableBlockScanInfo(pStatus->pTableMap, pBlockInfo->uid, &pBlockScanInfo, pReader->idStr);
503,127✔
5533
  if (code != TSDB_CODE_SUCCESS) {
503,146!
5534
    return code;
×
5535
  }
5536

5537
  code = doLoadFileBlockData(pReader, &pStatus->blockIter, &pStatus->fileBlockData, pBlockScanInfo->uid);
503,146✔
5538
  if (code != TSDB_CODE_SUCCESS) {
503,316!
5539
    tBlockDataReset(&pStatus->fileBlockData);
×
5540
    return code;
×
5541
  }
5542

5543
  code = copyBlockDataToSDataBlock(pReader, &pBlockScanInfo->lastProcKey);
503,316✔
5544
  if (code != TSDB_CODE_SUCCESS) {
503,283✔
5545
    tBlockDataReset(&pStatus->fileBlockData);
3✔
5546
  }
5547

5548
  *pBlock = pReader->resBlockInfo.pResBlock;
503,324✔
5549
  return code;
503,324✔
5550
}
5551

5552
int32_t tsdbRetrieveDataBlock2(STsdbReader* pReader, SSDataBlock** pBlock, SArray* pIdList) {
9,162,556✔
5553
  *pBlock = NULL;
9,162,556✔
5554

5555
  STsdbReader* pTReader = pReader;
9,162,556✔
5556
  if (pReader->type == TIMEWINDOW_RANGE_EXTERNAL) {
9,162,556✔
5557
    if (pReader->step == EXTERNAL_ROWS_PREV) {
3,160✔
5558
      pTReader = pReader->innerReader[0];
647✔
5559
    } else if (pReader->step == EXTERNAL_ROWS_NEXT) {
2,513✔
5560
      pTReader = pReader->innerReader[1];
744✔
5561
    }
5562
  }
5563

5564
  SReaderStatus* pStatus = &pTReader->status;
9,162,556✔
5565
  if (pStatus->composedDataBlock || pReader->info.execMode == READER_EXEC_ROWS) {
9,162,556!
5566
    //    tsdbReaderSuspend2(pReader);
5567
    //    tsdbReaderResume2(pReader);
5568
    *pBlock = pTReader->resBlockInfo.pResBlock;
8,659,457✔
5569
    return TSDB_CODE_SUCCESS;
8,659,457✔
5570
  }
5571

5572
  int32_t code = doRetrieveDataBlock(pTReader, pBlock);
503,099✔
5573

5574
  tsdbTrace("tsdb/read-retrieve: %p, unlock read mutex", pReader);
503,304!
5575
  (void) tsdbReleaseReader(pReader);
503,304✔
5576

5577
  //  tsdbReaderSuspend2(pReader);
5578
  //  tsdbReaderResume2(pReader);
5579
  return code;
503,423✔
5580
}
5581

5582
int32_t tsdbReaderReset2(STsdbReader* pReader, SQueryTableDataCond* pCond) {
20,928✔
5583
  int32_t code = TSDB_CODE_SUCCESS;
20,928✔
5584

5585
  tsdbTrace("tsdb/reader-reset: %p, take read mutex", pReader);
20,928!
5586
  code = tsdbAcquireReader(pReader);
20,928✔
5587
  if (code != TSDB_CODE_SUCCESS) {
20,933!
5588
    return code;
×
5589
  }
5590

5591
  if (pReader->flag == READER_STATUS_SUSPEND) {
20,933✔
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) {
20,933✔
5600
    tsdbDebug("tsdb reader reset return %p, %s", pReader->pReadSnap, pReader->idStr);
29✔
5601
    return tsdbReleaseReader(pReader);
29✔
5602
  }
5603

5604
  SReaderStatus*  pStatus = &pReader->status;
20,901✔
5605
  SDataBlockIter* pBlockIter = &pStatus->blockIter;
20,901✔
5606

5607
  pReader->info.order = pCond->order;
20,901✔
5608
  pReader->type = TIMEWINDOW_RANGE_CONTAINED;
20,901✔
5609
  pReader->info.window = updateQueryTimeWindow(pReader->pTsdb, &pCond->twindows);
20,901✔
5610
  pStatus->loadFromFile = true;
20,904✔
5611
  pStatus->pTableIter = NULL;
20,904✔
5612

5613
  // allocate buffer in order to load data blocks from file
5614
  memset(&pReader->suppInfo.tsColAgg, 0, sizeof(SColumnDataAgg));
20,904✔
5615

5616
  pReader->suppInfo.tsColAgg.colId = PRIMARYKEY_TIMESTAMP_COL_ID;
20,904✔
5617
  tsdbDataFileReaderClose(&pReader->pFileReader);
20,904✔
5618

5619
  int32_t numOfTables = tSimpleHashGetSize(pStatus->pTableMap);
20,903✔
5620

5621
  code = initFilesetIterator(&pStatus->fileIter, pReader->pReadSnap->pfSetArray, pReader);
20,904✔
5622
  if (code != TSDB_CODE_SUCCESS) {
20,900!
5623
    (void) tsdbReleaseReader(pReader);
×
5624
    return code;
×
5625
  }
5626

5627
  code = resetDataBlockIterator(pBlockIter, pReader->info.order, shouldFreePkBuf(&pReader->suppInfo), pReader->idStr);
20,900✔
5628
  if (code != TSDB_CODE_SUCCESS) {
20,899!
5629
    (void) tsdbReleaseReader(pReader);
×
5630
    return code;
×
5631
  }
5632

5633
  code = resetTableListIndex(&pReader->status, pReader->idStr);
20,899✔
5634
  if (code != TSDB_CODE_SUCCESS) {
20,903!
5635
    (void) tsdbReleaseReader(pReader);
×
5636
    return code;
×
5637
  }
5638

5639
  bool    asc = ASCENDING_TRAVERSE(pReader->info.order);
20,903✔
5640
  int32_t step = asc ? 1 : -1;
20,903✔
5641
  int64_t ts = 0;
20,903✔
5642
  if (asc) {
20,903✔
5643
    ts = (pReader->info.window.skey > INT64_MIN) ? pReader->info.window.skey - 1 : pReader->info.window.skey;
20,351!
5644
  } else {
5645
    ts = (pReader->info.window.ekey < INT64_MAX) ? pReader->info.window.ekey + 1 : pReader->info.window.ekey;
552✔
5646
  }
5647
  resetAllDataBlockScanInfo(pStatus->pTableMap, ts, step);
20,903✔
5648

5649
  // no data in files, let's try buffer in memory
5650
  if (pStatus->fileIter.numOfFiles == 0) {
20,900✔
5651
    pStatus->loadFromFile = false;
3,778✔
5652
    code = resetTableListIndex(pStatus, pReader->idStr);
3,778✔
5653
    if (code != TSDB_CODE_SUCCESS) {
3,777!
5654
      (void) tsdbReleaseReader(pReader);
×
5655
      return code;
×
5656
    }
5657
  } else {
5658
    code = initForFirstBlockInFile(pReader, pBlockIter);
17,122✔
5659
    if (code != TSDB_CODE_SUCCESS) {
17,098!
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
20,875✔
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);
20,875✔
5674
  return code;
20,894✔
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,244!
5699
    return code;
×
5700
  }
5701

5702
  if (pReader->flag == READER_STATUS_SUSPEND) {
3,244!
5703
    code = tsdbReaderResume2(pReader);
3,246✔
5704
    if (code != TSDB_CODE_SUCCESS) {
3,240!
5705
      return tsdbReleaseReader(pReader);
×
5706
    }
5707
  }
5708

5709
  SMergeTreeConf conf = {
3,238✔
5710
      .pReader = pReader,
5711
      .pSchema = pReader->info.pSchema,
3,238✔
5712
      .pCols = pReader->suppInfo.colId,
3,238✔
5713
      .numOfCols = pReader->suppInfo.numOfCols,
3,238✔
5714
      .suid = pReader->info.suid,
3,238✔
5715
  };
5716

5717
  SReaderStatus* pStatus = &pReader->status;
3,238✔
5718
  if (pStatus->pCurrentFileset != NULL) {
3,238✔
5719
    pTableBlockInfo->numOfSttRows += tsdbGetRowsInSttFiles(pStatus->pCurrentFileset, pStatus->pLDataIterArray,
1,892✔
5720
                                                           pReader->pTsdb, &conf, pReader->idStr);
1,888✔
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,021✔
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,020✔
5771
      if ((code != TSDB_CODE_SUCCESS) || (pStatus->loadFromFile == false)) {
7,023!
5772
        break;
5773
      }
5774

5775
      // add the data in stt files of new fileset
5776
      if (pStatus->pCurrentFileset != NULL) {
3,777!
5777
        pTableBlockInfo->numOfSttRows += tsdbGetRowsInSttFiles(pStatus->pCurrentFileset, pStatus->pLDataIterArray,
3,780✔
5778
                                                               pReader->pTsdb, &conf, pReader->idStr);
3,778✔
5779
      }
5780

5781
      pTableBlockInfo->numOfBlocks += pBlockIter->numOfBlocks;
3,779✔
5782
      hasNext = (pBlockIter->numOfBlocks > 0);
3,779✔
5783
    }
5784
  }
5785

5786
  // record the data in stt files
5787
  (void) tsdbReleaseReader(pReader);
3,246✔
5788
  return code;
3,249✔
5789
}
5790

5791
static void getMemTableTimeRange(STsdbReader* pReader, int64_t* pMaxKey, int64_t* pMinKey) {
1,973,648✔
5792
  int32_t code = TSDB_CODE_SUCCESS;
1,973,648✔
5793
  int64_t rows = 0;
1,973,648✔
5794

5795
  SReaderStatus* pStatus = &pReader->status;
1,973,648✔
5796

5797
  int32_t iter = 0;
1,973,648✔
5798
  int64_t maxKey = INT64_MIN;
1,973,648✔
5799
  int64_t minKey = INT64_MAX;
1,973,648✔
5800

5801
  void* pHashIter = tSimpleHashIterate(pStatus->pTableMap, NULL, &iter);
1,973,648✔
5802
  while (pHashIter != NULL) {
7,010,701✔
5803
    STableBlockScanInfo* pBlockScanInfo = *(STableBlockScanInfo**)pHashIter;
5,034,869✔
5804

5805
    STbData* d = NULL;
5,034,869✔
5806
    if (pReader->pReadSnap->pMem != NULL) {
5,034,869✔
5807
      d = tsdbGetTbDataFromMemTable(pReader->pReadSnap->pMem, pReader->info.suid, pBlockScanInfo->uid);
4,679,583✔
5808
      if (d != NULL) {
4,682,381✔
5809
        if (d->maxKey > maxKey) {
1,702,225✔
5810
          maxKey = d->maxKey;
1,450,831✔
5811
        }
5812
        if (d->minKey < minKey) {
1,702,225✔
5813
          minKey = d->minKey;
1,437,297✔
5814
        }
5815
      }
5816
    }
5817

5818
    STbData* di = NULL;
5,037,667✔
5819
    if (pReader->pReadSnap->pIMem != NULL) {
5,037,667✔
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,037,667✔
5833
  }
5834

5835
  *pMaxKey = maxKey;
1,975,832✔
5836
  *pMinKey = minKey;
1,975,832✔
5837
}
1,975,832✔
5838

5839
int64_t tsdbGetNumOfRowsInMemTable2(STsdbReader* pReader) {
3,247✔
5840
  int32_t code = TSDB_CODE_SUCCESS;
3,247✔
5841
  int64_t rows = 0;
3,247✔
5842

5843
  SReaderStatus* pStatus = &pReader->status;
3,247✔
5844
  code = tsdbAcquireReader(pReader);
3,247✔
5845
  if (code != TSDB_CODE_SUCCESS) {
3,249!
5846
    return code;
×
5847
  }
5848

5849
  if (pReader->flag == READER_STATUS_SUSPEND) {
3,249✔
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,249✔
5858
  pStatus->pTableIter = tSimpleHashIterate(pStatus->pTableMap, NULL, &iter);
3,249✔
5859

5860
  while (pStatus->pTableIter != NULL) {
10,267✔
5861
    STableBlockScanInfo* pBlockScanInfo = *(STableBlockScanInfo**)pStatus->pTableIter;
7,019✔
5862

5863
    STbData* d = NULL;
7,019✔
5864
    if (pReader->pReadSnap->pMem != NULL) {
7,019✔
5865
      d = tsdbGetTbDataFromMemTable(pReader->pReadSnap->pMem, pReader->info.suid, pBlockScanInfo->uid);
7,014✔
5866
      if (d != NULL) {
7,018✔
5867
        rows += tsdbGetNRowsInTbData(d);
1,621✔
5868
      }
5869
    }
5870

5871
    STbData* di = NULL;
7,023✔
5872
    if (pReader->pReadSnap->pIMem != NULL) {
7,023✔
5873
      di = tsdbGetTbDataFromMemTable(pReader->pReadSnap->pIMem, pReader->info.suid, pBlockScanInfo->uid);
3✔
5874
      if (di != NULL) {
3!
5875
        rows += tsdbGetNRowsInTbData(di);
3✔
5876
      }
5877
    }
5878

5879
    // current table is exhausted, let's try the next table
5880
    pStatus->pTableIter = tSimpleHashIterate(pStatus->pTableMap, pStatus->pTableIter, &iter);
7,023✔
5881
  }
5882

5883
  (void) tsdbReleaseReader(pReader);
3,248✔
5884

5885
  return rows;
3,250✔
5886
}
5887

5888
int32_t tsdbGetTableSchema(SMeta* pMeta, int64_t uid, STSchema** pSchema, int64_t* suid) {
425✔
5889
  SMetaReader mr = {0};
425✔
5890
  metaReaderDoInit(&mr, pMeta, META_READER_LOCK);
425✔
5891
  int32_t code = metaReaderGetTableEntryByUidCache(&mr, uid);
425✔
5892
  if (code != TSDB_CODE_SUCCESS) {
425!
5893
    code = TSDB_CODE_TDB_INVALID_TABLE_ID;
×
5894
    metaReaderClear(&mr);
×
5895
    return code;
×
5896
  }
5897

5898
  *suid = 0;
425✔
5899

5900
  // only child table and ordinary table is allowed, super table is not allowed.
5901
  if (mr.me.type == TSDB_CHILD_TABLE) {
425✔
5902
    tDecoderClear(&mr.coder);
299✔
5903
    *suid = mr.me.ctbEntry.suid;
299✔
5904
    code = metaReaderGetTableEntryByUidCache(&mr, *suid);
299✔
5905
    if (code != TSDB_CODE_SUCCESS) {
299!
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);
425✔
5919

5920
  // get the newest table schema version
5921
  code = metaGetTbTSchemaEx(pMeta, *suid, uid, -1, pSchema);
425✔
5922
  return code;
425✔
5923
}
5924

5925
int32_t tsdbTakeReadSnap2(STsdbReader* pReader, _query_reseek_func_t reseek, STsdbReadSnap** ppSnap, const char* id) {
4,919,107✔
5926
  int32_t        code = 0;
4,919,107✔
5927
  STsdb*         pTsdb = pReader->pTsdb;
4,919,107✔
5928
  SVersionRange* pRange = &pReader->info.verRange;
4,919,107✔
5929
  int32_t        lino = 0;
4,919,107✔
5930
  *ppSnap = NULL;
4,919,107✔
5931

5932
  // lock
5933
  code = taosThreadMutexLock(&pTsdb->mutex);
4,919,107✔
5934
  if (code != TSDB_CODE_SUCCESS) {
4,929,995!
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,929,995✔
5941
  if (pSnap == NULL) {
4,929,622!
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,929,622!
5948
    pSnap->pMem = pTsdb->mem;
4,383,670✔
5949
    pSnap->pNode = taosMemoryMalloc(sizeof(*pSnap->pNode));
4,383,670✔
5950
    if (pSnap->pNode == NULL) {
4,383,205!
5951
      (void) taosThreadMutexUnlock(&pTsdb->mutex);
×
5952
      TSDB_CHECK_NULL(pSnap->pNode, code, lino, _exit, terrno);
×
5953
    }
5954

5955
    pSnap->pNode->pQHandle = pReader;
4,383,205✔
5956
    pSnap->pNode->reseek = reseek;
4,383,205✔
5957

5958
    code = tsdbRefMemTable(pTsdb->mem, pSnap->pNode);
4,383,205✔
5959
    TSDB_CHECK_CODE(code, lino, _exit);
4,383,351!
5960
  }
5961

5962
  if (pTsdb->imem && (pRange->minVer <= pTsdb->imem->maxVer && pRange->maxVer >= pTsdb->imem->minVer)) {
4,929,303!
5963
    pSnap->pIMem = pTsdb->imem;
12,676✔
5964
    pSnap->pINode = taosMemoryMalloc(sizeof(*pSnap->pINode));
12,676✔
5965
    if (pSnap->pINode == NULL) {
12,675!
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;
12,675✔
5977
    pSnap->pINode->reseek = reseek;
12,675✔
5978

5979
    code = tsdbRefMemTable(pTsdb->imem, pSnap->pINode);
12,675✔
5980
    TSDB_CHECK_CODE(code, lino, _exit);
12,676!
5981
  }
5982

5983
  // fs
5984
  code = tsdbFSCreateRefSnapshotWithoutLock(pTsdb->pFS, &pSnap->pfSetArray);
4,929,303✔
5985
  if (code) {
4,927,289!
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,927,289✔
6000
  *ppSnap = pSnap;
4,929,372✔
6001

6002
  tsdbTrace("%s vgId:%d, take read snapshot", id, TD_VID(pTsdb->pVnode));
4,929,372✔
6003
  return code;
4,929,953✔
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,929,818✔
6017
  STsdb* pTsdb = pReader->pTsdb;
4,929,818✔
6018

6019
  if (pSnap) {
4,929,818!
6020
    if (pSnap->pMem) {
4,930,006✔
6021
      tsdbUnrefMemTable(pSnap->pMem, pSnap->pNode, proactive);
4,384,003✔
6022
    }
6023

6024
    if (pSnap->pIMem) {
4,930,010✔
6025
      tsdbUnrefMemTable(pSnap->pIMem, pSnap->pINode, proactive);
12,676✔
6026
    }
6027

6028
    if (pSnap->pNode) taosMemoryFree(pSnap->pNode);
4,930,010✔
6029
    if (pSnap->pINode) taosMemoryFree(pSnap->pINode);
4,930,042✔
6030

6031
    tsdbFSDestroyRefSnapshot(&pSnap->pfSetArray);
4,930,042✔
6032

6033
    taosMemoryFree(pSnap);
4,930,179✔
6034
  }
6035
  tsdbTrace("vgId:%d, untake read snapshot", TD_VID(pTsdb->pVnode));
4,930,267✔
6036
}
4,930,267✔
6037

6038
// if failed, do nothing
6039
int32_t tsdbReaderSetId(void* p, const char* idstr) {
954✔
6040
  STsdbReader* pReader = (STsdbReader*) p;
954✔
6041
  taosMemoryFreeClear(pReader->idStr);
954!
6042

6043
  pReader->idStr = taosStrdup(idstr);
954✔
6044
  if (pReader->idStr == NULL) {
954!
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;
954✔
6050
  return 0;
954✔
6051
}
6052

6053
void tsdbReaderSetCloseFlag(STsdbReader* pReader) { /*pReader->code = TSDB_CODE_TSC_QUERY_CANCELLED;*/ }
83✔
6054

6055
void tsdbSetFilesetDelimited(STsdbReader* pReader) { pReader->bFilesetDelimited = true; }
1,972,441✔
6056

6057
void tsdbReaderSetNotifyCb(STsdbReader* pReader, TsdReaderNotifyCbFn notifyFn, void* param) {
1,973,259✔
6058
  pReader->notifyFn = notifyFn;
1,973,259✔
6059
  pReader->notifyParam = param;
1,973,259✔
6060
}
1,973,259✔
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