tsdbCache.c 69.8 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
  rocksdb_writebatch_t *writebatch = rocksdb_writebatch_create();

  pTsdb->rCache.writebatch = writebatch;
104 105 106 107 108
  pTsdb->rCache.options = options;
  pTsdb->rCache.writeoptions = writeoptions;
  pTsdb->rCache.readoptions = readoptions;
  pTsdb->rCache.db = db;

109 110
  taosThreadMutexInit(&pTsdb->rCache.rMutex, NULL);

111 112 113 114 115 116 117 118 119 120 121 122 123 124
  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);
125
  rocksdb_writebatch_destroy(pTsdb->rCache.writebatch);
126 127 128
  rocksdb_readoptions_destroy(pTsdb->rCache.readoptions);
  rocksdb_writeoptions_destroy(pTsdb->rCache.writeoptions);
  rocksdb_options_destroy(pTsdb->rCache.options);
129
  taosThreadMutexDestroy(&pTsdb->rCache.rMutex);
130 131
}

132
SLastCol *tsdbCacheDeserialize(char const *value) {
133 134 135 136
  if (!value) {
    return NULL;
  }

137 138 139
  SLastCol *pLastCol = (SLastCol *)value;
  SColVal  *pColVal = &pLastCol->colVal;
  if (IS_VAR_DATA_TYPE(pColVal->type)) {
140
    pColVal->value.pData = (char *)value + sizeof(*pLastCol);
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
  }

  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);
    if (pColVal->value.nData) {
      memcpy(pColVal->value.pData, pVal, pColVal->value.nData);
    }
  }
  *size = length;
}

int32_t tsdbCacheUpdate(STsdb *pTsdb, tb_uid_t suid, tb_uid_t uid, TSDBROW *pRow) {
166 167
  int32_t code = 0;

168 169 170 171 172 173 174 175 176 177 178 179
  // 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));

180 181 182 183
  STSDBRowIter iter = {0};
  tsdbRowIterOpen(&iter, pRow, pTSchema);

  for (SColVal *pColVal = tsdbRowIterNext(&iter); pColVal; pColVal = tsdbRowIterNext(&iter)) {
M
Minglei Jin 已提交
184
    /*
185 186 187 188 189 190 191 192 193 194 195 196 197
    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);
      }
198
    }
M
Minglei Jin 已提交
199
    */
200
    taosArrayPush(aColVal, pColVal);
201 202 203 204
  }

  tsdbRowClose(&iter);

205 206 207 208 209 210
  // 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);
211
    int16_t  cid = pColVal->cid;
212 213

    char *keys = taosMemoryCalloc(2, ROCKS_KEY_LEN);
214
    int   last_key_len = snprintf(keys, ROCKS_KEY_LEN, "%" PRIi64 ":%" PRIi16 ":last", uid, cid);
215 216 217
    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));
    }
218
    int lr_key_len = snprintf(keys + ROCKS_KEY_LEN, ROCKS_KEY_LEN, "%" PRIi64 ":%" PRIi16 ":last_row", uid, cid);
219 220 221 222 223 224 225 226 227 228 229
    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 *));
230
  taosThreadMutexLock(&pTsdb->rCache.rMutex);
231 232 233 234 235
  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 已提交
236 237 238
  for (int i = 0; i < num_keys * 2; ++i) {
    rocksdb_free(errs[i]);
  }
239 240 241 242 243 244 245 246 247
  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)) {
248
      SLastCol *pLastCol = tsdbCacheDeserialize(values_list[i]);
249 250 251 252 253 254 255 256 257 258 259 260 261

      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 已提交
262
      SLastCol *pLastCol = tsdbCacheDeserialize(values_list[i + num_keys]);
263 264 265 266 267 268 269 270 271 272 273

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

    rocksdb_free(values_list[i]);
M
Minglei Jin 已提交
276
    rocksdb_free(values_list[i + num_keys]);
277 278 279 280 281 282 283 284 285
  }
  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);
286
  }
287
  taosThreadMutexUnlock(&pTsdb->rCache.rMutex);
288
  rocksdb_writebatch_clear(wb);
289

290 291 292
_exit:
  taosArrayDestroy(aColVal);
  taosMemoryFree(pTSchema);
293 294 295
  return code;
}

M
Minglei Jin 已提交
296
int32_t tsdbCacheGet(STsdb *pTsdb, tb_uid_t uid, SArray *pLastArray, SCacheRowsReader *pr, char const *lstring) {
297 298 299
  int32_t code = 0;

  SArray *pCidList = pr->pCidList;
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
  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 已提交
322
    rocksdb_free(errs[i]);
323 324 325 326 327 328 329
  }
  taosMemoryFree(keys_list);
  taosMemoryFree(keys_list_sizes);
  taosMemoryFree(errs);

  for (int i = 0; i < num_keys; ++i) {
    SLastCol *pLastCol = tsdbCacheDeserialize(values_list[i]);
330 331
    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 已提交
332 333 334 335
    if (pLastCol) {
      SColVal *pColVal = &pLastCol->colVal;
      if (IS_VAR_DATA_TYPE(pColVal->type)) {
        uint8_t *pVal = pColVal->value.pData;
336
        pColVal->value.pData = taosMemoryMalloc(pColVal->value.nData);
M
Minglei Jin 已提交
337 338 339 340 341 342
        if (pColVal->value.nData) {
          memcpy(pColVal->value.pData, pVal, pColVal->value.nData);
        }
      }
    } else {
      // recalc: load from tsdb
343

M
Minglei Jin 已提交
344
      // still null, then make up a null col value
345
      pLastCol = &noneCol;
M
Minglei Jin 已提交
346 347 348

      // maybe store it back to rocks cache
    }
349 350 351 352 353 354
    taosArrayPush(pLastArray, pLastCol);

    taosMemoryFree(values_list[i]);
  }
  taosMemoryFree(values_list);
  taosMemoryFree(values_list_sizes);
355 356 357 358

  return code;
}

359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
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) {
409 410
    SLastCol *pLastCol = tsdbCacheDeserialize(values_list[i]);
    if (NULL != pLastCol && (pLastCol->ts <= eKey && pLastCol->ts >= sKey)) {
411 412 413 414 415
      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);
    }

416 417
    pLastCol = tsdbCacheDeserialize(values_list[i + num_keys]);
    if (NULL != pLastCol && (pLastCol->ts <= eKey && pLastCol->ts >= sKey)) {
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
      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;
}

444
int32_t tsdbOpenCache(STsdb *pTsdb) {
H
Hongze Cheng 已提交
445
  int32_t    code = 0;
446
  SLRUCache *pCache = NULL;
447
  size_t     cfgCapacity = pTsdb->pVnode->config.cacheLastSize * 1024 * 1024;
448

449
  pCache = taosLRUCacheInit(cfgCapacity, 1, .5);
450 451 452 453 454
  if (pCache == NULL) {
    code = TSDB_CODE_OUT_OF_MEMORY;
    goto _err;
  }

455 456 457 458 459 460
  code = tsdbOpenBICache(pTsdb);
  if (code != TSDB_CODE_SUCCESS) {
    code = TSDB_CODE_OUT_OF_MEMORY;
    goto _err;
  }

461 462 463 464 465 466
  code = tsdbOpenRocksCache(pTsdb);
  if (code != TSDB_CODE_SUCCESS) {
    code = TSDB_CODE_OUT_OF_MEMORY;
    goto _err;
  }

467
  taosLRUCacheSetStrictCapacity(pCache, false);
468

469 470
  taosThreadMutexInit(&pTsdb->lruMutex, NULL);

471 472 473 474 475
_err:
  pTsdb->lruCache = pCache;
  return code;
}

476 477
void tsdbCloseCache(STsdb *pTsdb) {
  SLRUCache *pCache = pTsdb->lruCache;
478 479 480 481
  if (pCache) {
    taosLRUCacheEraseUnrefEntries(pCache);

    taosLRUCacheCleanup(pCache);
482 483

    taosThreadMutexDestroy(&pTsdb->lruMutex);
484
  }
485 486

  tsdbCloseBICache(pTsdb);
487
  tsdbCloseRocksCache(pTsdb);
488 489
}

490 491 492 493 494 495 496 497 498 499
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);
}

500 501 502 503 504
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);
505
    if (IS_VAR_DATA_TYPE(pLastCol->colVal.type) && pLastCol->colVal.value.nData > 0) {
506 507 508 509 510 511
      taosMemoryFree(pLastCol->colVal.value.pData);
    }
  }

  taosArrayDestroy(value);
}
512

513
int32_t tsdbCacheDeleteLastrow(SLRUCache *pCache, tb_uid_t uid, TSKEY eKey) {
514
  int32_t code = 0;
515 516 517

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

519 520
  // getTableCacheKey(uid, "lr", key, &keyLen);
  getTableCacheKey(uid, 0, key, &keyLen);
521 522
  LRUHandle *h = taosLRUCacheLookup(pCache, key, keyLen);
  if (h) {
523 524 525 526 527 528 529 530 531 532 533 534
    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;
      }
    }

535
    taosLRUCacheRelease(pCache, h, invalidate);
536
    if (invalidate) {
537
      taosLRUCacheErase(pCache, key, keyLen);
538 539 540 541 542 543
    }
  }

  return code;
}

544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565
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;
      }
    }

566
    taosLRUCacheRelease(pCache, h, invalidate);
567
    if (invalidate) {
568
      taosLRUCacheErase(pCache, key, keyLen);
569 570 571 572 573
    }
  }

  return code;
}
574
/*
575
int32_t tsdbCacheDelete(SLRUCache *pCache, tb_uid_t uid, TSKEY eKey) {
576 577 578 579
  int32_t code = 0;
  char    key[32] = {0};
  int     keyLen = 0;

580 581 582 583
  // getTableCacheKey(uid, "lr", key, &keyLen);
  getTableCacheKey(uid, 0, key, &keyLen);
  LRUHandle *h = taosLRUCacheLookup(pCache, key, keyLen);
  if (h) {
584 585 586 587 588 589 590 591 592 593 594 595 596
    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) {
597 598 599 600 601 602
      taosLRUCacheRelease(pCache, h, true);
    } else {
      taosLRUCacheRelease(pCache, h, false);
    }
  }

603 604
  // getTableCacheKey(uid, "l", key, &keyLen);
  getTableCacheKey(uid, 1, key, &keyLen);
605
  h = taosLRUCacheLookup(pCache, key, keyLen);
606
  if (h) {
607 608 609
    SArray *pLast = (SArray *)taosLRUCacheValue(pCache, h);
    bool    invalidate = false;
    int16_t nCol = taosArrayGetSize(pLast);
610

611 612 613 614 615 616 617 618 619 620 621 622 623
    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);
    }
624 625 626 627 628
    // void taosLRUCacheErase(SLRUCache * cache, const void *key, size_t keyLen);
  }

  return code;
}
629
*/
H
Hongze Cheng 已提交
630
int32_t tsdbCacheInsertLastrow(SLRUCache *pCache, STsdb *pTsdb, tb_uid_t uid, TSDBROW *row, bool dup) {
631 632
  int32_t code = 0;
  STSRow *cacheRow = NULL;
H
Hongze Cheng 已提交
633 634
  char    key[32] = {0};
  int     keyLen = 0;
635

636 637
  // getTableCacheKey(uid, "lr", key, &keyLen);
  getTableCacheKey(uid, 0, key, &keyLen);
638 639
  LRUHandle *h = taosLRUCacheLookup(pCache, key, keyLen);
  if (h) {
640
    STSchema *pTSchema = metaGetTbTSchema(pTsdb->pVnode->pMeta, uid, -1, 1);
H
Hongze Cheng 已提交
641
    TSKEY     keyTs = TSDBROW_TS(row);
642 643 644 645 646 647
    bool      invalidate = false;

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

648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682
    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;
    }

683 684 685 686 687
    if (nCol != pTSchema->numOfCols) {
      invalidate = true;
      goto _invalidate;
    }

688 689 690 691 692 693 694 695 696 697 698 699 700 701
    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 已提交
702
        tsdbRowGetColVal(row, pTSchema, iCol, &colVal);
703 704 705 706 707 708

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

709 710 711 712 713
        if (!COL_VAL_IS_NONE(&colVal)) {
          if (keyTs == tTsVal1->ts && !COL_VAL_IS_NONE(tColVal)) {
            invalidate = true;

            break;
714 715 716 717
          } 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);
718 719
              if (pLastCol->colVal.value.nData > 0 && NULL != pLastCol->colVal.value.pData)
                taosMemoryFree(pLastCol->colVal.value.pData);
720 721 722 723 724 725 726 727

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

730 731
            taosArraySet(pLast, iCol, &lastCol);
          }
732 733 734 735 736 737 738 739
        }
      }
    }

  _invalidate:
    taosMemoryFreeClear(pTSchema);

    taosLRUCacheRelease(pCache, h, invalidate);
740 741
    if (invalidate) {
      taosLRUCacheErase(pCache, key, keyLen);
742
    }
743
  }
744 745 746 747

  return code;
}

H
Hongze Cheng 已提交
748
int32_t tsdbCacheInsertLast(SLRUCache *pCache, tb_uid_t uid, TSDBROW *row, STsdb *pTsdb) {
749 750 751 752 753
  int32_t code = 0;
  STSRow *cacheRow = NULL;
  char    key[32] = {0};
  int     keyLen = 0;

754 755
  // getTableCacheKey(uid, "l", key, &keyLen);
  getTableCacheKey(uid, 1, key, &keyLen);
756 757
  LRUHandle *h = taosLRUCacheLookup(pCache, key, keyLen);
  if (h) {
758
    STSchema *pTSchema = metaGetTbTSchema(pTsdb->pVnode->pMeta, uid, -1, 1);
H
Hongze Cheng 已提交
759
    TSKEY     keyTs = TSDBROW_TS(row);
760 761 762 763 764 765
    bool      invalidate = false;

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

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 793 794 795 796 797 798 799 800
    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;
    }

801 802 803 804 805
    if (nCol != pTSchema->numOfCols) {
      invalidate = true;
      goto _invalidate;
    }

806 807 808
    SLastCol *tTsVal = (SLastCol *)taosArrayGet(pLast, iCol);
    if (keyTs > tTsVal->ts) {
      STColumn *pTColumn = &pTSchema->columns[0];
H
Hongze Cheng 已提交
809
      SColVal   tColVal = COL_VAL_VALUE(pTColumn->colId, pTColumn->type, (SValue){.val = keyTs});
810 811 812 813 814

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

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

        SColVal colVal = {0};
H
Hongze Cheng 已提交
820
        tsdbRowGetColVal(row, pTSchema, iCol, &colVal);
821 822 823 824 825 826

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

827
        if (COL_VAL_IS_VALUE(&colVal)) {
H
Hongze Cheng 已提交
828
          if (keyTs == tTsVal1->ts && COL_VAL_IS_VALUE(tColVal)) {
829 830 831
            invalidate = true;

            break;
832 833 834 835
          } else {
            SLastCol lastCol = {.ts = keyTs, .colVal = colVal};
            if (IS_VAR_DATA_TYPE(colVal.type) && colVal.value.nData > 0) {
              SLastCol *pLastCol = (SLastCol *)taosArrayGet(pLast, iCol);
836 837
              if (pLastCol->colVal.value.nData > 0 && NULL != pLastCol->colVal.value.pData)
                taosMemoryFree(pLastCol->colVal.value.pData);
838 839 840 841 842 843 844 845

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

848 849
            taosArraySet(pLast, iCol, &lastCol);
          }
850 851 852 853
        }
      }
    }

854
  _invalidate:
855 856 857
    taosMemoryFreeClear(pTSchema);

    taosLRUCacheRelease(pCache, h, invalidate);
858 859 860
    if (invalidate) {
      taosLRUCacheErase(pCache, key, keyLen);
    }
861 862 863 864 865
  }

  return code;
}

866 867 868 869 870
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 已提交
871
  if (metaGetTableEntryByUidCache(&mr, uid) < 0) {
H
Hongze Cheng 已提交
872
    metaReaderClear(&mr);  // table not esist
873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892
    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 已提交
893
    code = tsdbReadDelData(pDelReader, pDelIdx, aDelData);
894 895 896 897 898 899
  }

  return code;
}

static int32_t getTableDelDataFromTbData(STbData *pTbData, SArray *aDelData) {
H
Hongze Cheng 已提交
900
  int32_t   code = 0;
901 902 903 904 905 906 907 908 909
  SDelData *pDelData = pTbData ? pTbData->pHead : NULL;

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

  return code;
}

H
Hongze Cheng 已提交
910 911
static int32_t getTableDelData(STbData *pMem, STbData *pIMem, SDelFReader *pDelReader, SDelIdx *pDelIdx,
                               SArray *aDelData) {
912 913
  int32_t code = 0;

914 915 916 917 918
  if (pDelIdx) {
    code = getTableDelDataFromDelIdx(pDelReader, pDelIdx, aDelData);
    if (code) goto _err;
  }

919 920 921 922 923 924 925 926 927 928 929 930 931 932
  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 已提交
933 934
static int32_t getTableDelSkyline(STbData *pMem, STbData *pIMem, SDelFReader *pDelReader, SDelIdx *pDelIdx,
                                  SArray *aSkyline) {
935
  int32_t code = 0;
M
Minglei Jin 已提交
936
  SArray *aDelData = NULL;
937

M
Minglei Jin 已提交
938
  aDelData = taosArrayInit(32, sizeof(SDelData));
939 940 941 942
  code = getTableDelData(pMem, pIMem, pDelReader, pDelIdx, aDelData);
  if (code) goto _err;

  size_t nDelData = taosArrayGetSize(aDelData);
943 944 945 946
  if (nDelData > 0) {
    code = tsdbBuildDeleteSkyline(aDelData, 0, (int32_t)(nDelData - 1), aSkyline);
    if (code) goto _err;
  }
947

948
_err:
M
Minglei Jin 已提交
949 950 951
  if (aDelData) {
    taosArrayDestroy(aDelData);
  }
952 953
  return code;
}
S
stephenkgu 已提交
954
/*
955 956
static int32_t getTableDelIdx(SDelFReader *pDelFReader, tb_uid_t suid, tb_uid_t uid, SDelIdx *pDelIdx) {
  int32_t code = 0;
M
Minglei Jin 已提交
957
  SArray *pDelIdxArray = NULL;
958

959
  // SMapData delIdxMap;
M
Minglei Jin 已提交
960
  pDelIdxArray = taosArrayInit(32, sizeof(SDelIdx));
961
  SDelIdx idx = {.suid = suid, .uid = uid};
962

963
  // tMapDataReset(&delIdxMap);
H
Hongze Cheng 已提交
964
  code = tsdbReadDelIdx(pDelFReader, pDelIdxArray);
965 966
  if (code) goto _err;

967
  // code = tMapDataSearch(&delIdxMap, &idx, tGetDelIdx, tCmprDelIdx, pDelIdx);
968
  SDelIdx *pIdx = taosArraySearch(pDelIdxArray, &idx, tCmprDelIdx, TD_EQ);
969

970 971
  *pDelIdx = *pIdx;

972
_err:
M
Minglei Jin 已提交
973 974 975
  if (pDelIdxArray) {
    taosArrayDestroy(pDelIdxArray);
  }
976 977
  return code;
}
S
stephenkgu 已提交
978
*/
979 980 981 982 983 984 985 986
typedef enum {
  SFSLASTNEXTROW_FS,
  SFSLASTNEXTROW_FILESET,
  SFSLASTNEXTROW_BLOCKDATA,
  SFSLASTNEXTROW_BLOCKROW
} SFSLASTNEXTROWSTATES;

typedef struct {
987 988 989
  SFSLASTNEXTROWSTATES state;     // [input]
  STsdb               *pTsdb;     // [input]
  STSchema            *pTSchema;  // [input]
990
  tb_uid_t             suid;
991
  tb_uid_t             uid;
992 993 994
  int32_t              nFileSet;
  int32_t              iFileSet;
  SArray              *aDFileSet;
995
  SDataFReader       **pDataFReader;
996
  TSDBROW              row;
997

998
  bool               checkRemainingRow;
999 1000 1001
  SMergeTree         mergeTree;
  SMergeTree        *pMergeTree;
  SSttBlockLoadInfo *pLoadInfo;
1002
  int64_t            lastTs;
1003 1004
} SFSLastNextRowIter;

D
dapan1121 已提交
1005 1006
static int32_t getNextRowFromFSLast(void *iter, TSDBROW **ppRow, bool *pIgnoreEarlierTs, bool isLast, int16_t *aCols,
                                    int nCols) {
1007 1008
  SFSLastNextRowIter *state = (SFSLastNextRowIter *)iter;
  int32_t             code = 0;
D
dapan1121 已提交
1009
  bool                checkRemainingRow = true;
1010 1011 1012 1013 1014 1015 1016 1017 1018

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

    case SFSLASTNEXTROW_FILESET: {
      SDFileSet *pFileSet = NULL;
    _next_fileset:
1019 1020 1021 1022 1023
      if (state->pMergeTree != NULL) {
        tMergeTreeClose(state->pMergeTree);
        state->pMergeTree = NULL;
      }

1024 1025 1026 1027 1028 1029 1030
      if (--state->iFileSet >= 0) {
        pFileSet = (SDFileSet *)taosArrayGet(state->aDFileSet, state->iFileSet);
      } else {
        *ppRow = NULL;
        return code;
      }

1031 1032 1033
      if (*state->pDataFReader == NULL || (*state->pDataFReader)->pSet->fid != pFileSet->fid) {
        if (*state->pDataFReader != NULL) {
          tsdbDataFReaderClose(state->pDataFReader);
M
Minglei Jin 已提交
1034

1035 1036
          resetLastBlockLoadInfo(state->pLoadInfo);
        }
1037

1038 1039 1040 1041
        code = tsdbDataFReaderOpen(state->pDataFReader, state->pTsdb, pFileSet);
        if (code) goto _err;
      }

1042 1043 1044
      for (int i = 0; i < state->pLoadInfo->numOfStt; ++i) {
        state->pLoadInfo[i].colIds = aCols;
        state->pLoadInfo[i].numOfCols = nCols;
1045
        state->pLoadInfo[i].isLast = isLast;
1046
      }
1047
      tMergeTreeOpen(&state->mergeTree, 1, *state->pDataFReader, state->suid, state->uid,
D
dapan1121 已提交
1048 1049
                     &(STimeWindow){.skey = state->lastTs, .ekey = TSKEY_MAX},
                     &(SVersionRange){.minVer = 0, .maxVer = UINT64_MAX}, state->pLoadInfo, false, NULL, true);
1050
      state->pMergeTree = &state->mergeTree;
1051 1052 1053 1054 1055 1056 1057
      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;

1058 1059
          state->pLoadInfo[i].checkRemainingRow = state->checkRemainingRow;
        }
1060
      }
1061 1062
      bool hasVal = tMergeTreeNext(&state->mergeTree);
      if (!hasVal) {
D
dapan1121 已提交
1063 1064 1065 1066 1067
        if (tMergeTreeIgnoreEarlierTs(&state->mergeTree)) {
          *pIgnoreEarlierTs = true;
          *ppRow = NULL;
          return code;
        }
1068
        state->state = SFSLASTNEXTROW_FILESET;
1069 1070
        goto _next_fileset;
      }
1071 1072
      state->row = tMergeTreeGetRow(&state->mergeTree);
      *ppRow = &state->row;
D
dapan1121 已提交
1073

1074 1075 1076 1077 1078
      if (TSDBROW_TS(&state->row) <= state->lastTs) {
        *pIgnoreEarlierTs = true;
        *ppRow = NULL;
        return code;
      }
D
dapan1121 已提交
1079

1080 1081 1082 1083
      *pIgnoreEarlierTs = false;
      if (!hasVal) {
        state->state = SFSLASTNEXTROW_FILESET;
      }
1084

1085 1086 1087
      if (!state->checkRemainingRow) {
        state->checkRemainingRow = true;
      }
1088
      return code;
1089
    }
1090 1091 1092 1093 1094 1095
    default:
      ASSERT(0);
      break;
  }

_err:
1096
  /*if (state->pDataFReader) {
1097 1098
    tsdbDataFReaderClose(&state->pDataFReader);
    state->pDataFReader = NULL;
1099
    }*/
1100 1101 1102 1103 1104
  if (state->pMergeTree != NULL) {
    tMergeTreeClose(state->pMergeTree);
    state->pMergeTree = NULL;
  }

1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116
  *ppRow = NULL;

  return code;
}

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

  if (!state) {
    return code;
  }
1117
  /*
1118 1119 1120 1121
  if (state->pDataFReader) {
    tsdbDataFReaderClose(&state->pDataFReader);
    state->pDataFReader = NULL;
  }
1122
  */
1123 1124 1125 1126 1127
  if (state->pMergeTree != NULL) {
    tMergeTreeClose(state->pMergeTree);
    state->pMergeTree = NULL;
  }

1128 1129 1130
  return code;
}

1131 1132 1133 1134 1135 1136 1137 1138
typedef enum SFSNEXTROWSTATES {
  SFSNEXTROW_FS,
  SFSNEXTROW_FILESET,
  SFSNEXTROW_BLOCKDATA,
  SFSNEXTROW_BLOCKROW
} SFSNEXTROWSTATES;

typedef struct SFSNextRowIter {
1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149
  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;
1150
  LRUHandle         *aBlockIdxHandle;
1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161
  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;
1162
  int64_t            lastTs;
1163 1164
} SFSNextRowIter;

D
dapan1121 已提交
1165 1166
static int32_t getNextRowFromFS(void *iter, TSDBROW **ppRow, bool *pIgnoreEarlierTs, bool isLast, int16_t *aCols,
                                int nCols) {
1167 1168
  SFSNextRowIter *state = (SFSNextRowIter *)iter;
  int32_t         code = 0;
D
dapan1121 已提交
1169
  bool            checkRemainingRow = true;
1170 1171 1172

  switch (state->state) {
    case SFSNEXTROW_FS:
H
Hongze Cheng 已提交
1173
      // state->aDFileSet = state->pTsdb->pFS->cState->aDFileSet;
1174
      state->nFileSet = taosArrayGetSize(state->aDFileSet);
M
Minglei Jin 已提交
1175
      state->iFileSet = state->nFileSet;
1176 1177

      state->pBlockData = NULL;
1178 1179 1180

    case SFSNEXTROW_FILESET: {
      SDFileSet *pFileSet = NULL;
1181
    _next_fileset:
1182 1183 1184
      if (--state->iFileSet >= 0) {
        pFileSet = (SDFileSet *)taosArrayGet(state->aDFileSet, state->iFileSet);
      } else {
H
Hongze Cheng 已提交
1185
        // tBlockDataDestroy(&state->blockData, 1);
1186
        if (state->pBlockData) {
H
Hongze Cheng 已提交
1187
          tBlockDataDestroy(state->pBlockData);
1188 1189
          state->pBlockData = NULL;
        }
1190

1191 1192 1193 1194
        *ppRow = NULL;
        return code;
      }

1195 1196 1197 1198
      if (*state->pDataFReader == NULL || (*state->pDataFReader)->pSet->fid != pFileSet->fid) {
        if (*state->pDataFReader != NULL) {
          tsdbDataFReaderClose(state->pDataFReader);

1199
          // resetLastBlockLoadInfo(state->pLoadInfo);
1200 1201 1202 1203 1204
        }

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

      // tMapDataReset(&state->blockIdxMap);
1207
      /*
1208 1209 1210 1211 1212
      if (!state->aBlockIdx) {
        state->aBlockIdx = taosArrayInit(0, sizeof(SBlockIdx));
      } else {
        taosArrayClear(state->aBlockIdx);
      }
1213
      code = tsdbReadBlockIdx(*state->pDataFReader, state->aBlockIdx);
1214
      if (code) goto _err;
1215
      */
1216
      int32_t code = tsdbCacheGetBlockIdx(state->pTsdb->biCache, *state->pDataFReader, &state->aBlockIdxHandle);
1217 1218 1219
      if (code != TSDB_CODE_SUCCESS || state->aBlockIdxHandle == NULL) {
        goto _err;
      }
1220
      state->aBlockIdx = (SArray *)taosLRUCacheValue(state->pTsdb->biCache, state->aBlockIdxHandle);
1221

1222 1223
      /* if (state->pBlockIdx) { */
      /* } */
1224 1225
      /* code = tMapDataSearch(&state->blockIdxMap, state->pBlockIdxExp, tGetBlockIdx, tCmprBlockIdx,
       * &state->blockIdx);
1226 1227
       */
      state->pBlockIdx = taosArraySearch(state->aBlockIdx, state->pBlockIdxExp, tCmprBlockIdx, TD_EQ);
1228 1229 1230 1231 1232 1233
      if (!state->pBlockIdx) {
        tsdbBICacheRelease(state->pTsdb->biCache, state->aBlockIdxHandle);

        state->aBlockIdxHandle = NULL;
        state->aBlockIdx = NULL;
        /*
1234 1235 1236
         tsdbDataFReaderClose(state->pDataFReader);
         *state->pDataFReader = NULL;
         resetLastBlockLoadInfo(state->pLoadInfo);*/
1237 1238 1239
        goto _next_fileset;
      }

1240 1241
      tMapDataReset(&state->blockMap);
      /*
1242 1243 1244
      if (state->blockMap.pData != NULL) {
        tMapDataClear(&state->blockMap);
      }
1245 1246
      */
      code = tsdbReadDataBlk(*state->pDataFReader, state->pBlockIdx, &state->blockMap);
1247 1248 1249 1250
      if (code) goto _err;

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

1252 1253 1254
      if (!state->pBlockData) {
        state->pBlockData = &state->blockData;

1255 1256
        code = tBlockDataCreate(&state->blockData);
        if (code) goto _err;
1257
      }
1258 1259
    }
    case SFSNEXTROW_BLOCKDATA:
D
dapan1121 已提交
1260
    _next_datablock:
1261
      if (state->iBlock >= 0) {
H
Hongze Cheng 已提交
1262
        SDataBlk block = {0};
D
dapan1121 已提交
1263 1264
        bool     skipBlock = true;
        int      inputColIndex = 0;
1265

H
Hongze Cheng 已提交
1266
        tDataBlkReset(&block);
1267
        tBlockDataReset(state->pBlockData);
1268

H
Hongze Cheng 已提交
1269
        tMapDataGetItemByIdx(&state->blockMap, state->iBlock, &block, tGetDataBlk);
1270
        if (block.maxKey.ts <= state->lastTs) {
1271
          *pIgnoreEarlierTs = true;
D
dapan1121 已提交
1272 1273 1274 1275 1276 1277 1278
          if (state->pBlockData) {
            tBlockDataDestroy(state->pBlockData);
            state->pBlockData = NULL;
          }

          *ppRow = NULL;
          return code;
1279
        }
1280
        *pIgnoreEarlierTs = false;
1281
        tBlockDataReset(state->pBlockData);
H
Hongze Cheng 已提交
1282
        TABLEID tid = {.suid = state->suid, .uid = state->uid};
D
dapan1121 已提交
1283
        code = tBlockDataInit(state->pBlockData, &tid, state->pTSchema, aCols, nCols);
1284 1285
        if (code) goto _err;

1286
        code = tsdbReadDataBlock(*state->pDataFReader, &block, state->pBlockData);
1287 1288
        if (code) goto _err;

D
dapan1121 已提交
1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321
        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;
          }
        }

1322 1323 1324 1325
        state->nRow = state->blockData.nRow;
        state->iRow = state->nRow - 1;

        state->state = SFSNEXTROW_BLOCKROW;
D
dapan1121 已提交
1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368
        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;
          }
        }
1369
      }
D
dapan1121 已提交
1370

1371
      if (state->iRow >= 0) {
1372
        state->row = tsdbRowFromBlockData(state->pBlockData, state->iRow);
1373 1374 1375 1376 1377
        *ppRow = &state->row;

        if (--state->iRow < 0) {
          state->state = SFSNEXTROW_BLOCKDATA;
          if (--state->iBlock < 0) {
1378 1379
            tsdbDataFReaderClose(state->pDataFReader);
            *state->pDataFReader = NULL;
1380
            // resetLastBlockLoadInfo(state->pLoadInfo);
1381

1382
            if (state->aBlockIdx) {
1383
              // taosArrayDestroy(state->aBlockIdx);
1384
              tsdbBICacheRelease(state->pTsdb->biCache, state->aBlockIdxHandle);
1385 1386

              state->aBlockIdxHandle = NULL;
1387
              state->aBlockIdx = NULL;
1388
            }
1389

1390 1391 1392 1393 1394 1395
            state->state = SFSNEXTROW_FILESET;
          }
        }
      }

      return code;
D
dapan1121 已提交
1396
    }
1397 1398 1399 1400 1401 1402
    default:
      ASSERT(0);
      break;
  }

_err:
1403 1404 1405 1406 1407 1408
  /*
  if (*state->pDataFReader) {
    tsdbDataFReaderClose(state->pDataFReader);
    *state->pDataFReader = NULL;
    resetLastBlockLoadInfo(state->pLoadInfo);
    }*/
1409
  if (state->aBlockIdx) {
1410
    // taosArrayDestroy(state->aBlockIdx);
1411
    tsdbBICacheRelease(state->pTsdb->biCache, state->aBlockIdxHandle);
1412 1413

    state->aBlockIdxHandle = NULL;
1414 1415 1416
    state->aBlockIdx = NULL;
  }
  if (state->pBlockData) {
H
Hongze Cheng 已提交
1417
    tBlockDataDestroy(state->pBlockData);
1418
    state->pBlockData = NULL;
1419 1420
  }

1421
  *ppRow = NULL;
1422

1423 1424 1425
  return code;
}

1426 1427 1428 1429 1430 1431 1432
int32_t clearNextRowFromFS(void *iter) {
  int32_t code = 0;

  SFSNextRowIter *state = (SFSNextRowIter *)iter;
  if (!state) {
    return code;
  }
1433
  /*
1434 1435 1436
  if (state->pDataFReader) {
    tsdbDataFReaderClose(&state->pDataFReader);
    state->pDataFReader = NULL;
1437
    }*/
1438
  if (state->aBlockIdx) {
1439
    // taosArrayDestroy(state->aBlockIdx);
1440
    tsdbBICacheRelease(state->pTsdb->biCache, state->aBlockIdxHandle);
1441 1442

    state->aBlockIdxHandle = NULL;
1443 1444 1445
    state->aBlockIdx = NULL;
  }
  if (state->pBlockData) {
H
Hongze Cheng 已提交
1446
    // tBlockDataDestroy(&state->blockData, 1);
H
Hongze Cheng 已提交
1447
    tBlockDataDestroy(state->pBlockData);
1448 1449 1450
    state->pBlockData = NULL;
  }

1451 1452 1453 1454
  if (state->blockMap.pData != NULL) {
    tMapDataClear(&state->blockMap);
  }

1455 1456 1457
  return code;
}

1458 1459 1460 1461 1462 1463 1464 1465 1466
typedef enum SMEMNEXTROWSTATES {
  SMEMNEXTROW_ENTER,
  SMEMNEXTROW_NEXT,
} SMEMNEXTROWSTATES;

typedef struct SMemNextRowIter {
  SMEMNEXTROWSTATES state;
  STbData          *pMem;  // [input]
  STbDataIter       iter;  // mem buffer skip list iterator
1467
  int64_t           lastTs;
1468 1469
  // bool              iterOpened;
  // TSDBROW          *curRow;
1470 1471
} SMemNextRowIter;

D
dapan1121 已提交
1472 1473
static int32_t getNextRowFromMem(void *iter, TSDBROW **ppRow, bool *pIgnoreEarlierTs, bool isLast, int16_t *aCols,
                                 int nCols) {
1474 1475
  SMemNextRowIter *state = (SMemNextRowIter *)iter;
  int32_t          code = 0;
1476
  *pIgnoreEarlierTs = false;
1477 1478 1479
  switch (state->state) {
    case SMEMNEXTROW_ENTER: {
      if (state->pMem != NULL) {
1480 1481 1482 1483 1484
        if (state->pMem->maxKey <= state->lastTs) {
          *ppRow = NULL;
          *pIgnoreEarlierTs = true;
          return code;
        }
1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519
        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;
}

1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557
/* 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; */
/* } */
1558

1559
static bool tsdbKeyDeleted(TSDBKEY *key, SArray *pSkyline, int64_t *iSkyline) {
1560 1561 1562 1563 1564 1565 1566 1567
  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) {
1568
      if (key->version <= pItemFront->version || (key->ts == pItemBack->ts && key->version <= pItemBack->version)) {
1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584
        return true;
      } else {
        return false;
      }
    } else {
      if (*iSkyline > 1) {
        --*iSkyline;
      } else {
        return false;
      }
    }
  }

  return deleted;
}

D
dapan1121 已提交
1585 1586
typedef int32_t (*_next_row_fn_t)(void *iter, TSDBROW **ppRow, bool *pIgnoreEarlierTs, bool isLast, int16_t *aCols,
                                  int nCols);
1587
typedef int32_t (*_next_row_clear_fn_t)(void *iter);
1588

1589
typedef struct {
1590 1591 1592
  TSDBROW             *pRow;
  bool                 stop;
  bool                 next;
1593
  bool                 ignoreEarlierTs;
1594 1595 1596
  void                *iter;
  _next_row_fn_t       nextRowFn;
  _next_row_clear_fn_t nextRowClearFn;
1597
} TsdbNextRowState;
1598

1599 1600 1601 1602
typedef struct {
  SArray *pSkyline;
  int64_t iSkyline;

1603 1604 1605 1606 1607 1608
  SBlockIdx          idx;
  SMemNextRowIter    memState;
  SMemNextRowIter    imemState;
  SFSLastNextRowIter fsLastState;
  SFSNextRowIter     fsState;
  TSDBROW            memRow, imemRow, fsLastRow, fsRow;
1609

1610
  TsdbNextRowState input[4];
1611
  STsdb           *pTsdb;
1612 1613
} CacheNextRowIter;

1614
static int32_t nextRowIterOpen(CacheNextRowIter *pIter, tb_uid_t uid, STsdb *pTsdb, STSchema *pTSchema, tb_uid_t suid,
1615
                               SSttBlockLoadInfo *pLoadInfo, STsdbReadSnap *pReadSnap, SDataFReader **pDataFReader,
1616
                               SDataFReader **pDataFReaderLast, int64_t lastTs) {
1617 1618 1619
  int code = 0;

  STbData *pMem = NULL;
1620 1621
  if (pReadSnap->pMem) {
    pMem = tsdbGetTbDataFromMemTable(pReadSnap->pMem, suid, uid);
1622 1623 1624
  }

  STbData *pIMem = NULL;
1625 1626
  if (pReadSnap->pIMem) {
    pIMem = tsdbGetTbDataFromMemTable(pReadSnap->pIMem, suid, uid);
1627 1628
  }

H
Hongze Cheng 已提交
1629 1630
  pIter->pTsdb = pTsdb;

1631 1632
  pIter->pSkyline = taosArrayInit(32, sizeof(TSDBKEY));

1633
  SDelFile *pDelFile = pReadSnap->fs.pDelFile;
1634 1635 1636
  if (pDelFile) {
    SDelFReader *pDelFReader;

H
Hongze Cheng 已提交
1637
    code = tsdbDelFReaderOpen(&pDelFReader, pDelFile, pTsdb);
1638 1639
    if (code) goto _err;

S
stephenkgu 已提交
1640 1641 1642
    SArray *pDelIdxArray = taosArrayInit(32, sizeof(SDelIdx));

    code = tsdbReadDelIdx(pDelFReader, pDelIdxArray);
M
Minglei Jin 已提交
1643
    if (code) {
1644
      taosArrayDestroy(pDelIdxArray);
M
Minglei Jin 已提交
1645 1646 1647
      tsdbDelFReaderClose(&pDelFReader);
      goto _err;
    }
S
stephenkgu 已提交
1648 1649

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

S
stephenkgu 已提交
1651
    code = getTableDelSkyline(pMem, pIMem, pDelFReader, delIdx, pIter->pSkyline);
1652
    if (code) {
1653
      taosArrayDestroy(pDelIdxArray);
1654 1655 1656
      tsdbDelFReaderClose(&pDelFReader);
      goto _err;
    }
1657

S
stephenkgu 已提交
1658
    taosArrayDestroy(pDelIdxArray);
1659 1660 1661 1662 1663 1664 1665 1666 1667 1668
    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};

1669
  pIter->fsLastState.state = (SFSLASTNEXTROWSTATES)SFSNEXTROW_FS;
1670
  pIter->fsLastState.pTsdb = pTsdb;
1671
  pIter->fsLastState.aDFileSet = pReadSnap->fs.aDFileSet;
1672
  pIter->fsLastState.pTSchema = pTSchema;
1673
  pIter->fsLastState.suid = suid;
1674
  pIter->fsLastState.uid = uid;
1675
  pIter->fsLastState.pLoadInfo = pLoadInfo;
1676
  pIter->fsLastState.pDataFReader = pDataFReaderLast;
1677
  pIter->fsLastState.lastTs = lastTs;
1678

1679 1680
  pIter->fsState.state = SFSNEXTROW_FS;
  pIter->fsState.pTsdb = pTsdb;
1681
  pIter->fsState.aDFileSet = pReadSnap->fs.aDFileSet;
1682
  pIter->fsState.pBlockIdxExp = &pIter->idx;
1683 1684 1685
  pIter->fsState.pTSchema = pTSchema;
  pIter->fsState.suid = suid;
  pIter->fsState.uid = uid;
1686 1687
  pIter->fsState.pLoadInfo = pLoadInfo;
  pIter->fsState.pDataFReader = pDataFReader;
1688
  pIter->fsState.lastTs = lastTs;
1689

1690 1691 1692 1693
  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};
1694
  pIter->input[3] =
1695
      (TsdbNextRowState){&pIter->fsRow, false, true, false, &pIter->fsState, getNextRowFromFS, clearNextRowFromFS};
1696 1697 1698 1699

  if (pMem) {
    pIter->memState.pMem = pMem;
    pIter->memState.state = SMEMNEXTROW_ENTER;
1700
    pIter->memState.lastTs = lastTs;
1701 1702 1703 1704 1705 1706 1707
    pIter->input[0].stop = false;
    pIter->input[0].next = true;
  }

  if (pIMem) {
    pIter->imemState.pMem = pIMem;
    pIter->imemState.state = SMEMNEXTROW_ENTER;
1708
    pIter->imemState.lastTs = lastTs;
1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720
    pIter->input[1].stop = false;
    pIter->input[1].next = true;
  }

  return code;
_err:
  return code;
}

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

1721
  for (int i = 0; i < 4; ++i) {
1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735
    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 已提交
1736 1737
static int32_t nextRowIterGet(CacheNextRowIter *pIter, TSDBROW **ppRow, bool *pIgnoreEarlierTs, bool isLast,
                              int16_t *aCols, int nCols) {
1738
  int code = 0;
1739 1740 1741
  for (;;) {
    for (int i = 0; i < 4; ++i) {
      if (pIter->input[i].next && !pIter->input[i].stop) {
D
dapan1121 已提交
1742 1743
        code = pIter->input[i].nextRowFn(pIter->input[i].iter, &pIter->input[i].pRow, &pIter->input[i].ignoreEarlierTs,
                                         isLast, aCols, nCols);
1744
        if (code) goto _err;
1745

1746 1747 1748 1749
        if (pIter->input[i].pRow == NULL) {
          pIter->input[i].stop = true;
          pIter->input[i].next = false;
        }
1750 1751 1752
      }
    }

1753 1754
    if (pIter->input[0].stop && pIter->input[1].stop && pIter->input[2].stop && pIter->input[3].stop) {
      *ppRow = NULL;
1755 1756
      *pIgnoreEarlierTs = (pIter->input[0].ignoreEarlierTs || pIter->input[1].ignoreEarlierTs ||
                           pIter->input[2].ignoreEarlierTs || pIter->input[3].ignoreEarlierTs);
1757 1758
      return code;
    }
1759

1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775
    // 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;
          }
1776

1777 1778
          iMax[nMax] = i;
          max[nMax++] = pIter->input[i].pRow;
1779 1780
        } else {
          pIter->input[i].next = false;
1781 1782 1783 1784
        }
      }
    }

1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796
    // 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];
      }
1797

1798 1799
      pIter->input[iMax[i]].next = deleted;
    }
1800

1801 1802
    if (nMerge > 0) {
      pIter->input[iMerge[0]].next = true;
1803

1804 1805 1806
      *ppRow = merge[0];
      return code;
    }
1807 1808 1809 1810 1811 1812
  }

_err:
  return code;
}

1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848
static int32_t initLastColArray(STSchema *pTSchema, SArray **ppColArray) {
  SArray *pColArray = taosArrayInit(pTSchema->numOfCols, sizeof(SLastCol));
  if (NULL == pColArray) {
    return TSDB_CODE_OUT_OF_MEMORY;
  }

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

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

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

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

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

1850
static int32_t mergeLastRow(tb_uid_t uid, STsdb *pTsdb, bool *dup, SArray **ppColArray, SCacheRowsReader *pr) {
1851
  STSchema *pTSchema = pr->pSchema;  // metaGetTbTSchema(pTsdb->pVnode->pMeta, uid, -1, 1);
1852
  int16_t   nLastCol = pTSchema->numOfCols;
1853 1854 1855
  int16_t   iCol = 0;
  int16_t   noneCol = 0;
  bool      setNoneCol = false;
1856
  bool      hasRow = false;
1857
  bool      ignoreEarlierTs = false;
1858
  SArray   *pColArray = NULL;
1859 1860
  SColVal  *pColVal = &(SColVal){0};

1861 1862 1863 1864 1865
  int32_t code = initLastColArray(pTSchema, &pColArray);
  if (TSDB_CODE_SUCCESS != code) {
    return code;
  }

1866 1867 1868
  TSKEY lastRowTs = TSKEY_MAX;

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

  do {
    TSDBROW *pRow = NULL;
D
dapan1121 已提交
1874
    nextRowIterGet(&iter, &pRow, &ignoreEarlierTs, false, NULL, 0);
1875 1876 1877 1878 1879

    if (!pRow) {
      break;
    }

1880 1881
    hasRow = true;

1882 1883 1884 1885 1886 1887 1888
    int32_t sversion = TSDBROW_SVERSION(pRow);
    if (sversion != -1) {
      code = updateTSchema(sversion, pr, uid);
      if (TSDB_CODE_SUCCESS != code) {
        goto _err;
      }
      pTSchema = pr->pCurrSchema;
1889 1890 1891
    }
    int16_t nCol = pTSchema->numOfCols;

1892 1893
    TSKEY rowTs = TSDBROW_TS(pRow);

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

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

      for (iCol = 1; iCol < nCol; ++iCol) {
1902 1903 1904 1905 1906 1907 1908
        if (iCol >= nLastCol) {
          break;
        }
        SLastCol *pCol = taosArrayGet(pColArray, iCol);
        if (pCol->colVal.cid != pTSchema->columns[iCol].colId) {
          continue;
        }
1909 1910
        tsdbRowGetColVal(pRow, pTSchema, iCol, pColVal);

1911
        *pCol = (SLastCol){.ts = lastRowTs, .colVal = *pColVal};
1912
        if (IS_VAR_DATA_TYPE(pColVal->type) && pColVal->value.nData > 0) {
1913 1914
          pCol->colVal.value.pData = taosMemoryMalloc(pCol->colVal.value.nData);
          if (pCol->colVal.value.pData == NULL) {
M
Minglei Jin 已提交
1915 1916 1917 1918
            terrno = TSDB_CODE_OUT_OF_MEMORY;
            code = TSDB_CODE_OUT_OF_MEMORY;
            goto _err;
          }
1919
          memcpy(pCol->colVal.value.pData, pColVal->value.pData, pColVal->value.nData);
1920 1921
        }

H
Hongze Cheng 已提交
1922
        if (COL_VAL_IS_NONE(pColVal) && !setNoneCol) {
1923 1924 1925 1926 1927
          noneCol = iCol;
          setNoneCol = true;
        }
      }
      if (!setNoneCol) {
1928
        // done, goto return pColArray
1929 1930 1931 1932 1933 1934
        break;
      } else {
        continue;
      }
    }

1935 1936
    if ((rowTs < lastRowTs)) {
      // done, goto return pColArray
1937 1938 1939 1940 1941 1942 1943 1944 1945 1946
      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 已提交
1947
      if (COL_VAL_IS_NONE(tColVal) && !COL_VAL_IS_NONE(pColVal)) {
1948
        SLastCol lastCol = {.ts = rowTs, .colVal = *pColVal};
1949
        if (IS_VAR_DATA_TYPE(pColVal->type) && pColVal->value.nData > 0) {
1950 1951 1952 1953
          SLastCol *pLastCol = (SLastCol *)taosArrayGet(pColArray, iCol);
          taosMemoryFree(pLastCol->colVal.value.pData);

          lastCol.colVal.value.pData = taosMemoryMalloc(lastCol.colVal.value.nData);
M
Minglei Jin 已提交
1954 1955 1956 1957 1958
          if (lastCol.colVal.value.pData == NULL) {
            terrno = TSDB_CODE_OUT_OF_MEMORY;
            code = TSDB_CODE_OUT_OF_MEMORY;
            goto _err;
          }
1959 1960 1961 1962
          memcpy(lastCol.colVal.value.pData, pColVal->value.pData, pColVal->value.nData);
        }

        taosArraySet(pColArray, iCol, &lastCol);
H
Hongze Cheng 已提交
1963
      } else if (COL_VAL_IS_NONE(tColVal) && COL_VAL_IS_NONE(pColVal) && !setNoneCol) {
1964 1965 1966 1967 1968 1969 1970 1971
        noneCol = iCol;
        setNoneCol = true;
      }
    }
  } while (setNoneCol);

  // build the result ts row here
  *dup = false;
1972 1973 1974 1975
  // if (taosArrayGetSize(pColArray) != nCol) {
  //*ppColArray = NULL;
  // taosArrayDestroy(pColArray);
  //} else {
1976
  if (!hasRow) {
1977 1978 1979 1980 1981 1982
    if (ignoreEarlierTs) {
      taosArrayDestroy(pColArray);
      pColArray = NULL;
    } else {
      taosArrayClear(pColArray);
    }
1983
  }
1984 1985
  *ppColArray = pColArray;
  //}
1986 1987

  nextRowIterClose(&iter);
1988
  // taosMemoryFreeClear(pTSchema);
1989 1990 1991 1992 1993
  return code;

_err:
  nextRowIterClose(&iter);
  taosArrayDestroy(pColArray);
1994
  // taosMemoryFreeClear(pTSchema);
1995 1996 1997
  return code;
}

1998
static int32_t mergeLast(tb_uid_t uid, STsdb *pTsdb, SArray **ppLastArray, SCacheRowsReader *pr) {
1999
  STSchema *pTSchema = pr->pSchema;  // metaGetTbTSchema(pTsdb->pVnode->pMeta, uid, -1, 1);
2000
  int16_t   nLastCol = pTSchema->numOfCols;
2001 2002
  int16_t   noneCol = 0;
  bool      setNoneCol = false;
2003
  bool      hasRow = false;
2004
  bool      ignoreEarlierTs = false;
2005
  SArray   *pColArray = NULL;
2006
  SColVal  *pColVal = &(SColVal){0};
D
dapan1121 已提交
2007
  int16_t   nCols = nLastCol;
2008

2009 2010 2011 2012
  int32_t code = initLastColArray(pTSchema, &pColArray);
  if (TSDB_CODE_SUCCESS != code) {
    return code;
  }
D
dapan1121 已提交
2013 2014 2015 2016 2017 2018 2019 2020 2021
  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);
  }
2022

2023 2024 2025
  TSKEY lastRowTs = TSKEY_MAX;

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

  do {
    TSDBROW *pRow = NULL;
D
dapan1121 已提交
2031
    nextRowIterGet(&iter, &pRow, &ignoreEarlierTs, true, TARRAY_DATA(aColArray), TARRAY_SIZE(aColArray));
2032 2033 2034 2035 2036

    if (!pRow) {
      break;
    }

2037 2038
    hasRow = true;

2039 2040 2041 2042 2043 2044 2045
    int32_t sversion = TSDBROW_SVERSION(pRow);
    if (sversion != -1) {
      code = updateTSchema(sversion, pr, uid);
      if (TSDB_CODE_SUCCESS != code) {
        goto _err;
      }
      pTSchema = pr->pCurrSchema;
2046 2047 2048
    }
    int16_t nCol = pTSchema->numOfCols;

2049 2050 2051 2052 2053 2054
    TSKEY rowTs = TSDBROW_TS(pRow);

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

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

2058 2059 2060 2061 2062 2063 2064 2065
      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;
        }
2066 2067
        tsdbRowGetColVal(pRow, pTSchema, iCol, pColVal);

2068
        *pCol = (SLastCol){.ts = lastRowTs, .colVal = *pColVal};
2069
        if (IS_VAR_DATA_TYPE(pColVal->type) && pColVal->value.nData > 0) {
2070 2071
          pCol->colVal.value.pData = taosMemoryMalloc(pCol->colVal.value.nData);
          if (pCol->colVal.value.pData == NULL) {
M
Minglei Jin 已提交
2072 2073 2074 2075
            terrno = TSDB_CODE_OUT_OF_MEMORY;
            code = TSDB_CODE_OUT_OF_MEMORY;
            goto _err;
          }
2076
          memcpy(pCol->colVal.value.pData, pColVal->value.pData, pColVal->value.nData);
2077 2078
        }

D
dapan1121 已提交
2079 2080 2081 2082 2083 2084 2085 2086
        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);
2087 2088 2089
        }
      }
      if (!setNoneCol) {
2090
        // done, goto return pColArray
2091 2092 2093 2094 2095
        break;
      } else {
        continue;
      }
    }
2096

2097 2098
    // merge into pColArray
    setNoneCol = false;
2099 2100 2101 2102
    for (int16_t iCol = noneCol; iCol < nCol; ++iCol) {
      if (iCol >= nLastCol) {
        break;
      }
2103
      // high version's column value
2104
      SLastCol *lastColVal = (SLastCol *)taosArrayGet(pColArray, iCol);
2105 2106 2107 2108
      if (lastColVal->colVal.cid != pTSchema->columns[iCol].colId) {
        continue;
      }
      SColVal *tColVal = &lastColVal->colVal;
2109 2110

      tsdbRowGetColVal(pRow, pTSchema, iCol, pColVal);
H
Hongze Cheng 已提交
2111
      if (!COL_VAL_IS_VALUE(tColVal) && COL_VAL_IS_VALUE(pColVal)) {
2112
        SLastCol lastCol = {.ts = rowTs, .colVal = *pColVal};
2113
        if (IS_VAR_DATA_TYPE(pColVal->type) && pColVal->value.nData > 0) {
2114 2115 2116 2117
          SLastCol *pLastCol = (SLastCol *)taosArrayGet(pColArray, iCol);
          taosMemoryFree(pLastCol->colVal.value.pData);

          lastCol.colVal.value.pData = taosMemoryMalloc(lastCol.colVal.value.nData);
M
Minglei Jin 已提交
2118 2119 2120 2121 2122
          if (lastCol.colVal.value.pData == NULL) {
            terrno = TSDB_CODE_OUT_OF_MEMORY;
            code = TSDB_CODE_OUT_OF_MEMORY;
            goto _err;
          }
2123 2124 2125 2126
          memcpy(lastCol.colVal.value.pData, pColVal->value.pData, pColVal->value.nData);
        }

        taosArraySet(pColArray, iCol, &lastCol);
D
dapan1121 已提交
2127 2128
        int32_t aColIndex = taosArraySearchIdx(aColArray, &lastCol.colVal.cid, compareInt16Val, TD_EQ);
        taosArrayRemove(aColArray, aColIndex);
H
Hongze Cheng 已提交
2129
      } else if (!COL_VAL_IS_VALUE(tColVal) && !COL_VAL_IS_VALUE(pColVal) && !setNoneCol) {
2130 2131 2132 2133 2134 2135
        noneCol = iCol;
        setNoneCol = true;
      }
    }
  } while (setNoneCol);

2136 2137 2138 2139
  // if (taosArrayGetSize(pColArray) <= 0) {
  //*ppLastArray = NULL;
  // taosArrayDestroy(pColArray);
  //} else {
2140
  if (!hasRow) {
2141 2142 2143 2144 2145 2146
    if (ignoreEarlierTs) {
      taosArrayDestroy(pColArray);
      pColArray = NULL;
    } else {
      taosArrayClear(pColArray);
    }
2147
  }
2148 2149
  *ppLastArray = pColArray;
  //}
2150 2151

  nextRowIterClose(&iter);
D
dapan1121 已提交
2152
  taosArrayDestroy(aColArray);
2153
  // taosMemoryFreeClear(pTSchema);
2154 2155 2156 2157
  return code;

_err:
  nextRowIterClose(&iter);
2158
  // taosMemoryFreeClear(pTSchema);
2159 2160
  *ppLastArray = NULL;
  taosArrayDestroy(pColArray);
D
dapan1121 已提交
2161
  taosArrayDestroy(aColArray);
2162 2163 2164
  return code;
}

2165
int32_t tsdbCacheGetLastrowH(SLRUCache *pCache, tb_uid_t uid, SCacheRowsReader *pr, LRUHandle **handle) {
2166 2167 2168 2169
  int32_t code = 0;
  char    key[32] = {0};
  int     keyLen = 0;

2170
  //  getTableCacheKeyS(uid, "lr", key, &keyLen);
2171
  getTableCacheKey(uid, 0, key, &keyLen);
2172
  LRUHandle *h = taosLRUCacheLookup(pCache, key, keyLen);
2173
  if (!h) {
2174
    STsdb *pTsdb = pr->pVnode->pTsdb;
2175 2176 2177 2178
    taosThreadMutexLock(&pTsdb->lruMutex);

    h = taosLRUCacheLookup(pCache, key, keyLen);
    if (!h) {
2179
      SArray *pArray = NULL;
2180
      bool    dup = false;  // which is always false for now
2181
      code = mergeLastRow(uid, pTsdb, &dup, &pArray, pr);
2182 2183
      // if table's empty or error or ignore ignore earlier ts, set handle NULL and return
      if (code < 0 || pArray == NULL) {
2184 2185
        if (!dup && pArray) {
          taosArrayDestroy(pArray);
2186 2187
        }

M
Minglei Jin 已提交
2188 2189
        taosThreadMutexUnlock(&pTsdb->lruMutex);

2190
        *handle = NULL;
M
Minglei Jin 已提交
2191

2192
        return 0;
2193 2194
      }

M
Minglei Jin 已提交
2195
      size_t              charge = pArray->capacity * pArray->elemSize + sizeof(*pArray);
2196
      _taos_lru_deleter_t deleter = deleteTableCacheLast;
2197
      LRUStatus status = taosLRUCacheInsert(pCache, key, keyLen, pArray, charge, deleter, &h, TAOS_LRU_PRIORITY_LOW);
2198 2199 2200
      if (status != TAOS_LRU_STATUS_OK) {
        code = -1;
      }
2201
    }
2202
    taosThreadMutexUnlock(&pTsdb->lruMutex);
2203 2204 2205 2206 2207 2208
  }

  *handle = h;

  return code;
}
2209

2210
int32_t tsdbCacheGetLastH(SLRUCache *pCache, tb_uid_t uid, SCacheRowsReader *pr, LRUHandle **handle) {
2211 2212 2213 2214
  int32_t code = 0;
  char    key[32] = {0};
  int     keyLen = 0;

2215
  // getTableCacheKeyS(uid, "l", key, &keyLen);
2216
  getTableCacheKey(uid, 1, key, &keyLen);
2217
  LRUHandle *h = taosLRUCacheLookup(pCache, key, keyLen);
2218
  if (!h) {
2219
    STsdb *pTsdb = pr->pVnode->pTsdb;
2220
    taosThreadMutexLock(&pTsdb->lruMutex);
2221

2222
    h = taosLRUCacheLookup(pCache, key, keyLen);
2223 2224
    if (!h) {
      SArray *pLastArray = NULL;
2225
      code = mergeLast(uid, pTsdb, &pLastArray, pr);
2226 2227
      // if table's empty or error or ignore ignore earlier ts, set handle NULL and return
      if (code < 0 || pLastArray == NULL) {
2228 2229
        taosThreadMutexUnlock(&pTsdb->lruMutex);

2230 2231 2232 2233
        *handle = NULL;
        return 0;
      }

M
Minglei Jin 已提交
2234
      size_t              charge = pLastArray->capacity * pLastArray->elemSize + sizeof(*pLastArray);
2235
      _taos_lru_deleter_t deleter = deleteTableCacheLast;
M
Minglei Jin 已提交
2236
      LRUStatus           status =
2237
          taosLRUCacheInsert(pCache, key, keyLen, pLastArray, charge, deleter, &h, TAOS_LRU_PRIORITY_LOW);
2238 2239 2240
      if (status != TAOS_LRU_STATUS_OK) {
        code = -1;
      }
2241
    }
2242
    taosThreadMutexUnlock(&pTsdb->lruMutex);
2243 2244 2245
  }

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

2247 2248 2249
  return code;
}

M
Minglei Jin 已提交
2250 2251 2252 2253 2254 2255 2256
int32_t tsdbCacheRelease(SLRUCache *pCache, LRUHandle *h) {
  int32_t code = 0;

  taosLRUCacheRelease(pCache, h, false);

  return code;
}
2257 2258 2259 2260 2261 2262

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

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

2264 2265 2266 2267 2268 2269 2270 2271
size_t tsdbCacheGetUsage(SVnode *pVnode) {
  size_t usage = 0;
  if (pVnode->pTsdb != NULL) {
    usage = taosLRUCacheGetUsage(pVnode->pTsdb->lruCache);
  }

  return usage;
}
2272

D
dapan1121 已提交
2273 2274 2275 2276 2277 2278 2279 2280 2281
int32_t tsdbCacheGetElems(SVnode *pVnode) {
  int32_t elems = 0;
  if (pVnode->pTsdb != NULL) {
    elems = taosLRUCacheGetElems(pVnode->pTsdb->lruCache);
  }

  return elems;
}

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

2350
  tsdbTrace("bi cache:%p, ref", pCache);
2351 2352 2353 2354 2355 2356 2357 2358 2359
  *handle = h;

  return code;
}

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

  taosLRUCacheRelease(pCache, h, false);
2360
  tsdbTrace("bi cache:%p, release", pCache);
2361 2362 2363

  return code;
}