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

D
dapan1121 已提交
17 18
#define ROCKS_BATCH_SIZE (4096)

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

    taosLRUCacheCleanup(pCache);

    taosThreadMutexDestroy(&pTsdb->biMutex);
  }
}

51 52 53 54 55 56 57
#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;
58

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

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 105 106 107
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;
}

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

111 112 113 114 115 116 117 118 119 120 121 122
  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;

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

  rocksdb_writeoptions_t *writeoptions = rocksdb_writeoptions_create();
  if (NULL == writeoptions) {
    code = TSDB_CODE_OUT_OF_MEMORY;
    goto _err2;
  }
142
  rocksdb_writeoptions_disable_WAL(writeoptions, 1);
143 144 145 146

  rocksdb_readoptions_t *readoptions = rocksdb_readoptions_create();
  if (NULL == readoptions) {
    code = TSDB_CODE_OUT_OF_MEMORY;
147
    goto _err3;
148 149 150 151 152 153 154 155
  }

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

  rocksdb_t *db = rocksdb_open(options, cachePath, &err);
  if (NULL == db) {
156 157 158 159 160
    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;
161 162
  }

163 164 165
  rocksdb_flushoptions_t *flushoptions = rocksdb_flushoptions_create();
  if (NULL == flushoptions) {
    code = TSDB_CODE_OUT_OF_MEMORY;
166
    goto _err5;
167 168
  }

169
  rocksdb_writebatch_t *writebatch = rocksdb_writebatch_create();
170
  rocksdb_writebatch_t *rwritebatch = rocksdb_writebatch_create();
171 172

  pTsdb->rCache.writebatch = writebatch;
173
  pTsdb->rCache.rwritebatch = rwritebatch;
174
  pTsdb->rCache.my_comparator = cmp;
175 176 177
  pTsdb->rCache.options = options;
  pTsdb->rCache.writeoptions = writeoptions;
  pTsdb->rCache.readoptions = readoptions;
178
  pTsdb->rCache.flushoptions = flushoptions;
179 180
  pTsdb->rCache.db = db;

181 182
  taosThreadMutexInit(&pTsdb->rCache.rMutex, NULL);

183 184
  pTsdb->rCache.pTSchema = NULL;

185 186
  return code;

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

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

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

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

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

    rocksdb_writebatch_clear(wb);
  }

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

D
dapan1121 已提交
254
static SLastCol *tsdbCacheDeserialize(char const *value) {
255 256 257 258
  if (!value) {
    return NULL;
  }

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

  return pLastCol;
}

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

D
dapan1121 已提交
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 362 363 364
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;
}

365
static SLastCol *tsdbCacheLookup(STsdb *pTsdb, tb_uid_t uid, int16_t cid, int8_t ltype) {
366 367
  SLastCol *pLastCol = NULL;

368 369 370 371 372 373
  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);
374 375 376 377 378 379 380 381 382 383
  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;
}

384 385 386 387 388 389 390 391 392 393
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 已提交
394
static void tsdbCacheDeleter(const void *key, size_t klen, void *value, void *ud) {
395 396 397
  SLastCol *pLastCol = (SLastCol *)value;

  if (pLastCol->dirty) {
D
dapan1121 已提交
398 399
    tsdbCachePutBatch(pLastCol, key, klen, (SCacheFlushState *)ud);
  }
400

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

  taosMemoryFree(value);
406 407
}

D
dapan1121 已提交
408 409 410 411 412
typedef struct {
  int      idx;
  SLastKey key;
} SIdxKey;

413
int32_t tsdbCacheUpdate(STsdb *pTsdb, tb_uid_t suid, tb_uid_t uid, TSDBROW *pRow) {
414 415
  int32_t code = 0;

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

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

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

429 430 431 432
  STSDBRowIter iter = {0};
  tsdbRowIterOpen(&iter, pRow, pTSchema);

  for (SColVal *pColVal = tsdbRowIterNext(&iter); pColVal; pColVal = tsdbRowIterNext(&iter)) {
433
    taosArrayPush(aColVal, pColVal);
434 435 436 437
  }

  tsdbRowClose(&iter);

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

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

D
dapan1121 已提交
449 450 451 452 453
    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);
454

D
dapan1121 已提交
455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473
      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);
          }
        }
474

D
dapan1121 已提交
475 476 477 478
        if (!pLastCol->dirty) {
          pLastCol->dirty = 1;
        }
      }
479

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

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

D
dapan1121 已提交
494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512
        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);
            }
          }
513

D
dapan1121 已提交
514 515 516 517 518 519 520 521 522 523 524
          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});
525
      }
D
dapan1121 已提交
526 527
    }
  }
528

D
dapan1121 已提交
529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547
  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]);
548
    }
D
dapan1121 已提交
549 550 551 552 553 554 555 556 557 558
    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);
559 560

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

D
dapan1121 已提交
562 563 564 565 566 567 568
      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);
569

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

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

D
dapan1121 已提交
574 575 576 577
          pLastCol = (SLastCol *)value;
          SLastCol *pTmpLastCol = taosMemoryCalloc(1, sizeof(SLastCol));
          *pTmpLastCol = *pLastCol;
          pLastCol = pTmpLastCol;
578

D
dapan1121 已提交
579 580 581 582 583 584 585 586 587 588 589 590 591
          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);
592
        }
D
dapan1121 已提交
593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615
      } 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;
            }
616

D
dapan1121 已提交
617 618 619 620 621 622 623 624 625
            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);
          }
        }
626
      }
D
dapan1121 已提交
627 628

      rocksdb_free(values_list[i]);
629
    }
630

D
dapan1121 已提交
631 632 633 634 635
    rocksMayWrite(pTsdb, true, false, true);

    taosMemoryFree(values_list);

    taosArrayDestroy(remainCols);
636 637
  }

D
dapan1121 已提交
638
  taosThreadMutexUnlock(&pTsdb->lruMutex);
639

640 641
_exit:
  taosArrayDestroy(aColVal);
M
Minglei Jin 已提交
642
  taosMemoryFree(pTSchema);
643 644 645
  return code;
}

646 647 648
static int32_t mergeLastCid(tb_uid_t uid, STsdb *pTsdb, SArray **ppLastArray, SCacheRowsReader *pr, int16_t *aCols,
                            int nCols, int16_t *slotIds);

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

  SArray *pCidList = pr->pCidList;
657
  int     num_keys = TARRAY_SIZE(pCidList);
658 659 660 661

  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);
662 663 664
  for (int i = 0; i < num_keys; ++i) {
    int16_t cid = *(int16_t *)taosArrayGet(pCidList, i);

665 666 667
    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;
668
  }
669

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

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

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

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

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

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

        taosMemoryFree(value);
731
      } else {
732
        reallocVarData(&pLastCol->colVal);
733 734
      }

735
      if (wb) {
736
        rocksMayWrite(pTsdb, false, true, false);
737 738
      }

739
      taosThreadMutexUnlock(&pTsdb->rCache.rMutex);
M
Minglei Jin 已提交
740
    }
741

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

  return code;
}
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 783 784 785
#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
786
      wb = pTsdb->rCache.rwritebatch;
787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803
      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) {
804
      rocksMayWrite(pTsdb, false, true, false);
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 845 846 847
    }

    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;
848
      reallocVarData(&pLastCol->colVal);
849 850
    }

851 852 853 854 855 856 857
    taosArraySet(pLastArray, idxKey->idx, pLastCol);
    // taosArrayRemove(remainCols, i);

    if (!pTmpColArray) {
      continue;
    }

858 859 860 861
    SLastCol *pTmpLastCol = taosMemoryCalloc(1, sizeof(SLastCol));
    *pTmpLastCol = *pLastCol;
    pLastCol = pTmpLastCol;

M
Minglei Jin 已提交
862
    reallocVarData(&pLastCol->colVal);
863 864 865 866 867 868
    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 已提交
869
                                          TAOS_LRU_PRIORITY_LOW, &pTsdb->flushState);
870 871 872 873 874
    if (status != TAOS_LRU_STATUS_OK) {
      code = -1;
    }

    // store result back to rocks cache
875
    wb = pTsdb->rCache.rwritebatch;
876 877 878 879 880 881 882 883 884 885 886
    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) {
887
    rocksMayWrite(pTsdb, false, true, false);
888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930
  }

  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]);
931
    SIdxKey  *idxKey = &((SIdxKey *)TARRAY_DATA(remainCols))[j];
932 933 934 935 936 937 938 939 940 941 942 943
    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 已提交
944
                                            NULL, TAOS_LRU_PRIORITY_LOW, &pTsdb->flushState);
945 946 947 948
      if (status != TAOS_LRU_STATUS_OK) {
        code = -1;
      }

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

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

960 961 962 963 964 965 966 967 968 969 970 971
  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;
972
  SArray    *remainCols = NULL;
973 974 975 976 977
  SLRUCache *pCache = pTsdb->lruCache;
  SArray    *pCidList = pr->pCidList;
  int        num_keys = TARRAY_SIZE(pCidList);

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

    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;
987
      reallocVarData(&lastCol.colVal);
988 989
      taosArrayPush(pLastArray, &lastCol);

D
dapan1121 已提交
990
      taosLRUCacheRelease(pCache, h, false);
991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005
    } 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);) {
1006
      SIdxKey   *idxKey = &((SIdxKey *)TARRAY_DATA(remainCols))[i];
1007 1008 1009 1010 1011 1012 1013
      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 已提交
1014

D
dapan1121 已提交
1015
        taosLRUCacheRelease(pCache, h, false);
1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058

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

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

    taosThreadMutexUnlock(&pTsdb->lruMutex);
  }

  if (remainCols) {
    taosArrayDestroy(remainCols);
  }

  return code;
}

int32_t tsdbCacheGet(STsdb *pTsdb, tb_uid_t uid, SArray *pLastArray, SCacheRowsReader *pr, int8_t ltype) {
  int32_t    code = 0;
  SLRUCache *pCache = pTsdb->lruCache;
  SArray    *pCidList = pr->pCidList;
  int        num_keys = TARRAY_SIZE(pCidList);

  for (int i = 0; i < num_keys; ++i) {
    SLastCol *pLastCol = NULL;
    int16_t   cid = *(int16_t *)taosArrayGet(pCidList, i);

    SLastKey  *key = &(SLastKey){.ltype = ltype, .uid = uid, .cid = cid};
    LRUHandle *h = taosLRUCacheLookup(pCache, key, ROCKS_KEY_LEN);
    if (!h) {
      taosThreadMutexLock(&pTsdb->lruMutex);
      h = taosLRUCacheLookup(pCache, key, ROCKS_KEY_LEN);
      if (!h) {
        pLastCol = tsdbCacheLoadCol(pTsdb, pr, pr->pSlotIds[i], uid, cid, ltype);

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

        LRUStatus status = taosLRUCacheInsert(pCache, key, ROCKS_KEY_LEN, pLastCol, charge, tsdbCacheDeleter, &h,
D
dapan1121 已提交
1059
                                              TAOS_LRU_PRIORITY_LOW, &pTsdb->flushState);
1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081
        if (status != TAOS_LRU_STATUS_OK) {
          code = -1;
        }
      }

      taosThreadMutexUnlock(&pTsdb->lruMutex);
    }

    pLastCol = (SLastCol *)taosLRUCacheValue(pCache, h);

    SLastCol lastCol = *pLastCol;
    reallocVarData(&lastCol.colVal);

    if (h) {
      taosLRUCacheRelease(pCache, h, false);
    }

    taosArrayPush(pLastArray, &lastCol);
  }

  return code;
}
1082

1083 1084
int32_t tsdbCacheDel(STsdb *pTsdb, tb_uid_t suid, tb_uid_t uid, TSKEY sKey, TSKEY eKey) {
  int32_t code = 0;
1085
  // fetch schema
M
Minglei Jin 已提交
1086 1087 1088 1089 1090 1091
  STSchema *pTSchema = NULL;
  int       sver = -1;
  code = metaGetTbTSchemaEx(pTsdb->pVnode->pMeta, suid, uid, sver, &pTSchema);
  if (code != TSDB_CODE_SUCCESS) {
    terrno = code;
    return -1;
1092 1093
  }

1094
  // build keys & multi get from rocks
M
Minglei Jin 已提交
1095 1096 1097 1098
  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;
1099 1100 1101
  for (int i = 0; i < num_keys; ++i) {
    int16_t cid = pTSchema->columns[i].colId;

M
Minglei Jin 已提交
1102
    char *keys = taosMemoryCalloc(2, sizeof(SLastKey));
1103 1104 1105
    ((SLastKey *)keys)[0] = (SLastKey){.ltype = 1, .uid = uid, .cid = cid};
    ((SLastKey *)keys)[1] = (SLastKey){.ltype = 0, .uid = uid, .cid = cid};

1106
    keys_list[i] = keys;
M
Minglei Jin 已提交
1107
    keys_list[num_keys + i] = keys + sizeof(SLastKey);
1108 1109
    keys_list_sizes[i] = klen;
    keys_list_sizes[num_keys + i] = klen;
1110 1111 1112 1113 1114
  }
  char  **values_list = taosMemoryCalloc(num_keys * 2, sizeof(char *));
  size_t *values_list_sizes = taosMemoryCalloc(num_keys * 2, sizeof(size_t));
  char  **errs = taosMemoryCalloc(num_keys * 2, sizeof(char *));
  taosThreadMutexLock(&pTsdb->rCache.rMutex);
1115
  rocksMayWrite(pTsdb, true, false, false);
1116 1117
  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 已提交
1118 1119
  taosThreadMutexUnlock(&pTsdb->rCache.rMutex);

1120
  for (int i = 0; i < num_keys * 2; ++i) {
M
Minglei Jin 已提交
1121 1122 1123
    if (errs[i]) {
      rocksdb_free(errs[i]);
    }
1124 1125 1126 1127 1128
  }
  taosMemoryFree(errs);

  rocksdb_writebatch_t *wb = pTsdb->rCache.writebatch;
  for (int i = 0; i < num_keys; ++i) {
1129
    SLastCol *pLastCol = tsdbCacheDeserialize(values_list[i]);
D
dapan1121 已提交
1130
    taosThreadMutexLock(&pTsdb->rCache.rMutex);
1131
    if (NULL != pLastCol && (pLastCol->ts <= eKey && pLastCol->ts >= sKey)) {
M
Minglei Jin 已提交
1132
      rocksdb_writebatch_delete(wb, keys_list[i], klen);
1133
    }
1134 1135
    pLastCol = tsdbCacheDeserialize(values_list[i + num_keys]);
    if (NULL != pLastCol && (pLastCol->ts <= eKey && pLastCol->ts >= sKey)) {
M
Minglei Jin 已提交
1136
      rocksdb_writebatch_delete(wb, keys_list[num_keys + i], klen);
1137
    }
D
dapan1121 已提交
1138
    taosThreadMutexUnlock(&pTsdb->rCache.rMutex);
1139 1140 1141

    rocksdb_free(values_list[i]);
    rocksdb_free(values_list[i + num_keys]);
D
dapan1121 已提交
1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165

    taosThreadMutexLock(&pTsdb->lruMutex);

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

    taosThreadMutexUnlock(&pTsdb->lruMutex);
1166
  }
M
Minglei Jin 已提交
1167 1168 1169 1170 1171
  for (int i = 0; i < num_keys; ++i) {
    taosMemoryFree(keys_list[i]);
  }
  taosMemoryFree(keys_list);
  taosMemoryFree(keys_list_sizes);
1172 1173 1174
  taosMemoryFree(values_list);
  taosMemoryFree(values_list_sizes);

D
dapan1121 已提交
1175
  rocksMayWrite(pTsdb, true, false, true);
1176 1177

_exit:
M
Minglei Jin 已提交
1178
  taosMemoryFree(pTSchema);
1179 1180 1181 1182

  return code;
}

1183
int32_t tsdbOpenCache(STsdb *pTsdb) {
H
Hongze Cheng 已提交
1184
  int32_t    code = 0;
1185
  SLRUCache *pCache = NULL;
1186
  size_t     cfgCapacity = pTsdb->pVnode->config.cacheLastSize * 1024 * 1024;
1187

D
dapan1121 已提交
1188
  pCache = taosLRUCacheInit(cfgCapacity, 0, .5);
1189 1190 1191 1192 1193
  if (pCache == NULL) {
    code = TSDB_CODE_OUT_OF_MEMORY;
    goto _err;
  }

1194 1195 1196 1197 1198 1199
  code = tsdbOpenBICache(pTsdb);
  if (code != TSDB_CODE_SUCCESS) {
    code = TSDB_CODE_OUT_OF_MEMORY;
    goto _err;
  }

1200 1201 1202 1203 1204 1205
  code = tsdbOpenRocksCache(pTsdb);
  if (code != TSDB_CODE_SUCCESS) {
    code = TSDB_CODE_OUT_OF_MEMORY;
    goto _err;
  }

1206
  taosLRUCacheSetStrictCapacity(pCache, false);
1207

1208 1209
  taosThreadMutexInit(&pTsdb->lruMutex, NULL);

D
dapan1121 已提交
1210 1211 1212
  pTsdb->flushState.pTsdb = pTsdb;
  pTsdb->flushState.flush_count = 0;

1213 1214 1215 1216 1217
_err:
  pTsdb->lruCache = pCache;
  return code;
}

1218 1219
void tsdbCloseCache(STsdb *pTsdb) {
  SLRUCache *pCache = pTsdb->lruCache;
1220 1221 1222 1223
  if (pCache) {
    taosLRUCacheEraseUnrefEntries(pCache);

    taosLRUCacheCleanup(pCache);
1224 1225

    taosThreadMutexDestroy(&pTsdb->lruMutex);
1226
  }
1227 1228

  tsdbCloseBICache(pTsdb);
1229
  tsdbCloseRocksCache(pTsdb);
1230 1231
}

1232 1233 1234 1235 1236 1237 1238 1239 1240 1241
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 已提交
1242 1243
static void deleteTableCacheLast(const void *key, size_t keyLen, void *value, void *ud) {
  (void)ud;
1244 1245 1246 1247
  SArray *pLastArray = (SArray *)value;
  int16_t nCol = taosArrayGetSize(pLastArray);
  for (int16_t iCol = 0; iCol < nCol; ++iCol) {
    SLastCol *pLastCol = (SLastCol *)taosArrayGet(pLastArray, iCol);
1248
    if (IS_VAR_DATA_TYPE(pLastCol->colVal.type) && pLastCol->colVal.value.nData > 0) {
1249 1250 1251 1252 1253 1254
      taosMemoryFree(pLastCol->colVal.value.pData);
    }
  }

  taosArrayDestroy(value);
}
1255

1256
int32_t tsdbCacheDeleteLastrow(SLRUCache *pCache, tb_uid_t uid, TSKEY eKey) {
1257
  int32_t code = 0;
1258 1259 1260

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

1262 1263
  // getTableCacheKey(uid, "lr", key, &keyLen);
  getTableCacheKey(uid, 0, key, &keyLen);
1264 1265
  LRUHandle *h = taosLRUCacheLookup(pCache, key, keyLen);
  if (h) {
1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277
    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;
      }
    }

1278
    taosLRUCacheRelease(pCache, h, invalidate);
1279
    if (invalidate) {
1280
      taosLRUCacheErase(pCache, key, keyLen);
1281 1282 1283 1284 1285 1286
    }
  }

  return code;
}

1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308
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;
      }
    }

1309
    taosLRUCacheRelease(pCache, h, invalidate);
1310
    if (invalidate) {
1311
      taosLRUCacheErase(pCache, key, keyLen);
1312 1313 1314 1315 1316
    }
  }

  return code;
}
1317
/*
1318
int32_t tsdbCacheDelete(SLRUCache *pCache, tb_uid_t uid, TSKEY eKey) {
1319 1320 1321 1322
  int32_t code = 0;
  char    key[32] = {0};
  int     keyLen = 0;

1323 1324 1325 1326
  // getTableCacheKey(uid, "lr", key, &keyLen);
  getTableCacheKey(uid, 0, key, &keyLen);
  LRUHandle *h = taosLRUCacheLookup(pCache, key, keyLen);
  if (h) {
1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339
    SArray *pLast = (SArray *)taosLRUCacheValue(pCache, h);
    bool    invalidate = false;
    int16_t nCol = taosArrayGetSize(pLast);

    for (int16_t iCol = 0; iCol < nCol; ++iCol) {
      SLastCol *tTsVal = (SLastCol *)taosArrayGet(pLast, iCol);
      if (eKey >= tTsVal->ts) {
        invalidate = true;
        break;
      }
    }

    if (invalidate) {
1340 1341 1342 1343 1344 1345
      taosLRUCacheRelease(pCache, h, true);
    } else {
      taosLRUCacheRelease(pCache, h, false);
    }
  }

1346 1347
  // getTableCacheKey(uid, "l", key, &keyLen);
  getTableCacheKey(uid, 1, key, &keyLen);
1348
  h = taosLRUCacheLookup(pCache, key, keyLen);
1349
  if (h) {
1350 1351 1352
    SArray *pLast = (SArray *)taosLRUCacheValue(pCache, h);
    bool    invalidate = false;
    int16_t nCol = taosArrayGetSize(pLast);
1353

1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366
    for (int16_t iCol = 0; iCol < nCol; ++iCol) {
      SLastCol *tTsVal = (SLastCol *)taosArrayGet(pLast, iCol);
      if (eKey >= tTsVal->ts) {
        invalidate = true;
        break;
      }
    }

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

  return code;
}
1372
*/
H
Hongze Cheng 已提交
1373
int32_t tsdbCacheInsertLastrow(SLRUCache *pCache, STsdb *pTsdb, tb_uid_t uid, TSDBROW *row, bool dup) {
1374 1375
  int32_t code = 0;
  STSRow *cacheRow = NULL;
H
Hongze Cheng 已提交
1376 1377
  char    key[32] = {0};
  int     keyLen = 0;
1378

1379 1380
  // getTableCacheKey(uid, "lr", key, &keyLen);
  getTableCacheKey(uid, 0, key, &keyLen);
1381 1382
  LRUHandle *h = taosLRUCacheLookup(pCache, key, keyLen);
  if (h) {
1383
    STSchema *pTSchema = metaGetTbTSchema(pTsdb->pVnode->pMeta, uid, -1, 1);
H
Hongze Cheng 已提交
1384
    TSKEY     keyTs = TSDBROW_TS(row);
1385 1386 1387 1388 1389 1390
    bool      invalidate = false;

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

1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425
    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;
    }

1426 1427 1428 1429 1430
    if (nCol != pTSchema->numOfCols) {
      invalidate = true;
      goto _invalidate;
    }

1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444
    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 已提交
1445
        tsdbRowGetColVal(row, pTSchema, iCol, &colVal);
1446 1447 1448 1449 1450 1451

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

1452 1453 1454 1455 1456
        if (!COL_VAL_IS_NONE(&colVal)) {
          if (keyTs == tTsVal1->ts && !COL_VAL_IS_NONE(tColVal)) {
            invalidate = true;

            break;
1457 1458 1459 1460
          } 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);
1461 1462
              if (pLastCol->colVal.value.nData > 0 && NULL != pLastCol->colVal.value.pData)
                taosMemoryFree(pLastCol->colVal.value.pData);
1463 1464 1465 1466 1467 1468 1469 1470

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

1473 1474
            taosArraySet(pLast, iCol, &lastCol);
          }
1475 1476 1477 1478 1479 1480 1481 1482
        }
      }
    }

  _invalidate:
    taosMemoryFreeClear(pTSchema);

    taosLRUCacheRelease(pCache, h, invalidate);
1483 1484
    if (invalidate) {
      taosLRUCacheErase(pCache, key, keyLen);
1485
    }
1486
  }
1487 1488 1489 1490

  return code;
}

H
Hongze Cheng 已提交
1491
int32_t tsdbCacheInsertLast(SLRUCache *pCache, tb_uid_t uid, TSDBROW *row, STsdb *pTsdb) {
1492 1493 1494 1495 1496
  int32_t code = 0;
  STSRow *cacheRow = NULL;
  char    key[32] = {0};
  int     keyLen = 0;

1497 1498
  // getTableCacheKey(uid, "l", key, &keyLen);
  getTableCacheKey(uid, 1, key, &keyLen);
1499 1500
  LRUHandle *h = taosLRUCacheLookup(pCache, key, keyLen);
  if (h) {
1501
    STSchema *pTSchema = metaGetTbTSchema(pTsdb->pVnode->pMeta, uid, -1, 1);
H
Hongze Cheng 已提交
1502
    TSKEY     keyTs = TSDBROW_TS(row);
1503 1504 1505 1506 1507 1508
    bool      invalidate = false;

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

1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543
    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;
    }

1544 1545 1546 1547 1548
    if (nCol != pTSchema->numOfCols) {
      invalidate = true;
      goto _invalidate;
    }

1549 1550 1551
    SLastCol *tTsVal = (SLastCol *)taosArrayGet(pLast, iCol);
    if (keyTs > tTsVal->ts) {
      STColumn *pTColumn = &pTSchema->columns[0];
H
Hongze Cheng 已提交
1552
      SColVal   tColVal = COL_VAL_VALUE(pTColumn->colId, pTColumn->type, (SValue){.val = keyTs});
1553 1554 1555 1556 1557

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

    for (++iCol; iCol < nCol; ++iCol) {
1558 1559 1560
      SLastCol *tTsVal1 = (SLastCol *)taosArrayGet(pLast, iCol);
      if (keyTs >= tTsVal1->ts) {
        SColVal *tColVal = &tTsVal1->colVal;
1561 1562

        SColVal colVal = {0};
H
Hongze Cheng 已提交
1563
        tsdbRowGetColVal(row, pTSchema, iCol, &colVal);
1564 1565 1566 1567 1568 1569

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

1570
        if (COL_VAL_IS_VALUE(&colVal)) {
H
Hongze Cheng 已提交
1571
          if (keyTs == tTsVal1->ts && COL_VAL_IS_VALUE(tColVal)) {
1572 1573 1574
            invalidate = true;

            break;
1575 1576 1577 1578
          } else {
            SLastCol lastCol = {.ts = keyTs, .colVal = colVal};
            if (IS_VAR_DATA_TYPE(colVal.type) && colVal.value.nData > 0) {
              SLastCol *pLastCol = (SLastCol *)taosArrayGet(pLast, iCol);
1579 1580
              if (pLastCol->colVal.value.nData > 0 && NULL != pLastCol->colVal.value.pData)
                taosMemoryFree(pLastCol->colVal.value.pData);
1581 1582 1583 1584 1585 1586 1587 1588

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

1591 1592
            taosArraySet(pLast, iCol, &lastCol);
          }
1593 1594 1595 1596
        }
      }
    }

1597
  _invalidate:
1598 1599 1600
    taosMemoryFreeClear(pTSchema);

    taosLRUCacheRelease(pCache, h, invalidate);
1601 1602 1603
    if (invalidate) {
      taosLRUCacheErase(pCache, key, keyLen);
    }
1604 1605 1606 1607 1608
  }

  return code;
}

1609 1610 1611 1612
static tb_uid_t getTableSuidByUid(tb_uid_t uid, STsdb *pTsdb) {
  tb_uid_t suid = 0;

  SMetaReader mr = {0};
1613
  metaReaderDoInit(&mr, pTsdb->pVnode->pMeta, 0);
1614
  if (metaReaderGetTableEntryByUidCache(&mr, uid) < 0) {
H
Hongze Cheng 已提交
1615
    metaReaderClear(&mr);  // table not esist
1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635
    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 已提交
1636
    code = tsdbReadDelDatav1(pDelReader, pDelIdx, aDelData, INT64_MAX);
1637 1638 1639 1640 1641 1642
  }

  return code;
}

static int32_t getTableDelDataFromTbData(STbData *pTbData, SArray *aDelData) {
H
Hongze Cheng 已提交
1643
  int32_t   code = 0;
1644 1645 1646 1647 1648 1649 1650 1651 1652
  SDelData *pDelData = pTbData ? pTbData->pHead : NULL;

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

  return code;
}

H
Hongze Cheng 已提交
1653 1654
static int32_t getTableDelData(STbData *pMem, STbData *pIMem, SDelFReader *pDelReader, SDelIdx *pDelIdx,
                               SArray *aDelData) {
1655 1656
  int32_t code = 0;

1657 1658 1659 1660 1661
  if (pDelIdx) {
    code = getTableDelDataFromDelIdx(pDelReader, pDelIdx, aDelData);
    if (code) goto _err;
  }

1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675
  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 已提交
1676 1677
static int32_t getTableDelSkyline(STbData *pMem, STbData *pIMem, SDelFReader *pDelReader, SDelIdx *pDelIdx,
                                  SArray *aSkyline) {
1678
  int32_t code = 0;
M
Minglei Jin 已提交
1679
  SArray *aDelData = NULL;
1680

M
Minglei Jin 已提交
1681
  aDelData = taosArrayInit(32, sizeof(SDelData));
1682 1683 1684 1685
  code = getTableDelData(pMem, pIMem, pDelReader, pDelIdx, aDelData);
  if (code) goto _err;

  size_t nDelData = taosArrayGetSize(aDelData);
1686 1687 1688 1689
  if (nDelData > 0) {
    code = tsdbBuildDeleteSkyline(aDelData, 0, (int32_t)(nDelData - 1), aSkyline);
    if (code) goto _err;
  }
1690

1691
_err:
M
Minglei Jin 已提交
1692 1693 1694
  if (aDelData) {
    taosArrayDestroy(aDelData);
  }
1695 1696
  return code;
}
S
stephenkgu 已提交
1697
/*
1698 1699
static int32_t getTableDelIdx(SDelFReader *pDelFReader, tb_uid_t suid, tb_uid_t uid, SDelIdx *pDelIdx) {
  int32_t code = 0;
M
Minglei Jin 已提交
1700
  SArray *pDelIdxArray = NULL;
1701

1702
  // SMapData delIdxMap;
M
Minglei Jin 已提交
1703
  pDelIdxArray = taosArrayInit(32, sizeof(SDelIdx));
1704
  SDelIdx idx = {.suid = suid, .uid = uid};
1705

1706
  // tMapDataReset(&delIdxMap);
H
Hongze Cheng 已提交
1707
  code = tsdbReadDelIdx(pDelFReader, pDelIdxArray);
1708 1709
  if (code) goto _err;

1710
  // code = tMapDataSearch(&delIdxMap, &idx, tGetDelIdx, tCmprDelIdx, pDelIdx);
1711
  SDelIdx *pIdx = taosArraySearch(pDelIdxArray, &idx, tCmprDelIdx, TD_EQ);
1712

1713 1714
  *pDelIdx = *pIdx;

1715
_err:
M
Minglei Jin 已提交
1716 1717 1718
  if (pDelIdxArray) {
    taosArrayDestroy(pDelIdxArray);
  }
1719 1720
  return code;
}
S
stephenkgu 已提交
1721
*/
1722 1723 1724 1725 1726 1727 1728 1729
typedef enum {
  SFSLASTNEXTROW_FS,
  SFSLASTNEXTROW_FILESET,
  SFSLASTNEXTROW_BLOCKDATA,
  SFSLASTNEXTROW_BLOCKROW
} SFSLASTNEXTROWSTATES;

typedef struct {
1730 1731 1732
  SFSLASTNEXTROWSTATES state;     // [input]
  STsdb               *pTsdb;     // [input]
  STSchema            *pTSchema;  // [input]
1733
  tb_uid_t             suid;
1734
  tb_uid_t             uid;
1735 1736 1737
  int32_t              nFileSet;
  int32_t              iFileSet;
  SArray              *aDFileSet;
1738
  SDataFReader       **pDataFReader;
1739
  TSDBROW              row;
1740

1741
  bool               checkRemainingRow;
1742 1743 1744
  SMergeTree         mergeTree;
  SMergeTree        *pMergeTree;
  SSttBlockLoadInfo *pLoadInfo;
1745
  SLDataIter        *pDataIter;
1746
  int64_t            lastTs;
1747 1748
} SFSLastNextRowIter;

D
dapan1121 已提交
1749 1750
static int32_t getNextRowFromFSLast(void *iter, TSDBROW **ppRow, bool *pIgnoreEarlierTs, bool isLast, int16_t *aCols,
                                    int nCols) {
1751 1752
  SFSLastNextRowIter *state = (SFSLastNextRowIter *)iter;
  int32_t             code = 0;
D
dapan1121 已提交
1753
  bool                checkRemainingRow = true;
1754 1755 1756 1757 1758 1759 1760 1761 1762

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

    case SFSLASTNEXTROW_FILESET: {
      SDFileSet *pFileSet = NULL;
    _next_fileset:
1763 1764 1765 1766 1767
      if (state->pMergeTree != NULL) {
        tMergeTreeClose(state->pMergeTree);
        state->pMergeTree = NULL;
      }

1768 1769 1770 1771 1772 1773 1774
      if (--state->iFileSet >= 0) {
        pFileSet = (SDFileSet *)taosArrayGet(state->aDFileSet, state->iFileSet);
      } else {
        *ppRow = NULL;
        return code;
      }

1775 1776 1777
      if (*state->pDataFReader == NULL || (*state->pDataFReader)->pSet->fid != pFileSet->fid) {
        if (*state->pDataFReader != NULL) {
          tsdbDataFReaderClose(state->pDataFReader);
M
Minglei Jin 已提交
1778

1779 1780
          resetLastBlockLoadInfo(state->pLoadInfo);
        }
1781

1782 1783 1784 1785
        code = tsdbDataFReaderOpen(state->pDataFReader, state->pTsdb, pFileSet);
        if (code) goto _err;
      }

1786 1787 1788 1789 1790 1791
      int  nTmpCols = nCols;
      bool hasTs = false;
      if (aCols[0] == PRIMARYKEY_TIMESTAMP_COL_ID) {
        --nTmpCols;
        hasTs = true;
      }
1792
      for (int i = 0; i < state->pLoadInfo->numOfStt; ++i) {
1793 1794
        state->pLoadInfo[i].colIds = hasTs ? aCols + 1 : aCols;
        state->pLoadInfo[i].numOfCols = nTmpCols;
1795
        state->pLoadInfo[i].isLast = isLast;
1796
      }
1797
      tMergeTreeOpen(&state->mergeTree, 1, *state->pDataFReader, state->suid, state->uid,
D
dapan1121 已提交
1798
                     &(STimeWindow){.skey = state->lastTs, .ekey = TSKEY_MAX},
1799 1800
                     &(SVersionRange){.minVer = 0, .maxVer = UINT64_MAX}, state->pLoadInfo, false, NULL, true,
                     state->pDataIter);
1801
      state->pMergeTree = &state->mergeTree;
1802 1803 1804 1805 1806 1807 1808
      state->state = SFSLASTNEXTROW_BLOCKROW;
    }
    case SFSLASTNEXTROW_BLOCKROW: {
      if (nCols != state->pLoadInfo->numOfCols) {
        for (int i = 0; i < state->pLoadInfo->numOfStt; ++i) {
          state->pLoadInfo[i].numOfCols = nCols;

1809 1810
          state->pLoadInfo[i].checkRemainingRow = state->checkRemainingRow;
        }
1811
      }
1812 1813
      bool hasVal = tMergeTreeNext(&state->mergeTree);
      if (!hasVal) {
D
dapan1121 已提交
1814 1815 1816 1817 1818
        if (tMergeTreeIgnoreEarlierTs(&state->mergeTree)) {
          *pIgnoreEarlierTs = true;
          *ppRow = NULL;
          return code;
        }
1819
        state->state = SFSLASTNEXTROW_FILESET;
1820 1821
        goto _next_fileset;
      }
1822
      state->row = *tMergeTreeGetRow(&state->mergeTree);
1823
      *ppRow = &state->row;
D
dapan1121 已提交
1824

1825 1826 1827 1828 1829
      if (TSDBROW_TS(&state->row) <= state->lastTs) {
        *pIgnoreEarlierTs = true;
        *ppRow = NULL;
        return code;
      }
D
dapan1121 已提交
1830

1831 1832 1833 1834
      *pIgnoreEarlierTs = false;
      if (!hasVal) {
        state->state = SFSLASTNEXTROW_FILESET;
      }
1835

1836 1837 1838
      if (!state->checkRemainingRow) {
        state->checkRemainingRow = true;
      }
1839
      return code;
1840
    }
1841 1842 1843 1844 1845 1846
    default:
      ASSERT(0);
      break;
  }

_err:
1847
  /*if (state->pDataFReader) {
1848 1849
    tsdbDataFReaderClose(&state->pDataFReader);
    state->pDataFReader = NULL;
1850
    }*/
1851 1852 1853 1854 1855
  if (state->pMergeTree != NULL) {
    tMergeTreeClose(state->pMergeTree);
    state->pMergeTree = NULL;
  }

1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867
  *ppRow = NULL;

  return code;
}

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

  if (!state) {
    return code;
  }
1868
  /*
1869 1870 1871 1872
  if (state->pDataFReader) {
    tsdbDataFReaderClose(&state->pDataFReader);
    state->pDataFReader = NULL;
  }
1873
  */
1874 1875 1876 1877 1878
  if (state->pMergeTree != NULL) {
    tMergeTreeClose(state->pMergeTree);
    state->pMergeTree = NULL;
  }

1879 1880 1881
  return code;
}

1882 1883 1884 1885 1886 1887 1888 1889
typedef enum SFSNEXTROWSTATES {
  SFSNEXTROW_FS,
  SFSNEXTROW_FILESET,
  SFSNEXTROW_BLOCKDATA,
  SFSNEXTROW_BLOCKROW
} SFSNEXTROWSTATES;

typedef struct SFSNextRowIter {
1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900
  SFSNEXTROWSTATES   state;         // [input]
  STsdb             *pTsdb;         // [input]
  SBlockIdx         *pBlockIdxExp;  // [input]
  STSchema          *pTSchema;      // [input]
  tb_uid_t           suid;
  tb_uid_t           uid;
  int32_t            nFileSet;
  int32_t            iFileSet;
  SArray            *aDFileSet;
  SDataFReader     **pDataFReader;
  SArray            *aBlockIdx;
1901
  LRUHandle         *aBlockIdxHandle;
1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912
  SBlockIdx         *pBlockIdx;
  SMapData           blockMap;
  int32_t            nBlock;
  int32_t            iBlock;
  SDataBlk           block;
  SBlockData         blockData;
  SBlockData        *pBlockData;
  int32_t            nRow;
  int32_t            iRow;
  TSDBROW            row;
  SSttBlockLoadInfo *pLoadInfo;
1913
  int64_t            lastTs;
1914 1915
} SFSNextRowIter;

D
dapan1121 已提交
1916 1917
static int32_t getNextRowFromFS(void *iter, TSDBROW **ppRow, bool *pIgnoreEarlierTs, bool isLast, int16_t *aCols,
                                int nCols) {
1918 1919
  SFSNextRowIter *state = (SFSNextRowIter *)iter;
  int32_t         code = 0;
D
dapan1121 已提交
1920
  bool            checkRemainingRow = true;
1921 1922 1923

  switch (state->state) {
    case SFSNEXTROW_FS:
H
Hongze Cheng 已提交
1924
      // state->aDFileSet = state->pTsdb->pFS->cState->aDFileSet;
1925
      state->nFileSet = taosArrayGetSize(state->aDFileSet);
M
Minglei Jin 已提交
1926
      state->iFileSet = state->nFileSet;
1927 1928

      state->pBlockData = NULL;
1929 1930 1931

    case SFSNEXTROW_FILESET: {
      SDFileSet *pFileSet = NULL;
1932
    _next_fileset:
1933 1934 1935
      if (--state->iFileSet >= 0) {
        pFileSet = (SDFileSet *)taosArrayGet(state->aDFileSet, state->iFileSet);
      } else {
H
Hongze Cheng 已提交
1936
        // tBlockDataDestroy(&state->blockData, 1);
1937
        if (state->pBlockData) {
H
Hongze Cheng 已提交
1938
          tBlockDataDestroy(state->pBlockData);
1939 1940
          state->pBlockData = NULL;
        }
1941

1942 1943 1944 1945
        *ppRow = NULL;
        return code;
      }

1946 1947 1948 1949
      if (*state->pDataFReader == NULL || (*state->pDataFReader)->pSet->fid != pFileSet->fid) {
        if (*state->pDataFReader != NULL) {
          tsdbDataFReaderClose(state->pDataFReader);

1950
          // resetLastBlockLoadInfo(state->pLoadInfo);
1951 1952 1953 1954 1955
        }

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

      // tMapDataReset(&state->blockIdxMap);
1958
      /*
1959 1960 1961 1962 1963
      if (!state->aBlockIdx) {
        state->aBlockIdx = taosArrayInit(0, sizeof(SBlockIdx));
      } else {
        taosArrayClear(state->aBlockIdx);
      }
1964
      code = tsdbReadBlockIdx(*state->pDataFReader, state->aBlockIdx);
1965
      if (code) goto _err;
1966
      */
1967
      int32_t code = tsdbCacheGetBlockIdx(state->pTsdb->biCache, *state->pDataFReader, &state->aBlockIdxHandle);
1968 1969 1970
      if (code != TSDB_CODE_SUCCESS || state->aBlockIdxHandle == NULL) {
        goto _err;
      }
1971
      state->aBlockIdx = (SArray *)taosLRUCacheValue(state->pTsdb->biCache, state->aBlockIdxHandle);
1972

1973 1974
      /* if (state->pBlockIdx) { */
      /* } */
1975 1976
      /* code = tMapDataSearch(&state->blockIdxMap, state->pBlockIdxExp, tGetBlockIdx, tCmprBlockIdx,
       * &state->blockIdx);
1977 1978
       */
      state->pBlockIdx = taosArraySearch(state->aBlockIdx, state->pBlockIdxExp, tCmprBlockIdx, TD_EQ);
1979 1980 1981 1982 1983 1984
      if (!state->pBlockIdx) {
        tsdbBICacheRelease(state->pTsdb->biCache, state->aBlockIdxHandle);

        state->aBlockIdxHandle = NULL;
        state->aBlockIdx = NULL;
        /*
1985 1986 1987
         tsdbDataFReaderClose(state->pDataFReader);
         *state->pDataFReader = NULL;
         resetLastBlockLoadInfo(state->pLoadInfo);*/
1988 1989 1990
        goto _next_fileset;
      }

1991 1992
      tMapDataReset(&state->blockMap);
      /*
1993 1994 1995
      if (state->blockMap.pData != NULL) {
        tMapDataClear(&state->blockMap);
      }
1996 1997
      */
      code = tsdbReadDataBlk(*state->pDataFReader, state->pBlockIdx, &state->blockMap);
1998 1999 2000 2001
      if (code) goto _err;

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

2003 2004 2005
      if (!state->pBlockData) {
        state->pBlockData = &state->blockData;

2006 2007
        code = tBlockDataCreate(&state->blockData);
        if (code) goto _err;
2008
      }
2009 2010
    }
    case SFSNEXTROW_BLOCKDATA:
D
dapan1121 已提交
2011
    _next_datablock:
2012
      if (state->iBlock >= 0) {
H
Hongze Cheng 已提交
2013
        SDataBlk block = {0};
D
dapan1121 已提交
2014 2015
        bool     skipBlock = true;
        int      inputColIndex = 0;
2016

H
Hongze Cheng 已提交
2017
        tDataBlkReset(&block);
2018
        tBlockDataReset(state->pBlockData);
2019

H
Hongze Cheng 已提交
2020
        tMapDataGetItemByIdx(&state->blockMap, state->iBlock, &block, tGetDataBlk);
2021
        if (block.maxKey.ts <= state->lastTs) {
2022
          *pIgnoreEarlierTs = true;
D
dapan1121 已提交
2023 2024 2025 2026 2027 2028 2029
          if (state->pBlockData) {
            tBlockDataDestroy(state->pBlockData);
            state->pBlockData = NULL;
          }

          *ppRow = NULL;
          return code;
2030
        }
2031
        *pIgnoreEarlierTs = false;
2032
        tBlockDataReset(state->pBlockData);
H
Hongze Cheng 已提交
2033
        TABLEID tid = {.suid = state->suid, .uid = state->uid};
2034
        int     nTmpCols = nCols;
2035 2036 2037
        bool    hasTs = false;
        if (aCols[0] == PRIMARYKEY_TIMESTAMP_COL_ID) {
          --nTmpCols;
2038
          skipBlock = false;
2039
          hasTs = true;
2040
        }
2041
        code = tBlockDataInit(state->pBlockData, &tid, state->pTSchema, hasTs ? aCols + 1 : aCols, nTmpCols);
2042 2043
        if (code) goto _err;

2044
        code = tsdbReadDataBlock(*state->pDataFReader, &block, state->pBlockData);
2045 2046
        if (code) goto _err;

D
dapan1121 已提交
2047 2048 2049 2050 2051 2052
        for (int colIndex = 0; colIndex < state->pBlockData->nColData; ++colIndex) {
          SColData *pColData = &state->pBlockData->aColData[colIndex];

          if (isLast && (pColData->flag & HAS_VALUE)) {
            skipBlock = false;
            break;
M
Minglei Jin 已提交
2053
          } /*else if (pColData->flag & (HAS_VALUE | HAS_NULL)) {
D
dapan1121 已提交
2054 2055
            skipBlock = false;
            break;
M
Minglei Jin 已提交
2056 2057 2058 2059 2060
            }*/
        }

        if (!isLast) {
          skipBlock = false;
D
dapan1121 已提交
2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083
        }

        if (skipBlock) {
          if (--state->iBlock < 0) {
            tsdbDataFReaderClose(state->pDataFReader);
            *state->pDataFReader = NULL;
            // resetLastBlockLoadInfo(state->pLoadInfo);

            if (state->aBlockIdx) {
              // taosArrayDestroy(state->aBlockIdx);
              tsdbBICacheRelease(state->pTsdb->biCache, state->aBlockIdxHandle);

              state->aBlockIdxHandle = NULL;
              state->aBlockIdx = NULL;
            }

            state->state = SFSNEXTROW_FILESET;
            goto _next_fileset;
          } else {
            goto _next_datablock;
          }
        }

2084 2085 2086 2087
        state->nRow = state->blockData.nRow;
        state->iRow = state->nRow - 1;

        state->state = SFSNEXTROW_BLOCKROW;
D
dapan1121 已提交
2088 2089 2090 2091 2092 2093
        checkRemainingRow = false;
      }
    case SFSNEXTROW_BLOCKROW: {
      if (checkRemainingRow) {
        bool skipBlock = true;
        int  inputColIndex = 0;
M
Minglei Jin 已提交
2094 2095 2096
        if (aCols[0] == PRIMARYKEY_TIMESTAMP_COL_ID) {
          ++inputColIndex;
        }
D
dapan1121 已提交
2097 2098 2099 2100 2101 2102 2103 2104
        for (int colIndex = 0; colIndex < state->pBlockData->nColData; ++colIndex) {
          SColData *pColData = &state->pBlockData->aColData[colIndex];
          int16_t   cid = pColData->cid;

          if (inputColIndex < nCols && cid == aCols[inputColIndex]) {
            if (isLast && (pColData->flag & HAS_VALUE)) {
              skipBlock = false;
              break;
M
Minglei Jin 已提交
2105
            } /*else if (pColData->flag & (HAS_VALUE | HAS_NULL)) {
D
dapan1121 已提交
2106 2107
              skipBlock = false;
              break;
M
Minglei Jin 已提交
2108
              }*/
D
dapan1121 已提交
2109 2110 2111 2112 2113

            ++inputColIndex;
          }
        }

M
Minglei Jin 已提交
2114 2115 2116 2117
        if (!isLast) {
          skipBlock = false;
        }

D
dapan1121 已提交
2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137
        if (skipBlock) {
          if (--state->iBlock < 0) {
            tsdbDataFReaderClose(state->pDataFReader);
            *state->pDataFReader = NULL;
            // resetLastBlockLoadInfo(state->pLoadInfo);

            if (state->aBlockIdx) {
              // taosArrayDestroy(state->aBlockIdx);
              tsdbBICacheRelease(state->pTsdb->biCache, state->aBlockIdxHandle);

              state->aBlockIdxHandle = NULL;
              state->aBlockIdx = NULL;
            }

            state->state = SFSNEXTROW_FILESET;
            goto _next_fileset;
          } else {
            goto _next_datablock;
          }
        }
2138
      }
D
dapan1121 已提交
2139

2140
      if (state->iRow >= 0) {
2141
        state->row = tsdbRowFromBlockData(state->pBlockData, state->iRow);
2142 2143 2144 2145 2146
        *ppRow = &state->row;

        if (--state->iRow < 0) {
          state->state = SFSNEXTROW_BLOCKDATA;
          if (--state->iBlock < 0) {
2147 2148
            tsdbDataFReaderClose(state->pDataFReader);
            *state->pDataFReader = NULL;
2149
            // resetLastBlockLoadInfo(state->pLoadInfo);
2150

2151
            if (state->aBlockIdx) {
2152
              // taosArrayDestroy(state->aBlockIdx);
2153
              tsdbBICacheRelease(state->pTsdb->biCache, state->aBlockIdxHandle);
2154 2155

              state->aBlockIdxHandle = NULL;
2156
              state->aBlockIdx = NULL;
2157
            }
2158

2159 2160 2161 2162 2163 2164
            state->state = SFSNEXTROW_FILESET;
          }
        }
      }

      return code;
D
dapan1121 已提交
2165
    }
2166 2167 2168 2169 2170 2171
    default:
      ASSERT(0);
      break;
  }

_err:
2172 2173 2174 2175 2176 2177
  /*
  if (*state->pDataFReader) {
    tsdbDataFReaderClose(state->pDataFReader);
    *state->pDataFReader = NULL;
    resetLastBlockLoadInfo(state->pLoadInfo);
    }*/
2178
  if (state->aBlockIdx) {
2179
    // taosArrayDestroy(state->aBlockIdx);
2180
    tsdbBICacheRelease(state->pTsdb->biCache, state->aBlockIdxHandle);
2181 2182

    state->aBlockIdxHandle = NULL;
2183 2184 2185
    state->aBlockIdx = NULL;
  }
  if (state->pBlockData) {
H
Hongze Cheng 已提交
2186
    tBlockDataDestroy(state->pBlockData);
2187
    state->pBlockData = NULL;
2188 2189
  }

2190
  *ppRow = NULL;
2191

2192 2193 2194
  return code;
}

2195 2196 2197 2198 2199 2200 2201
int32_t clearNextRowFromFS(void *iter) {
  int32_t code = 0;

  SFSNextRowIter *state = (SFSNextRowIter *)iter;
  if (!state) {
    return code;
  }
2202
  /*
2203 2204 2205
  if (state->pDataFReader) {
    tsdbDataFReaderClose(&state->pDataFReader);
    state->pDataFReader = NULL;
2206
    }*/
2207
  if (state->aBlockIdx) {
2208
    // taosArrayDestroy(state->aBlockIdx);
2209
    tsdbBICacheRelease(state->pTsdb->biCache, state->aBlockIdxHandle);
2210 2211

    state->aBlockIdxHandle = NULL;
2212 2213 2214
    state->aBlockIdx = NULL;
  }
  if (state->pBlockData) {
H
Hongze Cheng 已提交
2215
    // tBlockDataDestroy(&state->blockData, 1);
H
Hongze Cheng 已提交
2216
    tBlockDataDestroy(state->pBlockData);
2217 2218 2219
    state->pBlockData = NULL;
  }

2220 2221 2222 2223
  if (state->blockMap.pData != NULL) {
    tMapDataClear(&state->blockMap);
  }

2224 2225 2226
  return code;
}

2227 2228 2229 2230 2231 2232 2233 2234 2235
typedef enum SMEMNEXTROWSTATES {
  SMEMNEXTROW_ENTER,
  SMEMNEXTROW_NEXT,
} SMEMNEXTROWSTATES;

typedef struct SMemNextRowIter {
  SMEMNEXTROWSTATES state;
  STbData          *pMem;  // [input]
  STbDataIter       iter;  // mem buffer skip list iterator
2236
  int64_t           lastTs;
2237 2238
  // bool              iterOpened;
  // TSDBROW          *curRow;
2239 2240
} SMemNextRowIter;

D
dapan1121 已提交
2241 2242
static int32_t getNextRowFromMem(void *iter, TSDBROW **ppRow, bool *pIgnoreEarlierTs, bool isLast, int16_t *aCols,
                                 int nCols) {
2243 2244
  SMemNextRowIter *state = (SMemNextRowIter *)iter;
  int32_t          code = 0;
2245
  *pIgnoreEarlierTs = false;
2246 2247 2248
  switch (state->state) {
    case SMEMNEXTROW_ENTER: {
      if (state->pMem != NULL) {
2249 2250 2251 2252 2253
        if (state->pMem->maxKey <= state->lastTs) {
          *ppRow = NULL;
          *pIgnoreEarlierTs = true;
          return code;
        }
2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288
        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;
}

2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326
/* static int32_t tsRowFromTsdbRow(STSchema *pTSchema, TSDBROW *pRow, STSRow **ppRow) { */
/*   int32_t code = 0; */

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

/*   if (pRow->type == 0) { */
/*     *ppRow = tdRowDup(pRow->pTSRow); */
/*   } else { */
/*     SArray *pArray = taosArrayInit(pTSchema->numOfCols, sizeof(SColVal)); */
/*     if (pArray == NULL) { */
/*       code = TSDB_CODE_OUT_OF_MEMORY; */
/*       goto _exit; */
/*     } */

/*     TSDBKEY   key = TSDBROW_KEY(pRow); */
/*     STColumn *pTColumn = &pTSchema->columns[0]; */
/*     *pColVal = COL_VAL_VALUE(pTColumn->colId, pTColumn->type, (SValue){.ts = key.ts}); */

/*     if (taosArrayPush(pArray, pColVal) == NULL) { */
/*       code = TSDB_CODE_OUT_OF_MEMORY; */
/*       goto _exit; */
/*     } */

/*     for (int16_t iCol = 1; iCol < pTSchema->numOfCols; iCol++) { */
/*       tsdbRowGetColVal(pRow, pTSchema, iCol, pColVal); */
/*       if (taosArrayPush(pArray, pColVal) == NULL) { */
/*         code = TSDB_CODE_OUT_OF_MEMORY; */
/*         goto _exit; */
/*       } */
/*     } */

/*     code = tdSTSRowNew(pArray, pTSchema, ppRow); */
/*     if (code) goto _exit; */
/*   } */

/* _exit: */
/*   return code; */
/* } */
2327

2328
static bool tsdbKeyDeleted(TSDBKEY *key, SArray *pSkyline, int64_t *iSkyline) {
2329 2330 2331 2332 2333 2334 2335 2336
  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) {
2337
      if (key->version <= pItemFront->version || (key->ts == pItemBack->ts && key->version <= pItemBack->version)) {
2338
        // if (key->version <= pItemFront->version || key->version <= pItemBack->version) {
2339 2340
        return true;
      } else {
2341 2342 2343 2344 2345
        if (*iSkyline > 1) {
          --*iSkyline;
        } else {
          return false;
        }
2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358
      }
    } else {
      if (*iSkyline > 1) {
        --*iSkyline;
      } else {
        return false;
      }
    }
  }

  return deleted;
}

D
dapan1121 已提交
2359 2360
typedef int32_t (*_next_row_fn_t)(void *iter, TSDBROW **ppRow, bool *pIgnoreEarlierTs, bool isLast, int16_t *aCols,
                                  int nCols);
2361
typedef int32_t (*_next_row_clear_fn_t)(void *iter);
2362

2363
typedef struct {
2364 2365 2366
  TSDBROW             *pRow;
  bool                 stop;
  bool                 next;
2367
  bool                 ignoreEarlierTs;
2368 2369 2370
  void                *iter;
  _next_row_fn_t       nextRowFn;
  _next_row_clear_fn_t nextRowClearFn;
2371
} TsdbNextRowState;
2372

2373 2374 2375 2376
typedef struct {
  SArray *pSkyline;
  int64_t iSkyline;

2377 2378 2379 2380 2381 2382
  SBlockIdx          idx;
  SMemNextRowIter    memState;
  SMemNextRowIter    imemState;
  SFSLastNextRowIter fsLastState;
  SFSNextRowIter     fsState;
  TSDBROW            memRow, imemRow, fsLastRow, fsRow;
2383

2384
  TsdbNextRowState input[4];
2385
  STsdb           *pTsdb;
2386 2387
} CacheNextRowIter;

2388
static int32_t nextRowIterOpen(CacheNextRowIter *pIter, tb_uid_t uid, STsdb *pTsdb, STSchema *pTSchema, tb_uid_t suid,
2389 2390
                               SSttBlockLoadInfo *pLoadInfo, SLDataIter *pLDataIter, STsdbReadSnap *pReadSnap,
                               SDataFReader **pDataFReader, SDataFReader **pDataFReaderLast, int64_t lastTs) {
2391 2392 2393
  int code = 0;

  STbData *pMem = NULL;
2394 2395
  if (pReadSnap->pMem) {
    pMem = tsdbGetTbDataFromMemTable(pReadSnap->pMem, suid, uid);
2396 2397 2398
  }

  STbData *pIMem = NULL;
2399 2400
  if (pReadSnap->pIMem) {
    pIMem = tsdbGetTbDataFromMemTable(pReadSnap->pIMem, suid, uid);
2401 2402
  }

H
Hongze Cheng 已提交
2403 2404
  pIter->pTsdb = pTsdb;

2405 2406
  pIter->pSkyline = taosArrayInit(32, sizeof(TSDBKEY));

2407
  SDelFile *pDelFile = pReadSnap->fs.pDelFile;
2408 2409 2410
  if (pDelFile) {
    SDelFReader *pDelFReader;

H
Hongze Cheng 已提交
2411
    code = tsdbDelFReaderOpen(&pDelFReader, pDelFile, pTsdb);
2412 2413
    if (code) goto _err;

S
stephenkgu 已提交
2414 2415 2416
    SArray *pDelIdxArray = taosArrayInit(32, sizeof(SDelIdx));

    code = tsdbReadDelIdx(pDelFReader, pDelIdxArray);
M
Minglei Jin 已提交
2417
    if (code) {
2418
      taosArrayDestroy(pDelIdxArray);
M
Minglei Jin 已提交
2419 2420 2421
      tsdbDelFReaderClose(&pDelFReader);
      goto _err;
    }
S
stephenkgu 已提交
2422 2423

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

S
stephenkgu 已提交
2425
    code = getTableDelSkyline(pMem, pIMem, pDelFReader, delIdx, pIter->pSkyline);
2426
    if (code) {
2427
      taosArrayDestroy(pDelIdxArray);
2428 2429 2430
      tsdbDelFReaderClose(&pDelFReader);
      goto _err;
    }
2431

S
stephenkgu 已提交
2432
    taosArrayDestroy(pDelIdxArray);
2433 2434 2435 2436 2437 2438 2439 2440 2441 2442
    tsdbDelFReaderClose(&pDelFReader);
  } else {
    code = getTableDelSkyline(pMem, pIMem, NULL, NULL, pIter->pSkyline);
    if (code) goto _err;
  }

  pIter->iSkyline = taosArrayGetSize(pIter->pSkyline) - 1;

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

2443
  pIter->fsLastState.state = (SFSLASTNEXTROWSTATES)SFSNEXTROW_FS;
2444
  pIter->fsLastState.pTsdb = pTsdb;
2445
  pIter->fsLastState.aDFileSet = pReadSnap->fs.aDFileSet;
2446
  pIter->fsLastState.pTSchema = pTSchema;
2447
  pIter->fsLastState.suid = suid;
2448
  pIter->fsLastState.uid = uid;
2449
  pIter->fsLastState.pLoadInfo = pLoadInfo;
2450
  pIter->fsLastState.pDataFReader = pDataFReaderLast;
2451
  pIter->fsLastState.lastTs = lastTs;
2452
  pIter->fsLastState.pDataIter = pLDataIter;
2453

2454 2455
  pIter->fsState.state = SFSNEXTROW_FS;
  pIter->fsState.pTsdb = pTsdb;
2456
  pIter->fsState.aDFileSet = pReadSnap->fs.aDFileSet;
2457
  pIter->fsState.pBlockIdxExp = &pIter->idx;
2458 2459 2460
  pIter->fsState.pTSchema = pTSchema;
  pIter->fsState.suid = suid;
  pIter->fsState.uid = uid;
2461 2462
  pIter->fsState.pLoadInfo = pLoadInfo;
  pIter->fsState.pDataFReader = pDataFReader;
2463
  pIter->fsState.lastTs = lastTs;
2464

2465 2466 2467 2468
  pIter->input[0] = (TsdbNextRowState){&pIter->memRow, true, false, false, &pIter->memState, getNextRowFromMem, NULL};
  pIter->input[1] = (TsdbNextRowState){&pIter->imemRow, true, false, false, &pIter->imemState, getNextRowFromMem, NULL};
  pIter->input[2] = (TsdbNextRowState){
      &pIter->fsLastRow, false, true, false, &pIter->fsLastState, getNextRowFromFSLast, clearNextRowFromFSLast};
2469
  pIter->input[3] =
2470
      (TsdbNextRowState){&pIter->fsRow, false, true, false, &pIter->fsState, getNextRowFromFS, clearNextRowFromFS};
2471 2472 2473 2474

  if (pMem) {
    pIter->memState.pMem = pMem;
    pIter->memState.state = SMEMNEXTROW_ENTER;
2475
    pIter->memState.lastTs = lastTs;
2476 2477 2478 2479 2480 2481 2482
    pIter->input[0].stop = false;
    pIter->input[0].next = true;
  }

  if (pIMem) {
    pIter->imemState.pMem = pIMem;
    pIter->imemState.state = SMEMNEXTROW_ENTER;
2483
    pIter->imemState.lastTs = lastTs;
2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495
    pIter->input[1].stop = false;
    pIter->input[1].next = true;
  }

  return code;
_err:
  return code;
}

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

2496
  for (int i = 0; i < 4; ++i) {
2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510
    if (pIter->input[i].nextRowClearFn) {
      pIter->input[i].nextRowClearFn(pIter->input[i].iter);
    }
  }

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

_err:
  return code;
}

// iterate next row non deleted backward ts, version (from high to low)
D
dapan1121 已提交
2511 2512
static int32_t nextRowIterGet(CacheNextRowIter *pIter, TSDBROW **ppRow, bool *pIgnoreEarlierTs, bool isLast,
                              int16_t *aCols, int nCols) {
2513
  int code = 0;
2514 2515 2516
  for (;;) {
    for (int i = 0; i < 4; ++i) {
      if (pIter->input[i].next && !pIter->input[i].stop) {
D
dapan1121 已提交
2517 2518
        code = pIter->input[i].nextRowFn(pIter->input[i].iter, &pIter->input[i].pRow, &pIter->input[i].ignoreEarlierTs,
                                         isLast, aCols, nCols);
2519
        if (code) goto _err;
2520

2521 2522 2523 2524
        if (pIter->input[i].pRow == NULL) {
          pIter->input[i].stop = true;
          pIter->input[i].next = false;
        }
2525 2526 2527
      }
    }

2528 2529
    if (pIter->input[0].stop && pIter->input[1].stop && pIter->input[2].stop && pIter->input[3].stop) {
      *ppRow = NULL;
2530 2531
      *pIgnoreEarlierTs = (pIter->input[0].ignoreEarlierTs || pIter->input[1].ignoreEarlierTs ||
                           pIter->input[2].ignoreEarlierTs || pIter->input[3].ignoreEarlierTs);
2532 2533
      return code;
    }
2534

2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550
    // select maxpoint(s) from mem, imem, fs and last
    TSDBROW *max[4] = {0};
    int      iMax[4] = {-1, -1, -1, -1};
    int      nMax = 0;
    TSKEY    maxKey = TSKEY_MIN;

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

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

2552 2553
          iMax[nMax] = i;
          max[nMax++] = pIter->input[i].pRow;
2554 2555
        } else {
          pIter->input[i].next = false;
2556 2557 2558 2559
        }
      }
    }

2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571
    // delete detection
    TSDBROW *merge[4] = {0};
    int      iMerge[4] = {-1, -1, -1, -1};
    int      nMerge = 0;
    for (int i = 0; i < nMax; ++i) {
      TSDBKEY maxKey1 = TSDBROW_KEY(max[i]);

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

2573 2574
      pIter->input[iMax[i]].next = deleted;
    }
2575

2576 2577
    if (nMerge > 0) {
      pIter->input[iMerge[0]].next = true;
2578

2579 2580 2581
      *ppRow = merge[0];
      return code;
    }
2582 2583 2584 2585 2586 2587
  }

_err:
  return code;
}

2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601
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;
}

2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616
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;
}

2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638
static int32_t cloneTSchema(STSchema *pSrc, STSchema **ppDst) {
  int32_t len = sizeof(STSchema) + sizeof(STColumn) * pSrc->numOfCols;
  *ppDst = taosMemoryMalloc(len);
  if (NULL == *ppDst) {
    return TSDB_CODE_OUT_OF_MEMORY;
  }
  memcpy(*ppDst, pSrc, len);
  return TSDB_CODE_SUCCESS;
}

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

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

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

2640
static int32_t mergeLastRow(tb_uid_t uid, STsdb *pTsdb, bool *dup, SArray **ppColArray, SCacheRowsReader *pr) {
2641
  STSchema *pTSchema = pr->pSchema;  // metaGetTbTSchema(pTsdb->pVnode->pMeta, uid, -1, 1);
2642
  int16_t   nLastCol = pTSchema->numOfCols;
2643 2644 2645
  int16_t   iCol = 0;
  int16_t   noneCol = 0;
  bool      setNoneCol = false;
2646
  bool      hasRow = false;
2647
  bool      ignoreEarlierTs = false;
2648
  SArray   *pColArray = NULL;
2649 2650
  SColVal  *pColVal = &(SColVal){0};

2651 2652 2653 2654 2655
  int32_t code = initLastColArray(pTSchema, &pColArray);
  if (TSDB_CODE_SUCCESS != code) {
    return code;
  }

2656 2657 2658
  TSKEY lastRowTs = TSKEY_MAX;

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

  do {
    TSDBROW *pRow = NULL;
D
dapan1121 已提交
2664
    nextRowIterGet(&iter, &pRow, &ignoreEarlierTs, false, NULL, 0);
2665 2666 2667 2668 2669

    if (!pRow) {
      break;
    }

2670 2671
    hasRow = true;

2672 2673 2674 2675 2676 2677 2678
    int32_t sversion = TSDBROW_SVERSION(pRow);
    if (sversion != -1) {
      code = updateTSchema(sversion, pr, uid);
      if (TSDB_CODE_SUCCESS != code) {
        goto _err;
      }
      pTSchema = pr->pCurrSchema;
2679 2680 2681
    }
    int16_t nCol = pTSchema->numOfCols;

2682 2683
    TSKEY rowTs = TSDBROW_TS(pRow);

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

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

      for (iCol = 1; iCol < nCol; ++iCol) {
2692 2693 2694 2695 2696 2697 2698
        if (iCol >= nLastCol) {
          break;
        }
        SLastCol *pCol = taosArrayGet(pColArray, iCol);
        if (pCol->colVal.cid != pTSchema->columns[iCol].colId) {
          continue;
        }
2699 2700
        tsdbRowGetColVal(pRow, pTSchema, iCol, pColVal);

2701
        *pCol = (SLastCol){.ts = lastRowTs, .colVal = *pColVal};
2702
        if (IS_VAR_DATA_TYPE(pColVal->type) && pColVal->value.nData > 0) {
2703 2704
          pCol->colVal.value.pData = taosMemoryMalloc(pCol->colVal.value.nData);
          if (pCol->colVal.value.pData == NULL) {
M
Minglei Jin 已提交
2705 2706 2707 2708
            terrno = TSDB_CODE_OUT_OF_MEMORY;
            code = TSDB_CODE_OUT_OF_MEMORY;
            goto _err;
          }
2709
          memcpy(pCol->colVal.value.pData, pColVal->value.pData, pColVal->value.nData);
2710 2711
        }

H
Hongze Cheng 已提交
2712
        if (COL_VAL_IS_NONE(pColVal) && !setNoneCol) {
2713 2714 2715 2716 2717
          noneCol = iCol;
          setNoneCol = true;
        }
      }
      if (!setNoneCol) {
2718
        // done, goto return pColArray
2719 2720 2721 2722 2723 2724
        break;
      } else {
        continue;
      }
    }

2725 2726
    if ((rowTs < lastRowTs)) {
      // done, goto return pColArray
2727 2728 2729 2730 2731 2732 2733 2734 2735 2736
      break;
    }

    // merge into pColArray
    setNoneCol = false;
    for (iCol = noneCol; iCol < nCol; ++iCol) {
      // high version's column value
      SColVal *tColVal = (SColVal *)taosArrayGet(pColArray, iCol);

      tsdbRowGetColVal(pRow, pTSchema, iCol, pColVal);
H
Hongze Cheng 已提交
2737
      if (COL_VAL_IS_NONE(tColVal) && !COL_VAL_IS_NONE(pColVal)) {
2738
        SLastCol lastCol = {.ts = rowTs, .colVal = *pColVal};
2739
        if (IS_VAR_DATA_TYPE(pColVal->type) && pColVal->value.nData > 0) {
2740 2741 2742 2743
          SLastCol *pLastCol = (SLastCol *)taosArrayGet(pColArray, iCol);
          taosMemoryFree(pLastCol->colVal.value.pData);

          lastCol.colVal.value.pData = taosMemoryMalloc(lastCol.colVal.value.nData);
M
Minglei Jin 已提交
2744 2745 2746 2747 2748
          if (lastCol.colVal.value.pData == NULL) {
            terrno = TSDB_CODE_OUT_OF_MEMORY;
            code = TSDB_CODE_OUT_OF_MEMORY;
            goto _err;
          }
2749 2750 2751 2752
          memcpy(lastCol.colVal.value.pData, pColVal->value.pData, pColVal->value.nData);
        }

        taosArraySet(pColArray, iCol, &lastCol);
H
Hongze Cheng 已提交
2753
      } else if (COL_VAL_IS_NONE(tColVal) && COL_VAL_IS_NONE(pColVal) && !setNoneCol) {
2754 2755 2756 2757 2758 2759 2760 2761
        noneCol = iCol;
        setNoneCol = true;
      }
    }
  } while (setNoneCol);

  // build the result ts row here
  *dup = false;
2762 2763 2764 2765
  // if (taosArrayGetSize(pColArray) != nCol) {
  //*ppColArray = NULL;
  // taosArrayDestroy(pColArray);
  //} else {
2766
  if (!hasRow) {
2767 2768 2769 2770 2771 2772
    if (ignoreEarlierTs) {
      taosArrayDestroy(pColArray);
      pColArray = NULL;
    } else {
      taosArrayClear(pColArray);
    }
2773
  }
2774 2775
  *ppColArray = pColArray;
  //}
2776 2777

  nextRowIterClose(&iter);
2778
  // taosMemoryFreeClear(pTSchema);
2779 2780 2781 2782 2783
  return code;

_err:
  nextRowIterClose(&iter);
  taosArrayDestroy(pColArray);
2784
  // taosMemoryFreeClear(pTSchema);
2785 2786 2787
  return code;
}

2788
static int32_t mergeLast(tb_uid_t uid, STsdb *pTsdb, SArray **ppLastArray, SCacheRowsReader *pr) {
2789
  STSchema *pTSchema = pr->pSchema;  // metaGetTbTSchema(pTsdb->pVnode->pMeta, uid, -1, 1);
2790
  int16_t   nLastCol = pTSchema->numOfCols;
2791 2792
  int16_t   noneCol = 0;
  bool      setNoneCol = false;
2793
  bool      hasRow = false;
2794
  bool      ignoreEarlierTs = false;
2795
  SArray   *pColArray = NULL;
2796
  SColVal  *pColVal = &(SColVal){0};
D
dapan1121 已提交
2797
  int16_t   nCols = nLastCol;
2798

2799 2800 2801 2802
  int32_t code = initLastColArray(pTSchema, &pColArray);
  if (TSDB_CODE_SUCCESS != code) {
    return code;
  }
D
dapan1121 已提交
2803 2804 2805 2806 2807 2808 2809 2810 2811
  SArray *aColArray = taosArrayInit(nCols, sizeof(int16_t));
  if (NULL == aColArray) {
    taosArrayDestroy(pColArray);

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

2813 2814 2815
  TSKEY lastRowTs = TSKEY_MAX;

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

  do {
    TSDBROW *pRow = NULL;
D
dapan1121 已提交
2821
    nextRowIterGet(&iter, &pRow, &ignoreEarlierTs, true, TARRAY_DATA(aColArray), TARRAY_SIZE(aColArray));
2822 2823 2824 2825 2826

    if (!pRow) {
      break;
    }

2827 2828
    hasRow = true;

2829 2830 2831 2832 2833 2834 2835
    int32_t sversion = TSDBROW_SVERSION(pRow);
    if (sversion != -1) {
      code = updateTSchema(sversion, pr, uid);
      if (TSDB_CODE_SUCCESS != code) {
        goto _err;
      }
      pTSchema = pr->pCurrSchema;
2836 2837 2838
    }
    int16_t nCol = pTSchema->numOfCols;

2839 2840 2841 2842 2843 2844
    TSKEY rowTs = TSDBROW_TS(pRow);

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

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

2848 2849 2850 2851 2852 2853 2854 2855
      for (int16_t iCol = 1; iCol < nCol; ++iCol) {
        if (iCol >= nLastCol) {
          break;
        }
        SLastCol *pCol = taosArrayGet(pColArray, iCol);
        if (pCol->colVal.cid != pTSchema->columns[iCol].colId) {
          continue;
        }
2856 2857
        tsdbRowGetColVal(pRow, pTSchema, iCol, pColVal);

2858
        *pCol = (SLastCol){.ts = lastRowTs, .colVal = *pColVal};
2859
        if (IS_VAR_DATA_TYPE(pColVal->type) && pColVal->value.nData > 0) {
2860 2861
          pCol->colVal.value.pData = taosMemoryMalloc(pCol->colVal.value.nData);
          if (pCol->colVal.value.pData == NULL) {
M
Minglei Jin 已提交
2862 2863 2864 2865
            terrno = TSDB_CODE_OUT_OF_MEMORY;
            code = TSDB_CODE_OUT_OF_MEMORY;
            goto _err;
          }
2866
          memcpy(pCol->colVal.value.pData, pColVal->value.pData, pColVal->value.nData);
2867 2868
        }

D
dapan1121 已提交
2869 2870 2871 2872 2873 2874 2875 2876
        if (!COL_VAL_IS_VALUE(pColVal)) {
          if (!setNoneCol) {
            noneCol = iCol;
            setNoneCol = true;
          }
        } else {
          int32_t aColIndex = taosArraySearchIdx(aColArray, &pColVal->cid, compareInt16Val, TD_EQ);
          taosArrayRemove(aColArray, aColIndex);
2877 2878 2879
        }
      }
      if (!setNoneCol) {
2880
        // done, goto return pColArray
2881 2882 2883 2884 2885
        break;
      } else {
        continue;
      }
    }
2886

2887 2888
    // merge into pColArray
    setNoneCol = false;
2889 2890 2891 2892
    for (int16_t iCol = noneCol; iCol < nCol; ++iCol) {
      if (iCol >= nLastCol) {
        break;
      }
2893
      // high version's column value
2894
      SLastCol *lastColVal = (SLastCol *)taosArrayGet(pColArray, iCol);
2895 2896 2897 2898
      if (lastColVal->colVal.cid != pTSchema->columns[iCol].colId) {
        continue;
      }
      SColVal *tColVal = &lastColVal->colVal;
2899 2900

      tsdbRowGetColVal(pRow, pTSchema, iCol, pColVal);
H
Hongze Cheng 已提交
2901
      if (!COL_VAL_IS_VALUE(tColVal) && COL_VAL_IS_VALUE(pColVal)) {
2902 2903 2904 2905 2906 2907 2908 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 2937 2938 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 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983
        SLastCol lastCol = {.ts = rowTs, .colVal = *pColVal};
        if (IS_VAR_DATA_TYPE(pColVal->type) && pColVal->value.nData > 0) {
          SLastCol *pLastCol = (SLastCol *)taosArrayGet(pColArray, iCol);
          taosMemoryFree(pLastCol->colVal.value.pData);

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

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

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

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

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

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

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

    return TSDB_CODE_OUT_OF_MEMORY;
  }

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

  TSKEY lastRowTs = TSKEY_MAX;

  CacheNextRowIter iter = {0};
H
Haojun Liao 已提交
2984
  nextRowIterOpen(&iter, uid, pTsdb, pTSchema, pr->suid, pr->pLoadInfo, pr->pDataIter, pr->pReadSnap, &pr->pDataFReader,
2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011
                  &pr->pDataFReaderLast, pr->lastTs);

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

    if (!pRow) {
      break;
    }

    hasRow = true;

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

    TSKEY rowTs = TSDBROW_TS(pRow);

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

3012
      for (int16_t iCol = noneCol; iCol < nCols; ++iCol) {
3013 3014 3015 3016 3017 3018 3019
        if (iCol >= nLastCol) {
          break;
        }
        SLastCol *pCol = taosArrayGet(pColArray, iCol);
        if (pCol->colVal.cid != pTSchema->columns[slotIds[iCol]].colId) {
          continue;
        }
3020 3021 3022
        if (slotIds[iCol] == 0) {
          STColumn *pTColumn = &pTSchema->columns[0];

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

3029
        *pCol = (SLastCol){.ts = rowTs, .colVal = *pColVal};
3030
        if (IS_VAR_DATA_TYPE(pColVal->type) /*&& pColVal->value.nData > 0*/) {
3031 3032 3033 3034 3035 3036
          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;
          }
3037 3038 3039
          if (pColVal->value.nData > 0) {
            memcpy(pCol->colVal.value.pData, pColVal->value.pData, pColVal->value.nData);
          }
3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076
        }

        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)) {
3077
        SLastCol lastCol = {.ts = rowTs, .colVal = *pColVal};
3078
        if (IS_VAR_DATA_TYPE(pColVal->type) && pColVal->value.nData > 0) {
3079 3080 3081 3082
          SLastCol *pLastCol = (SLastCol *)taosArrayGet(pColArray, iCol);
          taosMemoryFree(pLastCol->colVal.value.pData);

          lastCol.colVal.value.pData = taosMemoryMalloc(lastCol.colVal.value.nData);
M
Minglei Jin 已提交
3083 3084 3085 3086 3087
          if (lastCol.colVal.value.pData == NULL) {
            terrno = TSDB_CODE_OUT_OF_MEMORY;
            code = TSDB_CODE_OUT_OF_MEMORY;
            goto _err;
          }
3088 3089 3090 3091
          memcpy(lastCol.colVal.value.pData, pColVal->value.pData, pColVal->value.nData);
        }

        taosArraySet(pColArray, iCol, &lastCol);
D
dapan1121 已提交
3092 3093
        int32_t aColIndex = taosArraySearchIdx(aColArray, &lastCol.colVal.cid, compareInt16Val, TD_EQ);
        taosArrayRemove(aColArray, aColIndex);
H
Hongze Cheng 已提交
3094
      } else if (!COL_VAL_IS_VALUE(tColVal) && !COL_VAL_IS_VALUE(pColVal) && !setNoneCol) {
3095 3096 3097 3098 3099 3100
        noneCol = iCol;
        setNoneCol = true;
      }
    }
  } while (setNoneCol);

3101
  if (!hasRow) {
3102 3103 3104 3105 3106 3107
    if (ignoreEarlierTs) {
      taosArrayDestroy(pColArray);
      pColArray = NULL;
    } else {
      taosArrayClear(pColArray);
    }
3108
  }
3109
  *ppLastArray = pColArray;
3110 3111

  nextRowIterClose(&iter);
D
dapan1121 已提交
3112
  taosArrayDestroy(aColArray);
3113

3114 3115 3116 3117
  return code;

_err:
  nextRowIterClose(&iter);
3118
  // taosMemoryFreeClear(pTSchema);
3119 3120
  *ppLastArray = NULL;
  taosArrayDestroy(pColArray);
D
dapan1121 已提交
3121
  taosArrayDestroy(aColArray);
3122 3123 3124
  return code;
}

3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153
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};
H
Haojun Liao 已提交
3154
  nextRowIterOpen(&iter, uid, pTsdb, pTSchema, pr->suid, pr->pLoadInfo, pr->pDataIter, pr->pReadSnap, &pr->pDataFReader,
3155 3156 3157 3158
                  &pr->pDataFReaderLast, pr->lastTs);

  do {
    TSDBROW *pRow = NULL;
M
Minglei Jin 已提交
3159
    nextRowIterGet(&iter, &pRow, &ignoreEarlierTs, false, TARRAY_DATA(aColArray), TARRAY_SIZE(aColArray));
3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199

    if (!pRow) {
      break;
    }

    hasRow = true;

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

    TSKEY rowTs = TSDBROW_TS(pRow);

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

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

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

        *pCol = (SLastCol){.ts = rowTs, .colVal = *pColVal};
3200
        if (IS_VAR_DATA_TYPE(pColVal->type) /*&& pColVal->value.nData > 0*/) {
3201 3202 3203 3204 3205 3206
          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;
          }
3207 3208 3209
          if (pColVal->value.nData > 0) {
            memcpy(pCol->colVal.value.pData, pColVal->value.pData, pColVal->value.nData);
          }
3210 3211
        }

3212
        /*if (COL_VAL_IS_NONE(pColVal)) {
3213 3214 3215 3216
          if (!setNoneCol) {
            noneCol = iCol;
            setNoneCol = true;
          }
3217 3218 3219 3220
          } else {*/
        int32_t aColIndex = taosArraySearchIdx(aColArray, &pColVal->cid, compareInt16Val, TD_EQ);
        if (aColIndex >= 0) {
          taosArrayRemove(aColArray, aColIndex);
3221
        }
3222
        //}
3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294
      }
      if (!setNoneCol) {
        // done, goto return pColArray
        break;
      } else {
        continue;
      }
    }

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

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

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

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

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

  nextRowIterClose(&iter);
  taosArrayDestroy(aColArray);

  return code;

_err:
  nextRowIterClose(&iter);

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

3295
int32_t tsdbCacheGetLastrowH(SLRUCache *pCache, tb_uid_t uid, SCacheRowsReader *pr, LRUHandle **handle) {
3296 3297 3298 3299
  int32_t code = 0;
  char    key[32] = {0};
  int     keyLen = 0;

3300
  //  getTableCacheKeyS(uid, "lr", key, &keyLen);
3301
  getTableCacheKey(uid, 0, key, &keyLen);
3302
  LRUHandle *h = taosLRUCacheLookup(pCache, key, keyLen);
3303
  if (!h) {
3304
    STsdb *pTsdb = pr->pVnode->pTsdb;
3305 3306 3307 3308
    taosThreadMutexLock(&pTsdb->lruMutex);

    h = taosLRUCacheLookup(pCache, key, keyLen);
    if (!h) {
3309
      SArray *pArray = NULL;
3310
      bool    dup = false;  // which is always false for now
3311
      code = mergeLastRow(uid, pTsdb, &dup, &pArray, pr);
3312 3313
      // if table's empty or error or ignore ignore earlier ts, set handle NULL and return
      if (code < 0 || pArray == NULL) {
3314 3315
        if (!dup && pArray) {
          taosArrayDestroy(pArray);
3316 3317
        }

M
Minglei Jin 已提交
3318 3319
        taosThreadMutexUnlock(&pTsdb->lruMutex);

3320
        *handle = NULL;
M
Minglei Jin 已提交
3321

3322
        return 0;
3323 3324
      }

M
Minglei Jin 已提交
3325
      size_t              charge = pArray->capacity * pArray->elemSize + sizeof(*pArray);
3326
      _taos_lru_deleter_t deleter = deleteTableCacheLast;
D
dapan1121 已提交
3327 3328
      LRUStatus           status =
          taosLRUCacheInsert(pCache, key, keyLen, pArray, charge, deleter, &h, TAOS_LRU_PRIORITY_LOW, NULL);
3329 3330 3331
      if (status != TAOS_LRU_STATUS_OK) {
        code = -1;
      }
3332
    }
3333
    taosThreadMutexUnlock(&pTsdb->lruMutex);
3334 3335 3336 3337 3338 3339
  }

  *handle = h;

  return code;
}
3340

3341
int32_t tsdbCacheGetLastH(SLRUCache *pCache, tb_uid_t uid, SCacheRowsReader *pr, LRUHandle **handle) {
3342 3343 3344 3345
  int32_t code = 0;
  char    key[32] = {0};
  int     keyLen = 0;

3346
  // getTableCacheKeyS(uid, "l", key, &keyLen);
3347
  getTableCacheKey(uid, 1, key, &keyLen);
3348
  LRUHandle *h = taosLRUCacheLookup(pCache, key, keyLen);
3349
  if (!h) {
3350
    STsdb *pTsdb = pr->pVnode->pTsdb;
3351
    taosThreadMutexLock(&pTsdb->lruMutex);
3352

3353
    h = taosLRUCacheLookup(pCache, key, keyLen);
3354 3355
    if (!h) {
      SArray *pLastArray = NULL;
3356
      code = mergeLast(uid, pTsdb, &pLastArray, pr);
3357 3358
      // if table's empty or error or ignore ignore earlier ts, set handle NULL and return
      if (code < 0 || pLastArray == NULL) {
3359 3360
        taosThreadMutexUnlock(&pTsdb->lruMutex);

3361 3362 3363 3364
        *handle = NULL;
        return 0;
      }

M
Minglei Jin 已提交
3365
      size_t              charge = pLastArray->capacity * pLastArray->elemSize + sizeof(*pLastArray);
3366
      _taos_lru_deleter_t deleter = deleteTableCacheLast;
M
Minglei Jin 已提交
3367
      LRUStatus           status =
D
dapan1121 已提交
3368
          taosLRUCacheInsert(pCache, key, keyLen, pLastArray, charge, deleter, &h, TAOS_LRU_PRIORITY_LOW, NULL);
3369 3370 3371
      if (status != TAOS_LRU_STATUS_OK) {
        code = -1;
      }
3372
    }
3373
    taosThreadMutexUnlock(&pTsdb->lruMutex);
3374 3375 3376
  }

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

3378 3379 3380
  return code;
}

M
Minglei Jin 已提交
3381 3382 3383 3384 3385 3386 3387
int32_t tsdbCacheRelease(SLRUCache *pCache, LRUHandle *h) {
  int32_t code = 0;

  taosLRUCacheRelease(pCache, h, false);

  return code;
}
3388 3389 3390 3391 3392 3393

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

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

3395 3396 3397 3398 3399 3400 3401 3402
size_t tsdbCacheGetUsage(SVnode *pVnode) {
  size_t usage = 0;
  if (pVnode->pTsdb != NULL) {
    usage = taosLRUCacheGetUsage(pVnode->pTsdb->lruCache);
  }

  return usage;
}
3403

D
dapan1121 已提交
3404 3405 3406 3407 3408 3409 3410 3411 3412
int32_t tsdbCacheGetElems(SVnode *pVnode) {
  int32_t elems = 0;
  if (pVnode->pTsdb != NULL) {
    elems = taosLRUCacheGetElems(pVnode->pTsdb->lruCache);
  }

  return elems;
}

3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440
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 已提交
3441 3442
static void deleteBICache(const void *key, size_t keyLen, void *value, void *ud) {
  (void)ud;
3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472
  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 已提交
3473 3474
      LRUStatus           status =
          taosLRUCacheInsert(pCache, key, keyLen, pArray, charge, deleter, &h, TAOS_LRU_PRIORITY_LOW, NULL);
3475 3476 3477 3478 3479 3480 3481 3482
      if (status != TAOS_LRU_STATUS_OK) {
        code = -1;
      }
    }

    taosThreadMutexUnlock(&pTsdb->biMutex);
  }

3483
  tsdbTrace("bi cache:%p, ref", pCache);
3484 3485 3486 3487 3488 3489 3490 3491 3492
  *handle = h;

  return code;
}

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

  taosLRUCacheRelease(pCache, h, false);
3493
  tsdbTrace("bi cache:%p, release", pCache);
3494 3495 3496

  return code;
}