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

taosdata / TDengine / #3523

06 Nov 2024 02:29AM UTC coverage: 55.861% (-2.4%) from 58.216%
#3523

push

travis-ci

web-flow
Merge pull request #28551 from taosdata/feat/TS-5215-2

test(blob): testing & fixes for blob

106075 of 245834 branches covered (43.15%)

Branch coverage included in aggregate %.

0 of 15 new or added lines in 2 files covered. (0.0%)

17003 existing lines in 254 files now uncovered.

181910 of 269703 relevant lines covered (67.45%)

1527639.59 hits per line

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

59.51
/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) {
4✔
93
  if (p2 == NULL) {
11,160,529!
94
    return 1;
2,785,966✔
95
  }
96

97
  if (p1 == NULL) {
10,483,130!
98
    return -1;
×
99
  }
100

101
  if (p1->ts < p2->ts) {
10,483,130!
102
    return -1;
5,960,863✔
103
  } else if (p1->ts > p2->ts) {
4,522,267!
104
    return 1;
1,651,683✔
105
  }
106

107
  if (p1->numOfPKs == 0) {
2,870,584!
108
    return 0;
2,192,794✔
109
  } else {
110
    return tRowKeyCompare(p1, p2);
677,790✔
111
  }
112
}
113

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

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

122
  if (IS_NUMERIC_TYPE(cv.value.type)) {
1,345,018!
123
    pKey->pks[0].val = cv.value.val;
1,344,998✔
124
  } else {
125
    pKey->pks[0].nData = cv.value.nData;
20✔
126
    (void)memcpy(pKey->pks[0].pData, cv.value.pData, cv.value.nData);
20✔
127
  }
128
}
1,345,018✔
129

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

138
static void tRowGetPrimaryKeyDeepCopy(SRow* pRow, SRowKey* pKey) {
35,177,945✔
139
  SPrimaryKeyIndex indices[TD_MAX_PK_COLS];
140

141
  uint8_t* data = pRow->data;
35,177,945✔
142
  for (int32_t i = 0; i < pRow->numOfPKs; i++) {
70,355,890✔
143
    data += tGetPrimaryKeyIndex(data, &indices[i]);
35,177,945✔
144
  }
145

146
  // primary keys
147
  for (int32_t i = 0; i < pRow->numOfPKs; i++) {
70,355,890✔
148
    pKey->pks[i].type = indices[i].type;
35,177,945✔
149

150
    uint8_t* tdata = data + indices[i].offset;
35,177,945✔
151
    if (pRow->flag >> 4) {
35,177,945!
UNCOV
152
      tdata += tGetI16v(tdata, NULL);
×
153
    }
154

155
    if (IS_VAR_DATA_TYPE(indices[i].type)) {
35,177,945!
156
      tdata += tGetU32v(tdata, &pKey->pks[i].nData);
1!
157
      (void)memcpy(pKey->pks[i].pData, tdata, pKey->pks[i].nData);
1✔
158
    } else {
159
      (void)memcpy(&pKey->pks[i].val, data + indices[i].offset, tDataTypes[pKey->pks[i].type].bytes);
35,177,944✔
160
    }
161
  }
162
}
35,177,945✔
163

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

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

175
  pSupInfo->colId = taosMemoryMalloc(numOfCols * (sizeof(int16_t) * 2 + POINTER_BYTES));
131,499✔
176
  if (pSupInfo->colId == NULL) {
131,604✔
177
    taosMemoryFree(pSupInfo->colId);
6✔
178
    return terrno;
6✔
179
  }
180

181
  pSupInfo->slotId = (int16_t*)((char*)pSupInfo->colId + (sizeof(int16_t) * numOfCols));
131,598✔
182
  pSupInfo->buildBuf = (char**)((char*)pSupInfo->slotId + (sizeof(int16_t) * numOfCols));
131,598✔
183
  for (int32_t i = 0; i < numOfCols; ++i) {
1,137,729✔
184
    pSupInfo->colId[i] = pCols[i].colId;
1,005,775✔
185
    pSupInfo->slotId[i] = pSlotIdList[i];
1,005,775✔
186

187
    if (IS_VAR_DATA_TYPE(pCols[i].type)) {
1,005,775!
188
      pSupInfo->buildBuf[i] = taosMemoryMalloc(pCols[i].bytes);
121,515✔
189
      if (pSupInfo->buildBuf[i] == NULL) {
121,869✔
190
        tsdbError("failed to prepare memory for set columnId slot list, size:%d, code:out of memory", pCols[i].bytes);
5!
191
        initSucc = false;
7✔
192
      }
193
    } else {
194
      pSupInfo->buildBuf[i] = NULL;
884,260✔
195
    }
196

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

205
  return (initSucc)? TSDB_CODE_SUCCESS:TSDB_CODE_OUT_OF_MEMORY;
131,954✔
206
}
207

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

211
  while (i < pSchema->numOfCols && j < pSupInfo->numOfCols) {
1,255,835✔
212
    STColumn* pTCol = &pSchema->columns[i];
1,144,777✔
213
    if (pTCol->colId == pSupInfo->colId[j]) {
1,144,777✔
214
      if (!IS_BSMA_ON(pTCol) && (PRIMARYKEY_TIMESTAMP_COL_ID != pTCol->colId)) {
671,225✔
215
        pSupInfo->smaValid = false;
20,231✔
216
        return TSDB_CODE_SUCCESS;
20,231✔
217
      }
218

219
      i += 1;
650,994✔
220
      j += 1;
650,994✔
221
    } else if (pTCol->colId < pSupInfo->colId[j]) {  // do nothing
473,552!
222
      i += 1;
473,563✔
223
    } else {
224
      return TSDB_CODE_TDB_INVALID_TABLE_SCHEMA_VER;
×
225
    }
226
  }
227

228
  return TSDB_CODE_SUCCESS;
111,058✔
229
}
230

231
static bool isEmptyQueryTimeWindow(STimeWindow* pWindow) { return pWindow->skey > pWindow->ekey; }
465,105✔
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) {
131,845✔
236
  int64_t     earlyTs = tsdbGetEarliestTs(pTsdb);
131,845✔
237
  STimeWindow win = *pWindow;
131,961✔
238
  if (win.skey < earlyTs) {
131,961✔
239
    win.skey = earlyTs;
102,228✔
240
  }
241

242
  return win;
131,961✔
243
}
244

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

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

257
  if (pIter->pSttBlockReader == NULL) {
118,242✔
258
    pIter->pSttBlockReader = taosMemoryCalloc(1, sizeof(struct SSttBlockReader));
117,888✔
259
    if (pIter->pSttBlockReader == NULL) {
117,866✔
260
      tsdbError("failed to prepare the last block iterator, since:%s %s", tstrerror(terrno), pReader->idStr);
9!
261
      return terrno;
9✔
262
    }
263
  }
264

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

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

280
  return code;
118,267✔
281
}
282

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

288
  pIter->index += step;
74,536✔
289
  if ((asc && pIter->index >= pIter->numOfFiles) || ((!asc) && pIter->index < 0)) {
74,536✔
290
    *hasNext = false;
18,043✔
291
    return TSDB_CODE_SUCCESS;
18,043✔
292
  }
293

294
  SReadCostSummary* pCost = &pReader->cost;
56,493✔
295

296
  pIter->pSttBlockReader->uid = 0;
56,493✔
297
  tMergeTreeClose(&pIter->pSttBlockReader->mergeTree);
56,493✔
298
  destroySttBlockReader(pReader->status.pLDataIterArray, &pCost->sttCost);
56,499✔
299

300
  pReader->status.pLDataIterArray = taosArrayInit(4, POINTER_BYTES);
56,490✔
301
  if (pReader->status.pLDataIterArray == NULL) {
56,498✔
302
    return terrno;
3✔
303
  }
304

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

308
  while (1) {
2,335✔
309
    if (pReader->pFileReader != NULL) {
58,830✔
310
      tsdbDataFileReaderClose(&pReader->pFileReader);
1,009✔
311
    }
312

313
    pReader->status.pCurrentFileset = pIter->pFilesetList->data[pIter->index];
58,830✔
314

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

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

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

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

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

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

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

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

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

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

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

372
    *hasNext = true;
52,701✔
373
    return TSDB_CODE_SUCCESS;
52,701✔
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); }
302,730!
382

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

388
  if (pIter->blockList == NULL) {
170,599✔
389
    pIter->blockList = taosArrayInit(4, sizeof(SFileDataBlockInfo));
117,861✔
390
    if (pIter->blockList == NULL) {
117,866✔
391
      tsdbError("%s failed to reset block iter, func:%s at line:%d code:%s", id, __func__, __LINE__, tstrerror(terrno));
10!
392
      return terrno;
10✔
393
    }
394
  } else {
395
    clearDataBlockIterator(pIter, needFree);
52,738✔
396
  }
397

398
  return TSDB_CODE_SUCCESS;
170,619✔
399
}
400

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

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

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

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

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

430
  *pResBlock = pBlock;
4✔
431
  return code;
4✔
432
}
433

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

438
  return code;
131,520✔
439
}
440

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

445
  code = taosThreadMutexDestroy(&pReader->readerMutex);
131,576✔
446
  tsdbTrace("tsdb/read: %p, post-uninit read mutex: %p, code: %d", pReader, &pReader->readerMutex, code);
131,552!
447

448
  return code;
131,561✔
449
}
450

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

455
  code = taosThreadMutexLock(&pReader->readerMutex);
471,536✔
456
  if (code != 0) {
471,748!
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);
471,748!
460
  }
461

462
  return code;
471,686✔
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) {
471,778✔
476
  int32_t code = taosThreadMutexUnlock(&pReader->readerMutex);
471,778✔
477
  if (code != TSDB_CODE_SUCCESS) {
471,947!
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);
471,947!
481
  }
482
  return code;
471,918✔
483
}
484

485
void tsdbReleaseDataBlock2(STsdbReader* pReader) {
44,140✔
486
  SReaderStatus* pStatus = &pReader->status;
44,140✔
487
  if (!pStatus->composedDataBlock) {
44,140✔
488
    (void) tsdbReleaseReader(pReader);
297✔
489
  }
490
}
44,140✔
491

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

498
  if (pResBlockInfo->pResBlock == NULL) {
131,515✔
499
    pResBlockInfo->freeBlock = true;
4✔
500
    pResBlockInfo->pResBlock = NULL;
4✔
501

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

507
    if (pSup->numOfPks > 0) {
4!
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);
30✔
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;
131,511✔
530
  }
531

532
  return code;
131,487✔
533
}
534

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

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

549
  initReaderStatus(&pReader->status);
131,543✔
550
  getTsdbByRetentions(pVnode, pCond, pVnode->config.tsdbCfg.retentions, idstr, &level, &pReader->pTsdb);
131,546✔
551

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

557
  pReader->idStr = (idstr != NULL) ? taosStrdup(idstr) : NULL;
131,586✔
558
  if (idstr != NULL && pReader->idStr == NULL) {
131,577✔
559
    code = terrno;
6✔
560
    goto _end;
6✔
561
  }
562

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

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

581
  code = initResBlockInfo(&pReader->resBlockInfo, capacity, pResBlock, pCond, pSup);
131,575✔
582
  if (code != TSDB_CODE_SUCCESS) {
131,490!
583
    goto _end;
×
584
  }
585

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

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

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

616
  code = tsem_init(&pReader->resumeAfterSuspend, 0, 0);
131,515✔
617
  if (code != TSDB_CODE_SUCCESS) {
131,481!
618
    goto _end;
×
619
  }
620

621
  *ppReader = pReader;
131,481✔
622
  return code;
131,481✔
623

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

630
static int32_t doLoadBlockIndex(STsdbReader* pReader, SDataFileReader* pFileReader, SArray* pIndexList) {
52,698✔
631
  int64_t st = taosGetTimestampUs();
52,701✔
632
  int32_t numOfTables = tSimpleHashGetSize(pReader->status.pTableMap);
52,701✔
633
  if (pFileReader == NULL) {
52,704✔
634
    return TSDB_CODE_SUCCESS;
51,216✔
635
  }
636

637
  const TBrinBlkArray* pBlkArray = NULL;
1,488✔
638

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

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

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

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

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

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

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

697
    i += 1;
834✔
698
  }
699

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

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

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

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

727
  while (1) {
1,587✔
728
    int32_t code = getNextBrinRecord(&iter, &pRecord);
54,097✔
729
    if (code != TSDB_CODE_SUCCESS) {
54,099!
730
      clearBrinBlockIter(&iter);
×
731
      return code;
1✔
732
    }
733

734
    if (pRecord == NULL) {
54,099✔
735
      break;
51,983✔
736
    }
737

738
    if (pRecord->suid > pReader->info.suid) {
2,116✔
739
      break;
429✔
740
    }
741

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

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

752
      if (k >= numOfTables) {
187✔
753
        break;
100✔
754
      }
755

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

759
    if (pRecord->uid < uid) {
1,115✔
760
      continue;
348✔
761
    }
762

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

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

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

799
    if (asc) {
765✔
800
      if (pkCompEx(&pRecord->lastKey.key, &pScanInfo->lastProcKey) <= 0) {
864!
801
        continue;
×
802
      }
803
    } else {
804
      if (pkCompEx(&pRecord->firstKey.key, &pScanInfo->lastProcKey) >= 0) {
666!
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) {
765!
811
      continue;
×
812
    }
813

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

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

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

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

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

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

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

873
  clearBrinBlockIter(&iter);
52,512✔
874

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

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

888
  return TSDB_CODE_SUCCESS;
52,493✔
889
}
890

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

895
static void updateLastKeyInfo(SRowKey* pKey, SFileDataBlockInfo* pBlockInfo, SDataBlockInfo* pInfo, int32_t numOfPks,
188✔
896
                              bool asc) {
897
  pKey->ts = asc ? pInfo->window.ekey : pInfo->window.skey;
188✔
898
  pKey->numOfPKs = numOfPks;
188✔
899
  if (pKey->numOfPKs <= 0) {
188!
900
    return;
188✔
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,
162,153,446✔
913
                            SBlockLoadSuppInfo* pSup) {
914
  int32_t code = 0;
162,153,446✔
915

916
  if (IS_VAR_DATA_TYPE(pColVal->value.type)) {
162,153,446!
917
    if (!COL_VAL_IS_VALUE(pColVal)) {
18,919,967✔
918
      colDataSetNULL(pColInfoData, rowIndex);
7,439,237✔
919
    } else {
920
      varDataSetLen(pSup->buildBuf[colIndex], pColVal->value.nData);
11,480,730✔
921
      if ((pColVal->value.nData + VARSTR_HEADER_SIZE) > pColInfoData->info.bytes) {
11,480,730!
922
        tsdbWarn("column cid:%d actual data len %d is bigger than schema len %d", pColVal->cid, pColVal->value.nData,
×
923
                 pColInfoData->info.bytes);
924
        return TSDB_CODE_TDB_INVALID_TABLE_SCHEMA_VER;
×
925
      }
926

927
      if (pColVal->value.nData > 0) {  // pData may be null, if nData is 0
11,480,730!
928
        (void)memcpy(varDataVal(pSup->buildBuf[colIndex]), pColVal->value.pData, pColVal->value.nData);
15,295,022✔
929
      }
930

931
      code = colDataSetVal(pColInfoData, rowIndex, pSup->buildBuf[colIndex], false);
11,480,730✔
932
    }
933
  } else {
934
    code = colDataSetVal(pColInfoData, rowIndex, (const char*)&pColVal->value.val, !COL_VAL_IS_VALUE(pColVal));
143,233,479✔
935
  }
936

937
  return code;
163,277,345✔
938
}
939

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

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

947
  size_t num = TARRAY_SIZE(pBlockIter->blockList);
55,294✔
948
  if (num == 0) {
55,294✔
949
    if (num != pBlockIter->numOfBlocks) {
51,760!
950
      tsdbError("tsdb read failed at: %s:%d %s", __func__, __LINE__, id);
×
951
    }
952
    return TSDB_CODE_FAILED;
51,749✔
953
  }
954

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1168
    for (int32_t j = pDumpInfo->rowIndex; rowIndex < dumpedRows; j += step, rowIndex++) {
24✔
1169
      uint8_t v = tColDataGetBitValue(pData, j);
12✔
1170
      if (v == 0 || v == 1) {
12!
1171
        colDataSetNull_f(pColData->nullbitmap, rowIndex);
2✔
1172
        pColData->hasNull = true;
2✔
1173
      }
1174
    }
1175
  }
1176
}
26✔
1177

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

1183
  if (pSupp->numOfPks > 0) {
2,215!
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;
2,215✔
1203
  record->maxVer = pBlockInfo->maxVer;
2,215✔
1204
  record->blockOffset = pBlockInfo->blockOffset;
2,215✔
1205
  record->smaOffset = pBlockInfo->smaOffset;
2,215✔
1206
  record->blockSize = pBlockInfo->blockSize;
2,215✔
1207
  record->blockKeySize = pBlockInfo->blockKeySize;
2,215✔
1208
  record->smaSize = pBlockInfo->smaSize;
2,215✔
1209
  record->numRow = pBlockInfo->numRow;
2,215✔
1210
  record->count = pBlockInfo->count;
2,215✔
1211
}
2,215✔
1212

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

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

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

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

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

UNCOV
1260
      if (pDumpInfo->rowIndex < 0) {
×
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

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

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

1314
  int32_t i = 0;
87✔
1315
  int32_t rowIndex = 0;
87✔
1316

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

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

1327
  int32_t colIndex = 0;
87✔
1328
  int32_t num = pBlockData->nColData;
87✔
1329
  while (i < numOfOutputCols && colIndex < num) {
125!
1330
    rowIndex = 0;
38✔
1331

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

1341
      if (pData->flag == HAS_NONE || pData->flag == HAS_NULL || pData->flag == (HAS_NULL | HAS_NONE)) {
38!
1342
        colDataSetNNULL(pColData, 0, dumpedRows);
10✔
1343
      } else {
1344
        if (IS_MATHABLE_TYPE(pColData->info.type)) {
28!
1345
          copyNumericCols(pData, pDumpInfo, pColData, dumpedRows, asc);
26✔
1346
        } else {  // varchar/nchar type
1347
          for (int32_t j = pDumpInfo->rowIndex; rowIndex < dumpedRows; j += step) {
250✔
1348
            tColDataGetValue(pData, j, &cv);
248✔
1349
            code = doCopyColVal(pColData, rowIndex++, i, &cv, pSupInfo);
248✔
1350
            if (code) {
248!
1351
              return code;
×
1352
            }
1353
          }
1354
        }
1355
      }
1356

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

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

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

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

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

1403
  int32_t unDumpedRows = asc ? pRecord->numRow - pDumpInfo->rowIndex : pDumpInfo->rowIndex + 1;
87✔
1404
  tsdbDebug("%p copy file block to sdatablock, global index:%d, table index:%d, brange:%" PRId64 "-%" PRId64
87✔
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;
87✔
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,
652✔
1437
                                   uint64_t uid) {
1438
  int32_t             code = 0;
652✔
1439
  STSchema*           pSchema = pReader->info.pSchema;
652✔
1440
  int64_t             st = taosGetTimestampUs();
652✔
1441
  SFileDataBlockInfo* pBlockInfo = NULL;
652✔
1442
  SBlockLoadSuppInfo* pSup = &pReader->suppInfo;
652✔
1443

1444
  tBlockDataReset(pBlockData);
652✔
1445

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

1461
  SFileBlockDumpInfo* pDumpInfo = &pReader->status.fBlockDumpInfo;
652✔
1462

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

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

1486
  return code;
652✔
1487
}
1488

1489
/**
1490
 * This is an two rectangles overlap cases.
1491
 */
1492
static int32_t dataBlockPartiallyRequired(STimeWindow* pWindow, SVersionRange* pVerRange, SFileDataBlockInfo* pBlock) {
1,326✔
1493
  return (pWindow->ekey < pBlock->lastKey && pWindow->ekey >= pBlock->firstKey) ||
8!
1494
         (pWindow->skey > pBlock->firstKey && pWindow->skey <= pBlock->lastKey) ||
1,318!
1495
         (pVerRange->minVer > pBlock->minVer && pVerRange->minVer <= pBlock->maxVer) ||
3,970!
1496
         (pVerRange->maxVer < pBlock->maxVer && pVerRange->maxVer >= pBlock->minVer);
1,318!
1497
}
1498

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

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

1509
  if (!asc && pBlockInfo->tbBlockIdx == 0) {
871✔
1510
    return false;
803✔
1511
  }
1512

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

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

1523
  blockInfoToRecord(pRecord, p, pSupInfo);
68✔
1524

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

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

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

1658
  return key;
188✔
1659
}
1660

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

1666
  return (ascScan && (keyInBuf.ts != TSKEY_INITIAL_VAL && keyInBuf.ts < key)) ||
376!
1667
         (!ascScan && (keyInBuf.ts != TSKEY_INITIAL_VAL && keyInBuf.ts > key));
188!
1668
}
1669

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

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

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

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

1691
  SBrinRecord pRecord;
1692
  blockInfoToRecord(&pRecord, pBlockInfo, pSupInfo);
1,326✔
1693

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

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

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

1720
  bool loadDataBlock =
757✔
1721
      (info.overlapWithNeighborBlock || info.hasDupTs || info.partiallyRequired || info.overlapWithKeyInBuf ||
757!
1722
       info.moreThanCapcity || info.overlapWithDelInfo || info.overlapWithSttBlock);
1,514!
1723

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

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

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

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

1757
  return code;
3,448,662✔
1758
}
1759

1760
static int32_t buildDataBlockFromBuf(STsdbReader* pReader, STableBlockScanInfo* pBlockScanInfo, int64_t endKey) {
488,798✔
1761
  if (!(pBlockScanInfo->iiter.hasVal || pBlockScanInfo->iter.hasVal)) {
488,798✔
1762
    return TSDB_CODE_SUCCESS;
329,479✔
1763
  }
1764

1765
  int32_t code = initRowMergeIfNeeded(pReader, pBlockScanInfo->uid);
159,319✔
1766
  if (code != 0) {
159,412!
1767
    return code;
×
1768
  }
1769

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

1774
  double el = (taosGetTimestampUs() - st) / 1000.0;
159,435✔
1775
  updateComposedBlockInfo(pReader, el, pBlockScanInfo);
159,435✔
1776

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

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

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

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

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

1811
  return code;
127✔
1812
}
1813

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

1821
  while (1) {
41,442✔
1822
    bool hasVal = false;
2,303,967✔
1823
    code = tMergeTreeNext(&pSttBlockReader->mergeTree, &hasVal);
2,303,967✔
1824
    if (code) {
2,304,213!
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;
2,262,622✔
1828
    }
1829

1830
    if (!hasVal) {  // the next value will be the accessed key in stt
2,304,392✔
1831
      pScanInfo->sttKeyInfo.status = STT_FILE_NO_DATA;
176,373✔
1832

1833
      // next file, the timestamps in the next file must be greater than those in current
1834
      pNextProc->ts += step;
176,373✔
1835
      if (pSttBlockReader->numOfPks > 0) {
176,373✔
1836
        if (IS_NUMERIC_TYPE(pNextProc->pks[0].type)) {
55,123!
1837
          pNextProc->pks[0].val = INT64_MIN;
55,121✔
1838
        } else {
1839
          memset(pNextProc->pks[0].pData, 0, pNextProc->pks[0].nData);
2✔
1840
        }
1841
      }
1842
      return code;
176,373✔
1843
    }
1844

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

1849
    if (pSttBlockReader->numOfPks == 0) {
2,128,019✔
1850
      pSttBlockReader->currentKey.ts = key;
1,455,496✔
1851
    } else {
1852
      tColRowGetKeyDeepCopy(pRow->pBlockData, pRow->iRow, pkSrcSlot, &pSttBlockReader->currentKey);
672,523✔
1853
    }
1854

1855
    tColRowGetKeyDeepCopy(pRow->pBlockData, pRow->iRow, pkSrcSlot, pNextProc);
2,128,019✔
1856

1857
    if (pScanInfo->delSkyline != NULL && TARRAY_SIZE(pScanInfo->delSkyline) > 0) {
2,127,990!
1858
      if (!hasBeenDropped(pScanInfo->delSkyline, &pScanInfo->sttBlockDelIndex, key, ver, order, pVerRange,
62,546✔
1859
                          pSttBlockReader->numOfPks > 0)) {
62,846✔
1860
        pScanInfo->sttKeyInfo.status = STT_FILE_HAS_DATA;
21,104✔
1861
        return code;
21,104✔
1862
      }
1863
    } else {
1864
      pScanInfo->sttKeyInfo.status = STT_FILE_HAS_DATA;
2,065,144✔
1865
      return code;
2,065,144✔
1866
    }
1867
  }
1868

1869
  return code;
1870
}
1871

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

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

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

1882
  // avoid the fetch next row replace the referenced stt block in buffer
1883
  doPinSttBlock(pSttBlockReader);
502,251✔
1884
  code = nextRowFromSttBlocks(pSttBlockReader, pScanInfo, pReader->suppInfo.pkSrcSlot, &pReader->info.verRange);
501,984✔
1885
  doUnpinSttBlock(pSttBlockReader);
502,079✔
1886

1887
  if (code) {
501,664✔
1888
    return code;
1✔
1889
  }
1890

1891
  if (hasDataInSttBlock(pScanInfo)) {
501,663✔
1892
    SRowKey* pNext = getCurrentKeyInSttBlock(pSttBlockReader);
497,401!
1893
    if (pkCompEx(pSttKey, pNext) != 0) {
497,409✔
1894
      code = doAppendRowFromFileBlock(pReader->resBlockInfo.pResBlock, pReader, fRow->pBlockData, fRow->iRow);
497,340✔
1895
      *copied = (code == TSDB_CODE_SUCCESS);
498,542✔
1896
      return code;
498,542✔
1897
    }
1898
  } else {
1899
    code = doAppendRowFromFileBlock(pReader->resBlockInfo.pResBlock, pReader, fRow->pBlockData, fRow->iRow);
4,252✔
1900
    *copied = (code == TSDB_CODE_SUCCESS);
4,273✔
1901
    return code;
4,273✔
1902
  }
1903

1904
  return code;
69✔
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) {
2,876,315!
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) {
62,226,322!
1917
    return pReader->info.pSchema;
62,224,540✔
1918
  }
1919

1920
  void** p = tSimpleHashGet(pReader->pSchemaMap, &sversion, sizeof(sversion));
1,782✔
1921
  if (p != NULL) {
751!
1922
    return *(STSchema**)p;
487✔
1923
  }
1924

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

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

1948
  SRowKey* pSttKey = NULL;
2,787,170✔
1949
  if (hasDataInSttBlock(pBlockScanInfo) && (!pBlockScanInfo->cleanSttBlocks)) {
2,787,170!
1950
    pSttKey = getCurrentKeyInSttBlock(pSttBlockReader);
2,786,941✔
1951
  }
1952

1953
  SRowKey k = {0};
2,786,788✔
1954
  tRowGetKeyEx(pRow, &k);
2,786,788✔
1955

1956
  STSchema* pSchema = NULL;
2,786,480✔
1957
  if (pRow->type == TSDBROW_ROW_FMT) {
2,786,480!
1958
    pSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(pRow), pReader, pBlockScanInfo->uid);
2,786,918!
1959
    if (pSchema == NULL) {
2,786,881!
1960
      return terrno;
×
1961
    }
1962
  }
1963

1964
  SRowKey* pfKey = &(SRowKey){0};
2,786,443✔
1965
  if (hasDataInFileBlock(pBlockData, pDumpInfo)) {
2,786,443!
UNCOV
1966
    tColRowGetKey(pBlockData, pDumpInfo->rowIndex, pfKey);
×
1967
  } else {
1968
    pfKey = NULL;
2,786,650✔
1969
  }
1970

1971
  TSDBROW fRow = tsdbRowFromBlockData(pBlockData, pDumpInfo->rowIndex);
2,786,609✔
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);
2,786,609✔
1975
  if (code != 0) {
2,786,501!
1976
    return code;
×
1977
  }
1978

1979
  SRowKey minKey = k;
2,786,501✔
1980
  if (pReader->info.order == TSDB_ORDER_ASC) {
2,786,501✔
1981
    if (pfKey != NULL && pkCompEx(pfKey, &minKey) < 0) {
2,408,463!
UNCOV
1982
      minKey = *pfKey;
×
1983
    }
1984

1985
    if (pSttKey != NULL && pkCompEx(pSttKey, &minKey) < 0) {
4,817,776✔
1986
      minKey = *pSttKey;
1,445,293✔
1987
    }
1988
  } else {
1989
    if (pfKey != NULL && pkCompEx(pfKey, &minKey) > 0) {
378,038!
1990
      minKey = *pfKey;
×
1991
    }
1992

1993
    if (pSttKey != NULL && pkCompEx(pSttKey, &minKey) > 0) {
756,706!
1994
      minKey = *pSttKey;
126,143✔
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);
2,787,463✔
2001

2002
  // file block ---> stt block -----> mem
2003
  if (pkCompEx(&minKey, pfKey) == 0) {
2,785,966!
UNCOV
2004
    code = tsdbRowMergerAdd(pMerger, &fRow, NULL);
×
UNCOV
2005
    if (code != TSDB_CODE_SUCCESS) {
×
2006
      return code;
×
2007
    }
2008

UNCOV
2009
    code = doMergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pfKey, pReader);
×
UNCOV
2010
    if (code != TSDB_CODE_SUCCESS) {
×
2011
      return code;
×
2012
    }
2013
  }
2014

2015
  if (pkCompEx(&minKey, pSttKey) == 0) {
2,787,724✔
2016
    TSDBROW* fRow1 = tMergeTreeGetRow(&pSttBlockReader->mergeTree);
1,584,034✔
2017
    code = tsdbRowMergerAdd(pMerger, fRow1, NULL);
1,584,034✔
2018
    if (code != TSDB_CODE_SUCCESS) {
1,584,116✔
2019
      return code;
16✔
2020
    }
2021
    code = doMergeRowsInSttBlock(pSttBlockReader, pBlockScanInfo, pMerger, pkSrcSlot, &pReader->info.verRange, pReader->idStr);
1,584,100✔
2022
    if (code != TSDB_CODE_SUCCESS) {
1,583,945!
2023
      return code;
×
2024
    }
2025
  }
2026

2027
  if (pkCompEx(&minKey, &k) == 0) {
2,787,366✔
2028
    code = tsdbRowMergerAdd(pMerger, pRow, pSchema);
1,216,077✔
2029
    if (code != TSDB_CODE_SUCCESS) {
1,215,999✔
2030
      return code;
68✔
2031
    }
2032

2033
    code = doMergeRowsInBuf(pIter, pBlockScanInfo->uid, &k, pBlockScanInfo->delSkyline, pReader);
1,215,931✔
2034
    if (code != TSDB_CODE_SUCCESS) {
1,216,030!
2035
      return code;
×
2036
    }
2037
  }
2038

2039
  code = tsdbRowMergerGetRow(pMerger, &pTSRow);
2,787,319✔
2040
  if (code != TSDB_CODE_SUCCESS) {
2,787,374✔
2041
    return code;
99✔
2042
  }
2043

2044
  code = doAppendRowFromTSRow(pReader->resBlockInfo.pResBlock, pReader, pTSRow, pBlockScanInfo);
2,787,275✔
2045

2046
  taosMemoryFree(pTSRow);
2,785,678✔
2047
  tsdbRowMergerClear(pMerger);
2,788,247✔
2048

2049
  return code;
2,784,648✔
2050
}
2051

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

2065
  bool dataInDataFile = hasDataInFileBlock(pBlockData, pDumpInfo);
502,701✔
2066
  bool dataInSttFile = hasDataInSttBlock(pBlockScanInfo);
502,419✔
2067

2068
  if (dataInDataFile && (!dataInSttFile)) {
502,419!
2069
    // no stt file block available, only data block exists
2070
    return mergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pKey, pReader);
127✔
2071
  } else if ((!dataInDataFile) && dataInSttFile) {
502,292!
2072
    // no data in data file exists
2073
    return mergeRowsInSttBlocks(pSttBlockReader, pBlockScanInfo, pReader);
502,292✔
2074
  } else if (pBlockScanInfo->cleanSttBlocks && pReader->info.execMode == READER_EXEC_ROWS) {
×
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);
×
2080
    SRowKey* pSttKey = getCurrentKeyInSttBlock(pSttBlockReader);
×
2081

2082
    int32_t ret = pkCompEx(pKey, pSttKey);
×
2083

2084
    if (ASCENDING_TRAVERSE(pReader->info.order)) {
×
2085
      if (ret < 0) {  // asc
×
2086
        return mergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pKey, pReader);
×
2087
      } else if (ret > 0) {
×
2088
        return mergeRowsInSttBlocks(pSttBlockReader, pBlockScanInfo, pReader);
×
2089
      }
2090
    } else {  // desc
2091
      if (ret > 0) {
×
2092
        return mergeRowsInFileBlocks(pBlockData, pBlockScanInfo, pKey, pReader);
×
2093
      } else if (ret < 0) {
×
2094
        return mergeRowsInSttBlocks(pSttBlockReader, pBlockScanInfo, pReader);
×
2095
      }
2096
    }
2097

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

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

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

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

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

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

2133
    taosMemoryFree(pTSRow);
×
2134
    tsdbRowMergerClear(pMerger);
×
2135
    return code;
×
2136
  }
2137
}
2138

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

UNCOV
2150
  getValidMemRow(&pBlockScanInfo->iter, pDelList, pReader, &pRow);
×
UNCOV
2151
  getValidMemRow(&pBlockScanInfo->iiter, pDelList, pReader, &piRow);
×
2152

UNCOV
2153
  SRowKey* pSttKey = NULL;
×
UNCOV
2154
  if (hasDataInSttBlock(pBlockScanInfo) && (!pBlockScanInfo->cleanSttBlocks)) {
×
UNCOV
2155
    pSttKey = getCurrentKeyInSttBlock(pSttBlockReader);
×
2156
  }
2157

UNCOV
2158
  SRowKey* pfKey = &(SRowKey){0};
×
UNCOV
2159
  if (hasDataInFileBlock(pBlockData, pDumpInfo)) {
×
2160
    tColRowGetKey(pBlockData, pDumpInfo->rowIndex, pfKey);
×
2161
  } else {
UNCOV
2162
    pfKey = NULL;
×
2163
  }
2164

UNCOV
2165
  SRowKey k = {0}, ik = {0};
×
UNCOV
2166
  tRowGetKeyEx(pRow, &k);
×
UNCOV
2167
  tRowGetKeyEx(piRow, &ik);
×
2168

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

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

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

UNCOV
2191
  SRowKey minKey = k;
×
UNCOV
2192
  if (ASCENDING_TRAVERSE(pReader->info.order)) {
×
2193
    if (pkCompEx(&ik, &minKey) < 0) {  // minKey > ik.key.ts) {
×
2194
      minKey = ik;
×
2195
    }
2196

2197
    if ((pfKey != NULL) && (pkCompEx(pfKey, &minKey) < 0)) {
×
2198
      minKey = *pfKey;
×
2199
    }
2200

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

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

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

UNCOV
2218
  tRowKeyAssign(&pBlockScanInfo->lastProcKey, &minKey);
×
2219

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

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

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

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

UNCOV
2247
  if (pkCompEx(&minKey, &ik) == 0) {
×
UNCOV
2248
    code = tsdbRowMergerAdd(pMerger, piRow, piSchema);
×
UNCOV
2249
    if (code != TSDB_CODE_SUCCESS) {
×
2250
      return code;
×
2251
    }
2252

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

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

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

UNCOV
2271
  code = tsdbRowMergerGetRow(pMerger, &pTSRow);
×
UNCOV
2272
  if (code != TSDB_CODE_SUCCESS) {
×
2273
    return code;
×
2274
  }
2275

UNCOV
2276
  code = doAppendRowFromTSRow(pReader->resBlockInfo.pResBlock, pReader, pTSRow, pBlockScanInfo);
×
2277

UNCOV
2278
  taosMemoryFree(pTSRow);
×
UNCOV
2279
  tsdbRowMergerClear(pMerger);
×
UNCOV
2280
  return code;
×
2281
}
2282

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

2289
  if (pMem != NULL) {
784,719✔
2290
    *pData = tsdbGetTbDataFromMemTable(pMem, pReader->info.suid, pBlockScanInfo->uid);
373,845✔
2291

2292
    if ((*pData) != NULL) {
373,926✔
2293
      code = tsdbTbDataIterCreate((*pData), pKey, backward, &pIter->iter);
161,231✔
2294
      if (code == TSDB_CODE_SUCCESS) {
161,198✔
2295
        pIter->hasVal = (tsdbTbDataIterGet(pIter->iter) != NULL);
161,195!
2296

2297
        tsdbDebug("%p uid:%" PRIu64 ", check data in %s from skey:%" PRId64 ", order:%d, ts range in buf:%" PRId64
161,195✔
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,
3!
2303
                  type, tstrerror(code), pReader->idStr);
2304
        return code;
6✔
2305
      }
2306
    }
2307
  } else {
2308
    tsdbDebug("%p uid:%" PRIu64 ", no data in %s, %s", pReader, pBlockScanInfo->uid, type, pReader->idStr);
410,874✔
2309
  }
2310

2311
  return code;
784,815✔
2312
}
2313

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

2319
  while (1) {
4✔
2320
    getValidMemRow(pIter, pBlockScanInfo->delSkyline, pReader, &pRow);
37,036✔
2321
    if (!pIter->hasVal) {
37,036✔
2322
      break;
30,165✔
2323
    }
2324

2325
    tRowGetKeyEx(pRow, &rowKey);
6,871✔
2326
    int32_t ret = pkCompEx(pKey, &rowKey);
6,869✔
2327
    if (ret == 0) {
6,869!
2328
      pIter->hasVal = tsdbTbDataIterNext(pIter->iter);
×
2329
    } else {
2330
      break;
6,869✔
2331
    }
2332
  }
2333
}
37,034✔
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) {
18,517✔
2337
  doForwardDataIter(pKey, &pBlockScanInfo->iter, pBlockScanInfo, pReader);
18,517✔
2338
  doForwardDataIter(pKey, &pBlockScanInfo->iiter, pBlockScanInfo, pReader);
18,516✔
2339
}
18,518✔
2340

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

2349
  if (pBlockScanInfo->iterInit) {
691,592✔
2350
    return TSDB_CODE_SUCCESS;
299,317✔
2351
  }
2352

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

2361
  int32_t code = doInitMemDataIter(pReader, &d, pBlockScanInfo, &startKey, pSnap->pMem, &pBlockScanInfo->iter, "mem");
392,275✔
2362
  if (code != TSDB_CODE_SUCCESS) {
392,427✔
2363
    return code;
6✔
2364
  }
2365

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

2371
  code = loadMemTombData(&pBlockScanInfo->pMemDelData, d, di, pReader->info.verRange.maxVer);
392,446✔
2372
  if (code != TSDB_CODE_SUCCESS) {
392,489✔
2373
    return code;
60✔
2374
  }
2375

2376
  if (forward) {
392,429✔
2377
    forwardDataIter(&startKey.key, pBlockScanInfo, pReader);
18,518✔
2378
  }
2379

2380
  pBlockScanInfo->iterInit = true;
392,436✔
2381
  return TSDB_CODE_SUCCESS;
392,436✔
2382
}
2383

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

2400
  int64_t ts = pBlockData->aTSKEY[rowIndex];
83,386✔
2401
  if (ts > pInfo->window.ekey || ts < pInfo->window.skey) {
83,386!
2402
    return false;
×
2403
  }
2404

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

2409
  if (ts == pBlockScanInfo->lastProcKey.ts) {  // todo opt perf
83,386!
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) {
83,386!
2418
    bool dropped = hasBeenDropped(pBlockScanInfo->delSkyline, &pBlockScanInfo->fileDelIndex, ts, ver, pInfo->order,
83,386✔
2419
                                  &pInfo->verRange, pReader->suppInfo.numOfPks > 0);
83,386✔
2420
    if (dropped) {
83,386✔
2421
      return false;
83,259✔
2422
    }
2423
  }
2424

2425
  return true;
127✔
2426
}
2427

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

2432
  // the stt block reader has been initialized for this table.
2433
  if (pSttBlockReader->uid == pScanInfo->uid) {
259,489✔
2434
    return;
56,742✔
2435
  }
2436

2437
  if (pSttBlockReader->uid != 0) {
202,831✔
2438
    tMergeTreeClose(&pSttBlockReader->mergeTree);
155,405✔
2439
  }
2440

2441
  pSttBlockReader->uid = pScanInfo->uid;
202,857✔
2442

2443
  // second or third time init stt block reader
2444
  if (pScanInfo->cleanSttBlocks && (pReader->info.execMode == READER_EXEC_ROWS)) {
202,857!
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;
202,857✔
2454
  if (asc) {
202,857✔
2455
    w.skey = pScanInfo->sttKeyInfo.nextProcKey.ts;
175,439✔
2456
  } else {
2457
    w.ekey = pScanInfo->sttKeyInfo.nextProcKey.ts;
27,418✔
2458
  }
2459

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

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

2484
  SSttDataInfoForTable info = {.pKeyRangeList = taosArrayInit(4, sizeof(SSttKeyRange))};
202,871✔
2485
  if (info.pKeyRangeList == NULL) {
202,894✔
2486
    pReader->code = terrno;
19✔
2487
    return;
19✔
2488
  }
2489

2490
  int32_t code = tMergeTreeOpen2(&pSttBlockReader->mergeTree, &conf, &info);
202,875✔
2491
  if (code != TSDB_CODE_SUCCESS) {
202,873✔
2492
    taosArrayDestroy(info.pKeyRangeList);
48✔
2493
    pReader->code = code;
48✔
2494
    return;
48✔
2495
  }
2496

2497
  code = initMemDataIterator(pScanInfo, pReader);
202,825✔
2498
  if (code != TSDB_CODE_SUCCESS) {
202,829✔
2499
    taosArrayDestroy(info.pKeyRangeList);
17✔
2500
    pReader->code = code;
17✔
2501
    return;
17✔
2502
  }
2503

2504
  code = initDelSkylineIterator(pScanInfo, pReader->info.order, &pReader->cost);
202,812✔
2505
  if (code != TSDB_CODE_SUCCESS) {
202,813!
UNCOV
2506
    taosArrayDestroy(info.pKeyRangeList);
×
2507
    pReader->code = code;
×
2508
    return;
×
2509
  }
2510

2511
  if (conf.rspRows) {
202,814✔
2512
    pScanInfo->cleanSttBlocks = isCleanSttBlock(info.pKeyRangeList, &pReader->info.window, pScanInfo, order);
83,888✔
2513
    if (pScanInfo->cleanSttBlocks) {
83,885✔
2514
      pScanInfo->numOfRowsInStt = info.numOfRows;
26,252✔
2515

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

2523
        if (pkCompEx(&pScanInfo->sttRange.skey, &pKeyRange->skey) > 0) {
52,502!
2524
          tRowKeyAssign(&pScanInfo->sttRange.skey, &pKeyRange->skey);
26,251✔
2525
        }
2526

2527
        if (pkCompEx(&pScanInfo->sttRange.ekey, &pKeyRange->ekey) < 0) {
52,502!
2528
          tRowKeyAssign(&pScanInfo->sttRange.ekey, &pKeyRange->ekey);
26,250✔
2529
        }
2530
      }
2531

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

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

2546
  pScanInfo->sttBlockReturned = false;
202,806✔
2547
  taosArrayDestroy(info.pKeyRangeList);
202,806✔
2548

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

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

2558
static bool hasDataInSttBlock(STableBlockScanInfo* pInfo) { return pInfo->sttKeyInfo.status == STT_FILE_HAS_DATA; }
8,936,622✔
2559

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

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

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

2584
  tRowKeyAssign(&pBlockScanInfo->lastProcKey, pKey);
127✔
2585

2586
  if (copied) {
127✔
2587
    return TSDB_CODE_SUCCESS;
126✔
2588
  } else {
2589
    TSDBROW fRow = tsdbRowFromBlockData(pBlockData, pDumpInfo->rowIndex);
1✔
2590

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

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

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

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

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

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

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

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

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

2639
  if (copied) {
502,797✔
2640
    return TSDB_CODE_SUCCESS;
502,796✔
2641
  } else {
2642
    code = tsdbRowMergerAdd(pMerger, &fRow, NULL);
1✔
2643
    if (code != TSDB_CODE_SUCCESS) {
2!
2644
      return code;
×
2645
    }
2646

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

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

2658
    code = tsdbRowMergerGetRow(pMerger, &pTSRow);
2✔
2659
    if (code != TSDB_CODE_SUCCESS) {
2!
2660
      return code;
×
2661
    }
2662

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

2665
    taosMemoryFree(pTSRow);
2✔
2666
    tsdbRowMergerClear(pMerger);
2✔
2667
    return code;
1✔
2668
  }
2669
}
2670

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

2675
  TSDBROW *pRow = NULL, *piRow = NULL;
3,287,617✔
2676

2677
  SRowKey* pKey = &(SRowKey){0};
3,287,617✔
2678
  if (hasDataInFileBlock(pBlockData, pDumpInfo)) {
3,287,617✔
2679
    tColRowGetKey(pBlockData, pDumpInfo->rowIndex, pKey);
93!
2680
  } else {
2681
    pKey = NULL;
3,287,924✔
2682
  }
2683

2684
  if (pBlockScanInfo->iter.hasVal) {
3,289,658✔
2685
    getValidMemRow(&pBlockScanInfo->iter, pBlockScanInfo->delSkyline, pReader, &pRow);
2,780,503✔
2686
  }
2687

2688
  if (pBlockScanInfo->iiter.hasVal) {
3,289,703✔
2689
    getValidMemRow(&pBlockScanInfo->iiter, pBlockScanInfo->delSkyline, pReader, &piRow);
5,036✔
2690
  }
2691

2692
  // two levels of mem-table does contain the valid rows
2693
  if (pRow != NULL && piRow != NULL) {
3,289,703!
UNCOV
2694
    return doMergeMultiLevelRows(pReader, pBlockScanInfo, pBlockData, pSttBlockReader);
×
2695
  }
2696

2697
  // imem + file + stt block
2698
  if (pBlockScanInfo->iiter.hasVal) {
3,289,703✔
2699
    return doMergeBufAndFileRows(pReader, pBlockScanInfo, piRow, &pBlockScanInfo->iiter, pSttBlockReader);
5,036✔
2700
  }
2701

2702
  // mem + file + stt block
2703
  if (pBlockScanInfo->iter.hasVal) {
3,284,667✔
2704
    return doMergeBufAndFileRows(pReader, pBlockScanInfo, pRow, &pBlockScanInfo->iter, pSttBlockReader);
2,782,346✔
2705
  }
2706

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

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

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

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

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

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

2766
  int32_t code = blockDataUpdateTsWindow(pResBlock, pReader->suppInfo.slotId[0]);
190,464✔
2767
  code = blockDataUpdatePkRange(pResBlock, pReader->suppInfo.pkDstSlot, ASCENDING_TRAVERSE(pReader->info.order));
190,480✔
2768
  setComposedBlockFlag(pReader, true);
190,465✔
2769

2770
  pReader->cost.composedBlocks += 1;
190,443✔
2771
  pReader->cost.buildComposedBlockTime += el;
190,443✔
2772
}
190,443✔
2773

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

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

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

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

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

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

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

2821
  while (1) {
126✔
2822
    bool hasBlockData = false;
691✔
2823
    {
2824
      while (pBlockData->nRow > 0 && pBlockData->uid == pBlockScanInfo->uid) {
83,386!
2825
        // find the first qualified row in data block
2826
        if (isValidFileBlockRow(pBlockData, pDumpInfo->rowIndex, pBlockScanInfo, asc, &pReader->info, pReader)) {
83,386✔
2827
          hasBlockData = true;
127✔
2828
          break;
127✔
2829
        }
2830

2831
        pDumpInfo->rowIndex += step;
83,259✔
2832

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

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

2857
    code = buildComposedDataBlockImpl(pReader, pBlockScanInfo, pBlockData, pSttBlockReader);
127✔
2858
    if (code) {
127!
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)) {
127!
2864
      setBlockAllDumped(pDumpInfo, pBlockInfo->lastKey, pReader->info.order);
1✔
2865
      break;
1✔
2866
    }
2867

2868
    if (pResBlock->info.rows >= pReader->resBlockInfo.capacity) {
126!
2869
      break;
×
2870
    }
2871
  }
2872

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

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

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

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

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

2897
int32_t initDelSkylineIterator(STableBlockScanInfo* pBlockScanInfo, int32_t order, SReadCostSummary* pCost) {
691,649✔
2898
  int32_t code = 0;
691,649✔
2899
  int32_t newDelDataInFile = taosArrayGetSize(pBlockScanInfo->pFileDelData);
691,649✔
2900
  if (newDelDataInFile == 0 &&
691,656✔
2901
      ((pBlockScanInfo->delSkyline != NULL) || (TARRAY_SIZE(pBlockScanInfo->pMemDelData) == 0))) {
688,569✔
2902
    return code;
680,726✔
2903
  }
2904

2905
  int64_t st = taosGetTimestampUs();
10,952✔
2906

2907
  if (pBlockScanInfo->delSkyline != NULL) {
10,952✔
2908
    taosArrayClear(pBlockScanInfo->delSkyline);
2,366✔
2909
  } else {
2910
    pBlockScanInfo->delSkyline = taosArrayInit(4, sizeof(TSDBKEY));
8,586✔
2911
    if (pBlockScanInfo->delSkyline == NULL) {
8,586✔
2912
      return terrno;
1✔
2913
    }
2914
  }
2915

2916
  SArray* pSource = pBlockScanInfo->pFileDelData;
10,950✔
2917
  if (pSource == NULL) {
10,950✔
2918
    pSource = pBlockScanInfo->pMemDelData;
7,837✔
2919
  } else {
2920
    void* p1 = taosArrayAddAll(pSource, pBlockScanInfo->pMemDelData);
3,113✔
2921
    if (p1 == NULL) {
3,113!
2922
      return terrno;
×
2923
    }
2924
  }
2925

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

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

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

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

2939
  return code;
10,951✔
2940
}
2941

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

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

2950
  getValidMemRow(&pScanInfo->iter, pScanInfo->delSkyline, pReader, &pRow);
1,326✔
2951
  if (pRow != NULL) {
1,326!
UNCOV
2952
    hasKey = true;
×
UNCOV
2953
    key = TSDBROW_KEY(pRow);
×
2954
  }
2955

2956
  getValidMemRow(&pScanInfo->iiter, pScanInfo->delSkyline, pReader, &pIRow);
1,326✔
2957
  if (pIRow != NULL) {
1,326!
UNCOV
2958
    hasIKey = true;
×
UNCOV
2959
    ikey = TSDBROW_KEY(pIRow);
×
2960
  }
2961

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

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

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

2990
  if (ASCENDING_TRAVERSE(pReader->info.order)) {
13,659✔
2991
    pReader->status.bProcMemPreFileset = !(pReader->status.memTableMaxKey < pReader->status.prevFilesetStartKey ||
22,190✔
2992
                                           (winFid.skey - 1) < pReader->status.memTableMinKey);
8,913✔
2993
  } else {
2994
    pReader->status.bProcMemPreFileset = !(pReader->status.memTableMaxKey < (winFid.ekey + 1) ||
569✔
2995
                                           pReader->status.prevFilesetEndKey < pReader->status.memTableMinKey);
187!
2996
  }
2997

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

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

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

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

3022
  size_t  numOfTables = tSimpleHashGetSize(pReader->status.pTableMap);
74,251✔
3023
  SArray* pIndexList = taosArrayInit(numOfTables, sizeof(SBrinBlk));
74,251✔
3024
  if (pIndexList == NULL) {
74,251✔
3025
    return terrno;
6✔
3026
  }
3027

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

3035
    bool    hasNext = false;
74,536✔
3036
    int32_t code = filesetIteratorNext(&pStatus->fileIter, pReader, &hasNext);
74,536✔
3037
    if (code != TSDB_CODE_SUCCESS) {
74,526!
3038
      taosArrayDestroy(pIndexList);
×
3039
      return code;
3✔
3040
    }
3041

3042
    if (!hasNext) {  // no data files on disk
74,526✔
3043
      break;
21,823✔
3044
    }
3045

3046
    taosArrayClear(pIndexList);
52,703✔
3047
    code = doLoadBlockIndex(pReader, pReader->pFileReader, pIndexList);
52,702✔
3048
    if (code != TSDB_CODE_SUCCESS) {
52,695!
3049
      taosArrayDestroy(pIndexList);
×
3050
      return code;
×
3051
    }
3052

3053
    if (taosArrayGetSize(pIndexList) > 0 || pReader->status.pCurrentFileset->lvlArr->size > 0) {
52,695✔
3054
      code = loadFileBlockBrinInfo(pReader, pIndexList, pBlockNum, pTableList);
52,506✔
3055
      if (code != TSDB_CODE_SUCCESS) {
52,494✔
3056
        taosArrayDestroy(pIndexList);
1✔
3057
        return code;
1✔
3058
      }
3059

3060
      if (pBlockNum->numOfBlocks + pBlockNum->numOfSttFiles > 0) {
52,493✔
3061
        if (pReader->bFilesetDelimited) {
52,393✔
3062
          prepareDurationForNextFileSet(pReader);
13,660✔
3063
        }
3064
        break;
52,377✔
3065
      }
3066
    }
3067

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

3071
  taosArrayDestroy(pIndexList);
74,200✔
3072
  return loadDataFileTombDataForAll(pReader);
74,231✔
3073
}
3074

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

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

3087
  return 0;
197,102✔
3088
}
3089

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

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

3098
static bool moveToNextTable(STableUidList* pOrderedCheckInfo, SReaderStatus* pStatus) {
530,021✔
3099
  pOrderedCheckInfo->currentIndex += 1;
530,021✔
3100
  if (pOrderedCheckInfo->currentIndex >= tSimpleHashGetSize(pStatus->pTableMap)) {
530,021✔
3101
    pStatus->pTableIter = NULL;
158,636✔
3102
    return false;
158,636✔
3103
  }
3104

3105
  uint64_t uid = pOrderedCheckInfo->tableUidList[pOrderedCheckInfo->currentIndex];
371,408✔
3106
  pStatus->pTableIter = tSimpleHashGet(pStatus->pTableMap, &uid, sizeof(uid));
371,408✔
3107
  return (pStatus->pTableIter != NULL);
371,455✔
3108
}
3109

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

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

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

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

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

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

3142
  setComposedBlockFlag(pReader, true);
26,252✔
3143

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

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

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

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

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

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

3175
  if (pReader->suppInfo.numOfPks > 0) {
188!
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);
188✔
3190
  setBlockAllDumped(&pStatus->fBlockDumpInfo, pBlockInfo->lastKey, pReader->info.order);
188✔
3191
  updateLastKeyInfo(&pScanInfo->lastProcKey, pBlockInfo, pInfo, pReader->suppInfo.numOfPks, asc);
188✔
3192

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

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

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

3210
  SSDataBlock* pResBlock = pReader->resBlockInfo.pResBlock;
103,682✔
3211

3212
  while (1) {
155,928✔
3213
    if (pReader->code != TSDB_CODE_SUCCESS) {
259,610!
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;
259,610✔
3220
    if (pStatus->pTableIter == NULL) {
259,610!
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;
259,610✔
3230
    }
3231

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

3239
      continue;
1,337✔
3240
    }
3241

3242
    initSttBlockReader(pSttBlockReader, pScanInfo, pReader);
258,261✔
3243
    if (pReader->code != TSDB_CODE_SUCCESS) {
258,286✔
3244
      return pReader->code;
84✔
3245
    }
3246
    
3247
    if (!hasDataInSttBlock(pScanInfo)) {
258,202✔
3248
      bool hasNexTable = moveToNextTable(pUidList, pStatus);
201,302✔
3249
      if (!hasNexTable) {
201,294✔
3250
        return TSDB_CODE_SUCCESS;
46,709✔
3251
      }
3252

3253
      continue;
154,585✔
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) {
56,901✔
3258
      code = buildCleanBlockFromSttFiles(pReader, pScanInfo);
26,250✔
3259
      return code;
26,251✔
3260
    }
3261

3262
    int64_t st = taosGetTimestampUs();
30,661✔
3263
    while (1) {
3264
      // no data in stt block and block, no need to proceed.
3265
      if (!hasDataInSttBlock(pScanInfo)) {
3,317,819✔
3266
        break;
30,387✔
3267
      }
3268

3269
      code = buildComposedDataBlockImpl(pReader, pScanInfo, &pReader->status.fileBlockData, pSttBlockReader);
3,287,390✔
3270
      if (code) {
3,287,431✔
3271
        return code;
185✔
3272
      }
3273

3274
      if (pResBlock->info.rows >= pReader->resBlockInfo.capacity) {
3,287,246✔
3275
        break;
88✔
3276
      }
3277
    }
3278

3279
    double el = (taosGetTimestampUs() - st) / 1000.0;
30,475✔
3280
    updateComposedBlockInfo(pReader, el, pScanInfo);
30,475✔
3281

3282
    if (pResBlock->info.rows > 0) {
30,474!
3283
      tsdbDebug("%p uid:%" PRIu64 ", composed data block created, brange:%" PRIu64 "-%" PRIu64 " rows:%" PRId64
30,474✔
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;
30,474✔
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;
×
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) {
188✔
3300
  if ((!hasDataInSttBlock(pScanInfo)) || (pScanInfo->cleanSttBlocks == true)) {
188!
3301
    return true;
188✔
3302
  } else {
3303
    int64_t keyInStt = pScanInfo->sttKeyInfo.nextProcKey.ts;
×
3304
    return (asc && pBlockInfo->lastKey < keyInStt) || (!asc && pBlockInfo->firstKey > keyInStt);
×
3305
  }
3306
}
3307

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

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

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

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

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

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

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

3350
    // build composed data block
3351
    code = buildComposedDataBlock(pReader);
569✔
3352
  } else if (bufferDataInFileBlockGap(keyInBuf, pBlockInfo, pScanInfo, pReader->info.order)) {
188!
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
UNCOV
3355
    int64_t endKey = getBoarderKeyInFiles(pBlockInfo, pScanInfo, pReader->info.order);
×
UNCOV
3356
    code = buildDataBlockFromBuf(pReader, pScanInfo, endKey);
×
3357
  } else {
3358
    if (notOverlapWithFiles(pBlockInfo, pScanInfo, asc)) {
188!
3359
      int64_t keyInStt = pScanInfo->sttKeyInfo.nextProcKey.ts;
188✔
3360

3361
      if ((!hasDataInSttBlock(pScanInfo)) || (asc && pBlockInfo->lastKey < keyInStt) ||
188!
3362
          (!asc && pBlockInfo->firstKey > keyInStt)) {
×
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);
188✔
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;
×
3376
      tBlockDataReset(pBData);
×
3377

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

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

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

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

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

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

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

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

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

3435
  while (1) {
12,583✔
3436
    if (pReader->code != TSDB_CODE_SUCCESS) {
17,133!
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;
17,133✔
3442
    if (pReader->pIgnoreTables &&
34,266!
3443
        taosHashGet(*pReader->pIgnoreTables, &(*pBlockScanInfo)->uid, sizeof((*pBlockScanInfo)->uid))) {
17,133✔
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);
17,133✔
3452
    if (code != TSDB_CODE_SUCCESS) {
17,132!
3453
      return code;
×
3454
    }
3455

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

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

3466
    if (pReader->resBlockInfo.pResBlock->info.rows > 0) {
17,133✔
3467
      return TSDB_CODE_SUCCESS;
538✔
3468
    }
3469

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

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

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

3484
  while (1) {
215,499✔
3485
    if (pReader->code != TSDB_CODE_SUCCESS) {
478,170!
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;
478,170✔
3491
    if (pBlockScanInfo == NULL || *pBlockScanInfo == NULL) {
478,170!
3492
      return TSDB_CODE_SUCCESS;
×
3493
    }
3494

3495
    if (pReader->pIgnoreTables &&
955,754✔
3496
        taosHashGet(*pReader->pIgnoreTables, &(*pBlockScanInfo)->uid, sizeof((*pBlockScanInfo)->uid))) {
477,628✔
3497
      bool hasNexTable = moveToNextTable(pUidList, pStatus);
6,432✔
3498
      if (!hasNexTable) {
6,432✔
3499
        return TSDB_CODE_SUCCESS;
63✔
3500
      }
3501
      continue;
6,369✔
3502
    }
3503

3504
    int32_t code = initMemDataIterator(*pBlockScanInfo, pReader);
471,694✔
3505
    if (code != TSDB_CODE_SUCCESS) {
471,802✔
3506
      return code;
49✔
3507
    }
3508

3509
    code = initDelSkylineIterator(*pBlockScanInfo, pReader->info.order, &pReader->cost);
471,753✔
3510
    if (code != TSDB_CODE_SUCCESS) {
471,713✔
3511
      return code;
2✔
3512
    }
3513

3514
    code = buildDataBlockFromBuf(pReader, *pBlockScanInfo, endKey);
471,711✔
3515
    if (code != TSDB_CODE_SUCCESS) {
471,703✔
3516
      return code;
15✔
3517
    }
3518

3519
    if (pReader->resBlockInfo.pResBlock->info.rows > 0) {
471,688✔
3520
      return TSDB_CODE_SUCCESS;
150,778✔
3521
    }
3522

3523
    // current table is exhausted, let's try next table
3524
    bool hasNexTable = moveToNextTable(pUidList, pStatus);
320,910✔
3525
    if (!hasNexTable) {
320,975✔
3526
      return TSDB_CODE_SUCCESS;
111,845✔
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) {
52,512✔
3533
  SFileDataBlockInfo* pBlockInfo = NULL;
52,512✔
3534
  SReaderStatus*      pStatus = &pReader->status;
52,512✔
3535
  SFileBlockDumpInfo* pDumpInfo = &pStatus->fBlockDumpInfo;
52,512✔
3536

3537
  int32_t code = getCurrentBlockInfo(pBlockIter, &pBlockInfo, pReader->idStr);
52,512✔
3538
  if (code == TSDB_CODE_SUCCESS) {
52,513✔
3539
    pDumpInfo->totalRows = pBlockInfo->numRow;
763✔
3540
    pDumpInfo->rowIndex = ASCENDING_TRAVERSE(pReader->info.order) ? 0 : pBlockInfo->numRow - 1;
763✔
3541
  } else {
3542
    pDumpInfo->totalRows = 0;
51,750✔
3543
    pDumpInfo->rowIndex = 0;
51,750✔
3544
  }
3545

3546
  pDumpInfo->allDumped = false;
52,513✔
3547
}
52,513✔
3548

3549
static int32_t initForFirstBlockInFile(STsdbReader* pReader, SDataBlockIter* pBlockIter) {
74,248✔
3550
  SBlockNumber num = {0};
74,248✔
3551
  SArray*      pTableList = taosArrayInit(40, POINTER_BYTES);
74,248✔
3552
  if (pTableList == NULL) {
74,259✔
3553
    return terrno;
10✔
3554
  }
3555

3556
  int32_t code = moveToNextFile(pReader, &num, pTableList);
74,249✔
3557
  if (code != TSDB_CODE_SUCCESS) {
74,223✔
3558
    taosArrayDestroy(pTableList);
4✔
3559
    return code;
11✔
3560
  }
3561

3562
  // all data files are consumed, try data in buffer
3563
  if (num.numOfBlocks + num.numOfSttFiles == 0) {
74,219✔
3564
    pReader->status.loadFromFile = false;
21,821✔
3565
    taosArrayDestroy(pTableList);
21,821✔
3566
    return code;
21,822✔
3567
  }
3568

3569
  // initialize the block iterator for a new fileset
3570
  if (num.numOfBlocks > 0) {
52,398✔
3571
    code = initBlockIterator(pReader, pBlockIter, num.numOfBlocks, pTableList);
635✔
3572
  } else {  // no block data, only last block exists
3573
    tBlockDataReset(&pReader->status.fileBlockData);
51,763✔
3574
    code = resetDataBlockIterator(pBlockIter, pReader->info.order, shouldFreePkBuf(&pReader->suppInfo), pReader->idStr);
51,737✔
3575
    if (code) {
51,755!
3576
      return code;
×
3577
    }
3578

3579
    code = resetTableListIndex(&pReader->status, pReader->idStr);
51,755✔
3580
    if (code) {
51,763!
3581
      return code;
×
3582
    }
3583
  }
3584

3585
  if (code == TSDB_CODE_SUCCESS) { // set the correct start position according to the query time window
52,398✔
3586
    initBlockDumpInfo(pReader, pBlockIter);
52,384✔
3587
  }
3588

3589
  taosArrayDestroy(pTableList);
52,404✔
3590
  return code;
52,408✔
3591
}
3592

3593
static bool fileBlockPartiallyRead(SFileBlockDumpInfo* pDumpInfo, bool asc) {
1,025✔
3594
  return (!pDumpInfo->allDumped) &&
1,292✔
3595
         ((pDumpInfo->rowIndex > 0 && asc) || (pDumpInfo->rowIndex < (pDumpInfo->totalRows - 1) && (!asc)));
267!
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) {
75,184✔
3604
  int32_t         code = TSDB_CODE_SUCCESS;
75,184✔
3605
  SSDataBlock*    pResBlock = pReader->resBlockInfo.pResBlock;
75,184✔
3606
  SDataBlockIter* pBlockIter = &pReader->status.blockIter;
75,184✔
3607

3608
  *pReturnType = TSDB_READ_RETURN;
75,184✔
3609

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

3612
  while (1) {
3613
    code = doLoadSttBlockSequentially(pReader);
103,684✔
3614
    if (code != TSDB_CODE_SUCCESS) {
103,719✔
3615
      *pReturnType = TSDB_READ_RETURN;
269✔
3616
      return code;
269✔
3617
    }
3618

3619
    if (pResBlock->info.rows > 0) {
103,450✔
3620
      *pReturnType = TSDB_READ_RETURN;
56,723✔
3621
      return code;
56,723✔
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) {
46,727!
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);
46,727✔
3632

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

3639
    if (pReader->status.bProcMemPreFileset) {
29,320✔
3640
      code = buildFromPreFilesetBuffer(pReader);
3,948✔
3641
      if (code != TSDB_CODE_SUCCESS) {
3,948!
3642
        return code;
×
3643
      }
3644
      if (pResBlock->info.rows > 0) {
3,948✔
3645
        pReader->status.processingMemPreFileSet = true;
451✔
3646
        *pReturnType = TSDB_READ_RETURN;
451✔
3647
        return code;
451✔
3648
      }
3649
    }
3650

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

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

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

3673
  if (pBlockIter->numOfBlocks == 0) {
75,025✔
3674
    // let's try to extract data from stt files.
3675
    ERetrieveType type = 0;
74,570✔
3676
    code = doReadDataFromSttFiles(pReader, &type);
74,570✔
3677
    if (code != 0 || type == TSDB_READ_RETURN) {
74,587✔
3678
      return code;
74,553✔
3679
    }
3680

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

3687
  while (1) {
3688
    if (fileBlockPartiallyRead(pDumpInfo, asc)) {  // file data block is partially loaded
1,011!
3689
      code = buildComposedDataBlock(pReader);
×
3690
    } else {
3691
      // current block are exhausted, try the next file block
3692
      if (pDumpInfo->allDumped) {
1,025✔
3693
        // try next data block in current file
3694
        bool hasNext = blockIteratorNext(&pReader->status.blockIter, pReader->idStr);
758✔
3695
        if (hasNext) {  // check for the next block in the block accessed order list
758✔
3696
          initBlockDumpInfo(pReader, pBlockIter);
128✔
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) {
630✔
3701
            tBlockDataClear(pBlockData);
621✔
3702
          }
3703

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

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

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

3723
      code = doBuildDataBlock(pReader);
691✔
3724
    }
3725

3726
    if (code != TSDB_CODE_SUCCESS || pResBlock->info.rows > 0) {
691!
3727
      return code;
169✔
3728
    }
3729
  }
3730
}
3731

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

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

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

3787
  int64_t endVer = 0;
131,555✔
3788
  if (pCond->endVersion == -1) {
131,555✔
3789
    // user not specified end version, set current maximum version of vnode as the endVersion
3790
    endVer = pVnode->state.applied;
128,755✔
3791
  } else {
3792
    endVer = (pCond->endVersion > pVnode->state.applied) ? pVnode->state.applied : pCond->endVersion;
2,800✔
3793
  }
3794

3795
  return (SVersionRange){.minVer = startVer, .maxVer = endVer};
131,555✔
3796
}
3797

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

3802
  if (asc) {
204!
3803
    if (start >= num - 1) {
204✔
3804
      start = num - 1;
103✔
3805
    }
3806

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

3812
    while (p->ts >= key && start > 0) {
209✔
3813
      start -= 1;
5✔
3814
    }
3815
  } else {
UNCOV
3816
    if (index <= 0) {
×
3817
      start = 0;
×
3818
    }
3819

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

UNCOV
3825
    while (p->ts <= key && start < num - 1) {
×
UNCOV
3826
      start += 1;
×
3827
    }
3828
  }
3829

3830
  return start;
204✔
3831
}
3832

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

3839
  size_t  num = taosArrayGetSize(pDelList);
309,971✔
3840
  bool    asc = ASCENDING_TRAVERSE(order);
309,959✔
3841
  int32_t step = asc ? 1 : -1;
309,959✔
3842

3843
  if (hasPk) {  // handle the case where duplicated timestamps existed.
309,959✔
3844
    *index = reverseSearchStartPos(pDelList, *index, key, asc);
204✔
3845
  }
3846

3847
  if (asc) {
309,959✔
3848
    if (*index >= num - 1) {
255,153✔
3849
      TSDBKEY* last = taosArrayGetLast(pDelList);
33,760✔
3850
      if (last == NULL) {
33,760!
3851
        return false;
×
3852
      }
3853

3854
      if (key > last->ts) {
33,760✔
3855
        return false;
33,617✔
3856
      } else if (key == last->ts) {
143!
3857
        TSDBKEY* prev = taosArrayGet(pDelList, num - 2);
143✔
3858
        if (prev == NULL) {
143!
3859
          return false;
×
3860
        }
3861

3862
        return (prev->version >= ver && prev->version <= pVerRange->maxVer && prev->version >= pVerRange->minVer);
143!
3863
      }
3864
    } else {
3865
      TSDBKEY* pCurrent = taosArrayGet(pDelList, *index);
221,393✔
3866
      TSDBKEY* pNext = taosArrayGet(pDelList, (*index) + 1);
221,377✔
3867
      if (pCurrent == NULL || pNext == NULL) {
221,343!
3868
        return false;
×
3869
      }
3870

3871
      if (key < pCurrent->ts) {
221,343✔
3872
        return false;
58,048✔
3873
      }
3874

3875
      if (pCurrent->ts <= key && pNext->ts >= key && pCurrent->version >= ver &&
163,295!
3876
          pVerRange->maxVer >= pCurrent->version) {
114,987!
3877
        return true;
114,988✔
3878
      }
3879

3880
      while (pNext->ts <= key && (*index) < num - 1) {
67,995✔
3881
        (*index) += 1;
30,659✔
3882

3883
        if ((*index) < num - 1) {
30,659✔
3884
          pCurrent = taosArrayGet(pDelList, *index);
26,261✔
3885
          pNext = taosArrayGet(pDelList, (*index) + 1);
26,261✔
3886
          if (pCurrent == NULL || pNext == NULL) {
26,261!
3887
            return false;
×
3888
          }
3889

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

3895
          if (pCurrent->ts <= key && pNext->ts >= key && pCurrent->version >= ver &&
13,210!
3896
              pVerRange->maxVer >= pCurrent->version) {
10,971!
3897
            return true;
10,971✔
3898
          }
3899
        }
3900
      }
3901

3902
      return false;
37,336✔
3903
    }
3904
  } else {
3905
    if (*index <= 0) {
54,806!
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);
54,806✔
3920
      TSDBKEY* pPrev = taosArrayGet(pDelList, (*index) - 1);
54,802✔
3921
      if (pCurrent == NULL || pPrev == NULL) {
54,794!
3922
        return false;
×
3923
      }
3924

3925
      if (key > pCurrent->ts) {
54,794✔
3926
        return false;
4,576✔
3927
      }
3928

3929
      if (pPrev->ts <= key && pCurrent->ts >= key && pPrev->version >= ver) {
50,218!
3930
        return true;
45,684✔
3931
      }
3932

3933
      while (pPrev->ts >= key && (*index) > 1) {
4,860✔
3934
        (*index) += step;
437✔
3935

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

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

3948
          if (pPrev->ts <= key && pCurrent->ts >= key && pPrev->version >= ver) {
271!
3949
            return true;
111✔
3950
          }
3951
        }
3952
      }
3953

3954
      return false;
4,423✔
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;
173,213,912✔
3963

3964
  if (!pIter->hasVal) {
59,118,762!
3965
    return;
56,405,422✔
3966
  }
3967

3968
  int32_t  order = pReader->info.order;
116,808,490✔
3969
  TSDBROW* pRow = tsdbTbDataIterGet(pIter->iter);
116,808,490!
3970

3971
  TSDBKEY key;
3972
  TSDBROW_INIT_KEY(pRow, key);
116,808,490!
3973
  if (outOfTimeWindow(key.ts, &pReader->info.window)) {
116,808,490!
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) {
116,811,218!
3980
    if (pDelList == NULL || TARRAY_SIZE(pDelList) == 0) {
116,814,423!
3981
      *pRes = pRow;
116,694,608✔
3982
      return;
116,694,608✔
3983
    } else {
3984
      bool dropped = hasBeenDropped(pDelList, &pIter->index, key.ts, key.version, order, &pReader->info.verRange,
119,815✔
3985
                                    pReader->suppInfo.numOfPks > 0);
119,815✔
3986
      if (!dropped) {
119,815!
3987
        *pRes = pRow;
102,816✔
3988
        return;
102,816✔
3989
      }
3990
    }
3991
  }
3992

3993
  while (1) {
3994
    pIter->hasVal = tsdbTbDataIterNext(pIter->iter);
53,218✔
3995
    if (!pIter->hasVal) {
57,696!
3996
      return;
2,928✔
3997
    }
3998

3999
    pRow = tsdbTbDataIterGet(pIter->iter);
54,768!
4000

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

4007
    if (key.version <= pReader->info.verRange.maxVer && key.version >= pReader->info.verRange.minVer) {
54,184!
4008
      if (pDelList == NULL || TARRAY_SIZE(pDelList) == 0) {
44,703!
4009
        *pRes = pRow;
655✔
4010
        return;
655✔
4011
      } else {
4012
        bool dropped = hasBeenDropped(pDelList, &pIter->index, key.ts, key.version, order, &pReader->info.verRange,
44,048✔
4013
                                      pReader->suppInfo.numOfPks > 0);
44,048✔
4014
        if (!dropped) {
44,052!
4015
          *pRes = pRow;
14,109✔
4016
          return;
14,109✔
4017
        }
4018
      }
4019
    }
4020
  }
4021
}
4022

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

4027
  while (1) {
89,416✔
4028
    pIter->hasVal = tsdbTbDataIterNext(pIter->iter);
1,392,240✔
4029
    if (!pIter->hasVal) {
1,392,191✔
4030
      break;
8,566✔
4031
    }
4032

4033
    // data exists but not valid
4034
    TSDBROW* pRow = NULL;
1,383,625!
4035
    getValidMemRow(pIter, pDelList, pReader, &pRow);
4036
    if (pRow == NULL) {
1,383,674✔
4037
      break;
933✔
4038
    }
4039

4040
    // ts is not identical, quit
4041
    if (TSDBROW_TS(pRow) != pCurKey->ts) {
1,382,741!
4042
      break;
1,293,543✔
4043
    }
4044

4045
    if (pCurKey->numOfPKs > 0) {
89,198✔
4046
      SRowKey nextKey = {0};
6✔
4047
      tRowGetKeyEx(pRow, &nextKey);
6!
4048
      if (pkCompEx(pCurKey, &nextKey) != 0) {
6!
4049
        break;
6✔
4050
      }
4051
    }
4052

4053
    STSchema* pTSchema = NULL;
89,192✔
4054
    if (pRow->type == TSDBROW_ROW_FMT) {
89,192!
4055
      pTSchema = doGetSchemaForTSRow(TSDBROW_SVERSION(pRow), pReader, uid);
89,397!
4056
      if (pTSchema == NULL) {
89,395!
4057
        return terrno;
×
4058
      }
4059
    }
4060

4061
    code = tsdbRowMergerAdd(pMerger, pRow, pTSchema);
89,190✔
4062
    if (code != TSDB_CODE_SUCCESS) {
89,416!
4063
      return code;
×
4064
    }
4065
  }
4066

4067
  return code;
1,303,048✔
4068
}
4069

UNCOV
4070
static int32_t doMergeRowsInFileBlockImpl(SBlockData* pBlockData, int32_t* rowIndex, SRowKey* pKey, SRowMerger* pMerger,
×
4071
                                          SVersionRange* pVerRange, int32_t step) {
UNCOV
4072
  int32_t code = 0;
×
UNCOV
4073
  while ((*rowIndex) < pBlockData->nRow && (*rowIndex) >= 0) {
×
4074
    SRowKey cur;
UNCOV
4075
    tColRowGetKey(pBlockData, (*rowIndex), &cur);
×
UNCOV
4076
    if (pkCompEx(&cur, pKey) != 0) {
×
UNCOV
4077
      break;
×
4078
    }
4079

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

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

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

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

4136
  pDumpInfo->rowIndex += step;
1✔
4137
  if ((pDumpInfo->rowIndex <= pBlockData->nRow - 1 && asc) || (pDumpInfo->rowIndex >= 0 && !asc)) {
1!
UNCOV
4138
    code = doMergeRowsInFileBlockImpl(pBlockData, &pDumpInfo->rowIndex, pKey, pMerger, pRange, step);
×
UNCOV
4139
    if (code != TSDB_CODE_SUCCESS) {
×
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)) {
1!
4146
    while (1) {
×
4147
      CHECK_FILEBLOCK_STATE st;
4148

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

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

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

4167
  return code;
1✔
4168
}
4169

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

UNCOV
4175
  while (1) {
×
4176
    code = nextRowFromSttBlocks(pSttBlockReader, pScanInfo, pkSrcSlot, pVerRange);
1,584,100✔
4177
    if (code || (!hasDataInSttBlock(pScanInfo))) {
1,583,995✔
4178
      return code;
26,118✔
4179
    }
4180

4181
    SRowKey* pNextKey = getCurrentKeyInSttBlock(pSttBlockReader);
1,557,900!
4182

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

4198
  return code;
1,557,897✔
4199
}
4200

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

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

4210
    if (!pIter->hasVal) {
56,419,185✔
4211
      *pResRow = *pRow;
125,650✔
4212
      *freeTSRow = false;
125,650✔
4213
      return TSDB_CODE_SUCCESS;
125,650✔
4214
    } else {  // has next point in mem/imem
4215
      getValidMemRow(pIter, pDelList, pReader, &pNextRow);
4216
      if (pNextRow == NULL) {
56,290,084✔
4217
        *pResRow = current;
14,316✔
4218
        *freeTSRow = false;
14,316✔
4219
        return TSDB_CODE_SUCCESS;
14,316✔
4220
      }
4221

4222
      if (TSDBROW_TS(&current) != TSDBROW_TS(pNextRow)) {
56,275,768✔
4223
        *pResRow = current;
56,180,611✔
4224
        *freeTSRow = false;
56,180,611✔
4225
        return TSDB_CODE_SUCCESS;
56,180,611✔
4226
      }
4227

4228
      if (pKey->numOfPKs > 0) {
95,157✔
4229
        SRowKey nextRowKey = {0};
6,957✔
4230
        tRowGetKeyEx(pNextRow, &nextRowKey);
6,957!
4231
        if (pkCompEx(pKey, &nextRowKey) != 0) {
6,957✔
4232
          *pResRow = current;
33✔
4233
          *freeTSRow = false;
33✔
4234
          return TSDB_CODE_SUCCESS;
33✔
4235
        }
4236
      }
4237
    }
4238
  }
4239

4240
  terrno = 0;
95,124✔
4241
  int32_t code = 0;
86,911✔
4242

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

4252
  code = tsdbRowMergerAdd(pMerger, &current, pTSchema);
86,916✔
4253
  if (code != TSDB_CODE_SUCCESS) {
86,951✔
4254
    return code;
5✔
4255
  }
4256

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

4265
  code = tsdbRowMergerAdd(pMerger, pNextRow, pTSchema1);
86,931✔
4266
  if (code != TSDB_CODE_SUCCESS) {
86,942!
4267
    return code;
×
4268
  }
4269

4270
  code = doMergeRowsInBuf(pIter, uid, pKey, pDelList, pReader);
86,942✔
4271
  if (code != TSDB_CODE_SUCCESS) {
86,944!
4272
    return code;
×
4273
  }
4274

4275
  code = tsdbRowMergerGetRow(pMerger, &pResRow->pTSRow);
86,944✔
4276
  if (code != TSDB_CODE_SUCCESS) {
86,940✔
4277
    return code;
1✔
4278
  }
4279

4280
  pResRow->type = TSDBROW_ROW_FMT;
86,939✔
4281
  tsdbRowMergerClear(pMerger);
86,939✔
4282
  *freeTSRow = true;
86,914✔
4283

4284
  return TSDB_CODE_SUCCESS;
86,914✔
4285
}
4286

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

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

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

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

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

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

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

4352
  code = tsdbRowMergerGetRow(pMerger, pTSRow);
×
4353
  tsdbRowMergerClear(pMerger);
×
4354
  return code;
×
4355
}
4356

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

4362
  getValidMemRow(&pBlockScanInfo->iter, pBlockScanInfo->delSkyline, pReader, &pRow);
56,351,851✔
4363
  getValidMemRow(&pBlockScanInfo->iiter, pBlockScanInfo->delSkyline, pReader, &piRow);
56,359,674✔
4364

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

4371
  // todo refactor
4372
  bool asc = ASCENDING_TRAVERSE(pReader->info.order);
56,359,690✔
4373
  if (piter->hasVal) {
56,359,690!
4374
    tRowGetKeyEx(pRow, &rowKey);
56,410,636!
4375
    if ((rowKey.ts >= endKey && asc) || (rowKey.ts <= endKey && !asc)) {
56,414,137✔
4376
      pRow = NULL;
4,715✔
4377
    }
4378
  }
4379

4380
  if (piiter->hasVal) {
56,363,191✔
4381
    tRowGetKeyEx(piRow, &irowKey);
35,423!
4382
    if ((irowKey.ts >= endKey && asc) || (irowKey.ts <= endKey && !asc)) {
117,621!
4383
      piRow = NULL;
×
4384
    }
4385
  }
4386

4387
  if (pRow != NULL && piRow != NULL) {
56,445,389!
UNCOV
4388
    int32_t code = TSDB_CODE_SUCCESS;
×
UNCOV
4389
    if (rowKey.numOfPKs == 0) {
×
4390
      if ((rowKey.ts > irowKey.ts && asc) || (rowKey.ts < irowKey.ts && (!asc))) {  // ik.ts < k.ts
×
4391
        code = doMergeMemTableMultiRows(piRow, &irowKey, uid, piiter, pDelList, pResRow, pReader, freeTSRow);
×
4392
      } else if ((rowKey.ts < irowKey.ts && asc) || (rowKey.ts > irowKey.ts && (!asc))) {
×
4393
        code = doMergeMemTableMultiRows(pRow, &rowKey, uid, piter, pDelList, pResRow, pReader, freeTSRow);
×
4394
      } else {  // ik.ts == k.ts
4395
        *freeTSRow = true;
×
4396
        pResRow->type = TSDBROW_ROW_FMT;
×
4397
        code = doMergeMemIMemRows(pRow, &rowKey, piRow, &irowKey, pBlockScanInfo, pReader, &pResRow->pTSRow);
×
4398
        if (code != TSDB_CODE_SUCCESS) {
×
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
4411
        *freeTSRow = true;
×
4412
        pResRow->type = TSDBROW_ROW_FMT;
×
4413
        code = doMergeMemIMemRows(pRow, &rowKey, piRow, &irowKey, pBlockScanInfo, pReader, &pResRow->pTSRow);
×
4414
        if (code != TSDB_CODE_SUCCESS) {
×
4415
          return code;
×
4416
        }
4417
      }
4418
    }
4419

UNCOV
4420
    return code;
×
4421
  }
4422

4423
  if (piter->hasVal && pRow != NULL) {
56,445,389✔
4424
    return doMergeMemTableMultiRows(pRow, &rowKey, uid, piter, pDelList, pResRow, pReader, freeTSRow);
56,401,348✔
4425
  }
4426

4427
  if (piiter->hasVal && piRow != NULL) {
44,041!
4428
    return doMergeMemTableMultiRows(piRow, &irowKey, uid, piiter, pDelList, pResRow, pReader, freeTSRow);
35,402✔
4429
  }
4430

4431
  return TSDB_CODE_SUCCESS;
8,639✔
4432
}
4433

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

4439
  SBlockLoadSuppInfo* pSupInfo = &pReader->suppInfo;
59,176,143✔
4440
  STSchema*           pSchema = doGetSchemaForTSRow(pTSRow->sver, pReader, uid);
59,176,143!
4441
  if (pSchema == NULL) {
59,175,161!
4442
    return terrno;
×
4443
  }
4444

4445
  SColVal colVal = {0};
59,175,161✔
4446
  int32_t i = 0, j = 0;
59,175,161✔
4447

4448
  if (pSupInfo->colId[i] == PRIMARYKEY_TIMESTAMP_COL_ID) {
59,175,161!
4449
    SColumnInfoData* pColData = taosArrayGet(pBlock->pDataBlock, pSupInfo->slotId[i]);
59,177,190✔
4450
    if (pColData == NULL) {
59,153,312!
4451
      return TSDB_CODE_INVALID_PARA;
×
4452
    }
4453

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

4458
  while (i < pSupInfo->numOfCols && j < pSchema->numOfCols) {
402,826,160!
4459
    col_id_t colId = pSupInfo->colId[i];
342,600,280✔
4460

4461
    if (colId == pSchema->columns[j].colId) {
342,600,280✔
4462
      SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, pSupInfo->slotId[i]);
159,561,863✔
4463
      if (pColInfoData == NULL) {
158,433,296!
4464
        return TSDB_CODE_INVALID_PARA;
×
4465
      }
4466

4467
      code = tRowGet(pTSRow, pSchema, j, &colVal);
158,433,296✔
4468
      if (code) {
159,597,993!
4469
        return code;
×
4470
      }
4471

4472
      code = doCopyColVal(pColInfoData, outputRowIndex, i, &colVal, pSupInfo);
159,597,993✔
4473
      if (code) {
160,636,469✔
4474
        return code;
9✔
4475
      }
4476
      i += 1;
160,636,460✔
4477
      j += 1;
160,636,460✔
4478
    } else if (colId < pSchema->columns[j].colId) {
183,038,417!
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) {
183,038,417!
4487
      j += 1;
183,041,415✔
4488
    }
4489
  }
4490

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

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

4502
  pBlock->info.dataLoad = 1;
60,225,880✔
4503
  pBlock->info.rows += 1;
60,225,880✔
4504
  return TSDB_CODE_SUCCESS;
60,225,880✔
4505
}
4506

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

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

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

4521
  while (i < numOfOutputCols && j < numOfInputCols) {
2,527,860✔
4522
    SColData* pData = tBlockDataGetColDataByIdx(pBlockData, j);
2,023,851✔
4523
    if (pData->cid < pSupInfo->colId[i]) {
2,023,851!
4524
      j += 1;
×
4525
      continue;
×
4526
    }
4527

4528
    SColumnInfoData* pCol = TARRAY_GET_ELEM(pResBlock->pDataBlock, pSupInfo->slotId[i]);
2,023,851✔
4529
    if (pData->cid == pSupInfo->colId[i]) {
2,023,851!
4530
      tColDataGetValue(pData, rowIndex, &cv);
2,023,999✔
4531
      code = doCopyColVal(pCol, outputRowIndex, i, &cv, pSupInfo);
2,028,828✔
4532
      if (code) {
2,026,279✔
4533
        return code;
1✔
4534
      }
4535
      j += 1;
2,026,278✔
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;
2,026,130✔
4542
  }
4543

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

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

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

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

4564
  do {
56,196,543✔
4565
    TSDBROW row = {.type = -1};
56,355,938✔
4566
    bool    freeTSRow = false;
56,355,938✔
4567
    code = tsdbGetNextRowInMem(pBlockScanInfo, pReader, &row, endKey, &freeTSRow);
56,355,938✔
4568
    if (code != TSDB_CODE_SUCCESS) {
56,406,715✔
4569
      return code;
15✔
4570
    }
4571

4572
    if (row.type == -1) {
56,406,709✔
4573
      break;
8,639✔
4574
    }
4575

4576
    if (row.type == TSDBROW_ROW_FMT) {
56,398,070✔
4577
      code = doAppendRowFromTSRow(pBlock, pReader, row.pTSRow, pBlockScanInfo);
56,394,285✔
4578
      if (code == TSDB_CODE_SUCCESS) {
56,346,832!
4579
        pBlockScanInfo->lastProcKey.ts = row.pTSRow->ts;
56,347,726✔
4580
        pBlockScanInfo->lastProcKey.numOfPKs = row.pTSRow->numOfPKs;
56,347,726✔
4581
        if (row.pTSRow->numOfPKs > 0) {
56,347,726✔
4582
          tRowGetPrimaryKeyDeepCopy(row.pTSRow, &pBlockScanInfo->lastProcKey);
35,177,945✔
4583
        }
4584
      }
4585

4586
      if (freeTSRow) {
56,346,832✔
4587
        taosMemoryFree(row.pTSRow);
86,936✔
4588
      }
4589

4590
      if (code) {
56,346,851✔
4591
        return code;
9✔
4592
      }
4593
    } else {
4594
      code = doAppendRowFromFileBlock(pBlock, pReader, row.pBlockData, row.iRow);
3,785✔
4595
      if (code) {
×
4596
        return code;
×
4597
      }
4598

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

4602
    // no data in buffer, return immediately
4603
    if (!(pBlockScanInfo->iter.hasVal || pBlockScanInfo->iiter.hasVal)) {
56,347,321✔
4604
      break;
148,436✔
4605
    }
4606

4607
    if (pBlock->info.rows >= capacity) {
56,198,885✔
4608
      break;
2,342✔
4609
    }
4610
  } while (1);
4611

4612
  return code;
159,417✔
4613
}
4614

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

4620
  STableBlockScanInfo** p = NULL;
355✔
4621
  int32_t               iter = 0;
355✔
4622

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

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

4632
  tSimpleHashClear(pReader->status.pTableMap);
354✔
4633

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

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

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

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

4653
  STableKeyInfo* pList = (STableKeyInfo*)pTableList;
355✔
4654
  for (int32_t i = 0; i < num; ++i) {
719✔
4655
    pUidList->tableUidList[i] = pList[i].uid;
364✔
4656

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

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

4671
  (void) tsdbReleaseReader(pReader);
355✔
4672
  return code;
355✔
4673
}
4674

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

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

4682
  if (pReader->bFilesetDelimited) {
117,857✔
4683
    getMemTableTimeRange(pReader, &pReader->status.memTableMaxKey, &pReader->status.memTableMinKey);
29,789✔
4684
    pReader->status.bProcMemFirstFileset = true;
29,795✔
4685
  }
4686

4687
  code = initFilesetIterator(&pStatus->fileIter, pReader->pReadSnap->pfSetArray, pReader);
117,863✔
4688
  if (code != TSDB_CODE_SUCCESS) {
117,887✔
4689
    return code;
9✔
4690
  }
4691

4692
  code = resetDataBlockIterator(&pStatus->blockIter, pReader->info.order, shouldFreePkBuf(&pReader->suppInfo),
117,842✔
4693
                                pReader->idStr);
117,878✔
4694
  if (code != TSDB_CODE_SUCCESS) {
117,870✔
4695
    return code;
10✔
4696
  }
4697

4698
  if (pStatus->fileIter.numOfFiles == 0) {
117,860✔
4699
    pStatus->loadFromFile = false;
96,618✔
4700
  } else {
4701
    code = initForFirstBlockInFile(pReader, pBlockIter);
21,242✔
4702
  }
4703

4704
  if (!pStatus->loadFromFile) {
117,853✔
4705
    code = resetTableListIndex(pStatus, pReader->idStr);
98,087✔
4706
  }
4707

4708
  return code;
117,871✔
4709
}
4710

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

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

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

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

4749
  int32_t capacity = pConf->tsdbCfg.maxRows;
131,312✔
4750
  if (pResBlock != NULL) {
131,312!
4751
    code = blockDataEnsureCapacity(pResBlock, capacity);
131,620✔
4752
    TSDB_CHECK_CODE(code, lino, _err);
131,655✔
4753
  }
4754

4755
  code = tsdbReaderCreate(pVnode, pCond, ppReader, capacity, pResBlock, idstr);
131,265✔
4756
  TSDB_CHECK_CODE(code, lino, _err);
131,455✔
4757

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

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

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

4791
    code = tsdbReaderCreate(pVnode, pCond, (void**)&((STsdbReader*)pReader)->innerReader[1], 1, pResBlock, idstr);
12✔
4792
    TSDB_CHECK_CODE(code, lino, _err);
12!
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) {
131,361✔
4799
    code = metaGetTbTSchemaMaybeNull(pReader->pTsdb->pVnode->pMeta, pReader->info.suid, -1, 1, &pReader->info.pSchema);
125,224✔
4800
    TSDB_CHECK_CODE(code, lino, _err);
125,395✔
4801
    if (pReader->info.pSchema == NULL) {
125,329!
4802
      tsdbWarn("failed to get table schema, suid:%" PRIu64 ", ver:-1, %s", pReader->info.suid, pReader->idStr);
×
4803
    }
4804
  } else if (numOfTables > 0) {
6,137✔
4805
    STableKeyInfo* pKey = pTableList;
5,955✔
4806
    code = metaGetTbTSchemaMaybeNull(pReader->pTsdb->pVnode->pMeta, pKey->uid, -1, 1, &pReader->info.pSchema);
5,955✔
4807
    TSDB_CHECK_CODE(code, lino, _err);
5,955✔
4808
    if (pReader->info.pSchema == NULL) {
5,950!
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) {
131,461✔
4814
    code = tsdbRowMergerInit(&pReader->status.merger, pReader->info.pSchema);
131,232✔
4815
    TSDB_CHECK_CODE(code, lino, _err);
131,330✔
4816
  }
4817

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

4824
  tSimpleHashSetFreeFp(pReader->pSchemaMap, freeSchemaFunc);
131,446✔
4825
  if (pReader->info.pSchema != NULL) {
131,440✔
4826
    code = updateBlockSMAInfo(pReader->info.pSchema, &pReader->suppInfo);
131,296✔
4827
    TSDB_CHECK_CODE(code, lino, _err);
131,296!
4828
  }
4829

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

4832
  code = createDataBlockScanInfo(p, &pReader->blockInfoBuf, pTableList, &pReader->status.uidList, numOfTables, &pReader->status.pTableMap);
131,440✔
4833
  TSDB_CHECK_CODE(code, lino, _err);
131,447✔
4834

4835
  pReader->status.pLDataIterArray = taosArrayInit(4, POINTER_BYTES);
131,366✔
4836
  TSDB_CHECK_NULL(pReader->status.pLDataIterArray, code, lino, _err, terrno);
131,378✔
4837

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

4841
  pReader->pIgnoreTables = pIgnoreTables;
131,363✔
4842
  tsdbDebug("%p total numOfTable:%d, window:%" PRId64 " - %" PRId64 ", verRange:%" PRId64 " - %" PRId64
131,363✔
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;
131,358✔
4848

4849
_err:
308✔
4850
  tsdbError("failed to create data reader, error at:%d code:%s %s", lino, tstrerror(code), idstr);
308!
4851
  tsdbReaderClose2(*ppReader);
308✔
4852
  *ppReader = NULL;  // reset the pointer value.
308✔
4853
  return code;
308✔
4854
}
4855

4856
void tsdbReaderClose2(STsdbReader* pReader) {
198,672✔
4857
  if (pReader == NULL) {
198,672✔
4858
    return;
67,139✔
4859
  }
4860

4861
  int32_t code = tsdbAcquireReader(pReader);
131,533✔
4862
  if (code) {
131,585!
4863
    return;
×
4864
  }
4865

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

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

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

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

4882
  if (pSupInfo->buildBuf) {
131,532!
4883
    for (int32_t i = 0; i < pSupInfo->numOfCols; ++i) {
1,137,399✔
4884
      if (pSupInfo->buildBuf[i] != NULL) {
1,005,804✔
4885
        taosMemoryFreeClear(pSupInfo->buildBuf[i]);
121,765!
4886
      }
4887
    }
4888
  }
4889

4890
  if (pReader->resBlockInfo.freeBlock) {
131,580✔
4891
    blockDataDestroy(pReader->resBlockInfo.pResBlock);
4✔
4892
    pReader->resBlockInfo.pResBlock = NULL;
4✔
4893
  }
4894

4895
  taosMemoryFree(pSupInfo->colId);
131,580✔
4896
  tBlockDataDestroy(&pReader->status.fileBlockData);
131,595✔
4897
  cleanupDataBlockIterator(&pReader->status.blockIter, shouldFreePkBuf(&pReader->suppInfo));
131,557✔
4898

4899
  size_t numOfTables = tSimpleHashGetSize(pReader->status.pTableMap);
131,572✔
4900
  if (pReader->status.pTableMap != NULL) {
131,564✔
4901
    destroyAllBlockScanInfo(pReader->status.pTableMap);
131,372✔
4902
    pReader->status.pTableMap = NULL;
131,412✔
4903
  }
4904
  clearBlockScanInfoBuf(&pReader->blockInfoBuf);
131,604✔
4905

4906
  if (pReader->pFileReader != NULL) {
131,607✔
4907
    tsdbDataFileReaderClose(&pReader->pFileReader);
484✔
4908
  }
4909

4910
  SReadCostSummary* pCost = &pReader->cost;
131,607✔
4911
  SFilesetIter*     pFilesetIter = &pReader->status.fileIter;
131,607✔
4912
  if (pFilesetIter->pSttBlockReader != NULL) {
131,607✔
4913
    SSttBlockReader* pSttBlockReader = pFilesetIter->pSttBlockReader;
117,894✔
4914
    tMergeTreeClose(&pSttBlockReader->mergeTree);
117,894✔
4915

4916
    clearRowKey(&pSttBlockReader->currentKey);
117,874✔
4917
    taosMemoryFree(pSttBlockReader);
117,881✔
4918
  }
4919

4920
  destroySttBlockReader(pReader->status.pLDataIterArray, &pCost->sttCost);
131,602✔
4921
  taosMemoryFreeClear(pReader->status.uidList.tableUidList);
131,590✔
4922

4923
  tsdbTrace("tsdb/reader-close: %p, untake snapshot", pReader);
131,600!
4924
  void* p = pReader->pReadSnap;
131,600✔
4925
  if ((p == atomic_val_compare_exchange_ptr((void**)&pReader->pReadSnap, p, NULL)) && (p != NULL)) {
131,600!
4926
    tsdbUntakeReadSnap2(pReader, p, true);
117,872✔
4927
    pReader->pReadSnap = NULL;
117,877✔
4928
  }
4929

4930
  (void) tsem_destroy(&pReader->resumeAfterSuspend);
131,605✔
4931
  (void) tsdbReleaseReader(pReader);
131,549✔
4932
  (void) tsdbUninitReaderLock(pReader);
131,602✔
4933

4934
  tsdbDebug(
131,557✔
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);
131,558✔
4949

4950
  tsdbRowMergerCleanup(&pReader->status.merger);
131,604✔
4951
  taosMemoryFree(pReader->info.pSchema);
131,581✔
4952

4953
  tSimpleHashCleanup(pReader->pSchemaMap);
131,605✔
4954
  taosMemoryFreeClear(pReader);
131,602!
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) {
131,698✔
5055
  int32_t               code = 0;
131,698✔
5056
  STableBlockScanInfo** pBlockScanInfo = pReader->status.pTableIter;
131,698✔
5057

5058
  //  restore reader's state, task snapshot
5059
  int32_t numOfTables = tSimpleHashGetSize(pReader->status.pTableMap);
131,698✔
5060
  if (numOfTables > 0) {
131,744✔
5061
    tsdbTrace("tsdb/reader: %p, take snapshot", pReader);
117,865!
5062
    code = tsdbTakeReadSnap2(pReader, tsdbSetQueryReseek, &pReader->pReadSnap, pReader->idStr);
117,865✔
5063
    if (code != TSDB_CODE_SUCCESS) {
117,899✔
5064
      goto _err;
25✔
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;
117,874✔
5070

5071
    if (pReader->type == TIMEWINDOW_RANGE_CONTAINED) {
117,874!
5072
      code = doOpenReaderImpl(pReader);
117,876✔
5073
      if (code != TSDB_CODE_SUCCESS) {
117,836✔
5074
        return code;
29✔
5075
      }
5076
    } else {
5077
      STsdbReader* pPrevReader = pReader->innerReader[0];
×
5078
      STsdbReader* pNextReader = pReader->innerReader[1];
×
5079

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

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

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

5107
  tsdbDebug("reader: %p resumed uid %" PRIu64 ", numOfTable:%" PRId32 ", in this query %s", pReader,
131,697!
5108
            pBlockScanInfo ? (*pBlockScanInfo)->uid : 0, numOfTables, pReader->idStr);
5109
  return code;
131,676✔
5110

5111
_err:
25✔
5112
  tsdbError("failed to resume data reader, code:%s %s", tstrerror(code), pReader->idStr);
25!
5113
  return code;
25✔
5114
}
5115

5116
static int32_t buildFromPreFilesetBuffer(STsdbReader* pReader) {
4,550✔
5117
  int32_t        code = TSDB_CODE_SUCCESS;
4,550✔
5118
  SReaderStatus* pStatus = &pReader->status;
4,550✔
5119

5120
  SSDataBlock* pBlock = pReader->resBlockInfo.pResBlock;
4,550✔
5121

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

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

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

5149
  if (pStatus->loadFromFile) {
61,254✔
5150
    if (pStatus->bProcMemPreFileset) {
13,983✔
5151
      code = buildFromPreFilesetBuffer(pReader);
602✔
5152
      if (code != TSDB_CODE_SUCCESS || pBlock->info.rows > 0) {
602!
5153
        return code;
87✔
5154
      }
5155
    }
5156

5157
    code = buildBlockFromFiles(pReader);
13,896✔
5158
    if (code != TSDB_CODE_SUCCESS) {
13,898✔
5159
      return code;
39✔
5160
    }
5161

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

5183
      int64_t endKey = (ASCENDING_TRAVERSE(pReader->info.order)) ? INT64_MAX : INT64_MIN;
5,146✔
5184
      code = buildBlockFromBufferSequentially(pReader, endKey);
5,146✔
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;
47,271✔
5188
    code = buildBlockFromBufferSequentially(pReader, endKey);
47,271✔
5189
  }
5190
  return code;
61,145✔
5191
}
5192

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

5198
  if (pStatus->loadFromFile) {
259,122✔
5199
    code = buildBlockFromFiles(pReader);
61,141✔
5200
    if (code != TSDB_CODE_SUCCESS) {
61,159✔
5201
      return code;
238✔
5202
    }
5203

5204
    if (pBlock->info.rows <= 0) {
60,921✔
5205
      code = resetTableListIndex(&pReader->status, pReader->idStr);
12,253✔
5206
      if (code) {
12,253!
5207
        return code;
×
5208
      }
5209

5210
      int64_t endKey = (ASCENDING_TRAVERSE(pReader->info.order)) ? INT64_MAX : INT64_MIN;
12,253✔
5211
      code = buildBlockFromBufferSequentially(pReader, endKey);
12,253✔
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;
197,981✔
5215
    code = buildBlockFromBufferSequentially(pReader, endKey);
197,981✔
5216
  }
5217
  return code;
258,962✔
5218
}
5219

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

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

5227
  *hasNext = false;
333,378✔
5228

5229
  SReaderStatus* pStatus = &pReader->status;
333,378✔
5230
  if (tSimpleHashGetSize(pStatus->pTableMap) == 0) {
333,378✔
5231
    return code;
12,940✔
5232
  }
5233

5234
  if (!pReader->bFilesetDelimited) {
320,461✔
5235
    code = doTsdbNextDataBlockFilesFirst(pReader);
259,194✔
5236
  } else {
5237
    code = doTsdbNextDataBlockFilesetDelimited(pReader);
61,267✔
5238
  }
5239

5240
  *hasNext = pBlock->info.rows > 0;
320,469✔
5241

5242
  return code;
320,469✔
5243
}
5244

5245
int32_t tsdbNextDataBlock2(STsdbReader* pReader, bool* hasNext) {
333,361✔
5246
  int32_t code = TSDB_CODE_SUCCESS;
333,361✔
5247

5248
  *hasNext = false;
333,361✔
5249

5250
  if (isEmptyQueryTimeWindow(&pReader->info.window) || pReader->step == EXTERNAL_ROWS_NEXT ||
333,361!
5251
      pReader->code != TSDB_CODE_SUCCESS) {
333,454✔
UNCOV
5252
    return (pReader->code != TSDB_CODE_SUCCESS) ? pReader->code : code;
×
5253
  }
5254

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

5272
  tsdbTrace("tsdb/read: %p, take read mutex, code: %d", pReader, code);
333,446!
5273

5274
  if (pReader->flag == READER_STATUS_SUSPEND) {
333,446✔
5275
    code = tsdbReaderResume2(pReader);
128,365✔
5276
    if (code != TSDB_CODE_SUCCESS) {
128,289✔
5277
      // release reader failure should be suppressed here, to avoid over-write the original error code
5278
      (void) tsdbReleaseReader(pReader);
53✔
5279
      return code;
53✔
5280
    }
5281
  }
5282

5283
  if (pReader->innerReader[0] != NULL && pReader->step == 0) {
333,317✔
5284
    code = doTsdbNextDataBlock2(pReader->innerReader[0], hasNext);
11✔
5285
    if (code) {
11!
5286
      (void) tsdbReleaseReader(pReader);
×
5287
      return code;
×
5288
    }
5289

5290
    pReader->step = EXTERNAL_ROWS_PREV;
11✔
5291
    if (*hasNext) {
11✔
5292
      pStatus = &pReader->innerReader[0]->status;
6✔
5293
      if (pStatus->composedDataBlock) {
6!
5294
        tsdbTrace("tsdb/read: %p, unlock read mutex", pReader);
6!
5295
        code = tsdbReleaseReader(pReader);
6✔
5296
      }
5297

5298
      return code;
6✔
5299
    }
5300
  }
5301

5302
  if (pReader->step == EXTERNAL_ROWS_PREV) {
333,311✔
5303
    // prepare for the main scan
5304
    if (tSimpleHashGetSize(pReader->status.pTableMap) > 0) {
11!
5305
      code = doOpenReaderImpl(pReader);
11✔
5306
    }
5307

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

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

5316
    pReader->step = EXTERNAL_ROWS_MAIN;
11✔
5317
  }
5318

5319
  code = doTsdbNextDataBlock2(pReader, hasNext);
333,311✔
5320
  if (code != TSDB_CODE_SUCCESS) {
333,366✔
5321
    (void) tsdbReleaseReader(pReader);
306✔
5322
    return code;
343✔
5323
  }
5324

5325
  if (*hasNext) {
333,060✔
5326
    if (pStatus->composedDataBlock) {
208,231✔
5327
      tsdbTrace("tsdb/read: %p, unlock read mutex", pReader);
208,054!
5328
      code = tsdbReleaseReader(pReader);
208,054✔
5329
    }
5330
    return code;
208,242✔
5331
  }
5332

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

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

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

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

UNCOV
5360
      return code;
×
5361
    }
5362
  }
5363

5364
  tsdbTrace("tsdb/read: %p, unlock read mutex", pReader);
124,829!
5365
  code = tsdbReleaseReader(pReader);
124,829✔
5366
  return code;
124,832✔
5367
}
5368

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

5378
  size++;
82✔
5379

5380
  while (j < numOfCols && i < size) {
327✔
5381
    SColumnDataAgg* pAgg = &pSup->colAggArray.data[i];
245✔
5382
    if (pAgg->colId == pSup->colId[j]) {
245✔
5383
      i += 1;
163✔
5384
      j += 1;
163✔
5385
    } else if (pAgg->colId < pSup->colId[j]) {
82!
5386
      i += 1;
82✔
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) {
83✔
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) {
77,507✔
5417
  SColumnDataAgg**    pBlockSMA = &pDataBlock->pBlockAgg;
77,507✔
5418
  SFileDataBlockInfo* pBlockInfo = NULL;
77,507✔
5419
  int32_t             code = 0;
77,507✔
5420
  *allHave = false;
77,507✔
5421
  *pBlockSMA = NULL;
77,507✔
5422

5423
  if (pReader->type == TIMEWINDOW_RANGE_EXTERNAL) {
77,507!
5424
    return TSDB_CODE_SUCCESS;
×
5425
  }
5426

5427
  // there is no statistics data for composed block
5428
  if (pReader->status.composedDataBlock || (!pReader->suppInfo.smaValid)) {
77,507!
5429
    return TSDB_CODE_SUCCESS;
77,425✔
5430
  }
5431

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

5437
  SBlockLoadSuppInfo* pSup = &pReader->suppInfo;
82✔
5438

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

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

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

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

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

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

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

5488
  size_t size = pSup->colAggArray.size;
82✔
5489

5490
  int32_t i = 0, j = 0;
82✔
5491
  while (j < numOfCols && i < size) {
328!
5492
    SColumnDataAgg* pAgg = &pSup->colAggArray.data[i];
246✔
5493
    if (pAgg->colId == pSup->colId[j]) {
246✔
5494
      pResBlock->pBlockAgg[pSup->slotId[j]] = *pAgg;
164✔
5495
      i += 1;
164✔
5496
      j += 1;
164✔
5497
    } else if (pAgg->colId < pSup->colId[j]) {
82!
5498
      i += 1;
82✔
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;
82✔
5507
  pReader->cost.smaDataLoad += 1;
82✔
5508

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

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

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

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

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

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

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

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

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

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

5555
  STsdbReader* pTReader = pReader;
164,532✔
5556
  if (pReader->type == TIMEWINDOW_RANGE_EXTERNAL) {
164,532✔
5557
    if (pReader->step == EXTERNAL_ROWS_PREV) {
11✔
5558
      pTReader = pReader->innerReader[0];
6✔
5559
    } else if (pReader->step == EXTERNAL_ROWS_NEXT) {
5!
UNCOV
5560
      pTReader = pReader->innerReader[1];
×
5561
    }
5562
  }
5563

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

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

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

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

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

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

5591
  if (pReader->flag == READER_STATUS_SUSPEND) {
397✔
5592
    code = tsdbReaderResume2(pReader);
7✔
5593
    if (code != TSDB_CODE_SUCCESS) {
7!
5594
      (void) tsdbReleaseReader(pReader);
×
5595
      return code;
×
5596
    }
5597
  }
5598

5599
  if (isEmptyQueryTimeWindow(&pReader->info.window) || pReader->pReadSnap == NULL) {
397!
5600
    tsdbDebug("tsdb reader reset return %p, %s", pReader->pReadSnap, pReader->idStr);
7!
5601
    return tsdbReleaseReader(pReader);
7✔
5602
  }
5603

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

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

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

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

5619
  int32_t numOfTables = tSimpleHashGetSize(pStatus->pTableMap);
389✔
5620

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

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

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

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

5649
  // no data in files, let's try buffer in memory
5650
  if (pStatus->fileIter.numOfFiles == 0) {
390✔
5651
    pStatus->loadFromFile = false;
331✔
5652
    code = resetTableListIndex(pStatus, pReader->idStr);
331✔
5653
    if (code != TSDB_CODE_SUCCESS) {
331!
5654
      (void) tsdbReleaseReader(pReader);
×
5655
      return code;
×
5656
    }
5657
  } else {
5658
    code = initForFirstBlockInFile(pReader, pBlockIter);
59✔
5659
    if (code != TSDB_CODE_SUCCESS) {
59!
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
390✔
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);
390✔
5674
  return code;
390✔
5675
}
5676

5677
static int32_t getBucketIndex(int32_t startRow, int32_t bucketRange, int32_t numOfRows, int32_t numOfBucket) {
×
5678
  if (numOfRows < startRow) {
×
5679
    return 0;
×
5680
  }
5681
  int32_t bucketIndex = ((numOfRows - startRow) / bucketRange);
×
5682
  if (bucketIndex == numOfBucket) {
×
5683
    bucketIndex -= 1;
×
5684
  }
5685
  return bucketIndex;
×
5686
}
5687

5688
int32_t tsdbGetFileBlocksDistInfo2(STsdbReader* pReader, STableBlockDistInfo* pTableBlockInfo) {
2,946✔
5689
  int32_t       code = TSDB_CODE_SUCCESS;
2,946✔
5690
  const int32_t numOfBuckets = 20.0;
2,946✔
5691

5692
  pTableBlockInfo->totalSize = 0;
2,946✔
5693
  pTableBlockInfo->totalRows = 0;
2,946✔
5694
  pTableBlockInfo->numOfVgroups = 1;
2,946✔
5695

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

5702
  if (pReader->flag == READER_STATUS_SUSPEND) {
2,954✔
5703
    code = tsdbReaderResume2(pReader);
2,953✔
5704
    if (code != TSDB_CODE_SUCCESS) {
2,949✔
5705
      return tsdbReleaseReader(pReader);
1✔
5706
    }
5707
  }
5708

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

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

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

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

5729
  pTableBlockInfo->numOfFiles += 1;
2,950✔
5730

5731
  int32_t numOfTables = (int32_t)tSimpleHashGetSize(pStatus->pTableMap);
2,950✔
5732

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

5736
  if (pBlockIter->numOfBlocks > 0) {
2,948!
5737
    pTableBlockInfo->numOfBlocks += pBlockIter->numOfBlocks;
×
5738
  }
5739

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

5743
  while (true) {
5744
    if (hasNext) {
6,231!
5745
      SFileDataBlockInfo* pBlockInfo = NULL;
×
5746
      code = getCurrentBlockInfo(pBlockIter, &pBlockInfo, pReader->idStr);
×
5747
      if (code != TSDB_CODE_SUCCESS) {
×
5748
        break;
×
5749
      }
5750

5751
      int32_t numOfRows = pBlockInfo->numRow;
×
5752

5753
      pTableBlockInfo->totalRows += numOfRows;
×
5754

5755
      if (numOfRows > pTableBlockInfo->maxRows) {
×
5756
        pTableBlockInfo->maxRows = numOfRows;
×
5757
      }
5758

5759
      if (numOfRows < pTableBlockInfo->minRows) {
×
5760
        pTableBlockInfo->minRows = numOfRows;
×
5761
      }
5762

5763
      pTableBlockInfo->totalSize += pBlockInfo->blockSize;
×
5764

5765
      int32_t bucketIndex = getBucketIndex(pTableBlockInfo->defMinRows, bucketRange, numOfRows, numOfBuckets);
×
5766
      pTableBlockInfo->blockRowsHisto[bucketIndex]++;
×
5767

5768
      hasNext = blockIteratorNext(&pStatus->blockIter, pReader->idStr);
×
5769
    } else {
5770
      code = initForFirstBlockInFile(pReader, pBlockIter);
6,231✔
5771
      if ((code != TSDB_CODE_SUCCESS) || (pStatus->loadFromFile == false)) {
6,232✔
5772
        break;
5773
      }
5774

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

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

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

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

5795
  SReaderStatus* pStatus = &pReader->status;
29,780✔
5796

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

5801
  void* pHashIter = tSimpleHashIterate(pStatus->pTableMap, NULL, &iter);
29,780✔
5802
  while (pHashIter != NULL) {
101,399✔
5803
    STableBlockScanInfo* pBlockScanInfo = *(STableBlockScanInfo**)pHashIter;
71,603✔
5804

5805
    STbData* d = NULL;
71,603✔
5806
    if (pReader->pReadSnap->pMem != NULL) {
71,603✔
5807
      d = tsdbGetTbDataFromMemTable(pReader->pReadSnap->pMem, pReader->info.suid, pBlockScanInfo->uid);
65,416✔
5808
      if (d != NULL) {
65,435✔
5809
        if (d->maxKey > maxKey) {
22,661✔
5810
          maxKey = d->maxKey;
21,864✔
5811
        }
5812
        if (d->minKey < minKey) {
22,661✔
5813
          minKey = d->minKey;
21,790✔
5814
        }
5815
      }
5816
    }
5817

5818
    STbData* di = NULL;
71,622✔
5819
    if (pReader->pReadSnap->pIMem != NULL) {
71,622!
5820
      di = tsdbGetTbDataFromMemTable(pReader->pReadSnap->pIMem, pReader->info.suid, pBlockScanInfo->uid);
×
5821
      if (di != NULL) {
×
5822
        if (di->maxKey > maxKey) {
×
5823
          maxKey = di->maxKey;
×
5824
        }
5825
        if (di->minKey < minKey) {
×
5826
          minKey = di->minKey;
×
5827
        }
5828
      }
5829
    }
5830

5831
    // current table is exhausted, let's try the next table
5832
    pHashIter = tSimpleHashIterate(pStatus->pTableMap, pHashIter, &iter);
71,622✔
5833
  }
5834

5835
  *pMaxKey = maxKey;
29,796✔
5836
  *pMinKey = minKey;
29,796✔
5837
}
29,796✔
5838

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

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

5849
  if (pReader->flag == READER_STATUS_SUSPEND) {
2,951✔
5850
    code = tsdbReaderResume2(pReader);
489✔
5851
    if (code != TSDB_CODE_SUCCESS) {
489!
5852
      (void) tsdbReleaseReader(pReader);
×
5853
      return code;
×
5854
    }
5855
  }
5856

5857
  int32_t iter = 0;
2,951✔
5858
  pStatus->pTableIter = tSimpleHashIterate(pStatus->pTableMap, NULL, &iter);
2,951✔
5859

5860
  while (pStatus->pTableIter != NULL) {
9,346✔
5861
    STableBlockScanInfo* pBlockScanInfo = *(STableBlockScanInfo**)pStatus->pTableIter;
6,396✔
5862

5863
    STbData* d = NULL;
6,396✔
5864
    if (pReader->pReadSnap->pMem != NULL) {
6,396✔
5865
      d = tsdbGetTbDataFromMemTable(pReader->pReadSnap->pMem, pReader->info.suid, pBlockScanInfo->uid);
6,394✔
5866
      if (d != NULL) {
6,395✔
5867
        rows += tsdbGetNRowsInTbData(d);
1,479✔
5868
      }
5869
    }
5870

5871
    STbData* di = NULL;
6,397✔
5872
    if (pReader->pReadSnap->pIMem != NULL) {
6,397✔
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,397✔
5881
  }
5882

5883
  (void) tsdbReleaseReader(pReader);
2,950✔
5884

5885
  return rows;
2,950✔
5886
}
5887

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

5898
  *suid = 0;
19✔
5899

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

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

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

5932
  // lock
5933
  code = taosThreadMutexLock(&pTsdb->mutex);
118,203✔
5934
  if (code != TSDB_CODE_SUCCESS) {
118,329!
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));
118,329✔
5941
  if (pSnap == NULL) {
118,335✔
5942
    (void) taosThreadMutexUnlock(&pTsdb->mutex);
5✔
5943
    TSDB_CHECK_NULL(pSnap, code, lino, _exit, terrno);
5!
5944
  }
5945

5946
  // take snapshot
5947
  if (pTsdb->mem && (pRange->minVer <= pTsdb->mem->maxVer && pRange->maxVer >= pTsdb->mem->minVer)) {
118,330!
5948
    pSnap->pMem = pTsdb->mem;
110,943✔
5949
    pSnap->pNode = taosMemoryMalloc(sizeof(*pSnap->pNode));
110,943✔
5950
    if (pSnap->pNode == NULL) {
110,949✔
5951
      (void) taosThreadMutexUnlock(&pTsdb->mutex);
8✔
5952
      TSDB_CHECK_NULL(pSnap->pNode, code, lino, _exit, terrno);
8!
5953
    }
5954

5955
    pSnap->pNode->pQHandle = pReader;
110,941✔
5956
    pSnap->pNode->reseek = reseek;
110,941✔
5957

5958
    code = tsdbRefMemTable(pTsdb->mem, pSnap->pNode);
110,941✔
5959
    TSDB_CHECK_CODE(code, lino, _exit);
110,928!
5960
  }
5961

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

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

5983
  // fs
5984
  code = tsdbFSCreateRefSnapshotWithoutLock(pTsdb->pFS, &pSnap->pfSetArray);
118,315✔
5985
  if (code) {
118,288✔
5986
    if (pSnap->pNode) {
12✔
5987
      tsdbUnrefMemTable(pTsdb->mem, pSnap->pNode, true);  // unref the previous refed mem
11✔
5988
    }
5989

5990
    if (pSnap->pINode) {
12!
5991
      tsdbUnrefMemTable(pTsdb->imem, pSnap->pINode, true);
×
5992
    }
5993

5994
    (void) taosThreadMutexUnlock(&pTsdb->mutex);
12✔
5995
    TSDB_CHECK_CODE(code, lino, _exit);
12!
5996
  }
5997

5998
  // unlock
5999
  (void) taosThreadMutexUnlock(&pTsdb->mutex);
118,276✔
6000
  *ppSnap = pSnap;
118,313✔
6001

6002
  tsdbTrace("%s vgId:%d, take read snapshot", id, TD_VID(pTsdb->pVnode));
118,313!
6003
  return code;
118,310✔
6004

6005
_exit:
25✔
6006
  tsdbError("%s vgId:%d take read snapshot failed, line:%d code:%s", id, TD_VID(pTsdb->pVnode), lino, tstrerror(code));
25!
6007

6008
  if (pSnap) {
25✔
6009
    if (pSnap->pNode) taosMemoryFree(pSnap->pNode);
20✔
6010
    if (pSnap->pINode) taosMemoryFree(pSnap->pINode);
20!
6011
    taosMemoryFree(pSnap);
20✔
6012
  }
6013
  return code;
25✔
6014
}
6015

6016
void tsdbUntakeReadSnap2(STsdbReader* pReader, STsdbReadSnap* pSnap, bool proactive) {
118,290✔
6017
  STsdb* pTsdb = pReader->pTsdb;
118,290✔
6018

6019
  if (pSnap) {
118,290!
6020
    if (pSnap->pMem) {
118,301✔
6021
      tsdbUnrefMemTable(pSnap->pMem, pSnap->pNode, proactive);
110,921✔
6022
    }
6023

6024
    if (pSnap->pIMem) {
118,303✔
6025
      tsdbUnrefMemTable(pSnap->pIMem, pSnap->pINode, proactive);
201✔
6026
    }
6027

6028
    if (pSnap->pNode) taosMemoryFree(pSnap->pNode);
118,303✔
6029
    if (pSnap->pINode) taosMemoryFree(pSnap->pINode);
118,306✔
6030

6031
    tsdbFSDestroyRefSnapshot(&pSnap->pfSetArray);
118,306✔
6032

6033
    taosMemoryFree(pSnap);
118,303✔
6034
  }
6035
  tsdbTrace("vgId:%d, untake read snapshot", TD_VID(pTsdb->pVnode));
118,305!
6036
}
118,305✔
6037

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

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

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

6055
void tsdbSetFilesetDelimited(STsdbReader* pReader) { pReader->bFilesetDelimited = true; }
29,815✔
6056

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