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

taosdata / TDengine / #3526

10 Nov 2024 03:50AM UTC coverage: 60.225% (-0.6%) from 60.818%
#3526

push

travis-ci

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

merge: from main to 3.0 branch

117031 of 249004 branches covered (47.0%)

Branch coverage included in aggregate %.

130 of 169 new or added lines in 23 files covered. (76.92%)

4149 existing lines in 176 files now uncovered.

197577 of 273386 relevant lines covered (72.27%)

5840219.36 hits per line

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

69.3
/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,256✔
93
  if (p2 == NULL) {
385,674,670!
94
    return 1;
74,339,110✔
95
  }
96

97
  if (p1 == NULL) {
656,472,535!
98
    return -1;
×
99
  }
100

101
  if (p1->ts < p2->ts) {
656,472,535!
102
    return -1;
513,478,805✔
103
  } else if (p1->ts > p2->ts) {
142,993,730!
104
    return 1;
44,636,404✔
105
  }
106

107
  if (p1->numOfPKs == 0) {
98,357,326!
108
    return 0;
92,322,345✔
109
  } else {
110
    return tRowKeyCompare(p1, p2);
6,034,981✔
111
  }
112
}
113

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

119
  pKey->numOfPKs = 1;
10,708,212✔
120
  pKey->pks[0].type = cv.value.type;
10,708,212✔
121

122
  if (IS_NUMERIC_TYPE(cv.value.type)) {
10,708,212!
123
    pKey->pks[0].val = cv.value.val;
7,609,346✔
124
  } else {
125
    pKey->pks[0].nData = cv.value.nData;
3,098,866✔
126
    (void)memcpy(pKey->pks[0].pData, cv.value.pData, cv.value.nData);
3,098,866✔
127
  }
128
}
10,708,212✔
129

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

138
static void tRowGetPrimaryKeyDeepCopy(SRow* pRow, SRowKey* pKey) {
5,133,877✔
139
  SPrimaryKeyIndex indices[TD_MAX_PK_COLS];
140

141
  uint8_t* data = pRow->data;
5,133,877✔
142
  for (int32_t i = 0; i < pRow->numOfPKs; i++) {
10,263,629✔
143
    data += tGetPrimaryKeyIndex(data, &indices[i]);
5,134,363✔
144
  }
145

146
  // primary keys
147
  for (int32_t i = 0; i < pRow->numOfPKs; i++) {
10,284,139✔
148
    pKey->pks[i].type = indices[i].type;
5,154,873✔
149

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

155
    if (IS_VAR_DATA_TYPE(indices[i].type)) {
5,154,873!
156
      tdata += tGetU32v(tdata, &pKey->pks[i].nData);
1,535,857!
157
      (void)memcpy(pKey->pks[i].pData, tdata, pKey->pks[i].nData);
1,535,857✔
158
    } else {
159
      (void)memcpy(&pKey->pks[i].val, data + indices[i].offset, tDataTypes[pKey->pks[i].type].bytes);
3,619,016✔
160
    }
161
  }
162
}
5,129,266✔
163

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

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

175
  pSupInfo->colId = taosMemoryMalloc(numOfCols * (sizeof(int16_t) * 2 + POINTER_BYTES));
1,437,108✔
176
  if (pSupInfo->colId == NULL) {
1,438,650!
177
    taosMemoryFree(pSupInfo->colId);
×
178
    return terrno;
×
179
  }
180

181
  pSupInfo->slotId = (int16_t*)((char*)pSupInfo->colId + (sizeof(int16_t) * numOfCols));
1,438,673✔
182
  pSupInfo->buildBuf = (char**)((char*)pSupInfo->slotId + (sizeof(int16_t) * numOfCols));
1,438,673✔
183
  for (int32_t i = 0; i < numOfCols; ++i) {
7,185,984✔
184
    pSupInfo->colId[i] = pCols[i].colId;
5,746,005✔
185
    pSupInfo->slotId[i] = pSlotIdList[i];
5,746,005✔
186

187
    if (IS_VAR_DATA_TYPE(pCols[i].type)) {
5,746,005!
188
      pSupInfo->buildBuf[i] = taosMemoryMalloc(pCols[i].bytes);
762,756✔
189
      if (pSupInfo->buildBuf[i] == NULL) {
764,056!
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;
4,983,249✔
195
    }
196

197
    if (pCols[i].pk) {
5,747,311✔
198
      pSupInfo->pk = pCols[i];
109,776✔
199
      pSupInfo->pkSrcSlot = i - 1;
109,776✔
200
      pSupInfo->pkDstSlot = pSlotIdList[i];
109,776✔
201
      pSupInfo->numOfPks += 1;
109,776✔
202
    }
203
  }
204

205
  return (initSucc)? TSDB_CODE_SUCCESS:TSDB_CODE_OUT_OF_MEMORY;
1,439,979✔
206
}
207

208
static int32_t updateBlockSMAInfo(STSchema* pSchema, SBlockLoadSuppInfo* pSupInfo) {
1,387,792✔
209
  int32_t i = 0, j = 0;
1,387,792✔
210

211
  while (i < pSchema->numOfCols && j < pSupInfo->numOfCols) {
13,430,796✔
212
    STColumn* pTCol = &pSchema->columns[i];
12,054,040✔
213
    if (pTCol->colId == pSupInfo->colId[j]) {
12,054,040✔
214
      if (!IS_BSMA_ON(pTCol) && (PRIMARYKEY_TIMESTAMP_COL_ID != pTCol->colId)) {
5,528,590✔
215
        pSupInfo->smaValid = false;
11,878✔
216
        return TSDB_CODE_SUCCESS;
11,878✔
217
      }
218

219
      i += 1;
5,516,712✔
220
      j += 1;
5,516,712✔
221
    } else if (pTCol->colId < pSupInfo->colId[j]) {  // do nothing
6,525,450!
222
      i += 1;
6,526,292✔
223
    } else {
224
      return TSDB_CODE_TDB_INVALID_TABLE_SCHEMA_VER;
×
225
    }
226
  }
227

228
  return TSDB_CODE_SUCCESS;
1,376,756✔
229
}
230

231
static bool isEmptyQueryTimeWindow(STimeWindow* pWindow) { return pWindow->skey > pWindow->ekey; }
6,980,550✔
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) {
1,458,316✔
236
  int64_t     earlyTs = tsdbGetEarliestTs(pTsdb);
1,458,316✔
237
  STimeWindow win = *pWindow;
1,459,421✔
238
  if (win.skey < earlyTs) {
1,459,421✔
239
    win.skey = earlyTs;
1,336,961✔
240
  }
241

242
  return win;
1,459,421✔
243
}
244

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

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

257
  if (pIter->pSttBlockReader == NULL) {
1,369,482✔
258
    pIter->pSttBlockReader = taosMemoryCalloc(1, sizeof(struct SSttBlockReader));
1,348,993✔
259
    if (pIter->pSttBlockReader == NULL) {
1,348,867!
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;
1,369,356✔
266
  pSttReader->order = pReader->info.order;
1,369,356✔
267
  pSttReader->window = pReader->info.window;
1,369,356✔
268
  pSttReader->verRange = pReader->info.verRange;
1,369,356✔
269
  pSttReader->numOfPks = pReader->suppInfo.numOfPks;
1,369,356✔
270
  pSttReader->uid = 0;
1,369,356✔
271

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

280
  return code;
1,369,758✔
281
}
282

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

288
  pIter->index += step;
3,350,986✔
289
  if ((asc && pIter->index >= pIter->numOfFiles) || ((!asc) && pIter->index < 0)) {
3,350,986✔
290
    *hasNext = false;
297,757✔
291
    return TSDB_CODE_SUCCESS;
297,757✔
292
  }
293

294
  SReadCostSummary* pCost = &pReader->cost;
3,053,229✔
295

296
  pIter->pSttBlockReader->uid = 0;
3,053,229✔
297
  tMergeTreeClose(&pIter->pSttBlockReader->mergeTree);
3,053,229✔
298
  destroySttBlockReader(pReader->status.pLDataIterArray, &pCost->sttCost);
3,054,117✔
299

300
  pReader->status.pLDataIterArray = taosArrayInit(4, POINTER_BYTES);
3,056,640✔
301
  if (pReader->status.pLDataIterArray == NULL) {
3,056,465!
302
    return terrno;
×
303
  }
304

305
  // check file the time range of coverage
306
  STimeWindow win = {0};
3,056,465✔
307

308
  while (1) {
8,366✔
309
    if (pReader->pFileReader != NULL) {
3,064,831✔
310
      tsdbDataFileReaderClose(&pReader->pFileReader);
115,331✔
311
    }
312

313
    pReader->status.pCurrentFileset = pIter->pFilesetList->data[pIter->index];
3,064,846✔
314

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

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

321
      if (pFileObj[0] != NULL) {
126,844✔
322
        conf.files[0].file = *pFileObj[0]->f;
119,160✔
323
        conf.files[0].exist = true;
119,160✔
324
        filesName[0] = pFileObj[0]->fname;
119,160✔
325

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

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

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

341
      code = tsdbDataFileReaderOpen(filesName, &conf, &pReader->pFileReader);
126,844✔
342
      if (code != TSDB_CODE_SUCCESS) {
127,000!
343
        goto _err;
×
344
      }
345

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

349
    int32_t fid = pReader->status.pCurrentFileset->fid;
3,065,002✔
350
    tsdbFidKeyRange(fid, pReader->pTsdb->keepCfg.days, pReader->pTsdb->keepCfg.precision, &win.skey, &win.ekey);
3,065,002✔
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)) {
3,064,424✔
354
      tsdbDebug("%p remain files are not qualified for qrange:%" PRId64 "-%" PRId64 ", ignore, %s", pReader,
718✔
355
                pReader->info.window.skey, pReader->info.window.ekey, pReader->idStr);
356
      *hasNext = false;
838✔
357
      return TSDB_CODE_SUCCESS;
838✔
358
    }
359

360
    if ((asc && (win.ekey < pReader->info.window.skey)) || ((!asc) && (win.skey > pReader->info.window.ekey))) {
3,063,706✔
361
      pIter->index += step;
8,417✔
362
      if ((asc && pIter->index >= pIter->numOfFiles) || ((!asc) && pIter->index < 0)) {
8,417✔
363
        *hasNext = false;
51✔
364
        return TSDB_CODE_SUCCESS;
51✔
365
      }
366
      continue;
8,366✔
367
    }
368

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

372
    *hasNext = true;
3,055,097✔
373
    return TSDB_CODE_SUCCESS;
3,055,097✔
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); }
5,974,927!
382

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

388
  if (pIter->blockList == NULL) {
4,421,813✔
389
    pIter->blockList = taosArrayInit(4, sizeof(SFileDataBlockInfo));
1,348,897✔
390
    if (pIter->blockList == NULL) {
1,348,816!
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);
3,072,916✔
396
  }
397

398
  return TSDB_CODE_SUCCESS;
4,421,586✔
399
}
400

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

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

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

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

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

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

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

438
  return code;
1,437,725✔
439
}
440

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

445
  code = taosThreadMutexDestroy(&pReader->readerMutex);
1,439,142✔
446
  tsdbTrace("tsdb/read: %p, post-uninit read mutex: %p, code: %d", pReader, &pReader->readerMutex, code);
1,439,042✔
447

448
  return code;
1,439,080✔
449
}
450

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

455
  code = taosThreadMutexLock(&pReader->readerMutex);
6,960,873✔
456
  if (code != 0) {
6,965,635!
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);
6,965,635✔
460
  }
461

462
  return code;
6,965,380✔
463
}
464

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

475
static int32_t tsdbReleaseReader(STsdbReader* pReader) {
6,959,635✔
476
  int32_t code = taosThreadMutexUnlock(&pReader->readerMutex);
6,959,635✔
477
  if (code != TSDB_CODE_SUCCESS) {
6,966,279!
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);
6,966,279✔
481
  }
482
  return code;
6,964,960✔
483
}
484

485
void tsdbReleaseDataBlock2(STsdbReader* pReader) {
208,026✔
486
  SReaderStatus* pStatus = &pReader->status;
208,026✔
487
  if (!pStatus->composedDataBlock) {
208,026✔
488
    (void) tsdbReleaseReader(pReader);
48,301✔
489
  }
490
}
208,067✔
491

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

498
  if (pResBlockInfo->pResBlock == NULL) {
1,436,942✔
499
    pResBlockInfo->freeBlock = true;
2,526✔
500
    pResBlockInfo->pResBlock = NULL;
2,526✔
501

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

507
    if (pSup->numOfPks > 0) {
2,527✔
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);
232✔
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;
1,434,416✔
530
  }
531

532
  return code;
1,436,713✔
533
}
534

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

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

549
  initReaderStatus(&pReader->status);
1,437,951✔
550
  getTsdbByRetentions(pVnode, pCond, pVnode->config.tsdbCfg.retentions, idstr, &level, &pReader->pTsdb);
1,438,241✔
551

552
  pReader->info.suid = pCond->suid;
1,438,370✔
553
  pReader->info.order = pCond->order;
1,438,370✔
554
  pReader->info.verRange = getQueryVerRange(pVnode, pCond, level);
1,438,370✔
555
  pReader->info.window = updateQueryTimeWindow(pReader->pTsdb, &pCond->twindows);
1,438,357✔
556

557
  pReader->idStr = (idstr != NULL) ? taosStrdup(idstr) : NULL;
1,438,745✔
558
  if (idstr != NULL && pReader->idStr == NULL) {
1,438,202!
559
    code = terrno;
×
560
    goto _end;
×
561
  }
562

563
  pReader->type = pCond->type;
1,438,202✔
564
  pReader->bFilesetDelimited = false;
1,438,202✔
565
  pReader->blockInfoBuf.numPerBucket = 1000;  // 1000 tables per bucket
1,438,202✔
566

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

581
  code = initResBlockInfo(&pReader->resBlockInfo, capacity, pResBlock, pCond, pSup);
1,438,518✔
582
  if (code != TSDB_CODE_SUCCESS) {
1,436,739!
583
    goto _end;
×
584
  }
585

586
  code = tBlockDataCreate(&pReader->status.fileBlockData);
1,436,739✔
587
  if (code != TSDB_CODE_SUCCESS) {
1,436,546!
588
    goto _end;
×
589
  }
590

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

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

616
  code = tsem_init(&pReader->resumeAfterSuspend, 0, 0);
1,437,761✔
617
  if (code != TSDB_CODE_SUCCESS) {
1,437,240!
618
    goto _end;
×
619
  }
620

621
  *ppReader = pReader;
1,437,240✔
622
  return code;
1,437,240✔
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) {
3,053,987✔
631
  int64_t st = taosGetTimestampUs();
3,054,535✔
632
  int32_t numOfTables = tSimpleHashGetSize(pReader->status.pTableMap);
3,054,535✔
633
  if (pFileReader == NULL) {
3,054,215✔
634
    return TSDB_CODE_SUCCESS;
2,927,564✔
635
  }
636

637
  const TBrinBlkArray* pBlkArray = NULL;
126,651✔
638

639
  int32_t code = tsdbDataFileReadBrinBlk(pFileReader, &pBlkArray);
126,651✔
640
  if (code != TSDB_CODE_SUCCESS) {
126,657!
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();
126,699✔
663

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

667
  int32_t i = 0;
126,699✔
668
  while (i < TARRAY2_SIZE(pBlkArray)) {
245,257✔
669
    pBrinBlk = &pBlkArray->data[i];
118,938✔
670
    if (pBrinBlk->maxTbid.suid < pReader->info.suid) {
118,938✔
671
      i += 1;
2✔
672
      continue;
2✔
673
    }
674

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

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

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

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

697
    i += 1;
118,325✔
698
  }
699

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

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

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

723
  // clear info for the new file
724
  cleanupInfoForNextFileset(pReader->status.pTableMap);
3,053,725✔
725
  initBrinRecordIter(&iter, pReader->pFileReader, pIndexList);
3,053,942✔
726

727
  while (1) {
876,503✔
728
    int32_t code = getNextBrinRecord(&iter, &pRecord);
3,930,514✔
729
    if (code != TSDB_CODE_SUCCESS) {
3,930,726!
730
      clearBrinBlockIter(&iter);
×
731
      return code;
×
732
    }
733

734
    if (pRecord == NULL) {
3,931,131✔
735
      break;
3,050,804✔
736
    }
737

738
    if (pRecord->suid > pReader->info.suid) {
880,327✔
739
      break;
428✔
740
    }
741

742
    uint64_t uid = pReader->status.uidList.tableUidList[k];
879,899✔
743
    if (pRecord->suid < pReader->info.suid) {
879,899✔
744
      continue;
476,031✔
745
    }
746

747
    if (uid < pRecord->uid) {  // forward the table uid index
878,773✔
748
      while (k < numOfTables && pReader->status.uidList.tableUidList[k] < pRecord->uid) {
404,504✔
749
        k += 1;
204,301✔
750
      }
751

752
      if (k >= numOfTables) {
200,203✔
753
        break;
3,480✔
754
      }
755

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

759
    if (pRecord->uid < uid) {
875,293✔
760
      continue;
442,815✔
761
    }
762

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

769
    STableBlockScanInfo* pScanInfo = NULL;
432,549✔
770
    code = getTableBlockScanInfo(pReader->status.pTableMap, uid, &pScanInfo, pReader->idStr);
432,549✔
771
    if (code != TSDB_CODE_SUCCESS) {
432,440!
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) {
432,492✔
779
      w.skey = pScanInfo->lastProcKey.ts;
417,301✔
780
    } else {
781
      w.ekey = pScanInfo->lastProcKey.ts;
15,191✔
782
    }
783

784
    // NOTE: specialized for open interval
785
    if (((w.skey < INT64_MAX) && ((w.skey + 1) > w.ekey)) || (w.skey == INT64_MAX)) {
432,492!
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) {
432,528✔
796
      continue;
32,105✔
797
    }
798

799
    if (asc) {
400,423✔
800
      if (pkCompEx(&pRecord->lastKey.key, &pScanInfo->lastProcKey) <= 0) {
792,479!
801
        continue;
3✔
802
      }
803
    } else {
804
      if (pkCompEx(&pRecord->firstKey.key, &pScanInfo->lastProcKey) >= 0) {
8,319!
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) {
400,372!
811
      continue;
18✔
812
    }
813

814
    if (pScanInfo->pBlockList == NULL) {
400,354✔
815
      pScanInfo->pBlockList = taosArrayInit(4, sizeof(SFileDataBlockInfo));
311,524✔
816
      if (pScanInfo->pBlockList == NULL) {
311,624!
817
        clearBrinBlockIter(&iter);
×
818
        return terrno;
×
819
      }
820
    }
821

822
    if (pScanInfo->pBlockIdxList == NULL) {
400,454✔
823
      pScanInfo->pBlockIdxList = taosArrayInit(4, sizeof(STableDataBlockIdx));
32,874✔
824
      if (pScanInfo->pBlockIdxList == NULL) {
32,904!
825
        clearBrinBlockIter(&iter);
×
826
        return terrno;
×
827
      }
828
    }
829

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

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

851
    pBlockNum->numOfBlocks += 1;
400,773✔
852
    if (taosArrayGetSize(pTableScanInfoList) == 0) {
400,773✔
853
      p1 = taosArrayPush(pTableScanInfoList, &pScanInfo);
114,991✔
854
    } else {
855
      STableBlockScanInfo** p = taosArrayGetLast(pTableScanInfoList);
285,833✔
856
      if (p == NULL) {
285,919✔
857
        clearBrinBlockIter(&iter);
429✔
858
        tsdbError("invalid param, empty in tablescanInfoList, %s", pReader->idStr);
×
859
        return TSDB_CODE_INVALID_PARA;
×
860
      }
861

862
      if ((*p)->uid != uid) {
285,490✔
863
        p1 = taosArrayPush(pTableScanInfoList, &pScanInfo);
196,676✔
864
      }
865
    }
866

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

873
  clearBrinBlockIter(&iter);
3,054,712✔
874

875
  pBlockNum->numOfSttFiles = pReader->status.pCurrentFileset->lvlArr->size;
3,052,013✔
876
  int32_t total = pBlockNum->numOfSttFiles + pBlockNum->numOfBlocks;
3,052,013✔
877

878
  double el = (taosGetTimestampUs() - st) / 1000.0;
3,053,097✔
879
  tsdbDebug(
3,053,097✔
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;
3,053,209✔
886
  pReader->cost.headFileLoadTime += el;
3,053,209✔
887

888
  return TSDB_CODE_SUCCESS;
3,053,209✔
889
}
890

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

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

UNCOV
903
  if (IS_NUMERIC_TYPE(pKey->pks[0].type)) {
×
UNCOV
904
    pKey->pks[0].val = asc ? pBlockInfo->lastPk.val : pBlockInfo->firstPk.val;
×
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,
1,216,874,035✔
913
                            SBlockLoadSuppInfo* pSup) {
914
  int32_t code = 0;
1,216,874,035✔
915

916
  if (IS_VAR_DATA_TYPE(pColVal->value.type)) {
1,216,874,035!
917
    if (!COL_VAL_IS_VALUE(pColVal)) {
151,706,717✔
918
      colDataSetNULL(pColInfoData, rowIndex);
15,610,307✔
919
    } else {
920
      varDataSetLen(pSup->buildBuf[colIndex], pColVal->value.nData);
136,096,410✔
921
      if ((pColVal->value.nData + VARSTR_HEADER_SIZE) > pColInfoData->info.bytes) {
136,096,410✔
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
136,096,406!
928
        (void)memcpy(varDataVal(pSup->buildBuf[colIndex]), pColVal->value.pData, pColVal->value.nData);
141,622,120✔
929
      }
930

931
      code = colDataSetVal(pColInfoData, rowIndex, pSup->buildBuf[colIndex], false);
136,096,406✔
932
    }
933
  } else {
934
    code = colDataSetVal(pColInfoData, rowIndex, (const char*)&pColVal->value.val, !COL_VAL_IS_VALUE(pColVal));
1,065,167,318✔
935
  }
936

937
  return code;
1,222,619,505✔
938
}
939

940
static int32_t getCurrentBlockInfo(SDataBlockIter* pBlockIter, SFileDataBlockInfo** pInfo, const char* id) {
4,836,826✔
941
  *pInfo = NULL;
4,836,826✔
942

943
  if (pBlockIter->blockList == NULL) {
4,836,826!
944
    return TSDB_CODE_FAILED;
×
945
  }
946

947
  size_t num = TARRAY_SIZE(pBlockIter->blockList);
4,836,826✔
948
  if (num == 0) {
4,836,826✔
949
    if (num != pBlockIter->numOfBlocks) {
2,936,769!
950
      tsdbError("tsdb read failed at: %s:%d %s", __func__, __LINE__, id);
×
951
    }
952
    return TSDB_CODE_FAILED;
2,936,972✔
953
  }
954

955
  *pInfo = taosArrayGet(pBlockIter->blockList, pBlockIter->index);
1,900,057✔
956
  return (*pInfo) != NULL? TSDB_CODE_SUCCESS:TSDB_CODE_FAILED;
1,901,766!
957
}
958

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

964
  // check
965
  if (!(pos >= 0 && pos < num && num > 0)) {
2,737!
966
    return -1;
×
967
  }
968
  if (order == TSDB_ORDER_ASC) {
2,737✔
969
    // find the first position which is smaller than the key
970
    e = num - 1;
2,708✔
971
    if (key < keyList[pos]) return -1;
2,708!
972
    while (1) {
32,323✔
973
      // check can return
974
      if (key >= keyList[e]) return e;
35,031!
975
      if (key <= keyList[s]) return s;
35,031✔
976
      if (e - s <= 1) return s;
35,027✔
977

978
      // change start or end position
979
      int mid = s + (e - s + 1) / 2;
32,324✔
980
      if (keyList[mid] > key)
32,324✔
981
        e = mid;
21,302✔
982
      else if (keyList[mid] < key)
11,022✔
983
        s = mid;
11,021✔
984
      else
985
        return mid;
1✔
986
    }
987
  } else {  // DESC
988
    // find the first position which is bigger than the key
989
    e = 0;
29✔
990
    if (key > keyList[pos]) return -1;
29!
991
    while (1) {
314✔
992
      // check can return
993
      if (key <= keyList[e]) return e;
343!
994
      if (key >= keyList[s]) return s;
343!
995
      if (s - e <= 1) return s;
343✔
996

997
      // change start or end position
998
      int mid = s - (s - e + 1) / 2;
316✔
999
      if (keyList[mid] < key)
316✔
1000
        e = mid;
197✔
1001
      else if (keyList[mid] > key)
119✔
1002
        s = mid;
117✔
1003
      else
1004
        return mid;
2✔
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,736✔
1011
  int32_t i = startPos;
2,736✔
1012
  int64_t startTs = pTsList[startPos];
2,736✔
1013
  if (asc) {
2,736✔
1014
    while (i < num && (pTsList[i] == startTs)) {
5,414!
1015
      i++;
2,707✔
1016
    }
1017
    return i - 1;
2,707✔
1018
  } else {
1019
    while (i >= 0 && (pTsList[i] == startTs)) {
58!
1020
      i--;
29✔
1021
    }
1022
    return i + 1;
29✔
1023
  }
1024
}
1025

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

1031
  if (asc && pReader->info.window.ekey >= pRecord->lastKey.key.ts) {
336,035✔
1032
    endPos = pRecord->numRow - 1;
333,564✔
1033
  } else if (!asc && pReader->info.window.skey <= pRecord->firstKey.key.ts) {
2,471✔
1034
    endPos = 0;
1,370✔
1035
  } else {
1036
    int64_t key = asc ? pReader->info.window.ekey : pReader->info.window.skey;
1,101!
1037
    endPos = doBinarySearchKey(pBlockData->aTSKEY, pRecord->numRow, pos, key, pReader->info.order);
1,101✔
1038
    if (endPos == -1) {
1,370!
1039
      return endPos;
×
1040
    }
1041

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

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

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

1077
    // todo: opt perf by extract the loop
1078
    // reverse the array list
1079
    int32_t  mid = dumpedRows >> 1u;
1,340✔
1080
    int64_t* pts = (int64_t*)pColData->pData;
1,340✔
1081
    for (int32_t j = 0; j < mid; ++j) {
166,587✔
1082
      int64_t t = pts[j];
165,247✔
1083
      pts[j] = pts[dumpedRows - j - 1];
165,247✔
1084
      pts[dumpedRows - j - 1] = t;
165,247✔
1085
    }
1086
  }
1087
}
336,148✔
1088

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

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

1107
  // 2. reverse the array list in case of descending order scan data block
1108
  if (!asc) {
625,964✔
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) {
24,573✔
1117
          int64_t t = pts[j];
24,558✔
1118
          pts[j] = pts[dumpedRows - j - 1];
24,558✔
1119
          pts[dumpedRows - j - 1] = t;
24,558✔
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) {
24,573✔
1130
          int8_t t = pts[j];
24,558✔
1131
          pts[j] = pts[dumpedRows - j - 1];
24,558✔
1132
          pts[dumpedRows - j - 1] = t;
24,558✔
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) {
16,382✔
1142
          int64_t t = pts[j];
16,372✔
1143
          pts[j] = pts[dumpedRows - j - 1];
16,372✔
1144
          pts[dumpedRows - j - 1] = t;
16,372✔
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) {
24,573✔
1155
          int32_t t = pts[j];
24,558✔
1156
          pts[j] = pts[dumpedRows - j - 1];
24,558✔
1157
          pts[dumpedRows - j - 1] = t;
24,558✔
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) {
625,964✔
1166
    int32_t rowIndex = 0;
30,653✔
1167

1168
    for (int32_t j = pDumpInfo->rowIndex; rowIndex < dumpedRows; j += step, rowIndex++) {
124,481,905✔
1169
      uint8_t v = tColDataGetBitValue(pData, j);
124,450,057✔
1170
      if (v == 0 || v == 1) {
124,451,252!
1171
        colDataSetNull_f(pColData->nullbitmap, rowIndex);
12,438,682✔
1172
        pColData->hasNull = true;
12,438,682✔
1173
      }
1174
    }
1175
  }
1176
}
627,159✔
1177

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

1183
  if (pSupp->numOfPks > 0) {
1,270,452!
UNCOV
1184
    SValue* pFirst = &record->firstKey.key.pks[0];
×
UNCOV
1185
    SValue* pLast = &record->lastKey.key.pks[0];
×
1186

UNCOV
1187
    pFirst->type = pSupp->pk.type;
×
UNCOV
1188
    pLast->type = pSupp->pk.type;
×
1189

UNCOV
1190
    if (IS_VAR_DATA_TYPE(pFirst->type)) {
×
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 {
UNCOV
1197
      pFirst->val = pBlockInfo->firstPk.val;
×
UNCOV
1198
      pLast->val = pBlockInfo->lastPk.val;
×
1199
    }
1200
  }
1201

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

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

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

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

1233
  SColVal     cv = {0};
336,069✔
1234
  SBrinRecord tmp;
1235
  blockInfoToRecord(&tmp, pBlockInfo, pSupInfo);
336,069✔
1236
  SBrinRecord* pRecord = &tmp;
335,963✔
1237

1238
  // no data exists, return directly.
1239
  if (pBlockData->nRow == 0 || pBlockData->aTSKEY == 0) {
335,963!
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))) {
336,181!
1248
    if (asc && pReader->info.window.skey <= pRecord->firstKey.key.ts &&
335,564!
1249
        pReader->info.verRange.minVer <= pRecord->minVer) {
334,127!
1250
      // pDumpInfo->rowIndex = 0;
1251
    } else if (!asc && pReader->info.window.ekey >= pRecord->lastKey.key.ts &&
1,400✔
1252
               pReader->info.verRange.maxVer >= pRecord->maxVer) {
33!
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,367✔
1256
      int32_t order = asc ? TSDB_ORDER_DESC : TSDB_ORDER_ASC;
1,367✔
1257
      int64_t key = asc ? pReader->info.window.skey : pReader->info.window.ekey;
1,367✔
1258
      pDumpInfo->rowIndex = doBinarySearchKey(pBlockData->aTSKEY, pRecord->numRow, pos, key, order);
1,367✔
1259

1260
      if (pDumpInfo->rowIndex < 0) {
1,366!
UNCOV
1261
        tsdbError(
×
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);
UNCOV
1266
        return TSDB_CODE_INVALID_PARA;
×
1267
      }
1268

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

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

1314
  int32_t i = 0;
336,230✔
1315
  int32_t rowIndex = 0;
336,230✔
1316

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

1322
  if (pSupInfo->colId[i] == PRIMARYKEY_TIMESTAMP_COL_ID) {
336,209!
1323
    copyPrimaryTsCol(pBlockData, pDumpInfo, pColData, dumpedRows, asc);
336,248✔
1324
    i += 1;
336,012✔
1325
  }
1326

1327
  int32_t colIndex = 0;
335,973✔
1328
  int32_t num = pBlockData->nColData;
335,973✔
1329
  while (i < numOfOutputCols && colIndex < num) {
1,251,670✔
1330
    rowIndex = 0;
915,597✔
1331

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

1341
      if (pData->flag == HAS_NONE || pData->flag == HAS_NULL || pData->flag == (HAS_NULL | HAS_NONE)) {
915,590!
1342
        colDataSetNNULL(pColData, 0, dumpedRows);
85,236!
1343
      } else {
1344
        if (IS_MATHABLE_TYPE(pColData->info.type)) {
830,354!
1345
          copyNumericCols(pData, pDumpInfo, pColData, dumpedRows, asc);
625,852✔
1346
        } else {  // varchar/nchar type
1347
          for (int32_t j = pDumpInfo->rowIndex; rowIndex < dumpedRows; j += step) {
48,807,492✔
1348
            tColDataGetValue(pData, j, &cv);
48,623,410✔
1349
            code = doCopyColVal(pColData, rowIndex++, i, &cv, pSupInfo);
49,064,968✔
1350
            if (code) {
48,602,990!
1351
              return code;
×
1352
            }
1353
          }
1354
        }
1355
      }
1356

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

1385
  tColRowGetKeyDeepCopy(pBlockData, pDumpInfo->rowIndex - step, pSupInfo->pkSrcSlot, pLastProcKey);
336,073!
1386

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

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

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

1403
  int32_t unDumpedRows = asc ? pRecord->numRow - pDumpInfo->rowIndex : pDumpInfo->rowIndex + 1;
336,113✔
1404
  tsdbDebug("%p copy file block to sdatablock, global index:%d, table index:%d, brange:%" PRId64 "-%" PRId64
336,113✔
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;
336,214✔
1410
}
1411

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

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

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

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

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

1444
  tBlockDataReset(pBlockData);
352,804✔
1445

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

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

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

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

1486
  return code;
353,042✔
1487
}
1488

1489
/**
1490
 * This is an two rectangles overlap cases.
1491
 */
1492
static int32_t dataBlockPartiallyRequired(STimeWindow* pWindow, SVersionRange* pVerRange, SFileDataBlockInfo* pBlock) {
425,813✔
1493
  return (pWindow->ekey < pBlock->lastKey && pWindow->ekey >= pBlock->firstKey) ||
7,465!
1494
         (pWindow->skey > pBlock->firstKey && pWindow->skey <= pBlock->lastKey) ||
418,348!
1495
         (pVerRange->minVer > pBlock->minVer && pVerRange->minVer <= pBlock->maxVer) ||
1,269,758!
1496
         (pVerRange->maxVer < pBlock->maxVer && pVerRange->maxVer >= pBlock->minVer);
418,132!
1497
}
1498

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

1505
  if (asc && pBlockInfo->tbBlockIdx >= taosArrayGetSize(pScanInfo->pBlockIdxList) - 1) {
442,639✔
1506
    return false;
315,703✔
1507
  }
1508

1509
  if (!asc && pBlockInfo->tbBlockIdx == 0) {
126,923✔
1510
    return false;
10,116✔
1511
  }
1512

1513
  STableDataBlockIdx* pTableDataBlockIdx = taosArrayGet(pScanInfo->pBlockIdxList, pBlockInfo->tbBlockIdx + step);
116,807✔
1514
  if (pTableDataBlockIdx == NULL) {
117,123!
1515
    return TSDB_CODE_INVALID_PARA;
×
1516
  }
1517

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

1523
  blockInfoToRecord(pRecord, p, pSupInfo);
117,096✔
1524

1525
  *nextIndex = pBlockInfo->tbBlockIdx + step;
117,094✔
1526
  return true;
117,094✔
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,
117,089✔
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)) {
117,089✔
1613
    if (pBlock->lastKey == pRec->firstKey.key.ts) {
115,545!
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;
115,545✔
1627
    }
1628
  } else {
1629
    if (pBlock->firstKey == pRec->lastKey.key.ts) {
1,544!
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,544✔
1643
    }
1644
  }
1645
}
1646

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

1650
  int64_t key = 0;
381,081✔
1651
  if (pScanInfo->sttKeyInfo.status == STT_FILE_HAS_DATA) {
381,081✔
1652
    int64_t keyInStt = pScanInfo->sttKeyInfo.nextProcKey.ts;
9,624✔
1653
    key = ascScan ? TMIN(pBlock->firstKey, keyInStt) : TMAX(pBlock->lastKey, keyInStt);
9,624✔
1654
  } else {
1655
    key = ascScan ? pBlock->firstKey : pBlock->lastKey;
371,457!
1656
  }
1657

1658
  return key;
381,081✔
1659
}
1660

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

1666
  return (ascScan && (keyInBuf.ts != TSKEY_INITIAL_VAL && keyInBuf.ts < key)) ||
762,352✔
1667
         (!ascScan && (keyInBuf.ts != TSKEY_INITIAL_VAL && keyInBuf.ts > key));
381,168✔
1668
}
1669

1670
static bool keyOverlapFileBlock(TSDBKEY key, SFileDataBlockInfo* pBlock, SVersionRange* pVerRange) {
425,697✔
1671
  return (key.ts >= pBlock->firstKey && key.ts <= pBlock->lastKey) && (pBlock->maxVer >= pVerRange->minVer) &&
438,976!
1672
         (pBlock->minVer <= pVerRange->maxVer);
13,279!
1673
}
1674

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

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

1685
  // overlap with neighbor
1686
  if (hasNeighbor) {
426,066✔
1687
    pInfo->overlapWithNeighborBlock =
105,966✔
1688
        overlapWithNeighborBlock2(pBlockInfo, &rec, order, pSupInfo->pk.type, pSupInfo->numOfPks);
105,970✔
1689
  }
1690

1691
  SBrinRecord pRecord;
1692
  blockInfoToRecord(&pRecord, pBlockInfo, pSupInfo);
426,062✔
1693

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

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

1704
  pInfo->moreThanCapcity = pBlockInfo->numRow > pReader->resBlockInfo.capacity;
425,856✔
1705
  pInfo->partiallyRequired = dataBlockPartiallyRequired(&pReader->info.window, &pReader->info.verRange, pBlockInfo);
425,856✔
1706
  pInfo->overlapWithKeyInBuf = keyOverlapFileBlock(keyInBuf, pBlockInfo, &pReader->info.verRange);
425,729✔
1707
}
425,732✔
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,
401,385✔
1716
                                TSDBKEY keyInBuf) {
1717
  SDataBlockToLoadInfo info = {0};
401,385✔
1718
  getBlockToLoadInfo(&info, pBlockInfo, pScanInfo, keyInBuf, pReader);
401,385✔
1719

1720
  bool loadDataBlock =
401,471✔
1721
      (info.overlapWithNeighborBlock || info.hasDupTs || info.partiallyRequired || info.overlapWithKeyInBuf ||
401,550!
1722
       info.moreThanCapcity || info.overlapWithDelInfo || info.overlapWithSttBlock);
803,021!
1723

1724
  // log the reason why load the datablock for profile
1725
  if (loadDataBlock) {
401,471✔
1726
    tsdbDebug("%p uid:%" PRIu64
20,412✔
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;
401,586✔
1735
}
1736

1737
static bool isCleanFileDataBlock(STsdbReader* pReader, SFileDataBlockInfo* pBlockInfo, STableBlockScanInfo* pScanInfo,
24,303✔
1738
                                 TSDBKEY keyInBuf) {
1739
  SDataBlockToLoadInfo info = {0};
24,303✔
1740
  getBlockToLoadInfo(&info, pBlockInfo, pScanInfo, keyInBuf, pReader);
24,303✔
1741
  bool isCleanFileBlock = !(info.overlapWithNeighborBlock || info.hasDupTs || info.overlapWithKeyInBuf ||
40,886!
1742
                            info.overlapWithDelInfo || info.overlapWithSttBlock);
16,584✔
1743
  return isCleanFileBlock;
24,302✔
1744
}
1745

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

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

1757
  return code;
417,563,439✔
1758
}
1759

1760
static int32_t buildDataBlockFromBuf(STsdbReader* pReader, STableBlockScanInfo* pBlockScanInfo, int64_t endKey) {
5,169,990✔
1761
  if (!(pBlockScanInfo->iiter.hasVal || pBlockScanInfo->iter.hasVal)) {
5,169,990✔
1762
    return TSDB_CODE_SUCCESS;
3,542,527✔
1763
  }
1764

1765
  int32_t code = initRowMergeIfNeeded(pReader, pBlockScanInfo->uid);
1,627,463✔
1766
  if (code != 0) {
1,629,557!
1767
    return code;
×
1768
  }
1769

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

1774
  double el = (taosGetTimestampUs() - st) / 1000.0;
1,629,380✔
1775
  updateComposedBlockInfo(pReader, el, pBlockScanInfo);
1,629,380✔
1776

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

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

1793
  *copied = false;
30,614,105✔
1794
  bool asc = (pReader->info.order == TSDB_ORDER_ASC);
30,614,105✔
1795
  if ((pDumpInfo->rowIndex < pDumpInfo->totalRows - 1 && asc) || (pDumpInfo->rowIndex > 0 && (!asc))) {
30,614,105!
1796
    int32_t step = ASCENDING_TRAVERSE(pReader->info.order) ? 1 : -1;
30,656,881✔
1797

1798
    SRowKey nextRowKey;
1799
    tColRowGetKey(pBlockData, pDumpInfo->rowIndex + step, &nextRowKey);
30,656,881✔
1800

1801
    if (pkCompEx(pKey, &nextRowKey) != 0) {  // merge is not needed
30,671,011!
1802
      code = doAppendRowFromFileBlock(pReader->resBlockInfo.pResBlock, pReader, pBlockData, pDumpInfo->rowIndex);
30,673,115✔
1803
      if (code) {
30,749,570!
1804
        return code;
×
1805
      }
1806
      pDumpInfo->rowIndex += step;
30,749,570✔
1807
      *copied = true;
30,749,570✔
1808
    }
1809
  }
1810

1811
  return code;
30,704,690✔
1812
}
1813

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

1821
  while (1) {
608,041✔
1822
    bool hasVal = false;
334,297,150✔
1823
    code = tMergeTreeNext(&pSttBlockReader->mergeTree, &hasVal);
334,297,150✔
1824
    if (code) {
335,498,592!
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;
334,840,219✔
1828
    }
1829

1830
    if (!hasVal) {  // the next value will be the accessed key in stt
335,664,618✔
1831
      pScanInfo->sttKeyInfo.status = STT_FILE_NO_DATA;
5,672,067✔
1832

1833
      // next file, the timestamps in the next file must be greater than those in current
1834
      pNextProc->ts += step;
5,672,067✔
1835
      if (pSttBlockReader->numOfPks > 0) {
5,672,067✔
1836
        if (IS_NUMERIC_TYPE(pNextProc->pks[0].type)) {
2,537,766!
1837
          pNextProc->pks[0].val = INT64_MIN;
1,793,081✔
1838
        } else {
1839
          memset(pNextProc->pks[0].pData, 0, pNextProc->pks[0].nData);
744,685✔
1840
        }
1841
      }
1842
      return code;
5,672,067✔
1843
    }
1844

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

1849
    if (pSttBlockReader->numOfPks == 0) {
329,992,551✔
1850
      pSttBlockReader->currentKey.ts = key;
324,557,115✔
1851
    } else {
1852
      tColRowGetKeyDeepCopy(pRow->pBlockData, pRow->iRow, pkSrcSlot, &pSttBlockReader->currentKey);
5,435,436✔
1853
    }
1854

1855
    tColRowGetKeyDeepCopy(pRow->pBlockData, pRow->iRow, pkSrcSlot, pNextProc);
330,053,480✔
1856

1857
    if (pScanInfo->delSkyline != NULL && TARRAY_SIZE(pScanInfo->delSkyline) > 0) {
329,898,232!
1858
      if (!hasBeenDropped(pScanInfo->delSkyline, &pScanInfo->sttBlockDelIndex, key, ver, order, pVerRange,
21,490,162✔
1859
                          pSttBlockReader->numOfPks > 0)) {
21,612,201✔
1860
        pScanInfo->sttKeyInfo.status = STT_FILE_HAS_DATA;
20,882,121✔
1861
        return code;
20,882,121✔
1862
      }
1863
    } else {
1864
      pScanInfo->sttKeyInfo.status = STT_FILE_HAS_DATA;
308,286,031✔
1865
      return code;
308,286,031✔
1866
    }
1867
  }
1868

1869
  return code;
1870
}
1871

1872
static void doPinSttBlock(SSttBlockReader* pSttBlockReader) { tMergeTreePinSttBlock(&pSttBlockReader->mergeTree); }
272,852,328✔
1873

1874
static void doUnpinSttBlock(SSttBlockReader* pSttBlockReader) { tMergeTreeUnpinSttBlock(&pSttBlockReader->mergeTree); }
269,104,102✔
1875

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

1882
  // avoid the fetch next row replace the referenced stt block in buffer
1883
  doPinSttBlock(pSttBlockReader);
273,482,374✔
1884
  code = nextRowFromSttBlocks(pSttBlockReader, pScanInfo, pReader->suppInfo.pkSrcSlot, &pReader->info.verRange);
269,299,342✔
1885
  doUnpinSttBlock(pSttBlockReader);
271,420,798✔
1886

1887
  if (code) {
268,045,502!
1888
    return code;
×
1889
  }
1890

1891
  if (hasDataInSttBlock(pScanInfo)) {
268,045,502✔
1892
    SRowKey* pNext = getCurrentKeyInSttBlock(pSttBlockReader);
265,909,325!
1893
    if (pkCompEx(pSttKey, pNext) != 0) {
265,934,183✔
1894
      code = doAppendRowFromFileBlock(pReader->resBlockInfo.pResBlock, pReader, fRow->pBlockData, fRow->iRow);
263,647,880✔
1895
      *copied = (code == TSDB_CODE_SUCCESS);
277,798,388✔
1896
      return code;
277,798,388✔
1897
    }
1898
  } else {
1899
    code = doAppendRowFromFileBlock(pReader->resBlockInfo.pResBlock, pReader, fRow->pBlockData, fRow->iRow);
1,829,322✔
1900
    *copied = (code == TSDB_CODE_SUCCESS);
1,949,405✔
1901
    return code;
1,949,405✔
1902
  }
1903

1904
  return code;
2,286,303✔
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) {
83,762,542!
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) {
819,783,902!
1917
    return pReader->info.pSchema;
784,509,157✔
1918
  }
1919

1920
  void** p = tSimpleHashGet(pReader->pSchemaMap, &sversion, sizeof(sversion));
35,274,745✔
1921
  if (p != NULL) {
36,298,451!
1922
    return *(STSchema**)p;
36,174,388✔
1923
  }
1924

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

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

1948
  SRowKey* pSttKey = NULL;
76,861,613✔
1949
  if (hasDataInSttBlock(pBlockScanInfo) && (!pBlockScanInfo->cleanSttBlocks)) {
76,861,613!
1950
    pSttKey = getCurrentKeyInSttBlock(pSttBlockReader);
59,418,376✔
1951
  }
1952

1953
  SRowKey k = {0};
76,782,319✔
1954
  tRowGetKeyEx(pRow, &k);
76,782,319!
1955

1956
  STSchema* pSchema = NULL;
76,799,706✔
1957
  if (pRow->type == TSDBROW_ROW_FMT) {
76,799,706!
1958
    pSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(pRow), pReader, pBlockScanInfo->uid);
76,829,142!
1959
    if (pSchema == NULL) {
76,861,609!
1960
      return terrno;
×
1961
    }
1962
  }
1963

1964
  SRowKey* pfKey = &(SRowKey){0};
76,832,173✔
1965
  if (hasDataInFileBlock(pBlockData, pDumpInfo)) {
76,832,173✔
1966
    tColRowGetKey(pBlockData, pDumpInfo->rowIndex, pfKey);
22,905,028✔
1967
  } else {
1968
    pfKey = NULL;
54,047,321✔
1969
  }
1970

1971
  TSDBROW fRow = tsdbRowFromBlockData(pBlockData, pDumpInfo->rowIndex);
76,951,487✔
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);
76,951,487✔
1975
  if (code != 0) {
76,943,046!
1976
    return code;
×
1977
  }
1978

1979
  SRowKey minKey = k;
76,943,046✔
1980
  if (pReader->info.order == TSDB_ORDER_ASC) {
76,943,046✔
1981
    if (pfKey != NULL && pkCompEx(pfKey, &minKey) < 0) {
95,930,167✔
1982
      minKey = *pfKey;
20,108,542✔
1983
    }
1984

1985
    if (pSttKey != NULL && pkCompEx(pSttKey, &minKey) < 0) {
130,941,239✔
1986
      minKey = *pSttKey;
49,800,412✔
1987
    }
1988
  } else {
1989
    if (pfKey != NULL && pkCompEx(pfKey, &minKey) > 0) {
4,101,045✔
1990
      minKey = *pfKey;
944,421✔
1991
    }
1992

1993
    if (pSttKey != NULL && pkCompEx(pSttKey, &minKey) > 0) {
5,651,821!
1994
      minKey = *pSttKey;
1,118,208✔
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);
77,132,271✔
2001

2002
  // file block ---> stt block -----> mem
2003
  if (pkCompEx(&minKey, pfKey) == 0) {
77,062,495✔
2004
    code = tsdbRowMergerAdd(pMerger, &fRow, NULL);
21,962,411✔
2005
    if (code != TSDB_CODE_SUCCESS) {
22,028,516!
2006
      return code;
×
2007
    }
2008

2009
    code = doMergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pfKey, pReader);
22,028,516✔
2010
    if (code != TSDB_CODE_SUCCESS) {
22,045,675!
2011
      return code;
×
2012
    }
2013
  }
2014

2015
  if (pkCompEx(&minKey, pSttKey) == 0) {
77,284,565✔
2016
    TSDBROW* fRow1 = tMergeTreeGetRow(&pSttBlockReader->mergeTree);
54,143,350✔
2017
    code = tsdbRowMergerAdd(pMerger, fRow1, NULL);
54,143,350✔
2018
    if (code != TSDB_CODE_SUCCESS) {
54,489,783!
2019
      return code;
×
2020
    }
2021
    code = doMergeRowsInSttBlock(pSttBlockReader, pBlockScanInfo, pMerger, pkSrcSlot, &pReader->info.verRange, pReader->idStr);
54,489,783✔
2022
    if (code != TSDB_CODE_SUCCESS) {
53,824,068!
2023
      return code;
×
2024
    }
2025
  }
2026

2027
  if (pkCompEx(&minKey, &k) == 0) {
76,934,171✔
2028
    code = tsdbRowMergerAdd(pMerger, pRow, pSchema);
5,429,646✔
2029
    if (code != TSDB_CODE_SUCCESS) {
5,434,537!
2030
      return code;
×
2031
    }
2032

2033
    code = doMergeRowsInBuf(pIter, pBlockScanInfo->uid, &k, pBlockScanInfo->delSkyline, pReader);
5,434,537✔
2034
    if (code != TSDB_CODE_SUCCESS) {
5,428,458!
2035
      return code;
×
2036
    }
2037
  }
2038

2039
  code = tsdbRowMergerGetRow(pMerger, &pTSRow);
76,932,983✔
2040
  if (code != TSDB_CODE_SUCCESS) {
78,393,503!
2041
    return code;
×
2042
  }
2043

2044
  code = doAppendRowFromTSRow(pReader->resBlockInfo.pResBlock, pReader, pTSRow, pBlockScanInfo);
78,393,503✔
2045

2046
  taosMemoryFree(pTSRow);
77,968,363✔
2047
  tsdbRowMergerClear(pMerger);
78,606,226✔
2048

2049
  return code;
75,932,296✔
2050
}
2051

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

2065
  bool dataInDataFile = hasDataInFileBlock(pBlockData, pDumpInfo);
308,492,392✔
2066
  bool dataInSttFile = hasDataInSttBlock(pBlockScanInfo);
305,657,932✔
2067

2068
  if (dataInDataFile && (!dataInSttFile)) {
305,691,810✔
2069
    // no stt file block available, only data block exists
2070
    return mergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pKey, pReader);
12,350,657✔
2071
  } else if ((!dataInDataFile) && dataInSttFile) {
293,341,153!
2072
    // no data in data file exists
2073
    return mergeRowsInSttBlocks(pSttBlockReader, pBlockScanInfo, pReader);
274,109,618✔
2074
  } else if (pBlockScanInfo->cleanSttBlocks && pReader->info.execMode == READER_EXEC_ROWS) {
19,231,535!
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);
19,231,535✔
2080
    SRowKey* pSttKey = getCurrentKeyInSttBlock(pSttBlockReader);
19,231,535!
2081

2082
    int32_t ret = pkCompEx(pKey, pSttKey);
19,289,104✔
2083

2084
    if (ASCENDING_TRAVERSE(pReader->info.order)) {
19,289,104✔
2085
      if (ret < 0) {  // asc
18,640,032✔
2086
        return mergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pKey, pReader);
17,892,431✔
2087
      } else if (ret > 0) {
747,601✔
2088
        return mergeRowsInSttBlocks(pSttBlockReader, pBlockScanInfo, pReader);
17,460✔
2089
      }
2090
    } else {  // desc
2091
      if (ret > 0) {
649,072✔
2092
        return mergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pKey, pReader);
374,906✔
2093
      } else if (ret < 0) {
274,166✔
2094
        return mergeRowsInSttBlocks(pSttBlockReader, pBlockScanInfo, pReader);
186,579✔
2095
      }
2096
    }
2097

2098
    // pKey == pSttKey
2099
    tRowKeyAssign(&pBlockScanInfo->lastProcKey, pKey);
817,728✔
2100

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

2109
    code = doMergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pKey, pReader);
826,404✔
2110
    if (code != TSDB_CODE_SUCCESS) {
825,849!
2111
      return code;
×
2112
    }
2113

2114
    TSDBROW* pRow1 = tMergeTreeGetRow(&pSttBlockReader->mergeTree);
825,849✔
2115
    code = tsdbRowMergerAdd(pMerger, pRow1, NULL);
825,849✔
2116
    if (code != TSDB_CODE_SUCCESS) {
821,537!
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);
821,537✔
2122
    if (code != TSDB_CODE_SUCCESS) {
822,910!
2123
      return code;
×
2124
    }
2125

2126
    code = tsdbRowMergerGetRow(pMerger, &pTSRow);
822,910✔
2127
    if (code != TSDB_CODE_SUCCESS) {
828,327!
2128
      return code;
×
2129
    }
2130

2131
    code = doAppendRowFromTSRow(pReader->resBlockInfo.pResBlock, pReader, pTSRow, pBlockScanInfo);
828,327✔
2132

2133
    taosMemoryFree(pTSRow);
827,734✔
2134
    tsdbRowMergerClear(pMerger);
829,167✔
2135
    return code;
788,058✔
2136
  }
2137
}
2138

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

2150
  getValidMemRow(&pBlockScanInfo->iter, pDelList, pReader, &pRow);
2,494,272✔
2151
  getValidMemRow(&pBlockScanInfo->iiter, pDelList, pReader, &piRow);
2,494,023✔
2152

2153
  SRowKey* pSttKey = NULL;
2,493,504✔
2154
  if (hasDataInSttBlock(pBlockScanInfo) && (!pBlockScanInfo->cleanSttBlocks)) {
2,493,504!
2155
    pSttKey = getCurrentKeyInSttBlock(pSttBlockReader);
2,217,373✔
2156
  }
2157

2158
  SRowKey* pfKey = &(SRowKey){0};
2,494,289✔
2159
  if (hasDataInFileBlock(pBlockData, pDumpInfo)) {
2,494,289✔
2160
    tColRowGetKey(pBlockData, pDumpInfo->rowIndex, pfKey);
276,919!
2161
  } else {
2162
    pfKey = NULL;
2,217,773✔
2163
  }
2164

2165
  SRowKey k = {0}, ik = {0};
2,500,980✔
2166
  tRowGetKeyEx(pRow, &k);
2,500,980!
2167
  tRowGetKeyEx(piRow, &ik);
2,501,090!
2168

2169
  STSchema* pSchema = NULL;
2,501,090✔
2170
  if (pRow->type == TSDBROW_ROW_FMT) {
2,501,090✔
2171
    pSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(pRow), pReader, pBlockScanInfo->uid);
2,501,028!
2172
    if (pSchema == NULL) {
2,501,566!
2173
      return terrno;
×
2174
    }
2175
  }
2176

2177
  STSchema* piSchema = NULL;
2,501,628✔
2178
  if (piRow->type == TSDBROW_ROW_FMT) {
2,501,628✔
2179
    piSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(piRow), pReader, pBlockScanInfo->uid);
2,501,342!
2180
    if (piSchema == NULL) {
2,501,166!
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);
2,501,452✔
2187
  if (code != 0) {
2,501,062!
2188
    return code;
×
2189
  }
2190

2191
  SRowKey minKey = k;
2,501,062✔
2192
  if (ASCENDING_TRAVERSE(pReader->info.order)) {
2,501,062✔
2193
    if (pkCompEx(&ik, &minKey) < 0) {  // minKey > ik.key.ts) {
2,501,193✔
2194
      minKey = ik;
2,456,945✔
2195
    }
2196

2197
    if ((pfKey != NULL) && (pkCompEx(pfKey, &minKey) < 0)) {
2,780,018✔
2198
      minKey = *pfKey;
261,503✔
2199
    }
2200

2201
    if ((pSttKey != NULL) && (pkCompEx(pSttKey, &minKey) < 0)) {
4,723,641✔
2202
      minKey = *pSttKey;
2,146,179✔
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);
2,501,819✔
2219

2220
  // file block -----> stt block -----> imem -----> mem
2221
  if (pkCompEx(&minKey, pfKey) == 0) {
2,500,414✔
2222
    TSDBROW fRow = tsdbRowFromBlockData(pBlockData, pDumpInfo->rowIndex);
261,915✔
2223
    code = tsdbRowMergerAdd(pMerger, &fRow, NULL);
261,915✔
2224
    if (code != TSDB_CODE_SUCCESS) {
261,331!
2225
      return code;
×
2226
    }
2227

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

2234
  if (pkCompEx(&minKey, pSttKey) == 0) {
2,499,881✔
2235
    TSDBROW* pRow1 = tMergeTreeGetRow(&pSttBlockReader->mergeTree);
2,194,953✔
2236
    code = tsdbRowMergerAdd(pMerger, pRow1, NULL);
2,194,953✔
2237
    if (code != TSDB_CODE_SUCCESS) {
2,192,607!
2238
      return code;
×
2239
    }
2240

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

2247
  if (pkCompEx(&minKey, &ik) == 0) {
2,493,800✔
2248
    code = tsdbRowMergerAdd(pMerger, piRow, piSchema);
91,528✔
2249
    if (code != TSDB_CODE_SUCCESS) {
91,511!
2250
      return code;
×
2251
    }
2252

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

2259
  if (pkCompEx(&minKey, &k) == 0) {
2,493,040✔
2260
    code = tsdbRowMergerAdd(pMerger, pRow, pSchema);
31,952✔
2261
    if (code != TSDB_CODE_SUCCESS) {
31,952!
2262
      return code;
×
2263
    }
2264

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

2271
  code = tsdbRowMergerGetRow(pMerger, &pTSRow);
2,493,040✔
2272
  if (code != TSDB_CODE_SUCCESS) {
2,503,135!
2273
    return code;
×
2274
  }
2275

2276
  code = doAppendRowFromTSRow(pReader->resBlockInfo.pResBlock, pReader, pTSRow, pBlockScanInfo);
2,503,135✔
2277

2278
  taosMemoryFree(pTSRow);
2,500,598✔
2279
  tsdbRowMergerClear(pMerger);
2,503,484✔
2280
  return code;
2,492,273✔
2281
}
2282

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

2289
  if (pMem != NULL) {
7,293,044✔
2290
    *pData = tsdbGetTbDataFromMemTable(pMem, pReader->info.suid, pBlockScanInfo->uid);
2,959,802✔
2291

2292
    if ((*pData) != NULL) {
2,962,607✔
2293
      code = tsdbTbDataIterCreate((*pData), pKey, backward, &pIter->iter);
1,605,727✔
2294
      if (code == TSDB_CODE_SUCCESS) {
1,603,762!
2295
        pIter->hasVal = (tsdbTbDataIterGet(pIter->iter) != NULL);
1,603,811!
2296

2297
        tsdbDebug("%p uid:%" PRIu64 ", check data in %s from skey:%" PRId64 ", order:%d, ts range in buf:%" PRId64
1,603,811✔
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);
4,333,242✔
2309
  }
2310

2311
  return code;
7,293,027✔
2312
}
2313

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

2319
  while (1) {
290✔
2320
    getValidMemRow(pIter, pBlockScanInfo->delSkyline, pReader, &pRow);
407,139✔
2321
    if (!pIter->hasVal) {
407,146✔
2322
      break;
275,459✔
2323
    }
2324

2325
    tRowGetKeyEx(pRow, &rowKey);
131,687✔
2326
    int32_t ret = pkCompEx(pKey, &rowKey);
131,620✔
2327
    if (ret == 0) {
131,620!
2328
      pIter->hasVal = tsdbTbDataIterNext(pIter->iter);
×
2329
    } else {
2330
      break;
131,620✔
2331
    }
2332
  }
2333
}
407,079✔
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) {
203,746✔
2337
  doForwardDataIter(pKey, &pBlockScanInfo->iter, pBlockScanInfo, pReader);
203,746✔
2338
  doForwardDataIter(pKey, &pBlockScanInfo->iiter, pBlockScanInfo, pReader);
203,580✔
2339
}
203,521✔
2340

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

2349
  if (pBlockScanInfo->iterInit) {
10,869,760✔
2350
    return TSDB_CODE_SUCCESS;
7,227,549✔
2351
  }
2352

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

2361
  int32_t code = doInitMemDataIter(pReader, &d, pBlockScanInfo, &startKey, pSnap->pMem, &pBlockScanInfo->iter, "mem");
3,642,211✔
2362
  if (code != TSDB_CODE_SUCCESS) {
3,648,438!
2363
    return code;
×
2364
  }
2365

2366
  code = doInitMemDataIter(pReader, &di, pBlockScanInfo, &startKey, pSnap->pIMem, &pBlockScanInfo->iiter, "imem");
3,648,438✔
2367
  if (code != TSDB_CODE_SUCCESS) {
3,648,033!
2368
    return code;
×
2369
  }
2370

2371
  code = loadMemTombData(&pBlockScanInfo->pMemDelData, d, di, pReader->info.verRange.maxVer);
3,648,033✔
2372
  if (code != TSDB_CODE_SUCCESS) {
3,650,276!
2373
    return code;
×
2374
  }
2375

2376
  if (forward) {
3,650,276✔
2377
    forwardDataIter(&startKey.key, pBlockScanInfo, pReader);
203,755✔
2378
  }
2379

2380
  pBlockScanInfo->iterInit = true;
3,650,336✔
2381
  return TSDB_CODE_SUCCESS;
3,650,336✔
2382
}
2383

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

2400
  int64_t ts = pBlockData->aTSKEY[rowIndex];
62,324,757✔
2401
  if (ts > pInfo->window.ekey || ts < pInfo->window.skey) {
62,324,757✔
2402
    return false;
3,807,341✔
2403
  }
2404

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

2409
  if (ts == pBlockScanInfo->lastProcKey.ts) {  // todo opt perf
58,517,416!
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) {
58,517,416!
2418
    bool dropped = hasBeenDropped(pBlockScanInfo->delSkyline, &pBlockScanInfo->fileDelIndex, ts, ver, pInfo->order,
34,726,521✔
2419
                                  &pInfo->verRange, pReader->suppInfo.numOfPks > 0);
34,726,521✔
2420
    if (dropped) {
34,703,549✔
2421
      return false;
3,981,257✔
2422
    }
2423
  }
2424

2425
  return true;
54,513,187✔
2426
}
2427

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

2432
  // the stt block reader has been initialized for this table.
2433
  if (pSttBlockReader->uid == pScanInfo->uid) {
7,843,571✔
2434
    return;
2,144,444✔
2435
  }
2436

2437
  if (pSttBlockReader->uid != 0) {
5,699,127✔
2438
    tMergeTreeClose(&pSttBlockReader->mergeTree);
2,660,777✔
2439
  }
2440

2441
  pSttBlockReader->uid = pScanInfo->uid;
5,704,526✔
2442

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

2453
  STimeWindow w = pSttBlockReader->window;
5,704,526✔
2454
  if (asc) {
5,704,526✔
2455
    w.skey = pScanInfo->sttKeyInfo.nextProcKey.ts;
4,820,869✔
2456
  } else {
2457
    w.ekey = pScanInfo->sttKeyInfo.nextProcKey.ts;
883,657✔
2458
  }
2459

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

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

2484
  SSttDataInfoForTable info = {.pKeyRangeList = taosArrayInit(4, sizeof(SSttKeyRange))};
5,706,571✔
2485
  if (info.pKeyRangeList == NULL) {
5,714,263!
2486
    pReader->code = terrno;
×
2487
    return;
×
2488
  }
2489

2490
  int32_t code = tMergeTreeOpen2(&pSttBlockReader->mergeTree, &conf, &info);
5,714,263✔
2491
  if (code != TSDB_CODE_SUCCESS) {
5,701,593!
2492
    taosArrayDestroy(info.pKeyRangeList);
×
2493
    pReader->code = code;
×
2494
    return;
×
2495
  }
2496

2497
  code = initMemDataIterator(pScanInfo, pReader);
5,701,593✔
2498
  if (code != TSDB_CODE_SUCCESS) {
5,704,757!
2499
    taosArrayDestroy(info.pKeyRangeList);
×
2500
    pReader->code = code;
×
2501
    return;
×
2502
  }
2503

2504
  code = initDelSkylineIterator(pScanInfo, pReader->info.order, &pReader->cost);
5,704,757✔
2505
  if (code != TSDB_CODE_SUCCESS) {
5,704,728✔
2506
    taosArrayDestroy(info.pKeyRangeList);
588✔
2507
    pReader->code = code;
×
2508
    return;
×
2509
  }
2510

2511
  if (conf.rspRows) {
5,704,140✔
2512
    pScanInfo->cleanSttBlocks = isCleanSttBlock(info.pKeyRangeList, &pReader->info.window, pScanInfo, order);
161,545✔
2513
    if (pScanInfo->cleanSttBlocks) {
161,537✔
2514
      pScanInfo->numOfRowsInStt = info.numOfRows;
25,791✔
2515

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

2523
        if (pkCompEx(&pScanInfo->sttRange.skey, &pKeyRange->skey) > 0) {
51,553!
2524
          tRowKeyAssign(&pScanInfo->sttRange.skey, &pKeyRange->skey);
25,765✔
2525
        }
2526

2527
        if (pkCompEx(&pScanInfo->sttRange.ekey, &pKeyRange->ekey) < 0) {
51,532!
2528
          tRowKeyAssign(&pScanInfo->sttRange.ekey, &pKeyRange->ekey);
25,771✔
2529
        }
2530
      }
2531

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

2534
      SRowKey* p = asc ? &pScanInfo->sttRange.skey : &pScanInfo->sttRange.ekey;
25,745✔
2535
      tRowKeyAssign(&pScanInfo->sttKeyInfo.nextProcKey, p);
25,745✔
2536
    } else {                                // not clean stt blocks
2537
      INIT_KEYRANGE(&pScanInfo->sttRange);  // reset the time window
135,746✔
2538
      code = nextRowFromSttBlocks(pSttBlockReader, pScanInfo, pReader->suppInfo.pkSrcSlot, &pReader->info.verRange);
135,746✔
2539
    }
2540
  } else {
2541
    pScanInfo->cleanSttBlocks = false;
5,542,595✔
2542
    INIT_KEYRANGE(&pScanInfo->sttRange);  // reset the time window
5,542,595✔
2543
    code = nextRowFromSttBlocks(pSttBlockReader, pScanInfo, pReader->suppInfo.pkSrcSlot, &pReader->info.verRange);
5,542,595✔
2544
  }
2545

2546
  pScanInfo->sttBlockReturned = false;
5,702,418✔
2547
  taosArrayDestroy(info.pKeyRangeList);
5,702,418✔
2548

2549
  int64_t el = taosGetTimestampUs() - st;
5,710,962✔
2550
  pReader->cost.initSttBlockReader += (el / 1000.0);
5,710,962✔
2551

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

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

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

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

2573
  int32_t code = tryCopyDistinctRowFromFileBlock(pReader, pBlockData, pKey, pDumpInfo, &copied);
30,614,184✔
2574
  if (code != TSDB_CODE_SUCCESS) {
30,687,356!
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);
30,687,356✔
2580
  if (code != 0) {
30,665,901!
2581
    return code;
×
2582
  }
2583

2584
  tRowKeyAssign(&pBlockScanInfo->lastProcKey, pKey);
30,665,901✔
2585

2586
  if (copied) {
30,650,094✔
2587
    return TSDB_CODE_SUCCESS;
30,644,372✔
2588
  } else {
2589
    TSDBROW fRow = tsdbRowFromBlockData(pBlockData, pDumpInfo->rowIndex);
5,722✔
2590

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

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

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

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

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

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

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

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

2627
  if (IS_VAR_DATA_TYPE(pScanInfo->lastProcKey.pks[0].type)) {
273,406,682!
2628
    tsdbTrace("fRow ptr:%p, %d, uid:%" PRIu64 ", ts:%" PRId64 " pk:%s %s", pRow->pBlockData, pRow->iRow,
1,262,957!
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);
273,406,682✔
2635
  if (code) {
281,136,074!
2636
    return code;
×
2637
  }
2638

2639
  if (copied) {
281,136,074✔
2640
    return TSDB_CODE_SUCCESS;
279,692,873✔
2641
  } else {
2642
    code = tsdbRowMergerAdd(pMerger, &fRow, NULL);
1,443,201✔
2643
    if (code != TSDB_CODE_SUCCESS) {
1,548,167!
2644
      return code;
×
2645
    }
2646

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

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

2658
    code = tsdbRowMergerGetRow(pMerger, &pTSRow);
1,523,266✔
2659
    if (code != TSDB_CODE_SUCCESS) {
1,559,757!
2660
      return code;
×
2661
    }
2662

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

2665
    taosMemoryFree(pTSRow);
1,556,897✔
2666
    tsdbRowMergerClear(pMerger);
1,564,282✔
2667
    return code;
1,396,472✔
2668
  }
2669
}
2670

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

2675
  TSDBROW *pRow = NULL, *piRow = NULL;
387,198,989✔
2676

2677
  SRowKey* pKey = &(SRowKey){0};
387,198,989✔
2678
  if (hasDataInFileBlock(pBlockData, pDumpInfo)) {
387,198,989✔
2679
    tColRowGetKey(pBlockData, pDumpInfo->rowIndex, pKey);
54,339,058✔
2680
  } else {
2681
    pKey = NULL;
330,221,319✔
2682
  }
2683

2684
  if (pBlockScanInfo->iter.hasVal) {
385,663,942✔
2685
    getValidMemRow(&pBlockScanInfo->iter, pBlockScanInfo->delSkyline, pReader, &pRow);
62,795,062✔
2686
  }
2687

2688
  if (pBlockScanInfo->iiter.hasVal) {
385,524,131✔
2689
    getValidMemRow(&pBlockScanInfo->iiter, pBlockScanInfo->delSkyline, pReader, &piRow);
18,555,935✔
2690
  }
2691

2692
  // two levels of mem-table does contain the valid rows
2693
  if (pRow != NULL && piRow != NULL) {
385,531,200✔
2694
    return doMergeMultiLevelRows(pReader, pBlockScanInfo, pBlockData, pSttBlockReader);
2,494,400✔
2695
  }
2696

2697
  // imem + file + stt block
2698
  if (pBlockScanInfo->iiter.hasVal) {
383,036,800✔
2699
    return doMergeBufAndFileRows(pReader, pBlockScanInfo, piRow, &pBlockScanInfo->iiter, pSttBlockReader);
16,252,352✔
2700
  }
2701

2702
  // mem + file + stt block
2703
  if (pBlockScanInfo->iter.hasVal) {
366,784,448✔
2704
    return doMergeBufAndFileRows(pReader, pBlockScanInfo, pRow, &pBlockScanInfo->iter, pSttBlockReader);
60,863,106✔
2705
  }
2706

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

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

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

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

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

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

2766
  int32_t code = blockDataUpdateTsWindow(pResBlock, pReader->suppInfo.slotId[0]);
3,733,204✔
2767
  code = blockDataUpdatePkRange(pResBlock, pReader->suppInfo.pkDstSlot, ASCENDING_TRAVERSE(pReader->info.order));
3,735,073✔
2768
  setComposedBlockFlag(pReader, true);
3,734,285✔
2769

2770
  pReader->cost.composedBlocks += 1;
3,732,820✔
2771
  pReader->cost.buildComposedBlockTime += el;
3,732,820✔
2772
}
3,732,820✔
2773

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

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

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

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

2801
  TSDBKEY keyInBuf = getCurrentKeyInBuf(pBlockScanInfo, pReader);
24,303✔
2802

2803
  // it is a clean block, load it directly
2804
  int64_t cap = pReader->resBlockInfo.capacity;
24,303✔
2805
  bool    directCopy = isCleanFileDataBlock(pReader, pBlockInfo, pBlockScanInfo, keyInBuf) &&
24,303✔
2806
                    (pBlockInfo->numRow <= cap) && (pBlockScanInfo->sttKeyInfo.status == STT_FILE_NO_DATA) &&
27,785!
2807
                    ((asc && ((pBlockInfo->lastKey < keyInBuf.ts) || (keyInBuf.ts == INT64_MIN))) ||
2,129!
2808
                     (!asc && (pBlockInfo->lastKey > keyInBuf.ts)));
1,354!
2809
  if (directCopy) {
24,302✔
2810
    code = copyBlockDataToSDataBlock(pReader, &pBlockScanInfo->lastProcKey);
3,483✔
2811
    goto _end;
3,483✔
2812
  }
2813

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

2821
  while (1) {
54,432,917✔
2822
    bool hasBlockData = false;
54,453,736✔
2823
    {
2824
      while (pBlockData->nRow > 0 && pBlockData->uid == pBlockScanInfo->uid) {
62,248,894!
2825
        // find the first qualified row in data block
2826
        if (isValidFileBlockRow(pBlockData, pDumpInfo->rowIndex, pBlockScanInfo, asc, &pReader->info, pReader)) {
62,296,870✔
2827
          hasBlockData = true;
54,493,774✔
2828
          break;
54,493,774✔
2829
        }
2830

2831
        pDumpInfo->rowIndex += step;
7,850,680✔
2832

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

2852
    // no data in last block and block, no need to proceed.
2853
    if (hasBlockData == false) {
54,447,787✔
2854
      break;
1,989✔
2855
    }
2856

2857
    code = buildComposedDataBlockImpl(pReader, pBlockScanInfo, pBlockData, pSttBlockReader);
54,445,798✔
2858
    if (code) {
54,468,974!
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)) {
54,468,974✔
2864
      setBlockAllDumped(pDumpInfo, pBlockInfo->lastKey, pReader->info.order);
32,039✔
2865
      break;
14,813✔
2866
    }
2867

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

2873
_end:
24,303✔
2874
  el = (taosGetTimestampUs() - st) / 1000.0;
24,302✔
2875
  updateComposedBlockInfo(pReader, el, pBlockScanInfo);
24,302✔
2876

2877
  if (pResBlock->info.rows > 0) {
24,302✔
2878
    tsdbDebug("%p uid:%" PRIu64 ", composed data block created, brange:%" PRIu64 "-%" PRIu64 " rows:%" PRId64
23,112✔
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;
24,301✔
2885
}
2886

2887
void setComposedBlockFlag(STsdbReader* pReader, bool composed) { pReader->status.composedDataBlock = composed; }
4,139,164✔
2888

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

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

2897
int32_t initDelSkylineIterator(STableBlockScanInfo* pBlockScanInfo, int32_t order, SReadCostSummary* pCost) {
10,872,638✔
2898
  int32_t code = 0;
10,872,638✔
2899
  int32_t newDelDataInFile = taosArrayGetSize(pBlockScanInfo->pFileDelData);
10,872,638✔
2900
  if (newDelDataInFile == 0 &&
10,874,181✔
2901
      ((pBlockScanInfo->delSkyline != NULL) || (TARRAY_SIZE(pBlockScanInfo->pMemDelData) == 0))) {
10,849,269✔
2902
    return code;
10,835,261✔
2903
  }
2904

2905
  int64_t st = taosGetTimestampUs();
40,617✔
2906

2907
  if (pBlockScanInfo->delSkyline != NULL) {
40,617✔
2908
    taosArrayClear(pBlockScanInfo->delSkyline);
9,417✔
2909
  } else {
2910
    pBlockScanInfo->delSkyline = taosArrayInit(4, sizeof(TSDBKEY));
31,200✔
2911
    if (pBlockScanInfo->delSkyline == NULL) {
31,200!
2912
      return terrno;
×
2913
    }
2914
  }
2915

2916
  SArray* pSource = pBlockScanInfo->pFileDelData;
40,617✔
2917
  if (pSource == NULL) {
40,617✔
2918
    pSource = pBlockScanInfo->pMemDelData;
13,615✔
2919
  } else {
2920
    void* p1 = taosArrayAddAll(pSource, pBlockScanInfo->pMemDelData);
27,002✔
2921
    if (p1 == NULL) {
27,002!
2922
      return terrno;
×
2923
    }
2924
  }
2925

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

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

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

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

2939
  return code;
40,616✔
2940
}
2941

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

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

2950
  getValidMemRow(&pScanInfo->iter, pScanInfo->delSkyline, pReader, &pRow);
425,793✔
2951
  if (pRow != NULL) {
425,793✔
2952
    hasKey = true;
15,471✔
2953
    key = TSDBROW_KEY(pRow);
15,471!
2954
  }
2955

2956
  getValidMemRow(&pScanInfo->iiter, pScanInfo->delSkyline, pReader, &pIRow);
425,793✔
2957
  if (pIRow != NULL) {
425,793✔
2958
    hasIKey = true;
2,323✔
2959
    ikey = TSDBROW_KEY(pIRow);
2,323!
2960
  }
2961

2962
  if (hasKey) {
425,793✔
2963
    if (hasIKey) {  // has data in mem & imem
15,471✔
2964
      if (asc) {
190!
2965
        return key.ts <= ikey.ts ? key : ikey;
190✔
2966
      } else {
2967
        return key.ts <= ikey.ts ? ikey : key;
×
2968
      }
2969
    } else {  // no data in imem
2970
      return key;
15,281✔
2971
    }
2972
  } else {
2973
    // no data in mem & imem, return the initial value
2974
    // only imem has data, return ikey
2975
    return ikey;
410,322✔
2976
  }
2977
}
2978

2979
static void prepareDurationForNextFileSet(STsdbReader* pReader) {
143,457✔
2980
  if (pReader->status.bProcMemFirstFileset) {
143,457✔
2981
    pReader->status.prevFilesetStartKey = INT64_MIN;
18,960✔
2982
    pReader->status.prevFilesetEndKey = INT64_MAX;
18,960✔
2983
    pReader->status.bProcMemFirstFileset = false;
18,960✔
2984
  }
2985

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

2990
  if (ASCENDING_TRAVERSE(pReader->info.order)) {
143,462✔
2991
    pReader->status.bProcMemPreFileset = !(pReader->status.memTableMaxKey < pReader->status.prevFilesetStartKey ||
113,986✔
2992
                                           (winFid.skey - 1) < pReader->status.memTableMinKey);
16,722✔
2993
  } else {
2994
    pReader->status.bProcMemPreFileset = !(pReader->status.memTableMaxKey < (winFid.ekey + 1) ||
46,218✔
2995
                                           pReader->status.prevFilesetEndKey < pReader->status.memTableMinKey);
20!
2996
  }
2997

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

3004
  if (!pReader->status.bProcMemPreFileset) {
143,462✔
3005
    if (pReader->notifyFn) {
142,213✔
3006
      STsdReaderNotifyInfo info = {0};
141,964✔
3007
      info.duration.filesetId = fid;
141,964✔
3008
      pReader->notifyFn(TSD_READER_NOTIFY_DURATION_START, &info, pReader->notifyParam);
141,964✔
3009
      tsdbDebug("new duration %d start notification when no buffer preceeding fileset, %s", fid, pReader->idStr);
141,943✔
3010
    }
3011
  }
3012

3013
  pReader->status.prevFilesetStartKey = winFid.skey;
143,456✔
3014
  pReader->status.prevFilesetEndKey = winFid.ekey;
143,456✔
3015
}
143,456✔
3016

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

3022
  size_t  numOfTables = tSimpleHashGetSize(pReader->status.pTableMap);
3,350,523✔
3023
  SArray* pIndexList = taosArrayInit(numOfTables, sizeof(SBrinBlk));
3,350,980✔
3024
  if (pIndexList == NULL) {
3,350,858!
3025
    return terrno;
×
3026
  }
3027

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

3042
    if (!hasNext) {  // no data files on disk
3,353,565✔
3043
      break;
298,624✔
3044
    }
3045

3046
    taosArrayClear(pIndexList);
3,054,941✔
3047
    code = doLoadBlockIndex(pReader, pReader->pFileReader, pIndexList);
3,054,481✔
3048
    if (code != TSDB_CODE_SUCCESS) {
3,054,129!
3049
      taosArrayDestroy(pIndexList);
×
3050
      return code;
×
3051
    }
3052

3053
    if (taosArrayGetSize(pIndexList) > 0 || pReader->status.pCurrentFileset->lvlArr->size > 0) {
3,054,129✔
3054
      code = loadFileBlockBrinInfo(pReader, pIndexList, pBlockNum, pTableList);
3,053,169✔
3055
      if (code != TSDB_CODE_SUCCESS) {
3,053,194!
3056
        taosArrayDestroy(pIndexList);
×
3057
        return code;
×
3058
      }
3059

3060
      if (pBlockNum->numOfBlocks + pBlockNum->numOfSttFiles > 0) {
3,053,194✔
3061
        if (pReader->bFilesetDelimited) {
3,052,465✔
3062
          prepareDurationForNextFileSet(pReader);
143,495✔
3063
        }
3064
        break;
3,051,589✔
3065
      }
3066
    }
3067

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

3071
  taosArrayDestroy(pIndexList);
3,350,213✔
3072
  return loadDataFileTombDataForAll(pReader);
3,352,934✔
3073
}
3074

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

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

3087
  return 0;
7,038,730✔
3088
}
3089

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

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

3098
static bool moveToNextTable(STableUidList* pOrderedCheckInfo, SReaderStatus* pStatus) {
9,033,382✔
3099
  pOrderedCheckInfo->currentIndex += 1;
9,033,382✔
3100
  if (pOrderedCheckInfo->currentIndex >= tSimpleHashGetSize(pStatus->pTableMap)) {
9,033,382✔
3101
    pStatus->pTableIter = NULL;
4,344,705✔
3102
    return false;
4,344,705✔
3103
  }
3104

3105
  uint64_t uid = pOrderedCheckInfo->tableUidList[pOrderedCheckInfo->currentIndex];
4,689,150✔
3106
  pStatus->pTableIter = tSimpleHashGet(pStatus->pTableMap, &uid, sizeof(uid));
4,689,150✔
3107
  return (pStatus->pTableIter != NULL);
4,695,368✔
3108
}
3109

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

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

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

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

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

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

3142
  setComposedBlockFlag(pReader, true);
25,763✔
3143

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

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

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

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

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

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

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

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

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

3206
  if (tSimpleHashGetSize(pStatus->pTableMap) == 0) {
5,135,117!
3207
    return TSDB_CODE_SUCCESS;
×
3208
  }
3209

3210
  SSDataBlock* pResBlock = pReader->resBlockInfo.pResBlock;
5,134,908✔
3211

3212
  while (1) {
2,414,249✔
3213
    if (pReader->code != TSDB_CODE_SUCCESS) {
7,549,157!
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;
7,549,157✔
3220
    if (pStatus->pTableIter == NULL) {
7,549,157!
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;
7,549,157✔
3230
    }
3231

3232
    if (pReader->pIgnoreTables && taosHashGet(*pReader->pIgnoreTables, &pScanInfo->uid, sizeof(pScanInfo->uid))) {
7,549,157✔
3233
      // reset the index in last block when handing a new file
3234
      bool hasNexTable = moveToNextTable(pUidList, pStatus);
35,246✔
3235
      if (!hasNexTable) {
35,241✔
3236
        return TSDB_CODE_SUCCESS;
4,929✔
3237
      }
3238

3239
      continue;
30,312✔
3240
    }
3241

3242
    initSttBlockReader(pSttBlockReader, pScanInfo, pReader);
7,512,974✔
3243
    if (pReader->code != TSDB_CODE_SUCCESS) {
7,517,292!
3244
      return pReader->code;
×
3245
    }
3246
    
3247
    if (!hasDataInSttBlock(pScanInfo)) {
7,517,292✔
3248
      bool hasNexTable = moveToNextTable(pUidList, pStatus);
5,414,479✔
3249
      if (!hasNexTable) {
5,411,470✔
3250
        return TSDB_CODE_SUCCESS;
3,026,242✔
3251
      }
3252

3253
      continue;
2,385,228✔
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) {
2,102,857✔
3258
      code = buildCleanBlockFromSttFiles(pReader, pScanInfo);
25,780✔
3259
      return code;
25,763✔
3260
    }
3261

3262
    int64_t st = taosGetTimestampUs();
2,080,807✔
3263
    while (1) {
3264
      // no data in stt block and block, no need to proceed.
3265
      if (!hasDataInSttBlock(pScanInfo)) {
336,745,963✔
3266
        break;
2,018,886✔
3267
      }
3268

3269
      code = buildComposedDataBlockImpl(pReader, pScanInfo, &pReader->status.fileBlockData, pSttBlockReader);
333,364,319✔
3270
      if (code) {
334,726,919!
3271
        return code;
×
3272
      }
3273

3274
      if (pResBlock->info.rows >= pReader->resBlockInfo.capacity) {
334,726,919✔
3275
        break;
61,763✔
3276
      }
3277
    }
3278

3279
    double el = (taosGetTimestampUs() - st) / 1000.0;
2,080,169✔
3280
    updateComposedBlockInfo(pReader, el, pScanInfo);
2,080,169✔
3281

3282
    if (pResBlock->info.rows > 0) {
2,079,712!
3283
      tsdbDebug("%p uid:%" PRIu64 ", composed data block created, brange:%" PRIu64 "-%" PRIu64 " rows:%" PRId64
2,080,044✔
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;
2,080,205✔
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;
1,291✔
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) {
380,962✔
3300
  if ((!hasDataInSttBlock(pScanInfo)) || (pScanInfo->cleanSttBlocks == true)) {
380,962✔
3301
    return true;
371,523✔
3302
  } else {
3303
    int64_t keyInStt = pScanInfo->sttKeyInfo.nextProcKey.ts;
9,503✔
3304
    return (asc && pBlockInfo->lastKey < keyInStt) || (!asc && pBlockInfo->firstKey > keyInStt);
9,503✔
3305
  }
3306
}
3307

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

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

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

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

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

3336
  if (pScanInfo->sttKeyInfo.status == STT_FILE_READER_UNINIT) {
401,503✔
3337
    initSttBlockReader(pSttBlockReader, pScanInfo, pReader);
311,564✔
3338
    if (pReader->code != 0) {
311,722!
3339
      return pReader->code;
×
3340
    }
3341
  }
3342

3343
  TSDBKEY keyInBuf = getCurrentKeyInBuf(pScanInfo, pReader);
401,661✔
3344
  if (fileBlockShouldLoad(pReader, pBlockInfo, pScanInfo, keyInBuf)) {
401,469✔
3345
    code = doLoadFileBlockData(pReader, pBlockIter, &pStatus->fileBlockData, pScanInfo->uid);
20,412✔
3346
    if (code != TSDB_CODE_SUCCESS) {
20,413!
3347
      return code;
×
3348
    }
3349

3350
    // build composed data block
3351
    code = buildComposedDataBlock(pReader);
20,413✔
3352
  } else if (bufferDataInFileBlockGap(keyInBuf, pBlockInfo, pScanInfo, pReader->info.order)) {
381,170✔
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);
76✔
3356
    code = buildDataBlockFromBuf(pReader, pScanInfo, endKey);
76✔
3357
  } else {
3358
    if (notOverlapWithFiles(pBlockInfo, pScanInfo, asc)) {
381,128✔
3359
      int64_t keyInStt = pScanInfo->sttKeyInfo.nextProcKey.ts;
380,880✔
3360

3361
      if ((!hasDataInSttBlock(pScanInfo)) || (asc && pBlockInfo->lastKey < keyInStt) ||
380,880!
3362
          (!asc && pBlockInfo->firstKey > keyInStt)) {
4!
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);
380,843✔
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;
185✔
3376
      tBlockDataReset(pBData);
185✔
3377

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

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

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

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

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

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

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

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

3435
  while (1) {
427✔
3436
    if (pReader->code != TSDB_CODE_SUCCESS) {
3,230!
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;
3,230✔
3442
    if (pReader->pIgnoreTables &&
6,460!
3443
        taosHashGet(*pReader->pIgnoreTables, &(*pBlockScanInfo)->uid, sizeof((*pBlockScanInfo)->uid))) {
3,230✔
UNCOV
3444
      bool hasNexTable = moveToNextTableForPreFileSetMem(pStatus);
×
UNCOV
3445
      if (!hasNexTable) {
×
3446
        return TSDB_CODE_SUCCESS;
×
3447
      }
UNCOV
3448
      continue;
×
3449
    }
3450

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

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

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

3466
    if (pReader->resBlockInfo.pResBlock->info.rows > 0) {
3,230✔
3467
      return TSDB_CODE_SUCCESS;
1,590✔
3468
    }
3469

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

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

3482
  tsdbDebug("seq load data blocks from cache, %s", pReader->idStr);
2,928,987✔
3483

3484
  while (1) {
2,272,732✔
3485
    if (pReader->code != TSDB_CODE_SUCCESS) {
5,202,186!
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;
5,202,186✔
3491
    if (pBlockScanInfo == NULL || *pBlockScanInfo == NULL) {
5,202,186!
3492
      return TSDB_CODE_SUCCESS;
38✔
3493
    }
3494

3495
    if (pReader->pIgnoreTables &&
10,356,632✔
3496
        taosHashGet(*pReader->pIgnoreTables, &(*pBlockScanInfo)->uid, sizeof((*pBlockScanInfo)->uid))) {
5,155,285✔
3497
      bool hasNexTable = moveToNextTable(pUidList, pStatus);
33,982✔
3498
      if (!hasNexTable) {
33,982✔
3499
        return TSDB_CODE_SUCCESS;
2,182✔
3500
      }
3501
      continue;
31,800✔
3502
    }
3503

3504
    int32_t code = initMemDataIterator(*pBlockScanInfo, pReader);
5,167,365✔
3505
    if (code != TSDB_CODE_SUCCESS) {
5,168,448!
3506
      return code;
×
3507
    }
3508

3509
    code = initDelSkylineIterator(*pBlockScanInfo, pReader->info.order, &pReader->cost);
5,168,448✔
3510
    if (code != TSDB_CODE_SUCCESS) {
5,167,574!
3511
      return code;
×
3512
    }
3513

3514
    code = buildDataBlockFromBuf(pReader, *pBlockScanInfo, endKey);
5,167,574✔
3515
    if (code != TSDB_CODE_SUCCESS) {
5,167,160✔
3516
      return code;
4✔
3517
    }
3518

3519
    if (pReader->resBlockInfo.pResBlock->info.rows > 0) {
5,167,156✔
3520
      return TSDB_CODE_SUCCESS;
1,616,383✔
3521
    }
3522

3523
    // current table is exhausted, let's try next table
3524
    bool hasNexTable = moveToNextTable(pUidList, pStatus);
3,550,773✔
3525
    if (!hasNexTable) {
3,552,502✔
3526
      return TSDB_CODE_SUCCESS;
1,311,570✔
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) {
3,337,636✔
3533
  SFileDataBlockInfo* pBlockInfo = NULL;
3,337,636✔
3534
  SReaderStatus*      pStatus = &pReader->status;
3,337,636✔
3535
  SFileBlockDumpInfo* pDumpInfo = &pStatus->fBlockDumpInfo;
3,337,636✔
3536

3537
  int32_t code = getCurrentBlockInfo(pBlockIter, &pBlockInfo, pReader->idStr);
3,337,636✔
3538
  if (code == TSDB_CODE_SUCCESS) {
3,337,782✔
3539
    pDumpInfo->totalRows = pBlockInfo->numRow;
401,162✔
3540
    pDumpInfo->rowIndex = ASCENDING_TRAVERSE(pReader->info.order) ? 0 : pBlockInfo->numRow - 1;
401,162✔
3541
  } else {
3542
    pDumpInfo->totalRows = 0;
2,936,620✔
3543
    pDumpInfo->rowIndex = 0;
2,936,620✔
3544
  }
3545

3546
  pDumpInfo->allDumped = false;
3,337,782✔
3547
}
3,337,782✔
3548

3549
static int32_t initForFirstBlockInFile(STsdbReader* pReader, SDataBlockIter* pBlockIter) {
3,347,559✔
3550
  SBlockNumber num = {0};
3,347,559✔
3551
  SArray*      pTableList = taosArrayInit(40, POINTER_BYTES);
3,347,559✔
3552
  if (pTableList == NULL) {
3,351,538!
3553
    return terrno;
×
3554
  }
3555

3556
  int32_t code = moveToNextFile(pReader, &num, pTableList);
3,351,538✔
3557
  if (code != TSDB_CODE_SUCCESS) {
3,351,711!
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) {
3,352,034✔
3564
    pReader->status.loadFromFile = false;
298,646✔
3565
    taosArrayDestroy(pTableList);
298,646✔
3566
    return code;
298,651✔
3567
  }
3568

3569
  // initialize the block iterator for a new fileset
3570
  if (num.numOfBlocks > 0) {
3,053,388✔
3571
    code = initBlockIterator(pReader, pBlockIter, num.numOfBlocks, pTableList);
114,963✔
3572
  } else {  // no block data, only last block exists
3573
    tBlockDataReset(&pReader->status.fileBlockData);
2,938,425✔
3574
    code = resetDataBlockIterator(pBlockIter, pReader->info.order, shouldFreePkBuf(&pReader->suppInfo), pReader->idStr);
2,936,998✔
3575
    if (code) {
2,937,289!
3576
      return code;
×
3577
    }
3578

3579
    code = resetTableListIndex(&pReader->status, pReader->idStr);
2,937,289✔
3580
    if (code) {
2,937,220!
3581
      return code;
×
3582
    }
3583
  }
3584

3585
  if (code == TSDB_CODE_SUCCESS) { // set the correct start position according to the query time window
3,052,285✔
3586
    initBlockDumpInfo(pReader, pBlockIter);
3,051,390✔
3587
  }
3588

3589
  taosArrayDestroy(pTableList);
3,052,614✔
3590
  return code;
3,053,436✔
3591
}
3592

3593
static bool fileBlockPartiallyRead(SFileBlockDumpInfo* pDumpInfo, bool asc) {
408,755✔
3594
  return (!pDumpInfo->allDumped) &&
416,410✔
3595
         ((pDumpInfo->rowIndex > 0 && asc) || (pDumpInfo->rowIndex < (pDumpInfo->totalRows - 1) && (!asc)));
7,655✔
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) {
2,516,937✔
3604
  int32_t         code = TSDB_CODE_SUCCESS;
2,516,937✔
3605
  SSDataBlock*    pResBlock = pReader->resBlockInfo.pResBlock;
2,516,937✔
3606
  SDataBlockIter* pBlockIter = &pReader->status.blockIter;
2,516,937✔
3607

3608
  *pReturnType = TSDB_READ_RETURN;
2,516,937✔
3609

3610
  tsdbDebug("seq load data blocks from stt files %s", pReader->idStr);
2,516,937✔
3611

3612
  while (1) {
3613
    code = doLoadSttBlockSequentially(pReader);
5,138,878✔
3614
    if (code != TSDB_CODE_SUCCESS) {
5,133,610!
3615
      *pReturnType = TSDB_READ_RETURN;
×
3616
      return code;
×
3617
    }
3618

3619
    if (pResBlock->info.rows > 0) {
5,133,610✔
3620
      *pReturnType = TSDB_READ_RETURN;
2,105,168✔
3621
      return code;
2,105,168✔
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) {
3,028,442!
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);
3,028,442✔
3632

3633
    // error happens or all the data files are completely checked
3634
    if ((code != TSDB_CODE_SUCCESS) || (pReader->status.loadFromFile == false)) {
3,031,842!
3635
      *pReturnType = TSDB_READ_RETURN;
297,453✔
3636
      return code;
297,453✔
3637
    }
3638

3639
    if (pReader->status.bProcMemPreFileset) {
2,734,389✔
3640
      code = buildFromPreFilesetBuffer(pReader);
1,209✔
3641
      if (code != TSDB_CODE_SUCCESS) {
1,209!
3642
        return code;
×
3643
      }
3644
      if (pResBlock->info.rows > 0) {
1,209✔
3645
        pReader->status.processingMemPreFileSet = true;
1,185✔
3646
        *pReturnType = TSDB_READ_RETURN;
1,185✔
3647
        return code;
1,185✔
3648
      }
3649
    }
3650

3651
    if (pBlockIter->numOfBlocks > 0) {  // there are data blocks existed.
2,733,204✔
3652
      *pReturnType = TSDB_READ_CONTINUE;
111,706✔
3653
      return code;
111,706✔
3654
    } else {  // all blocks in data file are checked, let's check the data in stt-files
3655
      code = resetTableListIndex(&pReader->status, pReader->idStr);
2,621,498✔
3656
      if (code) {
2,621,938!
3657
        return code;
×
3658
      }
3659
    }
3660
  }
3661
}
3662

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

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

3673
  if (pBlockIter->numOfBlocks == 0) {
2,809,476✔
3674
    // let's try to extract data from stt files.
3675
    ERetrieveType type = 0;
2,402,077✔
3676
    code = doReadDataFromSttFiles(pReader, &type);
2,402,077✔
3677
    if (code != 0 || type == TSDB_READ_RETURN) {
2,399,971!
3678
      return code;
2,399,971✔
3679
    }
3680

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

3687
  while (1) {
3688
    if (fileBlockPartiallyRead(pDumpInfo, asc)) {  // file data block is partially loaded
408,603✔
3689
      code = buildComposedDataBlock(pReader);
3,890✔
3690
    } else {
3691
      // current block are exhausted, try the next file block
3692
      if (pDumpInfo->allDumped) {
404,862✔
3693
        // try next data block in current file
3694
        bool hasNext = blockIteratorNext(&pReader->status.blockIter, pReader->idStr);
401,133✔
3695
        if (hasNext) {  // check for the next block in the block accessed order list
401,137✔
3696
          initBlockDumpInfo(pReader, pBlockIter);
286,264✔
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) {
114,873✔
3701
            tBlockDataClear(pBlockData);
114,835✔
3702
          }
3703

3704
          tBlockDataReset(pBlockData);
114,866✔
3705
          code = resetDataBlockIterator(pBlockIter, pReader->info.order, shouldFreePkBuf(&pReader->suppInfo), id);
115,078✔
3706
          if (code != TSDB_CODE_SUCCESS) {
114,999!
3707
            return code;
3,245✔
3708
          }
3709

3710
          code = resetTableListIndex(&pReader->status, id);
114,999✔
3711
          if (code != TSDB_CODE_SUCCESS) {
115,046!
3712
            return code;
×
3713
          }
3714

3715
          ERetrieveType type = 0;
115,046✔
3716
          code = doReadDataFromSttFiles(pReader, &type);
115,046✔
3717
          if (code != 0 || type == TSDB_READ_RETURN) {
114,935!
3718
            return code;
3,245✔
3719
          }
3720
        }
3721
      }
3722

3723
      code = doBuildDataBlock(pReader);
401,651✔
3724
    }
3725

3726
    if (code != TSDB_CODE_SUCCESS || pResBlock->info.rows > 0) {
405,333✔
3727
      return code;
404,129✔
3728
    }
3729
  }
3730
}
3731

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

3738
  *pTsdb = NULL;
1,437,838✔
3739
  if (VND_IS_RSMA(pVnode) && !pCond->skipRollup) {
1,437,838✔
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);
1,437,800✔
3782
}
3783

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

3787
  int64_t endVer = 0;
1,438,153✔
3788
  if (pCond->endVersion == -1) {
1,438,153✔
3789
    // user not specified end version, set current maximum version of vnode as the endVersion
3790
    endVer = pVnode->state.applied;
1,431,147✔
3791
  } else {
3792
    endVer = (pCond->endVersion > pVnode->state.applied) ? pVnode->state.applied : pCond->endVersion;
7,006✔
3793
  }
3794

3795
  return (SVersionRange){.minVer = startVer, .maxVer = endVer};
1,438,153✔
3796
}
3797

3798
static int32_t reverseSearchStartPos(const SArray* pDelList, int32_t index, int64_t key, bool asc) {
4,409✔
3799
  size_t  num = taosArrayGetSize(pDelList);
4,409✔
3800
  int32_t start = index;
4,409✔
3801

3802
  if (asc) {
4,409✔
3803
    if (start >= num - 1) {
2,658✔
3804
      start = num - 1;
119✔
3805
    }
3806

3807
    TSDBKEY* p = taosArrayGet(pDelList, start);
2,658✔
3808
    if (p == NULL) {
2,658!
3809
      return TSDB_CODE_INVALID_PARA;
×
3810
    }
3811

3812
    while (p->ts >= key && start > 0) {
2,786✔
3813
      start -= 1;
128✔
3814
    }
3815
  } else {
3816
    if (index <= 0) {
1,751!
3817
      start = 0;
×
3818
    }
3819

3820
    TSDBKEY* p = taosArrayGet(pDelList, start);
1,751✔
3821
    if (p == NULL) {
1,751!
3822
      return TSDB_CODE_INVALID_PARA;
×
3823
    }
3824

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

3830
  return start;
4,409✔
3831
}
3832

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

3839
  size_t  num = taosArrayGetSize(pDelList);
247,080,052✔
3840
  bool    asc = ASCENDING_TRAVERSE(order);
246,823,660✔
3841
  int32_t step = asc ? 1 : -1;
246,823,660✔
3842

3843
  if (hasPk) {  // handle the case where duplicated timestamps existed.
246,823,660✔
3844
    *index = reverseSearchStartPos(pDelList, *index, key, asc);
4,409✔
3845
  }
3846

3847
  if (asc) {
246,823,660✔
3848
    if (*index >= num - 1) {
228,866,613✔
3849
      TSDBKEY* last = taosArrayGetLast(pDelList);
44,358,585✔
3850
      if (last == NULL) {
44,335,773!
3851
        return false;
×
3852
      }
3853

3854
      if (key > last->ts) {
44,335,773✔
3855
        return false;
44,333,071✔
3856
      } else if (key == last->ts) {
2,702!
3857
        TSDBKEY* prev = taosArrayGet(pDelList, num - 2);
4,544✔
3858
        if (prev == NULL) {
4,544!
3859
          return false;
×
3860
        }
3861

3862
        return (prev->version >= ver && prev->version <= pVerRange->maxVer && prev->version >= pVerRange->minVer);
4,544!
3863
      }
3864
    } else {
3865
      TSDBKEY* pCurrent = taosArrayGet(pDelList, *index);
184,508,028✔
3866
      TSDBKEY* pNext = taosArrayGet(pDelList, (*index) + 1);
185,254,102✔
3867
      if (pCurrent == NULL || pNext == NULL) {
184,053,546!
3868
        return false;
×
3869
      }
3870

3871
      if (key < pCurrent->ts) {
184,053,546✔
3872
        return false;
4,226,647✔
3873
      }
3874

3875
      if (pCurrent->ts <= key && pNext->ts >= key && pCurrent->version >= ver &&
179,826,899!
3876
          pVerRange->maxVer >= pCurrent->version) {
5,212,604!
3877
        return true;
5,212,942✔
3878
      }
3879

3880
      while (pNext->ts <= key && (*index) < num - 1) {
174,988,160✔
3881
        (*index) += 1;
524,999✔
3882

3883
        if ((*index) < num - 1) {
524,999✔
3884
          pCurrent = taosArrayGet(pDelList, *index);
509,650✔
3885
          pNext = taosArrayGet(pDelList, (*index) + 1);
509,650✔
3886
          if (pCurrent == NULL || pNext == NULL) {
509,648!
3887
            return false;
×
3888
          }
3889

3890
          // it is not a consecutive deletion range, ignore it
3891
          if (pCurrent->version == 0 && pNext->version > 0) {
509,648!
3892
            continue;
181,725✔
3893
          }
3894

3895
          if (pCurrent->ts <= key && pNext->ts >= key && pCurrent->version >= ver &&
327,923!
3896
              pVerRange->maxVer >= pCurrent->version) {
150,794!
3897
            return true;
150,794✔
3898
          }
3899
        }
3900
      }
3901

3902
      return false;
174,463,161✔
3903
    }
3904
  } else {
3905
    if (*index <= 0) {
17,957,047!
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);
17,957,047✔
3920
      TSDBKEY* pPrev = taosArrayGet(pDelList, (*index) - 1);
17,970,125✔
3921
      if (pCurrent == NULL || pPrev == NULL) {
17,940,214!
3922
        return false;
×
3923
      }
3924

3925
      if (key > pCurrent->ts) {
17,940,214✔
3926
        return false;
4,640,643✔
3927
      }
3928

3929
      if (pPrev->ts <= key && pCurrent->ts >= key && pPrev->version >= ver) {
13,299,571!
3930
        return true;
176,735✔
3931
      }
3932

3933
      while (pPrev->ts >= key && (*index) > 1) {
13,193,005✔
3934
        (*index) += step;
169,718✔
3935

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

3943
          // it is not a consecutive deletion range, ignore it
3944
          if (pCurrent->version > 0 && pPrev->version == 0) {
169,718✔
3945
            continue;
20,965✔
3946
          }
3947

3948
          if (pPrev->ts <= key && pCurrent->ts >= key && pPrev->version >= ver) {
148,753!
3949
            return true;
99,549✔
3950
          }
3951
        }
3952
      }
3953

3954
      return false;
13,023,287✔
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,004,758,201✔
3963

3964
  if (!pIter->hasVal) {
731,221,823!
3965
    return;
627,792,259✔
3966
  }
3967

3968
  int32_t  order = pReader->info.order;
1,376,965,942✔
3969
  TSDBROW* pRow = tsdbTbDataIterGet(pIter->iter);
1,376,965,942!
3970

3971
  TSDBKEY key;
3972
  TSDBROW_INIT_KEY(pRow, key);
1,376,965,942!
3973
  if (outOfTimeWindow(key.ts, &pReader->info.window)) {
1,376,965,942!
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) {
1,394,120,999!
3980
    if (pDelList == NULL || TARRAY_SIZE(pDelList) == 0) {
1,399,748,766!
3981
      *pRes = pRow;
1,207,954,226✔
3982
      return;
1,207,954,226✔
3983
    } else {
3984
      bool dropped = hasBeenDropped(pDelList, &pIter->index, key.ts, key.version, order, &pReader->info.verRange,
191,794,540✔
3985
                                    pReader->suppInfo.numOfPks > 0);
191,794,540✔
3986
      if (!dropped) {
190,924,131!
3987
        *pRes = pRow;
190,871,492✔
3988
        return;
190,871,492✔
3989
      }
3990
    }
3991
  }
3992

3993
  while (1) {
3994
    pIter->hasVal = tsdbTbDataIterNext(pIter->iter);
×
3995
    if (!pIter->hasVal) {
1,209,569!
3996
      return;
5,482✔
3997
    }
3998

3999
    pRow = tsdbTbDataIterGet(pIter->iter);
1,204,087!
4000

4001
    TSDBROW_INIT_KEY(pRow, key);
1,204,087!
4002
    if (outOfTimeWindow(key.ts, &pReader->info.window)) {
1,204,087!
4003
      pIter->hasVal = false;
2,473✔
4004
      return;
2,473✔
4005
    }
4006

4007
    if (key.version <= pReader->info.verRange.maxVer && key.version >= pReader->info.verRange.minVer) {
1,201,614!
4008
      if (pDelList == NULL || TARRAY_SIZE(pDelList) == 0) {
1,036,605!
4009
        *pRes = pRow;
607✔
4010
        return;
607✔
4011
      } else {
4012
        bool dropped = hasBeenDropped(pDelList, &pIter->index, key.ts, key.version, order, &pReader->info.verRange,
1,035,998✔
4013
                                      pReader->suppInfo.numOfPks > 0);
1,035,998✔
4014
        if (!dropped) {
1,036,037!
4015
          *pRes = pRow;
72,309✔
4016
          return;
72,309✔
4017
        }
4018
      }
4019
    }
4020
  }
4021
}
4022

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

4027
  while (1) {
1,760,023✔
4028
    pIter->hasVal = tsdbTbDataIterNext(pIter->iter);
13,307,231✔
4029
    if (!pIter->hasVal) {
13,298,952✔
4030
      break;
76,743✔
4031
    }
4032

4033
    // data exists but not valid
4034
    TSDBROW* pRow = NULL;
13,222,209!
4035
    getValidMemRow(pIter, pDelList, pReader, &pRow);
4036
    if (pRow == NULL) {
13,212,976✔
4037
      break;
1,304✔
4038
    }
4039

4040
    // ts is not identical, quit
4041
    if (TSDBROW_TS(pRow) != pCurKey->ts) {
13,211,672✔
4042
      break;
11,454,334✔
4043
    }
4044

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

4053
    STSchema* pTSchema = NULL;
1,756,906✔
4054
    if (pRow->type == TSDBROW_ROW_FMT) {
1,756,906!
4055
      pTSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(pRow), pReader, uid);
1,759,450!
4056
      if (pTSchema == NULL) {
1,759,460!
4057
        return terrno;
×
4058
      }
4059
    }
4060

4061
    code = tsdbRowMergerAdd(pMerger, pRow, pTSchema);
1,756,916✔
4062
    if (code != TSDB_CODE_SUCCESS) {
1,760,023!
4063
      return code;
×
4064
    }
4065
  }
4066

4067
  return code;
11,532,813✔
4068
}
4069

4070
static int32_t doMergeRowsInFileBlockImpl(SBlockData* pBlockData, int32_t* rowIndex, SRowKey* pKey, SRowMerger* pMerger,
23,074,588✔
4071
                                          SVersionRange* pVerRange, int32_t step) {
4072
  int32_t code = 0;
23,074,588✔
4073
  while ((*rowIndex) < pBlockData->nRow && (*rowIndex) >= 0) {
23,099,939!
4074
    SRowKey cur;
4075
    tColRowGetKey(pBlockData, (*rowIndex), &cur);
23,083,883✔
4076
    if (pkCompEx(&cur, pKey) != 0) {
23,128,985✔
4077
      break;
23,103,634✔
4078
    }
4079

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

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

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

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

4136
  pDumpInfo->rowIndex += step;
23,103,579✔
4137
  if ((pDumpInfo->rowIndex <= pBlockData->nRow - 1 && asc) || (pDumpInfo->rowIndex >= 0 && !asc)) {
23,103,579!
4138
    code = doMergeRowsInFileBlockImpl(pBlockData, &pDumpInfo->rowIndex, pKey, pMerger, pRange, step);
23,094,413✔
4139
    if (code != TSDB_CODE_SUCCESS) {
23,110,036!
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)) {
23,119,202!
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) {
14,813!
4152
        return code;
×
4153
      }
4154

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

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

4167
  return code;
23,169,274✔
4168
}
4169

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

4175
  while (1) {
1,321,059✔
4176
    code = nextRowFromSttBlocks(pSttBlockReader, pScanInfo, pkSrcSlot, pVerRange);
60,285,662✔
4177
    if (code || (!hasDataInSttBlock(pScanInfo))) {
59,664,182!
4178
      return code;
70,450✔
4179
    }
4180

4181
    SRowKey* pNextKey = getCurrentKeyInSttBlock(pSttBlockReader);
59,544,160!
4182

4183
    int32_t ret = pkCompEx(pRowKey, pNextKey);
59,561,142✔
4184
    if (ret == 0) {
59,561,142✔
4185
      TSDBROW* pRow1 = tMergeTreeGetRow(&pSttBlockReader->mergeTree);
1,327,204✔
4186
      code = tsdbRowMergerAdd(pMerger, pRow1, NULL);
1,327,204✔
4187
      if (code != TSDB_CODE_SUCCESS) {
1,321,059!
4188
        break;
×
4189
      }
4190
    } else {
4191
      tsdbTrace("uid:%" PRIu64 " last del index:%d, del range:%d, lastKeyInStt:%" PRId64 ", %s", pScanInfo->uid,
58,233,938!
4192
                pScanInfo->sttBlockDelIndex, (int32_t)taosArrayGetSize(pScanInfo->delSkyline),
4193
                pScanInfo->sttKeyInfo.nextProcKey.ts, idStr);
4194
      break;
58,235,887✔
4195
    }
4196
  }
4197

4198
  return code;
58,235,887✔
4199
}
4200

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

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

4210
    if (!pIter->hasVal) {
645,059,405✔
4211
      *pResRow = *pRow;
1,435,599✔
4212
      *freeTSRow = false;
1,435,599✔
4213
      return TSDB_CODE_SUCCESS;
1,435,599✔
4214
    } else {  // has next point in mem/imem
4215
      getValidMemRow(pIter, pDelList, pReader, &pNextRow);
4216
      if (pNextRow == NULL) {
644,172,056✔
4217
        *pResRow = current;
66,725✔
4218
        *freeTSRow = false;
66,725✔
4219
        return TSDB_CODE_SUCCESS;
66,725✔
4220
      }
4221

4222
      if (TSDBROW_TS(&current) != TSDBROW_TS(pNextRow)) {
644,105,331!
4223
        *pResRow = current;
644,301,698✔
4224
        *freeTSRow = false;
644,301,698✔
4225
        return TSDB_CODE_SUCCESS;
644,301,698✔
4226
      }
4227

UNCOV
4228
      if (pKey->numOfPKs > 0) {
×
4229
        SRowKey nextRowKey = {0};
3,091,851✔
4230
        tRowGetKeyEx(pNextRow, &nextRowKey);
3,091,851!
4231
        if (pkCompEx(pKey, &nextRowKey) != 0) {
3,092,613✔
4232
          *pResRow = current;
3,092,101✔
4233
          *freeTSRow = false;
3,092,101✔
4234
          return TSDB_CODE_SUCCESS;
3,092,101✔
4235
        }
4236
      }
4237
    }
4238
  }
4239

4240
  terrno = 0;
×
4241
  int32_t code = 0;
5,815,957✔
4242

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

4252
  code = tsdbRowMergerAdd(pMerger, &current, pTSchema);
5,815,763✔
4253
  if (code != TSDB_CODE_SUCCESS) {
5,819,979!
4254
    return code;
×
4255
  }
4256

4257
  STSchema* pTSchema1 = NULL;
5,819,979✔
4258
  if (pNextRow->type == TSDBROW_ROW_FMT) {  // get the correct schema for row-wise data in memory
5,819,979!
4259
    pTSchema1 = doGetSchemaForTSRow(pNextRow->pTSRow->sver, pReader, uid);
5,820,046!
4260
    if (pTSchema1 == NULL) {
5,819,800!
4261
      return terrno;
×
4262
    }
4263
  }
4264

4265
  code = tsdbRowMergerAdd(pMerger, pNextRow, pTSchema1);
5,819,733✔
4266
  if (code != TSDB_CODE_SUCCESS) {
5,819,870!
4267
    return code;
×
4268
  }
4269

4270
  code = doMergeRowsInBuf(pIter, uid, pKey, pDelList, pReader);
5,819,870✔
4271
  if (code != TSDB_CODE_SUCCESS) {
5,809,821!
4272
    return code;
×
4273
  }
4274

4275
  code = tsdbRowMergerGetRow(pMerger, &pResRow->pTSRow);
5,809,821✔
4276
  if (code != TSDB_CODE_SUCCESS) {
5,819,598!
4277
    return code;
×
4278
  }
4279

4280
  pResRow->type = TSDBROW_ROW_FMT;
5,819,598✔
4281
  tsdbRowMergerClear(pMerger);
5,819,598✔
4282
  *freeTSRow = true;
5,814,265✔
4283

4284
  return TSDB_CODE_SUCCESS;
5,814,265✔
4285
}
4286

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

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

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

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

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

4319
    code = tsdbRowMergerAdd(pMerger, pRow, pSchema);
85,788✔
4320
    if (code != TSDB_CODE_SUCCESS) {
85,789!
4321
      return code;
×
4322
    }
4323

4324
    code = doMergeRowsInBuf(&pBlockScanInfo->iter, pBlockScanInfo->uid, pRowKey, pBlockScanInfo->delSkyline, pReader);
85,789✔
4325
    if (code != TSDB_CODE_SUCCESS) {
85,789!
4326
      return code;
×
4327
    }
4328
  } else {
UNCOV
4329
    code = tsdbRowMergerAdd(pMerger, pRow, pSchema);
×
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);
85,789✔
4351

4352
  code = tsdbRowMergerGetRow(pMerger, pTSRow);
85,789✔
4353
  tsdbRowMergerClear(pMerger);
85,790✔
4354
  return code;
85,789✔
4355
}
4356

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

4362
  getValidMemRow(&pBlockScanInfo->iter, pBlockScanInfo->delSkyline, pReader, &pRow);
627,966,974✔
4363
  getValidMemRow(&pBlockScanInfo->iiter, pBlockScanInfo->delSkyline, pReader, &piRow);
632,347,195✔
4364

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

4371
  // todo refactor
4372
  bool asc = ASCENDING_TRAVERSE(pReader->info.order);
632,347,050✔
4373
  if (piter->hasVal) {
632,347,050✔
4374
    tRowGetKeyEx(pRow, &rowKey);
629,524,158!
4375
    if ((rowKey.ts >= endKey && asc) || (rowKey.ts <= endKey && !asc)) {
637,354,021!
4376
      pRow = NULL;
51✔
4377
    }
4378
  }
4379

4380
  if (piiter->hasVal) {
640,176,913✔
4381
    tRowGetKeyEx(piRow, &irowKey);
36,808,151!
4382
    if ((irowKey.ts >= endKey && asc) || (irowKey.ts <= endKey && !asc)) {
58,491,617!
4383
      piRow = NULL;
1✔
4384
    }
4385
  }
4386

4387
  if (pRow != NULL && piRow != NULL) {
661,860,379✔
4388
    int32_t code = TSDB_CODE_SUCCESS;
8,662,013✔
4389
    if (rowKey.numOfPKs == 0) {
8,662,013✔
4390
      if ((rowKey.ts > irowKey.ts && asc) || (rowKey.ts < irowKey.ts && (!asc))) {  // ik.ts < k.ts
8,661,648✔
4391
        code = doMergeMemTableMultiRows(piRow, &irowKey, uid, piiter, pDelList, pResRow, pReader, freeTSRow);
8,568,324✔
4392
      } else if ((rowKey.ts < irowKey.ts && asc) || (rowKey.ts > irowKey.ts && (!asc))) {
93,324!
4393
        code = doMergeMemTableMultiRows(pRow, &rowKey, uid, piter, pDelList, pResRow, pReader, freeTSRow);
11,147✔
4394
      } else {  // ik.ts == k.ts
4395
        *freeTSRow = true;
82,177✔
4396
        pResRow->type = TSDBROW_ROW_FMT;
82,177✔
4397
        code = doMergeMemIMemRows(pRow, &rowKey, piRow, &irowKey, pBlockScanInfo, pReader, &pResRow->pTSRow);
82,177✔
4398
        if (code != TSDB_CODE_SUCCESS) {
85,789!
4399
          return code;
×
4400
        }
4401
      }
4402
    } else {
UNCOV
4403
      int32_t ret = pkCompEx(&rowKey, &irowKey);
×
UNCOV
4404
      if (ret != 0) {
×
UNCOV
4405
        if ((ret > 0 && asc) || (ret < 0 && (!asc))) {  // ik.ts < k.ts
×
UNCOV
4406
          code = doMergeMemTableMultiRows(piRow, &irowKey, uid, piiter, pDelList, pResRow, pReader, freeTSRow);
×
UNCOV
4407
        } else if ((ret < 0 && asc) || (ret > 0 && (!asc))) {
×
UNCOV
4408
          code = doMergeMemTableMultiRows(pRow, &rowKey, uid, piter, pDelList, pResRow, pReader, freeTSRow);
×
4409
        }
4410
      } else {  // ik.ts == k.ts
UNCOV
4411
        *freeTSRow = true;
×
UNCOV
4412
        pResRow->type = TSDBROW_ROW_FMT;
×
UNCOV
4413
        code = doMergeMemIMemRows(pRow, &rowKey, piRow, &irowKey, pBlockScanInfo, pReader, &pResRow->pTSRow);
×
4414
        if (code != TSDB_CODE_SUCCESS) {
×
4415
          return code;
×
4416
        }
4417
      }
4418
    }
4419

4420
    return code;
8,636,318✔
4421
  }
4422

4423
  if (piter->hasVal && pRow != NULL) {
653,198,366!
4424
    return doMergeMemTableMultiRows(pRow, &rowKey, uid, piter, pDelList, pResRow, pReader, freeTSRow);
624,654,679✔
4425
  }
4426

4427
  if (piiter->hasVal && piRow != NULL) {
28,543,687!
4428
    return doMergeMemTableMultiRows(piRow, &irowKey, uid, piiter, pDelList, pResRow, pReader, freeTSRow);
28,531,779✔
4429
  }
4430

4431
  return TSDB_CODE_SUCCESS;
11,908✔
4432
}
4433

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

4439
  SBlockLoadSuppInfo* pSupInfo = &pReader->suppInfo;
724,385,383✔
4440
  STSchema*           pSchema = doGetSchemaForTSRow(pTSRow->sver, pReader, uid);
724,385,383!
4441
  if (pSchema == NULL) {
725,378,987!
4442
    return terrno;
×
4443
  }
4444

4445
  SColVal colVal = {0};
725,378,987✔
4446
  int32_t i = 0, j = 0;
725,378,987✔
4447

4448
  if (pSupInfo->colId[i] == PRIMARYKEY_TIMESTAMP_COL_ID) {
725,378,987!
4449
    SColumnInfoData* pColData = taosArrayGet(pBlock->pDataBlock, pSupInfo->slotId[i]);
729,391,685✔
4450
    if (pColData == NULL) {
719,154,650!
4451
      return TSDB_CODE_INVALID_PARA;
×
4452
    }
4453

4454
    ((int64_t*)pColData->pData)[outputRowIndex] = pTSRow->ts;
719,154,650✔
4455
    i += 1;
719,154,650✔
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]);
861,349,075✔
4463
      if (pColInfoData == NULL) {
855,164,904!
4464
        return TSDB_CODE_INVALID_PARA;
×
4465
      }
4466

4467
      code = tRowGet(pTSRow, pSchema, j, &colVal);
855,164,904✔
4468
      if (code) {
863,416,223!
4469
        return code;
×
4470
      }
4471

4472
      code = doCopyColVal(pColInfoData, outputRowIndex, i, &colVal, pSupInfo);
863,416,223✔
4473
      if (code) {
871,945,005✔
4474
        return code;
4✔
4475
      }
4476
      i += 1;
871,945,001✔
4477
      j += 1;
871,945,001✔
4478
    } else if (colId < pSchema->columns[j].colId) {
1,499,358,563!
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) {
1,499,358,563!
4487
      j += 1;
1,500,165,518✔
4488
    }
4489
  }
4490

4491
  // set null value since current column does not exist in the "pSchema"
4492
  while (i < pSupInfo->numOfCols) {
725,778,999✔
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;
725,737,878✔
4503
  pBlock->info.rows += 1;
725,737,878✔
4504
  return TSDB_CODE_SUCCESS;
725,737,878✔
4505
}
4506

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

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

4517
  SColVal cv = {0};
295,842,854✔
4518
  int32_t numOfInputCols = pBlockData->nColData;
295,842,854✔
4519
  int32_t numOfOutputCols = pSupInfo->numOfCols;
295,842,854✔
4520

4521
  while (i < numOfOutputCols && j < numOfInputCols) {
592,733,357✔
4522
    SColData* pData = tBlockDataGetColDataByIdx(pBlockData, j);
282,587,602✔
4523
    if (pData->cid < pSupInfo->colId[i]) {
282,587,602✔
4524
      j += 1;
150✔
4525
      continue;
150✔
4526
    }
4527

4528
    SColumnInfoData* pCol = TARRAY_GET_ELEM(pResBlock->pDataBlock, pSupInfo->slotId[i]);
282,587,452✔
4529
    if (pData->cid == pSupInfo->colId[i]) {
282,587,452!
4530
      tColDataGetValue(pData, rowIndex, &cv);
282,957,903✔
4531
      code = doCopyColVal(pCol, outputRowIndex, i, &cv, pSupInfo);
301,611,775✔
4532
      if (code) {
297,260,804!
4533
        return code;
×
4534
      }
4535
      j += 1;
297,260,804✔
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;
296,890,353✔
4542
  }
4543

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

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

4554
  pResBlock->info.dataLoad = 1;
310,145,755✔
4555
  pResBlock->info.rows += 1;
310,145,755✔
4556
  return TSDB_CODE_SUCCESS;
310,145,755✔
4557
}
4558

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

4564
  do {
627,897,382✔
4565
    TSDBROW row = {.type = -1};
629,526,577✔
4566
    bool    freeTSRow = false;
629,526,577✔
4567
    code = tsdbGetNextRowInMem(pBlockScanInfo, pReader, &row, endKey, &freeTSRow);
629,526,577✔
4568
    if (code != TSDB_CODE_SUCCESS) {
644,783,894!
4569
      return code;
4✔
4570
    }
4571

4572
    if (row.type == -1) {
644,783,894✔
4573
      break;
11,908✔
4574
    }
4575

4576
    if (row.type == TSDBROW_ROW_FMT) {
644,771,986✔
4577
      code = doAppendRowFromTSRow(pBlock, pReader, row.pTSRow, pBlockScanInfo);
641,708,180✔
4578
      if (code == TSDB_CODE_SUCCESS) {
628,980,492!
4579
        pBlockScanInfo->lastProcKey.ts = row.pTSRow->ts;
630,643,836✔
4580
        pBlockScanInfo->lastProcKey.numOfPKs = row.pTSRow->numOfPKs;
630,643,836✔
4581
        if (row.pTSRow->numOfPKs > 0) {
630,643,836✔
4582
          tRowGetPrimaryKeyDeepCopy(row.pTSRow, &pBlockScanInfo->lastProcKey);
5,135,804✔
4583
        }
4584
      }
4585

4586
      if (freeTSRow) {
628,996,227✔
4587
        taosMemoryFree(row.pTSRow);
5,899,520✔
4588
      }
4589

4590
      if (code) {
629,011,796✔
4591
        return code;
4✔
4592
      }
4593
    } else {
4594
      code = doAppendRowFromFileBlock(pBlock, pReader, row.pBlockData, row.iRow);
3,063,806✔
4595
      if (code) {
354!
4596
        return code;
×
4597
      }
4598

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

4602
    // no data in buffer, return immediately
4603
    if (!(pBlockScanInfo->iter.hasVal || pBlockScanInfo->iiter.hasVal)) {
629,514,574✔
4604
      break;
1,507,566✔
4605
    }
4606

4607
    if (pBlock->info.rows >= capacity) {
628,007,008✔
4608
      break;
109,626✔
4609
    }
4610
  } while (1);
4611

4612
  return code;
1,629,100✔
4613
}
4614

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

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

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

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

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

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

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

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

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

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

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

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

4682
  if (pReader->bFilesetDelimited) {
1,348,690✔
4683
    getMemTableTimeRange(pReader, &pReader->status.memTableMaxKey, &pReader->status.memTableMinKey);
232,991✔
4684
    pReader->status.bProcMemFirstFileset = true;
232,989✔
4685
  }
4686

4687
  code = initFilesetIterator(&pStatus->fileIter, pReader->pReadSnap->pfSetArray, pReader);
1,348,688✔
4688
  if (code != TSDB_CODE_SUCCESS) {
1,348,972!
4689
    return code;
×
4690
  }
4691

4692
  code = resetDataBlockIterator(&pStatus->blockIter, pReader->info.order, shouldFreePkBuf(&pReader->suppInfo),
1,348,792✔
4693
                                pReader->idStr);
1,348,972✔
4694
  if (code != TSDB_CODE_SUCCESS) {
1,348,895!
4695
    return code;
×
4696
  }
4697

4698
  if (pStatus->fileIter.numOfFiles == 0) {
1,348,895✔
4699
    pStatus->loadFromFile = false;
1,047,003✔
4700
  } else {
4701
    code = initForFirstBlockInFile(pReader, pBlockIter);
301,892✔
4702
  }
4703

4704
  if (!pStatus->loadFromFile) {
1,348,874✔
4705
    code = resetTableListIndex(pStatus, pReader->idStr);
1,048,151✔
4706
  }
4707

4708
  return code;
1,348,892✔
4709
}
4710

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

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

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

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

4749
  int32_t capacity = pConf->tsdbCfg.maxRows;
1,432,649✔
4750
  if (pResBlock != NULL) {
1,432,649✔
4751
    code = blockDataEnsureCapacity(pResBlock, capacity);
1,432,354✔
4752
    TSDB_CHECK_CODE(code, lino, _err);
1,432,564!
4753
  }
4754

4755
  code = tsdbReaderCreate(pVnode, pCond, ppReader, capacity, pResBlock, idstr);
1,432,859✔
4756
  TSDB_CHECK_CODE(code, lino, _err);
1,433,934!
4757

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

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

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

4791
    code = tsdbReaderCreate(pVnode, pCond, (void**)&((STsdbReader*)pReader)->innerReader[1], 1, pResBlock, idstr);
1,804✔
4792
    TSDB_CHECK_CODE(code, lino, _err);
1,804!
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) {
1,386,436✔
4799
    code = metaGetTbTSchemaMaybeNull(pReader->pTsdb->pVnode->pMeta, pReader->info.suid, -1, 1, &pReader->info.pSchema);
1,160,562✔
4800
    TSDB_CHECK_CODE(code, lino, _err);
1,162,674!
4801
    if (pReader->info.pSchema == NULL) {
1,162,674!
4802
      tsdbWarn("failed to get table schema, suid:%" PRIu64 ", ver:-1, %s", pReader->info.suid, pReader->idStr);
×
4803
    }
4804
  } else if (numOfTables > 0) {
225,874✔
4805
    STableKeyInfo* pKey = pTableList;
225,515✔
4806
    code = metaGetTbTSchemaMaybeNull(pReader->pTsdb->pVnode->pMeta, pKey->uid, -1, 1, &pReader->info.pSchema);
225,515✔
4807
    TSDB_CHECK_CODE(code, lino, _err);
225,623!
4808
    if (pReader->info.pSchema == NULL) {
225,623!
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) {
1,388,656✔
4814
    code = tsdbRowMergerInit(&pReader->status.merger, pReader->info.pSchema);
1,387,218✔
4815
    TSDB_CHECK_CODE(code, lino, _err);
1,388,335!
4816
  }
4817

4818
  pReader->pSchemaMap = tSimpleHashInit(8, taosFastHash);
1,389,773✔
4819
  if (pReader->pSchemaMap == NULL) {
1,388,665!
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);
1,388,665✔
4825
  if (pReader->info.pSchema != NULL) {
1,388,328✔
4826
    code = updateBlockSMAInfo(pReader->info.pSchema, &pReader->suppInfo);
1,388,123✔
4827
    TSDB_CHECK_CODE(code, lino, _err);
1,388,677✔
4828
  }
4829

4830
  STsdbReader* p = (pReader->innerReader[0] != NULL) ? pReader->innerReader[0] : pReader;
1,388,866✔
4831

4832
  code = createDataBlockScanInfo(p, &pReader->blockInfoBuf, pTableList, &pReader->status.uidList, numOfTables, &pReader->status.pTableMap);
1,388,866✔
4833
  TSDB_CHECK_CODE(code, lino, _err);
1,389,013!
4834

4835
  pReader->status.pLDataIterArray = taosArrayInit(4, POINTER_BYTES);
1,389,013✔
4836
  TSDB_CHECK_NULL(pReader->status.pLDataIterArray, code, lino, _err, terrno);
1,389,143✔
4837

4838
  pReader->flag = READER_STATUS_SUSPEND;
1,388,977✔
4839
  pReader->info.execMode = pCond->notLoadData ? READER_EXEC_ROWS : READER_EXEC_DATA;
1,388,977✔
4840

4841
  pReader->pIgnoreTables = pIgnoreTables;
1,388,977✔
4842
  tsdbDebug("%p total numOfTable:%d, window:%" PRId64 " - %" PRId64 ", verRange:%" PRId64 " - %" PRId64
1,388,977✔
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;
1,389,034✔
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) {
1,870,643✔
4857
  if (pReader == NULL) {
1,870,643✔
4858
    return;
431,535✔
4859
  }
4860

4861
  int32_t code = tsdbAcquireReader(pReader);
1,439,108✔
4862
  if (code) {
1,439,217!
4863
    return;
×
4864
  }
4865

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

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

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

4879
  SBlockLoadSuppInfo* pSupInfo = &pReader->suppInfo;
1,439,152✔
4880
  TARRAY2_DESTROY(&pSupInfo->colAggArray, NULL);
1,439,152✔
4881

4882
  if (pSupInfo->buildBuf) {
1,439,152!
4883
    for (int32_t i = 0; i < pSupInfo->numOfCols; ++i) {
7,164,348✔
4884
      if (pSupInfo->buildBuf[i] != NULL) {
5,724,878✔
4885
        taosMemoryFreeClear(pSupInfo->buildBuf[i]);
761,345!
4886
      }
4887
    }
4888
  }
4889

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

4895
  taosMemoryFree(pSupInfo->colId);
1,439,440✔
4896
  tBlockDataDestroy(&pReader->status.fileBlockData);
1,439,184✔
4897
  cleanupDataBlockIterator(&pReader->status.blockIter, shouldFreePkBuf(&pReader->suppInfo));
1,439,104✔
4898

4899
  size_t numOfTables = tSimpleHashGetSize(pReader->status.pTableMap);
1,439,191✔
4900
  if (pReader->status.pTableMap != NULL) {
1,439,163✔
4901
    destroyAllBlockScanInfo(pReader->status.pTableMap);
1,389,175✔
4902
    pReader->status.pTableMap = NULL;
1,389,228✔
4903
  }
4904
  clearBlockScanInfoBuf(&pReader->blockInfoBuf);
1,439,216✔
4905

4906
  if (pReader->pFileReader != NULL) {
1,439,207✔
4907
    tsdbDataFileReaderClose(&pReader->pFileReader);
11,570✔
4908
  }
4909

4910
  SReadCostSummary* pCost = &pReader->cost;
1,439,207✔
4911
  SFilesetIter*     pFilesetIter = &pReader->status.fileIter;
1,439,207✔
4912
  if (pFilesetIter->pSttBlockReader != NULL) {
1,439,207✔
4913
    SSttBlockReader* pSttBlockReader = pFilesetIter->pSttBlockReader;
1,349,195✔
4914
    tMergeTreeClose(&pSttBlockReader->mergeTree);
1,349,195✔
4915

4916
    clearRowKey(&pSttBlockReader->currentKey);
1,349,117✔
4917
    taosMemoryFree(pSttBlockReader);
1,349,142✔
4918
  }
4919

4920
  destroySttBlockReader(pReader->status.pLDataIterArray, &pCost->sttCost);
1,439,208✔
4921
  taosMemoryFreeClear(pReader->status.uidList.tableUidList);
1,439,209✔
4922

4923
  tsdbTrace("tsdb/reader-close: %p, untake snapshot", pReader);
1,439,228✔
4924
  void* p = pReader->pReadSnap;
1,439,228✔
4925
  if ((p == atomic_val_compare_exchange_ptr((void**)&pReader->pReadSnap, p, NULL)) && (p != NULL)) {
1,439,228!
4926
    tsdbUntakeReadSnap2(pReader, p, true);
1,345,572✔
4927
    pReader->pReadSnap = NULL;
1,345,619✔
4928
  }
4929

4930
  (void) tsem_destroy(&pReader->resumeAfterSuspend);
1,439,289✔
4931
  (void) tsdbReleaseReader(pReader);
1,439,096✔
4932
  (void) tsdbUninitReaderLock(pReader);
1,439,234✔
4933

4934
  tsdbDebug(
1,439,089✔
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);
1,439,090✔
4949

4950
  tsdbRowMergerCleanup(&pReader->status.merger);
1,439,246✔
4951
  taosMemoryFree(pReader->info.pSchema);
1,439,171✔
4952

4953
  tSimpleHashCleanup(pReader->pSchemaMap);
1,439,254✔
4954
  taosMemoryFreeClear(pReader);
1,439,224!
4955
}
4956

UNCOV
4957
static int32_t doSuspendCurrentReader(STsdbReader* pCurrentReader) {
×
UNCOV
4958
  SReaderStatus* pStatus = &pCurrentReader->status;
×
4959

UNCOV
4960
  if (pStatus->loadFromFile) {
×
UNCOV
4961
    tsdbDataFileReaderClose(&pCurrentReader->pFileReader);
×
4962

UNCOV
4963
    SReadCostSummary* pCost = &pCurrentReader->cost;
×
UNCOV
4964
    destroySttBlockReader(pStatus->pLDataIterArray, &pCost->sttCost);
×
UNCOV
4965
    pStatus->pLDataIterArray = taosArrayInit(4, POINTER_BYTES);
×
UNCOV
4966
    if (pStatus->pLDataIterArray == NULL) {
×
4967
      return terrno;
×
4968
    }
4969
  }
4970

4971
  // resetDataBlockScanInfo excluding lastKey
UNCOV
4972
  STableBlockScanInfo** p = NULL;
×
4973

UNCOV
4974
  int32_t step = ASCENDING_TRAVERSE(pCurrentReader->info.order) ? 1 : -1;
×
UNCOV
4975
  int32_t iter = 0;
×
UNCOV
4976
  while ((p = tSimpleHashIterate(pStatus->pTableMap, p, &iter)) != NULL) {
×
UNCOV
4977
    STableBlockScanInfo* pInfo = *(STableBlockScanInfo**)p;
×
UNCOV
4978
    clearBlockScanInfo(pInfo);
×
4979
    //    pInfo->sttKeyInfo.nextProcKey = pInfo->lastProcKey.ts + step;
4980
    //    pInfo->sttKeyInfo.nextProcKey = pInfo->lastProcKey + step;
4981
  }
4982

UNCOV
4983
  pStatus->uidList.currentIndex = 0;
×
UNCOV
4984
  initReaderStatus(pStatus);
×
4985

UNCOV
4986
  return TSDB_CODE_SUCCESS;
×
4987
}
4988

UNCOV
4989
int32_t tsdbReaderSuspend2(STsdbReader* pReader) {
×
4990
  // save reader's base state & reset top state to be reconstructed from base state
UNCOV
4991
  int32_t code = 0;
×
UNCOV
4992
  pReader->status.suspendInvoked = true;  // record the suspend status
×
4993

UNCOV
4994
  if (pReader->type == TIMEWINDOW_RANGE_EXTERNAL) {
×
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 {
UNCOV
5003
    code = doSuspendCurrentReader(pReader);
×
5004
  }
5005

5006
  // make sure only release once
UNCOV
5007
  void* p = pReader->pReadSnap;
×
UNCOV
5008
  if ((p == atomic_val_compare_exchange_ptr((void**)&pReader->pReadSnap, p, NULL)) && (p != NULL)) {
×
UNCOV
5009
    tsdbUntakeReadSnap2(pReader, p, false);
×
UNCOV
5010
    pReader->pReadSnap = NULL;
×
5011
  }
5012

UNCOV
5013
  if (pReader->bFilesetDelimited) {
×
5014
    pReader->status.memTableMinKey = INT64_MAX;
×
5015
    pReader->status.memTableMaxKey = INT64_MIN;
×
5016
  }
UNCOV
5017
  pReader->flag = READER_STATUS_SUSPEND;
×
5018

UNCOV
5019
  if (pReader->type == TIMEWINDOW_RANGE_EXTERNAL) {
×
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

UNCOV
5028
  tsdbDebug("reader: %p suspended in this query %s, step:%d", pReader, pReader->idStr, pReader->step);
×
UNCOV
5029
  return code;
×
5030
}
5031

UNCOV
5032
static int32_t tsdbSetQueryReseek(void* pQHandle) {
×
UNCOV
5033
  int32_t      code = 0;
×
UNCOV
5034
  STsdbReader* pReader = pQHandle;
×
5035

UNCOV
5036
  code = tsdbTryAcquireReader(pReader);
×
UNCOV
5037
  if (code == 0) {
×
UNCOV
5038
    if (pReader->flag == READER_STATUS_SUSPEND) {
×
5039
      code = tsdbReleaseReader(pReader);
×
5040
      return code;
×
5041
    }
5042

UNCOV
5043
    code = tsdbReaderSuspend2(pReader);
×
UNCOV
5044
    (void) tsdbReleaseReader(pReader);
×
UNCOV
5045
    return code;
×
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) {
1,387,893✔
5055
  int32_t               code = 0;
1,387,893✔
5056
  STableBlockScanInfo** pBlockScanInfo = pReader->status.pTableIter;
1,387,893✔
5057

5058
  //  restore reader's state, task snapshot
5059
  int32_t numOfTables = tSimpleHashGetSize(pReader->status.pTableMap);
1,387,893✔
5060
  if (numOfTables > 0) {
1,388,346✔
5061
    tsdbTrace("tsdb/reader: %p, take snapshot", pReader);
1,345,010✔
5062
    code = tsdbTakeReadSnap2(pReader, tsdbSetQueryReseek, &pReader->pReadSnap, pReader->idStr);
1,345,010✔
5063
    if (code != TSDB_CODE_SUCCESS) {
1,345,458!
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;
1,345,458✔
5070

5071
    if (pReader->type == TIMEWINDOW_RANGE_CONTAINED) {
1,345,458✔
5072
      code = doOpenReaderImpl(pReader);
1,343,723✔
5073
      if (code != TSDB_CODE_SUCCESS) {
1,343,288!
5074
        return code;
×
5075
      }
5076
    } else {
5077
      STsdbReader* pPrevReader = pReader->innerReader[0];
1,735✔
5078
      STsdbReader* pNextReader = pReader->innerReader[1];
1,735✔
5079

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

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

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

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

5120
  SSDataBlock* pBlock = pReader->resBlockInfo.pResBlock;
2,803✔
5121

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

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

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

5149
  if (pStatus->loadFromFile) {
730,123✔
5150
    if (pStatus->bProcMemPreFileset) {
182,336✔
5151
      code = buildFromPreFilesetBuffer(pReader);
1,594✔
5152
      if (code != TSDB_CODE_SUCCESS || pBlock->info.rows > 0) {
1,594!
5153
        return code;
405✔
5154
      }
5155
    }
5156

5157
    code = buildBlockFromFiles(pReader);
181,931✔
5158
    if (code != TSDB_CODE_SUCCESS) {
181,760!
5159
      return code;
×
5160
    }
5161

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

5183
      int64_t endKey = (ASCENDING_TRAVERSE(pReader->info.order)) ? INT64_MAX : INT64_MIN;
18,963✔
5184
      code = buildBlockFromBufferSequentially(pReader, endKey);
18,963✔
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;
547,787✔
5188
    code = buildBlockFromBufferSequentially(pReader, endKey);
547,787✔
5189
  }
5190
  return code;
729,435✔
5191
}
5192

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

5198
  if (pStatus->loadFromFile) {
4,711,858✔
5199
    code = buildBlockFromFiles(pReader);
2,627,844✔
5200
    if (code != TSDB_CODE_SUCCESS) {
2,624,878!
5201
      return code;
×
5202
    }
5203

5204
    if (pBlock->info.rows <= 0) {
2,624,878✔
5205
      code = resetTableListIndex(&pReader->status, pReader->idStr);
278,469✔
5206
      if (code) {
278,512!
5207
        return code;
×
5208
      }
5209

5210
      int64_t endKey = (ASCENDING_TRAVERSE(pReader->info.order)) ? INT64_MAX : INT64_MIN;
278,512✔
5211
      code = buildBlockFromBufferSequentially(pReader, endKey);
278,512✔
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;
2,084,014✔
5215
    code = buildBlockFromBufferSequentially(pReader, endKey);
2,084,014✔
5216
  }
5217
  return code;
4,709,416✔
5218
}
5219

5220
static int32_t doTsdbNextDataBlock2(STsdbReader* pReader, bool* hasNext) {
5,485,392✔
5221
  int32_t code = TSDB_CODE_SUCCESS;
5,485,392✔
5222

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

5227
  *hasNext = false;
5,485,752✔
5228

5229
  SReaderStatus* pStatus = &pReader->status;
5,485,752✔
5230
  if (tSimpleHashGetSize(pStatus->pTableMap) == 0) {
5,485,752✔
5231
    return code;
43,647✔
5232
  }
5233

5234
  if (!pReader->bFilesetDelimited) {
5,442,680✔
5235
    code = doTsdbNextDataBlockFilesFirst(pReader);
4,712,374✔
5236
  } else {
5237
    code = doTsdbNextDataBlockFilesetDelimited(pReader);
730,306✔
5238
  }
5239

5240
  *hasNext = pBlock->info.rows > 0;
5,440,341✔
5241

5242
  return code;
5,440,341✔
5243
}
5244

5245
int32_t tsdbNextDataBlock2(STsdbReader* pReader, bool* hasNext) {
5,527,814✔
5246
  int32_t code = TSDB_CODE_SUCCESS;
5,527,814✔
5247

5248
  *hasNext = false;
5,527,814✔
5249

5250
  if (isEmptyQueryTimeWindow(&pReader->info.window) || pReader->step == EXTERNAL_ROWS_NEXT ||
5,527,814!
5251
      pReader->code != TSDB_CODE_SUCCESS) {
5,483,441✔
5252
    return (pReader->code != TSDB_CODE_SUCCESS) ? pReader->code : code;
45,673!
5253
  }
5254

5255
  SReaderStatus* pStatus = &pReader->status;
5,483,352✔
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);
5,483,352✔
5268
  if (code != TSDB_CODE_SUCCESS) {
5,485,279!
5269
    return code;
×
5270
  }
5271

5272
  tsdbTrace("tsdb/read: %p, take read mutex, code: %d", pReader, code);
5,485,279✔
5273

5274
  if (pReader->flag == READER_STATUS_SUSPEND) {
5,485,279✔
5275
    code = tsdbReaderResume2(pReader);
1,389,067✔
5276
    if (code != TSDB_CODE_SUCCESS) {
1,388,347!
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) {
5,484,559✔
5284
    code = doTsdbNextDataBlock2(pReader->innerReader[0], hasNext);
1,804✔
5285
    if (code) {
1,804!
5286
      (void) tsdbReleaseReader(pReader);
×
5287
      return code;
×
5288
    }
5289

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

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

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

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

5319
  code = doTsdbNextDataBlock2(pReader, hasNext);
5,483,912✔
5320
  if (code != TSDB_CODE_SUCCESS) {
5,479,381!
5321
    (void) tsdbReleaseReader(pReader);
×
5322
    return code;
4✔
5323
  }
5324

5325
  if (*hasNext) {
5,480,617✔
5326
    if (pStatus->composedDataBlock) {
4,125,529✔
5327
      tsdbTrace("tsdb/read: %p, unlock read mutex", pReader);
3,745,726✔
5328
      code = tsdbReleaseReader(pReader);
3,745,726✔
5329
    }
5330
    return code;
4,129,177✔
5331
  }
5332

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

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

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

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

5360
      return code;
731✔
5361
    }
5362
  }
5363

5364
  tsdbTrace("tsdb/read: %p, unlock read mutex", pReader);
1,354,357✔
5365
  code = tsdbReleaseReader(pReader);
1,354,357✔
5366
  return code;
1,354,597✔
5367
}
5368

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

5378
  size++;
39,395✔
5379

5380
  while (j < numOfCols && i < size) {
159,703!
5381
    SColumnDataAgg* pAgg = &pSup->colAggArray.data[i];
120,308✔
5382
    if (pAgg->colId == pSup->colId[j]) {
120,308✔
5383
      i += 1;
84,339✔
5384
      j += 1;
84,339✔
5385
    } else if (pAgg->colId < pSup->colId[j]) {
35,969!
5386
      i += 1;
35,969✔
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) {
39,396✔
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) {
943,420✔
5417
  SColumnDataAgg**    pBlockSMA = &pDataBlock->pBlockAgg;
943,420✔
5418
  SFileDataBlockInfo* pBlockInfo = NULL;
943,420✔
5419
  int32_t             code = 0;
943,420✔
5420
  *allHave = false;
943,420✔
5421
  *pBlockSMA = NULL;
943,420✔
5422

5423
  if (pReader->type == TIMEWINDOW_RANGE_EXTERNAL) {
943,420✔
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)) {
943,395!
5429
    return TSDB_CODE_SUCCESS;
904,000✔
5430
  }
5431

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

5437
  SBlockLoadSuppInfo* pSup = &pReader->suppInfo;
39,395✔
5438

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

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

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

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

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

5474
  if (pResBlock->pBlockAgg == NULL) {
39,394!
5475
    size_t num = taosArrayGetSize(pResBlock->pDataBlock);
39,394✔
5476
    pResBlock->pBlockAgg = taosMemoryCalloc(num, sizeof(SColumnDataAgg));
39,394✔
5477
    if (pResBlock->pBlockAgg == NULL) {
39,395!
5478
      return terrno;
×
5479
    }
5480
    for (int i = 0; i < num; ++i) {
127,603✔
5481
      pResBlock->pBlockAgg[i].colId = -1;
88,208✔
5482
    }
5483
  }
5484

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

5488
  size_t size = pSup->colAggArray.size;
39,394✔
5489

5490
  int32_t i = 0, j = 0;
39,394✔
5491
  while (j < numOfCols && i < size) {
159,702!
5492
    SColumnDataAgg* pAgg = &pSup->colAggArray.data[i];
120,308✔
5493
    if (pAgg->colId == pSup->colId[j]) {
120,308✔
5494
      pResBlock->pBlockAgg[pSup->slotId[j]] = *pAgg;
84,340✔
5495
      i += 1;
84,340✔
5496
      j += 1;
84,340✔
5497
    } else if (pAgg->colId < pSup->colId[j]) {
35,968!
5498
      i += 1;
35,968✔
5499
    } else if (pSup->colId[j] < pAgg->colId) {
×
5500
      pResBlock->pBlockAgg[pSup->slotId[j]].colId = -1;
×
5501
      *allHave = false;
×
5502
      j += 1;
×
5503
    }
5504
  }
5505

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

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

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

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

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

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

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

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

5543
  code = copyBlockDataToSDataBlock(pReader, &pBlockScanInfo->lastProcKey);
332,579✔
5544
  if (code != TSDB_CODE_SUCCESS) {
332,541!
UNCOV
5545
    tBlockDataReset(&pStatus->fileBlockData);
×
5546
  }
5547

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

5552
int32_t tsdbRetrieveDataBlock2(STsdbReader* pReader, SSDataBlock** pBlock, SArray* pIdList) {
3,919,026✔
5553
  *pBlock = NULL;
3,919,026✔
5554

5555
  STsdbReader* pTReader = pReader;
3,919,026✔
5556
  if (pReader->type == TIMEWINDOW_RANGE_EXTERNAL) {
3,919,026✔
5557
    if (pReader->step == EXTERNAL_ROWS_PREV) {
3,484✔
5558
      pTReader = pReader->innerReader[0];
647✔
5559
    } else if (pReader->step == EXTERNAL_ROWS_NEXT) {
2,837✔
5560
      pTReader = pReader->innerReader[1];
731✔
5561
    }
5562
  }
5563

5564
  SReaderStatus* pStatus = &pTReader->status;
3,919,026✔
5565
  if (pStatus->composedDataBlock || pReader->info.execMode == READER_EXEC_ROWS) {
3,919,026!
5566
    //    tsdbReaderSuspend2(pReader);
5567
    //    tsdbReaderResume2(pReader);
5568
    *pBlock = pTReader->resBlockInfo.pResBlock;
3,586,709✔
5569
    return TSDB_CODE_SUCCESS;
3,586,709✔
5570
  }
5571

5572
  int32_t code = doRetrieveDataBlock(pTReader, pBlock);
332,317✔
5573

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

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

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

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

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

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

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

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

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

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

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

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

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

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

5649
  // no data in files, let's try buffer in memory
5650
  if (pStatus->fileIter.numOfFiles == 0) {
20,813✔
5651
    pStatus->loadFromFile = false;
3,817✔
5652
    code = resetTableListIndex(pStatus, pReader->idStr);
3,817✔
5653
    if (code != TSDB_CODE_SUCCESS) {
3,817!
5654
      (void) tsdbReleaseReader(pReader);
×
5655
      return code;
×
5656
    }
5657
  } else {
5658
    code = initForFirstBlockInFile(pReader, pBlockIter);
16,996✔
5659
    if (code != TSDB_CODE_SUCCESS) {
16,977!
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,794✔
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,794✔
5674
  return code;
20,814✔
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) {
10✔
5689
  int32_t       code = TSDB_CODE_SUCCESS;
10✔
5690
  const int32_t numOfBuckets = 20.0;
10✔
5691

5692
  pTableBlockInfo->totalSize = 0;
10✔
5693
  pTableBlockInfo->totalRows = 0;
10✔
5694
  pTableBlockInfo->numOfVgroups = 1;
10✔
5695

5696
  // find the start data block in file
5697
  code = tsdbAcquireReader(pReader);
10✔
5698
  if (code != TSDB_CODE_SUCCESS) {
10!
5699
    return code;
×
5700
  }
5701

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

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

5717
  SReaderStatus* pStatus = &pReader->status;
10✔
5718
  if (pStatus->pCurrentFileset != NULL) {
10✔
5719
    pTableBlockInfo->numOfSttRows += tsdbGetRowsInSttFiles(pStatus->pCurrentFileset, pStatus->pLDataIterArray,
4✔
5720
                                                           pReader->pTsdb, &conf, pReader->idStr);
4✔
5721
  }
5722

5723
  STsdbCfg* pc = &pReader->pTsdb->pVnode->config.tsdbCfg;
10✔
5724
  pTableBlockInfo->defMinRows = pc->minRows;
10✔
5725
  pTableBlockInfo->defMaxRows = pc->maxRows;
10✔
5726

5727
  int32_t bucketRange = ceil(((double)(pc->maxRows - pc->minRows)) / numOfBuckets);
10✔
5728

5729
  pTableBlockInfo->numOfFiles += 1;
10✔
5730

5731
  int32_t numOfTables = (int32_t)tSimpleHashGetSize(pStatus->pTableMap);
10✔
5732

5733
  SDataBlockIter* pBlockIter = &pStatus->blockIter;
10✔
5734
  pTableBlockInfo->numOfFiles += pStatus->fileIter.numOfFiles;
10✔
5735

5736
  if (pBlockIter->numOfBlocks > 0) {
10✔
5737
    pTableBlockInfo->numOfBlocks += pBlockIter->numOfBlocks;
1✔
5738
  }
5739

5740
  pTableBlockInfo->numOfTables = numOfTables;
10✔
5741
  bool hasNext = (pBlockIter->numOfBlocks > 0);
10✔
5742

5743
  while (true) {
5744
    if (hasNext) {
11✔
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);
10✔
5771
      if ((code != TSDB_CODE_SUCCESS) || (pStatus->loadFromFile == false)) {
10!
5772
        break;
5773
      }
5774

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

UNCOV
5781
      pTableBlockInfo->numOfBlocks += pBlockIter->numOfBlocks;
×
UNCOV
5782
      hasNext = (pBlockIter->numOfBlocks > 0);
×
5783
    }
5784
  }
5785

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

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

5795
  SReaderStatus* pStatus = &pReader->status;
232,938✔
5796

5797
  int32_t iter = 0;
232,938✔
5798
  int64_t maxKey = INT64_MIN;
232,938✔
5799
  int64_t minKey = INT64_MAX;
232,938✔
5800

5801
  void* pHashIter = tSimpleHashIterate(pStatus->pTableMap, NULL, &iter);
232,938✔
5802
  while (pHashIter != NULL) {
821,185✔
5803
    STableBlockScanInfo* pBlockScanInfo = *(STableBlockScanInfo**)pHashIter;
588,194✔
5804

5805
    STbData* d = NULL;
588,194✔
5806
    if (pReader->pReadSnap->pMem != NULL) {
588,194✔
5807
      d = tsdbGetTbDataFromMemTable(pReader->pReadSnap->pMem, pReader->info.suid, pBlockScanInfo->uid);
439,557✔
5808
      if (d != NULL) {
439,770✔
5809
        if (d->maxKey > maxKey) {
336,527✔
5810
          maxKey = d->maxKey;
134,849✔
5811
        }
5812
        if (d->minKey < minKey) {
336,527✔
5813
          minKey = d->minKey;
118,869✔
5814
        }
5815
      }
5816
    }
5817

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

5835
  *pMaxKey = maxKey;
232,991✔
5836
  *pMinKey = minKey;
232,991✔
5837
}
232,991✔
5838

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

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

5849
  if (pReader->flag == READER_STATUS_SUSPEND) {
10✔
5850
    code = tsdbReaderResume2(pReader);
4✔
5851
    if (code != TSDB_CODE_SUCCESS) {
4!
5852
      (void) tsdbReleaseReader(pReader);
×
5853
      return code;
×
5854
    }
5855
  }
5856

5857
  int32_t iter = 0;
10✔
5858
  pStatus->pTableIter = tSimpleHashIterate(pStatus->pTableMap, NULL, &iter);
10✔
5859

5860
  while (pStatus->pTableIter != NULL) {
16✔
5861
    STableBlockScanInfo* pBlockScanInfo = *(STableBlockScanInfo**)pStatus->pTableIter;
6✔
5862

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

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

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

5883
  (void) tsdbReleaseReader(pReader);
10✔
5884

5885
  return rows;
10✔
5886
}
5887

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

5898
  *suid = 0;
169✔
5899

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

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

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

5932
  // lock
5933
  code = taosThreadMutexLock(&pTsdb->mutex);
1,357,790✔
5934
  if (code != TSDB_CODE_SUCCESS) {
1,359,163!
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));
1,359,163✔
5941
  if (pSnap == NULL) {
1,359,173!
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)) {
1,359,173!
5948
    pSnap->pMem = pTsdb->mem;
1,014,015✔
5949
    pSnap->pNode = taosMemoryMalloc(sizeof(*pSnap->pNode));
1,014,015✔
5950
    if (pSnap->pNode == NULL) {
1,013,990!
5951
      (void) taosThreadMutexUnlock(&pTsdb->mutex);
×
5952
      TSDB_CHECK_NULL(pSnap->pNode, code, lino, _exit, terrno);
×
5953
    }
5954

5955
    pSnap->pNode->pQHandle = pReader;
1,013,990✔
5956
    pSnap->pNode->reseek = reseek;
1,013,990✔
5957

5958
    code = tsdbRefMemTable(pTsdb->mem, pSnap->pNode);
1,013,990✔
5959
    TSDB_CHECK_CODE(code, lino, _exit);
1,013,973!
5960
  }
5961

5962
  if (pTsdb->imem && (pRange->minVer <= pTsdb->imem->maxVer && pRange->maxVer >= pTsdb->imem->minVer)) {
1,359,131!
5963
    pSnap->pIMem = pTsdb->imem;
5,104✔
5964
    pSnap->pINode = taosMemoryMalloc(sizeof(*pSnap->pINode));
5,104✔
5965
    if (pSnap->pINode == NULL) {
5,105!
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;
5,105✔
5977
    pSnap->pINode->reseek = reseek;
5,105✔
5978

5979
    code = tsdbRefMemTable(pTsdb->imem, pSnap->pINode);
5,105✔
5980
    TSDB_CHECK_CODE(code, lino, _exit);
5,106!
5981
  }
5982

5983
  // fs
5984
  code = tsdbFSCreateRefSnapshotWithoutLock(pTsdb->pFS, &pSnap->pfSetArray);
1,359,133✔
5985
  if (code) {
1,358,765!
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);
1,358,765✔
6000
  *ppSnap = pSnap;
1,359,172✔
6001

6002
  tsdbTrace("%s vgId:%d, take read snapshot", id, TD_VID(pTsdb->pVnode));
1,359,172✔
6003
  return code;
1,359,163✔
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) {
1,359,127✔
6017
  STsdb* pTsdb = pReader->pTsdb;
1,359,127✔
6018

6019
  if (pSnap) {
1,359,127!
6020
    if (pSnap->pMem) {
1,359,164✔
6021
      tsdbUnrefMemTable(pSnap->pMem, pSnap->pNode, proactive);
1,014,040✔
6022
    }
6023

6024
    if (pSnap->pIMem) {
1,359,173✔
6025
      tsdbUnrefMemTable(pSnap->pIMem, pSnap->pINode, proactive);
5,106✔
6026
    }
6027

6028
    if (pSnap->pNode) taosMemoryFree(pSnap->pNode);
1,359,173✔
6029
    if (pSnap->pINode) taosMemoryFree(pSnap->pINode);
1,359,170✔
6030

6031
    tsdbFSDestroyRefSnapshot(&pSnap->pfSetArray);
1,359,170✔
6032

6033
    taosMemoryFree(pSnap);
1,359,206✔
6034
  }
6035
  tsdbTrace("vgId:%d, untake read snapshot", TD_VID(pTsdb->pVnode));
1,359,214✔
6036
}
1,359,214✔
6037

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

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

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

6055
void tsdbSetFilesetDelimited(STsdbReader* pReader) { pReader->bFilesetDelimited = true; }
232,693✔
6056

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