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

17 18
static int32_t tsdbOpenBICache(STsdb *pTsdb) {
  int32_t    code = 0;
19
  SLRUCache *pCache = taosLRUCacheInit(10 * 1024 * 1024, 0, .5);
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
  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) {
37 38
    int32_t elems = taosLRUCacheGetElems(pCache);
    tsdbTrace("vgId:%d, elems: %d", TD_VID(pTsdb->pVnode), elems);
39
    taosLRUCacheEraseUnrefEntries(pCache);
40 41
    elems = taosLRUCacheGetElems(pCache);
    tsdbTrace("vgId:%d, elems: %d", TD_VID(pTsdb->pVnode), elems);
42 43 44 45 46 47 48

    taosLRUCacheCleanup(pCache);

    taosThreadMutexDestroy(&pTsdb->biMutex);
  }
}

49 50
#define ROCKS_KEY_LEN 64

51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
static void tsdbGetRocksPath(STsdb *pTsdb, char *path) {
  SVnode *pVnode = pTsdb->pVnode;
  if (pVnode->pTfs) {
    if (path) {
      snprintf(path, TSDB_FILENAME_LEN, "%s%s%s%scache.rdb", tfsGetPrimaryPath(pTsdb->pVnode->pTfs), TD_DIRSEP,
               pTsdb->path, TD_DIRSEP);
    }
  } else {
    if (path) {
      snprintf(path, TSDB_FILENAME_LEN, "%s%scache.rdb", pTsdb->path, TD_DIRSEP);
    }
  }
}

static int32_t tsdbOpenRocksCache(STsdb *pTsdb) {
  int32_t code = 0;

  rocksdb_options_t *options = rocksdb_options_create();
  if (NULL == options) {
    code = TSDB_CODE_OUT_OF_MEMORY;
    goto _err;
  }

  rocksdb_options_set_create_if_missing(options, 1);
75 76
  // rocksdb_options_set_inplace_update_support(options, 1);
  // rocksdb_options_set_allow_concurrent_memtable_write(options, 0);
77 78 79 80 81 82

  rocksdb_writeoptions_t *writeoptions = rocksdb_writeoptions_create();
  if (NULL == writeoptions) {
    code = TSDB_CODE_OUT_OF_MEMORY;
    goto _err2;
  }
83
  // rocksdb_writeoptions_disable_WAL(writeoptions, 1);
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100

  rocksdb_readoptions_t *readoptions = rocksdb_readoptions_create();
  if (NULL == readoptions) {
    code = TSDB_CODE_OUT_OF_MEMORY;
    goto _err2;
  }

  char *err = NULL;
  char  cachePath[TSDB_FILENAME_LEN] = {0};
  tsdbGetRocksPath(pTsdb, cachePath);

  rocksdb_t *db = rocksdb_open(options, cachePath, &err);
  if (NULL == db) {
    code = -1;
    goto _err3;
  }

101 102 103 104 105 106
  rocksdb_flushoptions_t *flushoptions = rocksdb_flushoptions_create();
  if (NULL == flushoptions) {
    code = TSDB_CODE_OUT_OF_MEMORY;
    goto _err4;
  }

107 108 109
  rocksdb_writebatch_t *writebatch = rocksdb_writebatch_create();

  pTsdb->rCache.writebatch = writebatch;
110 111 112
  pTsdb->rCache.options = options;
  pTsdb->rCache.writeoptions = writeoptions;
  pTsdb->rCache.readoptions = readoptions;
113
  pTsdb->rCache.flushoptions = flushoptions;
114 115
  pTsdb->rCache.db = db;

116 117
  taosThreadMutexInit(&pTsdb->rCache.rMutex, NULL);

118 119 120 121 122 123 124 125 126 127 128 129 130 131
  return code;

_err4:
  rocksdb_readoptions_destroy(readoptions);
_err3:
  rocksdb_writeoptions_destroy(writeoptions);
_err2:
  rocksdb_options_destroy(options);
_err:
  return code;
}

static void tsdbCloseRocksCache(STsdb *pTsdb) {
  rocksdb_close(pTsdb->rCache.db);
132
  rocksdb_flushoptions_destroy(pTsdb->rCache.flushoptions);
133
  rocksdb_writebatch_destroy(pTsdb->rCache.writebatch);
134 135 136
  rocksdb_readoptions_destroy(pTsdb->rCache.readoptions);
  rocksdb_writeoptions_destroy(pTsdb->rCache.writeoptions);
  rocksdb_options_destroy(pTsdb->rCache.options);
137
  taosThreadMutexDestroy(&pTsdb->rCache.rMutex);
138 139
}

140 141 142 143 144 145 146 147 148 149 150 151 152 153
int32_t tsdbCacheCommit(STsdb *pTsdb) {
  int32_t code = 0;
  char   *err = NULL;

  rocksdb_flush(pTsdb->rCache.db, pTsdb->rCache.flushoptions, &err);
  if (NULL != err) {
    tsdbError("vgId:%d, %s failed at line %d since %s", TD_VID(pTsdb->pVnode), __func__, __LINE__, err);
    rocksdb_free(err);
    code = -1;
  }

  return code;
}

154
SLastCol *tsdbCacheDeserialize(char const *value) {
155 156 157 158
  if (!value) {
    return NULL;
  }

159 160 161
  SLastCol *pLastCol = (SLastCol *)value;
  SColVal  *pColVal = &pLastCol->colVal;
  if (IS_VAR_DATA_TYPE(pColVal->type)) {
162 163 164 165 166
    if (pColVal->value.nData > 0) {
      pColVal->value.pData = (char *)value + sizeof(*pLastCol);
    } else {
      pColVal->value.pData = NULL;
    }
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
  }

  return pLastCol;
}

void tsdbCacheSerialize(SLastCol *pLastCol, char **value, size_t *size) {
  SColVal *pColVal = &pLastCol->colVal;
  size_t   length = sizeof(*pLastCol);
  if (IS_VAR_DATA_TYPE(pColVal->type)) {
    length += pColVal->value.nData;
  }
  *value = taosMemoryMalloc(length);

  *(SLastCol *)(*value) = *pLastCol;
  if (IS_VAR_DATA_TYPE(pColVal->type)) {
    uint8_t *pVal = pColVal->value.pData;
    pColVal->value.pData = *value + sizeof(*pLastCol);
184
    if (pColVal->value.nData > 0) {
185
      memcpy(pColVal->value.pData, pVal, pColVal->value.nData);
186 187
    } else {
      pColVal->value.pData = NULL;
188 189 190 191 192
    }
  }
  *size = length;
}

193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
static SLastCol *tsdbCacheLookup(STsdb *pTsdb, tb_uid_t uid, int16_t cid, char const *lstring) {
  SLastCol *pLastCol = NULL;

  char  *err = NULL;
  size_t vlen = 0;
  char   key[ROCKS_KEY_LEN];
  size_t klen = snprintf(key, ROCKS_KEY_LEN, "%" PRIi64 ":%" PRIi16 ":%s", uid, cid, lstring);
  char  *value = NULL;
  value = rocksdb_get(pTsdb->rCache.db, pTsdb->rCache.readoptions, key, klen, &vlen, &err);
  if (NULL != err) {
    tsdbError("vgId:%d, %s failed at line %d since %s", TD_VID(pTsdb->pVnode), __func__, __LINE__, err);
    rocksdb_free(err);
  }

  pLastCol = tsdbCacheDeserialize(value);

  return pLastCol;
}

212
int32_t tsdbCacheUpdate(STsdb *pTsdb, tb_uid_t suid, tb_uid_t uid, TSDBROW *pRow) {
213 214
  int32_t code = 0;

215 216 217 218 219 220 221 222 223 224 225 226
  // 1, fetch schema
  STSchema *pTSchema = NULL;
  int32_t   sver = TSDBROW_SVERSION(pRow);
  code = metaGetTbTSchemaEx(pTsdb->pVnode->pMeta, suid, uid, sver, &pTSchema);
  if (code != TSDB_CODE_SUCCESS) {
    terrno = code;
    return -1;
  }

  // 2, iterate col values into array
  SArray *aColVal = taosArrayInit(32, sizeof(SColVal));

227 228 229 230
  STSDBRowIter iter = {0};
  tsdbRowIterOpen(&iter, pRow, pTSchema);

  for (SColVal *pColVal = tsdbRowIterNext(&iter); pColVal; pColVal = tsdbRowIterNext(&iter)) {
M
Minglei Jin 已提交
231
    /*
232 233 234 235 236 237 238 239 240 241 242 243 244
    if (IS_VAR_DATA_TYPE(pColVal->type)) {
      uint8_t *pVal = pColVal->value.pData;

      pColVal->value.pData = NULL;
      code = tRealloc(&pColVal->value.pData, pColVal->value.nData);
      if (code) {
        code = TSDB_CODE_OUT_OF_MEMORY;
        goto _exit;
      }

      if (pColVal->value.nData) {
        memcpy(pColVal->value.pData, pVal, pColVal->value.nData);
      }
245
    }
M
Minglei Jin 已提交
246
    */
247
    taosArrayPush(aColVal, pColVal);
248 249 250 251
  }

  tsdbRowClose(&iter);

252 253 254 255 256 257
  // 3, build keys & multi get from rocks
  int     num_keys = TARRAY_SIZE(aColVal);
  char  **keys_list = taosMemoryCalloc(num_keys * 2, sizeof(char *));
  size_t *keys_list_sizes = taosMemoryCalloc(num_keys * 2, sizeof(size_t));
  for (int i = 0; i < num_keys; ++i) {
    SColVal *pColVal = (SColVal *)taosArrayGet(aColVal, i);
258
    int16_t  cid = pColVal->cid;
259 260

    char *keys = taosMemoryCalloc(2, ROCKS_KEY_LEN);
261
    int   last_key_len = snprintf(keys, ROCKS_KEY_LEN, "%" PRIi64 ":%" PRIi16 ":last", uid, cid);
262 263 264
    if (last_key_len >= ROCKS_KEY_LEN) {
      tsdbError("vgId:%d, %s failed at line %d since %s", TD_VID(pTsdb->pVnode), __func__, __LINE__, tstrerror(code));
    }
265
    int lr_key_len = snprintf(keys + ROCKS_KEY_LEN, ROCKS_KEY_LEN, "%" PRIi64 ":%" PRIi16 ":last_row", uid, cid);
266 267 268 269 270 271 272 273 274 275 276
    if (lr_key_len >= ROCKS_KEY_LEN) {
      tsdbError("vgId:%d, %s failed at line %d since %s", TD_VID(pTsdb->pVnode), __func__, __LINE__, tstrerror(code));
    }
    keys_list[i] = keys;
    keys_list[num_keys + i] = keys + ROCKS_KEY_LEN;
    keys_list_sizes[i] = last_key_len;
    keys_list_sizes[num_keys + i] = lr_key_len;
  }
  char  **values_list = taosMemoryCalloc(num_keys * 2, sizeof(char *));
  size_t *values_list_sizes = taosMemoryCalloc(num_keys * 2, sizeof(size_t));
  char  **errs = taosMemoryCalloc(num_keys * 2, sizeof(char *));
277
  taosThreadMutexLock(&pTsdb->rCache.rMutex);
278 279 280 281 282
  rocksdb_multi_get(pTsdb->rCache.db, pTsdb->rCache.readoptions, num_keys * 2, (const char *const *)keys_list,
                    keys_list_sizes, values_list, values_list_sizes, errs);
  for (int i = 0; i < num_keys; ++i) {
    taosMemoryFree(keys_list[i]);
  }
M
Minglei Jin 已提交
283 284 285
  for (int i = 0; i < num_keys * 2; ++i) {
    rocksdb_free(errs[i]);
  }
286 287 288 289 290 291 292 293 294
  taosMemoryFree(keys_list);
  taosMemoryFree(keys_list_sizes);
  taosMemoryFree(errs);

  TSKEY                 keyTs = TSDBROW_TS(pRow);
  rocksdb_writebatch_t *wb = pTsdb->rCache.writebatch;
  for (int i = 0; i < num_keys; ++i) {
    SColVal *pColVal = (SColVal *)taosArrayGet(aColVal, i);
    if (COL_VAL_IS_VALUE(pColVal)) {
295
      SLastCol *pLastCol = tsdbCacheDeserialize(values_list[i]);
296 297 298 299 300 301 302 303 304 305 306 307 308

      if (NULL == pLastCol || pLastCol->ts <= keyTs) {
        char  *value = NULL;
        size_t vlen = 0;
        tsdbCacheSerialize(&(SLastCol){.ts = keyTs, .colVal = *pColVal}, &value, &vlen);
        char   key[ROCKS_KEY_LEN];
        size_t klen = snprintf(key, ROCKS_KEY_LEN, "%" PRIi64 ":%" PRIi16 ":last", uid, pColVal->cid);
        rocksdb_writebatch_put(wb, key, klen, value, vlen);
        taosMemoryFree(value);
      }
    }

    if (!COL_VAL_IS_NONE(pColVal)) {
M
Minglei Jin 已提交
309
      SLastCol *pLastCol = tsdbCacheDeserialize(values_list[i + num_keys]);
310 311 312 313 314 315 316 317 318 319 320

      if (NULL == pLastCol || pLastCol->ts <= keyTs) {
        char  *value = NULL;
        size_t vlen = 0;
        tsdbCacheSerialize(&(SLastCol){.ts = keyTs, .colVal = *pColVal}, &value, &vlen);
        char   key[ROCKS_KEY_LEN];
        size_t klen = snprintf(key, ROCKS_KEY_LEN, "%" PRIi64 ":%" PRIi16 ":last_row", uid, pColVal->cid);
        rocksdb_writebatch_put(wb, key, klen, value, vlen);
        taosMemoryFree(value);
      }
    }
321 322

    rocksdb_free(values_list[i]);
M
Minglei Jin 已提交
323
    rocksdb_free(values_list[i + num_keys]);
324 325 326 327 328 329 330 331 332
  }
  taosMemoryFree(values_list);
  taosMemoryFree(values_list_sizes);

  char *err = NULL;
  rocksdb_write(pTsdb->rCache.db, pTsdb->rCache.writeoptions, wb, &err);
  if (NULL != err) {
    tsdbError("vgId:%d, %s failed at line %d since %s", TD_VID(pTsdb->pVnode), __func__, __LINE__, err);
    rocksdb_free(err);
333
  }
334
  taosThreadMutexUnlock(&pTsdb->rCache.rMutex);
335
  rocksdb_writebatch_clear(wb);
336

337 338 339
_exit:
  taosArrayDestroy(aColVal);
  taosMemoryFree(pTSchema);
340 341 342
  return code;
}

343 344 345
static int32_t mergeLastCid(tb_uid_t uid, STsdb *pTsdb, SArray **ppLastArray, SCacheRowsReader *pr, int16_t *aCols,
                            int nCols, int16_t *slotIds);

346 347 348
static int32_t mergeLastRowCid(tb_uid_t uid, STsdb *pTsdb, SArray **ppLastArray, SCacheRowsReader *pr, int16_t *aCols,
                               int nCols, int16_t *slotIds);

349
int32_t tsdbCacheGet(STsdb *pTsdb, tb_uid_t uid, SArray *pLastArray, SCacheRowsReader *pr, int32_t ltype) {
M
Minglei Jin 已提交
350
  static char const *alstring[2] = {"last_row", "last"};
351 352
  char const        *lstring = alstring[ltype];
  int32_t            code = 0;
353 354

  SArray *pCidList = pr->pCidList;
355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
  int     num_keys = TARRAY_SIZE(pCidList);
  char  **keys_list = taosMemoryCalloc(num_keys, sizeof(char *));
  size_t *keys_list_sizes = taosMemoryCalloc(num_keys, sizeof(size_t));
  for (int i = 0; i < num_keys; ++i) {
    int16_t cid = *(int16_t *)taosArrayGet(pCidList, i);

    char *keys = taosMemoryCalloc(2, ROCKS_KEY_LEN);
    int   last_key_len = snprintf(keys, ROCKS_KEY_LEN, "%" PRIi64 ":%" PRIi16 ":%s", uid, cid, lstring);
    if (last_key_len >= ROCKS_KEY_LEN) {
      tsdbError("vgId:%d, %s failed at line %d since %s", TD_VID(pTsdb->pVnode), __func__, __LINE__, tstrerror(code));
    }

    keys_list[i] = keys;
    keys_list_sizes[i] = last_key_len;
  }
  char  **values_list = taosMemoryCalloc(num_keys, sizeof(char *));
  size_t *values_list_sizes = taosMemoryCalloc(num_keys, sizeof(size_t));
  char  **errs = taosMemoryCalloc(num_keys, sizeof(char *));
  rocksdb_multi_get(pTsdb->rCache.db, pTsdb->rCache.readoptions, num_keys, (const char *const *)keys_list,
                    keys_list_sizes, values_list, values_list_sizes, errs);
  for (int i = 0; i < num_keys; ++i) {
    taosMemoryFree(keys_list[i]);
M
Minglei Jin 已提交
377
    rocksdb_free(errs[i]);
378 379 380 381 382 383
  }
  taosMemoryFree(keys_list);
  taosMemoryFree(keys_list_sizes);
  taosMemoryFree(errs);

  for (int i = 0; i < num_keys; ++i) {
384
    bool      freeCol = true;
385
    SArray   *pTmpColArray = NULL;
386
    SLastCol *pLastCol = tsdbCacheDeserialize(values_list[i]);
387 388
    int16_t   cid = *(int16_t *)taosArrayGet(pCidList, i);
    SLastCol  noneCol = {.ts = TSKEY_MIN, .colVal = COL_VAL_NONE(cid, pr->pSchema->columns[pr->pSlotIds[i]].type)};
M
Minglei Jin 已提交
389 390 391 392
    if (pLastCol) {
      SColVal *pColVal = &pLastCol->colVal;
      if (IS_VAR_DATA_TYPE(pColVal->type)) {
        uint8_t *pVal = pColVal->value.pData;
393
        pColVal->value.pData = taosMemoryMalloc(pColVal->value.nData);
M
Minglei Jin 已提交
394 395 396 397 398
        if (pColVal->value.nData) {
          memcpy(pColVal->value.pData, pVal, pColVal->value.nData);
        }
      }
    } else {
399
      taosThreadMutexLock(&pTsdb->rCache.rMutex);
400

401
      pLastCol = tsdbCacheLookup(pTsdb, uid, cid, lstring);
402
      if (!pLastCol) {
403 404 405 406 407 408 409 410 411 412 413 414 415
        // recalc: load from tsdb
        int16_t aCols[1] = {cid};
        int16_t slotIds[1] = {pr->pSlotIds[i]};
        pTmpColArray = NULL;

        if (ltype) {
          mergeLastCid(uid, pTsdb, &pTmpColArray, pr, aCols, 1, slotIds);
        } else {
          mergeLastRowCid(uid, pTsdb, &pTmpColArray, pr, aCols, 1, slotIds);
        }

        if (pTmpColArray && TARRAY_SIZE(pTmpColArray) >= 1) {
          pLastCol = taosArrayGet(pTmpColArray, 0);
416
          freeCol = false;
417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
        }

        // still null, then make up a none col value
        if (!pLastCol) {
          pLastCol = &noneCol;
          freeCol = false;
        }

        // store result back to rocks cache
        rocksdb_writebatch_t *wb = pTsdb->rCache.writebatch;
        char                 *value = NULL;
        size_t                vlen = 0;
        tsdbCacheSerialize(pLastCol, &value, &vlen);
        char   key[ROCKS_KEY_LEN];
        size_t klen = snprintf(key, ROCKS_KEY_LEN, "%" PRIi64 ":%" PRIi16 ":%s", uid, pLastCol->colVal.cid, lstring);
        rocksdb_writebatch_put(wb, key, klen, value, vlen);

        taosMemoryFree(value);
M
Minglei Jin 已提交
435

436 437 438 439 440 441
        char *err = NULL;
        rocksdb_write(pTsdb->rCache.db, pTsdb->rCache.writeoptions, wb, &err);
        if (NULL != err) {
          tsdbError("vgId:%d, %s failed at line %d since %s", TD_VID(pTsdb->pVnode), __func__, __LINE__, err);
          rocksdb_free(err);
        }
442 443 444 445 446 447 448 449 450
      } else {
        SColVal *pColVal = &pLastCol->colVal;
        if (IS_VAR_DATA_TYPE(pColVal->type)) {
          uint8_t *pVal = pColVal->value.pData;
          pColVal->value.pData = taosMemoryMalloc(pColVal->value.nData);
          if (pColVal->value.nData) {
            memcpy(pColVal->value.pData, pVal, pColVal->value.nData);
          }
        }
451 452
      }

453
      taosThreadMutexUnlock(&pTsdb->rCache.rMutex);
M
Minglei Jin 已提交
454
    }
455

456 457
    taosArrayPush(pLastArray, pLastCol);

458
    taosArrayDestroy(pTmpColArray);
459 460 461
    if (freeCol) {
      taosMemoryFree(pLastCol);
    }
462 463 464
  }
  taosMemoryFree(values_list);
  taosMemoryFree(values_list_sizes);
465 466 467 468

  return code;
}

469 470 471 472 473 474 475 476 477 478 479 480 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 506 507 508 509 510 511 512 513 514 515 516 517 518
int32_t tsdbCacheDel(STsdb *pTsdb, tb_uid_t suid, tb_uid_t uid, TSKEY sKey, TSKEY eKey) {
  int32_t code = 0;
  // 1, fetch schema
  STSchema *pTSchema = NULL;
  int32_t   sver = -1;
  code = metaGetTbTSchemaEx(pTsdb->pVnode->pMeta, suid, uid, sver, &pTSchema);
  if (code != TSDB_CODE_SUCCESS) {
    terrno = code;
    return -1;
  }

  // 3, build keys & multi get from rocks
  int     num_keys = pTSchema->numOfCols;
  char  **keys_list = taosMemoryCalloc(num_keys * 2, sizeof(char *));
  size_t *keys_list_sizes = taosMemoryCalloc(num_keys * 2, sizeof(size_t));
  for (int i = 0; i < num_keys; ++i) {
    int16_t cid = pTSchema->columns[i].colId;

    char *keys = taosMemoryCalloc(2, ROCKS_KEY_LEN);
    int   last_key_len = snprintf(keys, ROCKS_KEY_LEN, "%" PRIi64 ":%" PRIi16 ":last", uid, cid);
    if (last_key_len >= ROCKS_KEY_LEN) {
      tsdbError("vgId:%d, %s failed at line %d since %s", TD_VID(pTsdb->pVnode), __func__, __LINE__, tstrerror(code));
    }
    int lr_key_len = snprintf(keys + ROCKS_KEY_LEN, ROCKS_KEY_LEN, "%" PRIi64 ":%" PRIi16 ":last_row", uid, cid);
    if (lr_key_len >= ROCKS_KEY_LEN) {
      tsdbError("vgId:%d, %s failed at line %d since %s", TD_VID(pTsdb->pVnode), __func__, __LINE__, tstrerror(code));
    }
    keys_list[i] = keys;
    keys_list[num_keys + i] = keys + ROCKS_KEY_LEN;
    keys_list_sizes[i] = last_key_len;
    keys_list_sizes[num_keys + i] = lr_key_len;
  }
  char  **values_list = taosMemoryCalloc(num_keys * 2, sizeof(char *));
  size_t *values_list_sizes = taosMemoryCalloc(num_keys * 2, sizeof(size_t));
  char  **errs = taosMemoryCalloc(num_keys * 2, sizeof(char *));
  taosThreadMutexLock(&pTsdb->rCache.rMutex);
  rocksdb_multi_get(pTsdb->rCache.db, pTsdb->rCache.readoptions, num_keys * 2, (const char *const *)keys_list,
                    keys_list_sizes, values_list, values_list_sizes, errs);
  for (int i = 0; i < num_keys; ++i) {
    taosMemoryFree(keys_list[i]);
  }
  for (int i = 0; i < num_keys * 2; ++i) {
    rocksdb_free(errs[i]);
  }
  taosMemoryFree(keys_list);
  taosMemoryFree(keys_list_sizes);
  taosMemoryFree(errs);

  rocksdb_writebatch_t *wb = pTsdb->rCache.writebatch;
  for (int i = 0; i < num_keys; ++i) {
519 520
    SLastCol *pLastCol = tsdbCacheDeserialize(values_list[i]);
    if (NULL != pLastCol && (pLastCol->ts <= eKey && pLastCol->ts >= sKey)) {
521 522 523 524 525
      char   key[ROCKS_KEY_LEN];
      size_t klen = snprintf(key, ROCKS_KEY_LEN, "%" PRIi64 ":%" PRIi16 ":last", uid, pLastCol->colVal.cid);
      rocksdb_writebatch_delete(wb, key, klen);
    }

526 527
    pLastCol = tsdbCacheDeserialize(values_list[i + num_keys]);
    if (NULL != pLastCol && (pLastCol->ts <= eKey && pLastCol->ts >= sKey)) {
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
      char   key[ROCKS_KEY_LEN];
      size_t klen = snprintf(key, ROCKS_KEY_LEN, "%" PRIi64 ":%" PRIi16 ":last_row", uid, pLastCol->colVal.cid);
      rocksdb_writebatch_delete(wb, key, klen);
    }

    rocksdb_free(values_list[i]);
    rocksdb_free(values_list[i + num_keys]);
  }
  taosMemoryFree(values_list);
  taosMemoryFree(values_list_sizes);

  char *err = NULL;
  rocksdb_write(pTsdb->rCache.db, pTsdb->rCache.writeoptions, wb, &err);
  if (NULL != err) {
    tsdbError("vgId:%d, %s failed at line %d since %s", TD_VID(pTsdb->pVnode), __func__, __LINE__, err);
    rocksdb_free(err);
  }
  taosThreadMutexUnlock(&pTsdb->rCache.rMutex);
  rocksdb_writebatch_clear(wb);

_exit:
  taosMemoryFree(pTSchema);

  return code;
}

554
int32_t tsdbOpenCache(STsdb *pTsdb) {
H
Hongze Cheng 已提交
555
  int32_t    code = 0;
556
  SLRUCache *pCache = NULL;
557
  size_t     cfgCapacity = pTsdb->pVnode->config.cacheLastSize * 1024 * 1024;
558

559
  pCache = taosLRUCacheInit(cfgCapacity, 1, .5);
560 561 562 563 564
  if (pCache == NULL) {
    code = TSDB_CODE_OUT_OF_MEMORY;
    goto _err;
  }

565 566 567 568 569 570
  code = tsdbOpenBICache(pTsdb);
  if (code != TSDB_CODE_SUCCESS) {
    code = TSDB_CODE_OUT_OF_MEMORY;
    goto _err;
  }

571 572 573 574 575 576
  code = tsdbOpenRocksCache(pTsdb);
  if (code != TSDB_CODE_SUCCESS) {
    code = TSDB_CODE_OUT_OF_MEMORY;
    goto _err;
  }

577
  taosLRUCacheSetStrictCapacity(pCache, false);
578

579 580
  taosThreadMutexInit(&pTsdb->lruMutex, NULL);

581 582 583 584 585
_err:
  pTsdb->lruCache = pCache;
  return code;
}

586 587
void tsdbCloseCache(STsdb *pTsdb) {
  SLRUCache *pCache = pTsdb->lruCache;
588 589 590 591
  if (pCache) {
    taosLRUCacheEraseUnrefEntries(pCache);

    taosLRUCacheCleanup(pCache);
592 593

    taosThreadMutexDestroy(&pTsdb->lruMutex);
594
  }
595 596

  tsdbCloseBICache(pTsdb);
597
  tsdbCloseRocksCache(pTsdb);
598 599
}

600 601 602 603 604 605 606 607 608 609
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);
}

610 611 612 613 614
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);
615
    if (IS_VAR_DATA_TYPE(pLastCol->colVal.type) && pLastCol->colVal.value.nData > 0) {
616 617 618 619 620 621
      taosMemoryFree(pLastCol->colVal.value.pData);
    }
  }

  taosArrayDestroy(value);
}
622

623
int32_t tsdbCacheDeleteLastrow(SLRUCache *pCache, tb_uid_t uid, TSKEY eKey) {
624
  int32_t code = 0;
625 626 627

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

629 630
  // getTableCacheKey(uid, "lr", key, &keyLen);
  getTableCacheKey(uid, 0, key, &keyLen);
631 632
  LRUHandle *h = taosLRUCacheLookup(pCache, key, keyLen);
  if (h) {
633 634 635 636 637 638 639 640 641 642 643 644
    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;
      }
    }

645
    taosLRUCacheRelease(pCache, h, invalidate);
646
    if (invalidate) {
647
      taosLRUCacheErase(pCache, key, keyLen);
648 649 650 651 652 653
    }
  }

  return code;
}

654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675
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;
      }
    }

676
    taosLRUCacheRelease(pCache, h, invalidate);
677
    if (invalidate) {
678
      taosLRUCacheErase(pCache, key, keyLen);
679 680 681 682 683
    }
  }

  return code;
}
684
/*
685
int32_t tsdbCacheDelete(SLRUCache *pCache, tb_uid_t uid, TSKEY eKey) {
686 687 688 689
  int32_t code = 0;
  char    key[32] = {0};
  int     keyLen = 0;

690 691 692 693
  // getTableCacheKey(uid, "lr", key, &keyLen);
  getTableCacheKey(uid, 0, key, &keyLen);
  LRUHandle *h = taosLRUCacheLookup(pCache, key, keyLen);
  if (h) {
694 695 696 697 698 699 700 701 702 703 704 705 706
    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) {
707 708 709 710 711 712
      taosLRUCacheRelease(pCache, h, true);
    } else {
      taosLRUCacheRelease(pCache, h, false);
    }
  }

713 714
  // getTableCacheKey(uid, "l", key, &keyLen);
  getTableCacheKey(uid, 1, key, &keyLen);
715
  h = taosLRUCacheLookup(pCache, key, keyLen);
716
  if (h) {
717 718 719
    SArray *pLast = (SArray *)taosLRUCacheValue(pCache, h);
    bool    invalidate = false;
    int16_t nCol = taosArrayGetSize(pLast);
720

721 722 723 724 725 726 727 728 729 730 731 732 733
    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);
    }
734 735 736 737 738
    // void taosLRUCacheErase(SLRUCache * cache, const void *key, size_t keyLen);
  }

  return code;
}
739
*/
H
Hongze Cheng 已提交
740
int32_t tsdbCacheInsertLastrow(SLRUCache *pCache, STsdb *pTsdb, tb_uid_t uid, TSDBROW *row, bool dup) {
741 742
  int32_t code = 0;
  STSRow *cacheRow = NULL;
H
Hongze Cheng 已提交
743 744
  char    key[32] = {0};
  int     keyLen = 0;
745

746 747
  // getTableCacheKey(uid, "lr", key, &keyLen);
  getTableCacheKey(uid, 0, key, &keyLen);
748 749
  LRUHandle *h = taosLRUCacheLookup(pCache, key, keyLen);
  if (h) {
750
    STSchema *pTSchema = metaGetTbTSchema(pTsdb->pVnode->pMeta, uid, -1, 1);
H
Hongze Cheng 已提交
751
    TSKEY     keyTs = TSDBROW_TS(row);
752 753 754 755 756 757
    bool      invalidate = false;

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

758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792
    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;
    }

793 794 795 796 797
    if (nCol != pTSchema->numOfCols) {
      invalidate = true;
      goto _invalidate;
    }

798 799 800 801 802 803 804 805 806 807 808 809 810 811
    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 已提交
812
        tsdbRowGetColVal(row, pTSchema, iCol, &colVal);
813 814 815 816 817 818

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

819 820 821 822 823
        if (!COL_VAL_IS_NONE(&colVal)) {
          if (keyTs == tTsVal1->ts && !COL_VAL_IS_NONE(tColVal)) {
            invalidate = true;

            break;
824 825 826 827
          } 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);
828 829
              if (pLastCol->colVal.value.nData > 0 && NULL != pLastCol->colVal.value.pData)
                taosMemoryFree(pLastCol->colVal.value.pData);
830 831 832 833 834 835 836 837

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

840 841
            taosArraySet(pLast, iCol, &lastCol);
          }
842 843 844 845 846 847 848 849
        }
      }
    }

  _invalidate:
    taosMemoryFreeClear(pTSchema);

    taosLRUCacheRelease(pCache, h, invalidate);
850 851
    if (invalidate) {
      taosLRUCacheErase(pCache, key, keyLen);
852
    }
853
  }
854 855 856 857

  return code;
}

H
Hongze Cheng 已提交
858
int32_t tsdbCacheInsertLast(SLRUCache *pCache, tb_uid_t uid, TSDBROW *row, STsdb *pTsdb) {
859 860 861 862 863
  int32_t code = 0;
  STSRow *cacheRow = NULL;
  char    key[32] = {0};
  int     keyLen = 0;

864 865
  // getTableCacheKey(uid, "l", key, &keyLen);
  getTableCacheKey(uid, 1, key, &keyLen);
866 867
  LRUHandle *h = taosLRUCacheLookup(pCache, key, keyLen);
  if (h) {
868
    STSchema *pTSchema = metaGetTbTSchema(pTsdb->pVnode->pMeta, uid, -1, 1);
H
Hongze Cheng 已提交
869
    TSKEY     keyTs = TSDBROW_TS(row);
870 871 872 873 874 875
    bool      invalidate = false;

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

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 906 907 908 909 910
    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;
    }

911 912 913 914 915
    if (nCol != pTSchema->numOfCols) {
      invalidate = true;
      goto _invalidate;
    }

916 917 918
    SLastCol *tTsVal = (SLastCol *)taosArrayGet(pLast, iCol);
    if (keyTs > tTsVal->ts) {
      STColumn *pTColumn = &pTSchema->columns[0];
H
Hongze Cheng 已提交
919
      SColVal   tColVal = COL_VAL_VALUE(pTColumn->colId, pTColumn->type, (SValue){.val = keyTs});
920 921 922 923 924

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

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

        SColVal colVal = {0};
H
Hongze Cheng 已提交
930
        tsdbRowGetColVal(row, pTSchema, iCol, &colVal);
931 932 933 934 935 936

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

937
        if (COL_VAL_IS_VALUE(&colVal)) {
H
Hongze Cheng 已提交
938
          if (keyTs == tTsVal1->ts && COL_VAL_IS_VALUE(tColVal)) {
939 940 941
            invalidate = true;

            break;
942 943 944 945
          } else {
            SLastCol lastCol = {.ts = keyTs, .colVal = colVal};
            if (IS_VAR_DATA_TYPE(colVal.type) && colVal.value.nData > 0) {
              SLastCol *pLastCol = (SLastCol *)taosArrayGet(pLast, iCol);
946 947
              if (pLastCol->colVal.value.nData > 0 && NULL != pLastCol->colVal.value.pData)
                taosMemoryFree(pLastCol->colVal.value.pData);
948 949 950 951 952 953 954 955

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

958 959
            taosArraySet(pLast, iCol, &lastCol);
          }
960 961 962 963
        }
      }
    }

964
  _invalidate:
965 966 967
    taosMemoryFreeClear(pTSchema);

    taosLRUCacheRelease(pCache, h, invalidate);
968 969 970
    if (invalidate) {
      taosLRUCacheErase(pCache, key, keyLen);
    }
971 972 973 974 975
  }

  return code;
}

976 977 978 979 980
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 已提交
981
  if (metaGetTableEntryByUidCache(&mr, uid) < 0) {
H
Hongze Cheng 已提交
982
    metaReaderClear(&mr);  // table not esist
983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002
    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 已提交
1003
    code = tsdbReadDelData(pDelReader, pDelIdx, aDelData);
1004 1005 1006 1007 1008 1009
  }

  return code;
}

static int32_t getTableDelDataFromTbData(STbData *pTbData, SArray *aDelData) {
H
Hongze Cheng 已提交
1010
  int32_t   code = 0;
1011 1012 1013 1014 1015 1016 1017 1018 1019
  SDelData *pDelData = pTbData ? pTbData->pHead : NULL;

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

  return code;
}

H
Hongze Cheng 已提交
1020 1021
static int32_t getTableDelData(STbData *pMem, STbData *pIMem, SDelFReader *pDelReader, SDelIdx *pDelIdx,
                               SArray *aDelData) {
1022 1023
  int32_t code = 0;

1024 1025 1026 1027 1028
  if (pDelIdx) {
    code = getTableDelDataFromDelIdx(pDelReader, pDelIdx, aDelData);
    if (code) goto _err;
  }

1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042
  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 已提交
1043 1044
static int32_t getTableDelSkyline(STbData *pMem, STbData *pIMem, SDelFReader *pDelReader, SDelIdx *pDelIdx,
                                  SArray *aSkyline) {
1045
  int32_t code = 0;
M
Minglei Jin 已提交
1046
  SArray *aDelData = NULL;
1047

M
Minglei Jin 已提交
1048
  aDelData = taosArrayInit(32, sizeof(SDelData));
1049 1050 1051 1052
  code = getTableDelData(pMem, pIMem, pDelReader, pDelIdx, aDelData);
  if (code) goto _err;

  size_t nDelData = taosArrayGetSize(aDelData);
1053 1054 1055 1056
  if (nDelData > 0) {
    code = tsdbBuildDeleteSkyline(aDelData, 0, (int32_t)(nDelData - 1), aSkyline);
    if (code) goto _err;
  }
1057

1058
_err:
M
Minglei Jin 已提交
1059 1060 1061
  if (aDelData) {
    taosArrayDestroy(aDelData);
  }
1062 1063
  return code;
}
S
stephenkgu 已提交
1064
/*
1065 1066
static int32_t getTableDelIdx(SDelFReader *pDelFReader, tb_uid_t suid, tb_uid_t uid, SDelIdx *pDelIdx) {
  int32_t code = 0;
M
Minglei Jin 已提交
1067
  SArray *pDelIdxArray = NULL;
1068

1069
  // SMapData delIdxMap;
M
Minglei Jin 已提交
1070
  pDelIdxArray = taosArrayInit(32, sizeof(SDelIdx));
1071
  SDelIdx idx = {.suid = suid, .uid = uid};
1072

1073
  // tMapDataReset(&delIdxMap);
H
Hongze Cheng 已提交
1074
  code = tsdbReadDelIdx(pDelFReader, pDelIdxArray);
1075 1076
  if (code) goto _err;

1077
  // code = tMapDataSearch(&delIdxMap, &idx, tGetDelIdx, tCmprDelIdx, pDelIdx);
1078
  SDelIdx *pIdx = taosArraySearch(pDelIdxArray, &idx, tCmprDelIdx, TD_EQ);
1079

1080 1081
  *pDelIdx = *pIdx;

1082
_err:
M
Minglei Jin 已提交
1083 1084 1085
  if (pDelIdxArray) {
    taosArrayDestroy(pDelIdxArray);
  }
1086 1087
  return code;
}
S
stephenkgu 已提交
1088
*/
1089 1090 1091 1092 1093 1094 1095 1096
typedef enum {
  SFSLASTNEXTROW_FS,
  SFSLASTNEXTROW_FILESET,
  SFSLASTNEXTROW_BLOCKDATA,
  SFSLASTNEXTROW_BLOCKROW
} SFSLASTNEXTROWSTATES;

typedef struct {
1097 1098 1099
  SFSLASTNEXTROWSTATES state;     // [input]
  STsdb               *pTsdb;     // [input]
  STSchema            *pTSchema;  // [input]
1100
  tb_uid_t             suid;
1101
  tb_uid_t             uid;
1102 1103 1104
  int32_t              nFileSet;
  int32_t              iFileSet;
  SArray              *aDFileSet;
1105
  SDataFReader       **pDataFReader;
1106
  TSDBROW              row;
1107

1108
  bool               checkRemainingRow;
1109 1110 1111
  SMergeTree         mergeTree;
  SMergeTree        *pMergeTree;
  SSttBlockLoadInfo *pLoadInfo;
1112
  int64_t            lastTs;
1113 1114
} SFSLastNextRowIter;

D
dapan1121 已提交
1115 1116
static int32_t getNextRowFromFSLast(void *iter, TSDBROW **ppRow, bool *pIgnoreEarlierTs, bool isLast, int16_t *aCols,
                                    int nCols) {
1117 1118
  SFSLastNextRowIter *state = (SFSLastNextRowIter *)iter;
  int32_t             code = 0;
D
dapan1121 已提交
1119
  bool                checkRemainingRow = true;
1120 1121 1122 1123 1124 1125 1126 1127 1128

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

    case SFSLASTNEXTROW_FILESET: {
      SDFileSet *pFileSet = NULL;
    _next_fileset:
1129 1130 1131 1132 1133
      if (state->pMergeTree != NULL) {
        tMergeTreeClose(state->pMergeTree);
        state->pMergeTree = NULL;
      }

1134 1135 1136 1137 1138 1139 1140
      if (--state->iFileSet >= 0) {
        pFileSet = (SDFileSet *)taosArrayGet(state->aDFileSet, state->iFileSet);
      } else {
        *ppRow = NULL;
        return code;
      }

1141 1142 1143
      if (*state->pDataFReader == NULL || (*state->pDataFReader)->pSet->fid != pFileSet->fid) {
        if (*state->pDataFReader != NULL) {
          tsdbDataFReaderClose(state->pDataFReader);
M
Minglei Jin 已提交
1144

1145 1146
          resetLastBlockLoadInfo(state->pLoadInfo);
        }
1147

1148 1149 1150 1151
        code = tsdbDataFReaderOpen(state->pDataFReader, state->pTsdb, pFileSet);
        if (code) goto _err;
      }

1152 1153 1154
      for (int i = 0; i < state->pLoadInfo->numOfStt; ++i) {
        state->pLoadInfo[i].colIds = aCols;
        state->pLoadInfo[i].numOfCols = nCols;
1155
        state->pLoadInfo[i].isLast = isLast;
1156
      }
1157
      tMergeTreeOpen(&state->mergeTree, 1, *state->pDataFReader, state->suid, state->uid,
D
dapan1121 已提交
1158 1159
                     &(STimeWindow){.skey = state->lastTs, .ekey = TSKEY_MAX},
                     &(SVersionRange){.minVer = 0, .maxVer = UINT64_MAX}, state->pLoadInfo, false, NULL, true);
1160
      state->pMergeTree = &state->mergeTree;
1161 1162 1163 1164 1165 1166 1167
      state->state = SFSLASTNEXTROW_BLOCKROW;
    }
    case SFSLASTNEXTROW_BLOCKROW: {
      if (nCols != state->pLoadInfo->numOfCols) {
        for (int i = 0; i < state->pLoadInfo->numOfStt; ++i) {
          state->pLoadInfo[i].numOfCols = nCols;

1168 1169
          state->pLoadInfo[i].checkRemainingRow = state->checkRemainingRow;
        }
1170
      }
1171 1172
      bool hasVal = tMergeTreeNext(&state->mergeTree);
      if (!hasVal) {
D
dapan1121 已提交
1173 1174 1175 1176 1177
        if (tMergeTreeIgnoreEarlierTs(&state->mergeTree)) {
          *pIgnoreEarlierTs = true;
          *ppRow = NULL;
          return code;
        }
1178
        state->state = SFSLASTNEXTROW_FILESET;
1179 1180
        goto _next_fileset;
      }
1181 1182
      state->row = tMergeTreeGetRow(&state->mergeTree);
      *ppRow = &state->row;
D
dapan1121 已提交
1183

1184 1185 1186 1187 1188
      if (TSDBROW_TS(&state->row) <= state->lastTs) {
        *pIgnoreEarlierTs = true;
        *ppRow = NULL;
        return code;
      }
D
dapan1121 已提交
1189

1190 1191 1192 1193
      *pIgnoreEarlierTs = false;
      if (!hasVal) {
        state->state = SFSLASTNEXTROW_FILESET;
      }
1194

1195 1196 1197
      if (!state->checkRemainingRow) {
        state->checkRemainingRow = true;
      }
1198
      return code;
1199
    }
1200 1201 1202 1203 1204 1205
    default:
      ASSERT(0);
      break;
  }

_err:
1206
  /*if (state->pDataFReader) {
1207 1208
    tsdbDataFReaderClose(&state->pDataFReader);
    state->pDataFReader = NULL;
1209
    }*/
1210 1211 1212 1213 1214
  if (state->pMergeTree != NULL) {
    tMergeTreeClose(state->pMergeTree);
    state->pMergeTree = NULL;
  }

1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226
  *ppRow = NULL;

  return code;
}

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

  if (!state) {
    return code;
  }
1227
  /*
1228 1229 1230 1231
  if (state->pDataFReader) {
    tsdbDataFReaderClose(&state->pDataFReader);
    state->pDataFReader = NULL;
  }
1232
  */
1233 1234 1235 1236 1237
  if (state->pMergeTree != NULL) {
    tMergeTreeClose(state->pMergeTree);
    state->pMergeTree = NULL;
  }

1238 1239 1240
  return code;
}

1241 1242 1243 1244 1245 1246 1247 1248
typedef enum SFSNEXTROWSTATES {
  SFSNEXTROW_FS,
  SFSNEXTROW_FILESET,
  SFSNEXTROW_BLOCKDATA,
  SFSNEXTROW_BLOCKROW
} SFSNEXTROWSTATES;

typedef struct SFSNextRowIter {
1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259
  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;
1260
  LRUHandle         *aBlockIdxHandle;
1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271
  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;
1272
  int64_t            lastTs;
1273 1274
} SFSNextRowIter;

D
dapan1121 已提交
1275 1276
static int32_t getNextRowFromFS(void *iter, TSDBROW **ppRow, bool *pIgnoreEarlierTs, bool isLast, int16_t *aCols,
                                int nCols) {
1277 1278
  SFSNextRowIter *state = (SFSNextRowIter *)iter;
  int32_t         code = 0;
D
dapan1121 已提交
1279
  bool            checkRemainingRow = true;
1280 1281 1282

  switch (state->state) {
    case SFSNEXTROW_FS:
H
Hongze Cheng 已提交
1283
      // state->aDFileSet = state->pTsdb->pFS->cState->aDFileSet;
1284
      state->nFileSet = taosArrayGetSize(state->aDFileSet);
M
Minglei Jin 已提交
1285
      state->iFileSet = state->nFileSet;
1286 1287

      state->pBlockData = NULL;
1288 1289 1290

    case SFSNEXTROW_FILESET: {
      SDFileSet *pFileSet = NULL;
1291
    _next_fileset:
1292 1293 1294
      if (--state->iFileSet >= 0) {
        pFileSet = (SDFileSet *)taosArrayGet(state->aDFileSet, state->iFileSet);
      } else {
H
Hongze Cheng 已提交
1295
        // tBlockDataDestroy(&state->blockData, 1);
1296
        if (state->pBlockData) {
H
Hongze Cheng 已提交
1297
          tBlockDataDestroy(state->pBlockData);
1298 1299
          state->pBlockData = NULL;
        }
1300

1301 1302 1303 1304
        *ppRow = NULL;
        return code;
      }

1305 1306 1307 1308
      if (*state->pDataFReader == NULL || (*state->pDataFReader)->pSet->fid != pFileSet->fid) {
        if (*state->pDataFReader != NULL) {
          tsdbDataFReaderClose(state->pDataFReader);

1309
          // resetLastBlockLoadInfo(state->pLoadInfo);
1310 1311 1312 1313 1314
        }

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

      // tMapDataReset(&state->blockIdxMap);
1317
      /*
1318 1319 1320 1321 1322
      if (!state->aBlockIdx) {
        state->aBlockIdx = taosArrayInit(0, sizeof(SBlockIdx));
      } else {
        taosArrayClear(state->aBlockIdx);
      }
1323
      code = tsdbReadBlockIdx(*state->pDataFReader, state->aBlockIdx);
1324
      if (code) goto _err;
1325
      */
1326
      int32_t code = tsdbCacheGetBlockIdx(state->pTsdb->biCache, *state->pDataFReader, &state->aBlockIdxHandle);
1327 1328 1329
      if (code != TSDB_CODE_SUCCESS || state->aBlockIdxHandle == NULL) {
        goto _err;
      }
1330
      state->aBlockIdx = (SArray *)taosLRUCacheValue(state->pTsdb->biCache, state->aBlockIdxHandle);
1331

1332 1333
      /* if (state->pBlockIdx) { */
      /* } */
1334 1335
      /* code = tMapDataSearch(&state->blockIdxMap, state->pBlockIdxExp, tGetBlockIdx, tCmprBlockIdx,
       * &state->blockIdx);
1336 1337
       */
      state->pBlockIdx = taosArraySearch(state->aBlockIdx, state->pBlockIdxExp, tCmprBlockIdx, TD_EQ);
1338 1339 1340 1341 1342 1343
      if (!state->pBlockIdx) {
        tsdbBICacheRelease(state->pTsdb->biCache, state->aBlockIdxHandle);

        state->aBlockIdxHandle = NULL;
        state->aBlockIdx = NULL;
        /*
1344 1345 1346
         tsdbDataFReaderClose(state->pDataFReader);
         *state->pDataFReader = NULL;
         resetLastBlockLoadInfo(state->pLoadInfo);*/
1347 1348 1349
        goto _next_fileset;
      }

1350 1351
      tMapDataReset(&state->blockMap);
      /*
1352 1353 1354
      if (state->blockMap.pData != NULL) {
        tMapDataClear(&state->blockMap);
      }
1355 1356
      */
      code = tsdbReadDataBlk(*state->pDataFReader, state->pBlockIdx, &state->blockMap);
1357 1358 1359 1360
      if (code) goto _err;

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

1362 1363 1364
      if (!state->pBlockData) {
        state->pBlockData = &state->blockData;

1365 1366
        code = tBlockDataCreate(&state->blockData);
        if (code) goto _err;
1367
      }
1368 1369
    }
    case SFSNEXTROW_BLOCKDATA:
D
dapan1121 已提交
1370
    _next_datablock:
1371
      if (state->iBlock >= 0) {
H
Hongze Cheng 已提交
1372
        SDataBlk block = {0};
D
dapan1121 已提交
1373 1374
        bool     skipBlock = true;
        int      inputColIndex = 0;
1375

H
Hongze Cheng 已提交
1376
        tDataBlkReset(&block);
1377
        tBlockDataReset(state->pBlockData);
1378

H
Hongze Cheng 已提交
1379
        tMapDataGetItemByIdx(&state->blockMap, state->iBlock, &block, tGetDataBlk);
1380
        if (block.maxKey.ts <= state->lastTs) {
1381
          *pIgnoreEarlierTs = true;
D
dapan1121 已提交
1382 1383 1384 1385 1386 1387 1388
          if (state->pBlockData) {
            tBlockDataDestroy(state->pBlockData);
            state->pBlockData = NULL;
          }

          *ppRow = NULL;
          return code;
1389
        }
1390
        *pIgnoreEarlierTs = false;
1391
        tBlockDataReset(state->pBlockData);
H
Hongze Cheng 已提交
1392
        TABLEID tid = {.suid = state->suid, .uid = state->uid};
1393
        int     nTmpCols = nCols;
1394
        if (aCols[0] == PRIMARYKEY_TIMESTAMP_COL_ID && nCols == 1) {
1395
          nTmpCols = 0;
1396 1397
          skipBlock = false;
        }
1398
        code = tBlockDataInit(state->pBlockData, &tid, state->pTSchema, aCols, nTmpCols);
1399 1400
        if (code) goto _err;

1401
        code = tsdbReadDataBlock(*state->pDataFReader, &block, state->pBlockData);
1402 1403
        if (code) goto _err;

D
dapan1121 已提交
1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436
        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;
          }
        }

1437 1438 1439 1440
        state->nRow = state->blockData.nRow;
        state->iRow = state->nRow - 1;

        state->state = SFSNEXTROW_BLOCKROW;
D
dapan1121 已提交
1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483
        checkRemainingRow = false;
      }
    case SFSNEXTROW_BLOCKROW: {
      if (checkRemainingRow) {
        bool skipBlock = true;
        int  inputColIndex = 0;
        for (int colIndex = 0; colIndex < state->pBlockData->nColData; ++colIndex) {
          SColData *pColData = &state->pBlockData->aColData[colIndex];
          int16_t   cid = pColData->cid;

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

            ++inputColIndex;
          }
        }

        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;
          }
        }
1484
      }
D
dapan1121 已提交
1485

1486
      if (state->iRow >= 0) {
1487
        state->row = tsdbRowFromBlockData(state->pBlockData, state->iRow);
1488 1489 1490 1491 1492
        *ppRow = &state->row;

        if (--state->iRow < 0) {
          state->state = SFSNEXTROW_BLOCKDATA;
          if (--state->iBlock < 0) {
1493 1494
            tsdbDataFReaderClose(state->pDataFReader);
            *state->pDataFReader = NULL;
1495
            // resetLastBlockLoadInfo(state->pLoadInfo);
1496

1497
            if (state->aBlockIdx) {
1498
              // taosArrayDestroy(state->aBlockIdx);
1499
              tsdbBICacheRelease(state->pTsdb->biCache, state->aBlockIdxHandle);
1500 1501

              state->aBlockIdxHandle = NULL;
1502
              state->aBlockIdx = NULL;
1503
            }
1504

1505 1506 1507 1508 1509 1510
            state->state = SFSNEXTROW_FILESET;
          }
        }
      }

      return code;
D
dapan1121 已提交
1511
    }
1512 1513 1514 1515 1516 1517
    default:
      ASSERT(0);
      break;
  }

_err:
1518 1519 1520 1521 1522 1523
  /*
  if (*state->pDataFReader) {
    tsdbDataFReaderClose(state->pDataFReader);
    *state->pDataFReader = NULL;
    resetLastBlockLoadInfo(state->pLoadInfo);
    }*/
1524
  if (state->aBlockIdx) {
1525
    // taosArrayDestroy(state->aBlockIdx);
1526
    tsdbBICacheRelease(state->pTsdb->biCache, state->aBlockIdxHandle);
1527 1528

    state->aBlockIdxHandle = NULL;
1529 1530 1531
    state->aBlockIdx = NULL;
  }
  if (state->pBlockData) {
H
Hongze Cheng 已提交
1532
    tBlockDataDestroy(state->pBlockData);
1533
    state->pBlockData = NULL;
1534 1535
  }

1536
  *ppRow = NULL;
1537

1538 1539 1540
  return code;
}

1541 1542 1543 1544 1545 1546 1547
int32_t clearNextRowFromFS(void *iter) {
  int32_t code = 0;

  SFSNextRowIter *state = (SFSNextRowIter *)iter;
  if (!state) {
    return code;
  }
1548
  /*
1549 1550 1551
  if (state->pDataFReader) {
    tsdbDataFReaderClose(&state->pDataFReader);
    state->pDataFReader = NULL;
1552
    }*/
1553
  if (state->aBlockIdx) {
1554
    // taosArrayDestroy(state->aBlockIdx);
1555
    tsdbBICacheRelease(state->pTsdb->biCache, state->aBlockIdxHandle);
1556 1557

    state->aBlockIdxHandle = NULL;
1558 1559 1560
    state->aBlockIdx = NULL;
  }
  if (state->pBlockData) {
H
Hongze Cheng 已提交
1561
    // tBlockDataDestroy(&state->blockData, 1);
H
Hongze Cheng 已提交
1562
    tBlockDataDestroy(state->pBlockData);
1563 1564 1565
    state->pBlockData = NULL;
  }

1566 1567 1568 1569
  if (state->blockMap.pData != NULL) {
    tMapDataClear(&state->blockMap);
  }

1570 1571 1572
  return code;
}

1573 1574 1575 1576 1577 1578 1579 1580 1581
typedef enum SMEMNEXTROWSTATES {
  SMEMNEXTROW_ENTER,
  SMEMNEXTROW_NEXT,
} SMEMNEXTROWSTATES;

typedef struct SMemNextRowIter {
  SMEMNEXTROWSTATES state;
  STbData          *pMem;  // [input]
  STbDataIter       iter;  // mem buffer skip list iterator
1582
  int64_t           lastTs;
1583 1584
  // bool              iterOpened;
  // TSDBROW          *curRow;
1585 1586
} SMemNextRowIter;

D
dapan1121 已提交
1587 1588
static int32_t getNextRowFromMem(void *iter, TSDBROW **ppRow, bool *pIgnoreEarlierTs, bool isLast, int16_t *aCols,
                                 int nCols) {
1589 1590
  SMemNextRowIter *state = (SMemNextRowIter *)iter;
  int32_t          code = 0;
1591
  *pIgnoreEarlierTs = false;
1592 1593 1594
  switch (state->state) {
    case SMEMNEXTROW_ENTER: {
      if (state->pMem != NULL) {
1595 1596 1597 1598 1599
        if (state->pMem->maxKey <= state->lastTs) {
          *ppRow = NULL;
          *pIgnoreEarlierTs = true;
          return code;
        }
1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634
        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;
}

1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672
/* 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; */
/* } */
1673

1674
static bool tsdbKeyDeleted(TSDBKEY *key, SArray *pSkyline, int64_t *iSkyline) {
1675 1676 1677 1678 1679 1680 1681 1682
  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) {
1683
      if (key->version <= pItemFront->version || (key->ts == pItemBack->ts && key->version <= pItemBack->version)) {
1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699
        return true;
      } else {
        return false;
      }
    } else {
      if (*iSkyline > 1) {
        --*iSkyline;
      } else {
        return false;
      }
    }
  }

  return deleted;
}

D
dapan1121 已提交
1700 1701
typedef int32_t (*_next_row_fn_t)(void *iter, TSDBROW **ppRow, bool *pIgnoreEarlierTs, bool isLast, int16_t *aCols,
                                  int nCols);
1702
typedef int32_t (*_next_row_clear_fn_t)(void *iter);
1703

1704
typedef struct {
1705 1706 1707
  TSDBROW             *pRow;
  bool                 stop;
  bool                 next;
1708
  bool                 ignoreEarlierTs;
1709 1710 1711
  void                *iter;
  _next_row_fn_t       nextRowFn;
  _next_row_clear_fn_t nextRowClearFn;
1712
} TsdbNextRowState;
1713

1714 1715 1716 1717
typedef struct {
  SArray *pSkyline;
  int64_t iSkyline;

1718 1719 1720 1721 1722 1723
  SBlockIdx          idx;
  SMemNextRowIter    memState;
  SMemNextRowIter    imemState;
  SFSLastNextRowIter fsLastState;
  SFSNextRowIter     fsState;
  TSDBROW            memRow, imemRow, fsLastRow, fsRow;
1724

1725
  TsdbNextRowState input[4];
1726
  STsdb           *pTsdb;
1727 1728
} CacheNextRowIter;

1729
static int32_t nextRowIterOpen(CacheNextRowIter *pIter, tb_uid_t uid, STsdb *pTsdb, STSchema *pTSchema, tb_uid_t suid,
1730
                               SSttBlockLoadInfo *pLoadInfo, STsdbReadSnap *pReadSnap, SDataFReader **pDataFReader,
1731
                               SDataFReader **pDataFReaderLast, int64_t lastTs) {
1732 1733 1734
  int code = 0;

  STbData *pMem = NULL;
1735 1736
  if (pReadSnap->pMem) {
    pMem = tsdbGetTbDataFromMemTable(pReadSnap->pMem, suid, uid);
1737 1738 1739
  }

  STbData *pIMem = NULL;
1740 1741
  if (pReadSnap->pIMem) {
    pIMem = tsdbGetTbDataFromMemTable(pReadSnap->pIMem, suid, uid);
1742 1743
  }

H
Hongze Cheng 已提交
1744 1745
  pIter->pTsdb = pTsdb;

1746 1747
  pIter->pSkyline = taosArrayInit(32, sizeof(TSDBKEY));

1748
  SDelFile *pDelFile = pReadSnap->fs.pDelFile;
1749 1750 1751
  if (pDelFile) {
    SDelFReader *pDelFReader;

H
Hongze Cheng 已提交
1752
    code = tsdbDelFReaderOpen(&pDelFReader, pDelFile, pTsdb);
1753 1754
    if (code) goto _err;

S
stephenkgu 已提交
1755 1756 1757
    SArray *pDelIdxArray = taosArrayInit(32, sizeof(SDelIdx));

    code = tsdbReadDelIdx(pDelFReader, pDelIdxArray);
M
Minglei Jin 已提交
1758
    if (code) {
1759
      taosArrayDestroy(pDelIdxArray);
M
Minglei Jin 已提交
1760 1761 1762
      tsdbDelFReaderClose(&pDelFReader);
      goto _err;
    }
S
stephenkgu 已提交
1763 1764

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

S
stephenkgu 已提交
1766
    code = getTableDelSkyline(pMem, pIMem, pDelFReader, delIdx, pIter->pSkyline);
1767
    if (code) {
1768
      taosArrayDestroy(pDelIdxArray);
1769 1770 1771
      tsdbDelFReaderClose(&pDelFReader);
      goto _err;
    }
1772

S
stephenkgu 已提交
1773
    taosArrayDestroy(pDelIdxArray);
1774 1775 1776 1777 1778 1779 1780 1781 1782 1783
    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};

1784
  pIter->fsLastState.state = (SFSLASTNEXTROWSTATES)SFSNEXTROW_FS;
1785
  pIter->fsLastState.pTsdb = pTsdb;
1786
  pIter->fsLastState.aDFileSet = pReadSnap->fs.aDFileSet;
1787
  pIter->fsLastState.pTSchema = pTSchema;
1788
  pIter->fsLastState.suid = suid;
1789
  pIter->fsLastState.uid = uid;
1790
  pIter->fsLastState.pLoadInfo = pLoadInfo;
1791
  pIter->fsLastState.pDataFReader = pDataFReaderLast;
1792
  pIter->fsLastState.lastTs = lastTs;
1793

1794 1795
  pIter->fsState.state = SFSNEXTROW_FS;
  pIter->fsState.pTsdb = pTsdb;
1796
  pIter->fsState.aDFileSet = pReadSnap->fs.aDFileSet;
1797
  pIter->fsState.pBlockIdxExp = &pIter->idx;
1798 1799 1800
  pIter->fsState.pTSchema = pTSchema;
  pIter->fsState.suid = suid;
  pIter->fsState.uid = uid;
1801 1802
  pIter->fsState.pLoadInfo = pLoadInfo;
  pIter->fsState.pDataFReader = pDataFReader;
1803
  pIter->fsState.lastTs = lastTs;
1804

1805 1806 1807 1808
  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};
1809
  pIter->input[3] =
1810
      (TsdbNextRowState){&pIter->fsRow, false, true, false, &pIter->fsState, getNextRowFromFS, clearNextRowFromFS};
1811 1812 1813 1814

  if (pMem) {
    pIter->memState.pMem = pMem;
    pIter->memState.state = SMEMNEXTROW_ENTER;
1815
    pIter->memState.lastTs = lastTs;
1816 1817 1818 1819 1820 1821 1822
    pIter->input[0].stop = false;
    pIter->input[0].next = true;
  }

  if (pIMem) {
    pIter->imemState.pMem = pIMem;
    pIter->imemState.state = SMEMNEXTROW_ENTER;
1823
    pIter->imemState.lastTs = lastTs;
1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835
    pIter->input[1].stop = false;
    pIter->input[1].next = true;
  }

  return code;
_err:
  return code;
}

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

1836
  for (int i = 0; i < 4; ++i) {
1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850
    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)
D
dapan1121 已提交
1851 1852
static int32_t nextRowIterGet(CacheNextRowIter *pIter, TSDBROW **ppRow, bool *pIgnoreEarlierTs, bool isLast,
                              int16_t *aCols, int nCols) {
1853
  int code = 0;
1854 1855 1856
  for (;;) {
    for (int i = 0; i < 4; ++i) {
      if (pIter->input[i].next && !pIter->input[i].stop) {
D
dapan1121 已提交
1857 1858
        code = pIter->input[i].nextRowFn(pIter->input[i].iter, &pIter->input[i].pRow, &pIter->input[i].ignoreEarlierTs,
                                         isLast, aCols, nCols);
1859
        if (code) goto _err;
1860

1861 1862 1863 1864
        if (pIter->input[i].pRow == NULL) {
          pIter->input[i].stop = true;
          pIter->input[i].next = false;
        }
1865 1866 1867
      }
    }

1868 1869
    if (pIter->input[0].stop && pIter->input[1].stop && pIter->input[2].stop && pIter->input[3].stop) {
      *ppRow = NULL;
1870 1871
      *pIgnoreEarlierTs = (pIter->input[0].ignoreEarlierTs || pIter->input[1].ignoreEarlierTs ||
                           pIter->input[2].ignoreEarlierTs || pIter->input[3].ignoreEarlierTs);
1872 1873
      return code;
    }
1874

1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890
    // 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;
          }
1891

1892 1893
          iMax[nMax] = i;
          max[nMax++] = pIter->input[i].pRow;
1894 1895
        } else {
          pIter->input[i].next = false;
1896 1897 1898 1899
        }
      }
    }

1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911
    // 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];
      }
1912

1913 1914
      pIter->input[iMax[i]].next = deleted;
    }
1915

1916 1917
    if (nMerge > 0) {
      pIter->input[iMerge[0]].next = true;
1918

1919 1920 1921
      *ppRow = merge[0];
      return code;
    }
1922 1923 1924 1925 1926 1927
  }

_err:
  return code;
}

1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941
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;
}

1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956
static int32_t initLastColArrayPartial(STSchema *pTSchema, SArray **ppColArray, int16_t *slotIds, int nCols) {
  SArray *pColArray = taosArrayInit(nCols, sizeof(SLastCol));
  if (NULL == pColArray) {
    return TSDB_CODE_OUT_OF_MEMORY;
  }

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

1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978
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);
}
1979

1980
static int32_t mergeLastRow(tb_uid_t uid, STsdb *pTsdb, bool *dup, SArray **ppColArray, SCacheRowsReader *pr) {
1981
  STSchema *pTSchema = pr->pSchema;  // metaGetTbTSchema(pTsdb->pVnode->pMeta, uid, -1, 1);
1982
  int16_t   nLastCol = pTSchema->numOfCols;
1983 1984 1985
  int16_t   iCol = 0;
  int16_t   noneCol = 0;
  bool      setNoneCol = false;
1986
  bool      hasRow = false;
1987
  bool      ignoreEarlierTs = false;
1988
  SArray   *pColArray = NULL;
1989 1990
  SColVal  *pColVal = &(SColVal){0};

1991 1992 1993 1994 1995
  int32_t code = initLastColArray(pTSchema, &pColArray);
  if (TSDB_CODE_SUCCESS != code) {
    return code;
  }

1996 1997 1998
  TSKEY lastRowTs = TSKEY_MAX;

  CacheNextRowIter iter = {0};
1999
  nextRowIterOpen(&iter, uid, pTsdb, pTSchema, pr->suid, pr->pLoadInfo, pr->pReadSnap, &pr->pDataFReader,
2000
                  &pr->pDataFReaderLast, pr->lastTs);
2001 2002 2003

  do {
    TSDBROW *pRow = NULL;
D
dapan1121 已提交
2004
    nextRowIterGet(&iter, &pRow, &ignoreEarlierTs, false, NULL, 0);
2005 2006 2007 2008 2009

    if (!pRow) {
      break;
    }

2010 2011
    hasRow = true;

2012 2013 2014 2015 2016 2017 2018
    int32_t sversion = TSDBROW_SVERSION(pRow);
    if (sversion != -1) {
      code = updateTSchema(sversion, pr, uid);
      if (TSDB_CODE_SUCCESS != code) {
        goto _err;
      }
      pTSchema = pr->pCurrSchema;
2019 2020 2021
    }
    int16_t nCol = pTSchema->numOfCols;

2022 2023
    TSKEY rowTs = TSDBROW_TS(pRow);

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

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

      for (iCol = 1; iCol < nCol; ++iCol) {
2032 2033 2034 2035 2036 2037 2038
        if (iCol >= nLastCol) {
          break;
        }
        SLastCol *pCol = taosArrayGet(pColArray, iCol);
        if (pCol->colVal.cid != pTSchema->columns[iCol].colId) {
          continue;
        }
2039 2040
        tsdbRowGetColVal(pRow, pTSchema, iCol, pColVal);

2041
        *pCol = (SLastCol){.ts = lastRowTs, .colVal = *pColVal};
2042
        if (IS_VAR_DATA_TYPE(pColVal->type) && pColVal->value.nData > 0) {
2043 2044
          pCol->colVal.value.pData = taosMemoryMalloc(pCol->colVal.value.nData);
          if (pCol->colVal.value.pData == NULL) {
M
Minglei Jin 已提交
2045 2046 2047 2048
            terrno = TSDB_CODE_OUT_OF_MEMORY;
            code = TSDB_CODE_OUT_OF_MEMORY;
            goto _err;
          }
2049
          memcpy(pCol->colVal.value.pData, pColVal->value.pData, pColVal->value.nData);
2050 2051
        }

H
Hongze Cheng 已提交
2052
        if (COL_VAL_IS_NONE(pColVal) && !setNoneCol) {
2053 2054 2055 2056 2057
          noneCol = iCol;
          setNoneCol = true;
        }
      }
      if (!setNoneCol) {
2058
        // done, goto return pColArray
2059 2060 2061 2062 2063 2064
        break;
      } else {
        continue;
      }
    }

2065 2066
    if ((rowTs < lastRowTs)) {
      // done, goto return pColArray
2067 2068 2069 2070 2071 2072 2073 2074 2075 2076
      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 已提交
2077
      if (COL_VAL_IS_NONE(tColVal) && !COL_VAL_IS_NONE(pColVal)) {
2078
        SLastCol lastCol = {.ts = rowTs, .colVal = *pColVal};
2079
        if (IS_VAR_DATA_TYPE(pColVal->type) && pColVal->value.nData > 0) {
2080 2081 2082 2083
          SLastCol *pLastCol = (SLastCol *)taosArrayGet(pColArray, iCol);
          taosMemoryFree(pLastCol->colVal.value.pData);

          lastCol.colVal.value.pData = taosMemoryMalloc(lastCol.colVal.value.nData);
M
Minglei Jin 已提交
2084 2085 2086 2087 2088
          if (lastCol.colVal.value.pData == NULL) {
            terrno = TSDB_CODE_OUT_OF_MEMORY;
            code = TSDB_CODE_OUT_OF_MEMORY;
            goto _err;
          }
2089 2090 2091 2092
          memcpy(lastCol.colVal.value.pData, pColVal->value.pData, pColVal->value.nData);
        }

        taosArraySet(pColArray, iCol, &lastCol);
H
Hongze Cheng 已提交
2093
      } else if (COL_VAL_IS_NONE(tColVal) && COL_VAL_IS_NONE(pColVal) && !setNoneCol) {
2094 2095 2096 2097 2098 2099 2100 2101
        noneCol = iCol;
        setNoneCol = true;
      }
    }
  } while (setNoneCol);

  // build the result ts row here
  *dup = false;
2102 2103 2104 2105
  // if (taosArrayGetSize(pColArray) != nCol) {
  //*ppColArray = NULL;
  // taosArrayDestroy(pColArray);
  //} else {
2106
  if (!hasRow) {
2107 2108 2109 2110 2111 2112
    if (ignoreEarlierTs) {
      taosArrayDestroy(pColArray);
      pColArray = NULL;
    } else {
      taosArrayClear(pColArray);
    }
2113
  }
2114 2115
  *ppColArray = pColArray;
  //}
2116 2117

  nextRowIterClose(&iter);
2118
  // taosMemoryFreeClear(pTSchema);
2119 2120 2121 2122 2123
  return code;

_err:
  nextRowIterClose(&iter);
  taosArrayDestroy(pColArray);
2124
  // taosMemoryFreeClear(pTSchema);
2125 2126 2127
  return code;
}

2128
static int32_t mergeLast(tb_uid_t uid, STsdb *pTsdb, SArray **ppLastArray, SCacheRowsReader *pr) {
2129
  STSchema *pTSchema = pr->pSchema;  // metaGetTbTSchema(pTsdb->pVnode->pMeta, uid, -1, 1);
2130
  int16_t   nLastCol = pTSchema->numOfCols;
2131 2132
  int16_t   noneCol = 0;
  bool      setNoneCol = false;
2133
  bool      hasRow = false;
2134
  bool      ignoreEarlierTs = false;
2135
  SArray   *pColArray = NULL;
2136
  SColVal  *pColVal = &(SColVal){0};
D
dapan1121 已提交
2137
  int16_t   nCols = nLastCol;
2138

2139 2140 2141 2142
  int32_t code = initLastColArray(pTSchema, &pColArray);
  if (TSDB_CODE_SUCCESS != code) {
    return code;
  }
D
dapan1121 已提交
2143 2144 2145 2146 2147 2148 2149 2150 2151
  SArray *aColArray = taosArrayInit(nCols, sizeof(int16_t));
  if (NULL == aColArray) {
    taosArrayDestroy(pColArray);

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

2153 2154 2155
  TSKEY lastRowTs = TSKEY_MAX;

  CacheNextRowIter iter = {0};
2156
  nextRowIterOpen(&iter, uid, pTsdb, pTSchema, pr->suid, pr->pLoadInfo, pr->pReadSnap, &pr->pDataFReader,
2157
                  &pr->pDataFReaderLast, pr->lastTs);
2158 2159 2160

  do {
    TSDBROW *pRow = NULL;
D
dapan1121 已提交
2161
    nextRowIterGet(&iter, &pRow, &ignoreEarlierTs, true, TARRAY_DATA(aColArray), TARRAY_SIZE(aColArray));
2162 2163 2164 2165 2166

    if (!pRow) {
      break;
    }

2167 2168
    hasRow = true;

2169 2170 2171 2172 2173 2174 2175
    int32_t sversion = TSDBROW_SVERSION(pRow);
    if (sversion != -1) {
      code = updateTSchema(sversion, pr, uid);
      if (TSDB_CODE_SUCCESS != code) {
        goto _err;
      }
      pTSchema = pr->pCurrSchema;
2176 2177 2178
    }
    int16_t nCol = pTSchema->numOfCols;

2179 2180 2181 2182 2183 2184
    TSKEY rowTs = TSDBROW_TS(pRow);

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

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

2188 2189 2190 2191 2192 2193 2194 2195
      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;
        }
2196 2197
        tsdbRowGetColVal(pRow, pTSchema, iCol, pColVal);

2198
        *pCol = (SLastCol){.ts = lastRowTs, .colVal = *pColVal};
2199
        if (IS_VAR_DATA_TYPE(pColVal->type) && pColVal->value.nData > 0) {
2200 2201
          pCol->colVal.value.pData = taosMemoryMalloc(pCol->colVal.value.nData);
          if (pCol->colVal.value.pData == NULL) {
M
Minglei Jin 已提交
2202 2203 2204 2205
            terrno = TSDB_CODE_OUT_OF_MEMORY;
            code = TSDB_CODE_OUT_OF_MEMORY;
            goto _err;
          }
2206
          memcpy(pCol->colVal.value.pData, pColVal->value.pData, pColVal->value.nData);
2207 2208
        }

D
dapan1121 已提交
2209 2210 2211 2212 2213 2214 2215 2216
        if (!COL_VAL_IS_VALUE(pColVal)) {
          if (!setNoneCol) {
            noneCol = iCol;
            setNoneCol = true;
          }
        } else {
          int32_t aColIndex = taosArraySearchIdx(aColArray, &pColVal->cid, compareInt16Val, TD_EQ);
          taosArrayRemove(aColArray, aColIndex);
2217 2218 2219
        }
      }
      if (!setNoneCol) {
2220
        // done, goto return pColArray
2221 2222 2223 2224 2225
        break;
      } else {
        continue;
      }
    }
2226

2227 2228
    // merge into pColArray
    setNoneCol = false;
2229 2230 2231 2232
    for (int16_t iCol = noneCol; iCol < nCol; ++iCol) {
      if (iCol >= nLastCol) {
        break;
      }
2233
      // high version's column value
2234
      SLastCol *lastColVal = (SLastCol *)taosArrayGet(pColArray, iCol);
2235 2236 2237 2238
      if (lastColVal->colVal.cid != pTSchema->columns[iCol].colId) {
        continue;
      }
      SColVal *tColVal = &lastColVal->colVal;
2239 2240

      tsdbRowGetColVal(pRow, pTSchema, iCol, pColVal);
H
Hongze Cheng 已提交
2241
      if (!COL_VAL_IS_VALUE(tColVal) && COL_VAL_IS_VALUE(pColVal)) {
2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351
        SLastCol lastCol = {.ts = rowTs, .colVal = *pColVal};
        if (IS_VAR_DATA_TYPE(pColVal->type) && pColVal->value.nData > 0) {
          SLastCol *pLastCol = (SLastCol *)taosArrayGet(pColArray, iCol);
          taosMemoryFree(pLastCol->colVal.value.pData);

          lastCol.colVal.value.pData = taosMemoryMalloc(lastCol.colVal.value.nData);
          if (lastCol.colVal.value.pData == NULL) {
            terrno = TSDB_CODE_OUT_OF_MEMORY;
            code = TSDB_CODE_OUT_OF_MEMORY;
            goto _err;
          }
          memcpy(lastCol.colVal.value.pData, pColVal->value.pData, pColVal->value.nData);
        }

        taosArraySet(pColArray, iCol, &lastCol);
        int32_t aColIndex = taosArraySearchIdx(aColArray, &lastCol.colVal.cid, compareInt16Val, TD_EQ);
        taosArrayRemove(aColArray, aColIndex);
      } else if (!COL_VAL_IS_VALUE(tColVal) && !COL_VAL_IS_VALUE(pColVal) && !setNoneCol) {
        noneCol = iCol;
        setNoneCol = true;
      }
    }
  } while (setNoneCol);

  // if (taosArrayGetSize(pColArray) <= 0) {
  //*ppLastArray = NULL;
  // taosArrayDestroy(pColArray);
  //} else {
  if (!hasRow) {
    if (ignoreEarlierTs) {
      taosArrayDestroy(pColArray);
      pColArray = NULL;
    } else {
      taosArrayClear(pColArray);
    }
  }
  *ppLastArray = pColArray;
  //}

  nextRowIterClose(&iter);
  taosArrayDestroy(aColArray);
  // taosMemoryFreeClear(pTSchema);
  return code;

_err:
  nextRowIterClose(&iter);
  // taosMemoryFreeClear(pTSchema);
  *ppLastArray = NULL;
  taosArrayDestroy(pColArray);
  taosArrayDestroy(aColArray);
  return code;
}

static int32_t mergeLastCid(tb_uid_t uid, STsdb *pTsdb, SArray **ppLastArray, SCacheRowsReader *pr, int16_t *aCols,
                            int nCols, int16_t *slotIds) {
  STSchema *pTSchema = pr->pSchema;  // metaGetTbTSchema(pTsdb->pVnode->pMeta, uid, -1, 1);
  int16_t   nLastCol = nCols;
  int16_t   noneCol = 0;
  bool      setNoneCol = false;
  bool      hasRow = false;
  bool      ignoreEarlierTs = false;
  SArray   *pColArray = NULL;
  SColVal  *pColVal = &(SColVal){0};

  int32_t code = initLastColArrayPartial(pTSchema, &pColArray, slotIds, nCols);
  if (TSDB_CODE_SUCCESS != code) {
    return code;
  }
  SArray *aColArray = taosArrayInit(nCols, sizeof(int16_t));
  if (NULL == aColArray) {
    taosArrayDestroy(pColArray);

    return TSDB_CODE_OUT_OF_MEMORY;
  }

  for (int i = 0; i < nCols; ++i) {
    taosArrayPush(aColArray, &aCols[i]);
  }

  TSKEY lastRowTs = TSKEY_MAX;

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

  do {
    TSDBROW *pRow = NULL;
    nextRowIterGet(&iter, &pRow, &ignoreEarlierTs, true, TARRAY_DATA(aColArray), TARRAY_SIZE(aColArray));

    if (!pRow) {
      break;
    }

    hasRow = true;

    int32_t sversion = TSDBROW_SVERSION(pRow);
    if (sversion != -1) {
      code = updateTSchema(sversion, pr, uid);
      if (TSDB_CODE_SUCCESS != code) {
        goto _err;
      }
      pTSchema = pr->pCurrSchema;
    }
    // int16_t nCol = pTSchema->numOfCols;

    TSKEY rowTs = TSDBROW_TS(pRow);

    if (lastRowTs == TSKEY_MAX) {
      lastRowTs = rowTs;

2352
      for (int16_t iCol = noneCol; iCol < nCols; ++iCol) {
2353 2354 2355 2356 2357 2358 2359
        if (iCol >= nLastCol) {
          break;
        }
        SLastCol *pCol = taosArrayGet(pColArray, iCol);
        if (pCol->colVal.cid != pTSchema->columns[slotIds[iCol]].colId) {
          continue;
        }
2360 2361 2362
        if (slotIds[iCol] == 0) {
          STColumn *pTColumn = &pTSchema->columns[0];

2363 2364
          *pColVal = COL_VAL_VALUE(pTColumn->colId, pTColumn->type, (SValue){.val = rowTs});
          taosArraySet(pColArray, 0, &(SLastCol){.ts = rowTs, .colVal = *pColVal});
2365 2366
          continue;
        }
2367 2368
        tsdbRowGetColVal(pRow, pTSchema, slotIds[iCol], pColVal);

2369
        *pCol = (SLastCol){.ts = rowTs, .colVal = *pColVal};
2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414
        if (IS_VAR_DATA_TYPE(pColVal->type) && pColVal->value.nData > 0) {
          pCol->colVal.value.pData = taosMemoryMalloc(pCol->colVal.value.nData);
          if (pCol->colVal.value.pData == NULL) {
            terrno = TSDB_CODE_OUT_OF_MEMORY;
            code = TSDB_CODE_OUT_OF_MEMORY;
            goto _err;
          }
          memcpy(pCol->colVal.value.pData, pColVal->value.pData, pColVal->value.nData);
        }

        if (!COL_VAL_IS_VALUE(pColVal)) {
          if (!setNoneCol) {
            noneCol = iCol;
            setNoneCol = true;
          }
        } else {
          int32_t aColIndex = taosArraySearchIdx(aColArray, &pColVal->cid, compareInt16Val, TD_EQ);
          if (aColIndex >= 0) {
            taosArrayRemove(aColArray, aColIndex);
          }
        }
      }
      if (!setNoneCol) {
        // done, goto return pColArray
        break;
      } else {
        continue;
      }
    }

    // merge into pColArray
    setNoneCol = false;
    for (int16_t iCol = noneCol; iCol < nCols; ++iCol) {
      if (iCol >= nLastCol) {
        break;
      }
      // high version's column value
      SLastCol *lastColVal = (SLastCol *)taosArrayGet(pColArray, iCol);
      if (lastColVal->colVal.cid != pTSchema->columns[slotIds[iCol]].colId) {
        continue;
      }
      SColVal *tColVal = &lastColVal->colVal;

      tsdbRowGetColVal(pRow, pTSchema, slotIds[iCol], pColVal);
      if (!COL_VAL_IS_VALUE(tColVal) && COL_VAL_IS_VALUE(pColVal)) {
2415
        SLastCol lastCol = {.ts = rowTs, .colVal = *pColVal};
2416
        if (IS_VAR_DATA_TYPE(pColVal->type) && pColVal->value.nData > 0) {
2417 2418 2419 2420
          SLastCol *pLastCol = (SLastCol *)taosArrayGet(pColArray, iCol);
          taosMemoryFree(pLastCol->colVal.value.pData);

          lastCol.colVal.value.pData = taosMemoryMalloc(lastCol.colVal.value.nData);
M
Minglei Jin 已提交
2421 2422 2423 2424 2425
          if (lastCol.colVal.value.pData == NULL) {
            terrno = TSDB_CODE_OUT_OF_MEMORY;
            code = TSDB_CODE_OUT_OF_MEMORY;
            goto _err;
          }
2426 2427 2428 2429
          memcpy(lastCol.colVal.value.pData, pColVal->value.pData, pColVal->value.nData);
        }

        taosArraySet(pColArray, iCol, &lastCol);
D
dapan1121 已提交
2430 2431
        int32_t aColIndex = taosArraySearchIdx(aColArray, &lastCol.colVal.cid, compareInt16Val, TD_EQ);
        taosArrayRemove(aColArray, aColIndex);
H
Hongze Cheng 已提交
2432
      } else if (!COL_VAL_IS_VALUE(tColVal) && !COL_VAL_IS_VALUE(pColVal) && !setNoneCol) {
2433 2434 2435 2436 2437 2438
        noneCol = iCol;
        setNoneCol = true;
      }
    }
  } while (setNoneCol);

2439
  if (!hasRow) {
2440 2441 2442 2443 2444 2445
    if (ignoreEarlierTs) {
      taosArrayDestroy(pColArray);
      pColArray = NULL;
    } else {
      taosArrayClear(pColArray);
    }
2446
  }
2447
  *ppLastArray = pColArray;
2448 2449

  nextRowIterClose(&iter);
D
dapan1121 已提交
2450
  taosArrayDestroy(aColArray);
2451

2452 2453 2454 2455
  return code;

_err:
  nextRowIterClose(&iter);
2456
  // taosMemoryFreeClear(pTSchema);
2457 2458
  *ppLastArray = NULL;
  taosArrayDestroy(pColArray);
D
dapan1121 已提交
2459
  taosArrayDestroy(aColArray);
2460 2461 2462
  return code;
}

2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630
static int32_t mergeLastRowCid(tb_uid_t uid, STsdb *pTsdb, SArray **ppLastArray, SCacheRowsReader *pr, int16_t *aCols,
                               int nCols, int16_t *slotIds) {
  STSchema *pTSchema = pr->pSchema;  // metaGetTbTSchema(pTsdb->pVnode->pMeta, uid, -1, 1);
  int16_t   nLastCol = nCols;
  int16_t   noneCol = 0;
  bool      setNoneCol = false;
  bool      hasRow = false;
  bool      ignoreEarlierTs = false;
  SArray   *pColArray = NULL;
  SColVal  *pColVal = &(SColVal){0};

  int32_t code = initLastColArrayPartial(pTSchema, &pColArray, slotIds, nCols);
  if (TSDB_CODE_SUCCESS != code) {
    return code;
  }
  SArray *aColArray = taosArrayInit(nCols, sizeof(int16_t));
  if (NULL == aColArray) {
    taosArrayDestroy(pColArray);

    return TSDB_CODE_OUT_OF_MEMORY;
  }

  for (int i = 0; i < nCols; ++i) {
    taosArrayPush(aColArray, &aCols[i]);
  }

  TSKEY lastRowTs = TSKEY_MAX;

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

  do {
    TSDBROW *pRow = NULL;
    nextRowIterGet(&iter, &pRow, &ignoreEarlierTs, true, TARRAY_DATA(aColArray), TARRAY_SIZE(aColArray));

    if (!pRow) {
      break;
    }

    hasRow = true;

    int32_t sversion = TSDBROW_SVERSION(pRow);
    if (sversion != -1) {
      code = updateTSchema(sversion, pr, uid);
      if (TSDB_CODE_SUCCESS != code) {
        goto _err;
      }
      pTSchema = pr->pCurrSchema;
    }
    // int16_t nCol = pTSchema->numOfCols;

    TSKEY rowTs = TSDBROW_TS(pRow);

    if (lastRowTs == TSKEY_MAX) {
      lastRowTs = rowTs;

      for (int16_t iCol = noneCol; iCol < nCols; ++iCol) {
        if (iCol >= nLastCol) {
          break;
        }
        SLastCol *pCol = taosArrayGet(pColArray, iCol);
        if (pCol->colVal.cid != pTSchema->columns[slotIds[iCol]].colId) {
          continue;
        }
        if (slotIds[iCol] == 0) {
          STColumn *pTColumn = &pTSchema->columns[0];

          *pColVal = COL_VAL_VALUE(pTColumn->colId, pTColumn->type, (SValue){.val = rowTs});
          taosArraySet(pColArray, 0, &(SLastCol){.ts = rowTs, .colVal = *pColVal});
          continue;
        }
        tsdbRowGetColVal(pRow, pTSchema, slotIds[iCol], pColVal);

        *pCol = (SLastCol){.ts = rowTs, .colVal = *pColVal};
        if (IS_VAR_DATA_TYPE(pColVal->type) && pColVal->value.nData > 0) {
          pCol->colVal.value.pData = taosMemoryMalloc(pCol->colVal.value.nData);
          if (pCol->colVal.value.pData == NULL) {
            terrno = TSDB_CODE_OUT_OF_MEMORY;
            code = TSDB_CODE_OUT_OF_MEMORY;
            goto _err;
          }
          memcpy(pCol->colVal.value.pData, pColVal->value.pData, pColVal->value.nData);
        }

        if (COL_VAL_IS_NONE(pColVal)) {
          if (!setNoneCol) {
            noneCol = iCol;
            setNoneCol = true;
          }
        } else {
          int32_t aColIndex = taosArraySearchIdx(aColArray, &pColVal->cid, compareInt16Val, TD_EQ);
          if (aColIndex >= 0) {
            taosArrayRemove(aColArray, aColIndex);
          }
        }
      }
      if (!setNoneCol) {
        // done, goto return pColArray
        break;
      } else {
        continue;
      }
    }

    // merge into pColArray
    setNoneCol = false;
    for (int16_t iCol = noneCol; iCol < nCols; ++iCol) {
      if (iCol >= nLastCol) {
        break;
      }
      // high version's column value
      SLastCol *lastColVal = (SLastCol *)taosArrayGet(pColArray, iCol);
      if (lastColVal->colVal.cid != pTSchema->columns[slotIds[iCol]].colId) {
        continue;
      }
      SColVal *tColVal = &lastColVal->colVal;

      tsdbRowGetColVal(pRow, pTSchema, slotIds[iCol], pColVal);
      if (COL_VAL_IS_NONE(tColVal) && !COL_VAL_IS_NONE(pColVal)) {
        SLastCol lastCol = {.ts = rowTs, .colVal = *pColVal};
        if (IS_VAR_DATA_TYPE(pColVal->type) && pColVal->value.nData > 0) {
          SLastCol *pLastCol = (SLastCol *)taosArrayGet(pColArray, iCol);
          taosMemoryFree(pLastCol->colVal.value.pData);

          lastCol.colVal.value.pData = taosMemoryMalloc(lastCol.colVal.value.nData);
          if (lastCol.colVal.value.pData == NULL) {
            terrno = TSDB_CODE_OUT_OF_MEMORY;
            code = TSDB_CODE_OUT_OF_MEMORY;
            goto _err;
          }
          memcpy(lastCol.colVal.value.pData, pColVal->value.pData, pColVal->value.nData);
        }

        taosArraySet(pColArray, iCol, &lastCol);
        int32_t aColIndex = taosArraySearchIdx(aColArray, &lastCol.colVal.cid, compareInt16Val, TD_EQ);
        taosArrayRemove(aColArray, aColIndex);
      } else if (COL_VAL_IS_NONE(tColVal) && !COL_VAL_IS_NONE(pColVal) && !setNoneCol) {
        noneCol = iCol;
        setNoneCol = true;
      }
    }
  } while (setNoneCol);

  if (!hasRow) {
    if (ignoreEarlierTs) {
      taosArrayDestroy(pColArray);
      pColArray = NULL;
    } else {
      taosArrayClear(pColArray);
    }
  }
  *ppLastArray = pColArray;

  nextRowIterClose(&iter);
  taosArrayDestroy(aColArray);

  return code;

_err:
  nextRowIterClose(&iter);

  *ppLastArray = NULL;
  taosArrayDestroy(pColArray);
  taosArrayDestroy(aColArray);
  return code;
}

2631
int32_t tsdbCacheGetLastrowH(SLRUCache *pCache, tb_uid_t uid, SCacheRowsReader *pr, LRUHandle **handle) {
2632 2633 2634 2635
  int32_t code = 0;
  char    key[32] = {0};
  int     keyLen = 0;

2636
  //  getTableCacheKeyS(uid, "lr", key, &keyLen);
2637
  getTableCacheKey(uid, 0, key, &keyLen);
2638
  LRUHandle *h = taosLRUCacheLookup(pCache, key, keyLen);
2639
  if (!h) {
2640
    STsdb *pTsdb = pr->pVnode->pTsdb;
2641 2642 2643 2644
    taosThreadMutexLock(&pTsdb->lruMutex);

    h = taosLRUCacheLookup(pCache, key, keyLen);
    if (!h) {
2645
      SArray *pArray = NULL;
2646
      bool    dup = false;  // which is always false for now
2647
      code = mergeLastRow(uid, pTsdb, &dup, &pArray, pr);
2648 2649
      // if table's empty or error or ignore ignore earlier ts, set handle NULL and return
      if (code < 0 || pArray == NULL) {
2650 2651
        if (!dup && pArray) {
          taosArrayDestroy(pArray);
2652 2653
        }

M
Minglei Jin 已提交
2654 2655
        taosThreadMutexUnlock(&pTsdb->lruMutex);

2656
        *handle = NULL;
M
Minglei Jin 已提交
2657

2658
        return 0;
2659 2660
      }

M
Minglei Jin 已提交
2661
      size_t              charge = pArray->capacity * pArray->elemSize + sizeof(*pArray);
2662
      _taos_lru_deleter_t deleter = deleteTableCacheLast;
2663
      LRUStatus status = taosLRUCacheInsert(pCache, key, keyLen, pArray, charge, deleter, &h, TAOS_LRU_PRIORITY_LOW);
2664 2665 2666
      if (status != TAOS_LRU_STATUS_OK) {
        code = -1;
      }
2667
    }
2668
    taosThreadMutexUnlock(&pTsdb->lruMutex);
2669 2670 2671 2672 2673 2674
  }

  *handle = h;

  return code;
}
2675

2676
int32_t tsdbCacheGetLastH(SLRUCache *pCache, tb_uid_t uid, SCacheRowsReader *pr, LRUHandle **handle) {
2677 2678 2679 2680
  int32_t code = 0;
  char    key[32] = {0};
  int     keyLen = 0;

2681
  // getTableCacheKeyS(uid, "l", key, &keyLen);
2682
  getTableCacheKey(uid, 1, key, &keyLen);
2683
  LRUHandle *h = taosLRUCacheLookup(pCache, key, keyLen);
2684
  if (!h) {
2685
    STsdb *pTsdb = pr->pVnode->pTsdb;
2686
    taosThreadMutexLock(&pTsdb->lruMutex);
2687

2688
    h = taosLRUCacheLookup(pCache, key, keyLen);
2689 2690
    if (!h) {
      SArray *pLastArray = NULL;
2691
      code = mergeLast(uid, pTsdb, &pLastArray, pr);
2692 2693
      // if table's empty or error or ignore ignore earlier ts, set handle NULL and return
      if (code < 0 || pLastArray == NULL) {
2694 2695
        taosThreadMutexUnlock(&pTsdb->lruMutex);

2696 2697 2698 2699
        *handle = NULL;
        return 0;
      }

M
Minglei Jin 已提交
2700
      size_t              charge = pLastArray->capacity * pLastArray->elemSize + sizeof(*pLastArray);
2701
      _taos_lru_deleter_t deleter = deleteTableCacheLast;
M
Minglei Jin 已提交
2702
      LRUStatus           status =
2703
          taosLRUCacheInsert(pCache, key, keyLen, pLastArray, charge, deleter, &h, TAOS_LRU_PRIORITY_LOW);
2704 2705 2706
      if (status != TAOS_LRU_STATUS_OK) {
        code = -1;
      }
2707
    }
2708
    taosThreadMutexUnlock(&pTsdb->lruMutex);
2709 2710 2711
  }

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

2713 2714 2715
  return code;
}

M
Minglei Jin 已提交
2716 2717 2718 2719 2720 2721 2722
int32_t tsdbCacheRelease(SLRUCache *pCache, LRUHandle *h) {
  int32_t code = 0;

  taosLRUCacheRelease(pCache, h, false);

  return code;
}
2723 2724 2725 2726 2727 2728

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

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

2730 2731 2732 2733 2734 2735 2736 2737
size_t tsdbCacheGetUsage(SVnode *pVnode) {
  size_t usage = 0;
  if (pVnode->pTsdb != NULL) {
    usage = taosLRUCacheGetUsage(pVnode->pTsdb->lruCache);
  }

  return usage;
}
2738

D
dapan1121 已提交
2739 2740 2741 2742 2743 2744 2745 2746 2747
int32_t tsdbCacheGetElems(SVnode *pVnode) {
  int32_t elems = 0;
  if (pVnode->pTsdb != NULL) {
    elems = taosLRUCacheGetElems(pVnode->pTsdb->lruCache);
  }

  return elems;
}

2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815
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);
  }

2816
  tsdbTrace("bi cache:%p, ref", pCache);
2817 2818 2819 2820 2821 2822 2823 2824 2825
  *handle = h;

  return code;
}

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

  taosLRUCacheRelease(pCache, h, false);
2826
  tsdbTrace("bi cache:%p, release", pCache);
2827 2828 2829

  return code;
}