tsdbMeta.c 52.4 KB
Newer Older
H
Hongze Cheng 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/*
 * 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/>.
 */
H
Hongze Cheng 已提交
15 16

#if 0
H
Hongze Cheng 已提交
17
#include "tcompare.h"
H
Hongze Cheng 已提交
18
#include "tsdbint.h"
H
Hongze Cheng 已提交
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
#include "tutil.h"

#define TSDB_SUPER_TABLE_SL_LEVEL 5
#define DEFAULT_TAG_INDEX_COLUMN 0

static char *  getTagIndexKey(const void *pData);
static STable *tsdbNewTable();
static STable *tsdbCreateTableFromCfg(STableCfg *pCfg, bool isSuper, STable *pSTable);
static void    tsdbFreeTable(STable *pTable);
static int     tsdbAddTableToMeta(STsdbRepo *pRepo, STable *pTable, bool addIdx, bool lock);
static void    tsdbRemoveTableFromMeta(STsdbRepo *pRepo, STable *pTable, bool rmFromIdx, bool lock);
static int     tsdbAddTableIntoIndex(STsdbMeta *pMeta, STable *pTable, bool refSuper);
static int     tsdbRemoveTableFromIndex(STsdbMeta *pMeta, STable *pTable);
static int     tsdbInitTableCfg(STableCfg *config, ETableType type, uint64_t uid, int32_t tid);
static int     tsdbTableSetSchema(STableCfg *config, STSchema *pSchema, bool dup);
static int     tsdbTableSetName(STableCfg *config, char *name, bool dup);
static int     tsdbTableSetTagSchema(STableCfg *config, STSchema *pSchema, bool dup);
static int     tsdbTableSetSName(STableCfg *config, char *sname, bool dup);
static int     tsdbTableSetSuperUid(STableCfg *config, uint64_t uid);
static int     tsdbTableSetTagValue(STableCfg *config, SKVRow row, bool dup);
static int     tsdbTableSetStreamSql(STableCfg *config, char *sql, bool dup);
static int     tsdbEncodeTableName(void **buf, tstr *name);
static void *  tsdbDecodeTableName(void *buf, tstr **name);
static int     tsdbEncodeTable(void **buf, STable *pTable);
static void *  tsdbDecodeTable(void *buf, STable **pRTable);
static int     tsdbGetTableEncodeSize(int8_t act, STable *pTable);
static void *  tsdbInsertTableAct(STsdbRepo *pRepo, int8_t act, void *buf, STable *pTable);
static int     tsdbRemoveTableFromStore(STsdbRepo *pRepo, STable *pTable);
static int     tsdbRmTableFromMeta(STsdbRepo *pRepo, STable *pTable);
static int     tsdbAdjustMetaTables(STsdbRepo *pRepo, int tid);
static int     tsdbCheckTableTagVal(SKVRow *pKVRow, STSchema *pSchema);
H
Hongze Cheng 已提交
50
static int     tsdbInsertNewTableAction(STsdbRepo *pRepo, STable *pTable);
H
Hongze Cheng 已提交
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
static int     tsdbAddSchema(STable *pTable, STSchema *pSchema);
static void    tsdbFreeTableSchema(STable *pTable);

// ------------------ OUTER FUNCTIONS ------------------
int tsdbCreateTable(STsdbRepo *repo, STableCfg *pCfg) {
  STsdbRepo *pRepo = (STsdbRepo *)repo;
  STsdbMeta *pMeta = pRepo->tsdbMeta;
  STable *   super = NULL;
  STable *   table = NULL;
  bool       newSuper = false;
  bool       superChanged = false;
  int        tid = pCfg->tableId.tid;
  STable *   pTable = NULL;

  if (tid < 1 || tid > TSDB_MAX_TABLES) {
    tsdbError("vgId:%d failed to create table since invalid tid %d", REPO_ID(pRepo), tid);
    terrno = TSDB_CODE_TDB_IVD_CREATE_TABLE_INFO;
    goto _err;
  }

  if (tid < pMeta->maxTables && pMeta->tables[tid] != NULL) {
    if (TABLE_UID(pMeta->tables[tid]) == pCfg->tableId.uid) {
      tsdbError("vgId:%d table %s already exists, tid %d uid %" PRId64, REPO_ID(pRepo),
                TABLE_CHAR_NAME(pMeta->tables[tid]), TABLE_TID(pMeta->tables[tid]), TABLE_UID(pMeta->tables[tid]));
      return 0;
    } else {
      tsdbInfo("vgId:%d table %s at tid %d uid %" PRIu64
H
Hongze Cheng 已提交
78 79 80
               " exists, replace it with new table, this can be not reasonable",
               REPO_ID(pRepo), TABLE_CHAR_NAME(pMeta->tables[tid]), TABLE_TID(pMeta->tables[tid]),
               TABLE_UID(pMeta->tables[tid]));
H
Hongze Cheng 已提交
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 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
      tsdbDropTable(pRepo, pMeta->tables[tid]->tableId);
    }
  }

  pTable = tsdbGetTableByUid(pMeta, pCfg->tableId.uid);
  if (pTable != NULL) {
    tsdbError("vgId:%d table %s already exists, tid %d uid %" PRId64, REPO_ID(pRepo), TABLE_CHAR_NAME(pTable),
              TABLE_TID(pTable), TABLE_UID(pTable));
    terrno = TSDB_CODE_TDB_TABLE_ALREADY_EXIST;
    goto _err;
  }

  if (pCfg->type == TSDB_CHILD_TABLE) {
    super = tsdbGetTableByUid(pMeta, pCfg->superUid);
    if (super == NULL) {  // super table not exists, try to create it
      newSuper = true;
      super = tsdbCreateTableFromCfg(pCfg, true, NULL);
      if (super == NULL) goto _err;
    } else {
      if (TABLE_TYPE(super) != TSDB_SUPER_TABLE || TABLE_UID(super) != pCfg->superUid) {
        terrno = TSDB_CODE_TDB_IVD_CREATE_TABLE_INFO;
        goto _err;
      }

      if (schemaVersion(pCfg->tagSchema) > schemaVersion(super->tagSchema)) {
        // tag schema out of date, need to update super table tag version
        STSchema *pOldSchema = super->tagSchema;
        TSDB_WLOCK_TABLE(super);
        super->tagSchema = tdDupSchema(pCfg->tagSchema);
        TSDB_WUNLOCK_TABLE(super);
        tdFreeSchema(pOldSchema);

        superChanged = true;
      }
    }
  }

  table = tsdbCreateTableFromCfg(pCfg, false, super);
  if (table == NULL) goto _err;

  // Register to meta
  tsdbWLockRepoMeta(pRepo);
  if (newSuper) {
    if (tsdbAddTableToMeta(pRepo, super, true, false) < 0) {
      super = NULL;
      tsdbUnlockRepoMeta(pRepo);
      goto _err;
    }
  }
  if (tsdbAddTableToMeta(pRepo, table, true, false) < 0) {
    table = NULL;
    tsdbUnlockRepoMeta(pRepo);
    goto _err;
  }
  tsdbUnlockRepoMeta(pRepo);

  // Write to memtable action
  if (newSuper || superChanged) {
    // add insert new super table action
    if (tsdbInsertNewTableAction(pRepo, super) != 0) {
      goto _err;
    }
  }
  // add insert new table action
  if (tsdbInsertNewTableAction(pRepo, table) != 0) {
    goto _err;
  }

  if (tsdbCheckCommit(pRepo) < 0) return -1;

  return 0;

_err:
  if (newSuper) {
    tsdbFreeTable(super);
  }
  tsdbFreeTable(table);
  return -1;
}

int tsdbDropTable(STsdbRepo *repo, STableId tableId) {
  STsdbRepo *pRepo = (STsdbRepo *)repo;
  STsdbMeta *pMeta = pRepo->tsdbMeta;
  uint64_t   uid = tableId.uid;
  int        tid = 0;
  char *     tbname = NULL;

  STable *pTable = tsdbGetTableByUid(pMeta, uid);
  if (pTable == NULL) {
    tsdbError("vgId:%d failed to drop table since table not exists! tid:%d uid %" PRIu64, REPO_ID(pRepo), tableId.tid,
              uid);
    terrno = TSDB_CODE_TDB_INVALID_TABLE_ID;
    return -1;
  }

  tsdbDebug("vgId:%d try to drop table %s type %d", REPO_ID(pRepo), TABLE_CHAR_NAME(pTable), TABLE_TYPE(pTable));

  tid = TABLE_TID(pTable);
  tbname = strdup(TABLE_CHAR_NAME(pTable));
  if (tbname == NULL) {
    terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
    return -1;
  }

  // Write to KV store first
  if (tsdbRemoveTableFromStore(pRepo, pTable) < 0) {
    tsdbError("vgId:%d failed to drop table %s since %s", REPO_ID(pRepo), tbname, tstrerror(terrno));
    goto _err;
  }

  // Remove table from Meta
  if (tsdbRmTableFromMeta(pRepo, pTable) < 0) {
    tsdbError("vgId:%d failed to drop table %s since %s", REPO_ID(pRepo), tbname, tstrerror(terrno));
    goto _err;
  }

  tsdbDebug("vgId:%d, table %s is dropped! tid:%d, uid:%" PRId64, pRepo->config.tsdbId, tbname, tid, uid);
  free(tbname);

  if (tsdbCheckCommit(pRepo) < 0) goto _err;

  return 0;

_err:
  tfree(tbname);
  return -1;
}

H
Hongze Cheng 已提交
209
void *tsdbGetTableTagVal(const void *pTable, int32_t colId, int16_t type) {
H
Hongze Cheng 已提交
210 211
  // TODO: this function should be changed also

H
Hongze Cheng 已提交
212
  STSchema *pSchema = tsdbGetTableTagSchema((STable *)pTable);
H
Hongze Cheng 已提交
213 214 215 216 217 218
  STColumn *pCol = tdGetColOfID(pSchema, colId);
  if (pCol == NULL) {
    return NULL;  // No matched tag volumn
  }

  char *val = NULL;
H
Hongze Cheng 已提交
219 220 221 222
  if (pCol->type == TSDB_DATA_TYPE_JSON) {
    val = ((STable *)pTable)->tagVal;
  } else {
    val = tdGetKVRowValOfCol(((STable *)pTable)->tagVal, colId);
H
Hongze Cheng 已提交
223 224 225 226 227 228
    assert(type == pCol->type);
  }

  return val;
}

H
Hongze Cheng 已提交
229
char *tsdbGetTableName(void *pTable) {
H
Hongze Cheng 已提交
230 231 232 233 234
  // TODO: need to change as thread-safe

  if (pTable == NULL) {
    return NULL;
  } else {
H
Hongze Cheng 已提交
235
    return (char *)(((STable *)pTable)->name);
H
Hongze Cheng 已提交
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
  }
}

STableCfg *tsdbCreateTableCfgFromMsg(SMDCreateTableMsg *pMsg) {
  if (pMsg == NULL) return NULL;

  SSchema *pSchema = (SSchema *)pMsg->data;
  int16_t  numOfCols = htons(pMsg->numOfColumns);
  int16_t  numOfTags = htons(pMsg->numOfTags);

  STSchemaBuilder schemaBuilder = {0};

  STableCfg *pCfg = (STableCfg *)calloc(1, sizeof(STableCfg));
  if (pCfg == NULL) {
    terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
    return NULL;
  }

  if (tsdbInitTableCfg(pCfg, pMsg->tableType, htobe64(pMsg->uid), htonl(pMsg->tid)) < 0) goto _err;
  if (tdInitTSchemaBuilder(&schemaBuilder, htonl(pMsg->sversion)) < 0) {
    terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
    goto _err;
  }

  for (int i = 0; i < numOfCols; i++) {
    if (tdAddColToSchema(&schemaBuilder, pSchema[i].type, htons(pSchema[i].colId), htons(pSchema[i].bytes)) < 0) {
      terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
      goto _err;
    }
  }
  if (tsdbTableSetSchema(pCfg, tdGetSchemaFromBuilder(&schemaBuilder), false) < 0) goto _err;
  if (tsdbTableSetName(pCfg, pMsg->tableFname, true) < 0) goto _err;

  if (numOfTags > 0) {
    // Decode tag schema
    tdResetTSchemaBuilder(&schemaBuilder, htonl(pMsg->tversion));
    for (int i = numOfCols; i < numOfCols + numOfTags; i++) {
      if (tdAddColToSchema(&schemaBuilder, pSchema[i].type, htons(pSchema[i].colId), htons(pSchema[i].bytes)) < 0) {
        terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
        goto _err;
      }
    }
    if (tsdbTableSetTagSchema(pCfg, tdGetSchemaFromBuilder(&schemaBuilder), false) < 0) goto _err;
    if (tsdbTableSetSName(pCfg, pMsg->stableFname, true) < 0) goto _err;
    if (tsdbTableSetSuperUid(pCfg, htobe64(pMsg->superTableUid)) < 0) goto _err;

    int32_t tagDataLen = htonl(pMsg->tagDataLen);
    if (tagDataLen) {
      char *pTagData = pMsg->data + (numOfCols + numOfTags) * sizeof(SSchema);
      tsdbTableSetTagValue(pCfg, pTagData, true);
    }
  }

  if (pMsg->tableType == TSDB_STREAM_TABLE) {
    char *sql = pMsg->data + (numOfCols + numOfTags) * sizeof(SSchema);
    tsdbTableSetStreamSql(pCfg, sql, true);
  }

  tdDestroyTSchemaBuilder(&schemaBuilder);

  return pCfg;

_err:
  tdDestroyTSchemaBuilder(&schemaBuilder);
  tsdbClearTableCfg(pCfg);
  return NULL;
}

H
Hongze Cheng 已提交
304 305 306
static UNUSED_FUNC int32_t colIdCompar(const void *left, const void *right) {
  int16_t   colId = *(int16_t *)left;
  STColumn *p2 = (STColumn *)right;
H
Hongze Cheng 已提交
307 308 309 310 311

  if (colId == p2->colId) {
    return 0;
  }

H
Hongze Cheng 已提交
312
  return (colId < p2->colId) ? -1 : 1;
H
Hongze Cheng 已提交
313 314 315 316 317 318 319 320 321
}

int tsdbUpdateTableTagValue(STsdbRepo *repo, SUpdateTableTagValMsg *pMsg) {
  STsdbRepo *pRepo = (STsdbRepo *)repo;
  STsdbMeta *pMeta = pRepo->tsdbMeta;
  STSchema * pNewSchema = NULL;

  pMsg->uid = htobe64(pMsg->uid);
  pMsg->tid = htonl(pMsg->tid);
H
Hongze Cheng 已提交
322 323 324
  pMsg->tversion = htons(pMsg->tversion);
  pMsg->colId = htons(pMsg->colId);
  pMsg->bytes = htons(pMsg->bytes);
H
Hongze Cheng 已提交
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 365
  pMsg->tagValLen = htonl(pMsg->tagValLen);
  pMsg->numOfTags = htons(pMsg->numOfTags);
  pMsg->schemaLen = htonl(pMsg->schemaLen);
  for (int i = 0; i < pMsg->numOfTags; i++) {
    STColumn *pTCol = (STColumn *)pMsg->data + i;
    pTCol->bytes = htons(pTCol->bytes);
    pTCol->colId = htons(pTCol->colId);
  }

  STable *pTable = tsdbGetTableByUid(pMeta, pMsg->uid);
  if (pTable == NULL || TABLE_TID(pTable) != pMsg->tid) {
    tsdbError("vgId:%d failed to update table tag value since invalid table id %d uid %" PRIu64, REPO_ID(pRepo),
              pMsg->tid, pMsg->uid);
    terrno = TSDB_CODE_TDB_INVALID_TABLE_ID;
    return -1;
  }

  if (TABLE_TYPE(pTable) != TSDB_CHILD_TABLE) {
    tsdbError("vgId:%d try to update tag value of a non-child table, invalid action", REPO_ID(pRepo));
    terrno = TSDB_CODE_TDB_INVALID_ACTION;
    return -1;
  }

  if (schemaVersion(pTable->pSuper->tagSchema) > pMsg->tversion) {
    tsdbError(
        "vgId:%d failed to update tag value of table %s since version out of date, client tag version %d server tag "
        "version %d",
        REPO_ID(pRepo), TABLE_CHAR_NAME(pTable), pMsg->tversion, schemaVersion(pTable->pSuper->tagSchema));
    terrno = TSDB_CODE_TDB_TAG_VER_OUT_OF_DATE;
    return -1;
  }

  if (schemaVersion(pTable->pSuper->tagSchema) < pMsg->tversion) {  // tag schema out of data,
    tsdbDebug("vgId:%d need to update tag schema of table %s tid %d uid %" PRIu64
              " since out of date, current version %d new version %d",
              REPO_ID(pRepo), TABLE_CHAR_NAME(pTable), TABLE_TID(pTable), TABLE_UID(pTable),
              schemaVersion(pTable->pSuper->tagSchema), pMsg->tversion);

    STSchemaBuilder schemaBuilder = {0};

    STColumn *pTCol = (STColumn *)pMsg->data;
H
Hongze Cheng 已提交
366 367
    ASSERT(pMsg->schemaLen % sizeof(STColumn) == 0 &&
           pTCol[0].colId == colColId(schemaColAt(pTable->pSuper->tagSchema, 0)));
H
Hongze Cheng 已提交
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
    if (tdInitTSchemaBuilder(&schemaBuilder, pMsg->tversion) < 0) {
      tsdbDebug("vgId:%d failed to update tag schema of table %s tid %d uid %" PRIu64 " since out of memory",
                REPO_ID(pRepo), TABLE_CHAR_NAME(pTable), TABLE_TID(pTable), TABLE_UID(pTable));
      terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
      return -1;
    }
    for (int i = 0; i < (pMsg->schemaLen / sizeof(STColumn)); i++) {
      if (tdAddColToSchema(&schemaBuilder, pTCol[i].type, pTCol[i].colId, pTCol[i].bytes) < 0) {
        tdDestroyTSchemaBuilder(&schemaBuilder);
        terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
        return -1;
      }
    }
    pNewSchema = tdGetSchemaFromBuilder(&schemaBuilder);
    if (pNewSchema == NULL) {
      tdDestroyTSchemaBuilder(&schemaBuilder);
      terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
      return -1;
    }
    tdDestroyTSchemaBuilder(&schemaBuilder);
  }

  // Change in memory
H
Hongze Cheng 已提交
391
  if (pNewSchema != NULL) {  // change super table tag schema
H
Hongze Cheng 已提交
392 393 394 395 396 397 398
    TSDB_WLOCK_TABLE(pTable->pSuper);
    STSchema *pOldSchema = pTable->pSuper->tagSchema;
    pTable->pSuper->tagSchema = pNewSchema;
    tdFreeSchema(pOldSchema);
    TSDB_WUNLOCK_TABLE(pTable->pSuper);
  }

H
Hongze Cheng 已提交
399 400
  bool isChangeIndexCol =
      (pMsg->colId == colColId(schemaColAt(pTable->pSuper->tagSchema, 0))) || pMsg->type == TSDB_DATA_TYPE_JSON;
H
Hongze Cheng 已提交
401 402 403 404 405 406 407 408
  // STColumn *pCol = bsearch(&(pMsg->colId), pMsg->data, pMsg->numOfTags, sizeof(STColumn), colIdCompar);
  // ASSERT(pCol != NULL);

  if (isChangeIndexCol) {
    tsdbWLockRepoMeta(pRepo);
    tsdbRemoveTableFromIndex(pMeta, pTable);
  }
  TSDB_WLOCK_TABLE(pTable);
H
Hongze Cheng 已提交
409
  if (pMsg->type == TSDB_DATA_TYPE_JSON) {
H
Hongze Cheng 已提交
410 411
    kvRowFree(pTable->tagVal);
    pTable->tagVal = tdKVRowDup(POINTER_SHIFT(pMsg->data, pMsg->schemaLen));
H
Hongze Cheng 已提交
412
  } else {
H
Hongze Cheng 已提交
413 414 415 416 417 418 419 420 421
    tdSetKVRowDataOfCol(&(pTable->tagVal), pMsg->colId, pMsg->type, POINTER_SHIFT(pMsg->data, pMsg->schemaLen));
  }
  TSDB_WUNLOCK_TABLE(pTable);
  if (isChangeIndexCol) {
    tsdbAddTableIntoIndex(pMeta, pTable, false);
    tsdbUnlockRepoMeta(pRepo);
  }

  // Update on file
H
Hongze Cheng 已提交
422 423 424
  int   tlen1 = (pNewSchema) ? tsdbGetTableEncodeSize(TSDB_UPDATE_META, pTable->pSuper) : 0;
  int   tlen2 = tsdbGetTableEncodeSize(TSDB_UPDATE_META, pTable);
  void *buf = tsdbAllocBytes(pRepo, tlen1 + tlen2);
H
Hongze Cheng 已提交
425 426 427 428 429 430 431 432 433 434 435 436 437 438
  ASSERT(buf != NULL);
  if (pNewSchema) {
    void *pBuf = tsdbInsertTableAct(pRepo, TSDB_UPDATE_META, buf, pTable->pSuper);
    ASSERT(POINTER_DISTANCE(pBuf, buf) == tlen1);
    buf = pBuf;
  }
  tsdbInsertTableAct(pRepo, TSDB_UPDATE_META, buf, pTable);

  if (tsdbCheckCommit(pRepo) < 0) return -1;

  return 0;
}

// ------------------ INTERNAL FUNCTIONS ------------------
H
Hongze Cheng 已提交
439
static int tsdbInsertNewTableAction(STsdbRepo *pRepo, STable *pTable) {
H
Hongze Cheng 已提交
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
  int   tlen = 0;
  void *pBuf = NULL;

  tlen = tsdbGetTableEncodeSize(TSDB_UPDATE_META, pTable);
  pBuf = tsdbAllocBytes(pRepo, tlen);
  if (pBuf == NULL) {
    return -1;
  }
  void *tBuf = tsdbInsertTableAct(pRepo, TSDB_UPDATE_META, pBuf, pTable);
  ASSERT(POINTER_DISTANCE(tBuf, pBuf) == tlen);

  return 0;
}

STsdbMeta *tsdbNewMeta(STsdbCfg *pCfg) {
  STsdbMeta *pMeta = (STsdbMeta *)calloc(1, sizeof(*pMeta));
  if (pMeta == NULL) {
    terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
    goto _err;
  }

  int code = pthread_rwlock_init(&pMeta->rwLock, NULL);
  if (code != 0) {
    tsdbError("vgId:%d failed to init TSDB meta r/w lock since %s", pCfg->tsdbId, strerror(code));
    terrno = TAOS_SYSTEM_ERROR(code);
    goto _err;
  }

  pMeta->maxTables = TSDB_INIT_NTABLES + 1;
  pMeta->tables = (STable **)calloc(pMeta->maxTables, sizeof(STable *));
  if (pMeta->tables == NULL) {
    terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
    goto _err;
  }

  pMeta->superList = tdListNew(sizeof(STable *));
  if (pMeta->superList == NULL) {
    terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
    goto _err;
  }

H
Hongze Cheng 已提交
481 482
  pMeta->uidMap =
      taosHashInit((size_t)(TSDB_INIT_NTABLES * 1.1), taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT), true, false);
H
Hongze Cheng 已提交
483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602
  if (pMeta->uidMap == NULL) {
    terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
    goto _err;
  }

  return pMeta;

_err:
  tsdbFreeMeta(pMeta);
  return NULL;
}

void tsdbFreeMeta(STsdbMeta *pMeta) {
  if (pMeta) {
    taosHashCleanup(pMeta->uidMap);
    tdListFree(pMeta->superList);
    tfree(pMeta->tables);
    pthread_rwlock_destroy(&pMeta->rwLock);
    free(pMeta);
  }
}

int tsdbOpenMeta(STsdbRepo *pRepo) {
  return 0;
#if 0
  char *     fname = NULL;
  STsdbMeta *pMeta = pRepo->tsdbMeta;
  ASSERT(pMeta != NULL);

  fname = tsdbGetMetaFileName(pRepo->rootDir);
  if (fname == NULL) {
    terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
    goto _err;
  }

  // pMeta->pStore = tdOpenKVStore(fname, tsdbRestoreTable, tsdbOrgMeta, (void *)pRepo);
  // if (pMeta->pStore == NULL) {
  //   tsdbError("vgId:%d failed to open TSDB meta while open the kv store since %s", REPO_ID(pRepo), tstrerror(terrno));
  //   goto _err;
  // }

  tsdbDebug("vgId:%d open TSDB meta succeed", REPO_ID(pRepo));
  tfree(fname);
  return 0;

_err:
  tfree(fname);
  return -1;
#endif
}

int tsdbCloseMeta(STsdbRepo *pRepo) {
  STsdbMeta *pMeta = pRepo->tsdbMeta;
  SListNode *pNode = NULL;
  STable *   pTable = NULL;

  if (pMeta == NULL) return 0;
  // tdCloseKVStore(pMeta->pStore);
  for (int i = 1; i < pMeta->maxTables; i++) {
    tsdbFreeTable(pMeta->tables[i]);
  }

  while ((pNode = tdListPopHead(pMeta->superList)) != NULL) {
    tdListNodeGetData(pMeta->superList, pNode, (void *)(&pTable));
    tsdbFreeTable(pTable);
    listNodeFree(pNode);
  }

  tsdbDebug("vgId:%d TSDB meta is closed", REPO_ID(pRepo));
  return 0;
}

STable *tsdbGetTableByUid(STsdbMeta *pMeta, uint64_t uid) {
  void *ptr = taosHashGet(pMeta->uidMap, (char *)(&uid), sizeof(uid));

  if (ptr == NULL) return NULL;

  return *(STable **)ptr;
}

STSchema *tsdbGetTableSchemaByVersion(STable *pTable, int16_t _version, int8_t rowType) {
  return tsdbGetTableSchemaImpl(pTable, true, false, _version, rowType);
}

int tsdbWLockRepoMeta(STsdbRepo *pRepo) {
  int code = pthread_rwlock_wrlock(&(pRepo->tsdbMeta->rwLock));
  if (code != 0) {
    tsdbError("vgId:%d failed to write lock TSDB meta since %s", REPO_ID(pRepo), strerror(code));
    terrno = TAOS_SYSTEM_ERROR(code);
    return -1;
  }

  return 0;
}

int tsdbRLockRepoMeta(STsdbRepo *pRepo) {
  int code = pthread_rwlock_rdlock(&(pRepo->tsdbMeta->rwLock));
  if (code != 0) {
    tsdbError("vgId:%d failed to read lock TSDB meta since %s", REPO_ID(pRepo), strerror(code));
    terrno = TAOS_SYSTEM_ERROR(code);
    return -1;
  }

  return 0;
}

int tsdbUnlockRepoMeta(STsdbRepo *pRepo) {
  int code = pthread_rwlock_unlock(&(pRepo->tsdbMeta->rwLock));
  if (code != 0) {
    tsdbError("vgId:%d failed to unlock TSDB meta since %s", REPO_ID(pRepo), strerror(code));
    terrno = TAOS_SYSTEM_ERROR(code);
    return -1;
  }

  return 0;
}

void tsdbRefTable(STable *pTable) {
  int32_t ref = T_REF_INC(pTable);
  UNUSED(ref);
H
Hongze Cheng 已提交
603 604
  tsdbDebug("ref table %s uid %" PRIu64 " tid:%d, refCount:%d", TABLE_CHAR_NAME(pTable), TABLE_UID(pTable),
            TABLE_TID(pTable), ref);
H
Hongze Cheng 已提交
605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621
}

void tsdbUnRefTable(STable *pTable) {
  uint64_t uid = TABLE_UID(pTable);
  int32_t  tid = TABLE_TID(pTable);
  int32_t  ref = T_REF_DEC(pTable);

  tsdbDebug("unref table, uid:%" PRIu64 " tid:%d, refCount:%d", uid, tid, ref);

  if (ref == 0) {
    if (TABLE_TYPE(pTable) == TSDB_CHILD_TABLE) {
      tsdbUnRefTable(pTable->pSuper);
    }
    tsdbFreeTable(pTable);
  }
}

H
Hongze Cheng 已提交
622
void tsdbFreeLastColumns(STable *pTable) {
H
Hongze Cheng 已提交
623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642
  if (pTable->lastCols == NULL) {
    return;
  }

  for (int i = 0; i < pTable->maxColNum; ++i) {
    if (pTable->lastCols[i].bytes == 0) {
      continue;
    }
    tfree(pTable->lastCols[i].pData);
    pTable->lastCols[i].bytes = 0;
    pTable->lastCols[i].pData = NULL;
  }
  tfree(pTable->lastCols);
  pTable->lastCols = NULL;
  pTable->maxColNum = 0;
  pTable->lastColSVersion = -1;
  pTable->restoreColumnNum = 0;
  pTable->hasRestoreLastColumn = false;
}

H
Hongze Cheng 已提交
643
int16_t tsdbGetLastColumnsIndexByColId(STable *pTable, int16_t colId) {
H
Hongze Cheng 已提交
644 645 646 647 648 649 650 651 652 653 654 655 656
  if (pTable->lastCols == NULL) {
    return -1;
  }
  // TODO: use binary search instead
  for (int16_t i = 0; i < pTable->maxColNum; ++i) {
    if (pTable->lastCols[i].colId == colId) {
      return i;
    }
  }

  return -1;
}

H
Hongze Cheng 已提交
657
int tsdbInitColIdCacheWithSchema(STable *pTable, STSchema *pSchema) {
H
Hongze Cheng 已提交
658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684
  TSDB_WLOCK_TABLE(pTable);
  if (pTable->lastCols == NULL) {
    int16_t numOfColumn = pSchema->numOfCols;

    pTable->lastCols = (SDataCol *)malloc(numOfColumn * sizeof(SDataCol));
    if (pTable->lastCols == NULL) {
      TSDB_WUNLOCK_TABLE(pTable);
      return -1;
    }

    for (int16_t i = 0; i < numOfColumn; ++i) {
      STColumn *pCol = schemaColAt(pSchema, i);
      SDataCol *pDataCol = &(pTable->lastCols[i]);
      pDataCol->bytes = 0;
      pDataCol->pData = NULL;
      pDataCol->colId = pCol->colId;
    }

    pTable->lastColSVersion = schemaVersion(pSchema);
    pTable->maxColNum = numOfColumn;
    pTable->restoreColumnNum = 0;
    pTable->hasRestoreLastColumn = false;
  }
  TSDB_WUNLOCK_TABLE(pTable);
  return 0;
}

H
Hongze Cheng 已提交
685
STSchema *tsdbGetTableLatestSchema(STable *pTable) { return tsdbGetTableSchemaByVersion(pTable, -1, -1); }
H
Hongze Cheng 已提交
686 687 688 689 690

int tsdbUpdateLastColSchema(STable *pTable, STSchema *pNewSchema) {
  if (pTable->lastColSVersion == schemaVersion(pNewSchema)) {
    return 0;
  }
H
Hongze Cheng 已提交
691 692 693 694 695 696

  tsdbDebug("tsdbUpdateLastColSchema:%s,%d->%d", pTable->name->data, pTable->lastColSVersion,
            schemaVersion(pNewSchema));

  int16_t   numOfCols = pNewSchema->numOfCols;
  SDataCol *lastCols = (SDataCol *)malloc(numOfCols * sizeof(SDataCol));
H
Hongze Cheng 已提交
697 698 699 700 701 702 703 704
  if (lastCols == NULL) {
    return -1;
  }

  TSDB_WLOCK_TABLE(pTable);

  for (int16_t i = 0; i < numOfCols; ++i) {
    STColumn *pCol = schemaColAt(pNewSchema, i);
H
Hongze Cheng 已提交
705
    int16_t   idx = tsdbGetLastColumnsIndexByColId(pTable, pCol->colId);
H
Hongze Cheng 已提交
706

H
Hongze Cheng 已提交
707
    SDataCol *pDataCol = &(lastCols[i]);
H
Hongze Cheng 已提交
708 709
    if (idx != -1) {
      // move col data to new last column array
H
Hongze Cheng 已提交
710
      SDataCol *pOldDataCol = &(pTable->lastCols[idx]);
H
Hongze Cheng 已提交
711 712 713 714 715 716 717 718 719 720
      memcpy(pDataCol, pOldDataCol, sizeof(SDataCol));
    } else {
      // init new colid data
      pDataCol->colId = pCol->colId;
      pDataCol->bytes = 0;
      pDataCol->pData = NULL;
    }
  }

  SDataCol *oldLastCols = pTable->lastCols;
H
Hongze Cheng 已提交
721
  int16_t   oldLastColNum = pTable->maxColNum;
H
Hongze Cheng 已提交
722 723 724 725 726 727 728 729 730 731 732 733

  pTable->lastColSVersion = schemaVersion(pNewSchema);
  pTable->lastCols = lastCols;
  pTable->maxColNum = numOfCols;

  if (oldLastCols == NULL) {
    TSDB_WUNLOCK_TABLE(pTable);
    return 0;
  }

  // free old schema last column datas
  for (int16_t i = 0; i < oldLastColNum; ++i) {
H
Hongze Cheng 已提交
734
    SDataCol *pDataCol = &(oldLastCols[i]);
H
Hongze Cheng 已提交
735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767
    if (pDataCol->bytes == 0) {
      continue;
    }
    int16_t idx = tsdbGetLastColumnsIndexByColId(pTable, pDataCol->colId);
    if (idx != -1) {
      continue;
    }

    // free not exist column data
    tfree(pDataCol->pData);
  }
  TSDB_WUNLOCK_TABLE(pTable);
  tfree(oldLastCols);

  return 0;
}

void tsdbUpdateTableSchema(STsdbRepo *pRepo, STable *pTable, STSchema *pSchema, bool insertAct) {
  ASSERT(TABLE_TYPE(pTable) != TSDB_STREAM_TABLE && TABLE_TYPE(pTable) != TSDB_SUPER_TABLE);
  STsdbMeta *pMeta = pRepo->tsdbMeta;

  STable *pCTable = (TABLE_TYPE(pTable) == TSDB_CHILD_TABLE) ? pTable->pSuper : pTable;
  ASSERT(schemaVersion(pSchema) > schemaVersion(*(STSchema **)taosArrayGetLast(pCTable->schema)));

  TSDB_WLOCK_TABLE(pCTable);
  tsdbAddSchema(pCTable, pSchema);

  if (schemaNCols(pSchema) > pMeta->maxCols) pMeta->maxCols = schemaNCols(pSchema);
  if (schemaTLen(pSchema) > pMeta->maxRowBytes) pMeta->maxRowBytes = schemaTLen(pSchema);
  TSDB_WUNLOCK_TABLE(pCTable);

  if (insertAct) {
    if (tsdbInsertNewTableAction(pRepo, pCTable) != 0) {
H
Hongze Cheng 已提交
768 769
      tsdbError("vgId:%d table %s tid %d uid %" PRIu64 " tsdbInsertNewTableAction fail", REPO_ID(pRepo),
                TABLE_CHAR_NAME(pTable), TABLE_TID(pTable), TABLE_UID(pTable));
H
Hongze Cheng 已提交
770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813
    }
  }
}

int tsdbRestoreTable(STsdbRepo *pRepo, void *cont, int contLen) {
  STable *pTable = NULL;

  if (!taosCheckChecksumWhole((uint8_t *)cont, contLen)) {
    terrno = TSDB_CODE_TDB_FILE_CORRUPTED;
    return -1;
  }

  tsdbDecodeTable(cont, &pTable);

  if (tsdbAddTableToMeta(pRepo, pTable, false, false) < 0) {
    tsdbFreeTable(pTable);
    return -1;
  }

  tsdbTrace("vgId:%d table %s tid %d uid %" PRIu64 " is restored from file", REPO_ID(pRepo), TABLE_CHAR_NAME(pTable),
            TABLE_TID(pTable), TABLE_UID(pTable));
  return 0;
}

void tsdbOrgMeta(STsdbRepo *pRepo) {
  STsdbMeta *pMeta = pRepo->tsdbMeta;

  for (int i = 1; i < pMeta->maxTables; i++) {
    STable *pTable = pMeta->tables[i];
    if (pTable != NULL && pTable->type == TSDB_CHILD_TABLE) {
      tsdbAddTableIntoIndex(pMeta, pTable, true);
    }
  }
}

// ------------------ LOCAL FUNCTIONS ------------------
static char *getTagIndexKey(const void *pData) {
  STable *pTable = (STable *)pData;

  STSchema *pSchema = tsdbGetTableTagSchema(pTable);
  STColumn *pCol = schemaColAt(pSchema, DEFAULT_TAG_INDEX_COLUMN);
  void *    res = tdGetKVRowValOfCol(pTable->tagVal, pCol->colId);
  if (res == NULL) {
    // treat the column as NULL if we cannot find it
H
Hongze Cheng 已提交
814
    res = (char *)getNullValue(pCol->type);
H
Hongze Cheng 已提交
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 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867
  }
  return res;
}

static STable *tsdbNewTable() {
  STable *pTable = (STable *)calloc(1, sizeof(*pTable));
  if (pTable == NULL) {
    terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
    return NULL;
  }

  pTable->lastKey = TSKEY_INITIAL_VAL;

  pTable->lastCols = NULL;
  pTable->restoreColumnNum = 0;
  pTable->cacheLastConfigVersion = 0;
  pTable->maxColNum = 0;
  pTable->hasRestoreLastColumn = false;
  pTable->lastColSVersion = -1;
  return pTable;
}

static STable *tsdbCreateTableFromCfg(STableCfg *pCfg, bool isSuper, STable *pSTable) {
  STable *pTable = NULL;
  size_t  tsize = 0;

  pTable = tsdbNewTable();
  if (pTable == NULL) goto _err;

  if (isSuper) {
    pTable->type = TSDB_SUPER_TABLE;
    tsize = strnlen(pCfg->sname, TSDB_TABLE_NAME_LEN - 1);
    pTable->name = calloc(1, tsize + VARSTR_HEADER_SIZE + 1);
    if (pTable->name == NULL) {
      terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
      goto _err;
    }
    STR_WITH_SIZE_TO_VARSTR(pTable->name, pCfg->sname, (VarDataLenT)tsize);
    TABLE_UID(pTable) = pCfg->superUid;
    TABLE_TID(pTable) = -1;
    TABLE_SUID(pTable) = -1;
    pTable->pSuper = NULL;
    if (tsdbAddSchema(pTable, tdDupSchema(pCfg->schema)) < 0) {
      terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
      goto _err;
    }
    pTable->tagSchema = tdDupSchema(pCfg->tagSchema);
    if (pTable->tagSchema == NULL) {
      terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
      goto _err;
    }
    pTable->tagVal = NULL;
    STColumn *pCol = schemaColAt(pTable->tagSchema, DEFAULT_TAG_INDEX_COLUMN);
H
Hongze Cheng 已提交
868
    if (pCol->type == TSDB_DATA_TYPE_JSON) {
H
Hongze Cheng 已提交
869 870 871 872 873 874 875
      assert(pTable->tagSchema->numOfCols == 1);
      pTable->jsonKeyMap = taosHashInit(8, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true, HASH_ENTRY_LOCK);
      if (pTable->jsonKeyMap == NULL) {
        terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
        tsdbFreeTable(pTable);
        return NULL;
      }
H
Hongze Cheng 已提交
876 877
      // taosHashSetFreeFp(pTable->jsonKeyMap, taosArrayDestroyForHash);
    } else {
H
Hongze Cheng 已提交
878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953
      pTable->pIndex = tSkipListCreate(TSDB_SUPER_TABLE_SL_LEVEL, colType(pCol), (uint8_t)(colBytes(pCol)), NULL,
                                       SL_ALLOW_DUP_KEY, getTagIndexKey);
      if (pTable->pIndex == NULL) {
        terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
        goto _err;
      }
    }
  } else {
    pTable->type = pCfg->type;
    tsize = strnlen(pCfg->name, TSDB_TABLE_NAME_LEN - 1);
    pTable->name = calloc(1, tsize + VARSTR_HEADER_SIZE + 1);
    if (pTable->name == NULL) {
      terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
      goto _err;
    }
    STR_WITH_SIZE_TO_VARSTR(pTable->name, pCfg->name, (VarDataLenT)tsize);
    TABLE_UID(pTable) = pCfg->tableId.uid;
    TABLE_TID(pTable) = pCfg->tableId.tid;

    if (pCfg->type == TSDB_CHILD_TABLE) {
      TABLE_SUID(pTable) = pCfg->superUid;
      if (tsdbCheckTableTagVal(pCfg->tagValues, pSTable->tagSchema) < 0) {
        goto _err;
      }
      pTable->tagVal = tdKVRowDup(pCfg->tagValues);
      if (pTable->tagVal == NULL) {
        terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
        goto _err;
      }
    } else {
      TABLE_SUID(pTable) = -1;
      if (tsdbAddSchema(pTable, tdDupSchema(pCfg->schema)) < 0) {
        terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
        goto _err;
      }

      if (TABLE_TYPE(pTable) == TSDB_STREAM_TABLE) {
        pTable->sql = strdup(pCfg->sql);
        if (pTable->sql == NULL) {
          terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
          goto _err;
        }
      }
    }
  }

  T_REF_INC(pTable);

  tsdbDebug("table %s tid %d uid %" PRIu64 " is created", TABLE_CHAR_NAME(pTable), TABLE_TID(pTable),
            TABLE_UID(pTable));

  return pTable;

_err:
  tsdbFreeTable(pTable);
  return NULL;
}

static void tsdbFreeTable(STable *pTable) {
  if (pTable) {
    if (pTable->name != NULL)
      tsdbTrace("table %s tid %d uid %" PRIu64 " is freed", TABLE_CHAR_NAME(pTable), TABLE_TID(pTable),
                TABLE_UID(pTable));
    tfree(TABLE_NAME(pTable));
    if (TABLE_TYPE(pTable) != TSDB_CHILD_TABLE) {
      tsdbFreeTableSchema(pTable);

      if (TABLE_TYPE(pTable) == TSDB_SUPER_TABLE) {
        tdFreeSchema(pTable->tagSchema);
      }
    }

    kvRowFree(pTable->tagVal);

    tSkipListDestroy(pTable->pIndex);
    taosHashCleanup(pTable->jsonKeyMap);
H
Hongze Cheng 已提交
954
    taosTZfree(pTable->lastRow);
H
Hongze Cheng 已提交
955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009
    tfree(pTable->sql);

    tsdbFreeLastColumns(pTable);
    free(pTable);
  }
}

static int tsdbAddTableToMeta(STsdbRepo *pRepo, STable *pTable, bool addIdx, bool lock) {
  STsdbMeta *pMeta = pRepo->tsdbMeta;

  if (lock && tsdbWLockRepoMeta(pRepo) < 0) {
    tsdbError("vgId:%d failed to add table %s to meta since %s", REPO_ID(pRepo), TABLE_CHAR_NAME(pTable),
              tstrerror(terrno));
    return -1;
  }

  if (TABLE_TYPE(pTable) == TSDB_SUPER_TABLE) {
    if (tdListAppend(pMeta->superList, (void *)(&pTable)) < 0) {
      terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
      tsdbError("vgId:%d failed to add table %s to meta since %s", REPO_ID(pRepo), TABLE_CHAR_NAME(pTable),
                tstrerror(terrno));
      goto _err;
    }
  } else {
    if (TABLE_TID(pTable) >= pMeta->maxTables) {
      if (tsdbAdjustMetaTables(pRepo, TABLE_TID(pTable)) < 0) goto _err;
    }
    if (TABLE_TYPE(pTable) == TSDB_CHILD_TABLE && addIdx) {  // add STABLE to the index
      if (tsdbAddTableIntoIndex(pMeta, pTable, true) < 0) {
        tsdbDebug("vgId:%d failed to add table %s to meta while add table to index since %s", REPO_ID(pRepo),
                  TABLE_CHAR_NAME(pTable), tstrerror(terrno));
        goto _err;
      }
    }
    ASSERT(TABLE_TID(pTable) < pMeta->maxTables);
    pMeta->tables[TABLE_TID(pTable)] = pTable;
    pMeta->nTables++;
  }

  if (taosHashPut(pMeta->uidMap, (char *)(&pTable->tableId.uid), sizeof(pTable->tableId.uid), (void *)(&pTable),
                  sizeof(pTable)) < 0) {
    terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
    tsdbError("vgId:%d failed to add table %s to meta while put into uid map since %s", REPO_ID(pRepo),
              TABLE_CHAR_NAME(pTable), tstrerror(terrno));
    goto _err;
  }

  if (TABLE_TYPE(pTable) != TSDB_CHILD_TABLE) {
    STSchema *pSchema = tsdbGetTableSchemaImpl(pTable, false, false, -1, -1);
    if (schemaNCols(pSchema) > pMeta->maxCols) pMeta->maxCols = schemaNCols(pSchema);
    if (schemaTLen(pSchema) > pMeta->maxRowBytes) pMeta->maxRowBytes = schemaTLen(pSchema);
  }

  if (lock && tsdbUnlockRepoMeta(pRepo) < 0) return -1;
  if (TABLE_TYPE(pTable) == TSDB_STREAM_TABLE && addIdx) {
H
Hongze Cheng 已提交
1010 1011 1012
    pTable->cqhandle =
        (*pRepo->appH.cqCreateFunc)(pRepo->appH.cqH, TABLE_UID(pTable), TABLE_TID(pTable), TABLE_NAME(pTable)->data,
                                    pTable->sql, tsdbGetTableSchemaImpl(pTable, false, false, -1, -1), 1);
H
Hongze Cheng 已提交
1013 1014 1015 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 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074
  }

  tsdbDebug("vgId:%d table %s tid %d uid %" PRIu64 " is added to meta", REPO_ID(pRepo), TABLE_CHAR_NAME(pTable),
            TABLE_TID(pTable), TABLE_UID(pTable));
  return 0;

_err:
  tsdbRemoveTableFromMeta(pRepo, pTable, false, false);
  if (lock) tsdbUnlockRepoMeta(pRepo);
  return -1;
}

static void tsdbRemoveTableFromMeta(STsdbRepo *pRepo, STable *pTable, bool rmFromIdx, bool lock) {
  STsdbMeta *pMeta = pRepo->tsdbMeta;
  SListIter  lIter = {0};
  SListNode *pNode = NULL;
  STable *   tTable = NULL;

  STSchema *pSchema = tsdbGetTableSchemaImpl(pTable, false, false, -1, -1);
  int       maxCols = schemaNCols(pSchema);
  int       maxRowBytes = schemaTLen(pSchema);

  if (lock) tsdbWLockRepoMeta(pRepo);

  if (TABLE_TYPE(pTable) == TSDB_SUPER_TABLE) {
    tdListInitIter(pMeta->superList, &lIter, TD_LIST_BACKWARD);

    while ((pNode = tdListNext(&lIter)) != NULL) {
      tdListNodeGetData(pMeta->superList, pNode, (void *)(&tTable));
      if (pTable == tTable) {
        tdListPopNode(pMeta->superList, pNode);
        free(pNode);
        break;
      }
    }
  } else {
    pMeta->tables[pTable->tableId.tid] = NULL;
    if (TABLE_TYPE(pTable) == TSDB_CHILD_TABLE && rmFromIdx) {
      tsdbRemoveTableFromIndex(pMeta, pTable);
    }

    pMeta->nTables--;
  }

  taosHashRemove(pMeta->uidMap, (char *)(&(TABLE_UID(pTable))), sizeof(TABLE_UID(pTable)));

  if (maxCols == pMeta->maxCols || maxRowBytes == pMeta->maxRowBytes) {
    maxCols = 0;
    maxRowBytes = 0;
    for (int i = 0; i < pMeta->maxTables; i++) {
      STable *_pTable = pMeta->tables[i];
      if (_pTable != NULL) {
        pSchema = tsdbGetTableSchemaImpl(_pTable, false, false, -1, -1);
        maxCols = MAX(maxCols, schemaNCols(pSchema));
        maxRowBytes = MAX(maxRowBytes, schemaTLen(pSchema));
      }
    }
  }
  pMeta->maxCols = maxCols;
  pMeta->maxRowBytes = maxRowBytes;

  if (lock) tsdbUnlockRepoMeta(pRepo);
H
Hongze Cheng 已提交
1075 1076
  tsdbDebug("vgId:%d table %s uid %" PRIu64 " is removed from meta", REPO_ID(pRepo), TABLE_CHAR_NAME(pTable),
            TABLE_UID(pTable));
H
Hongze Cheng 已提交
1077 1078 1079
  tsdbUnRefTable(pTable);
}

H
Hongze Cheng 已提交
1080
void *tsdbGetJsonTagValue(STable *pTable, char *key, int32_t keyLen, int16_t *retColId) {
H
Hongze Cheng 已提交
1081
  assert(TABLE_TYPE(pTable) == TSDB_CHILD_TABLE);
H
Hongze Cheng 已提交
1082 1083 1084 1085 1086
  STable * superTable = pTable->pSuper;
  SArray **data = (SArray **)taosHashGet(superTable->jsonKeyMap, key, keyLen);
  if (data == NULL) return NULL;
  JsonMapValue  jmvalue = {pTable, 0};
  JsonMapValue *p = taosArraySearch(*data, &jmvalue, tsdbCompareJsonMapValue, TD_EQ);
H
Hongze Cheng 已提交
1087 1088
  if (p == NULL) return NULL;
  int16_t colId = p->colId + 1;
H
Hongze Cheng 已提交
1089
  if (retColId) *retColId = p->colId;
H
Hongze Cheng 已提交
1090 1091 1092
  return tdGetKVRowValOfCol(pTable->tagVal, colId);
}

H
Hongze Cheng 已提交
1093 1094 1095
int tsdbCompareJsonMapValue(const void *a, const void *b) {
  const JsonMapValue *x = (const JsonMapValue *)a;
  const JsonMapValue *y = (const JsonMapValue *)b;
H
Hongze Cheng 已提交
1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108
  if (x->table > y->table) return 1;
  if (x->table < y->table) return -1;
  return 0;
}

static int tsdbAddTableIntoIndex(STsdbMeta *pMeta, STable *pTable, bool refSuper) {
  ASSERT(pTable->type == TSDB_CHILD_TABLE && pTable != NULL);
  STable *pSTable = tsdbGetTableByUid(pMeta, TABLE_SUID(pTable));
  ASSERT(pSTable != NULL);

  pTable->pSuper = pSTable;
  if (refSuper) T_REF_INC(pSTable);

H
Hongze Cheng 已提交
1109
  if (pSTable->tagSchema->columns[0].type == TSDB_DATA_TYPE_JSON) {
H
Hongze Cheng 已提交
1110 1111
    ASSERT(pSTable->tagSchema->numOfCols == 1);
    int16_t nCols = kvRowNCols(pTable->tagVal);
H
Hongze Cheng 已提交
1112
    ASSERT(nCols % 2 == 1);
H
Hongze Cheng 已提交
1113 1114 1115 1116
    // check first
    for (int j = 0; j < nCols; ++j) {
      if (j != 0 && j % 2 == 0) continue;  // jump value
      SColIdx *pColIdx = kvRowColIdxAt(pTable->tagVal, j);
H
Hongze Cheng 已提交
1117
      void *   val = (kvRowColVal(pTable->tagVal, pColIdx));
H
Hongze Cheng 已提交
1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130
      if (j == 0) {  // json value is the first
        int8_t jsonPlaceHolder = *(int8_t *)val;
        ASSERT(jsonPlaceHolder == TSDB_DATA_JSON_PLACEHOLDER);
        continue;
      }
      if (j == 1) {
        uint32_t jsonNULL = *(uint32_t *)(varDataVal(val));
        ASSERT(jsonNULL == TSDB_DATA_JSON_NULL);
      }

      // then insert
      char keyMd5[TSDB_MAX_JSON_KEY_MD5_LEN] = {0};
      jsonKeyMd5(varDataVal(val), varDataLen(val), keyMd5);
H
Hongze Cheng 已提交
1131
      SArray * tablistNew = NULL;
H
Hongze Cheng 已提交
1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149
      SArray **tablist = (SArray **)taosHashGet(pSTable->jsonKeyMap, keyMd5, TSDB_MAX_JSON_KEY_MD5_LEN);
      if (tablist == NULL) {
        tablistNew = taosArrayInit(8, sizeof(JsonMapValue));
        if (tablistNew == NULL) {
          terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
          tsdbError("out of memory when alloc json tag array");
          return -1;
        }
        if (taosHashPut(pSTable->jsonKeyMap, keyMd5, TSDB_MAX_JSON_KEY_MD5_LEN, &tablistNew, sizeof(void *)) < 0) {
          terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
          tsdbError("out of memory when put json tag array");
          return -1;
        }
      } else {
        tablistNew = *tablist;
      }

      JsonMapValue jmvalue = {pTable, pColIdx->colId};
H
Hongze Cheng 已提交
1150
      void *       p = taosArraySearch(tablistNew, &jmvalue, tsdbCompareJsonMapValue, TD_EQ);
H
Hongze Cheng 已提交
1151 1152
      if (p == NULL) {
        p = taosArraySearch(tablistNew, &jmvalue, tsdbCompareJsonMapValue, TD_GE);
H
Hongze Cheng 已提交
1153
        if (p == NULL) {
H
Hongze Cheng 已提交
1154
          taosArrayPush(tablistNew, &jmvalue);
H
Hongze Cheng 已提交
1155
        } else {
H
Hongze Cheng 已提交
1156 1157
          taosArrayInsert(tablistNew, TARRAY_ELEM_IDX(tablistNew, p), &jmvalue);
        }
H
Hongze Cheng 已提交
1158
      } else {
H
Hongze Cheng 已提交
1159 1160 1161
        tsdbError("insert dumplicate");
      }
    }
H
Hongze Cheng 已提交
1162
  } else {
H
Hongze Cheng 已提交
1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174
    tSkipListPut(pSTable->pIndex, (void *)pTable);
  }

  return 0;
}

static int tsdbRemoveTableFromIndex(STsdbMeta *pMeta, STable *pTable) {
  ASSERT(pTable->type == TSDB_CHILD_TABLE && pTable != NULL);

  STable *pSTable = pTable->pSuper;
  ASSERT(pSTable != NULL);

H
Hongze Cheng 已提交
1175
  if (pSTable->tagSchema->columns[0].type == TSDB_DATA_TYPE_JSON) {
H
Hongze Cheng 已提交
1176 1177
    ASSERT(pSTable->tagSchema->numOfCols == 1);
    int16_t nCols = kvRowNCols(pTable->tagVal);
H
Hongze Cheng 已提交
1178
    ASSERT(nCols % 2 == 1);
H
Hongze Cheng 已提交
1179
    for (int j = 0; j < nCols; ++j) {
H
Hongze Cheng 已提交
1180 1181 1182 1183 1184
      if (j != 0 && j % 2 == 0) continue;  // jump value
      SColIdx *pColIdx = kvRowColIdxAt(pTable->tagVal, j);
      void *   val = (kvRowColVal(pTable->tagVal, pColIdx));
      if (j == 0) {  // json value is the first
        int8_t jsonPlaceHolder = *(int8_t *)val;
H
Hongze Cheng 已提交
1185 1186 1187
        ASSERT(jsonPlaceHolder == TSDB_DATA_JSON_PLACEHOLDER);
        continue;
      }
H
Hongze Cheng 已提交
1188 1189
      if (j == 1) {
        uint32_t jsonNULL = *(uint32_t *)(varDataVal(val));
H
Hongze Cheng 已提交
1190 1191 1192 1193 1194
        ASSERT(jsonNULL == TSDB_DATA_JSON_NULL);
      }

      char keyMd5[TSDB_MAX_JSON_KEY_MD5_LEN] = {0};
      jsonKeyMd5(varDataVal(val), varDataLen(val), keyMd5);
H
Hongze Cheng 已提交
1195 1196
      SArray **tablist = (SArray **)taosHashGet(pSTable->jsonKeyMap, keyMd5, TSDB_MAX_JSON_KEY_MD5_LEN);
      if (tablist == NULL) {
H
Hongze Cheng 已提交
1197 1198 1199 1200 1201
        tsdbError("json tag no key error,%d", j);
        continue;
      }

      JsonMapValue jmvalue = {pTable, pColIdx->colId};
H
Hongze Cheng 已提交
1202
      void *       p = taosArraySearch(*tablist, &jmvalue, tsdbCompareJsonMapValue, TD_EQ);
H
Hongze Cheng 已提交
1203 1204 1205 1206 1207 1208
      if (p == NULL) {
        tsdbError("json tag no tableid error,%d", j);
        continue;
      }
      taosArrayRemove(*tablist, TARRAY_ELEM_IDX(*tablist, p));
    }
H
Hongze Cheng 已提交
1209
  } else {
H
Hongze Cheng 已提交
1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224
    char *  key = getTagIndexKey(pTable);
    SArray *res = tSkipListGet(pSTable->pIndex, key);

    size_t size = taosArrayGetSize(res);
    ASSERT(size > 0);

    for (int32_t i = 0; i < size; ++i) {
      SSkipListNode *pNode = taosArrayGetP(res, i);

      // STableIndexElem* pElem = (STableIndexElem*) SL_GET_NODE_DATA(pNode);
      if ((STable *)SL_GET_NODE_DATA(pNode) == pTable) {  // this is the exact what we need
        tSkipListRemoveNode(pSTable->pIndex, pNode);
      }
    }

H
Hongze Cheng 已提交
1225
    taosArrayDestroy(res);
H
Hongze Cheng 已提交
1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409
  }
  return 0;
}

static int tsdbInitTableCfg(STableCfg *config, ETableType type, uint64_t uid, int32_t tid) {
  if (type != TSDB_CHILD_TABLE && type != TSDB_NORMAL_TABLE && type != TSDB_STREAM_TABLE) {
    terrno = TSDB_CODE_TDB_INVALID_TABLE_TYPE;
    return -1;
  }

  memset((void *)config, 0, sizeof(*config));

  config->type = type;
  config->superUid = TSDB_INVALID_SUPER_TABLE_ID;
  config->tableId.uid = uid;
  config->tableId.tid = tid;
  return 0;
}

static int tsdbTableSetSchema(STableCfg *config, STSchema *pSchema, bool dup) {
  if (dup) {
    config->schema = tdDupSchema(pSchema);
    if (config->schema == NULL) {
      terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
      return -1;
    }
  } else {
    config->schema = pSchema;
  }
  return 0;
}

static int tsdbTableSetName(STableCfg *config, char *name, bool dup) {
  if (dup) {
    config->name = strdup(name);
    if (config->name == NULL) {
      terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
      return -1;
    }
  } else {
    config->name = name;
  }

  return 0;
}

static int tsdbTableSetTagSchema(STableCfg *config, STSchema *pSchema, bool dup) {
  if (config->type != TSDB_CHILD_TABLE) {
    terrno = TSDB_CODE_TDB_INVALID_CREATE_TB_MSG;
    return -1;
  }

  if (dup) {
    config->tagSchema = tdDupSchema(pSchema);
    if (config->tagSchema == NULL) {
      terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
      return -1;
    }
  } else {
    config->tagSchema = pSchema;
  }
  return 0;
}

static int tsdbTableSetSName(STableCfg *config, char *sname, bool dup) {
  if (config->type != TSDB_CHILD_TABLE) {
    terrno = TSDB_CODE_TDB_INVALID_CREATE_TB_MSG;
    return -1;
  }

  if (dup) {
    config->sname = strdup(sname);
    if (config->sname == NULL) {
      terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
      return -1;
    }
  } else {
    config->sname = sname;
  }
  return 0;
}

static int tsdbTableSetSuperUid(STableCfg *config, uint64_t uid) {
  if (config->type != TSDB_CHILD_TABLE || uid == TSDB_INVALID_SUPER_TABLE_ID) {
    terrno = TSDB_CODE_TDB_INVALID_CREATE_TB_MSG;
    return -1;
  }

  config->superUid = uid;
  return 0;
}

static int tsdbTableSetTagValue(STableCfg *config, SKVRow row, bool dup) {
  if (config->type != TSDB_CHILD_TABLE) {
    terrno = TSDB_CODE_TDB_INVALID_CREATE_TB_MSG;
    return -1;
  }

  if (dup) {
    config->tagValues = tdKVRowDup(row);
    if (config->tagValues == NULL) {
      terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
      return -1;
    }
  } else {
    config->tagValues = row;
  }

  return 0;
}

static int tsdbTableSetStreamSql(STableCfg *config, char *sql, bool dup) {
  if (config->type != TSDB_STREAM_TABLE) {
    terrno = TSDB_CODE_TDB_INVALID_CREATE_TB_MSG;
    return -1;
  }

  if (dup) {
    config->sql = strdup(sql);
    if (config->sql == NULL) {
      terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
      return -1;
    }
  } else {
    config->sql = sql;
  }

  return 0;
}

void tsdbClearTableCfg(STableCfg *config) {
  if (config) {
    if (config->schema) tdFreeSchema(config->schema);
    if (config->tagSchema) tdFreeSchema(config->tagSchema);
    if (config->tagValues) kvRowFree(config->tagValues);
    tfree(config->name);
    tfree(config->sname);
    tfree(config->sql);
    free(config);
  }
}

static int tsdbEncodeTableName(void **buf, tstr *name) {
  int tlen = 0;

  tlen += taosEncodeFixedI16(buf, name->len);
  if (buf != NULL) {
    memcpy(*buf, name->data, name->len);
    *buf = POINTER_SHIFT(*buf, name->len);
  }
  tlen += name->len;

  return tlen;
}

static void *tsdbDecodeTableName(void *buf, tstr **name) {
  VarDataLenT len = 0;

  buf = taosDecodeFixedI16(buf, &len);
  *name = calloc(1, sizeof(tstr) + len + 1);
  if (*name == NULL) {
    terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
    return NULL;
  }
  (*name)->len = len;
  memcpy((*name)->data, buf, len);

  buf = POINTER_SHIFT(buf, len);
  return buf;
}

static int tsdbEncodeTable(void **buf, STable *pTable) {
  ASSERT(pTable != NULL);
  int tlen = 0;

  tlen += taosEncodeFixedU8(buf, pTable->type);
  tlen += tsdbEncodeTableName(buf, pTable->name);
  tlen += taosEncodeFixedU64(buf, TABLE_UID(pTable));
  tlen += taosEncodeFixedI32(buf, TABLE_TID(pTable));

  if (TABLE_TYPE(pTable) == TSDB_CHILD_TABLE) {
    tlen += taosEncodeFixedU64(buf, TABLE_SUID(pTable));
    tlen += tdEncodeKVRow(buf, pTable->tagVal);
  } else {
H
Hongze Cheng 已提交
1410 1411
    uint32_t arraySize = (uint32_t)taosArrayGetSize(pTable->schema);
    if (arraySize > UINT8_MAX) {
H
Hongze Cheng 已提交
1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451
      tlen += taosEncodeFixedU8(buf, 0);
      tlen += taosEncodeFixedU32(buf, arraySize);
    } else {
      tlen += taosEncodeFixedU8(buf, (uint8_t)arraySize);
    }
    for (uint32_t i = 0; i < arraySize; i++) {
      STSchema *pSchema = taosArrayGetP(pTable->schema, i);
      tlen += tdEncodeSchema(buf, pSchema);
    }

    if (TABLE_TYPE(pTable) == TSDB_SUPER_TABLE) {
      tlen += tdEncodeSchema(buf, pTable->tagSchema);
    }

    if (TABLE_TYPE(pTable) == TSDB_STREAM_TABLE) {
      tlen += taosEncodeString(buf, pTable->sql);
    }
  }

  return tlen;
}

static void *tsdbDecodeTable(void *buf, STable **pRTable) {
  STable *pTable = tsdbNewTable();
  if (pTable == NULL) return NULL;

  uint8_t type = 0;

  buf = taosDecodeFixedU8(buf, &type);
  pTable->type = type;
  buf = tsdbDecodeTableName(buf, &(pTable->name));
  buf = taosDecodeFixedU64(buf, &TABLE_UID(pTable));
  buf = taosDecodeFixedI32(buf, &TABLE_TID(pTable));

  if (TABLE_TYPE(pTable) == TSDB_CHILD_TABLE) {
    buf = taosDecodeFixedU64(buf, &TABLE_SUID(pTable));
    buf = tdDecodeKVRow(buf, &(pTable->tagVal));
  } else {
    uint32_t nSchemas = 0;
    buf = taosDecodeFixedU8(buf, (uint8_t *)&nSchemas);
H
Hongze Cheng 已提交
1452
    if (nSchemas == 0) {
H
Hongze Cheng 已提交
1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463
      buf = taosDecodeFixedU32(buf, &nSchemas);
    }
    for (int i = 0; i < nSchemas; i++) {
      STSchema *pSchema;
      buf = tdDecodeSchema(buf, &pSchema);
      tsdbAddSchema(pTable, pSchema);
    }

    if (TABLE_TYPE(pTable) == TSDB_SUPER_TABLE) {
      buf = tdDecodeSchema(buf, &(pTable->tagSchema));
      STColumn *pCol = schemaColAt(pTable->tagSchema, DEFAULT_TAG_INDEX_COLUMN);
H
Hongze Cheng 已提交
1464
      if (pCol->type == TSDB_DATA_TYPE_JSON) {
H
Hongze Cheng 已提交
1465 1466 1467 1468 1469 1470 1471
        assert(pTable->tagSchema->numOfCols == 1);
        pTable->jsonKeyMap = taosHashInit(8, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true, HASH_ENTRY_LOCK);
        if (pTable->jsonKeyMap == NULL) {
          terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
          tsdbFreeTable(pTable);
          return NULL;
        }
H
Hongze Cheng 已提交
1472 1473
        // taosHashSetFreeFp(pTable->jsonKeyMap, taosArrayDestroyForHash);
      } else {
H
Hongze Cheng 已提交
1474
        pTable->pIndex = tSkipListCreate(TSDB_SUPER_TABLE_SL_LEVEL, colType(pCol), (uint8_t)(colBytes(pCol)), NULL,
H
Hongze Cheng 已提交
1475
                                         SL_ALLOW_DUP_KEY, getTagIndexKey);
H
Hongze Cheng 已提交
1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495
        if (pTable->pIndex == NULL) {
          terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
          tsdbFreeTable(pTable);
          return NULL;
        }
      }
    }

    if (TABLE_TYPE(pTable) == TSDB_STREAM_TABLE) {
      buf = taosDecodeString(buf, &(pTable->sql));
    }
  }

  T_REF_INC(pTable);

  *pRTable = pTable;

  return buf;
}

H
Hongze Cheng 已提交
1496
static SArray *getJsonTagTableList(STable *pTable) {
H
Hongze Cheng 已提交
1497
  uint32_t key = TSDB_DATA_JSON_NULL;
H
Hongze Cheng 已提交
1498
  char     keyMd5[TSDB_MAX_JSON_KEY_MD5_LEN] = {0};
H
Hongze Cheng 已提交
1499
  jsonKeyMd5(&key, INT_BYTES, keyMd5);
H
Hongze Cheng 已提交
1500
  SArray **tablist = (SArray **)taosHashGet(pTable->jsonKeyMap, keyMd5, TSDB_MAX_JSON_KEY_MD5_LEN);
H
Hongze Cheng 已提交
1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511

  return *tablist;
}

static int tsdbGetTableEncodeSize(int8_t act, STable *pTable) {
  int tlen = 0;
  if (act == TSDB_UPDATE_META) {
    tlen = sizeof(SListNode) + sizeof(SActObj) + sizeof(SActCont) + tsdbEncodeTable(NULL, pTable) + sizeof(TSCKSUM);
  } else {
    if (TABLE_TYPE(pTable) == TSDB_SUPER_TABLE) {
      size_t tableSize = 0;
H
Hongze Cheng 已提交
1512 1513
      if (pTable->tagSchema->columns[0].type == TSDB_DATA_TYPE_JSON) {
        SArray *tablist = getJsonTagTableList(pTable);
H
Hongze Cheng 已提交
1514
        tableSize = taosArrayGetSize(tablist);
H
Hongze Cheng 已提交
1515
      } else {
H
Hongze Cheng 已提交
1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532
        tableSize = SL_SIZE(pTable->pIndex);
      }
      tlen = (int)((sizeof(SListNode) + sizeof(SActObj)) * (tableSize + 1));
    } else {
      tlen = sizeof(SListNode) + sizeof(SActObj);
    }
  }

  return tlen;
}

static void *tsdbInsertTableAct(STsdbRepo *pRepo, int8_t act, void *buf, STable *pTable) {
  SListNode *pNode = (SListNode *)buf;
  SActObj *  pAct = (SActObj *)(pNode->data);
  SActCont * pCont = (SActCont *)POINTER_SHIFT(pAct, sizeof(*pAct));
  void *     pBuf = (void *)pCont;

H
Hongze Cheng 已提交
1533
  TD_DLIST_NODE_PREV(pNode) = TD_DLIST_NODE_NEXT(pNode) = NULL;
H
Hongze Cheng 已提交
1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557
  pAct->act = act;
  pAct->uid = TABLE_UID(pTable);

  if (act == TSDB_UPDATE_META) {
    pBuf = (void *)(pCont->cont);
    pCont->len = tsdbEncodeTable(&pBuf, pTable) + sizeof(TSCKSUM);
    taosCalcChecksumAppend(0, (uint8_t *)pCont->cont, pCont->len);
    pBuf = POINTER_SHIFT(pBuf, sizeof(TSCKSUM));
  }

  tdListAppendNode(pRepo->mem->actList, pNode);

  return pBuf;
}

static int tsdbRemoveTableFromStore(STsdbRepo *pRepo, STable *pTable) {
  int   tlen = tsdbGetTableEncodeSize(TSDB_DROP_META, pTable);
  void *buf = tsdbAllocBytes(pRepo, tlen);
  if (buf == NULL) {
    return -1;
  }

  void *pBuf = buf;
  if (TABLE_TYPE(pTable) == TSDB_SUPER_TABLE) {
H
Hongze Cheng 已提交
1558 1559
    if (pTable->tagSchema->columns[0].type == TSDB_DATA_TYPE_JSON) {
      SArray *tablist = getJsonTagTableList(pTable);
H
Hongze Cheng 已提交
1560
      for (int i = 0; i < taosArrayGetSize(tablist); ++i) {
H
Hongze Cheng 已提交
1561
        JsonMapValue *p = taosArrayGet(tablist, i);
H
Hongze Cheng 已提交
1562 1563 1564
        ASSERT(TABLE_TYPE((STable *)(p->table)) == TSDB_CHILD_TABLE);
        pBuf = tsdbInsertTableAct(pRepo, TSDB_DROP_META, pBuf, p->table);
      }
H
Hongze Cheng 已提交
1565
    } else {
H
Hongze Cheng 已提交
1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590
      SSkipListIterator *pIter = tSkipListCreateIter(pTable->pIndex);
      if (pIter == NULL) {
        terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
        return -1;
      }

      while (tSkipListIterNext(pIter)) {
        STable *tTable = (STable *)SL_GET_NODE_DATA(tSkipListIterGet(pIter));
        ASSERT(TABLE_TYPE(tTable) == TSDB_CHILD_TABLE);
        pBuf = tsdbInsertTableAct(pRepo, TSDB_DROP_META, pBuf, tTable);
      }

      tSkipListDestroyIter(pIter);
    }
  }
  pBuf = tsdbInsertTableAct(pRepo, TSDB_DROP_META, pBuf, pTable);

  ASSERT(POINTER_DISTANCE(pBuf, buf) == tlen);

  return 0;
}

static int tsdbRmTableFromMeta(STsdbRepo *pRepo, STable *pTable) {
  if (TABLE_TYPE(pTable) == TSDB_SUPER_TABLE) {
    tsdbWLockRepoMeta(pRepo);
H
Hongze Cheng 已提交
1591 1592
    if (pTable->tagSchema->columns[0].type == TSDB_DATA_TYPE_JSON) {
      SArray *tablist = getJsonTagTableList(pTable);
H
Hongze Cheng 已提交
1593
      for (int i = 0; i < taosArrayGetSize(tablist); ++i) {
H
Hongze Cheng 已提交
1594
        JsonMapValue *p = taosArrayGet(tablist, i);
H
Hongze Cheng 已提交
1595 1596
        tsdbRemoveTableFromMeta(pRepo, p->table, false, false);
      }
H
Hongze Cheng 已提交
1597
    } else {
H
Hongze Cheng 已提交
1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619
      SSkipListIterator *pIter = tSkipListCreateIter(pTable->pIndex);
      if (pIter == NULL) {
        terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
        return -1;
      }
      while (tSkipListIterNext(pIter)) {
        STable *tTable = (STable *)SL_GET_NODE_DATA(tSkipListIterGet(pIter));
        tsdbRemoveTableFromMeta(pRepo, tTable, false, false);
      }
      tSkipListDestroyIter(pIter);
    }
    tsdbRemoveTableFromMeta(pRepo, pTable, false, false);
    tsdbUnlockRepoMeta(pRepo);
  } else {
    if ((TABLE_TYPE(pTable) == TSDB_STREAM_TABLE) && pTable->cqhandle) pRepo->appH.cqDropFunc(pTable->cqhandle);
    tsdbRemoveTableFromMeta(pRepo, pTable, true, true);
  }

  return 0;
}

static int tsdbAdjustMetaTables(STsdbRepo *pRepo, int tid) {
H
Hongze Cheng 已提交
1620
#if 0
H
Hongze Cheng 已提交
1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639
  STsdbMeta *pMeta = pRepo->tsdbMeta;
  ASSERT(tid >= pMeta->maxTables);

  int maxTables = tsdbGetNextMaxTables(tid);

  STable **tables = (STable **)calloc(maxTables, sizeof(STable *));
  if (tables == NULL) {
    terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
    return -1;
  }

  memcpy((void *)tables, (void *)pMeta->tables, sizeof(STable *) * pMeta->maxTables);
  pMeta->maxTables = maxTables;

  STable **tTables = pMeta->tables;
  pMeta->tables = tables;
  tfree(tTables);
  tsdbDebug("vgId:%d tsdb meta maxTables is adjusted as %d", REPO_ID(pRepo), maxTables);

H
Hongze Cheng 已提交
1640
#endif
H
Hongze Cheng 已提交
1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691
  return 0;
}

static int tsdbCheckTableTagVal(SKVRow *pKVRow, STSchema *pSchema) {
  for (size_t i = 0; i < kvRowNCols(pKVRow); i++) {
    SColIdx * pColIdx = kvRowColIdxAt(pKVRow, i);
    STColumn *pCol = tdGetColOfID(pSchema, pColIdx->colId);

    if ((pCol == NULL) || (!IS_VAR_DATA_TYPE(pCol->type))) continue;

    void *pValue = tdGetKVRowValOfCol(pKVRow, pCol->colId);
    if (varDataTLen(pValue) > pCol->bytes) {
      terrno = TSDB_CODE_TDB_IVLD_TAG_VAL;
      return -1;
    }
  }

  return 0;
}

static int tsdbAddSchema(STable *pTable, STSchema *pSchema) {
  ASSERT(TABLE_TYPE(pTable) != TSDB_CHILD_TABLE);

  if (pTable->schema == NULL) {
    pTable->schema = taosArrayInit(TSDB_MAX_TABLE_SCHEMAS, sizeof(SSchema *));
    if (pTable->schema == NULL) {
      terrno = TAOS_SYSTEM_ERROR(errno);
      return -1;
    }
  }

  ASSERT(taosArrayGetSize(pTable->schema) == 0 ||
         schemaVersion(pSchema) > schemaVersion(*(STSchema **)taosArrayGetLast(pTable->schema)));

  if (taosArrayPush(pTable->schema, &pSchema) == NULL) {
    terrno = TAOS_SYSTEM_ERROR(errno);
    return -1;
  }

  return 0;
}

static void tsdbFreeTableSchema(STable *pTable) {
  ASSERT(pTable != NULL);

  if (pTable->schema) {
    for (size_t i = 0; i < taosArrayGetSize(pTable->schema); i++) {
      STSchema *pSchema = taosArrayGetP(pTable->schema, i);
      tdFreeSchema(pSchema);
    }

H
Hongze Cheng 已提交
1692
    taosArrayDestroy(pTable->schema);
H
Hongze Cheng 已提交
1693 1694
  }
}
H
Hongze Cheng 已提交
1695
#endif