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

#include "tsdb.h"
17
#include "tsdbFSet2.h"
H
Haojun Liao 已提交
18
#include "tsdbReadUtil.h"
19
#include "tsdbSttFileRW.h"
H
Hongze Cheng 已提交
20

H
Haojun Liao 已提交
21 22
static void tLDataIterClose2(SLDataIter *pIter);

23
// SLDataIter =================================================
24 25
SSttBlockLoadInfo *tCreateLastBlockLoadInfo(STSchema *pSchema, int16_t *colList, int32_t numOfCols,
                                            int32_t numOfSttTrigger) {
26
  SSttBlockLoadInfo *pLoadInfo = taosMemoryCalloc(numOfSttTrigger, sizeof(SSttBlockLoadInfo));
27
  if (pLoadInfo == NULL) {
H
Hongze Cheng 已提交
28
    terrno = TSDB_CODE_OUT_OF_MEMORY;
29 30 31
    return NULL;
  }

32
  for (int32_t i = 0; i < numOfSttTrigger; ++i) {
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
    pLoadInfo[i].blockIndex[0] = -1;
    pLoadInfo[i].blockIndex[1] = -1;
    pLoadInfo[i].currentLoadBlockIndex = 1;

    int32_t code = tBlockDataCreate(&pLoadInfo[i].blockData[0]);
    if (code) {
      terrno = code;
    }

    code = tBlockDataCreate(&pLoadInfo[i].blockData[1]);
    if (code) {
      terrno = code;
    }

    pLoadInfo[i].aSttBlk = taosArrayInit(4, sizeof(SSttBlk));
H
Haojun Liao 已提交
48 49 50
    pLoadInfo[i].pSchema = pSchema;
    pLoadInfo[i].colIds = colList;
    pLoadInfo[i].numOfCols = numOfCols;
51 52 53 54 55
  }

  return pLoadInfo;
}

56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
SSttBlockLoadInfo *tCreateOneLastBlockLoadInfo(STSchema *pSchema, int16_t *colList, int32_t numOfCols) {
  SSttBlockLoadInfo *pLoadInfo = taosMemoryCalloc(1, sizeof(SSttBlockLoadInfo));
  if (pLoadInfo == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

  pLoadInfo->blockIndex[0] = -1;
  pLoadInfo->blockIndex[1] = -1;
  pLoadInfo->currentLoadBlockIndex = 1;

  int32_t code = tBlockDataCreate(&pLoadInfo->blockData[0]);
  if (code) {
    terrno = code;
  }

  code = tBlockDataCreate(&pLoadInfo->blockData[1]);
  if (code) {
    terrno = code;
  }

  pLoadInfo->aSttBlk = taosArrayInit(4, sizeof(SSttBlk));
  pLoadInfo->pSchema = pSchema;
  pLoadInfo->colIds = colList;
  pLoadInfo->numOfCols = numOfCols;

  return pLoadInfo;
}

H
Hongze Cheng 已提交
85
void resetLastBlockLoadInfo(SSttBlockLoadInfo *pLoadInfo) {
86
  for (int32_t i = 0; i < 1; ++i) {
87 88 89
    pLoadInfo[i].currentLoadBlockIndex = 1;
    pLoadInfo[i].blockIndex[0] = -1;
    pLoadInfo[i].blockIndex[1] = -1;
90

91
    taosArrayClear(pLoadInfo[i].aSttBlk);
H
Haojun Liao 已提交
92 93 94

    pLoadInfo[i].elapsedTime = 0;
    pLoadInfo[i].loadBlocks = 0;
95
    pLoadInfo[i].sttBlockLoaded = false;
H
Haojun Liao 已提交
96 97 98
  }
}

H
Hongze Cheng 已提交
99
void getLastBlockLoadInfo(SSttBlockLoadInfo *pLoadInfo, int64_t *blocks, double *el) {
100
  for (int32_t i = 0; i < 1; ++i) {
H
Haojun Liao 已提交
101 102
    *el += pLoadInfo[i].elapsedTime;
    *blocks += pLoadInfo[i].loadBlocks;
103 104 105
  }
}

106 107
static void freeTombBlock(void *param) {
  STombBlock **pTombBlock = (STombBlock **)param;
H
Haojun Liao 已提交
108 109 110 111
  tTombBlockDestroy(*pTombBlock);
  taosMemoryFree(*pTombBlock);
}

H
Hongze Cheng 已提交
112
void *destroyLastBlockLoadInfo(SSttBlockLoadInfo *pLoadInfo) {
H
Haojun Liao 已提交
113 114 115 116
  if (pLoadInfo == NULL) {
    return NULL;
  }

117
  for (int32_t i = 0; i < 1; ++i) {
118 119 120 121
    pLoadInfo[i].currentLoadBlockIndex = 1;
    pLoadInfo[i].blockIndex[0] = -1;
    pLoadInfo[i].blockIndex[1] = -1;

H
Hongze Cheng 已提交
122 123
    tBlockDataDestroy(&pLoadInfo[i].blockData[0]);
    tBlockDataDestroy(&pLoadInfo[i].blockData[1]);
124 125 126 127 128 129 130 131

    taosArrayDestroy(pLoadInfo[i].aSttBlk);
  }

  taosMemoryFree(pLoadInfo);
  return NULL;
}

132
static void destroyLDataIter(SLDataIter *pIter) {
133 134 135
  tLDataIterClose2(pIter);
  destroyLastBlockLoadInfo(pIter->pBlockLoadInfo);
  taosMemoryFree(pIter);
136 137
}

138
void *destroySttBlockReader(SArray *pLDataIterArray, int64_t *blocks, double *el) {
139 140
  if (pLDataIterArray == NULL) {
    return NULL;
H
Haojun Liao 已提交
141 142
  }

143
  int32_t numOfLevel = taosArrayGetSize(pLDataIterArray);
144 145 146 147
  for (int32_t i = 0; i < numOfLevel; ++i) {
    SArray *pList = taosArrayGetP(pLDataIterArray, i);
    for (int32_t j = 0; j < taosArrayGetSize(pList); ++j) {
      SLDataIter *pIter = taosArrayGetP(pList, j);
148 149 150 151 152
      *el += pIter->pBlockLoadInfo->elapsedTime;
      *blocks += pIter->pBlockLoadInfo->loadBlocks;
      destroyLDataIter(pIter);
    }
    taosArrayDestroy(pList);
H
Haojun Liao 已提交
153
  }
154 155 156

  taosArrayDestroy(pLDataIterArray);
  return NULL;
H
Haojun Liao 已提交
157 158
}

H
Hongze Cheng 已提交
159
static SBlockData *loadLastBlock(SLDataIter *pIter, const char *idStr) {
160 161
  int32_t code = 0;

H
Hongze Cheng 已提交
162 163
  SSttBlockLoadInfo *pInfo = pIter->pBlockLoadInfo;
  if (pInfo->blockIndex[0] == pIter->iSttBlk) {
164 165 166 167 168
    if (pInfo->currentLoadBlockIndex != 0) {
      tsdbDebug("current load index is set to 0, block index:%d, file index:%d, due to uid:%" PRIu64 ", load data, %s",
                pIter->iSttBlk, pIter->iStt, pIter->uid, idStr);
      pInfo->currentLoadBlockIndex = 0;
    }
169 170 171
    return &pInfo->blockData[0];
  }

172
  if (pInfo->blockIndex[1] == pIter->iSttBlk) {
173
    if (pInfo->currentLoadBlockIndex != 1) {
H
Hongze Cheng 已提交
174
      tsdbDebug("current load index is set to 1, block index:%d, file index:%d, due to uid:%" PRIu64 ", load data, %s",
175 176 177
                pIter->iSttBlk, pIter->iStt, pIter->uid, idStr);
      pInfo->currentLoadBlockIndex = 1;
    }
178 179 180
    return &pInfo->blockData[1];
  }

181
  if (pIter->pSttBlk == NULL || pInfo->pSchema == NULL) {
H
Haojun Liao 已提交
182 183 184 185
    return NULL;
  }

  // current block not loaded yet
186
  pInfo->currentLoadBlockIndex ^= 1;
H
Haojun Liao 已提交
187
  int64_t st = taosGetTimestampUs();
188

H
Haojun Liao 已提交
189
  SBlockData *pBlock = &pInfo->blockData[pInfo->currentLoadBlockIndex];
190 191
  code = tsdbSttFileReadBlockDataByColumn(pIter->pReader, pIter->pSttBlk, pBlock, pInfo->pSchema, &pInfo->colIds[1],
                                          pInfo->numOfCols - 1);
H
Haojun Liao 已提交
192 193 194
  if (code != TSDB_CODE_SUCCESS) {
    goto _exit;
  }
H
Haojun Liao 已提交
195

H
Haojun Liao 已提交
196 197 198
  double el = (taosGetTimestampUs() - st) / 1000.0;
  pInfo->elapsedTime += el;
  pInfo->loadBlocks += 1;
199

H
Haojun Liao 已提交
200
  tsdbDebug("read last block, total load:%d, trigger by uid:%" PRIu64
201
            ", last file index:%d, last block index:%d, entry:%d, rows:%d, %p, elapsed time:%.2f ms, %s",
dengyihao's avatar
dengyihao 已提交
202 203
            pInfo->loadBlocks, pIter->uid, pIter->iStt, pIter->iSttBlk, pInfo->currentLoadBlockIndex, pBlock->nRow,
            pBlock, el, idStr);
204

H
Haojun Liao 已提交
205 206
  pInfo->blockIndex[pInfo->currentLoadBlockIndex] = pIter->iSttBlk;
  pIter->iRow = (pIter->backward) ? pInfo->blockData[pInfo->currentLoadBlockIndex].nRow : -1;
H
Haojun Liao 已提交
207

208 209
  tsdbDebug("last block index list:%d, %d, rowIndex:%d %s", pInfo->blockIndex[0], pInfo->blockIndex[1], pIter->iRow,
            idStr);
210 211
  return &pInfo->blockData[pInfo->currentLoadBlockIndex];

H
Hongze Cheng 已提交
212
_exit:
213 214 215 216 217
  if (code != TSDB_CODE_SUCCESS) {
    terrno = code;
  }

  return NULL;
218 219
}

220
// find the earliest block that contains the required records
H
Hongze Cheng 已提交
221 222
static FORCE_INLINE int32_t findEarliestIndex(int32_t index, uint64_t uid, const SSttBlk *pBlockList, int32_t num,
                                              int32_t backward) {
223
  int32_t i = index;
H
Hongze Cheng 已提交
224
  int32_t step = backward ? 1 : -1;
H
Haojun Liao 已提交
225
  while (i >= 0 && i < num && uid >= pBlockList[i].minUid && uid <= pBlockList[i].maxUid) {
226 227 228 229 230
    i += step;
  }
  return i - step;
}

H
Hongze Cheng 已提交
231
static int32_t binarySearchForStartBlock(SSttBlk *pBlockList, int32_t num, uint64_t uid, int32_t backward) {
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
  int32_t midPos = -1;
  if (num <= 0) {
    return -1;
  }

  int32_t firstPos = 0;
  int32_t lastPos = num - 1;

  // find the first position which is bigger than the key
  if ((uid > pBlockList[lastPos].maxUid) || (uid < pBlockList[firstPos].minUid)) {
    return -1;
  }

  while (1) {
    if (uid >= pBlockList[firstPos].minUid && uid <= pBlockList[firstPos].maxUid) {
247
      return findEarliestIndex(firstPos, uid, pBlockList, num, backward);
248 249 250 251 252 253 254 255 256 257 258 259 260 261
    }

    if (uid > pBlockList[lastPos].maxUid || uid < pBlockList[firstPos].minUid) {
      return -1;
    }

    int32_t numOfRows = lastPos - firstPos + 1;
    midPos = (numOfRows >> 1u) + firstPos;

    if (uid < pBlockList[midPos].minUid) {
      lastPos = midPos - 1;
    } else if (uid > pBlockList[midPos].maxUid) {
      firstPos = midPos + 1;
    } else {
262
      return findEarliestIndex(midPos, uid, pBlockList, num, backward);
263 264 265 266
    }
  }
}

H
Hongze Cheng 已提交
267 268
static FORCE_INLINE int32_t findEarliestRow(int32_t index, uint64_t uid, const uint64_t *uidList, int32_t num,
                                            int32_t backward) {
269
  int32_t i = index;
H
Hongze Cheng 已提交
270
  int32_t step = backward ? 1 : -1;
H
Haojun Liao 已提交
271
  while (i >= 0 && i < num && uid == uidList[i]) {
272 273 274 275 276
    i += step;
  }
  return i - step;
}

H
Hongze Cheng 已提交
277
static int32_t binarySearchForStartRowIndex(uint64_t *uidList, int32_t num, uint64_t uid, int32_t backward) {
278 279 280 281 282 283 284 285 286 287
  int32_t firstPos = 0;
  int32_t lastPos = num - 1;

  // find the first position which is bigger than the key
  if ((uid > uidList[lastPos]) || (uid < uidList[firstPos])) {
    return -1;
  }

  while (1) {
    if (uid == uidList[firstPos]) {
288
      return findEarliestRow(firstPos, uid, uidList, num, backward);
289 290 291 292 293 294 295 296 297 298 299 300 301 302
    }

    if (uid > uidList[lastPos] || uid < uidList[firstPos]) {
      return -1;
    }

    int32_t numOfRows = lastPos - firstPos + 1;
    int32_t midPos = (numOfRows >> 1u) + firstPos;

    if (uid < uidList[midPos]) {
      lastPos = midPos - 1;
    } else if (uid > uidList[midPos]) {
      firstPos = midPos + 1;
    } else {
303
      return findEarliestRow(midPos, uid, uidList, num, backward);
304 305 306 307
    }
  }
}

308
int32_t tLDataIterOpen(struct SLDataIter *pIter, SDataFReader *pReader, int32_t iStt, int8_t backward, uint64_t suid,
309 310
                       uint64_t uid, STimeWindow *pTimeWindow, SVersionRange *pRange, SSttBlockLoadInfo *pBlockLoadInfo,
                       const char *idStr, bool strictTimeRange) {
311 312 313
  return 0;
}

314 315
static int32_t extractSttBlockInfo(SLDataIter *pIter, const TSttBlkArray *pArray, SSttBlockLoadInfo *pBlockLoadInfo,
                                   uint64_t suid) {
316 317 318 319 320 321 322 323 324
  if (TARRAY2_SIZE(pArray) <= 0) {
    return TSDB_CODE_SUCCESS;
  }

  SSttBlk *pStart = &pArray->data[0];
  SSttBlk *pEnd = &pArray->data[TARRAY2_SIZE(pArray) - 1];

  // all identical
  if (pStart->suid == pEnd->suid) {
325
    if (pStart->suid != suid) {  // no qualified stt block existed
326 327 328 329 330 331 332 333 334 335
      taosArrayClear(pBlockLoadInfo->aSttBlk);
      pIter->iSttBlk = -1;
      return TSDB_CODE_SUCCESS;
    } else {  // all blocks are qualified
      taosArrayClear(pBlockLoadInfo->aSttBlk);
      taosArrayAddBatch(pBlockLoadInfo->aSttBlk, pArray->data, pArray->size);
    }
  } else {
    SArray *pTmp = taosArrayInit(TARRAY2_SIZE(pArray), sizeof(SSttBlk));
    for (int32_t i = 0; i < TARRAY2_SIZE(pArray); ++i) {
336
      SSttBlk *p = &pArray->data[i];
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
      if (p->suid < suid) {
        continue;
      }

      if (p->suid == suid) {
        taosArrayPush(pTmp, p);
      } else if (p->suid > suid) {
        break;
      }
    }

    taosArrayDestroy(pBlockLoadInfo->aSttBlk);
    pBlockLoadInfo->aSttBlk = pTmp;
  }

  return TSDB_CODE_SUCCESS;
}

355 356 357
static int32_t uidComparFn(const void *p1, const void *p2) {
  const uint64_t *uid1 = p1;
  const uint64_t *uid2 = p2;
358 359
  return (*uid1) - (*uid2);
}
360

361 362 363 364
static bool existsFromSttBlkStatis(const TStatisBlkArray *pStatisBlkArray, uint64_t suid, uint64_t uid,
                                   SSttFileReader *pReader) {
  if (TARRAY2_SIZE(pStatisBlkArray) <= 0) {
    return true;
365 366
  }

367 368 369
  int32_t i = 0;
  for (i = 0; i < TARRAY2_SIZE(pStatisBlkArray); ++i) {
    SStatisBlk *p = &pStatisBlkArray->data[i];
H
Haojun Liao 已提交
370
    if (p->minTbid.suid <= suid && p->maxTbid.suid >= suid) {
371
      break;
372
    }
373
  }
374

375 376 377 378 379 380 381 382 383 384
  //  for (; i < TARRAY2_SIZE(pStatisBlkArray); ++i) {
  //    SStatisBlk *p = &pStatisBlkArray->data[i];
  //    if (p->minTbid.uid <= uid && p->maxTbid.uid >= uid) {
  //      break;
  //    }
  //
  //    if (p->maxTbid.uid < uid) {
  //      break;
  //    }
  //  }
385

386 387
  if (i >= TARRAY2_SIZE(pStatisBlkArray)) {
    return false;
388 389
  }

390 391 392 393 394
  SStatisBlk    *p = &pStatisBlkArray->data[i];
  STbStatisBlock block = {0};
  tsdbSttFileReadStatisBlock(pReader, p, &block);

  int32_t index = tarray2SearchIdx(block.uid, &uid, sizeof(int64_t), uidComparFn, TD_EQ);
H
Haojun Liao 已提交
395
  tStatisBlockDestroy(&block);
396

H
Haojun Liao 已提交
397
  return (index != -1);
398 399
}

400 401 402 403
int32_t tLDataIterOpen2(struct SLDataIter *pIter, SSttFileReader *pSttFileReader, int32_t iStt, int8_t backward,
                        uint64_t suid, uint64_t uid, STimeWindow *pTimeWindow, SVersionRange *pRange,
                        SSttBlockLoadInfo *pBlockLoadInfo, const char *idStr, bool strictTimeRange,
                        _load_tomb_fn loadTombFn, void *pReader1) {
H
Haojun Liao 已提交
404 405
  int32_t code = TSDB_CODE_SUCCESS;

406 407 408
  pIter->uid = uid;
  pIter->iStt = iStt;
  pIter->backward = backward;
409 410 411 412
  pIter->verRange.minVer = pRange->minVer;
  pIter->verRange.maxVer = pRange->maxVer;
  pIter->timeWindow.skey = pTimeWindow->skey;
  pIter->timeWindow.ekey = pTimeWindow->ekey;
H
Haojun Liao 已提交
413
  pIter->pReader = pSttFileReader;
414
  pIter->pBlockLoadInfo = pBlockLoadInfo;
415

416
  if (!pBlockLoadInfo->sttBlockLoaded) {
417
    int64_t st = taosGetTimestampUs();
418

419
    const TSttBlkArray *pSttBlkArray = NULL;
420
    pBlockLoadInfo->sttBlockLoaded = true;
421

422 423
    // load the stt block info for each stt-block
    code = tsdbSttFileReadSttBlk(pIter->pReader, &pSttBlkArray);
424
    if (code != TSDB_CODE_SUCCESS) {
425
      tsdbError("load stt blk failed, code:%s, %s", tstrerror(code), idStr);
426
      return code;
427 428
    }

429
    code = extractSttBlockInfo(pIter, pSttBlkArray, pBlockLoadInfo, suid);
430
    if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
431
      tsdbError("load stt block info failed, code:%s, %s", tstrerror(code), idStr);
432
      return code;
433
    }
434

435 436 437 438 439 440 441 442
    // load stt blocks statis for all stt-blocks, to decide if the data of queried table exists in current stt file
    code = tsdbSttFileReadStatisBlk(pIter->pReader, (const TStatisBlkArray **)&pBlockLoadInfo->pSttStatisBlkArray);
    if (code != TSDB_CODE_SUCCESS) {
      tsdbError("failed to load stt block statistics, code:%s, %s", tstrerror(code), idStr);
      return code;
    }

    code = loadTombFn(pReader1, pIter->pReader, pIter->pBlockLoadInfo);
H
Haojun Liao 已提交
443

H
Hongze Cheng 已提交
444
    double el = (taosGetTimestampUs() - st) / 1000.0;
445 446 447
    tsdbDebug("load the stt file info completed, elapsed time:%.2fms, %s", el, idStr);
  }

448 449 450 451 452 453
  //  bool exists = existsFromSttBlkStatis(pBlockLoadInfo->pSttStatisBlkArray, suid, uid, pIter->pReader);
  //  if (!exists) {
  //    pIter->iSttBlk = -1;
  //    pIter->pSttBlk = NULL;
  //    return TSDB_CODE_SUCCESS;
  //  }
H
Hongze Cheng 已提交
454

455 456
  // find the start block, actually we could load the position to avoid repeatly searching for the start position when
  // the skey is updated.
H
Haojun Liao 已提交
457 458
  size_t size = taosArrayGetSize(pBlockLoadInfo->aSttBlk);
  pIter->iSttBlk = binarySearchForStartBlock(pBlockLoadInfo->aSttBlk->pData, size, uid, backward);
459
  if (pIter->iSttBlk != -1) {
H
Haojun Liao 已提交
460
    pIter->pSttBlk = taosArrayGet(pBlockLoadInfo->aSttBlk, pIter->iSttBlk);
461 462 463 464 465
    pIter->iRow = (pIter->backward) ? pIter->pSttBlk->nRow : -1;

    if ((!backward) && ((strictTimeRange && pIter->pSttBlk->minKey >= pIter->timeWindow.ekey) ||
                        (!strictTimeRange && pIter->pSttBlk->minKey > pIter->timeWindow.ekey))) {
      pIter->pSttBlk = NULL;
466 467
    }

468 469 470 471
    if (backward && ((strictTimeRange && pIter->pSttBlk->maxKey <= pIter->timeWindow.skey) ||
                     (!strictTimeRange && pIter->pSttBlk->maxKey < pIter->timeWindow.skey))) {
      pIter->pSttBlk = NULL;
      pIter->ignoreEarlierTs = true;
472
    }
H
Hongze Cheng 已提交
473 474
  }

H
Haojun Liao 已提交
475
  return code;
H
Hongze Cheng 已提交
476 477
}

H
Haojun Liao 已提交
478 479
void tLDataIterClose2(SLDataIter *pIter) {
  tsdbSttFileReaderClose(&pIter->pReader);
H
Haojun Liao 已提交
480
  pIter->pReader = NULL;
H
Haojun Liao 已提交
481
}
H
Hongze Cheng 已提交
482

H
Hongze Cheng 已提交
483
void tLDataIterNextBlock(SLDataIter *pIter, const char *idStr) {
H
Hongze Cheng 已提交
484
  int32_t step = pIter->backward ? -1 : 1;
485 486
  int32_t oldIndex = pIter->iSttBlk;

H
Hongze Cheng 已提交
487
  pIter->iSttBlk += step;
H
Hongze Cheng 已提交
488

489
  int32_t index = -1;
H
Haojun Liao 已提交
490
  size_t  size = pIter->pBlockLoadInfo->aSttBlk->size;
H
Hongze Cheng 已提交
491
  for (int32_t i = pIter->iSttBlk; i < size && i >= 0; i += step) {
492
    SSttBlk *p = taosArrayGet(pIter->pBlockLoadInfo->aSttBlk, i);
493 494 495 496 497
    if ((!pIter->backward) && p->minUid > pIter->uid) {
      break;
    }

    if (pIter->backward && p->maxUid < pIter->uid) {
498 499 500
      break;
    }

501
    // check uid firstly
502
    if (p->minUid <= pIter->uid && p->maxUid >= pIter->uid) {
503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525
      if ((!pIter->backward) && p->minKey > pIter->timeWindow.ekey) {
        break;
      }

      if (pIter->backward && p->maxKey < pIter->timeWindow.skey) {
        break;
      }

      // check time range secondly
      if (p->minKey <= pIter->timeWindow.ekey && p->maxKey >= pIter->timeWindow.skey) {
        if ((!pIter->backward) && p->minVer > pIter->verRange.maxVer) {
          break;
        }

        if (pIter->backward && p->maxVer < pIter->verRange.minVer) {
          break;
        }

        if (p->minVer <= pIter->verRange.maxVer && p->maxVer >= pIter->verRange.minVer) {
          index = i;
          break;
        }
      }
526 527 528
    }
  }

529 530
  pIter->pSttBlk = NULL;
  if (index != -1) {
H
Haojun Liao 已提交
531
    pIter->iSttBlk = index;
532
    pIter->pSttBlk = (SSttBlk *)taosArrayGet(pIter->pBlockLoadInfo->aSttBlk, pIter->iSttBlk);
533 534
    tsdbDebug("try next last file block:%d from stt fileIdx:%d, trigger by uid:%" PRIu64 ", file index:%d, %s",
              pIter->iSttBlk, oldIndex, pIter->uid, pIter->iStt, idStr);
535
  } else {
536
    tsdbDebug("no more last block qualified, uid:%" PRIu64 ", file index:%d, %s", pIter->uid, oldIndex, idStr);
537 538 539
  }
}

H
Hongze Cheng 已提交
540 541
static void findNextValidRow(SLDataIter *pIter, const char *idStr) {
  bool    hasVal = false;
542
  int32_t step = pIter->backward ? -1 : 1;
H
Hongze Cheng 已提交
543
  int32_t i = pIter->iRow;
544

545
  SBlockData *pData = loadLastBlock(pIter, idStr);
546

547
  // mostly we only need to find the start position for a given table
548 549
  if ((((i == 0) && (!pIter->backward)) || (i == pData->nRow - 1 && pIter->backward)) && pData->aUid != NULL) {
    i = binarySearchForStartRowIndex((uint64_t *)pData->aUid, pData->nRow, pIter->uid, pIter->backward);
H
Haojun Liao 已提交
550
    if (i == -1) {
551
      tsdbDebug("failed to find the data in pBlockData, uid:%" PRIu64 " , %s", pIter->uid, idStr);
H
Haojun Liao 已提交
552 553 554
      pIter->iRow = -1;
      return;
    }
555 556
  }

557 558
  for (; i < pData->nRow && i >= 0; i += step) {
    if (pData->aUid != NULL) {
559
      if (!pIter->backward) {
560
        if (pData->aUid[i] > pIter->uid) {
561 562 563
          break;
        }
      } else {
564
        if (pData->aUid[i] < pIter->uid) {
565 566 567 568 569
          break;
        }
      }
    }

570
    int64_t ts = pData->aTSKEY[i];
H
Hongze Cheng 已提交
571
    if (!pIter->backward) {               // asc
572 573 574 575 576 577 578 579 580 581 582
      if (ts > pIter->timeWindow.ekey) {  // no more data
        break;
      } else if (ts < pIter->timeWindow.skey) {
        continue;
      }
    } else {
      if (ts < pIter->timeWindow.skey) {
        break;
      } else if (ts > pIter->timeWindow.ekey) {
        continue;
      }
583 584
    }

585
    int64_t ver = pData->aVersion[i];
586 587 588 589 590 591 592 593 594 595 596
    if (ver < pIter->verRange.minVer) {
      continue;
    }

    // todo opt handle desc case
    if (ver > pIter->verRange.maxVer) {
      continue;
    }

    hasVal = true;
    break;
H
Hongze Cheng 已提交
597
  }
598

H
Hongze Cheng 已提交
599
  pIter->iRow = (hasVal) ? i : -1;
H
Hongze Cheng 已提交
600 601
}

H
Hongze Cheng 已提交
602
bool tLDataIterNextRow(SLDataIter *pIter, const char *idStr) {
H
Hongze Cheng 已提交
603
  int32_t step = pIter->backward ? -1 : 1;
H
Haojun Liao 已提交
604
  terrno = TSDB_CODE_SUCCESS;
605 606

  // no qualified last file block in current file, no need to fetch row
H
Hongze Cheng 已提交
607
  if (pIter->pSttBlk == NULL) {
608 609
    return false;
  }
H
Hongze Cheng 已提交
610

H
Hongze Cheng 已提交
611
  int32_t     iBlockL = pIter->iSttBlk;
H
Haojun Liao 已提交
612
  SBlockData *pBlockData = loadLastBlock(pIter, idStr);
H
Haojun Liao 已提交
613
  if (pBlockData == NULL || terrno != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
614 615 616
    goto _exit;
  }

617 618
  pIter->iRow += step;

H
Hongze Cheng 已提交
619
  while (1) {
620
    bool skipBlock = false;
H
Haojun Liao 已提交
621
    findNextValidRow(pIter, idStr);
622

623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646
    if (pIter->pBlockLoadInfo->checkRemainingRow) {
      skipBlock = true;
      int16_t *aCols = pIter->pBlockLoadInfo->colIds;
      int      nCols = pIter->pBlockLoadInfo->numOfCols;
      bool     isLast = pIter->pBlockLoadInfo->isLast;
      for (int inputColIndex = 0; inputColIndex < nCols; ++inputColIndex) {
        for (int colIndex = 0; colIndex < pBlockData->nColData; ++colIndex) {
          SColData *pColData = &pBlockData->aColData[colIndex];
          int16_t   cid = pColData->cid;

          if (cid == aCols[inputColIndex]) {
            if (isLast && (pColData->flag & HAS_VALUE)) {
              skipBlock = false;
              break;
            } else if (pColData->flag & (HAS_VALUE | HAS_NULL)) {
              skipBlock = false;
              break;
            }
          }
        }
      }
    }

    if (skipBlock || pIter->iRow >= pBlockData->nRow || pIter->iRow < 0) {
647
      tLDataIterNextBlock(pIter, idStr);
H
Hongze Cheng 已提交
648
      if (pIter->pSttBlk == NULL) {  // no more data
649 650 651 652
        goto _exit;
      }
    } else {
      break;
H
Hongze Cheng 已提交
653 654
    }

H
Hongze Cheng 已提交
655
    if (iBlockL != pIter->iSttBlk) {
H
Haojun Liao 已提交
656
      pBlockData = loadLastBlock(pIter, idStr);
657 658 659
      if (pBlockData == NULL) {
        goto _exit;
      }
H
Haojun Liao 已提交
660 661

      // set start row index
662
      pIter->iRow = pIter->backward ? pBlockData->nRow - 1 : 0;
H
Hongze Cheng 已提交
663 664 665
    }
  }

666 667 668
  pIter->rInfo.suid = pBlockData->suid;
  pIter->rInfo.uid = pBlockData->uid;
  pIter->rInfo.row = tsdbRowFromBlockData(pBlockData, pIter->iRow);
H
Hongze Cheng 已提交
669 670

_exit:
671
  return (terrno == TSDB_CODE_SUCCESS) && (pIter->pSttBlk != NULL) && (pBlockData != NULL);
H
Hongze Cheng 已提交
672 673
}

H
Hongze Cheng 已提交
674
SRowInfo *tLDataIterGet(SLDataIter *pIter) { return &pIter->rInfo; }
H
Hongze Cheng 已提交
675 676

// SMergeTree =================================================
H
Hongze Cheng 已提交
677 678 679
static FORCE_INLINE int32_t tLDataIterCmprFn(const SRBTreeNode *p1, const SRBTreeNode *p2) {
  SLDataIter *pIter1 = (SLDataIter *)(((uint8_t *)p1) - offsetof(SLDataIter, node));
  SLDataIter *pIter2 = (SLDataIter *)(((uint8_t *)p2) - offsetof(SLDataIter, node));
H
Hongze Cheng 已提交
680

681 682
  TSDBKEY key1 = TSDBROW_KEY(&pIter1->rInfo.row);
  TSDBKEY key2 = TSDBROW_KEY(&pIter2->rInfo.row);
H
Hongze Cheng 已提交
683

684 685 686 687 688 689 690 691 692 693 694 695 696
  if (key1.ts < key2.ts) {
    return -1;
  } else if (key1.ts > key2.ts) {
    return 1;
  } else {
    if (key1.version < key2.version) {
      return -1;
    } else if (key1.version > key2.version) {
      return 1;
    } else {
      return 0;
    }
  }
H
Hongze Cheng 已提交
697 698
}

699 700 701 702
static FORCE_INLINE int32_t tLDataIterDescCmprFn(const SRBTreeNode *p1, const SRBTreeNode *p2) {
  return -1 * tLDataIterCmprFn(p1, p2);
}

703
int32_t tMergeTreeOpen(SMergeTree *pMTree, int8_t backward, SDataFReader *pFReader, uint64_t suid, uint64_t uid,
704
                       STimeWindow *pTimeWindow, SVersionRange *pVerRange, SSttBlockLoadInfo *pBlockLoadInfo,
705
                       bool destroyLoadInfo, const char *idStr, bool strictTimeRange, SLDataIter *pLDataIter) {
706 707
  int32_t code = TSDB_CODE_SUCCESS;

H
Hongze Cheng 已提交
708
  pMTree->backward = backward;
709
  pMTree->pIter = NULL;
H
Haojun Liao 已提交
710
  pMTree->idStr = idStr;
711

dengyihao's avatar
dengyihao 已提交
712
  if (!pMTree->backward) {  // asc
713
    tRBTreeCreate(&pMTree->rbt, tLDataIterCmprFn);
dengyihao's avatar
dengyihao 已提交
714
  } else {  // desc
715 716
    tRBTreeCreate(&pMTree->rbt, tLDataIterDescCmprFn);
  }
717

718 719
  pMTree->pLoadInfo = pBlockLoadInfo;
  pMTree->destroyLoadInfo = destroyLoadInfo;
720
  pMTree->ignoreEarlierTs = false;
721

H
Hongze Cheng 已提交
722
  for (int32_t i = 0; i < pFReader->pSet->nSttF; ++i) {  // open all last file
723 724
    memset(&pLDataIter[i], 0, sizeof(SLDataIter));
    code = tLDataIterOpen(&pLDataIter[i], pFReader, i, pMTree->backward, suid, uid, pTimeWindow, pVerRange,
725
                          &pMTree->pLoadInfo[i], pMTree->idStr, strictTimeRange);
726 727 728 729
    if (code != TSDB_CODE_SUCCESS) {
      goto _end;
    }

730
    bool hasVal = tLDataIterNextRow(&pLDataIter[i], pMTree->idStr);
731
    if (hasVal) {
732
      tMergeTreeAddIter(pMTree, &pLDataIter[i]);
733
    } else {
734
      if (!pMTree->ignoreEarlierTs) {
735
        pMTree->ignoreEarlierTs = pLDataIter[i].ignoreEarlierTs;
736
      }
737 738
    }
  }
739 740 741

  return code;

H
Hongze Cheng 已提交
742
_end:
743 744
  tMergeTreeClose(pMTree);
  return code;
H
Hongze Cheng 已提交
745
}
H
Hongze Cheng 已提交
746

747
int32_t tMergeTreeOpen2(SMergeTree *pMTree, SMergeTreeConf *pConf) {
H
Haojun Liao 已提交
748
  int32_t code = TSDB_CODE_SUCCESS;
749

H
Haojun Liao 已提交
750
  pMTree->pIter = NULL;
751 752
  pMTree->backward = pConf->backward;
  pMTree->idStr = pConf->idstr;
753

H
Haojun Liao 已提交
754 755 756 757 758
  if (!pMTree->backward) {  // asc
    tRBTreeCreate(&pMTree->rbt, tLDataIterCmprFn);
  } else {  // desc
    tRBTreeCreate(&pMTree->rbt, tLDataIterDescCmprFn);
  }
759

H
Haojun Liao 已提交
760
  pMTree->ignoreEarlierTs = false;
761

762
  int32_t size = ((STFileSet *)pConf->pCurrentFileset)->lvlArr->size;
H
Haojun Liao 已提交
763 764 765
  if (size == 0) {
    goto _end;
  }
766

767
  // add the list/iter placeholder
768
  while (taosArrayGetSize(pConf->pSttFileBlockIterArray) < size) {
769
    SArray *pList = taosArrayInit(4, POINTER_BYTES);
770
    taosArrayPush(pConf->pSttFileBlockIterArray, &pList);
771
  }
772

773
  for (int32_t j = 0; j < size; ++j) {
774
    SSttLvl *pSttLevel = ((STFileSet *)pConf->pCurrentFileset)->lvlArr->data[j];
775
    ASSERT(pSttLevel->level == j);
776

777
    SArray *pList = taosArrayGetP(pConf->pSttFileBlockIterArray, j);
778
    int32_t numOfIter = taosArrayGetSize(pList);
H
Haojun Liao 已提交
779

780 781
    if (numOfIter < TARRAY2_SIZE(pSttLevel->fobjArr)) {
      int32_t inc = TARRAY2_SIZE(pSttLevel->fobjArr) - numOfIter;
782
      for (int32_t k = 0; k < inc; ++k) {
783 784
        SLDataIter *pIter = taosMemoryCalloc(1, sizeof(SLDataIter));
        taosArrayPush(pList, &pIter);
H
Haojun Liao 已提交
785
      }
H
Haojun Liao 已提交
786
    }
H
Haojun Liao 已提交
787

788
    for (int32_t i = 0; i < TARRAY2_SIZE(pSttLevel->fobjArr); ++i) {  // open all last file
789
      SLDataIter *pIter = taosArrayGetP(pList, i);
H
Haojun Liao 已提交
790

791 792
      SSttFileReader    *pSttFileReader = pIter->pReader;
      SSttBlockLoadInfo *pLoadInfo = pIter->pBlockLoadInfo;
793 794 795

      // open stt file reader if not
      if (pSttFileReader == NULL) {
796
        SSttFileReaderConfig conf = {.tsdb = pConf->pTsdb, .szPage = pConf->pTsdb->pVnode->config.tsdbPageSize};
797 798 799 800 801 802 803 804 805
        conf.file[0] = *pSttLevel->fobjArr->data[i]->f;

        code = tsdbSttFileReaderOpen(pSttLevel->fobjArr->data[i]->fname, &conf, &pSttFileReader);
        if (code != TSDB_CODE_SUCCESS) {
          return code;
        }
      }

      if (pLoadInfo == NULL) {
806
        pLoadInfo = tCreateOneLastBlockLoadInfo(pConf->pSchema, pConf->pCols, pConf->numOfCols);
807 808 809
      }

      memset(pIter, 0, sizeof(SLDataIter));
810
      code = tLDataIterOpen2(pIter, pSttFileReader, i, pMTree->backward, pConf->suid, pConf->uid, &pConf->timewindow,
811 812
                             &pConf->verRange, pLoadInfo, pMTree->idStr, pConf->strictTimeRange, pConf->loadTombFn,
                             pConf->pReader);
813 814 815 816 817 818 819 820 821 822 823
      if (code != TSDB_CODE_SUCCESS) {
        goto _end;
      }

      bool hasVal = tLDataIterNextRow(pIter, pMTree->idStr);
      if (hasVal) {
        tMergeTreeAddIter(pMTree, pIter);
      } else {
        if (!pMTree->ignoreEarlierTs) {
          pMTree->ignoreEarlierTs = pIter->ignoreEarlierTs;
        }
H
Haojun Liao 已提交
824
      }
825
    }
H
Haojun Liao 已提交
826
  }
827

H
Haojun Liao 已提交
828
  return code;
829

H
Haojun Liao 已提交
830 831 832
_end:
  tMergeTreeClose(pMTree);
  return code;
833 834
}

835 836
void tMergeTreeAddIter(SMergeTree *pMTree, SLDataIter *pIter) { tRBTreePut(&pMTree->rbt, (SRBTreeNode *)pIter); }

837 838
bool tMergeTreeIgnoreEarlierTs(SMergeTree *pMTree) { return pMTree->ignoreEarlierTs; }

H
Hongze Cheng 已提交
839
bool tMergeTreeNext(SMergeTree *pMTree) {
840 841 842 843
  int32_t code = TSDB_CODE_SUCCESS;
  if (pMTree->pIter) {
    SLDataIter *pIter = pMTree->pIter;

H
Haojun Liao 已提交
844
    bool hasVal = tLDataIterNextRow(pIter, pMTree->idStr);
845 846 847 848 849 850 851
    if (!hasVal) {
      pMTree->pIter = NULL;
    }

    // compare with min in RB Tree
    pIter = (SLDataIter *)tRBTreeMin(&pMTree->rbt);
    if (pMTree->pIter && pIter) {
H
Hongze Cheng 已提交
852
      int32_t c = pMTree->rbt.cmprFn(&pMTree->pIter->node, &pIter->node);
853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871
      if (c > 0) {
        tRBTreePut(&pMTree->rbt, (SRBTreeNode *)pMTree->pIter);
        pMTree->pIter = NULL;
      } else {
        ASSERT(c);
      }
    }
  }

  if (pMTree->pIter == NULL) {
    pMTree->pIter = (SLDataIter *)tRBTreeMin(&pMTree->rbt);
    if (pMTree->pIter) {
      tRBTreeDrop(&pMTree->rbt, (SRBTreeNode *)pMTree->pIter);
    }
  }

  return pMTree->pIter != NULL;
}

H
Hongze Cheng 已提交
872
void tMergeTreeClose(SMergeTree *pMTree) {
873
  pMTree->pIter = NULL;
874 875 876 877
  if (pMTree->destroyLoadInfo) {
    pMTree->pLoadInfo = destroyLastBlockLoadInfo(pMTree->pLoadInfo);
    pMTree->destroyLoadInfo = false;
  }
878
}