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

int32_t tsdbOpenCache(STsdb *pTsdb) {
H
Hongze Cheng 已提交
19
  int32_t    code = 0;
20
  SLRUCache *pCache = NULL;
21 22
  // TODO: get cfg from vnode config: pTsdb->pVnode->config.lruCapacity
  size_t cfgCapacity = 1024 * 1024;
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44

  pCache = taosLRUCacheInit(cfgCapacity, -1, .5);
  if (pCache == NULL) {
    code = TSDB_CODE_OUT_OF_MEMORY;
    goto _err;
  }

  taosLRUCacheSetStrictCapacity(pCache, true);

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

void tsdbCloseCache(SLRUCache *pCache) {
  if (pCache) {
    taosLRUCacheEraseUnrefEntries(pCache);

    taosLRUCacheCleanup(pCache);
  }
}

45
static void getTableCacheKeyS(tb_uid_t uid, const char *cacheType, char *key, int *len) {
H
Hongze Cheng 已提交
46
  snprintf(key, 30, "%" PRIi64 "%s", uid, cacheType);
47 48 49
  *len = strlen(key);
}

50 51 52 53 54 55 56 57 58 59
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);
}

H
Hongze Cheng 已提交
60
static void deleteTableCacheLastrow(const void *key, size_t keyLen, void *value) { taosMemoryFree(value); }
61

62 63 64 65 66
static int32_t tsdbCacheDeleteLastrow(SLRUCache *pCache, tb_uid_t uid, TSKEY eKey) {
  int32_t code = 0;
  char    key[32] = {0};
  int     keyLen = 0;

67 68
  // getTableCacheKey(uid, "lr", key, &keyLen);
  getTableCacheKey(uid, 0, key, &keyLen);
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
  LRUHandle *h = taosLRUCacheLookup(pCache, key, keyLen);
  if (h) {
    STSRow *pRow = (STSRow *)taosLRUCacheValue(pCache, h);
    if (pRow->ts <= eKey) {
      taosLRUCacheRelease(pCache, h, true);
    } else {
      taosLRUCacheRelease(pCache, h, false);
    }

    // void taosLRUCacheErase(SLRUCache * cache, const void *key, size_t keyLen);
  }

  return code;
}

static int32_t tsdbCacheDeleteLast(SLRUCache *pCache, tb_uid_t uid, TSKEY eKey) {
  int32_t code = 0;
  char    key[32] = {0};
  int     keyLen = 0;

89 90
  // getTableCacheKey(uid, "l", key, &keyLen);
  getTableCacheKey(uid, 1, key, &keyLen);
91 92 93 94 95 96 97 98 99 100 101
  LRUHandle *h = taosLRUCacheLookup(pCache, key, keyLen);
  if (h) {
    // clear last cache anyway, no matter where eKey ends.
    taosLRUCacheRelease(pCache, h, true);

    // void taosLRUCacheErase(SLRUCache * cache, const void *key, size_t keyLen);
  }

  return code;
}

102
int32_t tsdbCacheInsertLastrow(SLRUCache *pCache, STsdb *pTsdb, tb_uid_t uid, STSRow *row, bool dup) {
103 104
  int32_t code = 0;
  STSRow *cacheRow = NULL;
H
Hongze Cheng 已提交
105 106
  char    key[32] = {0};
  int     keyLen = 0;
107

108 109
  // getTableCacheKey(uid, "lr", key, &keyLen);
  getTableCacheKey(uid, 0, key, &keyLen);
110 111
  LRUHandle *h = taosLRUCacheLookup(pCache, key, keyLen);
  if (h) {
H
Hongze Cheng 已提交
112
    cacheRow = (STSRow *)taosLRUCacheValue(pCache, h);
113
    if (row->ts >= cacheRow->ts) {
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
      if (row->ts == cacheRow->ts) {
        STSRow    *mergedRow;
        SRowMerger merger = {0};
        STSchema  *pTSchema = metaGetTbTSchema(pTsdb->pVnode->pMeta, uid, -1);

        tRowMergerInit(&merger, &tsdbRowFromTSRow(0, cacheRow), pTSchema);

        tRowMerge(&merger, &tsdbRowFromTSRow(1, row));

        tRowMergerGetRow(&merger, &mergedRow);
        tRowMergerClear(&merger);

        taosMemoryFreeClear(pTSchema);

        row = mergedRow;
        dup = false;
      }

132
      if (TD_ROW_LEN(row) <= TD_ROW_LEN(cacheRow)) {
H
Hongze Cheng 已提交
133
        tdRowCpy(cacheRow, row);
134 135 136
        if (!dup) {
          taosMemoryFree(row);
        }
137 138

        taosLRUCacheRelease(pCache, h, false);
139
      } else {
140 141
        taosLRUCacheRelease(pCache, h, true);
        // tsdbCacheDeleteLastrow(pCache, uid, TSKEY_MAX);
M
Minglei Jin 已提交
142 143 144 145 146
        if (dup) {
          cacheRow = tdRowDup(row);
        } else {
          cacheRow = row;
        }
147 148 149 150 151 152 153
        _taos_lru_deleter_t deleter = deleteTableCacheLastrow;
        LRUStatus status = taosLRUCacheInsert(pCache, key, keyLen, cacheRow, TD_ROW_LEN(cacheRow), deleter, NULL,
                                              TAOS_LRU_PRIORITY_LOW);
        if (status != TAOS_LRU_STATUS_OK) {
          code = -1;
        }
        /* tsdbCacheInsertLastrow(pCache, uid, row, dup); */
154 155 156
      }
    }
  } else {
157 158 159 160 161
    if (dup) {
      cacheRow = tdRowDup(row);
    } else {
      cacheRow = row;
    }
162 163

    _taos_lru_deleter_t deleter = deleteTableCacheLastrow;
H
Hongze Cheng 已提交
164 165
    LRUStatus           status =
        taosLRUCacheInsert(pCache, key, keyLen, cacheRow, TD_ROW_LEN(cacheRow), deleter, NULL, TAOS_LRU_PRIORITY_LOW);
166 167 168 169 170 171 172 173
    if (status != TAOS_LRU_STATUS_OK) {
      code = -1;
    }
  }

  return code;
}

174 175 176 177 178 179
int32_t tsdbCacheInsertLast(SLRUCache *pCache, tb_uid_t uid, STSRow *row) {
  int32_t code = 0;
  STSRow *cacheRow = NULL;
  char    key[32] = {0};
  int     keyLen = 0;

180 181
  ((void)(row));

182 183
  // getTableCacheKey(uid, "l", key, &keyLen);
  getTableCacheKey(uid, 1, key, &keyLen);
184 185
  LRUHandle *h = taosLRUCacheLookup(pCache, key, keyLen);
  if (h) {
186 187
    // clear last cache anyway, lazy load when get last lookup
    taosLRUCacheRelease(pCache, h, true);
188 189 190 191 192
  }

  return code;
}

193 194 195 196 197 198
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);
  if (metaGetTableEntryByUid(&mr, uid) < 0) {
H
Hongze Cheng 已提交
199
    metaReaderClear(&mr);  // table not esist
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
    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;

219 220
  // SMapData delDataMap;
  // SDelData delData;
221 222

  if (pDelIdx) {
223
    // tMapDataReset(&delDataMap);
224

225
    // code = tsdbReadDelData(pDelReader, pDelIdx, &delDataMap, NULL);
226
    code = tsdbReadDelData(pDelReader, pDelIdx, aDelData, NULL);
227
    if (code) goto _err;
228
    /*
229 230 231 232 233 234
    for (int32_t iDelData = 0; iDelData < delDataMap.nItem; ++iDelData) {
      code = tMapDataGetItemByIdx(&delDataMap, iDelData, &delData, tGetDelData);
      if (code) goto _err;

      taosArrayPush(aDelData, &delData);
    }
235
    */
236 237 238 239 240 241 242
  }

_err:
  return code;
}

static int32_t getTableDelDataFromTbData(STbData *pTbData, SArray *aDelData) {
H
Hongze Cheng 已提交
243
  int32_t   code = 0;
244 245 246 247 248 249 250 251 252
  SDelData *pDelData = pTbData ? pTbData->pHead : NULL;

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

  return code;
}

H
Hongze Cheng 已提交
253 254
static int32_t getTableDelData(STbData *pMem, STbData *pIMem, SDelFReader *pDelReader, SDelIdx *pDelIdx,
                               SArray *aDelData) {
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
  int32_t code = 0;

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

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

  if (pDelIdx) {
    code = getTableDelDataFromDelIdx(pDelReader, pDelIdx, aDelData);
    if (code) goto _err;
  }

_err:
  return code;
}

H
Hongze Cheng 已提交
276 277
static int32_t getTableDelSkyline(STbData *pMem, STbData *pIMem, SDelFReader *pDelReader, SDelIdx *pDelIdx,
                                  SArray *aSkyline) {
278
  int32_t code = 0;
M
Minglei Jin 已提交
279
  SArray *aDelData = NULL;
280

M
Minglei Jin 已提交
281
  aDelData = taosArrayInit(32, sizeof(SDelData));
282 283 284 285
  code = getTableDelData(pMem, pIMem, pDelReader, pDelIdx, aDelData);
  if (code) goto _err;

  size_t nDelData = taosArrayGetSize(aDelData);
286 287 288 289
  if (nDelData > 0) {
    code = tsdbBuildDeleteSkyline(aDelData, 0, (int32_t)(nDelData - 1), aSkyline);
    if (code) goto _err;
  }
290

M
Minglei Jin 已提交
291 292 293
  if (aDelData) {
    taosArrayDestroy(aDelData);
  }
294 295 296 297 298 299
_err:
  return code;
}

static int32_t getTableDelIdx(SDelFReader *pDelFReader, tb_uid_t suid, tb_uid_t uid, SDelIdx *pDelIdx) {
  int32_t code = 0;
M
Minglei Jin 已提交
300
  SArray *pDelIdxArray = NULL;
301

302
  // SMapData delIdxMap;
M
Minglei Jin 已提交
303
  pDelIdxArray = taosArrayInit(32, sizeof(SDelIdx));
304
  SDelIdx idx = {.suid = suid, .uid = uid};
305

306 307 308
  // tMapDataReset(&delIdxMap);
  //  code = tsdbReadDelIdx(pDelFReader, &delIdxMap, NULL);
  code = tsdbReadDelIdx(pDelFReader, pDelIdxArray, NULL);
309 310
  if (code) goto _err;

311 312
  // code = tMapDataSearch(&delIdxMap, &idx, tGetDelIdx, tCmprDelIdx, pDelIdx);
  pDelIdx = taosArraySearch(pDelIdxArray, &idx, tCmprDelIdx, TD_EQ);
313 314
  if (code) goto _err;

M
Minglei Jin 已提交
315 316 317
  if (pDelIdxArray) {
    taosArrayDestroy(pDelIdxArray);
  }
318 319 320
_err:
  return code;
}
321

322 323 324 325 326 327 328 329 330 331 332 333 334 335 336
typedef enum SFSNEXTROWSTATES {
  SFSNEXTROW_FS,
  SFSNEXTROW_FILESET,
  SFSNEXTROW_BLOCKDATA,
  SFSNEXTROW_BLOCKROW
} SFSNEXTROWSTATES;

typedef struct SFSNextRowIter {
  SFSNEXTROWSTATES state;         // [input]
  STsdb           *pTsdb;         // [input]
  SBlockIdx       *pBlockIdxExp;  // [input]
  int32_t          nFileSet;
  int32_t          iFileSet;
  SArray          *aDFileSet;
  SDataFReader    *pDataFReader;
337 338 339
  SArray          *aBlockIdx;
  // SMapData         blockIdxMap;
  //  SBlockIdx  blockIdx;
340 341 342 343 344 345 346 347 348 349
  SBlockIdx  *pBlockIdx;
  SMapData    blockMap;
  int32_t     nBlock;
  int32_t     iBlock;
  SBlock      block;
  SBlockData  blockData;
  SBlockData *pBlockData;
  int32_t     nRow;
  int32_t     iRow;
  TSDBROW     row;
350 351 352 353 354 355 356 357 358 359
} SFSNextRowIter;

static int32_t getNextRowFromFS(void *iter, TSDBROW **ppRow) {
  SFSNextRowIter *state = (SFSNextRowIter *)iter;
  int32_t         code = 0;

  switch (state->state) {
    case SFSNEXTROW_FS:
      state->aDFileSet = state->pTsdb->fs->cState->aDFileSet;
      state->nFileSet = taosArrayGetSize(state->aDFileSet);
360 361 362
      state->iFileSet = state->nFileSet - 1;

      state->pBlockData = NULL;
363 364 365 366 367 368

    case SFSNEXTROW_FILESET: {
      SDFileSet *pFileSet = NULL;
      if (--state->iFileSet >= 0) {
        pFileSet = (SDFileSet *)taosArrayGet(state->aDFileSet, state->iFileSet);
      } else {
369 370 371 372 373
        // tBlockDataClear(&state->blockData);
        if (state->pBlockData) {
          tBlockDataClear(state->pBlockData);
          state->pBlockData = NULL;
        }
374

375 376 377 378 379 380
        *ppRow = NULL;
        return code;
      }

      code = tsdbDataFReaderOpen(&state->pDataFReader, state->pTsdb, pFileSet);
      if (code) goto _err;
381 382 383 384 385 386 387 388 389

      // tMapDataReset(&state->blockIdxMap);
      // code = tsdbReadBlockIdx(state->pDataFReader, &state->blockIdxMap, NULL);
      if (!state->aBlockIdx) {
        state->aBlockIdx = taosArrayInit(0, sizeof(SBlockIdx));
      } else {
        taosArrayClear(state->aBlockIdx);
      }
      code = tsdbReadBlockIdx(state->pDataFReader, state->aBlockIdx, NULL);
390 391
      if (code) goto _err;

392 393 394 395
      /* if (state->pBlockIdx) { */
      /*   tBlockIdxReset(state->blockIdx); */
      /* } */
      /* tBlockIdxReset(state->blockIdx); */
396 397
      /* code = tMapDataSearch(&state->blockIdxMap, state->pBlockIdxExp, tGetBlockIdx, tCmprBlockIdx,
       * &state->blockIdx);
398 399
       */
      state->pBlockIdx = taosArraySearch(state->aBlockIdx, state->pBlockIdxExp, tCmprBlockIdx, TD_EQ);
400
      if (code) goto _err;
401

402
      tMapDataReset(&state->blockMap);
403 404
      code = tsdbReadBlock(state->pDataFReader, state->pBlockIdx, &state->blockMap, NULL);
      /* code = tsdbReadBlock(state->pDataFReader, &state->blockIdx, &state->blockMap, NULL); */
405 406 407 408
      if (code) goto _err;

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

410 411 412 413 414
      if (!state->pBlockData) {
        state->pBlockData = &state->blockData;

        tBlockDataInit(&state->blockData);
      }
415 416 417 418 419 420
    }
    case SFSNEXTROW_BLOCKDATA:
      if (state->iBlock >= 0) {
        SBlock block = {0};

        tBlockReset(&block);
421 422
        // tBlockDataReset(&state->blockData);
        tBlockDataReset(state->pBlockData);
423 424

        tMapDataGetItemByIdx(&state->blockMap, state->iBlock, &block, tGetBlock);
425
        /* code = tsdbReadBlockData(state->pDataFReader, &state->blockIdx, &block, &state->blockData, NULL, NULL); */
426
        code = tsdbReadBlockData(state->pDataFReader, state->pBlockIdx, &block, state->pBlockData, NULL, NULL);
427 428 429 430 431 432 433 434 435
        if (code) goto _err;

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

        state->state = SFSNEXTROW_BLOCKROW;
      }
    case SFSNEXTROW_BLOCKROW:
      if (state->iRow >= 0) {
436
        state->row = tsdbRowFromBlockData(state->pBlockData, state->iRow);
437 438 439 440 441 442
        *ppRow = &state->row;

        if (--state->iRow < 0) {
          state->state = SFSNEXTROW_BLOCKDATA;
          if (--state->iBlock < 0) {
            tsdbDataFReaderClose(&state->pDataFReader);
443 444
            state->pDataFReader = NULL;

445 446
            if (state->aBlockIdx) {
              taosArrayDestroy(state->aBlockIdx);
447
              state->aBlockIdx = NULL;
448
            }
449

450 451 452 453 454 455 456 457 458 459 460 461
            state->state = SFSNEXTROW_FILESET;
          }
        }
      }

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

_err:
462 463
  if (state->pDataFReader) {
    tsdbDataFReaderClose(&state->pDataFReader);
464
    state->pDataFReader = NULL;
465 466 467
  }
  if (state->aBlockIdx) {
    taosArrayDestroy(state->aBlockIdx);
468 469 470 471 472 473
    state->aBlockIdx = NULL;
  }
  if (state->pBlockData) {
    // tBlockDataClear(&state->blockData);
    tBlockDataClear(state->pBlockData);
    state->pBlockData = NULL;
474 475
  }

476
  *ppRow = NULL;
477

478 479 480
  return code;
}

481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505
int32_t clearNextRowFromFS(void *iter) {
  int32_t code = 0;

  SFSNextRowIter *state = (SFSNextRowIter *)iter;
  if (!state) {
    return code;
  }

  if (state->pDataFReader) {
    tsdbDataFReaderClose(&state->pDataFReader);
    state->pDataFReader = NULL;
  }
  if (state->aBlockIdx) {
    taosArrayDestroy(state->aBlockIdx);
    state->aBlockIdx = NULL;
  }
  if (state->pBlockData) {
    // tBlockDataClear(&state->blockData);
    tBlockDataClear(state->pBlockData);
    state->pBlockData = NULL;
  }

  return code;
}

506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558
typedef enum SMEMNEXTROWSTATES {
  SMEMNEXTROW_ENTER,
  SMEMNEXTROW_NEXT,
} SMEMNEXTROWSTATES;

typedef struct SMemNextRowIter {
  SMEMNEXTROWSTATES state;
  STbData          *pMem;  // [input]
  STbDataIter       iter;  // mem buffer skip list iterator
} SMemNextRowIter;

static int32_t getNextRowFromMem(void *iter, TSDBROW **ppRow) {
  SMemNextRowIter *state = (SMemNextRowIter *)iter;
  int32_t          code = 0;

  switch (state->state) {
    case SMEMNEXTROW_ENTER: {
      if (state->pMem != NULL) {
        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;
}

559 560 561 562 563
static int32_t tsRowFromTsdbRow(STSchema *pTSchema, TSDBROW *pRow, STSRow **ppRow) {
  int32_t code = 0;

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

564
  if (pRow->type == 0) {
565
    *ppRow = tdRowDup(pRow->pTSRow);
566
  } else {
567 568 569 570 571 572
    SArray *pArray = taosArrayInit(pTSchema->numOfCols, sizeof(SColVal));
    if (pArray == NULL) {
      code = TSDB_CODE_OUT_OF_MEMORY;
      goto _exit;
    }

573 574 575 576 577 578 579 580 581
    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;
    }

582 583 584 585 586 587 588 589 590 591
    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;
592 593
  }

594 595
_exit:
  return code;
596 597
}

598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623
static bool tsdbKeyDeleted(TSDBKEY *key, SArray *pSkyline, int *iSkyline) {
  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) {
      if ((key->version <= pItemFront->version || key->ts == pItemBack->ts && key->version <= pItemBack->version)) {
        return true;
      } else {
        return false;
      }
    } else {
      if (*iSkyline > 1) {
        --*iSkyline;
      } else {
        return false;
      }
    }
  }

  return deleted;
}

624
typedef int32_t (*_next_row_fn_t)(void *iter, TSDBROW **ppRow);
625
typedef int32_t (*_next_row_clear_fn_t)(void *iter);
626 627

typedef struct TsdbNextRowState {
628 629 630 631 632 633
  TSDBROW             *pRow;
  bool                 stop;
  bool                 next;
  void                *iter;
  _next_row_fn_t       nextRowFn;
  _next_row_clear_fn_t nextRowClearFn;
634
} TsdbNextRowState;
635

636
static int32_t mergeLastRow(tb_uid_t uid, STsdb *pTsdb, bool *dup, STSRow **ppRow) {
637
  int32_t code = 0;
638
  SArray *pSkyline = NULL;
639

M
Minglei Jin 已提交
640 641 642 643
  STSchema *pTSchema = metaGetTbTSchema(pTsdb->pVnode->pMeta, uid, -1);
  int16_t   nCol = pTSchema->numOfCols;
  SArray   *pColArray = taosArrayInit(nCol, sizeof(SColVal));

644 645
  tb_uid_t suid = getTableSuidByUid(uid, pTsdb);

646
  STbData *pMem = NULL;
647 648 649 650
  if (pTsdb->mem) {
    tsdbGetTbDataFromMemTable(pTsdb->mem, suid, uid, &pMem);
  }

651
  STbData *pIMem = NULL;
652 653 654 655 656 657
  if (pTsdb->imem) {
    tsdbGetTbDataFromMemTable(pTsdb->imem, suid, uid, &pIMem);
  }

  *ppRow = NULL;

658
  pSkyline = taosArrayInit(32, sizeof(TSDBKEY));
659

M
Minglei Jin 已提交
660 661
  SDelIdx delIdx;

662 663 664
  SDelFile *pDelFile = tsdbFSStateGetDelFile(pTsdb->fs->cState);
  if (pDelFile) {
    SDelFReader *pDelFReader;
665

666 667
    code = tsdbDelFReaderOpen(&pDelFReader, pDelFile, pTsdb, NULL);
    if (code) goto _err;
668

669 670 671 672 673
    code = getTableDelIdx(pDelFReader, suid, uid, &delIdx);
    if (code) goto _err;

    code = getTableDelSkyline(pMem, pIMem, pDelFReader, &delIdx, pSkyline);
    if (code) goto _err;
674

H
Hongze Cheng 已提交
675
    tsdbDelFReaderClose(&pDelFReader);
M
Minglei Jin 已提交
676 677 678
  } else {
    code = getTableDelSkyline(pMem, pIMem, NULL, NULL, pSkyline);
    if (code) goto _err;
679 680 681
  }

  int iSkyline = taosArrayGetSize(pSkyline) - 1;
682 683 684 685 686 687 688

  SBlockIdx idx = {.suid = suid, .uid = uid};

  SFSNextRowIter fsState = {0};
  fsState.state = SFSNEXTROW_FS;
  fsState.pTsdb = pTsdb;
  fsState.pBlockIdxExp = &idx;
H
Hongze Cheng 已提交
689

690 691 692 693
  SMemNextRowIter memState = {0};
  SMemNextRowIter imemState = {0};
  TSDBROW         memRow, imemRow, fsRow;

694 695 696
  TsdbNextRowState input[3] = {{&memRow, true, false, &memState, getNextRowFromMem, NULL},
                               {&imemRow, true, false, &imemState, getNextRowFromMem, NULL},
                               {&fsRow, false, true, &fsState, getNextRowFromFS, clearNextRowFromFS}};
697 698 699 700 701 702 703 704 705 706 707 708

  if (pMem) {
    memState.pMem = pMem;
    memState.state = SMEMNEXTROW_ENTER;
    input[0].stop = false;
    input[0].next = true;
  }
  if (pIMem) {
    imemState.pMem = pIMem;
    imemState.state = SMEMNEXTROW_ENTER;
    input[1].stop = false;
    input[1].next = true;
H
Hongze Cheng 已提交
709
  }
710

M
Minglei Jin 已提交
711 712 713
  int16_t nilColCount = nCol - 1;  // count of null & none cols
  int     iCol = 0;                // index of first nil col index from left to right
  bool    setICol = false;
714

715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735
  do {
    for (int i = 0; i < 3; ++i) {
      if (input[i].next && !input[i].stop) {
        code = input[i].nextRowFn(input[i].iter, &input[i].pRow);
        if (code) goto _err;

        if (input[i].pRow == NULL) {
          input[i].stop = true;
          input[i].next = false;
        }
      }
    }

    if (input[0].stop && input[1].stop && input[2].stop) {
      break;
    }

    // select maxpoint(s) from mem, imem, fs
    TSDBROW *max[3] = {0};
    int      iMax[3] = {-1, -1, -1};
    int      nMax = 0;
M
Minglei Jin 已提交
736 737
    TSKEY    maxKey = TSKEY_MIN;

738
    for (int i = 0; i < 3; ++i) {
M
Minglei Jin 已提交
739
      if (!input[i].stop && input[i].pRow != NULL) {
740 741 742
        TSDBKEY key = TSDBROW_KEY(input[i].pRow);

        // merging & deduplicating on client side
M
Minglei Jin 已提交
743 744
        if (maxKey <= key.ts) {
          if (maxKey < key.ts) {
745
            nMax = 0;
M
Minglei Jin 已提交
746
            maxKey = key.ts;
747 748 749 750 751 752 753 754 755 756
          }

          iMax[nMax] = i;
          max[nMax++] = input[i].pRow;
        }
      }
    }

    // delete detection
    TSDBROW *merge[3] = {0};
757 758
    // int      iMerge[3] = {-1, -1, -1};
    int nMerge = 0;
759 760 761
    for (int i = 0; i < nMax; ++i) {
      TSDBKEY maxKey = TSDBROW_KEY(max[i]);

762 763
      // bool deleted = false;
      bool deleted = tsdbKeyDeleted(&maxKey, pSkyline, &iSkyline);
764
      if (!deleted) {
765
        // iMerge[nMerge] = i;
766 767
        merge[nMerge++] = max[i];
      }
768 769

      input[iMax[i]].next = deleted;
770 771 772 773
    }

    // merge if nMerge > 1
    if (nMerge > 0) {
774 775
      *dup = false;

776
      if (nMerge == 1) {
777 778
        code = tsRowFromTsdbRow(pTSchema, merge[nMerge - 1], ppRow);
        if (code) goto _err;
779 780 781 782 783 784 785 786 787 788 789 790
      } else {
        // merge 2 or 3 rows
        SRowMerger merger = {0};

        tRowMergerInit(&merger, merge[0], pTSchema);
        for (int i = 1; i < nMerge; ++i) {
          tRowMerge(&merger, merge[i]);
        }
        tRowMergerGetRow(&merger, ppRow);
        tRowMergerClear(&merger);
      }
    }
M
Minglei Jin 已提交
791

792
  } while (*ppRow == NULL);
793

794 795 796 797 798 799 800 801
  for (int i = 0; i < 3; ++i) {
    if (input[i].nextRowClearFn) {
      input[i].nextRowClearFn(input[i].iter);
    }
  }
  if (pSkyline) {
    taosArrayDestroy(pSkyline);
  }
802
  taosMemoryFreeClear(pTSchema);
803

804
  return code;
805
_err:
M
Minglei Jin 已提交
806 807 808 809 810
  for (int i = 0; i < 3; ++i) {
    if (input[i].nextRowClearFn) {
      input[i].nextRowClearFn(input[i].iter);
    }
  }
811 812 813
  if (pSkyline) {
    taosArrayDestroy(pSkyline);
  }
814
  taosMemoryFreeClear(pTSchema);
815 816 817 818
  tsdbError("vgId:%d merge last_row failed since %s", TD_VID(pTsdb->pVnode), tstrerror(code));
  return code;
}

M
Minglei Jin 已提交
819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856
static int32_t mergeLast(tb_uid_t uid, STsdb *pTsdb, STSRow **ppRow) {
  int32_t code = 0;

  STSchema *pTSchema = metaGetTbTSchema(pTsdb->pVnode->pMeta, uid, -1);
  int16_t   nCol = pTSchema->numOfCols;
  SArray   *pColArray = taosArrayInit(nCol, sizeof(SColVal));

  tb_uid_t suid = getTableSuidByUid(uid, pTsdb);

  STbData *pMem = NULL;
  if (pTsdb->mem) {
    tsdbGetTbDataFromMemTable(pTsdb->mem, suid, uid, &pMem);
  }

  STbData *pIMem = NULL;
  if (pTsdb->imem) {
    tsdbGetTbDataFromMemTable(pTsdb->imem, suid, uid, &pIMem);
  }

  *ppRow = NULL;

  SArray *pSkyline = taosArrayInit(32, sizeof(TSDBKEY));

  SDelIdx delIdx;

  SDelFile *pDelFile = tsdbFSStateGetDelFile(pTsdb->fs->cState);
  if (pDelFile) {
    SDelFReader *pDelFReader;

    code = tsdbDelFReaderOpen(&pDelFReader, pDelFile, pTsdb, NULL);
    if (code) goto _err;

    code = getTableDelIdx(pDelFReader, suid, uid, &delIdx);
    if (code) goto _err;

    code = getTableDelSkyline(pMem, pIMem, pDelFReader, &delIdx, pSkyline);
    if (code) goto _err;

H
Hongze Cheng 已提交
857
    tsdbDelFReaderClose(&pDelFReader);
M
Minglei Jin 已提交
858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875
  } else {
    code = getTableDelSkyline(pMem, pIMem, NULL, NULL, pSkyline);
    if (code) goto _err;
  }

  int iSkyline = taosArrayGetSize(pSkyline) - 1;

  SBlockIdx idx = {.suid = suid, .uid = uid};

  SFSNextRowIter fsState = {0};
  fsState.state = SFSNEXTROW_FS;
  fsState.pTsdb = pTsdb;
  fsState.pBlockIdxExp = &idx;

  SMemNextRowIter memState = {0};
  SMemNextRowIter imemState = {0};
  TSDBROW         memRow, imemRow, fsRow;

876 877 878
  TsdbNextRowState input[3] = {{&memRow, true, false, &memState, getNextRowFromMem, NULL},
                               {&imemRow, true, false, &imemState, getNextRowFromMem, NULL},
                               {&fsRow, false, true, &fsState, getNextRowFromFS, clearNextRowFromFS}};
M
Minglei Jin 已提交
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 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946

  if (pMem) {
    memState.pMem = pMem;
    memState.state = SMEMNEXTROW_ENTER;
    input[0].stop = false;
    input[0].next = true;
  }
  if (pIMem) {
    imemState.pMem = pIMem;
    imemState.state = SMEMNEXTROW_ENTER;
    input[1].stop = false;
    input[1].next = true;
  }

  int16_t nilColCount = nCol - 1;  // count of null & none cols
  int     iCol = 0;                // index of first nil col index from left to right
  bool    setICol = false;

  do {
    for (int i = 0; i < 3; ++i) {
      if (input[i].next && !input[i].stop) {
        code = input[i].nextRowFn(input[i].iter, &input[i].pRow);
        if (code) goto _err;

        if (input[i].pRow == NULL) {
          input[i].stop = true;
          input[i].next = false;
        }
      }
    }

    if (input[0].stop && input[1].stop && input[2].stop) {
      break;
    }

    // select maxpoint(s) from mem, imem, fs
    TSDBROW *max[3] = {0};
    int      iMax[3] = {-1, -1, -1};
    int      nMax = 0;
    TSKEY    maxKey = TSKEY_MIN;

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

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

          iMax[nMax] = i;
          max[nMax++] = input[i].pRow;
        }
      }
    }

    // delete detection
    TSDBROW *merge[3] = {0};
    int      iMerge[3] = {-1, -1, -1};
    int      nMerge = 0;
    for (int i = 0; i < nMax; ++i) {
      TSDBKEY maxKey = TSDBROW_KEY(max[i]);

      // bool deleted = false;
      bool deleted = tsdbKeyDeleted(&maxKey, pSkyline, &iSkyline);
      if (!deleted) {
947
        iMerge[nMerge] = iMax[i];
M
Minglei Jin 已提交
948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969
        merge[nMerge++] = max[i];
      }

      input[iMax[i]].next = deleted;
    }

    // merge if nMerge > 1
    if (nMerge > 0) {
      if (nMerge == 1) {
        code = tsRowFromTsdbRow(pTSchema, merge[nMerge - 1], ppRow);
        if (code) goto _err;
      } else {
        // merge 2 or 3 rows
        SRowMerger merger = {0};

        tRowMergerInit(&merger, merge[0], pTSchema);
        for (int i = 1; i < nMerge; ++i) {
          tRowMerge(&merger, merge[i]);
        }
        tRowMergerGetRow(&merger, ppRow);
        tRowMergerClear(&merger);
      }
970 971 972
    } else {
      *ppRow = NULL;
      return code;
M
Minglei Jin 已提交
973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988
    }

    if (iCol == 0) {
      STColumn *pTColumn = &pTSchema->columns[0];
      SColVal  *pColVal = &(SColVal){0};

      *pColVal = COL_VAL_VALUE(pTColumn->colId, pTColumn->type, (SValue){.ts = maxKey});

      if (taosArrayPush(pColArray, pColVal) == NULL) {
        code = TSDB_CODE_OUT_OF_MEMORY;
        goto _err;
      }

      ++iCol;

      setICol = false;
989
      for (int16_t i = iCol; i < nCol; ++i) {
M
Minglei Jin 已提交
990
        // tsdbRowGetColVal(*ppRow, pTSchema, i, pColVal);
991
        tTSRowGetVal(*ppRow, pTSchema, i, pColVal);
M
Minglei Jin 已提交
992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
        if (taosArrayPush(pColArray, pColVal) == NULL) {
          code = TSDB_CODE_OUT_OF_MEMORY;
          goto _err;
        }

        if (pColVal->isNull || pColVal->isNone) {
          for (int j = 0; j < nMerge; ++j) {
            SColVal jColVal = {0};
            tsdbRowGetColVal(merge[j], pTSchema, i, &jColVal);
            if (jColVal.isNull || jColVal.isNone) {
              input[iMerge[j]].next = true;
            }
          }
          if (!setICol) {
            iCol = i;
            setICol = true;
          }
        } else {
          --nilColCount;
        }
      }
1013
      /*
M
Minglei Jin 已提交
1014 1015 1016
      if (*ppRow) {
        taosMemoryFreeClear(*ppRow);
      }
1017
      */
M
Minglei Jin 已提交
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033
      continue;
    }

    setICol = false;
    for (int16_t i = iCol; i < nCol; ++i) {
      SColVal colVal = {0};
      tTSRowGetVal(*ppRow, pTSchema, i, &colVal);

      SColVal *tColVal = (SColVal *)taosArrayGet(pColArray, i);

      if (!colVal.isNone && !colVal.isNull) {
        if (tColVal->isNull || tColVal->isNone) {
          taosArraySet(pColArray, i, &colVal);
          --nilColCount;
        }
      } else {
1034
        if ((tColVal->isNull || tColVal->isNone) && !setICol) {
M
Minglei Jin 已提交
1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
          iCol = i;
          setICol = true;

          for (int j = 0; j < nMerge; ++j) {
            SColVal jColVal = {0};
            tsdbRowGetColVal(merge[j], pTSchema, i, &jColVal);
            if (jColVal.isNull || jColVal.isNone) {
              input[iMerge[j]].next = true;
            }
          }
        }
      }
    }
M
Minglei Jin 已提交
1048 1049 1050 1051

    if (*ppRow) {
      taosMemoryFreeClear(*ppRow);
    }
M
Minglei Jin 已提交
1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069
  } while (nilColCount > 0);

  // if () new ts row from pColArray if non empty
  if (taosArrayGetSize(pColArray) == nCol) {
    code = tdSTSRowNew(pColArray, pTSchema, ppRow);
    if (code) goto _err;
  }
  taosArrayDestroy(pColArray);
  taosMemoryFreeClear(pTSchema);

  return code;
_err:
  taosArrayDestroy(pColArray);
  taosMemoryFreeClear(pTSchema);
  tsdbError("vgId:%d merge last_row failed since %s", TD_VID(pTsdb->pVnode), tstrerror(code));
  return code;
}

1070 1071 1072 1073 1074
int32_t tsdbCacheGetLastrowH(SLRUCache *pCache, tb_uid_t uid, STsdb *pTsdb, LRUHandle **handle) {
  int32_t code = 0;
  char    key[32] = {0};
  int     keyLen = 0;

1075 1076
  //  getTableCacheKey(uid, "lr", key, &keyLen);
  getTableCacheKey(uid, 0, key, &keyLen);
1077 1078 1079 1080 1081
  LRUHandle *h = taosLRUCacheLookup(pCache, key, keyLen);
  if (h) {
    //*ppRow = (STSRow *)taosLRUCacheValue(pCache, h);
  } else {
    STSRow *pRow = NULL;
1082 1083
    bool    dup = false;
    code = mergeLastRow(uid, pTsdb, &dup, &pRow);
1084 1085
    // if table's empty or error, return code of -1
    if (code < 0 || pRow == NULL) {
1086
      if (!dup && pRow) {
1087 1088 1089
        taosMemoryFree(pRow);
      }

1090 1091
      *handle = NULL;
      return 0;
1092 1093
    }

1094
    tsdbCacheInsertLastrow(pCache, pTsdb, uid, pRow, dup);
1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108
    h = taosLRUCacheLookup(pCache, key, keyLen);
    //*ppRow = (STSRow *)taosLRUCacheValue(pCache, h);
  }

  *handle = h;

  return code;
}

int32_t tsdbCacheGetLastH(SLRUCache *pCache, tb_uid_t uid, STsdb *pTsdb, LRUHandle **handle) {
  int32_t code = 0;
  char    key[32] = {0};
  int     keyLen = 0;

1109 1110
  // getTableCacheKey(uid, "l", key, &keyLen);
  getTableCacheKey(uid, 1, key, &keyLen);
1111 1112 1113 1114 1115 1116 1117 1118 1119
  LRUHandle *h = taosLRUCacheLookup(pCache, key, keyLen);
  if (h) {
    //*ppRow = (STSRow *)taosLRUCacheValue(pCache, h);

  } else {
    STSRow *pRow = NULL;
    code = mergeLast(uid, pTsdb, &pRow);
    // if table's empty or error, return code of -1
    if (code < 0 || pRow == NULL) {
1120 1121
      *handle = NULL;
      return 0;
1122 1123
    }

1124 1125 1126 1127 1128 1129 1130
    _taos_lru_deleter_t deleter = deleteTableCacheLastrow;
    LRUStatus           status =
        taosLRUCacheInsert(pCache, key, keyLen, pRow, TD_ROW_LEN(pRow), deleter, NULL, TAOS_LRU_PRIORITY_LOW);
    if (status != TAOS_LRU_STATUS_OK) {
      code = -1;
    }
    /* tsdbCacheInsertLast(pCache, uid, pRow); */
1131 1132 1133 1134 1135
    h = taosLRUCacheLookup(pCache, key, keyLen);
    //*ppRow = (STSRow *)taosLRUCacheValue(pCache, h);
  }

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

1137 1138 1139
  return code;
}

1140
int32_t tsdbCacheDelete(SLRUCache *pCache, tb_uid_t uid, TSKEY eKey) {
1141
  int32_t code = 0;
H
Hongze Cheng 已提交
1142 1143
  char    key[32] = {0};
  int     keyLen = 0;
1144

1145 1146
  // getTableCacheKey(uid, "lr", key, &keyLen);
  getTableCacheKey(uid, 0, key, &keyLen);
1147 1148
  LRUHandle *h = taosLRUCacheLookup(pCache, key, keyLen);
  if (h) {
M
Minglei Jin 已提交
1149 1150 1151 1152 1153 1154 1155 1156 1157 1158
    STSRow *pRow = (STSRow *)taosLRUCacheValue(pCache, h);
    if (pRow->ts <= eKey) {
      taosLRUCacheRelease(pCache, h, true);
    } else {
      taosLRUCacheRelease(pCache, h, false);
    }

    // void taosLRUCacheErase(SLRUCache * cache, const void *key, size_t keyLen);
  }

1159 1160
  // getTableCacheKey(uid, "l", key, &keyLen);
  getTableCacheKey(uid, 1, key, &keyLen);
M
Minglei Jin 已提交
1161 1162 1163
  h = taosLRUCacheLookup(pCache, key, keyLen);
  if (h) {
    // clear last cache anyway, no matter where eKey ends.
1164
    taosLRUCacheRelease(pCache, h, true);
M
Minglei Jin 已提交
1165 1166

    // void taosLRUCacheErase(SLRUCache * cache, const void *key, size_t keyLen);
1167 1168 1169 1170
  }

  return code;
}
M
Minglei Jin 已提交
1171 1172 1173 1174 1175 1176 1177 1178

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

  taosLRUCacheRelease(pCache, h, false);

  return code;
}