tsdbCache.c 43.6 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
  size_t     cfgCapacity = pTsdb->pVnode->config.cacheLastSize * 1024 * 1024;
22 23 24 25 26 27 28

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

29
  taosLRUCacheSetStrictCapacity(pCache, false);
30

31 32
  taosThreadMutexInit(&pTsdb->lruMutex, NULL);

33 34 35 36 37
_err:
  pTsdb->lruCache = pCache;
  return code;
}

38 39
void tsdbCloseCache(STsdb *pTsdb) {
  SLRUCache *pCache = pTsdb->lruCache;
40 41 42 43
  if (pCache) {
    taosLRUCacheEraseUnrefEntries(pCache);

    taosLRUCacheCleanup(pCache);
44 45

    taosThreadMutexDestroy(&pTsdb->lruMutex);
46 47 48
  }
}

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

59 60 61 62 63
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);
64
    if (IS_VAR_DATA_TYPE(pLastCol->colVal.type) && pLastCol->colVal.value.nData > 0) {
65 66 67 68 69 70
      taosMemoryFree(pLastCol->colVal.value.pData);
    }
  }

  taosArrayDestroy(value);
}
71

72
int32_t tsdbCacheDeleteLastrow(SLRUCache *pCache, tb_uid_t uid, TSKEY eKey) {
73
  int32_t code = 0;
74 75 76

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

78 79
  // getTableCacheKey(uid, "lr", key, &keyLen);
  getTableCacheKey(uid, 0, key, &keyLen);
80 81
  LRUHandle *h = taosLRUCacheLookup(pCache, key, keyLen);
  if (h) {
82 83 84 85 86 87 88 89 90 91 92 93 94
    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) {
95 96 97 98 99 100 101 102 103 104
      taosLRUCacheRelease(pCache, h, true);
    } else {
      taosLRUCacheRelease(pCache, h, false);
    }
    // void taosLRUCacheErase(SLRUCache * cache, const void *key, size_t keyLen);
  }

  return code;
}

105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
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;
      }
    }

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

  return code;
}

int32_t tsdbCacheDelete(SLRUCache *pCache, tb_uid_t uid, TSKEY eKey) {
139 140 141 142
  int32_t code = 0;
  char    key[32] = {0};
  int     keyLen = 0;

143 144 145 146
  // getTableCacheKey(uid, "lr", key, &keyLen);
  getTableCacheKey(uid, 0, key, &keyLen);
  LRUHandle *h = taosLRUCacheLookup(pCache, key, keyLen);
  if (h) {
147 148 149 150 151 152 153 154 155 156 157 158 159
    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) {
160 161 162 163 164 165
      taosLRUCacheRelease(pCache, h, true);
    } else {
      taosLRUCacheRelease(pCache, h, false);
    }
  }

166 167
  // getTableCacheKey(uid, "l", key, &keyLen);
  getTableCacheKey(uid, 1, key, &keyLen);
168
  h = taosLRUCacheLookup(pCache, key, keyLen);
169
  if (h) {
170 171 172
    SArray *pLast = (SArray *)taosLRUCacheValue(pCache, h);
    bool    invalidate = false;
    int16_t nCol = taosArrayGetSize(pLast);
173

174 175 176 177 178 179 180 181 182 183 184 185 186
    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);
    }
187 188 189 190 191 192
    // void taosLRUCacheErase(SLRUCache * cache, const void *key, size_t keyLen);
  }

  return code;
}

H
Hongze Cheng 已提交
193
int32_t tsdbCacheInsertLastrow(SLRUCache *pCache, STsdb *pTsdb, tb_uid_t uid, TSDBROW *row, bool dup) {
194 195
  int32_t code = 0;
  STSRow *cacheRow = NULL;
H
Hongze Cheng 已提交
196 197
  char    key[32] = {0};
  int     keyLen = 0;
198

199 200
  // getTableCacheKey(uid, "lr", key, &keyLen);
  getTableCacheKey(uid, 0, key, &keyLen);
201 202
  LRUHandle *h = taosLRUCacheLookup(pCache, key, keyLen);
  if (h) {
203
    STSchema *pTSchema = metaGetTbTSchema(pTsdb->pVnode->pMeta, uid, -1, 1);
H
Hongze Cheng 已提交
204
    TSKEY     keyTs = TSDBROW_TS(row);
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
    bool      invalidate = false;

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

    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 已提交
225
        tsdbRowGetColVal(row, pTSchema, iCol, &colVal);
226 227 228 229 230 231 232
        if (!COL_VAL_IS_NONE(&colVal)) {
          if (keyTs == tTsVal1->ts && !COL_VAL_IS_NONE(tColVal)) {
            invalidate = true;

            break;
          }
        } else {
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
          SLastCol lastCol = {.ts = keyTs, .colVal = colVal};
          if (IS_VAR_DATA_TYPE(colVal.type) && colVal.value.nData > 0) {
            SLastCol *pLastCol = (SLastCol *)taosArrayGet(pLast, iCol);
            taosMemoryFree(pLastCol->colVal.value.pData);

            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);
          }

          taosArraySet(pLast, iCol, &lastCol);
248 249 250 251 252 253 254 255 256
        }
      }
    }

  _invalidate:
    taosMemoryFreeClear(pTSchema);

    taosLRUCacheRelease(pCache, h, invalidate);
    /*
H
Hongze Cheng 已提交
257
    cacheRow = (STSRow *)taosLRUCacheValue(pCache, h);
258
    if (row->ts >= cacheRow->ts) {
259
      if (row->ts == cacheRow->ts) {
M
Minglei Jin 已提交
260
        STSRow    *mergedRow = NULL;
261
        SRowMerger merger = {0};
262
        STSchema  *pTSchema = metaGetTbTSchema(pTsdb->pVnode->pMeta, uid, -1, 1);
263

H
Hongze Cheng 已提交
264
        tsdbRowMergerInit(&merger, &tsdbRowFromTSRow(0, cacheRow), pTSchema);
265

H
Hongze Cheng 已提交
266
        tsdbRowMerge(&merger, &tsdbRowFromTSRow(1, row));
267

H
Hongze Cheng 已提交
268 269
        tsdbRowMergerGetRow(&merger, &mergedRow);
        tsdbRowMergerClear(&merger);
270 271 272 273 274 275 276

        taosMemoryFreeClear(pTSchema);

        row = mergedRow;
        dup = false;
      }

277
      if (TD_ROW_LEN(row) <= TD_ROW_LEN(cacheRow)) {
H
Hongze Cheng 已提交
278
        tdRowCpy(cacheRow, row);
279 280 281
        if (!dup) {
          taosMemoryFree(row);
        }
282 283

        taosLRUCacheRelease(pCache, h, false);
284
      } else {
285 286
        taosLRUCacheRelease(pCache, h, true);
        // tsdbCacheDeleteLastrow(pCache, uid, TSKEY_MAX);
M
Minglei Jin 已提交
287 288 289 290 291
        if (dup) {
          cacheRow = tdRowDup(row);
        } else {
          cacheRow = row;
        }
292 293 294 295 296 297
        _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;
        }
298
        // tsdbCacheInsertLastrow(pCache, uid, row, dup);
299
      }
300
    }*/
301
  } /*else {
302 303 304 305 306
    if (dup) {
      cacheRow = tdRowDup(row);
    } else {
      cacheRow = row;
    }
307 308

    _taos_lru_deleter_t deleter = deleteTableCacheLastrow;
H
Hongze Cheng 已提交
309 310
    LRUStatus           status =
        taosLRUCacheInsert(pCache, key, keyLen, cacheRow, TD_ROW_LEN(cacheRow), deleter, NULL, TAOS_LRU_PRIORITY_LOW);
311 312 313
    if (status != TAOS_LRU_STATUS_OK) {
      code = -1;
    }
314
    }*/
315 316 317 318

  return code;
}

H
Hongze Cheng 已提交
319
int32_t tsdbCacheInsertLast(SLRUCache *pCache, tb_uid_t uid, TSDBROW *row, STsdb *pTsdb) {
320 321 322 323 324
  int32_t code = 0;
  STSRow *cacheRow = NULL;
  char    key[32] = {0};
  int     keyLen = 0;

325 326
  // getTableCacheKey(uid, "l", key, &keyLen);
  getTableCacheKey(uid, 1, key, &keyLen);
327 328
  LRUHandle *h = taosLRUCacheLookup(pCache, key, keyLen);
  if (h) {
329
    STSchema *pTSchema = metaGetTbTSchema(pTsdb->pVnode->pMeta, uid, -1, 1);
H
Hongze Cheng 已提交
330
    TSKEY     keyTs = TSDBROW_TS(row);
331 332 333 334 335 336 337 338 339
    bool      invalidate = false;

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

    SLastCol *tTsVal = (SLastCol *)taosArrayGet(pLast, iCol);
    if (keyTs > tTsVal->ts) {
      STColumn *pTColumn = &pTSchema->columns[0];
H
Hongze Cheng 已提交
340
      SColVal   tColVal = COL_VAL_VALUE(pTColumn->colId, pTColumn->type, (SValue){.val = keyTs});
341 342 343 344 345

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

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

        SColVal colVal = {0};
H
Hongze Cheng 已提交
351
        tsdbRowGetColVal(row, pTSchema, iCol, &colVal);
H
Hongze Cheng 已提交
352 353
        if (!COL_VAL_IS_VALUE(&colVal)) {
          if (keyTs == tTsVal1->ts && COL_VAL_IS_VALUE(tColVal)) {
354 355 356 357 358
            invalidate = true;

            break;
          }
        } else {
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
          SLastCol lastCol = {.ts = keyTs, .colVal = colVal};
          if (IS_VAR_DATA_TYPE(colVal.type) && colVal.value.nData > 0) {
            SLastCol *pLastCol = (SLastCol *)taosArrayGet(pLast, iCol);
            taosMemoryFree(pLastCol->colVal.value.pData);

            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);
          }

          taosArraySet(pLast, iCol, &lastCol);
374 375 376 377
        }
      }
    }

378
  _invalidate:
379 380 381 382
    taosMemoryFreeClear(pTSchema);

    taosLRUCacheRelease(pCache, h, invalidate);

383
    // clear last cache anyway, lazy load when get last lookup
384
    // taosLRUCacheRelease(pCache, h, true);
385 386 387 388 389
  }

  return code;
}

390 391 392 393 394
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 已提交
395
  if (metaGetTableEntryByUidCache(&mr, uid) < 0) {
H
Hongze Cheng 已提交
396
    metaReaderClear(&mr);  // table not esist
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416
    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 已提交
417
    code = tsdbReadDelData(pDelReader, pDelIdx, aDelData);
418 419 420 421 422 423
  }

  return code;
}

static int32_t getTableDelDataFromTbData(STbData *pTbData, SArray *aDelData) {
H
Hongze Cheng 已提交
424
  int32_t   code = 0;
425 426 427 428 429 430 431 432 433
  SDelData *pDelData = pTbData ? pTbData->pHead : NULL;

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

  return code;
}

H
Hongze Cheng 已提交
434 435
static int32_t getTableDelData(STbData *pMem, STbData *pIMem, SDelFReader *pDelReader, SDelIdx *pDelIdx,
                               SArray *aDelData) {
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456
  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 已提交
457 458
static int32_t getTableDelSkyline(STbData *pMem, STbData *pIMem, SDelFReader *pDelReader, SDelIdx *pDelIdx,
                                  SArray *aSkyline) {
459
  int32_t code = 0;
M
Minglei Jin 已提交
460
  SArray *aDelData = NULL;
461

M
Minglei Jin 已提交
462
  aDelData = taosArrayInit(32, sizeof(SDelData));
463 464 465 466
  code = getTableDelData(pMem, pIMem, pDelReader, pDelIdx, aDelData);
  if (code) goto _err;

  size_t nDelData = taosArrayGetSize(aDelData);
467 468 469 470
  if (nDelData > 0) {
    code = tsdbBuildDeleteSkyline(aDelData, 0, (int32_t)(nDelData - 1), aSkyline);
    if (code) goto _err;
  }
471

472
_err:
M
Minglei Jin 已提交
473 474 475
  if (aDelData) {
    taosArrayDestroy(aDelData);
  }
476 477
  return code;
}
S
stephenkgu 已提交
478
/*
479 480
static int32_t getTableDelIdx(SDelFReader *pDelFReader, tb_uid_t suid, tb_uid_t uid, SDelIdx *pDelIdx) {
  int32_t code = 0;
M
Minglei Jin 已提交
481
  SArray *pDelIdxArray = NULL;
482

483
  // SMapData delIdxMap;
M
Minglei Jin 已提交
484
  pDelIdxArray = taosArrayInit(32, sizeof(SDelIdx));
485
  SDelIdx idx = {.suid = suid, .uid = uid};
486

487
  // tMapDataReset(&delIdxMap);
H
Hongze Cheng 已提交
488
  code = tsdbReadDelIdx(pDelFReader, pDelIdxArray);
489 490
  if (code) goto _err;

491
  // code = tMapDataSearch(&delIdxMap, &idx, tGetDelIdx, tCmprDelIdx, pDelIdx);
492
  SDelIdx *pIdx = taosArraySearch(pDelIdxArray, &idx, tCmprDelIdx, TD_EQ);
493

494 495
  *pDelIdx = *pIdx;

496
_err:
M
Minglei Jin 已提交
497 498 499
  if (pDelIdxArray) {
    taosArrayDestroy(pDelIdxArray);
  }
500 501
  return code;
}
S
stephenkgu 已提交
502
*/
503 504 505 506 507 508 509 510
typedef enum {
  SFSLASTNEXTROW_FS,
  SFSLASTNEXTROW_FILESET,
  SFSLASTNEXTROW_BLOCKDATA,
  SFSLASTNEXTROW_BLOCKROW
} SFSLASTNEXTROWSTATES;

typedef struct {
511 512 513
  SFSLASTNEXTROWSTATES state;     // [input]
  STsdb               *pTsdb;     // [input]
  STSchema            *pTSchema;  // [input]
514
  tb_uid_t             suid;
515
  tb_uid_t             uid;
516 517 518
  int32_t              nFileSet;
  int32_t              iFileSet;
  SArray              *aDFileSet;
519
  SDataFReader       **pDataFReader;
520
  TSDBROW              row;
521

522 523 524
  SMergeTree         mergeTree;
  SMergeTree        *pMergeTree;
  SSttBlockLoadInfo *pLoadInfo;
525 526 527 528 529 530 531 532 533 534 535 536 537 538
} SFSLastNextRowIter;

static int32_t getNextRowFromFSLast(void *iter, TSDBROW **ppRow) {
  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:
539 540 541 542 543
      if (state->pMergeTree != NULL) {
        tMergeTreeClose(state->pMergeTree);
        state->pMergeTree = NULL;
      }

544 545 546 547 548 549 550
      if (--state->iFileSet >= 0) {
        pFileSet = (SDFileSet *)taosArrayGet(state->aDFileSet, state->iFileSet);
      } else {
        *ppRow = NULL;
        return code;
      }

551 552 553
      if (*state->pDataFReader == NULL || (*state->pDataFReader)->pSet->fid != pFileSet->fid) {
        if (*state->pDataFReader != NULL) {
          tsdbDataFReaderClose(state->pDataFReader);
M
Minglei Jin 已提交
554

555 556
          resetLastBlockLoadInfo(state->pLoadInfo);
        }
557

558 559 560 561 562
        code = tsdbDataFReaderOpen(state->pDataFReader, state->pTsdb, pFileSet);
        if (code) goto _err;
      }

      tMergeTreeOpen(&state->mergeTree, 1, *state->pDataFReader, state->suid, state->uid,
563
                     &(STimeWindow){.skey = TSKEY_MIN, .ekey = TSKEY_MAX},
564
                     &(SVersionRange){.minVer = 0, .maxVer = UINT64_MAX}, state->pLoadInfo, false, NULL);
565
      state->pMergeTree = &state->mergeTree;
566 567 568
      bool hasVal = tMergeTreeNext(&state->mergeTree);
      if (!hasVal) {
        state->state = SFSLASTNEXTROW_FILESET;
569 570 571
        goto _next_fileset;
      }
      state->state = SFSLASTNEXTROW_BLOCKROW;
572
    }
573
    case SFSLASTNEXTROW_BLOCKROW:
574 575 576 577 578
      state->row = tMergeTreeGetRow(&state->mergeTree);
      *ppRow = &state->row;
      bool hasVal = tMergeTreeNext(&state->mergeTree);
      if (!hasVal) {
        state->state = SFSLASTNEXTROW_FILESET;
579
      }
580

581 582 583 584 585 586 587
      return code;
    default:
      ASSERT(0);
      break;
  }

_err:
588
  /*if (state->pDataFReader) {
589 590
    tsdbDataFReaderClose(&state->pDataFReader);
    state->pDataFReader = NULL;
591
    }*/
592 593 594 595 596
  if (state->pMergeTree != NULL) {
    tMergeTreeClose(state->pMergeTree);
    state->pMergeTree = NULL;
  }

597 598 599 600 601 602 603 604 605 606 607 608
  *ppRow = NULL;

  return code;
}

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

  if (!state) {
    return code;
  }
609
  /*
610 611 612 613
  if (state->pDataFReader) {
    tsdbDataFReaderClose(&state->pDataFReader);
    state->pDataFReader = NULL;
  }
614
  */
615 616 617 618 619
  if (state->pMergeTree != NULL) {
    tMergeTreeClose(state->pMergeTree);
    state->pMergeTree = NULL;
  }

620 621 622
  return code;
}

623 624 625 626 627 628 629 630
typedef enum SFSNEXTROWSTATES {
  SFSNEXTROW_FS,
  SFSNEXTROW_FILESET,
  SFSNEXTROW_BLOCKDATA,
  SFSNEXTROW_BLOCKROW
} SFSNEXTROWSTATES;

typedef struct SFSNextRowIter {
631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652
  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;
  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;
653 654 655 656 657 658 659 660
} SFSNextRowIter;

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

  switch (state->state) {
    case SFSNEXTROW_FS:
H
Hongze Cheng 已提交
661
      // state->aDFileSet = state->pTsdb->pFS->cState->aDFileSet;
662
      state->nFileSet = taosArrayGetSize(state->aDFileSet);
M
Minglei Jin 已提交
663
      state->iFileSet = state->nFileSet;
664 665

      state->pBlockData = NULL;
666 667 668

    case SFSNEXTROW_FILESET: {
      SDFileSet *pFileSet = NULL;
669
    _next_fileset:
670 671 672
      if (--state->iFileSet >= 0) {
        pFileSet = (SDFileSet *)taosArrayGet(state->aDFileSet, state->iFileSet);
      } else {
H
Hongze Cheng 已提交
673
        // tBlockDataDestroy(&state->blockData, 1);
674
        if (state->pBlockData) {
H
Hongze Cheng 已提交
675
          tBlockDataDestroy(state->pBlockData);
676 677
          state->pBlockData = NULL;
        }
678

679 680 681 682
        *ppRow = NULL;
        return code;
      }

683 684 685 686
      if (*state->pDataFReader == NULL || (*state->pDataFReader)->pSet->fid != pFileSet->fid) {
        if (*state->pDataFReader != NULL) {
          tsdbDataFReaderClose(state->pDataFReader);

687
          // resetLastBlockLoadInfo(state->pLoadInfo);
688 689 690 691 692
        }

        code = tsdbDataFReaderOpen(state->pDataFReader, state->pTsdb, pFileSet);
        if (code) goto _err;
      }
693 694 695 696 697 698 699

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

703 704
      /* if (state->pBlockIdx) { */
      /* } */
705 706
      /* code = tMapDataSearch(&state->blockIdxMap, state->pBlockIdxExp, tGetBlockIdx, tCmprBlockIdx,
       * &state->blockIdx);
707 708
       */
      state->pBlockIdx = taosArraySearch(state->aBlockIdx, state->pBlockIdxExp, tCmprBlockIdx, TD_EQ);
709 710 711 712
      if (!state->pBlockIdx) { /*
         tsdbDataFReaderClose(state->pDataFReader);
         *state->pDataFReader = NULL;
         resetLastBlockLoadInfo(state->pLoadInfo);*/
713 714 715
        goto _next_fileset;
      }

716 717
      tMapDataReset(&state->blockMap);
      /*
718 719 720
      if (state->blockMap.pData != NULL) {
        tMapDataClear(&state->blockMap);
      }
721 722
      */
      code = tsdbReadDataBlk(*state->pDataFReader, state->pBlockIdx, &state->blockMap);
723 724 725 726
      if (code) goto _err;

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

728 729 730
      if (!state->pBlockData) {
        state->pBlockData = &state->blockData;

H
Hongze Cheng 已提交
731
        tBlockDataCreate(&state->blockData);
732
      }
733 734 735
    }
    case SFSNEXTROW_BLOCKDATA:
      if (state->iBlock >= 0) {
H
Hongze Cheng 已提交
736
        SDataBlk block = {0};
737

H
Hongze Cheng 已提交
738
        tDataBlkReset(&block);
739 740
        // tBlockDataReset(&state->blockData);
        tBlockDataReset(state->pBlockData);
741

H
Hongze Cheng 已提交
742
        tMapDataGetItemByIdx(&state->blockMap, state->iBlock, &block, tGetDataBlk);
743
        /* code = tsdbReadBlockData(state->pDataFReader, &state->blockIdx, &block, &state->blockData, NULL, NULL); */
744
        tBlockDataReset(state->pBlockData);
H
Hongze Cheng 已提交
745 746
        TABLEID tid = {.suid = state->suid, .uid = state->uid};
        code = tBlockDataInit(state->pBlockData, &tid, state->pTSchema, NULL, 0);
747 748
        if (code) goto _err;

749
        code = tsdbReadDataBlock(*state->pDataFReader, &block, state->pBlockData);
750 751 752 753 754 755 756 757 758
        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) {
759
        state->row = tsdbRowFromBlockData(state->pBlockData, state->iRow);
760 761 762 763 764
        *ppRow = &state->row;

        if (--state->iRow < 0) {
          state->state = SFSNEXTROW_BLOCKDATA;
          if (--state->iBlock < 0) {
765 766
            tsdbDataFReaderClose(state->pDataFReader);
            *state->pDataFReader = NULL;
767
            // resetLastBlockLoadInfo(state->pLoadInfo);
768

769 770
            if (state->aBlockIdx) {
              taosArrayDestroy(state->aBlockIdx);
771
              state->aBlockIdx = NULL;
772
            }
773

774 775 776 777 778 779 780 781 782 783 784 785
            state->state = SFSNEXTROW_FILESET;
          }
        }
      }

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

_err:
786 787 788 789 790 791
  /*
  if (*state->pDataFReader) {
    tsdbDataFReaderClose(state->pDataFReader);
    *state->pDataFReader = NULL;
    resetLastBlockLoadInfo(state->pLoadInfo);
    }*/
792 793
  if (state->aBlockIdx) {
    taosArrayDestroy(state->aBlockIdx);
794 795 796
    state->aBlockIdx = NULL;
  }
  if (state->pBlockData) {
H
Hongze Cheng 已提交
797
    tBlockDataDestroy(state->pBlockData);
798
    state->pBlockData = NULL;
799 800
  }

801
  *ppRow = NULL;
802

803 804 805
  return code;
}

806 807 808 809 810 811 812
int32_t clearNextRowFromFS(void *iter) {
  int32_t code = 0;

  SFSNextRowIter *state = (SFSNextRowIter *)iter;
  if (!state) {
    return code;
  }
813
  /*
814 815 816
  if (state->pDataFReader) {
    tsdbDataFReaderClose(&state->pDataFReader);
    state->pDataFReader = NULL;
817
    }*/
818 819 820 821 822
  if (state->aBlockIdx) {
    taosArrayDestroy(state->aBlockIdx);
    state->aBlockIdx = NULL;
  }
  if (state->pBlockData) {
H
Hongze Cheng 已提交
823
    // tBlockDataDestroy(&state->blockData, 1);
H
Hongze Cheng 已提交
824
    tBlockDataDestroy(state->pBlockData);
825 826 827
    state->pBlockData = NULL;
  }

828 829 830 831
  if (state->blockMap.pData != NULL) {
    tMapDataClear(&state->blockMap);
  }

832 833 834
  return code;
}

835 836 837 838 839 840 841 842 843
typedef enum SMEMNEXTROWSTATES {
  SMEMNEXTROW_ENTER,
  SMEMNEXTROW_NEXT,
} SMEMNEXTROWSTATES;

typedef struct SMemNextRowIter {
  SMEMNEXTROWSTATES state;
  STbData          *pMem;  // [input]
  STbDataIter       iter;  // mem buffer skip list iterator
844 845
  // bool              iterOpened;
  // TSDBROW          *curRow;
846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 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
} 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;
}

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
/* 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; */
/* } */
927

928
static bool tsdbKeyDeleted(TSDBKEY *key, SArray *pSkyline, int64_t *iSkyline) {
929 930 931 932 933 934 935 936
  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) {
937
      if (key->version <= pItemFront->version || (key->ts == pItemBack->ts && key->version <= pItemBack->version)) {
938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953
        return true;
      } else {
        return false;
      }
    } else {
      if (*iSkyline > 1) {
        --*iSkyline;
      } else {
        return false;
      }
    }
  }

  return deleted;
}

954
typedef int32_t (*_next_row_fn_t)(void *iter, TSDBROW **ppRow);
955
typedef int32_t (*_next_row_clear_fn_t)(void *iter);
956

957
typedef struct {
958 959 960 961 962 963
  TSDBROW             *pRow;
  bool                 stop;
  bool                 next;
  void                *iter;
  _next_row_fn_t       nextRowFn;
  _next_row_clear_fn_t nextRowClearFn;
964
} TsdbNextRowState;
965

966 967 968 969
typedef struct {
  SArray *pSkyline;
  int64_t iSkyline;

970 971 972 973 974 975
  SBlockIdx          idx;
  SMemNextRowIter    memState;
  SMemNextRowIter    imemState;
  SFSLastNextRowIter fsLastState;
  SFSNextRowIter     fsState;
  TSDBROW            memRow, imemRow, fsLastRow, fsRow;
976

977
  TsdbNextRowState input[4];
978
  STsdb           *pTsdb;
979 980
} CacheNextRowIter;

981
static int32_t nextRowIterOpen(CacheNextRowIter *pIter, tb_uid_t uid, STsdb *pTsdb, STSchema *pTSchema, tb_uid_t suid,
982 983
                               SSttBlockLoadInfo *pLoadInfo, STsdbReadSnap *pReadSnap, SDataFReader **pDataFReader,
                               SDataFReader **pDataFReaderLast) {
984 985 986
  int code = 0;

  STbData *pMem = NULL;
987 988
  if (pReadSnap->pMem) {
    pMem = tsdbGetTbDataFromMemTable(pReadSnap->pMem, suid, uid);
989 990 991
  }

  STbData *pIMem = NULL;
992 993
  if (pReadSnap->pIMem) {
    pIMem = tsdbGetTbDataFromMemTable(pReadSnap->pIMem, suid, uid);
994 995
  }

H
Hongze Cheng 已提交
996 997
  pIter->pTsdb = pTsdb;

998 999
  pIter->pSkyline = taosArrayInit(32, sizeof(TSDBKEY));

1000
  SDelFile *pDelFile = pReadSnap->fs.pDelFile;
1001 1002 1003
  if (pDelFile) {
    SDelFReader *pDelFReader;

H
Hongze Cheng 已提交
1004
    code = tsdbDelFReaderOpen(&pDelFReader, pDelFile, pTsdb);
1005 1006
    if (code) goto _err;

S
stephenkgu 已提交
1007 1008 1009 1010 1011 1012
    SArray *pDelIdxArray = taosArrayInit(32, sizeof(SDelIdx));

    code = tsdbReadDelIdx(pDelFReader, pDelIdxArray);
    if (code) goto _err;

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

S
stephenkgu 已提交
1014
    code = getTableDelSkyline(pMem, pIMem, pDelFReader, delIdx, pIter->pSkyline);
1015 1016 1017 1018
    if (code) {
      tsdbDelFReaderClose(&pDelFReader);
      goto _err;
    }
1019

S
stephenkgu 已提交
1020
    taosArrayDestroy(pDelIdxArray);
1021 1022 1023 1024 1025 1026 1027 1028 1029 1030
    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};

1031
  pIter->fsLastState.state = (SFSLASTNEXTROWSTATES)SFSNEXTROW_FS;
1032
  pIter->fsLastState.pTsdb = pTsdb;
1033
  pIter->fsLastState.aDFileSet = pReadSnap->fs.aDFileSet;
1034
  pIter->fsLastState.pTSchema = pTSchema;
1035
  pIter->fsLastState.suid = suid;
1036
  pIter->fsLastState.uid = uid;
1037
  pIter->fsLastState.pLoadInfo = pLoadInfo;
1038
  pIter->fsLastState.pDataFReader = pDataFReaderLast;
1039

1040 1041
  pIter->fsState.state = SFSNEXTROW_FS;
  pIter->fsState.pTsdb = pTsdb;
1042
  pIter->fsState.aDFileSet = pReadSnap->fs.aDFileSet;
1043
  pIter->fsState.pBlockIdxExp = &pIter->idx;
1044 1045 1046
  pIter->fsState.pTSchema = pTSchema;
  pIter->fsState.suid = suid;
  pIter->fsState.uid = uid;
1047 1048
  pIter->fsState.pLoadInfo = pLoadInfo;
  pIter->fsState.pDataFReader = pDataFReader;
1049 1050 1051

  pIter->input[0] = (TsdbNextRowState){&pIter->memRow, true, false, &pIter->memState, getNextRowFromMem, NULL};
  pIter->input[1] = (TsdbNextRowState){&pIter->imemRow, true, false, &pIter->imemState, getNextRowFromMem, NULL};
1052 1053 1054
  pIter->input[2] = (TsdbNextRowState){&pIter->fsLastRow,     false, true, &pIter->fsLastState, getNextRowFromFSLast,
                                       clearNextRowFromFSLast};
  pIter->input[3] =
1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078
      (TsdbNextRowState){&pIter->fsRow, false, true, &pIter->fsState, getNextRowFromFS, clearNextRowFromFS};

  if (pMem) {
    pIter->memState.pMem = pMem;
    pIter->memState.state = SMEMNEXTROW_ENTER;
    pIter->input[0].stop = false;
    pIter->input[0].next = true;
  }

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

  return code;
_err:
  return code;
}

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

1079
  for (int i = 0; i < 4; ++i) {
1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095
    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)
static int32_t nextRowIterGet(CacheNextRowIter *pIter, TSDBROW **ppRow) {
  int code = 0;
1096 1097 1098 1099 1100
  for (;;) {
    for (int i = 0; i < 4; ++i) {
      if (pIter->input[i].next && !pIter->input[i].stop) {
        code = pIter->input[i].nextRowFn(pIter->input[i].iter, &pIter->input[i].pRow);
        if (code) goto _err;
1101

1102 1103 1104 1105
        if (pIter->input[i].pRow == NULL) {
          pIter->input[i].stop = true;
          pIter->input[i].next = false;
        }
1106 1107 1108
      }
    }

1109 1110 1111 1112
    if (pIter->input[0].stop && pIter->input[1].stop && pIter->input[2].stop && pIter->input[3].stop) {
      *ppRow = NULL;
      return code;
    }
1113

1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129
    // 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;
          }
1130

1131 1132
          iMax[nMax] = i;
          max[nMax++] = pIter->input[i].pRow;
1133 1134 1135 1136
        }
      }
    }

1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148
    // 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];
      }
1149

1150 1151
      pIter->input[iMax[i]].next = deleted;
    }
1152

1153 1154
    if (nMerge > 0) {
      pIter->input[iMerge[0]].next = true;
1155

1156 1157 1158
      *ppRow = merge[0];
      return code;
    }
1159 1160 1161 1162 1163 1164
  }

_err:
  return code;
}

1165
static int32_t mergeLastRow(tb_uid_t uid, STsdb *pTsdb, bool *dup, SArray **ppColArray, SCacheRowsReader *pr) {
1166 1167
  int32_t code = 0;

1168
  STSchema *pTSchema = pr->pSchema;  // metaGetTbTSchema(pTsdb->pVnode->pMeta, uid, -1, 1);
1169 1170 1171 1172
  int16_t   nCol = pTSchema->numOfCols;
  int16_t   iCol = 0;
  int16_t   noneCol = 0;
  bool      setNoneCol = false;
M
Minglei Jin 已提交
1173
  SArray   *pColArray = taosArrayInit(nCol, sizeof(SLastCol));
1174 1175 1176 1177 1178
  SColVal  *pColVal = &(SColVal){0};

  TSKEY lastRowTs = TSKEY_MAX;

  CacheNextRowIter iter = {0};
1179 1180
  nextRowIterOpen(&iter, uid, pTsdb, pTSchema, pr->suid, pr->pLoadInfo, pr->pReadSnap, &pr->pDataFReader,
                  &pr->pDataFReaderLast);
1181 1182 1183 1184 1185 1186 1187 1188 1189

  do {
    TSDBROW *pRow = NULL;
    nextRowIterGet(&iter, &pRow);

    if (!pRow) {
      break;
    }

1190 1191
    TSKEY rowTs = TSDBROW_TS(pRow);

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

H
Hongze Cheng 已提交
1196
      *pColVal = COL_VAL_VALUE(pTColumn->colId, pTColumn->type, (SValue){.val = lastRowTs});
1197
      if (taosArrayPush(pColArray, &(SLastCol){.ts = lastRowTs, .colVal = *pColVal}) == NULL) {
M
Minglei Jin 已提交
1198
        terrno = TSDB_CODE_OUT_OF_MEMORY;
1199 1200 1201 1202 1203 1204 1205
        code = TSDB_CODE_OUT_OF_MEMORY;
        goto _err;
      }

      for (iCol = 1; iCol < nCol; ++iCol) {
        tsdbRowGetColVal(pRow, pTSchema, iCol, pColVal);

M
Minglei Jin 已提交
1206
        SLastCol lastCol = {.ts = lastRowTs, .colVal = *pColVal};
1207
        if (IS_VAR_DATA_TYPE(pColVal->type) && pColVal->value.nData > 0) {
M
Minglei Jin 已提交
1208
          lastCol.colVal.value.pData = taosMemoryMalloc(lastCol.colVal.value.nData);
M
Minglei Jin 已提交
1209 1210 1211 1212 1213
          if (lastCol.colVal.value.pData == NULL) {
            terrno = TSDB_CODE_OUT_OF_MEMORY;
            code = TSDB_CODE_OUT_OF_MEMORY;
            goto _err;
          }
M
Minglei Jin 已提交
1214 1215
          memcpy(lastCol.colVal.value.pData, pColVal->value.pData, pColVal->value.nData);
        }
1216

M
Minglei Jin 已提交
1217
        if (taosArrayPush(pColArray, &lastCol) == NULL) {
1218 1219 1220 1221
          code = TSDB_CODE_OUT_OF_MEMORY;
          goto _err;
        }

H
Hongze Cheng 已提交
1222
        if (COL_VAL_IS_NONE(pColVal) && !setNoneCol) {
1223 1224 1225 1226 1227
          noneCol = iCol;
          setNoneCol = true;
        }
      }
      if (!setNoneCol) {
1228
        // done, goto return pColArray
1229 1230 1231 1232 1233 1234
        break;
      } else {
        continue;
      }
    }

1235 1236
    if ((rowTs < lastRowTs)) {
      // done, goto return pColArray
1237 1238 1239 1240 1241 1242 1243 1244 1245 1246
      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 已提交
1247
      if (COL_VAL_IS_NONE(tColVal) && !COL_VAL_IS_NONE(pColVal)) {
1248
        SLastCol lastCol = {.ts = rowTs, .colVal = *pColVal};
1249
        if (IS_VAR_DATA_TYPE(pColVal->type) && pColVal->value.nData > 0) {
1250 1251 1252 1253
          SLastCol *pLastCol = (SLastCol *)taosArrayGet(pColArray, iCol);
          taosMemoryFree(pLastCol->colVal.value.pData);

          lastCol.colVal.value.pData = taosMemoryMalloc(lastCol.colVal.value.nData);
M
Minglei Jin 已提交
1254 1255 1256 1257 1258
          if (lastCol.colVal.value.pData == NULL) {
            terrno = TSDB_CODE_OUT_OF_MEMORY;
            code = TSDB_CODE_OUT_OF_MEMORY;
            goto _err;
          }
1259 1260 1261 1262
          memcpy(lastCol.colVal.value.pData, pColVal->value.pData, pColVal->value.nData);
        }

        taosArraySet(pColArray, iCol, &lastCol);
H
Hongze Cheng 已提交
1263
      } else if (COL_VAL_IS_NONE(tColVal) && COL_VAL_IS_NONE(pColVal) && !setNoneCol) {
1264 1265 1266 1267 1268 1269 1270 1271
        noneCol = iCol;
        setNoneCol = true;
      }
    }
  } while (setNoneCol);

  // build the result ts row here
  *dup = false;
M
Minglei Jin 已提交
1272
  if (taosArrayGetSize(pColArray) != nCol) {
1273 1274
    *ppColArray = NULL;
    taosArrayDestroy(pColArray);
1275
  } else {
1276
    *ppColArray = pColArray;
1277 1278 1279
  }

  nextRowIterClose(&iter);
1280
  // taosMemoryFreeClear(pTSchema);
1281 1282 1283 1284 1285
  return code;

_err:
  nextRowIterClose(&iter);
  taosArrayDestroy(pColArray);
1286
  // taosMemoryFreeClear(pTSchema);
1287 1288 1289
  return code;
}

1290
static int32_t mergeLast(tb_uid_t uid, STsdb *pTsdb, SArray **ppLastArray, SCacheRowsReader *pr) {
1291 1292
  int32_t code = 0;

1293
  STSchema *pTSchema = pr->pSchema;  // metaGetTbTSchema(pTsdb->pVnode->pMeta, uid, -1, 1);
1294 1295 1296 1297 1298 1299 1300 1301 1302 1303
  int16_t   nCol = pTSchema->numOfCols;
  int16_t   iCol = 0;
  int16_t   noneCol = 0;
  bool      setNoneCol = false;
  SArray   *pColArray = taosArrayInit(nCol, sizeof(SLastCol));
  SColVal  *pColVal = &(SColVal){0};

  TSKEY lastRowTs = TSKEY_MAX;

  CacheNextRowIter iter = {0};
1304 1305
  nextRowIterOpen(&iter, uid, pTsdb, pTSchema, pr->suid, pr->pLoadInfo, pr->pReadSnap, &pr->pDataFReader,
                  &pr->pDataFReaderLast);
1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320

  do {
    TSDBROW *pRow = NULL;
    nextRowIterGet(&iter, &pRow);

    if (!pRow) {
      break;
    }

    TSKEY rowTs = TSDBROW_TS(pRow);

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

H
Hongze Cheng 已提交
1321
      *pColVal = COL_VAL_VALUE(pTColumn->colId, pTColumn->type, (SValue){.val = lastRowTs});
1322 1323 1324 1325 1326 1327 1328 1329
      if (taosArrayPush(pColArray, &(SLastCol){.ts = lastRowTs, .colVal = *pColVal}) == NULL) {
        code = TSDB_CODE_OUT_OF_MEMORY;
        goto _err;
      }

      for (iCol = 1; iCol < nCol; ++iCol) {
        tsdbRowGetColVal(pRow, pTSchema, iCol, pColVal);

1330
        SLastCol lastCol = {.ts = lastRowTs, .colVal = *pColVal};
1331
        if (IS_VAR_DATA_TYPE(pColVal->type) && pColVal->value.nData > 0) {
1332
          lastCol.colVal.value.pData = taosMemoryMalloc(lastCol.colVal.value.nData);
M
Minglei Jin 已提交
1333 1334 1335 1336 1337
          if (lastCol.colVal.value.pData == NULL) {
            terrno = TSDB_CODE_OUT_OF_MEMORY;
            code = TSDB_CODE_OUT_OF_MEMORY;
            goto _err;
          }
1338 1339 1340 1341
          memcpy(lastCol.colVal.value.pData, pColVal->value.pData, pColVal->value.nData);
        }

        if (taosArrayPush(pColArray, &lastCol) == NULL) {
1342 1343 1344 1345
          code = TSDB_CODE_OUT_OF_MEMORY;
          goto _err;
        }

H
Hongze Cheng 已提交
1346
        if (!COL_VAL_IS_VALUE(pColVal) && !setNoneCol) {
1347 1348 1349 1350 1351
          noneCol = iCol;
          setNoneCol = true;
        }
      }
      if (!setNoneCol) {
1352
        // done, goto return pColArray
1353 1354 1355 1356 1357
        break;
      } else {
        continue;
      }
    }
1358

1359 1360 1361 1362
    // merge into pColArray
    setNoneCol = false;
    for (iCol = noneCol; iCol < nCol; ++iCol) {
      // high version's column value
1363 1364
      SLastCol *lastColVal = (SLastCol *)taosArrayGet(pColArray, iCol);
      SColVal  *tColVal = &lastColVal->colVal;
1365 1366

      tsdbRowGetColVal(pRow, pTSchema, iCol, pColVal);
H
Hongze Cheng 已提交
1367
      if (!COL_VAL_IS_VALUE(tColVal) && COL_VAL_IS_VALUE(pColVal)) {
1368
        SLastCol lastCol = {.ts = rowTs, .colVal = *pColVal};
1369
        if (IS_VAR_DATA_TYPE(pColVal->type) && pColVal->value.nData > 0) {
1370 1371 1372 1373
          SLastCol *pLastCol = (SLastCol *)taosArrayGet(pColArray, iCol);
          taosMemoryFree(pLastCol->colVal.value.pData);

          lastCol.colVal.value.pData = taosMemoryMalloc(lastCol.colVal.value.nData);
M
Minglei Jin 已提交
1374 1375 1376 1377 1378
          if (lastCol.colVal.value.pData == NULL) {
            terrno = TSDB_CODE_OUT_OF_MEMORY;
            code = TSDB_CODE_OUT_OF_MEMORY;
            goto _err;
          }
1379 1380 1381 1382
          memcpy(lastCol.colVal.value.pData, pColVal->value.pData, pColVal->value.nData);
        }

        taosArraySet(pColArray, iCol, &lastCol);
H
Hongze Cheng 已提交
1383
      } else if (!COL_VAL_IS_VALUE(tColVal) && !COL_VAL_IS_VALUE(pColVal) && !setNoneCol) {
1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397
        noneCol = iCol;
        setNoneCol = true;
      }
    }
  } while (setNoneCol);

  if (taosArrayGetSize(pColArray) <= 0) {
    *ppLastArray = NULL;
    taosArrayDestroy(pColArray);
  } else {
    *ppLastArray = pColArray;
  }

  nextRowIterClose(&iter);
1398
  // taosMemoryFreeClear(pTSchema);
1399 1400 1401 1402
  return code;

_err:
  nextRowIterClose(&iter);
1403
  // taosMemoryFreeClear(pTSchema);
1404 1405
  *ppLastArray = NULL;
  taosArrayDestroy(pColArray);
1406 1407 1408
  return code;
}

1409
int32_t tsdbCacheGetLastrowH(SLRUCache *pCache, tb_uid_t uid, SCacheRowsReader *pr, LRUHandle **handle) {
1410 1411 1412 1413
  int32_t code = 0;
  char    key[32] = {0};
  int     keyLen = 0;

1414
  //  getTableCacheKeyS(uid, "lr", key, &keyLen);
1415
  getTableCacheKey(uid, 0, key, &keyLen);
1416
  LRUHandle *h = taosLRUCacheLookup(pCache, key, keyLen);
1417
  if (!h) {
1418
    STsdb *pTsdb = pr->pVnode->pTsdb;
1419 1420 1421 1422
    taosThreadMutexLock(&pTsdb->lruMutex);

    h = taosLRUCacheLookup(pCache, key, keyLen);
    if (!h) {
1423
      SArray *pArray = NULL;
1424
      bool    dup = false;  // which is always false for now
1425
      code = mergeLastRow(uid, pTsdb, &dup, &pArray, pr);
1426
      // if table's empty or error, return code of -1
1427 1428 1429
      if (code < 0 || pArray == NULL) {
        if (!dup && pArray) {
          taosArrayDestroy(pArray);
1430 1431
        }

M
Minglei Jin 已提交
1432 1433
        taosThreadMutexUnlock(&pTsdb->lruMutex);

1434
        *handle = NULL;
M
Minglei Jin 已提交
1435

1436
        return 0;
1437 1438
      }

M
Minglei Jin 已提交
1439
      size_t              charge = pArray->capacity * pArray->elemSize + sizeof(*pArray);
1440
      _taos_lru_deleter_t deleter = deleteTableCacheLast;
1441
      LRUStatus status = taosLRUCacheInsert(pCache, key, keyLen, pArray, charge, deleter, &h, TAOS_LRU_PRIORITY_LOW);
1442 1443 1444
      if (status != TAOS_LRU_STATUS_OK) {
        code = -1;
      }
1445

1446
      // taosThreadMutexUnlock(&pTsdb->lruMutex);
1447

1448 1449 1450 1451
      // h = taosLRUCacheLookup(pCache, key, keyLen);
    }  // else {
    taosThreadMutexUnlock(&pTsdb->lruMutex);
    //}
1452 1453 1454 1455 1456 1457 1458
  }

  *handle = h;

  return code;
}

H
Hongze Cheng 已提交
1459 1460 1461 1462
// int32_t tsdbCacheLastArray2Row(SArray *pLastArray, STSRow **ppRow, STSchema *pTSchema) {
//   int32_t code = 0;
//   int16_t nCol = taosArrayGetSize(pLastArray);
//   SArray *pColArray = taosArrayInit(nCol, sizeof(SColVal));
1463

H
Hongze Cheng 已提交
1464 1465 1466 1467 1468
//   for (int16_t iCol = 0; iCol < nCol; ++iCol) {
//     SLastCol *tTsVal = (SLastCol *)taosArrayGet(pLastArray, iCol);
//     SColVal  *tColVal = &tTsVal->colVal;
//     taosArrayPush(pColArray, tColVal);
//   }
1469

H
Hongze Cheng 已提交
1470 1471
//   code = tdSTSRowNew(pColArray, pTSchema, ppRow);
//   if (code) goto _err;
1472

H
Hongze Cheng 已提交
1473
//   taosArrayDestroy(pColArray);
1474

H
Hongze Cheng 已提交
1475
//   return code;
1476

H
Hongze Cheng 已提交
1477 1478
// _err:
//   taosArrayDestroy(pColArray);
1479

H
Hongze Cheng 已提交
1480 1481
//   return code;
// }
1482

1483
int32_t tsdbCacheGetLastH(SLRUCache *pCache, tb_uid_t uid, SCacheRowsReader *pr, LRUHandle **handle) {
1484 1485 1486 1487
  int32_t code = 0;
  char    key[32] = {0};
  int     keyLen = 0;

1488
  // getTableCacheKeyS(uid, "l", key, &keyLen);
1489
  getTableCacheKey(uid, 1, key, &keyLen);
1490
  LRUHandle *h = taosLRUCacheLookup(pCache, key, keyLen);
1491
  if (!h) {
1492
    STsdb *pTsdb = pr->pVnode->pTsdb;
1493
    taosThreadMutexLock(&pTsdb->lruMutex);
1494

1495
    h = taosLRUCacheLookup(pCache, key, keyLen);
1496 1497
    if (!h) {
      SArray *pLastArray = NULL;
1498
      code = mergeLast(uid, pTsdb, &pLastArray, pr);
1499 1500
      // if table's empty or error, return code of -1
      if (code < 0 || pLastArray == NULL) {
1501 1502
        taosThreadMutexUnlock(&pTsdb->lruMutex);

1503 1504 1505 1506
        *handle = NULL;
        return 0;
      }

M
Minglei Jin 已提交
1507
      size_t              charge = pLastArray->capacity * pLastArray->elemSize + sizeof(*pLastArray);
1508
      _taos_lru_deleter_t deleter = deleteTableCacheLast;
M
Minglei Jin 已提交
1509
      LRUStatus           status =
1510
          taosLRUCacheInsert(pCache, key, keyLen, pLastArray, charge, deleter, &h, TAOS_LRU_PRIORITY_LOW);
1511 1512 1513 1514
      if (status != TAOS_LRU_STATUS_OK) {
        code = -1;
      }

1515
      // taosThreadMutexUnlock(&pTsdb->lruMutex);
1516

1517 1518 1519 1520
      // h = taosLRUCacheLookup(pCache, key, keyLen);
    }  // else {
    taosThreadMutexUnlock(&pTsdb->lruMutex);
    //}
1521 1522 1523
  }

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

1525 1526 1527
  return code;
}

M
Minglei Jin 已提交
1528 1529 1530 1531 1532 1533 1534
int32_t tsdbCacheRelease(SLRUCache *pCache, LRUHandle *h) {
  int32_t code = 0;

  taosLRUCacheRelease(pCache, h, false);

  return code;
}
1535 1536 1537 1538 1539 1540

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

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

1542 1543 1544 1545 1546 1547 1548 1549
size_t tsdbCacheGetUsage(SVnode *pVnode) {
  size_t usage = 0;
  if (pVnode->pTsdb != NULL) {
    usage = taosLRUCacheGetUsage(pVnode->pTsdb->lruCache);
  }

  return usage;
}