tsdbCache.c 55.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/*
 * 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"

18 19
static int32_t tsdbOpenBICache(STsdb *pTsdb) {
  int32_t    code = 0;
20
  SLRUCache *pCache = taosLRUCacheInit(10 * 1024 * 1024, 0, .5);
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
  if (pCache == NULL) {
    code = TSDB_CODE_OUT_OF_MEMORY;
    goto _err;
  }

  taosLRUCacheSetStrictCapacity(pCache, false);

  taosThreadMutexInit(&pTsdb->biMutex, NULL);

_err:
  pTsdb->biCache = pCache;
  return code;
}

static void tsdbCloseBICache(STsdb *pTsdb) {
  SLRUCache *pCache = pTsdb->biCache;
  if (pCache) {
    taosLRUCacheEraseUnrefEntries(pCache);

    taosLRUCacheCleanup(pCache);

    taosThreadMutexDestroy(&pTsdb->biMutex);
  }
}

46
int32_t tsdbOpenCache(STsdb *pTsdb) {
H
Hongze Cheng 已提交
47
  int32_t    code = 0;
48
  SLRUCache *pCache = NULL;
49
  size_t     cfgCapacity = pTsdb->pVnode->config.cacheLastSize * 1024 * 1024;
50

51
  pCache = taosLRUCacheInit(cfgCapacity, 1, .5);
52 53 54 55 56
  if (pCache == NULL) {
    code = TSDB_CODE_OUT_OF_MEMORY;
    goto _err;
  }

57 58 59 60 61 62
  code = tsdbOpenBICache(pTsdb);
  if (code != TSDB_CODE_SUCCESS) {
    code = TSDB_CODE_OUT_OF_MEMORY;
    goto _err;
  }

63
  taosLRUCacheSetStrictCapacity(pCache, false);
64

65 66
  taosThreadMutexInit(&pTsdb->lruMutex, NULL);

67 68 69 70 71
_err:
  pTsdb->lruCache = pCache;
  return code;
}

72 73
void tsdbCloseCache(STsdb *pTsdb) {
  SLRUCache *pCache = pTsdb->lruCache;
74 75 76 77
  if (pCache) {
    taosLRUCacheEraseUnrefEntries(pCache);

    taosLRUCacheCleanup(pCache);
78 79

    taosThreadMutexDestroy(&pTsdb->lruMutex);
80
  }
81 82

  tsdbCloseBICache(pTsdb);
83 84
}

85 86 87 88 89 90 91 92 93 94
static void getTableCacheKey(tb_uid_t uid, int cacheType, char *key, int *len) {
  if (cacheType == 0) {  // last_row
    *(uint64_t *)key = (uint64_t)uid;
  } else {  // last
    *(uint64_t *)key = ((uint64_t)uid) | 0x8000000000000000;
  }

  *len = sizeof(uint64_t);
}

95 96 97 98 99
static void deleteTableCacheLast(const void *key, size_t keyLen, void *value) {
  SArray *pLastArray = (SArray *)value;
  int16_t nCol = taosArrayGetSize(pLastArray);
  for (int16_t iCol = 0; iCol < nCol; ++iCol) {
    SLastCol *pLastCol = (SLastCol *)taosArrayGet(pLastArray, iCol);
100
    if (IS_VAR_DATA_TYPE(pLastCol->colVal.type) && pLastCol->colVal.value.nData > 0) {
101 102 103 104 105 106
      taosMemoryFree(pLastCol->colVal.value.pData);
    }
  }

  taosArrayDestroy(value);
}
107

108
int32_t tsdbCacheDeleteLastrow(SLRUCache *pCache, tb_uid_t uid, TSKEY eKey) {
109
  int32_t code = 0;
110 111 112

  char key[32] = {0};
  int  keyLen = 0;
113

114 115
  // getTableCacheKey(uid, "lr", key, &keyLen);
  getTableCacheKey(uid, 0, key, &keyLen);
116 117
  LRUHandle *h = taosLRUCacheLookup(pCache, key, keyLen);
  if (h) {
118 119 120 121 122 123 124 125 126 127 128 129
    SArray *pLast = (SArray *)taosLRUCacheValue(pCache, h);
    bool    invalidate = false;
    int16_t nCol = taosArrayGetSize(pLast);

    for (int16_t iCol = 0; iCol < nCol; ++iCol) {
      SLastCol *tTsVal = (SLastCol *)taosArrayGet(pLast, iCol);
      if (eKey >= tTsVal->ts) {
        invalidate = true;
        break;
      }
    }

130
    taosLRUCacheRelease(pCache, h, invalidate);
131
    if (invalidate) {
132
      taosLRUCacheErase(pCache, key, keyLen);
133 134 135 136 137 138
    }
  }

  return code;
}

139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
int32_t tsdbCacheDeleteLast(SLRUCache *pCache, tb_uid_t uid, TSKEY eKey) {
  int32_t code = 0;

  char key[32] = {0};
  int  keyLen = 0;

  // getTableCacheKey(uid, "l", key, &keyLen);
  getTableCacheKey(uid, 1, key, &keyLen);
  LRUHandle *h = taosLRUCacheLookup(pCache, key, keyLen);
  if (h) {
    SArray *pLast = (SArray *)taosLRUCacheValue(pCache, h);
    bool    invalidate = false;
    int16_t nCol = taosArrayGetSize(pLast);

    for (int16_t iCol = 0; iCol < nCol; ++iCol) {
      SLastCol *tTsVal = (SLastCol *)taosArrayGet(pLast, iCol);
      if (eKey >= tTsVal->ts) {
        invalidate = true;
        break;
      }
    }

161
    taosLRUCacheRelease(pCache, h, invalidate);
162
    if (invalidate) {
163
      taosLRUCacheErase(pCache, key, keyLen);
164 165 166 167 168 169 170
    }
  }

  return code;
}

int32_t tsdbCacheDelete(SLRUCache *pCache, tb_uid_t uid, TSKEY eKey) {
171 172 173 174
  int32_t code = 0;
  char    key[32] = {0};
  int     keyLen = 0;

175 176 177 178
  // getTableCacheKey(uid, "lr", key, &keyLen);
  getTableCacheKey(uid, 0, key, &keyLen);
  LRUHandle *h = taosLRUCacheLookup(pCache, key, keyLen);
  if (h) {
179 180 181 182 183 184 185 186 187 188 189 190 191
    SArray *pLast = (SArray *)taosLRUCacheValue(pCache, h);
    bool    invalidate = false;
    int16_t nCol = taosArrayGetSize(pLast);

    for (int16_t iCol = 0; iCol < nCol; ++iCol) {
      SLastCol *tTsVal = (SLastCol *)taosArrayGet(pLast, iCol);
      if (eKey >= tTsVal->ts) {
        invalidate = true;
        break;
      }
    }

    if (invalidate) {
192 193 194 195 196 197
      taosLRUCacheRelease(pCache, h, true);
    } else {
      taosLRUCacheRelease(pCache, h, false);
    }
  }

198 199
  // getTableCacheKey(uid, "l", key, &keyLen);
  getTableCacheKey(uid, 1, key, &keyLen);
200
  h = taosLRUCacheLookup(pCache, key, keyLen);
201
  if (h) {
202 203 204
    SArray *pLast = (SArray *)taosLRUCacheValue(pCache, h);
    bool    invalidate = false;
    int16_t nCol = taosArrayGetSize(pLast);
205

206 207 208 209 210 211 212 213 214 215 216 217 218
    for (int16_t iCol = 0; iCol < nCol; ++iCol) {
      SLastCol *tTsVal = (SLastCol *)taosArrayGet(pLast, iCol);
      if (eKey >= tTsVal->ts) {
        invalidate = true;
        break;
      }
    }

    if (invalidate) {
      taosLRUCacheRelease(pCache, h, true);
    } else {
      taosLRUCacheRelease(pCache, h, false);
    }
219 220 221 222 223 224
    // void taosLRUCacheErase(SLRUCache * cache, const void *key, size_t keyLen);
  }

  return code;
}

H
Hongze Cheng 已提交
225
int32_t tsdbCacheInsertLastrow(SLRUCache *pCache, STsdb *pTsdb, tb_uid_t uid, TSDBROW *row, bool dup) {
226 227
  int32_t code = 0;
  STSRow *cacheRow = NULL;
H
Hongze Cheng 已提交
228 229
  char    key[32] = {0};
  int     keyLen = 0;
230

231 232
  // getTableCacheKey(uid, "lr", key, &keyLen);
  getTableCacheKey(uid, 0, key, &keyLen);
233 234
  LRUHandle *h = taosLRUCacheLookup(pCache, key, keyLen);
  if (h) {
235
    STSchema *pTSchema = metaGetTbTSchema(pTsdb->pVnode->pMeta, uid, -1, 1);
H
Hongze Cheng 已提交
236
    TSKEY     keyTs = TSDBROW_TS(row);
237 238 239 240 241 242
    bool      invalidate = false;

    SArray *pLast = (SArray *)taosLRUCacheValue(pCache, h);
    int16_t nCol = taosArrayGetSize(pLast);
    int16_t iCol = 0;

243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
    if (nCol <= 0) {
      nCol = pTSchema->numOfCols;

      STColumn *pTColumn = &pTSchema->columns[0];
      SColVal   tColVal = COL_VAL_VALUE(pTColumn->colId, pTColumn->type, (SValue){.val = keyTs});
      if (taosArrayPush(pLast, &(SLastCol){.ts = keyTs, .colVal = tColVal}) == NULL) {
        terrno = TSDB_CODE_OUT_OF_MEMORY;
        code = TSDB_CODE_OUT_OF_MEMORY;
        goto _invalidate;
      }

      for (iCol = 1; iCol < nCol; ++iCol) {
        SColVal colVal = {0};
        tsdbRowGetColVal(row, pTSchema, iCol, &colVal);

        SLastCol lastCol = {.ts = keyTs, .colVal = colVal};
        if (IS_VAR_DATA_TYPE(colVal.type) && colVal.value.nData > 0) {
          lastCol.colVal.value.pData = taosMemoryMalloc(colVal.value.nData);
          if (lastCol.colVal.value.pData == NULL) {
            terrno = TSDB_CODE_OUT_OF_MEMORY;
            code = TSDB_CODE_OUT_OF_MEMORY;
            goto _invalidate;
          }
          memcpy(lastCol.colVal.value.pData, colVal.value.pData, colVal.value.nData);
        }

        if (taosArrayPush(pLast, &lastCol) == NULL) {
          code = TSDB_CODE_OUT_OF_MEMORY;
          goto _invalidate;
        }
      }

      goto _invalidate;
    }

278 279 280 281 282
    if (nCol != pTSchema->numOfCols) {
      invalidate = true;
      goto _invalidate;
    }

283 284 285 286 287 288 289 290 291 292 293 294 295 296
    SLastCol *tTsVal = (SLastCol *)taosArrayGet(pLast, iCol);
    if (keyTs > tTsVal->ts) {
      STColumn *pTColumn = &pTSchema->columns[0];
      SColVal   tColVal = COL_VAL_VALUE(pTColumn->colId, pTColumn->type, (SValue){.val = keyTs});

      taosArraySet(pLast, iCol, &(SLastCol){.ts = keyTs, .colVal = tColVal});
    }

    for (++iCol; iCol < nCol; ++iCol) {
      SLastCol *tTsVal1 = (SLastCol *)taosArrayGet(pLast, iCol);
      if (keyTs >= tTsVal1->ts) {
        SColVal *tColVal = &tTsVal1->colVal;

        SColVal colVal = {0};
H
Hongze Cheng 已提交
297
        tsdbRowGetColVal(row, pTSchema, iCol, &colVal);
298 299 300 301 302 303

        if (colVal.cid != tColVal->cid) {
          invalidate = true;
          goto _invalidate;
        }

304 305 306 307 308
        if (!COL_VAL_IS_NONE(&colVal)) {
          if (keyTs == tTsVal1->ts && !COL_VAL_IS_NONE(tColVal)) {
            invalidate = true;

            break;
309 310 311 312
          } else {  // new inserting key is greater than cached, update cached entry
            SLastCol lastCol = {.ts = keyTs, .colVal = colVal};
            if (IS_VAR_DATA_TYPE(colVal.type) && colVal.value.nData > 0) {
              SLastCol *pLastCol = (SLastCol *)taosArrayGet(pLast, iCol);
313 314
              if (pLastCol->colVal.value.nData > 0 && NULL != pLastCol->colVal.value.pData)
                taosMemoryFree(pLastCol->colVal.value.pData);
315 316 317 318 319 320 321 322

              lastCol.colVal.value.pData = taosMemoryMalloc(colVal.value.nData);
              if (lastCol.colVal.value.pData == NULL) {
                terrno = TSDB_CODE_OUT_OF_MEMORY;
                code = TSDB_CODE_OUT_OF_MEMORY;
                goto _invalidate;
              }
              memcpy(lastCol.colVal.value.pData, colVal.value.pData, colVal.value.nData);
323 324
            }

325 326
            taosArraySet(pLast, iCol, &lastCol);
          }
327 328 329 330 331 332 333 334
        }
      }
    }

  _invalidate:
    taosMemoryFreeClear(pTSchema);

    taosLRUCacheRelease(pCache, h, invalidate);
335 336
    if (invalidate) {
      taosLRUCacheErase(pCache, key, keyLen);
337
    }
338
  }
339 340 341 342

  return code;
}

H
Hongze Cheng 已提交
343
int32_t tsdbCacheInsertLast(SLRUCache *pCache, tb_uid_t uid, TSDBROW *row, STsdb *pTsdb) {
344 345 346 347 348
  int32_t code = 0;
  STSRow *cacheRow = NULL;
  char    key[32] = {0};
  int     keyLen = 0;

349 350
  // getTableCacheKey(uid, "l", key, &keyLen);
  getTableCacheKey(uid, 1, key, &keyLen);
351 352
  LRUHandle *h = taosLRUCacheLookup(pCache, key, keyLen);
  if (h) {
353
    STSchema *pTSchema = metaGetTbTSchema(pTsdb->pVnode->pMeta, uid, -1, 1);
H
Hongze Cheng 已提交
354
    TSKEY     keyTs = TSDBROW_TS(row);
355 356 357 358 359 360
    bool      invalidate = false;

    SArray *pLast = (SArray *)taosLRUCacheValue(pCache, h);
    int16_t nCol = taosArrayGetSize(pLast);
    int16_t iCol = 0;

361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
    if (nCol <= 0) {
      nCol = pTSchema->numOfCols;

      STColumn *pTColumn = &pTSchema->columns[0];
      SColVal   tColVal = COL_VAL_VALUE(pTColumn->colId, pTColumn->type, (SValue){.val = keyTs});
      if (taosArrayPush(pLast, &(SLastCol){.ts = keyTs, .colVal = tColVal}) == NULL) {
        terrno = TSDB_CODE_OUT_OF_MEMORY;
        code = TSDB_CODE_OUT_OF_MEMORY;
        goto _invalidate;
      }

      for (iCol = 1; iCol < nCol; ++iCol) {
        SColVal colVal = {0};
        tsdbRowGetColVal(row, pTSchema, iCol, &colVal);

        SLastCol lastCol = {.ts = keyTs, .colVal = colVal};
        if (IS_VAR_DATA_TYPE(colVal.type) && colVal.value.nData > 0) {
          lastCol.colVal.value.pData = taosMemoryMalloc(colVal.value.nData);
          if (lastCol.colVal.value.pData == NULL) {
            terrno = TSDB_CODE_OUT_OF_MEMORY;
            code = TSDB_CODE_OUT_OF_MEMORY;
            goto _invalidate;
          }
          memcpy(lastCol.colVal.value.pData, colVal.value.pData, colVal.value.nData);
        }

        if (taosArrayPush(pLast, &lastCol) == NULL) {
          code = TSDB_CODE_OUT_OF_MEMORY;
          goto _invalidate;
        }
      }

      goto _invalidate;
    }

396 397 398 399 400
    if (nCol != pTSchema->numOfCols) {
      invalidate = true;
      goto _invalidate;
    }

401 402 403
    SLastCol *tTsVal = (SLastCol *)taosArrayGet(pLast, iCol);
    if (keyTs > tTsVal->ts) {
      STColumn *pTColumn = &pTSchema->columns[0];
H
Hongze Cheng 已提交
404
      SColVal   tColVal = COL_VAL_VALUE(pTColumn->colId, pTColumn->type, (SValue){.val = keyTs});
405 406 407 408 409

      taosArraySet(pLast, iCol, &(SLastCol){.ts = keyTs, .colVal = tColVal});
    }

    for (++iCol; iCol < nCol; ++iCol) {
410 411 412
      SLastCol *tTsVal1 = (SLastCol *)taosArrayGet(pLast, iCol);
      if (keyTs >= tTsVal1->ts) {
        SColVal *tColVal = &tTsVal1->colVal;
413 414

        SColVal colVal = {0};
H
Hongze Cheng 已提交
415
        tsdbRowGetColVal(row, pTSchema, iCol, &colVal);
416 417 418 419 420 421

        if (colVal.cid != tColVal->cid) {
          invalidate = true;
          goto _invalidate;
        }

422
        if (COL_VAL_IS_VALUE(&colVal)) {
H
Hongze Cheng 已提交
423
          if (keyTs == tTsVal1->ts && COL_VAL_IS_VALUE(tColVal)) {
424 425 426
            invalidate = true;

            break;
427 428 429 430
          } else {
            SLastCol lastCol = {.ts = keyTs, .colVal = colVal};
            if (IS_VAR_DATA_TYPE(colVal.type) && colVal.value.nData > 0) {
              SLastCol *pLastCol = (SLastCol *)taosArrayGet(pLast, iCol);
431 432
              if (pLastCol->colVal.value.nData > 0 && NULL != pLastCol->colVal.value.pData)
                taosMemoryFree(pLastCol->colVal.value.pData);
433 434 435 436 437 438 439 440

              lastCol.colVal.value.pData = taosMemoryMalloc(colVal.value.nData);
              if (lastCol.colVal.value.pData == NULL) {
                terrno = TSDB_CODE_OUT_OF_MEMORY;
                code = TSDB_CODE_OUT_OF_MEMORY;
                goto _invalidate;
              }
              memcpy(lastCol.colVal.value.pData, colVal.value.pData, colVal.value.nData);
441 442
            }

443 444
            taosArraySet(pLast, iCol, &lastCol);
          }
445 446 447 448
        }
      }
    }

449
  _invalidate:
450 451 452
    taosMemoryFreeClear(pTSchema);

    taosLRUCacheRelease(pCache, h, invalidate);
453 454 455
    if (invalidate) {
      taosLRUCacheErase(pCache, key, keyLen);
    }
456 457 458 459 460
  }

  return code;
}

461 462 463 464 465
static tb_uid_t getTableSuidByUid(tb_uid_t uid, STsdb *pTsdb) {
  tb_uid_t suid = 0;

  SMetaReader mr = {0};
  metaReaderInit(&mr, pTsdb->pVnode->pMeta, 0);
H
Haojun Liao 已提交
466
  if (metaGetTableEntryByUidCache(&mr, uid) < 0) {
H
Hongze Cheng 已提交
467
    metaReaderClear(&mr);  // table not esist
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
    return 0;
  }

  if (mr.me.type == TSDB_CHILD_TABLE) {
    suid = mr.me.ctbEntry.suid;
  } else if (mr.me.type == TSDB_NORMAL_TABLE) {
    suid = 0;
  } else {
    suid = 0;
  }

  metaReaderClear(&mr);

  return suid;
}

static int32_t getTableDelDataFromDelIdx(SDelFReader *pDelReader, SDelIdx *pDelIdx, SArray *aDelData) {
  int32_t code = 0;

  if (pDelIdx) {
H
Hongze Cheng 已提交
488
    code = tsdbReadDelData(pDelReader, pDelIdx, aDelData);
489 490 491 492 493 494
  }

  return code;
}

static int32_t getTableDelDataFromTbData(STbData *pTbData, SArray *aDelData) {
H
Hongze Cheng 已提交
495
  int32_t   code = 0;
496 497 498 499 500 501 502 503 504
  SDelData *pDelData = pTbData ? pTbData->pHead : NULL;

  for (; pDelData; pDelData = pDelData->pNext) {
    taosArrayPush(aDelData, pDelData);
  }

  return code;
}

H
Hongze Cheng 已提交
505 506
static int32_t getTableDelData(STbData *pMem, STbData *pIMem, SDelFReader *pDelReader, SDelIdx *pDelIdx,
                               SArray *aDelData) {
507 508
  int32_t code = 0;

509 510 511 512 513
  if (pDelIdx) {
    code = getTableDelDataFromDelIdx(pDelReader, pDelIdx, aDelData);
    if (code) goto _err;
  }

514 515 516 517 518 519 520 521 522 523 524 525 526 527
  if (pMem) {
    code = getTableDelDataFromTbData(pMem, aDelData);
    if (code) goto _err;
  }

  if (pIMem) {
    code = getTableDelDataFromTbData(pIMem, aDelData);
    if (code) goto _err;
  }

_err:
  return code;
}

H
Hongze Cheng 已提交
528 529
static int32_t getTableDelSkyline(STbData *pMem, STbData *pIMem, SDelFReader *pDelReader, SDelIdx *pDelIdx,
                                  SArray *aSkyline) {
530
  int32_t code = 0;
M
Minglei Jin 已提交
531
  SArray *aDelData = NULL;
532

M
Minglei Jin 已提交
533
  aDelData = taosArrayInit(32, sizeof(SDelData));
534 535 536 537
  code = getTableDelData(pMem, pIMem, pDelReader, pDelIdx, aDelData);
  if (code) goto _err;

  size_t nDelData = taosArrayGetSize(aDelData);
538 539 540 541
  if (nDelData > 0) {
    code = tsdbBuildDeleteSkyline(aDelData, 0, (int32_t)(nDelData - 1), aSkyline);
    if (code) goto _err;
  }
542

543
_err:
M
Minglei Jin 已提交
544 545 546
  if (aDelData) {
    taosArrayDestroy(aDelData);
  }
547 548
  return code;
}
S
stephenkgu 已提交
549
/*
550 551
static int32_t getTableDelIdx(SDelFReader *pDelFReader, tb_uid_t suid, tb_uid_t uid, SDelIdx *pDelIdx) {
  int32_t code = 0;
M
Minglei Jin 已提交
552
  SArray *pDelIdxArray = NULL;
553

554
  // SMapData delIdxMap;
M
Minglei Jin 已提交
555
  pDelIdxArray = taosArrayInit(32, sizeof(SDelIdx));
556
  SDelIdx idx = {.suid = suid, .uid = uid};
557

558
  // tMapDataReset(&delIdxMap);
H
Hongze Cheng 已提交
559
  code = tsdbReadDelIdx(pDelFReader, pDelIdxArray);
560 561
  if (code) goto _err;

562
  // code = tMapDataSearch(&delIdxMap, &idx, tGetDelIdx, tCmprDelIdx, pDelIdx);
563
  SDelIdx *pIdx = taosArraySearch(pDelIdxArray, &idx, tCmprDelIdx, TD_EQ);
564

565 566
  *pDelIdx = *pIdx;

567
_err:
M
Minglei Jin 已提交
568 569 570
  if (pDelIdxArray) {
    taosArrayDestroy(pDelIdxArray);
  }
571 572
  return code;
}
S
stephenkgu 已提交
573
*/
574 575 576 577 578 579 580 581
typedef enum {
  SFSLASTNEXTROW_FS,
  SFSLASTNEXTROW_FILESET,
  SFSLASTNEXTROW_BLOCKDATA,
  SFSLASTNEXTROW_BLOCKROW
} SFSLASTNEXTROWSTATES;

typedef struct {
582 583 584
  SFSLASTNEXTROWSTATES state;     // [input]
  STsdb               *pTsdb;     // [input]
  STSchema            *pTSchema;  // [input]
585
  tb_uid_t             suid;
586
  tb_uid_t             uid;
587 588 589
  int32_t              nFileSet;
  int32_t              iFileSet;
  SArray              *aDFileSet;
590
  SDataFReader       **pDataFReader;
591
  TSDBROW              row;
592

593 594 595
  SMergeTree         mergeTree;
  SMergeTree        *pMergeTree;
  SSttBlockLoadInfo *pLoadInfo;
596
  int64_t            lastTs;
597 598
} SFSLastNextRowIter;

599 600
static int32_t getNextRowFromFSLast(void *iter, TSDBROW **ppRow, bool *pIgnoreEarlierTs, bool isLast, int16_t *aCols,
                                    int nCols) {
601 602 603 604 605 606 607 608 609 610 611
  SFSLastNextRowIter *state = (SFSLastNextRowIter *)iter;
  int32_t             code = 0;

  switch (state->state) {
    case SFSLASTNEXTROW_FS:
      state->nFileSet = taosArrayGetSize(state->aDFileSet);
      state->iFileSet = state->nFileSet;

    case SFSLASTNEXTROW_FILESET: {
      SDFileSet *pFileSet = NULL;
    _next_fileset:
612 613 614 615 616
      if (state->pMergeTree != NULL) {
        tMergeTreeClose(state->pMergeTree);
        state->pMergeTree = NULL;
      }

617 618 619 620 621 622 623
      if (--state->iFileSet >= 0) {
        pFileSet = (SDFileSet *)taosArrayGet(state->aDFileSet, state->iFileSet);
      } else {
        *ppRow = NULL;
        return code;
      }

624 625 626
      if (*state->pDataFReader == NULL || (*state->pDataFReader)->pSet->fid != pFileSet->fid) {
        if (*state->pDataFReader != NULL) {
          tsdbDataFReaderClose(state->pDataFReader);
M
Minglei Jin 已提交
627

628 629
          resetLastBlockLoadInfo(state->pLoadInfo);
        }
630

631 632 633 634 635
        code = tsdbDataFReaderOpen(state->pDataFReader, state->pTsdb, pFileSet);
        if (code) goto _err;
      }

      tMergeTreeOpen(&state->mergeTree, 1, *state->pDataFReader, state->suid, state->uid,
636 637
                     &(STimeWindow){.skey = state->lastTs, .ekey = TSKEY_MAX},
                     &(SVersionRange){.minVer = 0, .maxVer = UINT64_MAX}, state->pLoadInfo, false, NULL, true);
638
      state->pMergeTree = &state->mergeTree;
639 640
      bool hasVal = tMergeTreeNext(&state->mergeTree);
      if (!hasVal) {
641 642 643 644 645
        if (tMergeTreeIgnoreEarlierTs(&state->mergeTree)) {
          *pIgnoreEarlierTs = true;
          *ppRow = NULL;
          return code;
        }
646
        state->state = SFSLASTNEXTROW_FILESET;
647 648 649
        goto _next_fileset;
      }
      state->state = SFSLASTNEXTROW_BLOCKROW;
650
    }
651 652
    case SFSLASTNEXTROW_BLOCKROW: {
      bool hasVal = false;
X
Xiaoyu Wang 已提交
653 654 655
      state->row = tMergeTreeGetRow(&state->mergeTree);
      *ppRow = &state->row;
      hasVal = tMergeTreeNext(&state->mergeTree);
656 657
      if (TSDBROW_TS(&state->row) <= state->lastTs) {
        *pIgnoreEarlierTs = true;
X
Xiaoyu Wang 已提交
658 659
        *ppRow = NULL;
        return code;
660 661 662
      }

      *pIgnoreEarlierTs = false;
663 664
      if (!hasVal) {
        state->state = SFSLASTNEXTROW_FILESET;
665
      }
666

667
      return code;
668
    }
669 670 671 672 673 674
    default:
      ASSERT(0);
      break;
  }

_err:
675
  /*if (state->pDataFReader) {
676 677
    tsdbDataFReaderClose(&state->pDataFReader);
    state->pDataFReader = NULL;
678
    }*/
679 680 681 682 683
  if (state->pMergeTree != NULL) {
    tMergeTreeClose(state->pMergeTree);
    state->pMergeTree = NULL;
  }

684 685 686 687 688 689 690 691 692 693 694 695
  *ppRow = NULL;

  return code;
}

int32_t clearNextRowFromFSLast(void *iter) {
  SFSLastNextRowIter *state = (SFSLastNextRowIter *)iter;
  int32_t             code = 0;

  if (!state) {
    return code;
  }
696
  /*
697 698 699 700
  if (state->pDataFReader) {
    tsdbDataFReaderClose(&state->pDataFReader);
    state->pDataFReader = NULL;
  }
701
  */
702 703 704 705 706
  if (state->pMergeTree != NULL) {
    tMergeTreeClose(state->pMergeTree);
    state->pMergeTree = NULL;
  }

707 708 709
  return code;
}

710 711 712 713 714 715 716 717
typedef enum SFSNEXTROWSTATES {
  SFSNEXTROW_FS,
  SFSNEXTROW_FILESET,
  SFSNEXTROW_BLOCKDATA,
  SFSNEXTROW_BLOCKROW
} SFSNEXTROWSTATES;

typedef struct SFSNextRowIter {
718 719 720 721 722 723 724 725 726 727 728
  SFSNEXTROWSTATES   state;         // [input]
  STsdb             *pTsdb;         // [input]
  SBlockIdx         *pBlockIdxExp;  // [input]
  STSchema          *pTSchema;      // [input]
  tb_uid_t           suid;
  tb_uid_t           uid;
  int32_t            nFileSet;
  int32_t            iFileSet;
  SArray            *aDFileSet;
  SDataFReader     **pDataFReader;
  SArray            *aBlockIdx;
729
  LRUHandle         *aBlockIdxHandle;
730 731 732 733 734 735 736 737 738 739 740
  SBlockIdx         *pBlockIdx;
  SMapData           blockMap;
  int32_t            nBlock;
  int32_t            iBlock;
  SDataBlk           block;
  SBlockData         blockData;
  SBlockData        *pBlockData;
  int32_t            nRow;
  int32_t            iRow;
  TSDBROW            row;
  SSttBlockLoadInfo *pLoadInfo;
741
  int64_t            lastTs;
742 743
} SFSNextRowIter;

744 745
static int32_t getNextRowFromFS(void *iter, TSDBROW **ppRow, bool *pIgnoreEarlierTs, bool isLast, int16_t *aCols,
                                int nCols) {
746 747
  SFSNextRowIter *state = (SFSNextRowIter *)iter;
  int32_t         code = 0;
748
  bool            checkRemainingRow = true;
749 750 751

  switch (state->state) {
    case SFSNEXTROW_FS:
H
Hongze Cheng 已提交
752
      // state->aDFileSet = state->pTsdb->pFS->cState->aDFileSet;
753
      state->nFileSet = taosArrayGetSize(state->aDFileSet);
M
Minglei Jin 已提交
754
      state->iFileSet = state->nFileSet;
755 756

      state->pBlockData = NULL;
757 758 759

    case SFSNEXTROW_FILESET: {
      SDFileSet *pFileSet = NULL;
760
    _next_fileset:
761 762 763
      if (--state->iFileSet >= 0) {
        pFileSet = (SDFileSet *)taosArrayGet(state->aDFileSet, state->iFileSet);
      } else {
H
Hongze Cheng 已提交
764
        // tBlockDataDestroy(&state->blockData, 1);
765
        if (state->pBlockData) {
H
Hongze Cheng 已提交
766
          tBlockDataDestroy(state->pBlockData);
767 768
          state->pBlockData = NULL;
        }
769

770 771 772 773
        *ppRow = NULL;
        return code;
      }

774 775 776 777
      if (*state->pDataFReader == NULL || (*state->pDataFReader)->pSet->fid != pFileSet->fid) {
        if (*state->pDataFReader != NULL) {
          tsdbDataFReaderClose(state->pDataFReader);

778
          // resetLastBlockLoadInfo(state->pLoadInfo);
779 780 781 782 783
        }

        code = tsdbDataFReaderOpen(state->pDataFReader, state->pTsdb, pFileSet);
        if (code) goto _err;
      }
784 785

      // tMapDataReset(&state->blockIdxMap);
786
      /*
787 788 789 790 791
      if (!state->aBlockIdx) {
        state->aBlockIdx = taosArrayInit(0, sizeof(SBlockIdx));
      } else {
        taosArrayClear(state->aBlockIdx);
      }
792
      code = tsdbReadBlockIdx(*state->pDataFReader, state->aBlockIdx);
793
      if (code) goto _err;
794
      */
795
      int32_t code = tsdbCacheGetBlockIdx(state->pTsdb->biCache, *state->pDataFReader, &state->aBlockIdxHandle);
796 797 798
      if (code != TSDB_CODE_SUCCESS || state->aBlockIdxHandle == NULL) {
        goto _err;
      }
799
      state->aBlockIdx = (SArray *)taosLRUCacheValue(state->pTsdb->biCache, state->aBlockIdxHandle);
800

801 802
      /* if (state->pBlockIdx) { */
      /* } */
803 804
      /* code = tMapDataSearch(&state->blockIdxMap, state->pBlockIdxExp, tGetBlockIdx, tCmprBlockIdx,
       * &state->blockIdx);
805 806
       */
      state->pBlockIdx = taosArraySearch(state->aBlockIdx, state->pBlockIdxExp, tCmprBlockIdx, TD_EQ);
807 808 809 810
      if (!state->pBlockIdx) { /*
         tsdbDataFReaderClose(state->pDataFReader);
         *state->pDataFReader = NULL;
         resetLastBlockLoadInfo(state->pLoadInfo);*/
811 812 813
        goto _next_fileset;
      }

814 815
      tMapDataReset(&state->blockMap);
      /*
816 817 818
      if (state->blockMap.pData != NULL) {
        tMapDataClear(&state->blockMap);
      }
819 820
      */
      code = tsdbReadDataBlk(*state->pDataFReader, state->pBlockIdx, &state->blockMap);
821 822 823 824
      if (code) goto _err;

      state->nBlock = state->blockMap.nItem;
      state->iBlock = state->nBlock - 1;
825

826 827 828
      if (!state->pBlockData) {
        state->pBlockData = &state->blockData;

829 830
        code = tBlockDataCreate(&state->blockData);
        if (code) goto _err;
831
      }
832 833
    }
    case SFSNEXTROW_BLOCKDATA:
834
    _next_datablock:
835
      if (state->iBlock >= 0) {
H
Hongze Cheng 已提交
836
        SDataBlk block = {0};
837 838
        bool     skipBlock = true;
        int      inputColIndex = 0;
839

H
Hongze Cheng 已提交
840
        tDataBlkReset(&block);
841
        tBlockDataReset(state->pBlockData);
842

H
Hongze Cheng 已提交
843
        tMapDataGetItemByIdx(&state->blockMap, state->iBlock, &block, tGetDataBlk);
844
        if (block.maxKey.ts <= state->lastTs) {
845
          *pIgnoreEarlierTs = true;
X
Xiaoyu Wang 已提交
846 847 848 849 850 851 852
          if (state->pBlockData) {
            tBlockDataDestroy(state->pBlockData);
            state->pBlockData = NULL;
          }

          *ppRow = NULL;
          return code;
853
        }
854
        *pIgnoreEarlierTs = false;
855
        tBlockDataReset(state->pBlockData);
H
Hongze Cheng 已提交
856
        TABLEID tid = {.suid = state->suid, .uid = state->uid};
857
        code = tBlockDataInit(state->pBlockData, &tid, state->pTSchema, aCols, nCols);
858 859
        if (code) goto _err;

860
        code = tsdbReadDataBlock(*state->pDataFReader, &block, state->pBlockData);
861 862
        if (code) goto _err;

863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905
        for (int colIndex = 0; colIndex < state->pBlockData->nColData; ++colIndex) {
          SColData *pColData = &state->pBlockData->aColData[colIndex];

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

        if (skipBlock) {
          if (--state->iBlock < 0) {
            tsdbDataFReaderClose(state->pDataFReader);
            *state->pDataFReader = NULL;
            // resetLastBlockLoadInfo(state->pLoadInfo);

            if (state->aBlockIdx) {
              // taosArrayDestroy(state->aBlockIdx);
              tsdbBICacheRelease(state->pTsdb->biCache, state->aBlockIdxHandle);

              state->aBlockIdxHandle = NULL;
              state->aBlockIdx = NULL;
            }

            state->state = SFSNEXTROW_FILESET;
            goto _next_fileset;
          } else {
            goto _next_datablock;
          }
        }

        state->nRow = state->blockData.nRow;
        state->iRow = state->nRow - 1;

        state->state = SFSNEXTROW_BLOCKROW;
        checkRemainingRow = false;
      }
    case SFSNEXTROW_BLOCKROW: {
      if (checkRemainingRow) {
        bool skipBlock = true;
        int  inputColIndex = 0;
906 907 908 909
        for (int colIndex = 0; colIndex < state->pBlockData->nColData; ++colIndex) {
          SColData *pColData = &state->pBlockData->aColData[colIndex];
          int16_t   cid = pColData->cid;

910
          if (inputColIndex < nCols && cid == aCols[inputColIndex]) {
911 912 913 914 915 916 917
            if (isLast && pColData->numOfValue != 0) {
              skipBlock = false;
              break;
            } else if (pColData->numOfNone != pColData->nVal) {
              skipBlock = false;
              break;
            }
918 919

            ++inputColIndex;
920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942
          }
        }

        if (skipBlock) {
          if (--state->iBlock < 0) {
            tsdbDataFReaderClose(state->pDataFReader);
            *state->pDataFReader = NULL;
            // resetLastBlockLoadInfo(state->pLoadInfo);

            if (state->aBlockIdx) {
              // taosArrayDestroy(state->aBlockIdx);
              tsdbBICacheRelease(state->pTsdb->biCache, state->aBlockIdxHandle);

              state->aBlockIdxHandle = NULL;
              state->aBlockIdx = NULL;
            }

            state->state = SFSNEXTROW_FILESET;
            goto _next_fileset;
          } else {
            goto _next_datablock;
          }
        }
943
      }
944

945
      if (state->iRow >= 0) {
946
        state->row = tsdbRowFromBlockData(state->pBlockData, state->iRow);
947 948 949 950 951
        *ppRow = &state->row;

        if (--state->iRow < 0) {
          state->state = SFSNEXTROW_BLOCKDATA;
          if (--state->iBlock < 0) {
952 953
            tsdbDataFReaderClose(state->pDataFReader);
            *state->pDataFReader = NULL;
954
            // resetLastBlockLoadInfo(state->pLoadInfo);
955

956
            if (state->aBlockIdx) {
957
              // taosArrayDestroy(state->aBlockIdx);
958
              tsdbBICacheRelease(state->pTsdb->biCache, state->aBlockIdxHandle);
959 960

              state->aBlockIdxHandle = NULL;
961
              state->aBlockIdx = NULL;
962
            }
963

964 965 966 967 968 969
            state->state = SFSNEXTROW_FILESET;
          }
        }
      }

      return code;
970
    }
971 972 973 974 975 976
    default:
      ASSERT(0);
      break;
  }

_err:
977 978 979 980 981 982
  /*
  if (*state->pDataFReader) {
    tsdbDataFReaderClose(state->pDataFReader);
    *state->pDataFReader = NULL;
    resetLastBlockLoadInfo(state->pLoadInfo);
    }*/
983
  if (state->aBlockIdx) {
984
    // taosArrayDestroy(state->aBlockIdx);
985
    tsdbBICacheRelease(state->pTsdb->biCache, state->aBlockIdxHandle);
986 987

    state->aBlockIdxHandle = NULL;
988 989 990
    state->aBlockIdx = NULL;
  }
  if (state->pBlockData) {
H
Hongze Cheng 已提交
991
    tBlockDataDestroy(state->pBlockData);
992
    state->pBlockData = NULL;
993 994
  }

995
  *ppRow = NULL;
996

997 998 999
  return code;
}

1000 1001 1002 1003 1004 1005 1006
int32_t clearNextRowFromFS(void *iter) {
  int32_t code = 0;

  SFSNextRowIter *state = (SFSNextRowIter *)iter;
  if (!state) {
    return code;
  }
1007
  /*
1008 1009 1010
  if (state->pDataFReader) {
    tsdbDataFReaderClose(&state->pDataFReader);
    state->pDataFReader = NULL;
1011
    }*/
1012
  if (state->aBlockIdx) {
1013
    // taosArrayDestroy(state->aBlockIdx);
1014
    tsdbBICacheRelease(state->pTsdb->biCache, state->aBlockIdxHandle);
1015 1016

    state->aBlockIdxHandle = NULL;
1017 1018 1019
    state->aBlockIdx = NULL;
  }
  if (state->pBlockData) {
H
Hongze Cheng 已提交
1020
    // tBlockDataDestroy(&state->blockData, 1);
H
Hongze Cheng 已提交
1021
    tBlockDataDestroy(state->pBlockData);
1022 1023 1024
    state->pBlockData = NULL;
  }

1025 1026 1027 1028
  if (state->blockMap.pData != NULL) {
    tMapDataClear(&state->blockMap);
  }

1029 1030 1031
  return code;
}

1032 1033 1034 1035 1036 1037 1038 1039 1040
typedef enum SMEMNEXTROWSTATES {
  SMEMNEXTROW_ENTER,
  SMEMNEXTROW_NEXT,
} SMEMNEXTROWSTATES;

typedef struct SMemNextRowIter {
  SMEMNEXTROWSTATES state;
  STbData          *pMem;  // [input]
  STbDataIter       iter;  // mem buffer skip list iterator
1041
  int64_t           lastTs;
1042 1043
  // bool              iterOpened;
  // TSDBROW          *curRow;
1044 1045
} SMemNextRowIter;

1046 1047
static int32_t getNextRowFromMem(void *iter, TSDBROW **ppRow, bool *pIgnoreEarlierTs, bool isLast, int16_t *aCols,
                                 int nCols) {
1048 1049
  SMemNextRowIter *state = (SMemNextRowIter *)iter;
  int32_t          code = 0;
1050
  *pIgnoreEarlierTs = false;
1051 1052 1053
  switch (state->state) {
    case SMEMNEXTROW_ENTER: {
      if (state->pMem != NULL) {
1054 1055 1056 1057 1058
        if (state->pMem->maxKey <= state->lastTs) {
          *ppRow = NULL;
          *pIgnoreEarlierTs = true;
          return code;
        }
1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093
        tsdbTbDataIterOpen(state->pMem, NULL, 1, &state->iter);

        TSDBROW *pMemRow = tsdbTbDataIterGet(&state->iter);
        if (pMemRow) {
          *ppRow = pMemRow;
          state->state = SMEMNEXTROW_NEXT;

          return code;
        }
      }

      *ppRow = NULL;

      return code;
    }
    case SMEMNEXTROW_NEXT:
      if (tsdbTbDataIterNext(&state->iter)) {
        *ppRow = tsdbTbDataIterGet(&state->iter);

        return code;
      } else {
        *ppRow = NULL;

        return code;
      }
    default:
      ASSERT(0);
      break;
  }

_err:
  *ppRow = NULL;
  return code;
}

1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131
/* static int32_t tsRowFromTsdbRow(STSchema *pTSchema, TSDBROW *pRow, STSRow **ppRow) { */
/*   int32_t code = 0; */

/*   SColVal *pColVal = &(SColVal){0}; */

/*   if (pRow->type == 0) { */
/*     *ppRow = tdRowDup(pRow->pTSRow); */
/*   } else { */
/*     SArray *pArray = taosArrayInit(pTSchema->numOfCols, sizeof(SColVal)); */
/*     if (pArray == NULL) { */
/*       code = TSDB_CODE_OUT_OF_MEMORY; */
/*       goto _exit; */
/*     } */

/*     TSDBKEY   key = TSDBROW_KEY(pRow); */
/*     STColumn *pTColumn = &pTSchema->columns[0]; */
/*     *pColVal = COL_VAL_VALUE(pTColumn->colId, pTColumn->type, (SValue){.ts = key.ts}); */

/*     if (taosArrayPush(pArray, pColVal) == NULL) { */
/*       code = TSDB_CODE_OUT_OF_MEMORY; */
/*       goto _exit; */
/*     } */

/*     for (int16_t iCol = 1; iCol < pTSchema->numOfCols; iCol++) { */
/*       tsdbRowGetColVal(pRow, pTSchema, iCol, pColVal); */
/*       if (taosArrayPush(pArray, pColVal) == NULL) { */
/*         code = TSDB_CODE_OUT_OF_MEMORY; */
/*         goto _exit; */
/*       } */
/*     } */

/*     code = tdSTSRowNew(pArray, pTSchema, ppRow); */
/*     if (code) goto _exit; */
/*   } */

/* _exit: */
/*   return code; */
/* } */
1132

1133
static bool tsdbKeyDeleted(TSDBKEY *key, SArray *pSkyline, int64_t *iSkyline) {
1134 1135 1136 1137 1138 1139 1140 1141
  bool deleted = false;
  while (*iSkyline > 0) {
    TSDBKEY *pItemBack = (TSDBKEY *)taosArrayGet(pSkyline, *iSkyline);
    TSDBKEY *pItemFront = (TSDBKEY *)taosArrayGet(pSkyline, *iSkyline - 1);

    if (key->ts > pItemBack->ts) {
      return false;
    } else if (key->ts >= pItemFront->ts && key->ts <= pItemBack->ts) {
1142
      if (key->version <= pItemFront->version || (key->ts == pItemBack->ts && key->version <= pItemBack->version)) {
1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158
        return true;
      } else {
        return false;
      }
    } else {
      if (*iSkyline > 1) {
        --*iSkyline;
      } else {
        return false;
      }
    }
  }

  return deleted;
}

1159 1160
typedef int32_t (*_next_row_fn_t)(void *iter, TSDBROW **ppRow, bool *pIgnoreEarlierTs, bool isLast, int16_t *aCols,
                                  int nCols);
1161
typedef int32_t (*_next_row_clear_fn_t)(void *iter);
1162

1163
typedef struct {
1164 1165 1166
  TSDBROW             *pRow;
  bool                 stop;
  bool                 next;
1167
  bool                 ignoreEarlierTs;
1168 1169 1170
  void                *iter;
  _next_row_fn_t       nextRowFn;
  _next_row_clear_fn_t nextRowClearFn;
1171
} TsdbNextRowState;
1172

1173 1174 1175 1176
typedef struct {
  SArray *pSkyline;
  int64_t iSkyline;

1177 1178 1179 1180 1181 1182
  SBlockIdx          idx;
  SMemNextRowIter    memState;
  SMemNextRowIter    imemState;
  SFSLastNextRowIter fsLastState;
  SFSNextRowIter     fsState;
  TSDBROW            memRow, imemRow, fsLastRow, fsRow;
1183

1184
  TsdbNextRowState input[4];
1185
  STsdb           *pTsdb;
1186 1187
} CacheNextRowIter;

1188
static int32_t nextRowIterOpen(CacheNextRowIter *pIter, tb_uid_t uid, STsdb *pTsdb, STSchema *pTSchema, tb_uid_t suid,
1189
                               SSttBlockLoadInfo *pLoadInfo, STsdbReadSnap *pReadSnap, SDataFReader **pDataFReader,
1190
                               SDataFReader **pDataFReaderLast, int64_t lastTs) {
1191 1192 1193
  int code = 0;

  STbData *pMem = NULL;
1194 1195
  if (pReadSnap->pMem) {
    pMem = tsdbGetTbDataFromMemTable(pReadSnap->pMem, suid, uid);
1196 1197 1198
  }

  STbData *pIMem = NULL;
1199 1200
  if (pReadSnap->pIMem) {
    pIMem = tsdbGetTbDataFromMemTable(pReadSnap->pIMem, suid, uid);
1201 1202
  }

H
Hongze Cheng 已提交
1203 1204
  pIter->pTsdb = pTsdb;

1205 1206
  pIter->pSkyline = taosArrayInit(32, sizeof(TSDBKEY));

1207
  SDelFile *pDelFile = pReadSnap->fs.pDelFile;
1208 1209 1210
  if (pDelFile) {
    SDelFReader *pDelFReader;

H
Hongze Cheng 已提交
1211
    code = tsdbDelFReaderOpen(&pDelFReader, pDelFile, pTsdb);
1212 1213
    if (code) goto _err;

S
stephenkgu 已提交
1214 1215 1216
    SArray *pDelIdxArray = taosArrayInit(32, sizeof(SDelIdx));

    code = tsdbReadDelIdx(pDelFReader, pDelIdxArray);
M
Minglei Jin 已提交
1217
    if (code) {
1218
      taosArrayDestroy(pDelIdxArray);
M
Minglei Jin 已提交
1219 1220 1221
      tsdbDelFReaderClose(&pDelFReader);
      goto _err;
    }
S
stephenkgu 已提交
1222 1223

    SDelIdx *delIdx = taosArraySearch(pDelIdxArray, &(SDelIdx){.suid = suid, .uid = uid}, tCmprDelIdx, TD_EQ);
1224

S
stephenkgu 已提交
1225
    code = getTableDelSkyline(pMem, pIMem, pDelFReader, delIdx, pIter->pSkyline);
1226
    if (code) {
1227
      taosArrayDestroy(pDelIdxArray);
1228 1229 1230
      tsdbDelFReaderClose(&pDelFReader);
      goto _err;
    }
1231

S
stephenkgu 已提交
1232
    taosArrayDestroy(pDelIdxArray);
1233 1234 1235 1236 1237 1238 1239 1240 1241 1242
    tsdbDelFReaderClose(&pDelFReader);
  } else {
    code = getTableDelSkyline(pMem, pIMem, NULL, NULL, pIter->pSkyline);
    if (code) goto _err;
  }

  pIter->iSkyline = taosArrayGetSize(pIter->pSkyline) - 1;

  pIter->idx = (SBlockIdx){.suid = suid, .uid = uid};

1243
  pIter->fsLastState.state = (SFSLASTNEXTROWSTATES)SFSNEXTROW_FS;
1244
  pIter->fsLastState.pTsdb = pTsdb;
1245
  pIter->fsLastState.aDFileSet = pReadSnap->fs.aDFileSet;
1246
  pIter->fsLastState.pTSchema = pTSchema;
1247
  pIter->fsLastState.suid = suid;
1248
  pIter->fsLastState.uid = uid;
1249
  pIter->fsLastState.pLoadInfo = pLoadInfo;
1250
  pIter->fsLastState.pDataFReader = pDataFReaderLast;
1251
  pIter->fsLastState.lastTs = lastTs;
1252

1253 1254
  pIter->fsState.state = SFSNEXTROW_FS;
  pIter->fsState.pTsdb = pTsdb;
1255
  pIter->fsState.aDFileSet = pReadSnap->fs.aDFileSet;
1256
  pIter->fsState.pBlockIdxExp = &pIter->idx;
1257 1258 1259
  pIter->fsState.pTSchema = pTSchema;
  pIter->fsState.suid = suid;
  pIter->fsState.uid = uid;
1260 1261
  pIter->fsState.pLoadInfo = pLoadInfo;
  pIter->fsState.pDataFReader = pDataFReader;
1262
  pIter->fsState.lastTs = lastTs;
1263

1264 1265 1266 1267
  pIter->input[0] = (TsdbNextRowState){&pIter->memRow, true, false, false, &pIter->memState, getNextRowFromMem, NULL};
  pIter->input[1] = (TsdbNextRowState){&pIter->imemRow, true, false, false, &pIter->imemState, getNextRowFromMem, NULL};
  pIter->input[2] = (TsdbNextRowState){
      &pIter->fsLastRow, false, true, false, &pIter->fsLastState, getNextRowFromFSLast, clearNextRowFromFSLast};
1268
  pIter->input[3] =
1269
      (TsdbNextRowState){&pIter->fsRow, false, true, false, &pIter->fsState, getNextRowFromFS, clearNextRowFromFS};
1270 1271 1272 1273

  if (pMem) {
    pIter->memState.pMem = pMem;
    pIter->memState.state = SMEMNEXTROW_ENTER;
1274
    pIter->memState.lastTs = lastTs;
1275 1276 1277 1278 1279 1280 1281
    pIter->input[0].stop = false;
    pIter->input[0].next = true;
  }

  if (pIMem) {
    pIter->imemState.pMem = pIMem;
    pIter->imemState.state = SMEMNEXTROW_ENTER;
1282
    pIter->imemState.lastTs = lastTs;
1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294
    pIter->input[1].stop = false;
    pIter->input[1].next = true;
  }

  return code;
_err:
  return code;
}

static int32_t nextRowIterClose(CacheNextRowIter *pIter) {
  int code = 0;

1295
  for (int i = 0; i < 4; ++i) {
1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309
    if (pIter->input[i].nextRowClearFn) {
      pIter->input[i].nextRowClearFn(pIter->input[i].iter);
    }
  }

  if (pIter->pSkyline) {
    taosArrayDestroy(pIter->pSkyline);
  }

_err:
  return code;
}

// iterate next row non deleted backward ts, version (from high to low)
1310 1311
static int32_t nextRowIterGet(CacheNextRowIter *pIter, TSDBROW **ppRow, bool *pIgnoreEarlierTs, bool isLast,
                              int16_t *aCols, int nCols) {
1312
  int code = 0;
1313 1314 1315
  for (;;) {
    for (int i = 0; i < 4; ++i) {
      if (pIter->input[i].next && !pIter->input[i].stop) {
1316 1317
        code = pIter->input[i].nextRowFn(pIter->input[i].iter, &pIter->input[i].pRow, &pIter->input[i].ignoreEarlierTs,
                                         isLast, aCols, nCols);
1318
        if (code) goto _err;
1319

1320 1321 1322 1323
        if (pIter->input[i].pRow == NULL) {
          pIter->input[i].stop = true;
          pIter->input[i].next = false;
        }
1324 1325 1326
      }
    }

1327 1328
    if (pIter->input[0].stop && pIter->input[1].stop && pIter->input[2].stop && pIter->input[3].stop) {
      *ppRow = NULL;
1329 1330
      *pIgnoreEarlierTs = (pIter->input[0].ignoreEarlierTs || pIter->input[1].ignoreEarlierTs ||
                           pIter->input[2].ignoreEarlierTs || pIter->input[3].ignoreEarlierTs);
1331 1332
      return code;
    }
1333

1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349
    // select maxpoint(s) from mem, imem, fs and last
    TSDBROW *max[4] = {0};
    int      iMax[4] = {-1, -1, -1, -1};
    int      nMax = 0;
    TSKEY    maxKey = TSKEY_MIN;

    for (int i = 0; i < 4; ++i) {
      if (!pIter->input[i].stop && pIter->input[i].pRow != NULL) {
        TSDBKEY key = TSDBROW_KEY(pIter->input[i].pRow);

        // merging & deduplicating on client side
        if (maxKey <= key.ts) {
          if (maxKey < key.ts) {
            nMax = 0;
            maxKey = key.ts;
          }
1350

1351 1352
          iMax[nMax] = i;
          max[nMax++] = pIter->input[i].pRow;
1353 1354
        } else {
          pIter->input[i].next = false;
1355 1356 1357 1358
        }
      }
    }

1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370
    // delete detection
    TSDBROW *merge[4] = {0};
    int      iMerge[4] = {-1, -1, -1, -1};
    int      nMerge = 0;
    for (int i = 0; i < nMax; ++i) {
      TSDBKEY maxKey1 = TSDBROW_KEY(max[i]);

      bool deleted = tsdbKeyDeleted(&maxKey1, pIter->pSkyline, &pIter->iSkyline);
      if (!deleted) {
        iMerge[nMerge] = iMax[i];
        merge[nMerge++] = max[i];
      }
1371

1372 1373
      pIter->input[iMax[i]].next = deleted;
    }
1374

1375 1376
    if (nMerge > 0) {
      pIter->input[iMerge[0]].next = true;
1377

1378 1379 1380
      *ppRow = merge[0];
      return code;
    }
1381 1382 1383 1384 1385 1386
  }

_err:
  return code;
}

1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422
static int32_t initLastColArray(STSchema *pTSchema, SArray **ppColArray) {
  SArray *pColArray = taosArrayInit(pTSchema->numOfCols, sizeof(SLastCol));
  if (NULL == pColArray) {
    return TSDB_CODE_OUT_OF_MEMORY;
  }

  for (int32_t i = 0; i < pTSchema->numOfCols; ++i) {
    SLastCol col = {.ts = 0, .colVal = COL_VAL_NULL(pTSchema->columns[i].colId, pTSchema->columns[i].type)};
    taosArrayPush(pColArray, &col);
  }
  *ppColArray = pColArray;
  return TSDB_CODE_SUCCESS;
}

static int32_t cloneTSchema(STSchema *pSrc, STSchema **ppDst) {
  int32_t len = sizeof(STSchema) + sizeof(STColumn) * pSrc->numOfCols;
  *ppDst = taosMemoryMalloc(len);
  if (NULL == *ppDst) {
    return TSDB_CODE_OUT_OF_MEMORY;
  }
  memcpy(*ppDst, pSrc, len);
  return TSDB_CODE_SUCCESS;
}

static int32_t updateTSchema(int32_t sversion, SCacheRowsReader *pReader, uint64_t uid) {
  if (NULL == pReader->pCurrSchema && sversion == pReader->pSchema->version) {
    return cloneTSchema(pReader->pSchema, &pReader->pCurrSchema);
  }

  if (NULL != pReader->pCurrSchema && sversion == pReader->pCurrSchema->version) {
    return TSDB_CODE_SUCCESS;
  }

  taosMemoryFreeClear(pReader->pCurrSchema);
  return metaGetTbTSchemaEx(pReader->pTsdb->pVnode->pMeta, pReader->suid, uid, sversion, &pReader->pCurrSchema);
}
1423

1424
static int32_t mergeLastRow(tb_uid_t uid, STsdb *pTsdb, bool *dup, SArray **ppColArray, SCacheRowsReader *pr) {
1425
  STSchema *pTSchema = pr->pSchema;  // metaGetTbTSchema(pTsdb->pVnode->pMeta, uid, -1, 1);
1426
  int16_t   nLastCol = pTSchema->numOfCols;
1427 1428 1429
  int16_t   iCol = 0;
  int16_t   noneCol = 0;
  bool      setNoneCol = false;
1430
  bool      hasRow = false;
1431
  bool      ignoreEarlierTs = false;
1432
  SArray   *pColArray = NULL;
1433 1434
  SColVal  *pColVal = &(SColVal){0};

1435 1436 1437 1438 1439
  int32_t code = initLastColArray(pTSchema, &pColArray);
  if (TSDB_CODE_SUCCESS != code) {
    return code;
  }

1440 1441 1442
  TSKEY lastRowTs = TSKEY_MAX;

  CacheNextRowIter iter = {0};
1443
  nextRowIterOpen(&iter, uid, pTsdb, pTSchema, pr->suid, pr->pLoadInfo, pr->pReadSnap, &pr->pDataFReader,
1444
                  &pr->pDataFReaderLast, pr->lastTs);
1445 1446 1447

  do {
    TSDBROW *pRow = NULL;
1448
    nextRowIterGet(&iter, &pRow, &ignoreEarlierTs, false, NULL, 0);
1449 1450 1451 1452 1453

    if (!pRow) {
      break;
    }

1454 1455
    hasRow = true;

1456 1457 1458 1459 1460 1461 1462
    code = updateTSchema(TSDBROW_SVERSION(pRow), pr, uid);
    if (TSDB_CODE_SUCCESS != code) {
      goto _err;
    }
    pTSchema = pr->pCurrSchema;
    int16_t nCol = pTSchema->numOfCols;

1463 1464
    TSKEY rowTs = TSDBROW_TS(pRow);

1465
    if (lastRowTs == TSKEY_MAX) {
1466
      lastRowTs = rowTs;
1467 1468
      STColumn *pTColumn = &pTSchema->columns[0];

H
Hongze Cheng 已提交
1469
      *pColVal = COL_VAL_VALUE(pTColumn->colId, pTColumn->type, (SValue){.val = lastRowTs});
1470
      taosArraySet(pColArray, 0, &(SLastCol){.ts = lastRowTs, .colVal = *pColVal});
1471 1472

      for (iCol = 1; iCol < nCol; ++iCol) {
1473 1474 1475 1476 1477 1478 1479
        if (iCol >= nLastCol) {
          break;
        }
        SLastCol *pCol = taosArrayGet(pColArray, iCol);
        if (pCol->colVal.cid != pTSchema->columns[iCol].colId) {
          continue;
        }
1480 1481
        tsdbRowGetColVal(pRow, pTSchema, iCol, pColVal);

1482
        *pCol = (SLastCol){.ts = lastRowTs, .colVal = *pColVal};
1483
        if (IS_VAR_DATA_TYPE(pColVal->type) && pColVal->value.nData > 0) {
1484 1485
          pCol->colVal.value.pData = taosMemoryMalloc(pCol->colVal.value.nData);
          if (pCol->colVal.value.pData == NULL) {
M
Minglei Jin 已提交
1486 1487 1488 1489
            terrno = TSDB_CODE_OUT_OF_MEMORY;
            code = TSDB_CODE_OUT_OF_MEMORY;
            goto _err;
          }
1490
          memcpy(pCol->colVal.value.pData, pColVal->value.pData, pColVal->value.nData);
1491 1492
        }

H
Hongze Cheng 已提交
1493
        if (COL_VAL_IS_NONE(pColVal) && !setNoneCol) {
1494 1495 1496 1497 1498
          noneCol = iCol;
          setNoneCol = true;
        }
      }
      if (!setNoneCol) {
1499
        // done, goto return pColArray
1500 1501 1502 1503 1504 1505
        break;
      } else {
        continue;
      }
    }

1506 1507
    if ((rowTs < lastRowTs)) {
      // done, goto return pColArray
1508 1509 1510 1511 1512 1513 1514 1515 1516 1517
      break;
    }

    // merge into pColArray
    setNoneCol = false;
    for (iCol = noneCol; iCol < nCol; ++iCol) {
      // high version's column value
      SColVal *tColVal = (SColVal *)taosArrayGet(pColArray, iCol);

      tsdbRowGetColVal(pRow, pTSchema, iCol, pColVal);
H
Hongze Cheng 已提交
1518
      if (COL_VAL_IS_NONE(tColVal) && !COL_VAL_IS_NONE(pColVal)) {
1519
        SLastCol lastCol = {.ts = rowTs, .colVal = *pColVal};
1520
        if (IS_VAR_DATA_TYPE(pColVal->type) && pColVal->value.nData > 0) {
1521 1522 1523 1524
          SLastCol *pLastCol = (SLastCol *)taosArrayGet(pColArray, iCol);
          taosMemoryFree(pLastCol->colVal.value.pData);

          lastCol.colVal.value.pData = taosMemoryMalloc(lastCol.colVal.value.nData);
M
Minglei Jin 已提交
1525 1526 1527 1528 1529
          if (lastCol.colVal.value.pData == NULL) {
            terrno = TSDB_CODE_OUT_OF_MEMORY;
            code = TSDB_CODE_OUT_OF_MEMORY;
            goto _err;
          }
1530 1531 1532 1533
          memcpy(lastCol.colVal.value.pData, pColVal->value.pData, pColVal->value.nData);
        }

        taosArraySet(pColArray, iCol, &lastCol);
H
Hongze Cheng 已提交
1534
      } else if (COL_VAL_IS_NONE(tColVal) && COL_VAL_IS_NONE(pColVal) && !setNoneCol) {
1535 1536 1537 1538 1539 1540 1541 1542
        noneCol = iCol;
        setNoneCol = true;
      }
    }
  } while (setNoneCol);

  // build the result ts row here
  *dup = false;
1543 1544 1545 1546
  // if (taosArrayGetSize(pColArray) != nCol) {
  //*ppColArray = NULL;
  // taosArrayDestroy(pColArray);
  //} else {
1547
  if (!hasRow) {
1548 1549 1550 1551 1552 1553
    if (ignoreEarlierTs) {
      taosArrayDestroy(pColArray);
      pColArray = NULL;
    } else {
      taosArrayClear(pColArray);
    }
1554
  }
1555 1556
  *ppColArray = pColArray;
  //}
1557 1558

  nextRowIterClose(&iter);
1559
  // taosMemoryFreeClear(pTSchema);
1560 1561 1562 1563 1564
  return code;

_err:
  nextRowIterClose(&iter);
  taosArrayDestroy(pColArray);
1565
  // taosMemoryFreeClear(pTSchema);
1566 1567 1568
  return code;
}

1569
static int32_t mergeLast(tb_uid_t uid, STsdb *pTsdb, SArray **ppLastArray, SCacheRowsReader *pr) {
1570
  STSchema *pTSchema = pr->pSchema;  // metaGetTbTSchema(pTsdb->pVnode->pMeta, uid, -1, 1);
1571
  int16_t   nLastCol = pTSchema->numOfCols;
1572 1573
  int16_t   noneCol = 0;
  bool      setNoneCol = false;
1574
  bool      hasRow = false;
1575
  bool      ignoreEarlierTs = false;
1576
  SArray   *pColArray = NULL;
1577
  SColVal  *pColVal = &(SColVal){0};
1578
  int16_t   nCols = nLastCol;
1579

1580 1581 1582 1583
  int32_t code = initLastColArray(pTSchema, &pColArray);
  if (TSDB_CODE_SUCCESS != code) {
    return code;
  }
1584 1585 1586 1587 1588 1589
  SArray *aColArray = taosArrayInit(nCols, sizeof(int16_t));
  if (NULL == aColArray) {
    taosArrayDestroy(pColArray);

    return TSDB_CODE_OUT_OF_MEMORY;
  }
1590 1591 1592
  for (int i = 1; i < pTSchema->numOfCols; ++i) {
    taosArrayPush(aColArray, &pTSchema->columns[i].colId);
  }
1593

1594 1595 1596
  TSKEY lastRowTs = TSKEY_MAX;

  CacheNextRowIter iter = {0};
1597
  nextRowIterOpen(&iter, uid, pTsdb, pTSchema, pr->suid, pr->pLoadInfo, pr->pReadSnap, &pr->pDataFReader,
1598
                  &pr->pDataFReaderLast, pr->lastTs);
1599 1600 1601

  do {
    TSDBROW *pRow = NULL;
1602
    nextRowIterGet(&iter, &pRow, &ignoreEarlierTs, true, TARRAY_DATA(aColArray), TARRAY_SIZE(aColArray));
1603 1604 1605 1606 1607

    if (!pRow) {
      break;
    }

1608 1609
    hasRow = true;

1610 1611 1612 1613 1614 1615 1616
    code = updateTSchema(TSDBROW_SVERSION(pRow), pr, uid);
    if (TSDB_CODE_SUCCESS != code) {
      goto _err;
    }
    pTSchema = pr->pCurrSchema;
    int16_t nCol = pTSchema->numOfCols;

1617 1618 1619 1620 1621 1622
    TSKEY rowTs = TSDBROW_TS(pRow);

    if (lastRowTs == TSKEY_MAX) {
      lastRowTs = rowTs;
      STColumn *pTColumn = &pTSchema->columns[0];

H
Hongze Cheng 已提交
1623
      *pColVal = COL_VAL_VALUE(pTColumn->colId, pTColumn->type, (SValue){.val = lastRowTs});
1624
      taosArraySet(pColArray, 0, &(SLastCol){.ts = lastRowTs, .colVal = *pColVal});
1625

1626 1627 1628 1629 1630 1631 1632 1633
      for (int16_t iCol = 1; iCol < nCol; ++iCol) {
        if (iCol >= nLastCol) {
          break;
        }
        SLastCol *pCol = taosArrayGet(pColArray, iCol);
        if (pCol->colVal.cid != pTSchema->columns[iCol].colId) {
          continue;
        }
1634 1635
        tsdbRowGetColVal(pRow, pTSchema, iCol, pColVal);

1636
        *pCol = (SLastCol){.ts = lastRowTs, .colVal = *pColVal};
1637
        if (IS_VAR_DATA_TYPE(pColVal->type) && pColVal->value.nData > 0) {
1638 1639
          pCol->colVal.value.pData = taosMemoryMalloc(pCol->colVal.value.nData);
          if (pCol->colVal.value.pData == NULL) {
M
Minglei Jin 已提交
1640 1641 1642 1643
            terrno = TSDB_CODE_OUT_OF_MEMORY;
            code = TSDB_CODE_OUT_OF_MEMORY;
            goto _err;
          }
1644
          memcpy(pCol->colVal.value.pData, pColVal->value.pData, pColVal->value.nData);
1645 1646
        }

1647 1648 1649 1650 1651
        if (!COL_VAL_IS_VALUE(pColVal)) {
          if (!setNoneCol) {
            noneCol = iCol;
            setNoneCol = true;
          }
1652 1653 1654
        } else {
          int32_t aColIndex = taosArraySearchIdx(aColArray, &pColVal->cid, compareInt16Val, TD_EQ);
          taosArrayRemove(aColArray, aColIndex);
1655 1656 1657
        }
      }
      if (!setNoneCol) {
1658
        // done, goto return pColArray
1659 1660 1661 1662 1663
        break;
      } else {
        continue;
      }
    }
1664

1665 1666
    // merge into pColArray
    setNoneCol = false;
1667 1668 1669 1670
    for (int16_t iCol = noneCol; iCol < nCol; ++iCol) {
      if (iCol >= nLastCol) {
        break;
      }
1671
      // high version's column value
1672
      SLastCol *lastColVal = (SLastCol *)taosArrayGet(pColArray, iCol);
1673 1674 1675 1676
      if (lastColVal->colVal.cid != pTSchema->columns[iCol].colId) {
        continue;
      }
      SColVal *tColVal = &lastColVal->colVal;
1677 1678

      tsdbRowGetColVal(pRow, pTSchema, iCol, pColVal);
H
Hongze Cheng 已提交
1679
      if (!COL_VAL_IS_VALUE(tColVal) && COL_VAL_IS_VALUE(pColVal)) {
1680
        SLastCol lastCol = {.ts = rowTs, .colVal = *pColVal};
1681
        if (IS_VAR_DATA_TYPE(pColVal->type) && pColVal->value.nData > 0) {
1682 1683 1684 1685
          SLastCol *pLastCol = (SLastCol *)taosArrayGet(pColArray, iCol);
          taosMemoryFree(pLastCol->colVal.value.pData);

          lastCol.colVal.value.pData = taosMemoryMalloc(lastCol.colVal.value.nData);
M
Minglei Jin 已提交
1686 1687 1688 1689 1690
          if (lastCol.colVal.value.pData == NULL) {
            terrno = TSDB_CODE_OUT_OF_MEMORY;
            code = TSDB_CODE_OUT_OF_MEMORY;
            goto _err;
          }
1691 1692 1693 1694
          memcpy(lastCol.colVal.value.pData, pColVal->value.pData, pColVal->value.nData);
        }

        taosArraySet(pColArray, iCol, &lastCol);
1695 1696
        int32_t aColIndex = taosArraySearchIdx(aColArray, &lastCol.colVal.cid, compareInt16Val, TD_EQ);
        taosArrayRemove(aColArray, aColIndex);
H
Hongze Cheng 已提交
1697
      } else if (!COL_VAL_IS_VALUE(tColVal) && !COL_VAL_IS_VALUE(pColVal) && !setNoneCol) {
1698 1699 1700 1701 1702 1703
        noneCol = iCol;
        setNoneCol = true;
      }
    }
  } while (setNoneCol);

1704 1705 1706 1707
  // if (taosArrayGetSize(pColArray) <= 0) {
  //*ppLastArray = NULL;
  // taosArrayDestroy(pColArray);
  //} else {
1708
  if (!hasRow) {
1709 1710 1711 1712 1713 1714
    if (ignoreEarlierTs) {
      taosArrayDestroy(pColArray);
      pColArray = NULL;
    } else {
      taosArrayClear(pColArray);
    }
1715
  }
1716 1717
  *ppLastArray = pColArray;
  //}
1718 1719

  nextRowIterClose(&iter);
M
Minglei Jin 已提交
1720
  taosArrayDestroy(aColArray);
1721
  // taosMemoryFreeClear(pTSchema);
1722 1723 1724 1725
  return code;

_err:
  nextRowIterClose(&iter);
1726
  // taosMemoryFreeClear(pTSchema);
1727 1728
  *ppLastArray = NULL;
  taosArrayDestroy(pColArray);
1729
  taosArrayDestroy(aColArray);
1730 1731 1732
  return code;
}

1733
int32_t tsdbCacheGetLastrowH(SLRUCache *pCache, tb_uid_t uid, SCacheRowsReader *pr, LRUHandle **handle) {
1734 1735 1736 1737
  int32_t code = 0;
  char    key[32] = {0};
  int     keyLen = 0;

1738
  //  getTableCacheKeyS(uid, "lr", key, &keyLen);
1739
  getTableCacheKey(uid, 0, key, &keyLen);
1740
  LRUHandle *h = taosLRUCacheLookup(pCache, key, keyLen);
1741
  if (!h) {
1742
    STsdb *pTsdb = pr->pVnode->pTsdb;
1743 1744 1745 1746
    taosThreadMutexLock(&pTsdb->lruMutex);

    h = taosLRUCacheLookup(pCache, key, keyLen);
    if (!h) {
1747
      SArray *pArray = NULL;
1748
      bool    dup = false;  // which is always false for now
1749
      code = mergeLastRow(uid, pTsdb, &dup, &pArray, pr);
1750 1751
      // if table's empty or error or ignore ignore earlier ts, set handle NULL and return
      if (code < 0 || pArray == NULL) {
1752 1753
        if (!dup && pArray) {
          taosArrayDestroy(pArray);
1754 1755
        }

M
Minglei Jin 已提交
1756 1757
        taosThreadMutexUnlock(&pTsdb->lruMutex);

1758
        *handle = NULL;
M
Minglei Jin 已提交
1759

1760
        return 0;
1761 1762
      }

M
Minglei Jin 已提交
1763
      size_t              charge = pArray->capacity * pArray->elemSize + sizeof(*pArray);
1764
      _taos_lru_deleter_t deleter = deleteTableCacheLast;
1765
      LRUStatus status = taosLRUCacheInsert(pCache, key, keyLen, pArray, charge, deleter, &h, TAOS_LRU_PRIORITY_LOW);
1766 1767 1768
      if (status != TAOS_LRU_STATUS_OK) {
        code = -1;
      }
1769
    }
1770
    taosThreadMutexUnlock(&pTsdb->lruMutex);
1771 1772 1773 1774 1775 1776
  }

  *handle = h;

  return code;
}
1777

1778
int32_t tsdbCacheGetLastH(SLRUCache *pCache, tb_uid_t uid, SCacheRowsReader *pr, LRUHandle **handle) {
1779 1780 1781 1782
  int32_t code = 0;
  char    key[32] = {0};
  int     keyLen = 0;

1783
  // getTableCacheKeyS(uid, "l", key, &keyLen);
1784
  getTableCacheKey(uid, 1, key, &keyLen);
1785
  LRUHandle *h = taosLRUCacheLookup(pCache, key, keyLen);
1786
  if (!h) {
1787
    STsdb *pTsdb = pr->pVnode->pTsdb;
1788
    taosThreadMutexLock(&pTsdb->lruMutex);
1789

1790
    h = taosLRUCacheLookup(pCache, key, keyLen);
1791 1792
    if (!h) {
      SArray *pLastArray = NULL;
1793
      code = mergeLast(uid, pTsdb, &pLastArray, pr);
1794 1795
      // if table's empty or error or ignore ignore earlier ts, set handle NULL and return
      if (code < 0 || pLastArray == NULL) {
1796 1797
        taosThreadMutexUnlock(&pTsdb->lruMutex);

1798 1799 1800 1801
        *handle = NULL;
        return 0;
      }

M
Minglei Jin 已提交
1802
      size_t              charge = pLastArray->capacity * pLastArray->elemSize + sizeof(*pLastArray);
1803
      _taos_lru_deleter_t deleter = deleteTableCacheLast;
M
Minglei Jin 已提交
1804
      LRUStatus           status =
1805
          taosLRUCacheInsert(pCache, key, keyLen, pLastArray, charge, deleter, &h, TAOS_LRU_PRIORITY_LOW);
1806 1807 1808
      if (status != TAOS_LRU_STATUS_OK) {
        code = -1;
      }
1809
    }
1810
    taosThreadMutexUnlock(&pTsdb->lruMutex);
1811 1812 1813
  }

  *handle = h;
M
Minglei Jin 已提交
1814

1815 1816 1817
  return code;
}

M
Minglei Jin 已提交
1818 1819 1820 1821 1822 1823 1824
int32_t tsdbCacheRelease(SLRUCache *pCache, LRUHandle *h) {
  int32_t code = 0;

  taosLRUCacheRelease(pCache, h, false);

  return code;
}
1825 1826 1827 1828 1829 1830

void tsdbCacheSetCapacity(SVnode *pVnode, size_t capacity) {
  taosLRUCacheSetCapacity(pVnode->pTsdb->lruCache, capacity);
}

size_t tsdbCacheGetCapacity(SVnode *pVnode) { return taosLRUCacheGetCapacity(pVnode->pTsdb->lruCache); }
1831

1832 1833 1834 1835 1836 1837 1838 1839
size_t tsdbCacheGetUsage(SVnode *pVnode) {
  size_t usage = 0;
  if (pVnode->pTsdb != NULL) {
    usage = taosLRUCacheGetUsage(pVnode->pTsdb->lruCache);
  }

  return usage;
}
1840

1841 1842 1843 1844 1845 1846 1847 1848 1849
int32_t tsdbCacheGetElems(SVnode *pVnode) {
  int32_t elems = 0;
  if (pVnode->pTsdb != NULL) {
    elems = taosLRUCacheGetElems(pVnode->pTsdb->lruCache);
  }

  return elems;
}

1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929
static void getBICacheKey(int32_t fid, int64_t commitID, char *key, int *len) {
  struct {
    int32_t fid;
    int64_t commitID;
  } biKey = {0};

  biKey.fid = fid;
  biKey.commitID = commitID;

  *len = sizeof(biKey);
  memcpy(key, &biKey, *len);
}

static int32_t tsdbCacheLoadBlockIdx(SDataFReader *pFileReader, SArray **aBlockIdx) {
  SArray *pArray = taosArrayInit(8, sizeof(SBlockIdx));
  int32_t code = tsdbReadBlockIdx(pFileReader, pArray);

  if (code != TSDB_CODE_SUCCESS) {
    taosArrayDestroy(pArray);
    code = TSDB_CODE_OUT_OF_MEMORY;
    return code;
  }

  *aBlockIdx = pArray;

  return code;
}

static void deleteBICache(const void *key, size_t keyLen, void *value) {
  SArray *pArray = (SArray *)value;

  taosArrayDestroy(pArray);
}

int32_t tsdbCacheGetBlockIdx(SLRUCache *pCache, SDataFReader *pFileReader, LRUHandle **handle) {
  int32_t code = 0;
  char    key[128] = {0};
  int     keyLen = 0;

  getBICacheKey(pFileReader->pSet->fid, pFileReader->pSet->pHeadF->commitID, key, &keyLen);
  LRUHandle *h = taosLRUCacheLookup(pCache, key, keyLen);
  if (!h) {
    STsdb *pTsdb = pFileReader->pTsdb;
    taosThreadMutexLock(&pTsdb->biMutex);

    h = taosLRUCacheLookup(pCache, key, keyLen);
    if (!h) {
      SArray *pArray = NULL;
      code = tsdbCacheLoadBlockIdx(pFileReader, &pArray);
      //  if table's empty or error, return code of -1
      if (code != TSDB_CODE_SUCCESS || pArray == NULL) {
        taosThreadMutexUnlock(&pTsdb->biMutex);

        *handle = NULL;
        return 0;
      }

      size_t              charge = pArray->capacity * pArray->elemSize + sizeof(*pArray);
      _taos_lru_deleter_t deleter = deleteBICache;
      LRUStatus status = taosLRUCacheInsert(pCache, key, keyLen, pArray, charge, deleter, &h, TAOS_LRU_PRIORITY_LOW);
      if (status != TAOS_LRU_STATUS_OK) {
        code = -1;
      }
    }

    taosThreadMutexUnlock(&pTsdb->biMutex);
  }

  *handle = h;

  return code;
}

int32_t tsdbBICacheRelease(SLRUCache *pCache, LRUHandle *h) {
  int32_t code = 0;

  taosLRUCacheRelease(pCache, h, false);

  return code;
}