tsdbCache.c 86.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/*
 * 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"
M
Minglei Jin 已提交
16
#include "tsdbDataFileRW.h"
M
Minglei Jin 已提交
17
#include "tsdbReadUtil.h"
18
#include "vnd.h"
19

D
dapan1121 已提交
20 21
#define ROCKS_BATCH_SIZE (4096)

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

    taosLRUCacheCleanup(pCache);

    taosThreadMutexDestroy(&pTsdb->biMutex);
  }
}

54 55 56 57 58 59 60
#define ROCKS_KEY_LEN (sizeof(tb_uid_t) + sizeof(int16_t) + sizeof(int8_t))

typedef struct {
  tb_uid_t uid;
  int16_t  cid;
  int8_t   ltype;
} SLastKey;
61

62 63
static void tsdbGetRocksPath(STsdb *pTsdb, char *path) {
  SVnode *pVnode = pTsdb->pVnode;
64
  vnodeGetPrimaryDir(pTsdb->path, pVnode->diskPrimary, pVnode->pTfs, path, TSDB_FILENAME_LEN);
65 66 67

  int32_t offset = strlen(path);
  snprintf(path + offset, TSDB_FILENAME_LEN - offset - 1, "%scache.rdb", TD_DIRSEP);
68 69
}

70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
static const char *myCmpName(void *state) {
  (void)state;
  return "myCmp";
}

static void myCmpDestroy(void *state) { (void)state; }

static int myCmp(void *state, const char *a, size_t alen, const char *b, size_t blen) {
  (void)state;
  (void)alen;
  (void)blen;
  SLastKey *lhs = (SLastKey *)a;
  SLastKey *rhs = (SLastKey *)b;

  if (lhs->uid < rhs->uid) {
    return -1;
  } else if (lhs->uid > rhs->uid) {
    return 1;
  }

  if (lhs->cid < rhs->cid) {
    return -1;
  } else if (lhs->cid > rhs->cid) {
    return 1;
  }

  if (lhs->ltype < rhs->ltype) {
    return -1;
  } else if (lhs->ltype > rhs->ltype) {
    return 1;
  }

  return 0;
}

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

108 109 110 111 112 113 114 115 116 117 118 119
  rocksdb_comparator_t *cmp = rocksdb_comparator_create(NULL, myCmpDestroy, myCmp, myCmpName);
  if (NULL == cmp) {
    code = TSDB_CODE_OUT_OF_MEMORY;
    return code;
  }

  rocksdb_cache_t *cache = rocksdb_cache_create_lru(5 * 1024 * 1024);
  pTsdb->rCache.blockcache = cache;

  rocksdb_block_based_table_options_t *tableoptions = rocksdb_block_based_options_create();
  pTsdb->rCache.tableoptions = tableoptions;

120 121 122 123 124 125 126
  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);
127 128 129
  rocksdb_options_set_comparator(options, cmp);
  rocksdb_block_based_options_set_block_cache(tableoptions, cache);
  rocksdb_options_set_block_based_table_factory(options, tableoptions);
130
  rocksdb_options_set_info_log_level(options, 2);  // WARN_LEVEL
131 132
  // rocksdb_options_set_inplace_update_support(options, 1);
  // rocksdb_options_set_allow_concurrent_memtable_write(options, 0);
133 134 135 136 137 138

  rocksdb_writeoptions_t *writeoptions = rocksdb_writeoptions_create();
  if (NULL == writeoptions) {
    code = TSDB_CODE_OUT_OF_MEMORY;
    goto _err2;
  }
139
  rocksdb_writeoptions_disable_WAL(writeoptions, 1);
140 141 142 143

  rocksdb_readoptions_t *readoptions = rocksdb_readoptions_create();
  if (NULL == readoptions) {
    code = TSDB_CODE_OUT_OF_MEMORY;
144
    goto _err3;
145 146 147 148 149 150 151 152
  }

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

  rocksdb_t *db = rocksdb_open(options, cachePath, &err);
  if (NULL == db) {
153 154 155 156 157
    tsdbError("vgId:%d, %s failed at line %d since %s", TD_VID(pTsdb->pVnode), __func__, __LINE__, err);
    rocksdb_free(err);

    code = TSDB_CODE_OUT_OF_MEMORY;
    goto _err4;
158 159
  }

160 161 162
  rocksdb_flushoptions_t *flushoptions = rocksdb_flushoptions_create();
  if (NULL == flushoptions) {
    code = TSDB_CODE_OUT_OF_MEMORY;
163
    goto _err5;
164 165
  }

166
  rocksdb_writebatch_t *writebatch = rocksdb_writebatch_create();
167
  rocksdb_writebatch_t *rwritebatch = rocksdb_writebatch_create();
168 169

  pTsdb->rCache.writebatch = writebatch;
170
  pTsdb->rCache.rwritebatch = rwritebatch;
171
  pTsdb->rCache.my_comparator = cmp;
172 173 174
  pTsdb->rCache.options = options;
  pTsdb->rCache.writeoptions = writeoptions;
  pTsdb->rCache.readoptions = readoptions;
175
  pTsdb->rCache.flushoptions = flushoptions;
176 177
  pTsdb->rCache.db = db;

178 179
  taosThreadMutexInit(&pTsdb->rCache.rMutex, NULL);

180 181
  pTsdb->rCache.pTSchema = NULL;

182 183
  return code;

184 185
_err5:
  rocksdb_close(pTsdb->rCache.db);
186 187 188 189 190 191
_err4:
  rocksdb_readoptions_destroy(readoptions);
_err3:
  rocksdb_writeoptions_destroy(writeoptions);
_err2:
  rocksdb_options_destroy(options);
192 193
  rocksdb_block_based_options_destroy(tableoptions);
  rocksdb_cache_destroy(cache);
194
_err:
195
  rocksdb_comparator_destroy(cmp);
196 197 198 199 200
  return code;
}

static void tsdbCloseRocksCache(STsdb *pTsdb) {
  rocksdb_close(pTsdb->rCache.db);
201
  rocksdb_flushoptions_destroy(pTsdb->rCache.flushoptions);
202
  rocksdb_writebatch_destroy(pTsdb->rCache.writebatch);
203
  rocksdb_writebatch_destroy(pTsdb->rCache.rwritebatch);
204 205 206
  rocksdb_readoptions_destroy(pTsdb->rCache.readoptions);
  rocksdb_writeoptions_destroy(pTsdb->rCache.writeoptions);
  rocksdb_options_destroy(pTsdb->rCache.options);
207 208 209
  rocksdb_block_based_options_destroy(pTsdb->rCache.tableoptions);
  rocksdb_cache_destroy(pTsdb->rCache.blockcache);
  rocksdb_comparator_destroy(pTsdb->rCache.my_comparator);
210
  taosThreadMutexDestroy(&pTsdb->rCache.rMutex);
211
  taosMemoryFree(pTsdb->rCache.pTSchema);
212 213
}

214
static void rocksMayWrite(STsdb *pTsdb, bool force, bool read, bool lock) {
D
dapan1121 已提交
215
  rocksdb_writebatch_t *wb = pTsdb->rCache.writebatch;
216
  if (read) {
217 218 219
    if (lock) {
      taosThreadMutexLock(&pTsdb->lruMutex);
    }
220
    wb = pTsdb->rCache.rwritebatch;
221 222 223 224
  } else {
    if (lock) {
      taosThreadMutexLock(&pTsdb->rCache.rMutex);
    }
225
  }
D
dapan1121 已提交
226

227
  int count = rocksdb_writebatch_count(wb);
D
dapan1121 已提交
228
  if ((force && count > 0) || count >= ROCKS_BATCH_SIZE) {
229
    char *err = NULL;
D
dapan1121 已提交
230

231 232
    rocksdb_write(pTsdb->rCache.db, pTsdb->rCache.writeoptions, wb, &err);
    if (NULL != err) {
233 234
      tsdbError("vgId:%d, %s failed at line %d, count: %d since %s", TD_VID(pTsdb->pVnode), __func__, __LINE__, count,
                err);
235
      rocksdb_free(err);
D
dapan1121 已提交
236
      // pTsdb->flushState.flush_count = 0;
237 238 239 240 241
    }

    rocksdb_writebatch_clear(wb);
  }

D
dapan1121 已提交
242 243 244 245 246 247
  if (lock) {
    if (read) {
      taosThreadMutexUnlock(&pTsdb->lruMutex);
    } else {
      taosThreadMutexUnlock(&pTsdb->rCache.rMutex);
    }
248 249 250
  }
}

D
dapan1121 已提交
251
static SLastCol *tsdbCacheDeserialize(char const *value) {
252 253 254 255
  if (!value) {
    return NULL;
  }

256 257 258
  SLastCol *pLastCol = (SLastCol *)value;
  SColVal  *pColVal = &pLastCol->colVal;
  if (IS_VAR_DATA_TYPE(pColVal->type)) {
259 260 261 262 263
    if (pColVal->value.nData > 0) {
      pColVal->value.pData = (char *)value + sizeof(*pLastCol);
    } else {
      pColVal->value.pData = NULL;
    }
264 265 266 267 268
  }

  return pLastCol;
}

D
dapan1121 已提交
269
static void tsdbCacheSerialize(SLastCol *pLastCol, char **value, size_t *size) {
270 271 272 273 274 275 276 277 278 279
  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;
280 281
    SColVal *pDColVal = &((SLastCol *)(*value))->colVal;
    pDColVal->value.pData = *value + sizeof(*pLastCol);
282
    if (pColVal->value.nData > 0) {
283
      memcpy(pDColVal->value.pData, pVal, pColVal->value.nData);
284
    } else {
285
      pDColVal->value.pData = NULL;
286 287 288 289 290
    }
  }
  *size = length;
}

D
dapan1121 已提交
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
static void tsdbCachePutBatch(SLastCol *pLastCol, const void *key, size_t klen, SCacheFlushState *state) {
  STsdb                *pTsdb = state->pTsdb;
  SRocksCache          *rCache = &pTsdb->rCache;
  rocksdb_writebatch_t *wb = rCache->writebatch;
  char                 *rocks_value = NULL;
  size_t                vlen = 0;

  tsdbCacheSerialize(pLastCol, &rocks_value, &vlen);

  taosThreadMutexLock(&rCache->rMutex);

  rocksdb_writebatch_put(wb, (char *)key, klen, rocks_value, vlen);

  taosMemoryFree(rocks_value);

  if (++state->flush_count >= ROCKS_BATCH_SIZE) {
    char *err = NULL;

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

    rocksdb_writebatch_clear(wb);

    state->flush_count = 0;
  }

  taosThreadMutexUnlock(&rCache->rMutex);
}

int tsdbCacheFlushDirty(const void *key, size_t klen, void *value, void *ud) {
  SLastCol *pLastCol = (SLastCol *)value;

  if (pLastCol->dirty) {
    tsdbCachePutBatch(pLastCol, key, klen, (SCacheFlushState *)ud);

    pLastCol->dirty = 0;
  }

  return 0;
}

int32_t tsdbCacheCommit(STsdb *pTsdb) {
  int32_t code = 0;
  char   *err = NULL;

  SLRUCache            *pCache = pTsdb->lruCache;
  rocksdb_writebatch_t *wb = pTsdb->rCache.writebatch;

  taosThreadMutexLock(&pTsdb->lruMutex);

  taosLRUCacheApply(pCache, tsdbCacheFlushDirty, &pTsdb->flushState);

  rocksMayWrite(pTsdb, true, false, false);
  rocksMayWrite(pTsdb, true, true, false);
  rocksdb_flush(pTsdb->rCache.db, pTsdb->rCache.flushoptions, &err);

  taosThreadMutexUnlock(&pTsdb->lruMutex);

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

362
static SLastCol *tsdbCacheLookup(STsdb *pTsdb, tb_uid_t uid, int16_t cid, int8_t ltype) {
363 364
  SLastCol *pLastCol = NULL;

365 366 367 368 369 370
  char     *err = NULL;
  size_t    vlen = 0;
  SLastKey *key = &(SLastKey){.ltype = ltype, .uid = uid, .cid = cid};
  size_t    klen = ROCKS_KEY_LEN;
  char     *value = NULL;
  value = rocksdb_get(pTsdb->rCache.db, pTsdb->rCache.readoptions, (char *)key, klen, &vlen, &err);
371 372 373 374 375 376 377 378 379 380
  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;
}

381 382 383 384 385 386 387 388 389 390
static void reallocVarData(SColVal *pColVal) {
  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);
    }
  }
}

D
dapan1121 已提交
391
static void tsdbCacheDeleter(const void *key, size_t klen, void *value, void *ud) {
392 393 394
  SLastCol *pLastCol = (SLastCol *)value;

  if (pLastCol->dirty) {
D
dapan1121 已提交
395 396
    tsdbCachePutBatch(pLastCol, key, klen, (SCacheFlushState *)ud);
  }
397

D
dapan1121 已提交
398 399
  if (IS_VAR_DATA_TYPE(pLastCol->colVal.type) /* && pLastCol->colVal.value.nData > 0*/) {
    taosMemoryFree(pLastCol->colVal.value.pData);
400
  }
D
dapan1121 已提交
401 402

  taosMemoryFree(value);
403 404
}

D
dapan1121 已提交
405 406 407 408 409
typedef struct {
  int      idx;
  SLastKey key;
} SIdxKey;

410
int32_t tsdbCacheUpdate(STsdb *pTsdb, tb_uid_t suid, tb_uid_t uid, TSDBROW *pRow) {
411 412
  int32_t code = 0;

413
  // 1, fetch schema
M
Minglei Jin 已提交
414
  STSchema *pTSchema = NULL;
415 416
  int32_t   sver = TSDBROW_SVERSION(pRow);

M
Minglei Jin 已提交
417 418 419 420
  code = metaGetTbTSchemaEx(pTsdb->pVnode->pMeta, suid, uid, sver, &pTSchema);
  if (code != TSDB_CODE_SUCCESS) {
    terrno = code;
    return -1;
421
  }
M
Minglei Jin 已提交
422

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

426 427 428 429
  STSDBRowIter iter = {0};
  tsdbRowIterOpen(&iter, pRow, pTSchema);

  for (SColVal *pColVal = tsdbRowIterNext(&iter); pColVal; pColVal = tsdbRowIterNext(&iter)) {
430
    taosArrayPush(aColVal, pColVal);
431 432 433 434
  }

  tsdbRowClose(&iter);

435
  // 3, build keys & multi get from rocks
D
dapan1121 已提交
436 437 438 439 440 441
  int        num_keys = TARRAY_SIZE(aColVal);
  TSKEY      keyTs = TSDBROW_TS(pRow);
  SArray    *remainCols = NULL;
  SLRUCache *pCache = pTsdb->lruCache;

  taosThreadMutexLock(&pTsdb->lruMutex);
442 443
  for (int i = 0; i < num_keys; ++i) {
    SColVal *pColVal = (SColVal *)taosArrayGet(aColVal, i);
444
    int16_t  cid = pColVal->cid;
445

D
dapan1121 已提交
446 447 448 449 450
    SLastKey  *key = &(SLastKey){.ltype = 0, .uid = uid, .cid = cid};
    size_t     klen = ROCKS_KEY_LEN;
    LRUHandle *h = taosLRUCacheLookup(pCache, key, klen);
    if (h) {
      SLastCol *pLastCol = (SLastCol *)taosLRUCacheValue(pCache, h);
451

D
dapan1121 已提交
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
      if (pLastCol->ts <= keyTs) {
        uint8_t *pVal = NULL;
        int      nData = pLastCol->colVal.value.nData;
        if (IS_VAR_DATA_TYPE(pColVal->type)) {
          pVal = pLastCol->colVal.value.pData;
        }
        pLastCol->ts = keyTs;
        pLastCol->colVal = *pColVal;
        if (IS_VAR_DATA_TYPE(pColVal->type)) {
          if (nData < pColVal->value.nData) {
            taosMemoryFree(pVal);
            pLastCol->colVal.value.pData = taosMemoryCalloc(1, pColVal->value.nData);
          } else {
            pLastCol->colVal.value.pData = pVal;
          }
          if (pColVal->value.nData) {
            memcpy(pLastCol->colVal.value.pData, pColVal->value.pData, pColVal->value.nData);
          }
        }
471

D
dapan1121 已提交
472 473 474 475
        if (!pLastCol->dirty) {
          pLastCol->dirty = 1;
        }
      }
476

D
dapan1121 已提交
477 478 479 480 481 482 483
      taosLRUCacheRelease(pCache, h, false);
    } else {
      if (!remainCols) {
        remainCols = taosArrayInit(num_keys * 2, sizeof(SIdxKey));
      }
      taosArrayPush(remainCols, &(SIdxKey){i, *key});
    }
484

D
dapan1121 已提交
485 486 487 488 489
    if (COL_VAL_IS_VALUE(pColVal)) {
      key->ltype = 1;
      LRUHandle *h = taosLRUCacheLookup(pCache, key, klen);
      if (h) {
        SLastCol *pLastCol = (SLastCol *)taosLRUCacheValue(pCache, h);
490

D
dapan1121 已提交
491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509
        if (pLastCol->ts <= keyTs) {
          uint8_t *pVal = NULL;
          int      nData = pLastCol->colVal.value.nData;
          if (IS_VAR_DATA_TYPE(pColVal->type)) {
            pVal = pLastCol->colVal.value.pData;
          }
          pLastCol->ts = keyTs;
          pLastCol->colVal = *pColVal;
          if (IS_VAR_DATA_TYPE(pColVal->type)) {
            if (nData < pColVal->value.nData) {
              taosMemoryFree(pVal);
              pLastCol->colVal.value.pData = taosMemoryCalloc(1, pColVal->value.nData);
            } else {
              pLastCol->colVal.value.pData = pVal;
            }
            if (pColVal->value.nData) {
              memcpy(pLastCol->colVal.value.pData, pColVal->value.pData, pColVal->value.nData);
            }
          }
510

D
dapan1121 已提交
511 512 513 514 515 516 517 518 519 520 521
          if (!pLastCol->dirty) {
            pLastCol->dirty = 1;
          }
        }

        taosLRUCacheRelease(pCache, h, false);
      } else {
        if (!remainCols) {
          remainCols = taosArrayInit(num_keys * 2, sizeof(SIdxKey));
        }
        taosArrayPush(remainCols, &(SIdxKey){i, *key});
522
      }
D
dapan1121 已提交
523 524
    }
  }
525

D
dapan1121 已提交
526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
  if (remainCols) {
    num_keys = TARRAY_SIZE(remainCols);
  }
  if (remainCols && num_keys > 0) {
    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) {
      SIdxKey *idxKey = &((SIdxKey *)TARRAY_DATA(remainCols))[i];

      keys_list[i] = (char *)&idxKey->key;
      keys_list_sizes[i] = ROCKS_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) {
      rocksdb_free(errs[i]);
545
    }
D
dapan1121 已提交
546 547 548 549 550 551 552 553 554 555
    taosMemoryFree(errs);
    taosMemoryFree(keys_list);
    taosMemoryFree(keys_list_sizes);
    taosMemoryFree(values_list_sizes);

    rocksdb_writebatch_t *wb = pTsdb->rCache.writebatch;
    for (int i = 0; i < num_keys; ++i) {
      SIdxKey *idxKey = &((SIdxKey *)TARRAY_DATA(remainCols))[i];
      SColVal *pColVal = (SColVal *)TARRAY_DATA(aColVal) + idxKey->idx;
      // SColVal *pColVal = (SColVal *)taosArrayGet(aColVal, idxKey->idx);
556 557

      SLastCol *pLastCol = tsdbCacheDeserialize(values_list[i]);
558

D
dapan1121 已提交
559 560 561 562 563 564 565
      if (idxKey->key.ltype == 0) {
        if (NULL == pLastCol || pLastCol->ts <= keyTs) {
          char  *value = NULL;
          size_t vlen = 0;
          tsdbCacheSerialize(&(SLastCol){.ts = keyTs, .colVal = *pColVal}, &value, &vlen);
          // SLastKey key = (SLastKey){.ltype = 0, .uid = uid, .cid = pColVal->cid};
          taosThreadMutexLock(&pTsdb->rCache.rMutex);
566

D
dapan1121 已提交
567
          rocksdb_writebatch_put(wb, (char *)&idxKey->key, ROCKS_KEY_LEN, value, vlen);
568

D
dapan1121 已提交
569
          taosThreadMutexUnlock(&pTsdb->rCache.rMutex);
570

D
dapan1121 已提交
571 572 573 574
          pLastCol = (SLastCol *)value;
          SLastCol *pTmpLastCol = taosMemoryCalloc(1, sizeof(SLastCol));
          *pTmpLastCol = *pLastCol;
          pLastCol = pTmpLastCol;
575

D
dapan1121 已提交
576 577 578 579 580 581 582 583 584 585 586 587 588
          reallocVarData(&pLastCol->colVal);
          size_t charge = sizeof(*pLastCol);
          if (IS_VAR_DATA_TYPE(pLastCol->colVal.type)) {
            charge += pLastCol->colVal.value.nData;
          }

          LRUStatus status = taosLRUCacheInsert(pTsdb->lruCache, &idxKey->key, ROCKS_KEY_LEN, pLastCol, charge,
                                                tsdbCacheDeleter, NULL, TAOS_LRU_PRIORITY_LOW, &pTsdb->flushState);
          if (status != TAOS_LRU_STATUS_OK) {
            code = -1;
          }

          taosMemoryFree(value);
589
        }
D
dapan1121 已提交
590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612
      } else {
        if (COL_VAL_IS_VALUE(pColVal)) {
          if (NULL == pLastCol || pLastCol->ts <= keyTs) {
            char  *value = NULL;
            size_t vlen = 0;
            tsdbCacheSerialize(&(SLastCol){.ts = keyTs, .colVal = *pColVal}, &value, &vlen);
            // SLastKey key = (SLastKey){.ltype = 1, .uid = uid, .cid = pColVal->cid};
            taosThreadMutexLock(&pTsdb->rCache.rMutex);

            rocksdb_writebatch_put(wb, (char *)&idxKey->key, ROCKS_KEY_LEN, value, vlen);

            taosThreadMutexUnlock(&pTsdb->rCache.rMutex);

            pLastCol = (SLastCol *)value;
            SLastCol *pTmpLastCol = taosMemoryCalloc(1, sizeof(SLastCol));
            *pTmpLastCol = *pLastCol;
            pLastCol = pTmpLastCol;

            reallocVarData(&pLastCol->colVal);
            size_t charge = sizeof(*pLastCol);
            if (IS_VAR_DATA_TYPE(pLastCol->colVal.type)) {
              charge += pLastCol->colVal.value.nData;
            }
613

D
dapan1121 已提交
614 615 616 617 618 619 620 621 622
            LRUStatus status = taosLRUCacheInsert(pTsdb->lruCache, &idxKey->key, ROCKS_KEY_LEN, pLastCol, charge,
                                                  tsdbCacheDeleter, NULL, TAOS_LRU_PRIORITY_LOW, &pTsdb->flushState);
            if (status != TAOS_LRU_STATUS_OK) {
              code = -1;
            }

            taosMemoryFree(value);
          }
        }
623
      }
D
dapan1121 已提交
624 625

      rocksdb_free(values_list[i]);
626
    }
627

D
dapan1121 已提交
628 629 630 631 632
    rocksMayWrite(pTsdb, true, false, true);

    taosMemoryFree(values_list);

    taosArrayDestroy(remainCols);
633 634
  }

D
dapan1121 已提交
635
  taosThreadMutexUnlock(&pTsdb->lruMutex);
636

637 638
_exit:
  taosArrayDestroy(aColVal);
M
Minglei Jin 已提交
639
  taosMemoryFree(pTSchema);
640 641 642
  return code;
}

643 644 645
static int32_t mergeLastCid(tb_uid_t uid, STsdb *pTsdb, SArray **ppLastArray, SCacheRowsReader *pr, int16_t *aCols,
                            int nCols, int16_t *slotIds);

646 647
static int32_t mergeLastRowCid(tb_uid_t uid, STsdb *pTsdb, SArray **ppLastArray, SCacheRowsReader *pr, int16_t *aCols,
                               int nCols, int16_t *slotIds);
648 649
#if 1
int32_t tsdbCacheGetSlow(STsdb *pTsdb, tb_uid_t uid, SArray *pLastArray, SCacheRowsReader *pr, int8_t ltype) {
650 651
  rocksdb_writebatch_t *wb = NULL;
  int32_t               code = 0;
652 653

  SArray *pCidList = pr->pCidList;
654
  int     num_keys = TARRAY_SIZE(pCidList);
655 656 657 658

  char  **keys_list = taosMemoryMalloc(num_keys * sizeof(char *));
  size_t *keys_list_sizes = taosMemoryMalloc(num_keys * sizeof(size_t));
  char   *key_list = taosMemoryMalloc(num_keys * ROCKS_KEY_LEN);
659 660 661
  for (int i = 0; i < num_keys; ++i) {
    int16_t cid = *(int16_t *)taosArrayGet(pCidList, i);

662 663 664
    memcpy(key_list + i * ROCKS_KEY_LEN, &(SLastKey){.ltype = ltype, .uid = uid, .cid = cid}, ROCKS_KEY_LEN);
    keys_list[i] = key_list + i * ROCKS_KEY_LEN;
    keys_list_sizes[i] = ROCKS_KEY_LEN;
665
  }
666

667 668
  char  **values_list = taosMemoryCalloc(num_keys, sizeof(char *));
  size_t *values_list_sizes = taosMemoryCalloc(num_keys, sizeof(size_t));
669
  char  **errs = taosMemoryMalloc(num_keys * sizeof(char *));
670 671 672
  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) {
673 674 675
    if (errs[i]) {
      rocksdb_free(errs[i]);
    }
676
  }
677
  taosMemoryFree(key_list);
678 679 680 681 682
  taosMemoryFree(keys_list);
  taosMemoryFree(keys_list_sizes);
  taosMemoryFree(errs);

  for (int i = 0; i < num_keys; ++i) {
683
    bool      freeCol = true;
684
    SArray   *pTmpColArray = NULL;
685
    SLastCol *pLastCol = tsdbCacheDeserialize(values_list[i]);
686 687
    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 已提交
688
    if (pLastCol) {
689
      reallocVarData(&pLastCol->colVal);
M
Minglei Jin 已提交
690
    } else {
691
      taosThreadMutexLock(&pTsdb->rCache.rMutex);
692

693
      pLastCol = tsdbCacheLookup(pTsdb, uid, cid, ltype);
694
      if (!pLastCol) {
695 696 697 698 699 700 701 702 703 704 705 706 707
        // 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);
708
          freeCol = false;
709 710 711 712 713 714 715 716 717
        }

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

        // store result back to rocks cache
718
        wb = pTsdb->rCache.rwritebatch;
719 720
        char  *value = NULL;
        size_t vlen = 0;
721
        tsdbCacheSerialize(pLastCol, &value, &vlen);
722 723 724 725

        SLastKey *key = &(SLastKey){.ltype = ltype, .uid = uid, .cid = pLastCol->colVal.cid};
        size_t    klen = ROCKS_KEY_LEN;
        rocksdb_writebatch_put(wb, (char *)key, klen, value, vlen);
726 727

        taosMemoryFree(value);
728
      } else {
729
        reallocVarData(&pLastCol->colVal);
730 731
      }

732
      if (wb) {
733
        rocksMayWrite(pTsdb, false, true, false);
734 735
      }

736
      taosThreadMutexUnlock(&pTsdb->rCache.rMutex);
M
Minglei Jin 已提交
737
    }
738

739
    taosArrayPush(pLastArray, pLastCol);
740
    taosArrayDestroy(pTmpColArray);
741 742 743
    if (freeCol) {
      taosMemoryFree(pLastCol);
    }
744 745 746
  }
  taosMemoryFree(values_list);
  taosMemoryFree(values_list_sizes);
747 748 749

  return code;
}
750 751 752 753 754 755 756 757 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
#endif

static SLastCol *tsdbCacheLoadCol(STsdb *pTsdb, SCacheRowsReader *pr, int16_t slotid, tb_uid_t uid, int16_t cid,
                                  int8_t ltype) {
  SLastCol *pLastCol = tsdbCacheLookup(pTsdb, uid, cid, ltype);
  if (!pLastCol) {
    rocksdb_writebatch_t *wb = NULL;

    taosThreadMutexLock(&pTsdb->rCache.rMutex);
    pLastCol = tsdbCacheLookup(pTsdb, uid, cid, ltype);
    if (!pLastCol) {
      // recalc: load from tsdb
      int16_t aCols[1] = {cid};
      int16_t slotIds[1] = {slotid};
      SArray *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);
      }

      // still null, then make up a none col value
      SLastCol noneCol = {.ts = TSKEY_MIN, .colVal = COL_VAL_NONE(cid, pr->pSchema->columns[slotid].type)};
      if (!pLastCol) {
        pLastCol = &noneCol;
      }

      // store result back to rocks cache
783
      wb = pTsdb->rCache.rwritebatch;
784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800
      char  *value = NULL;
      size_t vlen = 0;
      tsdbCacheSerialize(pLastCol, &value, &vlen);

      SLastKey *key = &(SLastKey){.ltype = ltype, .uid = uid, .cid = pLastCol->colVal.cid};
      size_t    klen = ROCKS_KEY_LEN;
      rocksdb_writebatch_put(wb, (char *)key, klen, value, vlen);
      taosMemoryFree(value);

      SLastCol *pTmpLastCol = taosMemoryCalloc(1, sizeof(SLastCol));
      *pTmpLastCol = *pLastCol;
      pLastCol = pTmpLastCol;

      taosArrayDestroy(pTmpColArray);
    }

    if (wb) {
801
      rocksMayWrite(pTsdb, false, true, false);
802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844
    }

    taosThreadMutexUnlock(&pTsdb->rCache.rMutex);
  }

  return pLastCol;
}

static int32_t tsdbCacheLoadFromRaw(STsdb *pTsdb, tb_uid_t uid, SArray *pLastArray, SArray *remainCols,
                                    SCacheRowsReader *pr, int8_t ltype) {
  int32_t               code = 0;
  rocksdb_writebatch_t *wb = NULL;
  SArray               *pTmpColArray = NULL;
  int                   num_keys = TARRAY_SIZE(remainCols);
  int16_t              *aCols = taosMemoryMalloc(num_keys * sizeof(int16_t));
  int16_t              *slotIds = taosMemoryMalloc(num_keys * sizeof(int16_t));

  for (int i = 0; i < num_keys; ++i) {
    SIdxKey *idxKey = taosArrayGet(remainCols, i);
    aCols[i] = idxKey->key.cid;
    slotIds[i] = pr->pSlotIds[idxKey->idx];
  }

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

  SLRUCache *pCache = pTsdb->lruCache;
  for (int i = 0; i < num_keys; ++i) {
    SIdxKey  *idxKey = taosArrayGet(remainCols, i);
    SLastCol *pLastCol = NULL;

    if (pTmpColArray && TARRAY_SIZE(pTmpColArray) >= i + 1) {
      pLastCol = taosArrayGet(pTmpColArray, i);
    }

    // still null, then make up a none col value
    SLastCol noneCol = {.ts = TSKEY_MIN,
                        .colVal = COL_VAL_NONE(idxKey->key.cid, pr->pSchema->columns[slotIds[i]].type)};
    if (!pLastCol) {
      pLastCol = &noneCol;
845
      reallocVarData(&pLastCol->colVal);
846 847
    }

848 849 850 851 852 853 854
    taosArraySet(pLastArray, idxKey->idx, pLastCol);
    // taosArrayRemove(remainCols, i);

    if (!pTmpColArray) {
      continue;
    }

855 856 857 858
    SLastCol *pTmpLastCol = taosMemoryCalloc(1, sizeof(SLastCol));
    *pTmpLastCol = *pLastCol;
    pLastCol = pTmpLastCol;

M
Minglei Jin 已提交
859
    reallocVarData(&pLastCol->colVal);
860 861 862 863 864 865
    size_t charge = sizeof(*pLastCol);
    if (IS_VAR_DATA_TYPE(pLastCol->colVal.type)) {
      charge += pLastCol->colVal.value.nData;
    }

    LRUStatus status = taosLRUCacheInsert(pCache, &idxKey->key, ROCKS_KEY_LEN, pLastCol, charge, tsdbCacheDeleter, NULL,
D
dapan1121 已提交
866
                                          TAOS_LRU_PRIORITY_LOW, &pTsdb->flushState);
867 868 869 870 871
    if (status != TAOS_LRU_STATUS_OK) {
      code = -1;
    }

    // store result back to rocks cache
872
    wb = pTsdb->rCache.rwritebatch;
873 874 875 876 877 878 879 880 881 882 883
    char  *value = NULL;
    size_t vlen = 0;
    tsdbCacheSerialize(pLastCol, &value, &vlen);

    SLastKey *key = &idxKey->key;
    size_t    klen = ROCKS_KEY_LEN;
    rocksdb_writebatch_put(wb, (char *)key, klen, value, vlen);
    taosMemoryFree(value);
  }

  if (wb) {
884
    rocksMayWrite(pTsdb, false, true, false);
885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927
  }

  taosArrayDestroy(pTmpColArray);

  taosMemoryFree(aCols);
  taosMemoryFree(slotIds);

  return code;
}

static int32_t tsdbCacheLoadFromRocks(STsdb *pTsdb, tb_uid_t uid, SArray *pLastArray, SArray *remainCols,
                                      SCacheRowsReader *pr, int8_t ltype) {
  int32_t code = 0;
  int     num_keys = TARRAY_SIZE(remainCols);
  char  **keys_list = taosMemoryMalloc(num_keys * sizeof(char *));
  size_t *keys_list_sizes = taosMemoryMalloc(num_keys * sizeof(size_t));
  char   *key_list = taosMemoryMalloc(num_keys * ROCKS_KEY_LEN);
  for (int i = 0; i < num_keys; ++i) {
    int16_t cid = *(int16_t *)taosArrayGet(remainCols, i);

    memcpy(key_list + i * ROCKS_KEY_LEN, &((SIdxKey *)taosArrayGet(remainCols, i))->key, ROCKS_KEY_LEN);
    keys_list[i] = key_list + i * ROCKS_KEY_LEN;
    keys_list_sizes[i] = ROCKS_KEY_LEN;
  }

  char  **values_list = taosMemoryCalloc(num_keys, sizeof(char *));
  size_t *values_list_sizes = taosMemoryCalloc(num_keys, sizeof(size_t));
  char  **errs = taosMemoryMalloc(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) {
    if (errs[i]) {
      rocksdb_free(errs[i]);
    }
  }
  taosMemoryFree(key_list);
  taosMemoryFree(keys_list);
  taosMemoryFree(keys_list_sizes);
  taosMemoryFree(errs);

  SLRUCache *pCache = pTsdb->lruCache;
  for (int i = 0, j = 0; i < num_keys && j < TARRAY_SIZE(remainCols); ++i) {
    SLastCol *pLastCol = tsdbCacheDeserialize(values_list[i]);
928
    SIdxKey  *idxKey = &((SIdxKey *)TARRAY_DATA(remainCols))[j];
929 930 931 932 933 934 935 936 937 938 939 940
    if (pLastCol) {
      SLastCol *pTmpLastCol = taosMemoryCalloc(1, sizeof(SLastCol));
      *pTmpLastCol = *pLastCol;
      pLastCol = pTmpLastCol;

      reallocVarData(&pLastCol->colVal);
      size_t charge = sizeof(*pLastCol);
      if (IS_VAR_DATA_TYPE(pLastCol->colVal.type)) {
        charge += pLastCol->colVal.value.nData;
      }

      LRUStatus status = taosLRUCacheInsert(pCache, &idxKey->key, ROCKS_KEY_LEN, pLastCol, charge, tsdbCacheDeleter,
D
dapan1121 已提交
941
                                            NULL, TAOS_LRU_PRIORITY_LOW, &pTsdb->flushState);
942 943 944 945
      if (status != TAOS_LRU_STATUS_OK) {
        code = -1;
      }

946 947 948
      SLastCol lastCol = *pLastCol;
      reallocVarData(&lastCol.colVal);
      taosArraySet(pLastArray, idxKey->idx, &lastCol);
949 950 951 952 953 954 955
      taosArrayRemove(remainCols, j);

      taosMemoryFree(values_list[i]);
    } else {
      ++j;
    }
  }
956

957 958 959 960 961 962 963 964 965 966 967 968
  taosMemoryFree(values_list);
  taosMemoryFree(values_list_sizes);

  if (TARRAY_SIZE(remainCols) > 0) {
    code = tsdbCacheLoadFromRaw(pTsdb, uid, pLastArray, remainCols, pr, ltype);
  }

  return code;
}

int32_t tsdbCacheGetBatch(STsdb *pTsdb, tb_uid_t uid, SArray *pLastArray, SCacheRowsReader *pr, int8_t ltype) {
  int32_t    code = 0;
969
  SArray    *remainCols = NULL;
970 971 972 973 974
  SLRUCache *pCache = pTsdb->lruCache;
  SArray    *pCidList = pr->pCidList;
  int        num_keys = TARRAY_SIZE(pCidList);

  for (int i = 0; i < num_keys; ++i) {
975
    int16_t cid = ((int16_t *)TARRAY_DATA(pCidList))[i];
976 977 978 979 980 981 982 983

    SLastKey *key = &(SLastKey){.ltype = ltype, .uid = uid, .cid = cid};

    LRUHandle *h = taosLRUCacheLookup(pCache, key, ROCKS_KEY_LEN);
    if (h) {
      SLastCol *pLastCol = (SLastCol *)taosLRUCacheValue(pCache, h);

      SLastCol lastCol = *pLastCol;
984
      reallocVarData(&lastCol.colVal);
985 986
      taosArrayPush(pLastArray, &lastCol);

D
dapan1121 已提交
987
      taosLRUCacheRelease(pCache, h, false);
988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002
    } else {
      SLastCol noneCol = {.ts = TSKEY_MIN, .colVal = COL_VAL_NONE(cid, pr->pSchema->columns[pr->pSlotIds[i]].type)};

      taosArrayPush(pLastArray, &noneCol);

      if (!remainCols) {
        remainCols = taosArrayInit(num_keys, sizeof(SIdxKey));
      }
      taosArrayPush(remainCols, &(SIdxKey){i, *key});
    }
  }

  if (remainCols && TARRAY_SIZE(remainCols) > 0) {
    taosThreadMutexLock(&pTsdb->lruMutex);
    for (int i = 0; i < TARRAY_SIZE(remainCols);) {
1003
      SIdxKey   *idxKey = &((SIdxKey *)TARRAY_DATA(remainCols))[i];
1004 1005 1006 1007 1008 1009 1010
      LRUHandle *h = taosLRUCacheLookup(pCache, &idxKey->key, ROCKS_KEY_LEN);
      if (h) {
        SLastCol *pLastCol = (SLastCol *)taosLRUCacheValue(pCache, h);

        SLastCol lastCol = *pLastCol;
        reallocVarData(&lastCol.colVal);
        taosArraySet(pLastArray, idxKey->idx, &lastCol);
M
Minglei Jin 已提交
1011

D
dapan1121 已提交
1012
        taosLRUCacheRelease(pCache, h, false);
1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023

        taosArrayRemove(remainCols, i);
      } else {
        ++i;
      }
    }

    code = tsdbCacheLoadFromRocks(pTsdb, uid, pLastArray, remainCols, pr, ltype);

    taosThreadMutexUnlock(&pTsdb->lruMutex);

1024 1025 1026
    if (remainCols) {
      taosArrayDestroy(remainCols);
    }
1027 1028 1029 1030 1031
  }

  return code;
}

1032 1033
int32_t tsdbCacheDel(STsdb *pTsdb, tb_uid_t suid, tb_uid_t uid, TSKEY sKey, TSKEY eKey) {
  int32_t code = 0;
1034
  // fetch schema
M
Minglei Jin 已提交
1035 1036 1037 1038 1039 1040
  STSchema *pTSchema = NULL;
  int       sver = -1;
  code = metaGetTbTSchemaEx(pTsdb->pVnode->pMeta, suid, uid, sver, &pTSchema);
  if (code != TSDB_CODE_SUCCESS) {
    terrno = code;
    return -1;
1041 1042
  }

1043
  // build keys & multi get from rocks
M
Minglei Jin 已提交
1044 1045 1046 1047
  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));
  const size_t klen = ROCKS_KEY_LEN;
1048 1049 1050
  for (int i = 0; i < num_keys; ++i) {
    int16_t cid = pTSchema->columns[i].colId;

M
Minglei Jin 已提交
1051
    char *keys = taosMemoryCalloc(2, sizeof(SLastKey));
1052 1053 1054
    ((SLastKey *)keys)[0] = (SLastKey){.ltype = 1, .uid = uid, .cid = cid};
    ((SLastKey *)keys)[1] = (SLastKey){.ltype = 0, .uid = uid, .cid = cid};

1055
    keys_list[i] = keys;
M
Minglei Jin 已提交
1056
    keys_list[num_keys + i] = keys + sizeof(SLastKey);
1057 1058
    keys_list_sizes[i] = klen;
    keys_list_sizes[num_keys + i] = klen;
1059 1060 1061 1062
  }
  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 *));
1063
  taosThreadMutexLock(&pTsdb->lruMutex);
1064
  taosThreadMutexLock(&pTsdb->rCache.rMutex);
1065
  rocksMayWrite(pTsdb, true, false, false);
1066 1067
  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);
D
dapan1121 已提交
1068 1069
  taosThreadMutexUnlock(&pTsdb->rCache.rMutex);

1070
  for (int i = 0; i < num_keys * 2; ++i) {
M
Minglei Jin 已提交
1071 1072 1073
    if (errs[i]) {
      rocksdb_free(errs[i]);
    }
1074 1075 1076 1077 1078
  }
  taosMemoryFree(errs);

  rocksdb_writebatch_t *wb = pTsdb->rCache.writebatch;
  for (int i = 0; i < num_keys; ++i) {
1079
    SLastCol *pLastCol = tsdbCacheDeserialize(values_list[i]);
D
dapan1121 已提交
1080
    taosThreadMutexLock(&pTsdb->rCache.rMutex);
1081
    if (NULL != pLastCol && (pLastCol->ts <= eKey && pLastCol->ts >= sKey)) {
M
Minglei Jin 已提交
1082
      rocksdb_writebatch_delete(wb, keys_list[i], klen);
1083
    }
1084 1085
    pLastCol = tsdbCacheDeserialize(values_list[i + num_keys]);
    if (NULL != pLastCol && (pLastCol->ts <= eKey && pLastCol->ts >= sKey)) {
M
Minglei Jin 已提交
1086
      rocksdb_writebatch_delete(wb, keys_list[num_keys + i], klen);
1087
    }
D
dapan1121 已提交
1088
    taosThreadMutexUnlock(&pTsdb->rCache.rMutex);
1089 1090 1091

    rocksdb_free(values_list[i]);
    rocksdb_free(values_list[i + num_keys]);
D
dapan1121 已提交
1092

1093
    // taosThreadMutexLock(&pTsdb->lruMutex);
D
dapan1121 已提交
1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114

    LRUHandle *h = taosLRUCacheLookup(pTsdb->lruCache, keys_list[i], klen);
    if (h) {
      SLastCol *pLastCol = (SLastCol *)taosLRUCacheValue(pTsdb->lruCache, h);
      if (pLastCol->dirty) {
        pLastCol->dirty = 0;
      }
      taosLRUCacheRelease(pTsdb->lruCache, h, true);
    }
    taosLRUCacheErase(pTsdb->lruCache, keys_list[i], klen);

    h = taosLRUCacheLookup(pTsdb->lruCache, keys_list[num_keys + i], klen);
    if (h) {
      SLastCol *pLastCol = (SLastCol *)taosLRUCacheValue(pTsdb->lruCache, h);
      if (pLastCol->dirty) {
        pLastCol->dirty = 0;
      }
      taosLRUCacheRelease(pTsdb->lruCache, h, true);
    }
    taosLRUCacheErase(pTsdb->lruCache, keys_list[num_keys + i], klen);

1115
    // taosThreadMutexUnlock(&pTsdb->lruMutex);
1116
  }
M
Minglei Jin 已提交
1117 1118 1119 1120 1121
  for (int i = 0; i < num_keys; ++i) {
    taosMemoryFree(keys_list[i]);
  }
  taosMemoryFree(keys_list);
  taosMemoryFree(keys_list_sizes);
1122 1123 1124
  taosMemoryFree(values_list);
  taosMemoryFree(values_list_sizes);

D
dapan1121 已提交
1125
  rocksMayWrite(pTsdb, true, false, true);
1126

1127 1128
  taosThreadMutexUnlock(&pTsdb->lruMutex);

1129
_exit:
M
Minglei Jin 已提交
1130
  taosMemoryFree(pTSchema);
1131 1132 1133 1134

  return code;
}

1135
int32_t tsdbOpenCache(STsdb *pTsdb) {
H
Hongze Cheng 已提交
1136
  int32_t    code = 0;
1137
  SLRUCache *pCache = NULL;
1138
  size_t     cfgCapacity = pTsdb->pVnode->config.cacheLastSize * 1024 * 1024;
1139

D
dapan1121 已提交
1140
  pCache = taosLRUCacheInit(cfgCapacity, 0, .5);
1141 1142 1143 1144 1145
  if (pCache == NULL) {
    code = TSDB_CODE_OUT_OF_MEMORY;
    goto _err;
  }

1146 1147 1148 1149 1150 1151
  code = tsdbOpenBICache(pTsdb);
  if (code != TSDB_CODE_SUCCESS) {
    code = TSDB_CODE_OUT_OF_MEMORY;
    goto _err;
  }

1152 1153 1154 1155 1156 1157
  code = tsdbOpenRocksCache(pTsdb);
  if (code != TSDB_CODE_SUCCESS) {
    code = TSDB_CODE_OUT_OF_MEMORY;
    goto _err;
  }

1158
  taosLRUCacheSetStrictCapacity(pCache, false);
1159

1160 1161
  taosThreadMutexInit(&pTsdb->lruMutex, NULL);

D
dapan1121 已提交
1162 1163 1164
  pTsdb->flushState.pTsdb = pTsdb;
  pTsdb->flushState.flush_count = 0;

1165 1166 1167 1168 1169
_err:
  pTsdb->lruCache = pCache;
  return code;
}

1170 1171
void tsdbCloseCache(STsdb *pTsdb) {
  SLRUCache *pCache = pTsdb->lruCache;
1172 1173 1174 1175
  if (pCache) {
    taosLRUCacheEraseUnrefEntries(pCache);

    taosLRUCacheCleanup(pCache);
1176 1177

    taosThreadMutexDestroy(&pTsdb->lruMutex);
1178
  }
1179 1180

  tsdbCloseBICache(pTsdb);
1181
  tsdbCloseRocksCache(pTsdb);
1182 1183
}

1184 1185 1186 1187 1188 1189 1190 1191 1192 1193
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);
}

D
dapan1121 已提交
1194 1195
static void deleteTableCacheLast(const void *key, size_t keyLen, void *value, void *ud) {
  (void)ud;
1196 1197 1198 1199
  SArray *pLastArray = (SArray *)value;
  int16_t nCol = taosArrayGetSize(pLastArray);
  for (int16_t iCol = 0; iCol < nCol; ++iCol) {
    SLastCol *pLastCol = (SLastCol *)taosArrayGet(pLastArray, iCol);
1200
    if (IS_VAR_DATA_TYPE(pLastCol->colVal.type) && pLastCol->colVal.value.nData > 0) {
1201 1202 1203 1204 1205 1206
      taosMemoryFree(pLastCol->colVal.value.pData);
    }
  }

  taosArrayDestroy(value);
}
1207

1208
int32_t tsdbCacheDeleteLastrow(SLRUCache *pCache, tb_uid_t uid, TSKEY eKey) {
1209
  int32_t code = 0;
1210 1211 1212

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

1214 1215
  // getTableCacheKey(uid, "lr", key, &keyLen);
  getTableCacheKey(uid, 0, key, &keyLen);
1216 1217
  LRUHandle *h = taosLRUCacheLookup(pCache, key, keyLen);
  if (h) {
1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229
    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;
      }
    }

1230
    taosLRUCacheRelease(pCache, h, invalidate);
1231
    if (invalidate) {
1232
      taosLRUCacheErase(pCache, key, keyLen);
1233 1234 1235 1236 1237 1238
    }
  }

  return code;
}

1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260
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;
      }
    }

1261
    taosLRUCacheRelease(pCache, h, invalidate);
1262
    if (invalidate) {
1263
      taosLRUCacheErase(pCache, key, keyLen);
1264 1265 1266 1267 1268
    }
  }

  return code;
}
1269

H
Hongze Cheng 已提交
1270
int32_t tsdbCacheInsertLastrow(SLRUCache *pCache, STsdb *pTsdb, tb_uid_t uid, TSDBROW *row, bool dup) {
1271 1272
  int32_t code = 0;
  STSRow *cacheRow = NULL;
H
Hongze Cheng 已提交
1273 1274
  char    key[32] = {0};
  int     keyLen = 0;
1275

1276 1277
  // getTableCacheKey(uid, "lr", key, &keyLen);
  getTableCacheKey(uid, 0, key, &keyLen);
1278 1279
  LRUHandle *h = taosLRUCacheLookup(pCache, key, keyLen);
  if (h) {
1280
    STSchema *pTSchema = metaGetTbTSchema(pTsdb->pVnode->pMeta, uid, -1, 1);
H
Hongze Cheng 已提交
1281
    TSKEY     keyTs = TSDBROW_TS(row);
1282 1283 1284 1285 1286 1287
    bool      invalidate = false;

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

1288 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 1322
    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;
    }

1323 1324 1325 1326 1327
    if (nCol != pTSchema->numOfCols) {
      invalidate = true;
      goto _invalidate;
    }

1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341
    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 已提交
1342
        tsdbRowGetColVal(row, pTSchema, iCol, &colVal);
1343 1344 1345 1346 1347 1348

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

1349 1350 1351 1352 1353
        if (!COL_VAL_IS_NONE(&colVal)) {
          if (keyTs == tTsVal1->ts && !COL_VAL_IS_NONE(tColVal)) {
            invalidate = true;

            break;
1354 1355 1356 1357
          } 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);
1358 1359
              if (pLastCol->colVal.value.nData > 0 && NULL != pLastCol->colVal.value.pData)
                taosMemoryFree(pLastCol->colVal.value.pData);
1360 1361 1362 1363 1364 1365 1366 1367

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

1370 1371
            taosArraySet(pLast, iCol, &lastCol);
          }
1372 1373 1374 1375 1376 1377 1378 1379
        }
      }
    }

  _invalidate:
    taosMemoryFreeClear(pTSchema);

    taosLRUCacheRelease(pCache, h, invalidate);
1380 1381
    if (invalidate) {
      taosLRUCacheErase(pCache, key, keyLen);
1382
    }
1383
  }
1384 1385 1386 1387

  return code;
}

H
Hongze Cheng 已提交
1388
int32_t tsdbCacheInsertLast(SLRUCache *pCache, tb_uid_t uid, TSDBROW *row, STsdb *pTsdb) {
1389 1390 1391 1392 1393
  int32_t code = 0;
  STSRow *cacheRow = NULL;
  char    key[32] = {0};
  int     keyLen = 0;

1394 1395
  // getTableCacheKey(uid, "l", key, &keyLen);
  getTableCacheKey(uid, 1, key, &keyLen);
1396 1397
  LRUHandle *h = taosLRUCacheLookup(pCache, key, keyLen);
  if (h) {
1398
    STSchema *pTSchema = metaGetTbTSchema(pTsdb->pVnode->pMeta, uid, -1, 1);
H
Hongze Cheng 已提交
1399
    TSKEY     keyTs = TSDBROW_TS(row);
1400 1401 1402 1403 1404 1405
    bool      invalidate = false;

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

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 1437 1438 1439 1440
    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;
    }

1441 1442 1443 1444 1445
    if (nCol != pTSchema->numOfCols) {
      invalidate = true;
      goto _invalidate;
    }

1446 1447 1448
    SLastCol *tTsVal = (SLastCol *)taosArrayGet(pLast, iCol);
    if (keyTs > tTsVal->ts) {
      STColumn *pTColumn = &pTSchema->columns[0];
H
Hongze Cheng 已提交
1449
      SColVal   tColVal = COL_VAL_VALUE(pTColumn->colId, pTColumn->type, (SValue){.val = keyTs});
1450 1451 1452 1453 1454

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

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

        SColVal colVal = {0};
H
Hongze Cheng 已提交
1460
        tsdbRowGetColVal(row, pTSchema, iCol, &colVal);
1461 1462 1463 1464 1465 1466

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

1467
        if (COL_VAL_IS_VALUE(&colVal)) {
H
Hongze Cheng 已提交
1468
          if (keyTs == tTsVal1->ts && COL_VAL_IS_VALUE(tColVal)) {
1469 1470 1471
            invalidate = true;

            break;
1472 1473 1474 1475
          } else {
            SLastCol lastCol = {.ts = keyTs, .colVal = colVal};
            if (IS_VAR_DATA_TYPE(colVal.type) && colVal.value.nData > 0) {
              SLastCol *pLastCol = (SLastCol *)taosArrayGet(pLast, iCol);
1476 1477
              if (pLastCol->colVal.value.nData > 0 && NULL != pLastCol->colVal.value.pData)
                taosMemoryFree(pLastCol->colVal.value.pData);
1478 1479 1480 1481 1482 1483 1484 1485

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

1488 1489
            taosArraySet(pLast, iCol, &lastCol);
          }
1490 1491 1492 1493
        }
      }
    }

1494
  _invalidate:
1495 1496 1497
    taosMemoryFreeClear(pTSchema);

    taosLRUCacheRelease(pCache, h, invalidate);
1498 1499 1500
    if (invalidate) {
      taosLRUCacheErase(pCache, key, keyLen);
    }
1501 1502 1503 1504 1505
  }

  return code;
}

1506 1507 1508 1509
static tb_uid_t getTableSuidByUid(tb_uid_t uid, STsdb *pTsdb) {
  tb_uid_t suid = 0;

  SMetaReader mr = {0};
1510
  metaReaderDoInit(&mr, pTsdb->pVnode->pMeta, 0);
1511
  if (metaReaderGetTableEntryByUidCache(&mr, uid) < 0) {
H
Hongze Cheng 已提交
1512
    metaReaderClear(&mr);  // table not esist
1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532
    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
Haojun Liao 已提交
1533
    code = tsdbReadDelDatav1(pDelReader, pDelIdx, aDelData, INT64_MAX);
1534 1535 1536 1537 1538 1539
  }

  return code;
}

static int32_t getTableDelDataFromTbData(STbData *pTbData, SArray *aDelData) {
H
Hongze Cheng 已提交
1540
  int32_t   code = 0;
1541 1542 1543 1544 1545 1546 1547 1548 1549
  SDelData *pDelData = pTbData ? pTbData->pHead : NULL;

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

  return code;
}

H
Hongze Cheng 已提交
1550 1551
static int32_t getTableDelData(STbData *pMem, STbData *pIMem, SDelFReader *pDelReader, SDelIdx *pDelIdx,
                               SArray *aDelData) {
1552 1553
  int32_t code = 0;

1554 1555 1556 1557 1558
  if (pDelIdx) {
    code = getTableDelDataFromDelIdx(pDelReader, pDelIdx, aDelData);
    if (code) goto _err;
  }

1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572
  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 已提交
1573 1574
static int32_t getTableDelSkyline(STbData *pMem, STbData *pIMem, SDelFReader *pDelReader, SDelIdx *pDelIdx,
                                  SArray *aSkyline) {
1575
  int32_t code = 0;
M
Minglei Jin 已提交
1576
  SArray *aDelData = NULL;
1577

M
Minglei Jin 已提交
1578
  aDelData = taosArrayInit(32, sizeof(SDelData));
1579 1580 1581 1582
  code = getTableDelData(pMem, pIMem, pDelReader, pDelIdx, aDelData);
  if (code) goto _err;

  size_t nDelData = taosArrayGetSize(aDelData);
1583 1584 1585 1586
  if (nDelData > 0) {
    code = tsdbBuildDeleteSkyline(aDelData, 0, (int32_t)(nDelData - 1), aSkyline);
    if (code) goto _err;
  }
1587

1588
_err:
M
Minglei Jin 已提交
1589 1590 1591
  if (aDelData) {
    taosArrayDestroy(aDelData);
  }
1592 1593 1594
  return code;
}

1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606
static void freeTableInfoFunc(void *param) {
  void **p = (void **)param;
  taosMemoryFreeClear(*p);
}

static STableLoadInfo *getTableLoadInfo(SCacheRowsReader *pReader, uint64_t uid) {
  if (!pReader->pTableMap) {
    pReader->pTableMap = tSimpleHashInit(pReader->numOfTables, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT));

    tSimpleHashSetFreeFp(pReader->pTableMap, freeTableInfoFunc);
  }

1607
  STableLoadInfo  *pInfo = NULL;
M
Minglei Jin 已提交
1608 1609
  STableLoadInfo **ppInfo = tSimpleHashGet(pReader->pTableMap, &uid, sizeof(uid));
  if (!ppInfo) {
1610
    pInfo = taosMemoryCalloc(1, sizeof(STableLoadInfo));
1611
    tSimpleHashPut(pReader->pTableMap, &uid, sizeof(uint64_t), &pInfo, POINTER_BYTES);
M
Minglei Jin 已提交
1612

1613
    return pInfo;
1614 1615
  }

M
Minglei Jin 已提交
1616
  return *ppInfo;
1617 1618
}

1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635
static uint64_t *getUidList(SCacheRowsReader *pReader) {
  if (!pReader->uidList) {
    int32_t numOfTables = pReader->numOfTables;

    pReader->uidList = taosMemoryMalloc(numOfTables * sizeof(uint64_t));

    for (int32_t i = 0; i < numOfTables; ++i) {
      uint64_t uid = pReader->pTableList[i].uid;
      pReader->uidList[i] = uid;
    }

    taosSort(pReader->uidList, numOfTables, sizeof(uint64_t), uidComparFunc);
  }

  return pReader->uidList;
}

1636 1637
static int32_t loadTombFromBlk(const TTombBlkArray *pTombBlkArray, SCacheRowsReader *pReader, void *pFileReader,
                               bool isFile) {
1638
  int32_t   code = 0;
1639
  uint64_t *uidList = getUidList(pReader);
1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661
  int32_t   numOfTables = pReader->numOfTables;
  int64_t   suid = pReader->info.suid;

  for (int i = 0, j = 0; i < pTombBlkArray->size && j < numOfTables; ++i) {
    STombBlk *pTombBlk = &pTombBlkArray->data[i];
    if (pTombBlk->maxTbid.suid < suid || (pTombBlk->maxTbid.suid == suid && pTombBlk->maxTbid.uid < uidList[0])) {
      continue;
    }

    if (pTombBlk->minTbid.suid > suid ||
        (pTombBlk->minTbid.suid == suid && pTombBlk->minTbid.uid > uidList[numOfTables - 1])) {
      break;
    }

    STombBlock block = {0};
    code = isFile ? tsdbDataFileReadTombBlock(pFileReader, &pTombBlkArray->data[i], &block)
                  : tsdbSttFileReadTombBlock(pFileReader, &pTombBlkArray->data[i], &block);
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

    uint64_t        uid = uidList[j];
1662
    STableLoadInfo *pInfo = getTableLoadInfo(pReader, uid);
1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703
    if (pInfo->pTombData == NULL) {
      pInfo->pTombData = taosArrayInit(4, sizeof(SDelData));
    }

    STombRecord record = {0};
    bool        finished = false;
    for (int32_t k = 0; k < TARRAY2_SIZE(block.suid); ++k) {
      code = tTombBlockGet(&block, k, &record);
      if (code != TSDB_CODE_SUCCESS) {
        finished = true;
        break;
      }

      if (record.suid < suid) {
        continue;
      }
      if (record.suid > suid) {
        finished = true;
        break;
      }

      bool newTable = false;
      if (uid < record.uid) {
        while (j < numOfTables && uidList[j] < record.uid) {
          ++j;
          newTable = true;
        }

        if (j >= numOfTables) {
          finished = true;
          break;
        }

        uid = uidList[j];
      }

      if (record.uid < uid) {
        continue;
      }

      if (newTable) {
1704
        pInfo = getTableLoadInfo(pReader, uid);
1705 1706 1707 1708 1709 1710
        if (pInfo->pTombData == NULL) {
          pInfo->pTombData = taosArrayInit(4, sizeof(SDelData));
        }
      }

      if (record.version <= pReader->info.verRange.maxVer) {
1711 1712 1713
        tsdbError("tomb xx load/cache: vgId:%d fid:%d commit %" PRId64 "~%" PRId64 "~%" PRId64 " tomb records",
                  TD_VID(pReader->pTsdb->pVnode), pReader->pCurFileSet->fid, record.skey, record.ekey, uid);

1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724
        SDelData delData = {.version = record.version, .sKey = record.skey, .eKey = record.ekey};
        taosArrayPush(pInfo->pTombData, &delData);
      }
    }

    tTombBlockDestroy(&block);

    if (finished) {
      return code;
    }
  }
1725

1726 1727
  return TSDB_CODE_SUCCESS;
}
1728

1729 1730
static int32_t loadDataTomb(SCacheRowsReader *pReader, SDataFileReader *pFileReader) {
  int32_t code = 0;
1731

1732 1733 1734 1735
  const TTombBlkArray *pBlkArray = NULL;
  code = tsdbDataFileReadTombBlk(pFileReader, &pBlkArray);
  if (code != TSDB_CODE_SUCCESS) {
    return code;
M
Minglei Jin 已提交
1736
  }
1737 1738

  return loadTombFromBlk(pBlkArray, pReader, pFileReader, true);
1739
}
1740

1741
static int32_t loadSttTomb(STsdbReader *pTsdbReader, SSttFileReader *pSttFileReader, SSttBlockLoadInfo *pLoadInfo) {
1742
  int32_t code = 0;
M
Minglei Jin 已提交
1743 1744 1745

  SCacheRowsReader *pReader = (SCacheRowsReader *)pTsdbReader;

1746
  const TTombBlkArray *pBlkArray = NULL;
M
Minglei Jin 已提交
1747
  code = tsdbSttFileReadTombBlk(pSttFileReader, &pBlkArray);
1748 1749 1750 1751
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

1752
  return loadTombFromBlk(pBlkArray, pReader, pSttFileReader, false);
1753 1754
}

1755 1756 1757 1758 1759
typedef struct {
  SMergeTree  mergeTree;
  SMergeTree *pMergeTree;
} SFSLastIter;

1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781
static int32_t lastIterOpen(SFSLastIter *iter, STFileSet *pFileSet, STsdb *pTsdb, STSchema *pTSchema, tb_uid_t suid,
                            tb_uid_t uid, SCacheRowsReader *pr, int64_t lastTs, int16_t *aCols, int nCols) {
  int32_t code = 0;

  int64_t loadBlocks = 0;
  double  elapse = 0;
  pr->pLDataIterArray = destroySttBlockReader(pr->pLDataIterArray, &loadBlocks, &elapse);
  pr->pLDataIterArray = taosArrayInit(4, POINTER_BYTES);

  SMergeTreeConf conf = {
      .uid = uid,
      .suid = suid,
      .pTsdb = pTsdb,
      .timewindow = (STimeWindow){.skey = lastTs, .ekey = TSKEY_MAX},
      .verRange = (SVersionRange){.minVer = 0, .maxVer = UINT64_MAX},
      .strictTimeRange = false,
      .pSchema = pTSchema,
      .pCurrentFileset = pFileSet,
      .backward = 1,
      .pSttFileBlockIterArray = pr->pLDataIterArray,
      .pCols = aCols,
      .numOfCols = nCols,
1782
      .loadTombFn = loadSttTomb,
1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796
      .pReader = pr,
      .idstr = pr->idstr,
  };

  code = tMergeTreeOpen2(&iter->mergeTree, &conf);
  if (code != TSDB_CODE_SUCCESS) {
    return -1;
  }

  iter->pMergeTree = &iter->mergeTree;

  return code;
}

M
Minglei Jin 已提交
1797 1798
static int32_t lastIterClose(SFSLastIter **iter) {
  int32_t code = 0;
1799

M
Minglei Jin 已提交
1800 1801 1802
  if ((*iter)->pMergeTree) {
    tMergeTreeClose((*iter)->pMergeTree);
    (*iter)->pMergeTree = NULL;
M
Minglei Jin 已提交
1803
  }
1804

M
Minglei Jin 已提交
1805
  *iter = NULL;
1806

M
Minglei Jin 已提交
1807 1808
  return code;
}
M
Minglei Jin 已提交
1809

1810
static int32_t lastIterNext(SFSLastIter *iter, TSDBROW **ppRow) {
M
Minglei Jin 已提交
1811
  int32_t code = 0;
1812

M
Minglei Jin 已提交
1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830
  bool hasVal = tMergeTreeNext(iter->pMergeTree);
  if (!hasVal) {
    *ppRow = NULL;
    return code;
  }

  *ppRow = tMergeTreeGetRow(iter->pMergeTree);

  return code;
}

typedef enum SFSNEXTROWSTATES {
  SFSNEXTROW_FS,
  SFSNEXTROW_FILESET,
  SFSNEXTROW_INDEXLIST,
  SFSNEXTROW_BRINBLOCK,
  SFSNEXTROW_BRINRECORD,
  SFSNEXTROW_BLOCKDATA,
1831 1832
  SFSNEXTROW_BLOCKROW,
  SFSNEXTROW_NEXTSTTROW
M
Minglei Jin 已提交
1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858
} SFSNEXTROWSTATES;

struct CacheNextRowIter;

typedef struct SFSNextRowIter {
  SFSNEXTROWSTATES         state;         // [input]
  SBlockIdx               *pBlockIdxExp;  // [input]
  STSchema                *pTSchema;      // [input]
  tb_uid_t                 suid;
  tb_uid_t                 uid;
  int32_t                  iFileSet;
  STFileSet               *pFileSet;
  TFileSetArray           *aDFileSet;
  SArray                  *pIndexList;
  int32_t                  iBrinIndex;
  SBrinBlock               brinBlock;
  int32_t                  iBrinRecord;
  SBrinRecord              brinRecord;
  SBlockData               blockData;
  SBlockData              *pBlockData;
  int32_t                  nRow;
  int32_t                  iRow;
  TSDBROW                  row;
  int64_t                  lastTs;
  SFSLastIter              lastIter;
  SFSLastIter             *pLastIter;
1859
  int8_t                   lastEmpty;
M
Minglei Jin 已提交
1860
  TSDBROW                 *pLastRow;
M
Minglei Jin 已提交
1861 1862
  SRow                    *pTSRow;
  SRowMerger               rowMerger;
M
Minglei Jin 已提交
1863
  SCacheRowsReader        *pr;
M
Minglei Jin 已提交
1864 1865 1866
  struct CacheNextRowIter *pRowIter;
} SFSNextRowIter;

1867
static void clearLastFileSet(SFSNextRowIter *state);
1868

M
Minglei Jin 已提交
1869 1870 1871 1872
static int32_t getNextRowFromFS(void *iter, TSDBROW **ppRow, bool *pIgnoreEarlierTs, bool isLast, int16_t *aCols,
                                int nCols) {
  SFSNextRowIter *state = (SFSNextRowIter *)iter;
  int32_t         code = 0;
1873
  STsdb          *pTsdb = state->pr->pTsdb;
M
Minglei Jin 已提交
1874 1875

  if (SFSNEXTROW_FS == state->state) {
1876
    state->iFileSet = TARRAY2_SIZE(state->aDFileSet);
1877

M
Minglei Jin 已提交
1878 1879 1880 1881 1882
    state->state = SFSNEXTROW_FILESET;
  }

  if (SFSNEXTROW_FILESET == state->state) {
  _next_fileset:
1883 1884
    if (--state->iFileSet < 0) {
      clearLastFileSet(state);
M
Minglei Jin 已提交
1885

1886 1887
      *ppRow = NULL;
      return code;
M
Minglei Jin 已提交
1888 1889 1890 1891
    } else {
      state->pFileSet = TARRAY2_GET(state->aDFileSet, state->iFileSet);
    }

M
Minglei Jin 已提交
1892
    STFileObj **pFileObj = state->pFileSet->farr;
M
Minglei Jin 已提交
1893
    if (pFileObj[0] != NULL || pFileObj[3] != NULL) {
1894
      if (state->pFileSet != state->pr->pCurFileSet) {
1895
        SDataFileReaderConfig conf = {.tsdb = pTsdb, .szPage = pTsdb->pVnode->config.tsdbPageSize};
1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909
        const char           *filesName[4] = {0};
        if (pFileObj[0] != NULL) {
          conf.files[0].file = *pFileObj[0]->f;
          conf.files[0].exist = true;
          filesName[0] = pFileObj[0]->fname;

          conf.files[1].file = *pFileObj[1]->f;
          conf.files[1].exist = true;
          filesName[1] = pFileObj[1]->fname;

          conf.files[2].file = *pFileObj[2]->f;
          conf.files[2].exist = true;
          filesName[2] = pFileObj[2]->fname;
        }
M
Minglei Jin 已提交
1910

1911 1912 1913 1914 1915
        if (pFileObj[3] != NULL) {
          conf.files[3].exist = true;
          conf.files[3].file = *pFileObj[3]->f;
          filesName[3] = pFileObj[3]->fname;
        }
M
Minglei Jin 已提交
1916

1917 1918 1919 1920 1921 1922
        code = tsdbDataFileReaderOpen(filesName, &conf, &state->pr->pFileReader);
        if (code != TSDB_CODE_SUCCESS) {
          goto _err;
        }

        state->pr->pCurFileSet = state->pFileSet;
1923 1924

        loadDataTomb(state->pr, state->pr->pFileReader);
1925 1926 1927 1928 1929

        int32_t code = tsdbDataFileReadBrinBlk(state->pr->pFileReader, &state->pr->pBlkArray);
        if (code != TSDB_CODE_SUCCESS) {
          goto _err;
        }
1930
      }
1931

M
Minglei Jin 已提交
1932 1933 1934 1935
      if (!state->pIndexList) {
        state->pIndexList = taosArrayInit(1, sizeof(SBrinBlk));
      } else {
        taosArrayClear(state->pIndexList);
1936
      }
D
dapan1121 已提交
1937

1938
      const TBrinBlkArray *pBlkArray = state->pr->pBlkArray;
D
dapan1121 已提交
1939

1940
      for (int i = TARRAY2_SIZE(pBlkArray) - 1; i >= 0; --i) {
M
Minglei Jin 已提交
1941 1942 1943 1944 1945 1946 1947 1948 1949
        SBrinBlk *pBrinBlk = &pBlkArray->data[i];
        if (state->suid >= pBrinBlk->minTbid.suid && state->suid <= pBrinBlk->maxTbid.suid) {
          if (state->uid >= pBrinBlk->minTbid.uid && state->uid <= pBrinBlk->maxTbid.uid) {
            taosArrayPush(state->pIndexList, pBrinBlk);
          }
        } else if (state->suid > pBrinBlk->maxTbid.suid ||
                   (state->suid == pBrinBlk->maxTbid.suid && state->uid > pBrinBlk->maxTbid.uid)) {
          break;
        }
1950
      }
M
Minglei Jin 已提交
1951 1952 1953

      int indexSize = TARRAY_SIZE(state->pIndexList);
      if (indexSize <= 0) {
1954
        goto _check_stt_data;
1955
      }
M
Minglei Jin 已提交
1956 1957 1958

      state->state = SFSNEXTROW_INDEXLIST;
      state->iBrinIndex = indexSize;
1959 1960
    }

1961
  _check_stt_data:
1962 1963 1964 1965
    if (state->pFileSet != state->pr->pCurFileSet) {
      state->pr->pCurFileSet = state->pFileSet;
    }

1966 1967
    code = lastIterOpen(&state->lastIter, state->pFileSet, pTsdb, state->pTSchema, state->suid, state->uid, state->pr,
                        state->lastTs, aCols, nCols);
1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005
    if (code != TSDB_CODE_SUCCESS) {
      goto _err;
    }

    code = lastIterNext(&state->lastIter, &state->pLastRow);
    if (code != TSDB_CODE_SUCCESS) {
      goto _err;
    }

    if (!state->pLastRow) {
      state->lastEmpty = 1;

      if (SFSNEXTROW_INDEXLIST != state->state) {
        clearLastFileSet(state);
        goto _next_fileset;
      }
    } else {
      state->lastEmpty = 0;

      if (SFSNEXTROW_INDEXLIST != state->state) {
        state->state = SFSNEXTROW_NEXTSTTROW;

        *ppRow = state->pLastRow;
        state->pLastRow = NULL;
        return code;
      }
    }

    state->pLastIter = &state->lastIter;
  }

  if (SFSNEXTROW_NEXTSTTROW == state->state) {
    code = lastIterNext(&state->lastIter, &state->pLastRow);
    if (code != TSDB_CODE_SUCCESS) {
      goto _err;
    }

    if (!state->pLastRow) {
2006 2007 2008
      if (state->pLastIter) {
        lastIterClose(&state->pLastIter);
      }
2009 2010 2011

      clearLastFileSet(state);
      state->state = SFSNEXTROW_FILESET;
2012
      goto _next_fileset;
2013 2014 2015 2016
    } else {
      *ppRow = state->pLastRow;
      state->pLastRow = NULL;
      return code;
2017
    }
2018 2019
  }

M
Minglei Jin 已提交
2020 2021 2022
  if (SFSNEXTROW_INDEXLIST == state->state) {
    SBrinBlk *pBrinBlk = NULL;
  _next_brinindex:
2023 2024 2025 2026 2027 2028 2029 2030
    if (--state->iBrinIndex < 0) {
      if (state->pLastRow) {
        state->state = SFSNEXTROW_NEXTSTTROW;
        *ppRow = state->pLastRow;
        state->pLastRow = NULL;
        return code;
      }

2031 2032
      clearLastFileSet(state);
      goto _next_fileset;
M
Minglei Jin 已提交
2033 2034 2035 2036
    } else {
      pBrinBlk = taosArrayGet(state->pIndexList, state->iBrinIndex);
    }

2037
    code = tsdbDataFileReadBrinBlock(state->pr->pFileReader, pBrinBlk, &state->brinBlock);
M
Minglei Jin 已提交
2038 2039 2040 2041 2042 2043
    if (code != TSDB_CODE_SUCCESS) {
      goto _err;
    }

    state->iBrinRecord = BRIN_BLOCK_SIZE(&state->brinBlock) - 1;
    state->state = SFSNEXTROW_BRINBLOCK;
2044 2045
  }

M
Minglei Jin 已提交
2046 2047 2048 2049 2050 2051 2052 2053 2054 2055
  if (SFSNEXTROW_BRINBLOCK == state->state) {
  _next_brinrecord:
    if (state->iBrinRecord < 0) {  // empty brin block, goto _next_brinindex
      tBrinBlockClear(&state->brinBlock);
      goto _next_brinindex;
    }
    code = tBrinBlockGet(&state->brinBlock, state->iBrinRecord, &state->brinRecord);
    if (code != TSDB_CODE_SUCCESS) {
      goto _err;
    }
2056

M
Minglei Jin 已提交
2057 2058 2059 2060 2061 2062
    SBrinRecord *pRecord = &state->brinRecord;
    if (pRecord->uid != state->uid) {
      // TODO: goto next brin block early
      --state->iBrinRecord;
      goto _next_brinrecord;
    }
2063

M
Minglei Jin 已提交
2064 2065
    state->state = SFSNEXTROW_BRINRECORD;
  }
2066

M
Minglei Jin 已提交
2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081
  if (SFSNEXTROW_BRINRECORD == state->state) {
    SBrinRecord *pRecord = &state->brinRecord;

    if (!state->pBlockData) {
      state->pBlockData = &state->blockData;
      code = tBlockDataCreate(&state->blockData);
      if (code) goto _err;
    } else {
      tBlockDataReset(state->pBlockData);
    }

    if (aCols[0] == PRIMARYKEY_TIMESTAMP_COL_ID) {
      --nCols;
      ++aCols;
    }
2082
    code = tsdbDataFileReadBlockDataByColumn(state->pr->pFileReader, pRecord, state->pBlockData, state->pTSchema, aCols,
M
Minglei Jin 已提交
2083 2084 2085 2086 2087 2088 2089 2090 2091
                                             nCols);
    if (code != TSDB_CODE_SUCCESS) {
      goto _err;
    }

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

    state->state = SFSNEXTROW_BLOCKROW;
2092
  }
M
Minglei Jin 已提交
2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108

  if (SFSNEXTROW_BLOCKROW == state->state) {
    if (state->iRow < 0) {
      --state->iBrinRecord;
      goto _next_brinrecord;
    }

    state->row = tsdbRowFromBlockData(state->pBlockData, state->iRow);
    if (!state->pLastIter) {
      *ppRow = &state->row;
      --state->iRow;
      return code;
    }

    if (!state->pLastRow) {
      // get next row from fslast and process with fs row, --state->Row if select fs row
2109
      code = lastIterNext(&state->lastIter, &state->pLastRow);
M
Minglei Jin 已提交
2110 2111 2112 2113 2114 2115
      if (code != TSDB_CODE_SUCCESS) {
        goto _err;
      }
    }

    if (!state->pLastRow) {
2116 2117 2118
      if (state->pLastIter) {
        lastIterClose(&state->pLastIter);
      }
M
Minglei Jin 已提交
2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137

      *ppRow = &state->row;
      --state->iRow;
      return code;
    }

    // process state->pLastRow & state->row
    TSKEY rowTs = TSDBROW_TS(&state->row);
    TSKEY lastRowTs = TSDBROW_TS(state->pLastRow);
    if (lastRowTs > rowTs) {
      *ppRow = state->pLastRow;
      state->pLastRow = NULL;
      return code;
    } else if (lastRowTs < rowTs) {
      *ppRow = &state->row;
      --state->iRow;
      return code;
    } else {
      // TODO: merge rows and *ppRow = mergedRow
M
Minglei Jin 已提交
2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166
      SRowMerger *pMerger = &state->rowMerger;
      tsdbRowMergerInit(pMerger, state->pTSchema);

      code = tsdbRowMergerAdd(pMerger, &state->row, state->pTSchema);
      if (code != TSDB_CODE_SUCCESS) {
        goto _err;
      }
      code = tsdbRowMergerAdd(pMerger, state->pLastRow, state->pTSchema);
      if (code != TSDB_CODE_SUCCESS) {
        goto _err;
      }

      if (state->pTSRow) {
        taosMemoryFree(state->pTSRow);
        state->pTSRow = NULL;
      }

      code = tsdbRowMergerGetRow(pMerger, &state->pTSRow);
      if (code != TSDB_CODE_SUCCESS) {
        goto _err;
      }

      state->row = tsdbRowFromTSRow(TSDBROW_VERSION(&state->row), state->pTSRow);
      *ppRow = &state->row;
      --state->iRow;

      tsdbRowMergerClear(pMerger);

      return code;
M
Minglei Jin 已提交
2167
    }
2168
  }
M
Minglei Jin 已提交
2169 2170

_err:
2171
  clearLastFileSet(state);
M
Minglei Jin 已提交
2172

2173
  *ppRow = NULL;
2174

2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186
  return code;
}

typedef enum SMEMNEXTROWSTATES {
  SMEMNEXTROW_ENTER,
  SMEMNEXTROW_NEXT,
} SMEMNEXTROWSTATES;

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

D
dapan1121 已提交
2190 2191
static int32_t getNextRowFromMem(void *iter, TSDBROW **ppRow, bool *pIgnoreEarlierTs, bool isLast, int16_t *aCols,
                                 int nCols) {
2192 2193
  SMemNextRowIter *state = (SMemNextRowIter *)iter;
  int32_t          code = 0;
2194
  *pIgnoreEarlierTs = false;
2195 2196 2197
  switch (state->state) {
    case SMEMNEXTROW_ENTER: {
      if (state->pMem != NULL) {
2198 2199 2200 2201 2202
        if (state->pMem->maxKey <= state->lastTs) {
          *ppRow = NULL;
          *pIgnoreEarlierTs = true;
          return code;
        }
2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237
        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;
}

2238
static bool tsdbKeyDeleted(TSDBKEY *key, SArray *pSkyline, int64_t *iSkyline) {
2239 2240 2241 2242 2243 2244 2245 2246
  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) {
2247
      if (key->version <= pItemFront->version || (key->ts == pItemBack->ts && key->version <= pItemBack->version)) {
2248
        // if (key->version <= pItemFront->version || key->version <= pItemBack->version) {
2249 2250
        return true;
      } else {
2251 2252 2253 2254 2255
        if (*iSkyline > 1) {
          --*iSkyline;
        } else {
          return false;
        }
2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268
      }
    } else {
      if (*iSkyline > 1) {
        --*iSkyline;
      } else {
        return false;
      }
    }
  }

  return deleted;
}

D
dapan1121 已提交
2269 2270
typedef int32_t (*_next_row_fn_t)(void *iter, TSDBROW **ppRow, bool *pIgnoreEarlierTs, bool isLast, int16_t *aCols,
                                  int nCols);
2271
typedef int32_t (*_next_row_clear_fn_t)(void *iter);
2272

2273
typedef struct {
2274 2275 2276
  TSDBROW             *pRow;
  bool                 stop;
  bool                 next;
2277
  bool                 ignoreEarlierTs;
2278 2279 2280
  void                *iter;
  _next_row_fn_t       nextRowFn;
  _next_row_clear_fn_t nextRowClearFn;
2281
} TsdbNextRowState;
2282

M
Minglei Jin 已提交
2283
typedef struct CacheNextRowIter {
2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294
  SArray           *pMemDelData;
  SArray           *pSkyline;
  int64_t           iSkyline;
  SBlockIdx         idx;
  SMemNextRowIter   memState;
  SMemNextRowIter   imemState;
  SFSNextRowIter    fsState;
  TSDBROW           memRow, imemRow, fsLastRow, fsRow;
  TsdbNextRowState  input[3];
  SCacheRowsReader *pr;
  STsdb            *pTsdb;
2295 2296
} CacheNextRowIter;

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
int32_t clearNextRowFromFS(void *iter) {
  int32_t code = 0;

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

  if (state->pLastIter) {
    lastIterClose(&state->pLastIter);
  }

  if (state->pBlockData) {
    tBlockDataDestroy(state->pBlockData);
    state->pBlockData = NULL;
  }

  if (state->pTSRow) {
    taosMemoryFree(state->pTSRow);
    state->pTSRow = NULL;
  }

  if (state->pRowIter->pSkyline) {
    taosArrayDestroy(state->pRowIter->pSkyline);
    state->pRowIter->pSkyline = NULL;
  }

  return code;
}

2327 2328 2329 2330 2331 2332 2333 2334 2335 2336
static void clearLastFileSet(SFSNextRowIter *state) {
  if (state->pLastIter) {
    lastIterClose(&state->pLastIter);
  }

  if (state->pBlockData) {
    tBlockDataDestroy(state->pBlockData);
    state->pBlockData = NULL;
  }

2337 2338 2339
  if (state->pr->pFileReader) {
    tsdbDataFileReaderClose(&state->pr->pFileReader);
    state->pr->pFileReader = NULL;
2340 2341

    state->pr->pCurFileSet = NULL;
2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361
  }

  if (state->pTSRow) {
    taosMemoryFree(state->pTSRow);
    state->pTSRow = NULL;
  }

  if (state->pRowIter->pSkyline) {
    taosArrayDestroy(state->pRowIter->pSkyline);
    state->pRowIter->pSkyline = NULL;

    void   *pe = NULL;
    int32_t iter = 0;
    while ((pe = tSimpleHashIterate(state->pr->pTableMap, pe, &iter)) != NULL) {
      STableLoadInfo *pInfo = *(STableLoadInfo **)pe;
      pInfo->pTombData = taosArrayDestroy(pInfo->pTombData);
    }
  }
}

2362
static int32_t nextRowIterOpen(CacheNextRowIter *pIter, tb_uid_t uid, STsdb *pTsdb, STSchema *pTSchema, tb_uid_t suid,
2363 2364
                               SArray *pLDataIterArray, STsdbReadSnap *pReadSnap, int64_t lastTs,
                               SCacheRowsReader *pr) {
2365 2366 2367
  int code = 0;

  STbData *pMem = NULL;
2368 2369
  if (pReadSnap->pMem) {
    pMem = tsdbGetTbDataFromMemTable(pReadSnap->pMem, suid, uid);
2370 2371 2372
  }

  STbData *pIMem = NULL;
2373 2374
  if (pReadSnap->pIMem) {
    pIMem = tsdbGetTbDataFromMemTable(pReadSnap->pIMem, suid, uid);
2375 2376
  }

H
Hongze Cheng 已提交
2377 2378
  pIter->pTsdb = pTsdb;

M
Minglei Jin 已提交
2379
  pIter->pMemDelData = NULL;
2380

2381
  loadMemTombData(&pIter->pMemDelData, pMem, pIMem, pr->info.verRange.maxVer);
2382 2383

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

M
Minglei Jin 已提交
2385
  pIter->fsState.pRowIter = pIter;
2386
  pIter->fsState.state = SFSNEXTROW_FS;
M
Minglei Jin 已提交
2387
  pIter->fsState.aDFileSet = pReadSnap->pfSetArray;
2388
  pIter->fsState.pBlockIdxExp = &pIter->idx;
2389 2390 2391
  pIter->fsState.pTSchema = pTSchema;
  pIter->fsState.suid = suid;
  pIter->fsState.uid = uid;
2392
  pIter->fsState.lastTs = lastTs;
2393
  pIter->fsState.pr = pr;
2394

2395 2396
  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};
2397
  pIter->input[2] =
2398
      (TsdbNextRowState){&pIter->fsRow, false, true, false, &pIter->fsState, getNextRowFromFS, clearNextRowFromFS};
2399 2400 2401 2402

  if (pMem) {
    pIter->memState.pMem = pMem;
    pIter->memState.state = SMEMNEXTROW_ENTER;
2403
    pIter->memState.lastTs = lastTs;
2404 2405 2406 2407 2408 2409 2410
    pIter->input[0].stop = false;
    pIter->input[0].next = true;
  }

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

2416
  pIter->pr = pr;
2417 2418 2419 2420 2421 2422 2423
_err:
  return code;
}

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

2424
  for (int i = 0; i < 3; ++i) {
2425 2426 2427 2428 2429 2430 2431 2432 2433
    if (pIter->input[i].nextRowClearFn) {
      pIter->input[i].nextRowClearFn(pIter->input[i].iter);
    }
  }

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

M
Minglei Jin 已提交
2434 2435 2436 2437
  if (pIter->pMemDelData) {
    taosArrayDestroy(pIter->pMemDelData);
  }

2438 2439 2440 2441 2442
_err:
  return code;
}

// iterate next row non deleted backward ts, version (from high to low)
D
dapan1121 已提交
2443 2444
static int32_t nextRowIterGet(CacheNextRowIter *pIter, TSDBROW **ppRow, bool *pIgnoreEarlierTs, bool isLast,
                              int16_t *aCols, int nCols) {
2445
  int code = 0;
2446
  for (;;) {
2447
    for (int i = 0; i < 3; ++i) {
2448
      if (pIter->input[i].next && !pIter->input[i].stop) {
D
dapan1121 已提交
2449 2450
        code = pIter->input[i].nextRowFn(pIter->input[i].iter, &pIter->input[i].pRow, &pIter->input[i].ignoreEarlierTs,
                                         isLast, aCols, nCols);
2451
        if (code) goto _err;
2452

2453 2454 2455 2456
        if (pIter->input[i].pRow == NULL) {
          pIter->input[i].stop = true;
          pIter->input[i].next = false;
        }
2457 2458 2459
      }
    }

M
Minglei Jin 已提交
2460
    if (pIter->input[0].stop && pIter->input[1].stop && pIter->input[2].stop) {
2461
      *ppRow = NULL;
M
Minglei Jin 已提交
2462 2463
      *pIgnoreEarlierTs =
          (pIter->input[0].ignoreEarlierTs || pIter->input[1].ignoreEarlierTs || pIter->input[2].ignoreEarlierTs);
2464 2465
      return code;
    }
2466

2467 2468 2469 2470 2471 2472
    // 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;

2473
    for (int i = 0; i < 3; ++i) {
2474 2475 2476 2477 2478 2479 2480 2481 2482
      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;
          }
2483

2484 2485
          iMax[nMax] = i;
          max[nMax++] = pIter->input[i].pRow;
2486 2487
        } else {
          pIter->input[i].next = false;
2488 2489 2490 2491
        }
      }
    }

2492 2493 2494 2495 2496 2497 2498
    // 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]);

2499 2500 2501 2502
      if (!pIter->pSkyline) {
        pIter->pSkyline = taosArrayInit(32, sizeof(TSDBKEY));

        uint64_t        uid = pIter->idx.uid;
2503
        STableLoadInfo *pInfo = getTableLoadInfo(pIter->pr, uid);
M
Minglei Jin 已提交
2504 2505
        if (pInfo->pTombData == NULL) {
          pInfo->pTombData = taosArrayInit(4, sizeof(SDelData));
2506
        }
2507

M
Minglei Jin 已提交
2508 2509 2510
        taosArrayAddAll(pInfo->pTombData, pIter->pMemDelData);

        size_t delSize = TARRAY_SIZE(pInfo->pTombData);
2511
        if (delSize > 0) {
M
Minglei Jin 已提交
2512
          code = tsdbBuildDeleteSkyline(pInfo->pTombData, 0, (int32_t)(delSize - 1), pIter->pSkyline);
2513
        }
2514 2515 2516
        pIter->iSkyline = taosArrayGetSize(pIter->pSkyline) - 1;
      }

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

2523 2524
      pIter->input[iMax[i]].next = deleted;
    }
2525

2526 2527
    if (nMerge > 0) {
      pIter->input[iMerge[0]].next = true;
2528

2529 2530 2531
      *ppRow = merge[0];
      return code;
    }
2532 2533 2534 2535 2536 2537
  }

_err:
  return code;
}

2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551
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;
}

2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566
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;
}

2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586
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);
2587
  return metaGetTbTSchemaEx(pReader->pTsdb->pVnode->pMeta, pReader->info.suid, uid, sversion, &pReader->pCurrSchema);
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
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};
2619
  nextRowIterOpen(&iter, uid, pTsdb, pTSchema, pr->info.suid, pr->pLDataIterArray, pr->pReadSnap, pr->lastTs, pr);
2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645

  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;

2646
      for (int16_t iCol = noneCol; iCol < nCols; ++iCol) {
2647 2648 2649 2650 2651 2652 2653
        if (iCol >= nLastCol) {
          break;
        }
        SLastCol *pCol = taosArrayGet(pColArray, iCol);
        if (pCol->colVal.cid != pTSchema->columns[slotIds[iCol]].colId) {
          continue;
        }
2654 2655 2656
        if (slotIds[iCol] == 0) {
          STColumn *pTColumn = &pTSchema->columns[0];

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

2663
        *pCol = (SLastCol){.ts = rowTs, .colVal = *pColVal};
2664
        if (IS_VAR_DATA_TYPE(pColVal->type) /*&& pColVal->value.nData > 0*/) {
2665 2666 2667 2668 2669 2670
          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;
          }
2671 2672 2673
          if (pColVal->value.nData > 0) {
            memcpy(pCol->colVal.value.pData, pColVal->value.pData, pColVal->value.nData);
          }
2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710
        }

        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)) {
2711
        SLastCol lastCol = {.ts = rowTs, .colVal = *pColVal};
2712
        if (IS_VAR_DATA_TYPE(pColVal->type) && pColVal->value.nData > 0) {
2713 2714 2715 2716
          SLastCol *pLastCol = (SLastCol *)taosArrayGet(pColArray, iCol);
          taosMemoryFree(pLastCol->colVal.value.pData);

          lastCol.colVal.value.pData = taosMemoryMalloc(lastCol.colVal.value.nData);
M
Minglei Jin 已提交
2717 2718 2719 2720 2721
          if (lastCol.colVal.value.pData == NULL) {
            terrno = TSDB_CODE_OUT_OF_MEMORY;
            code = TSDB_CODE_OUT_OF_MEMORY;
            goto _err;
          }
2722 2723 2724 2725
          memcpy(lastCol.colVal.value.pData, pColVal->value.pData, pColVal->value.nData);
        }

        taosArraySet(pColArray, iCol, &lastCol);
D
dapan1121 已提交
2726 2727
        int32_t aColIndex = taosArraySearchIdx(aColArray, &lastCol.colVal.cid, compareInt16Val, TD_EQ);
        taosArrayRemove(aColArray, aColIndex);
H
Hongze Cheng 已提交
2728
      } else if (!COL_VAL_IS_VALUE(tColVal) && !COL_VAL_IS_VALUE(pColVal) && !setNoneCol) {
2729 2730 2731 2732 2733 2734
        noneCol = iCol;
        setNoneCol = true;
      }
    }
  } while (setNoneCol);

2735
  if (!hasRow) {
2736 2737 2738 2739 2740 2741
    if (ignoreEarlierTs) {
      taosArrayDestroy(pColArray);
      pColArray = NULL;
    } else {
      taosArrayClear(pColArray);
    }
2742
  }
2743
  *ppLastArray = pColArray;
2744 2745

  nextRowIterClose(&iter);
D
dapan1121 已提交
2746
  taosArrayDestroy(aColArray);
2747

2748 2749 2750 2751
  return code;

_err:
  nextRowIterClose(&iter);
2752
  // taosMemoryFreeClear(pTSchema);
2753 2754
  *ppLastArray = NULL;
  taosArrayDestroy(pColArray);
D
dapan1121 已提交
2755
  taosArrayDestroy(aColArray);
2756 2757 2758
  return code;
}

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
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};
2788
  nextRowIterOpen(&iter, uid, pTsdb, pTSchema, pr->info.suid, pr->pLDataIterArray, pr->pReadSnap, pr->lastTs, pr);
2789 2790 2791

  do {
    TSDBROW *pRow = NULL;
M
Minglei Jin 已提交
2792
    nextRowIterGet(&iter, &pRow, &ignoreEarlierTs, false, TARRAY_DATA(aColArray), TARRAY_SIZE(aColArray));
2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811

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

2812
    lastRowTs = rowTs;
2813 2814 2815 2816 2817

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

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

2831 2832 2833 2834 2835 2836 2837 2838 2839 2840
      *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;
        }
        if (pColVal->value.nData > 0) {
          memcpy(pCol->colVal.value.pData, pColVal->value.pData, pColVal->value.nData);
2841
        }
2842
      }
2843

2844 2845
      int32_t aColIndex = taosArraySearchIdx(aColArray, &pColVal->cid, compareInt16Val, TD_EQ);
      if (aColIndex >= 0) {
2846 2847 2848
        taosArrayRemove(aColArray, aColIndex);
      }
    }
2849 2850 2851

    break;
  } while (1);
2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876

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

M
Minglei Jin 已提交
2877 2878 2879 2880 2881 2882 2883
int32_t tsdbCacheRelease(SLRUCache *pCache, LRUHandle *h) {
  int32_t code = 0;

  taosLRUCacheRelease(pCache, h, false);

  return code;
}
2884 2885 2886 2887 2888 2889

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

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

2891 2892 2893 2894 2895 2896 2897 2898
size_t tsdbCacheGetUsage(SVnode *pVnode) {
  size_t usage = 0;
  if (pVnode->pTsdb != NULL) {
    usage = taosLRUCacheGetUsage(pVnode->pTsdb->lruCache);
  }

  return usage;
}
2899

D
dapan1121 已提交
2900 2901 2902 2903 2904 2905 2906 2907 2908
int32_t tsdbCacheGetElems(SVnode *pVnode) {
  int32_t elems = 0;
  if (pVnode->pTsdb != NULL) {
    elems = taosLRUCacheGetElems(pVnode->pTsdb->lruCache);
  }

  return elems;
}

2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936
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;
}

D
dapan1121 已提交
2937 2938
static void deleteBICache(const void *key, size_t keyLen, void *value, void *ud) {
  (void)ud;
2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968
  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;
D
dapan1121 已提交
2969 2970
      LRUStatus           status =
          taosLRUCacheInsert(pCache, key, keyLen, pArray, charge, deleter, &h, TAOS_LRU_PRIORITY_LOW, NULL);
2971 2972 2973 2974 2975 2976 2977 2978
      if (status != TAOS_LRU_STATUS_OK) {
        code = -1;
      }
    }

    taosThreadMutexUnlock(&pTsdb->biMutex);
  }

2979
  tsdbTrace("bi cache:%p, ref", pCache);
2980 2981 2982 2983 2984 2985 2986 2987 2988
  *handle = h;

  return code;
}

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

  taosLRUCacheRelease(pCache, h, false);
2989
  tsdbTrace("bi cache:%p, release", pCache);
2990 2991 2992

  return code;
}