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

H
Hongze Cheng 已提交
16
#include "vnodeInt.h"
H
Hongze Cheng 已提交
17

S
Shengliang Guan 已提交
18
static int      tsdbScanAndConvertSubmitMsg(STsdb *pTsdb, SSubmitReq *pMsg);
H
Hongze Cheng 已提交
19 20 21 22 23 24
static int      tsdbMemTableInsertTbData(STsdb *pRepo, SSubmitBlk *pBlock, int32_t *pAffectedRows);
static STbData *tsdbNewTbData(tb_uid_t uid);
static void     tsdbFreeTbData(STbData *pTbData);
static char *   tsdbGetTsTupleKey(const void *data);
static int      tsdbTbDataComp(const void *arg1, const void *arg2);
static char *   tsdbTbDataGetUid(const void *arg);
C
Cary Xu 已提交
25
static int      tsdbAppendTableRowToCols(STable *pTable, SDataCols *pCols, STSchema **ppSchema, STSRow *row);
H
Hongze Cheng 已提交
26

H
Hongze Cheng 已提交
27
STsdbMemTable *tsdbNewMemTable(STsdb *pTsdb) {
wafwerar's avatar
wafwerar 已提交
28
  STsdbMemTable *pMemTable = (STsdbMemTable *)taosMemoryCalloc(1, sizeof(*pMemTable));
H
Hongze Cheng 已提交
29
  if (pMemTable == NULL) {
H
Hongze Cheng 已提交
30
    terrno = TSDB_CODE_OUT_OF_MEMORY;
H
Hongze Cheng 已提交
31 32 33 34 35 36
    return NULL;
  }

  T_REF_INIT_VAL(pMemTable, 1);
  taosInitRWLatch(&(pMemTable->latch));
  pMemTable->keyMax = TSKEY_MIN;
H
Hongze Cheng 已提交
37
  pMemTable->keyMin = TSKEY_MAX;
H
Hongze Cheng 已提交
38
  pMemTable->nRow = 0;
H
Hongze Cheng 已提交
39 40
  pMemTable->pMA = pTsdb->pmaf->create(pTsdb->pmaf);
  if (pMemTable->pMA == NULL) {
wafwerar's avatar
wafwerar 已提交
41
    taosMemoryFree(pMemTable);
H
Hongze Cheng 已提交
42 43 44 45
    return NULL;
  }

  // Initialize the container
H
Hongze Cheng 已提交
46 47 48
  pMemTable->pSlIdx =
      tSkipListCreate(5, TSDB_DATA_TYPE_BIGINT, sizeof(tb_uid_t), tsdbTbDataComp, SL_DISCARD_DUP_KEY, tsdbTbDataGetUid);
  if (pMemTable->pSlIdx == NULL) {
H
Hongze Cheng 已提交
49
    pTsdb->pmaf->destroy(pTsdb->pmaf, pMemTable->pMA);
wafwerar's avatar
wafwerar 已提交
50
    taosMemoryFree(pMemTable);
H
Hongze Cheng 已提交
51 52 53 54 55 56
    return NULL;
  }

  pMemTable->pHashIdx = taosHashInit(1024, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT), false, HASH_NO_LOCK);
  if (pMemTable->pHashIdx == NULL) {
    pTsdb->pmaf->destroy(pTsdb->pmaf, pMemTable->pMA);
H
Hongze Cheng 已提交
57
    tSkipListDestroy(pMemTable->pSlIdx);
wafwerar's avatar
wafwerar 已提交
58
    taosMemoryFree(pMemTable);
H
Hongze Cheng 已提交
59 60
    return NULL;
  }
H
Hongze Cheng 已提交
61 62 63 64

  return pMemTable;
}

H
Hongze Cheng 已提交
65 66 67
void tsdbFreeMemTable(STsdb *pTsdb, STsdbMemTable *pMemTable) {
  if (pMemTable) {
    taosHashCleanup(pMemTable->pHashIdx);
H
Hongze Cheng 已提交
68
    tSkipListDestroy(pMemTable->pSlIdx);
H
Hongze Cheng 已提交
69 70 71
    if (pMemTable->pMA) {
      pTsdb->pmaf->destroy(pTsdb->pmaf, pMemTable->pMA);
    }
wafwerar's avatar
wafwerar 已提交
72
    taosMemoryFree(pMemTable);
H
Hongze Cheng 已提交
73 74
  }
}
H
Hongze Cheng 已提交
75

S
Shengliang Guan 已提交
76
int tsdbMemTableInsert(STsdb *pTsdb, STsdbMemTable *pMemTable, SSubmitReq *pMsg, SSubmitRsp *pRsp) {
H
Hongze Cheng 已提交
77 78 79 80 81 82 83 84 85 86 87
  SSubmitBlk *   pBlock = NULL;
  SSubmitMsgIter msgIter = {0};
  int32_t        affectedrows = 0, numOfRows = 0;

  if (tsdbScanAndConvertSubmitMsg(pTsdb, pMsg) < 0) {
    if (terrno != TSDB_CODE_TDB_TABLE_RECONFIGURE) {
      tsdbError("vgId:%d failed to insert data since %s", REPO_ID(pTsdb), tstrerror(terrno));
    }
    return -1;
  }

H
Hongze Cheng 已提交
88
  tInitSubmitMsgIter(pMsg, &msgIter);
H
Hongze Cheng 已提交
89
  while (true) {
H
Hongze Cheng 已提交
90
    tGetSubmitMsgNext(&msgIter, &pBlock);
H
Hongze Cheng 已提交
91
    if (pBlock == NULL) break;
H
Hongze Cheng 已提交
92
    if (tsdbMemTableInsertTbData(pTsdb, pBlock, &affectedrows) < 0) {
H
Hongze Cheng 已提交
93 94
      return -1;
    }
H
Hongze Cheng 已提交
95

H
Hongze Cheng 已提交
96 97 98 99 100 101
    numOfRows += pBlock->numOfRows;
  }

  if (pRsp != NULL) {
    pRsp->affectedRows = htonl(affectedrows);
    pRsp->numOfRows = htonl(numOfRows);
H
Hongze Cheng 已提交
102 103
  }

H
Hongze Cheng 已提交
104
  return 0;
H
Hongze Cheng 已提交
105 106
}

H
Hongze Cheng 已提交
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
/**
 * This is an important function to load data or try to load data from memory skiplist iterator.
 *
 * This function load memory data until:
 * 1. iterator ends
 * 2. data key exceeds maxKey
 * 3. rowsIncreased = rowsInserted - rowsDeleteSucceed >= maxRowsToRead
 * 4. operations in pCols not exceeds its max capacity if pCols is given
 *
 * The function tries to procceed AS MUCH AS POSSIBLE.
 */
int tsdbLoadDataFromCache(STable *pTable, SSkipListIterator *pIter, TSKEY maxKey, int maxRowsToRead, SDataCols *pCols,
                          TKEY *filterKeys, int nFilterKeys, bool keepDup, SMergeInfo *pMergeInfo) {
  ASSERT(maxRowsToRead > 0 && nFilterKeys >= 0);
  if (pIter == NULL) return 0;
  STSchema * pSchema = NULL;
  TSKEY      rowKey = 0;
  TSKEY      fKey = 0;
  bool       isRowDel = false;
  int        filterIter = 0;
C
Cary Xu 已提交
127
  STSRow *   row = NULL;
H
Hongze Cheng 已提交
128 129 130 131 132 133 134 135 136 137
  SMergeInfo mInfo;

  if (pMergeInfo == NULL) pMergeInfo = &mInfo;

  memset(pMergeInfo, 0, sizeof(*pMergeInfo));
  pMergeInfo->keyFirst = INT64_MAX;
  pMergeInfo->keyLast = INT64_MIN;
  if (pCols) tdResetDataCols(pCols);

  row = tsdbNextIterRow(pIter);
C
Cary Xu 已提交
138
  if (row == NULL || TD_ROW_KEY(row) > maxKey) {
H
Hongze Cheng 已提交
139 140 141
    rowKey = INT64_MAX;
    isRowDel = false;
  } else {
C
Cary Xu 已提交
142 143
    rowKey = TD_ROW_KEY(row);
    isRowDel = TD_ROW_IS_DELETED(row);
H
Hongze Cheng 已提交
144 145 146 147 148 149 150 151 152 153 154 155
  }

  if (filterIter >= nFilterKeys) {
    fKey = INT64_MAX;
  } else {
    fKey = tdGetKey(filterKeys[filterIter]);
  }

  while (true) {
    if (fKey == INT64_MAX && rowKey == INT64_MAX) break;

    if (fKey < rowKey) {
dengyihao's avatar
dengyihao 已提交
156 157
      pMergeInfo->keyFirst = TMIN(pMergeInfo->keyFirst, fKey);
      pMergeInfo->keyLast = TMAX(pMergeInfo->keyLast, fKey);
H
Hongze Cheng 已提交
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172

      filterIter++;
      if (filterIter >= nFilterKeys) {
        fKey = INT64_MAX;
      } else {
        fKey = tdGetKey(filterKeys[filterIter]);
      }
    } else if (fKey > rowKey) {
      if (isRowDel) {
        pMergeInfo->rowsDeleteFailed++;
      } else {
        if (pMergeInfo->rowsInserted - pMergeInfo->rowsDeleteSucceed >= maxRowsToRead) break;
        if (pCols && pMergeInfo->nOperations >= pCols->maxPoints) break;
        pMergeInfo->rowsInserted++;
        pMergeInfo->nOperations++;
dengyihao's avatar
dengyihao 已提交
173 174
        pMergeInfo->keyFirst = TMIN(pMergeInfo->keyFirst, rowKey);
        pMergeInfo->keyLast = TMAX(pMergeInfo->keyLast, rowKey);
H
Hongze Cheng 已提交
175 176 177 178 179
        tsdbAppendTableRowToCols(pTable, pCols, &pSchema, row);
      }

      tSkipListIterNext(pIter);
      row = tsdbNextIterRow(pIter);
C
Cary Xu 已提交
180
      if (row == NULL || TD_ROW_KEY(row) > maxKey) {
H
Hongze Cheng 已提交
181 182 183
        rowKey = INT64_MAX;
        isRowDel = false;
      } else {
C
Cary Xu 已提交
184 185
        rowKey = TD_ROW_KEY(row);
        isRowDel = TD_ROW_IS_DELETED(row);
H
Hongze Cheng 已提交
186 187 188 189 190 191 192 193 194 195 196 197 198
      }
    } else {
      if (isRowDel) {
        ASSERT(!keepDup);
        if (pCols && pMergeInfo->nOperations >= pCols->maxPoints) break;
        pMergeInfo->rowsDeleteSucceed++;
        pMergeInfo->nOperations++;
        tsdbAppendTableRowToCols(pTable, pCols, &pSchema, row);
      } else {
        if (keepDup) {
          if (pCols && pMergeInfo->nOperations >= pCols->maxPoints) break;
          pMergeInfo->rowsUpdated++;
          pMergeInfo->nOperations++;
dengyihao's avatar
dengyihao 已提交
199 200
          pMergeInfo->keyFirst = TMIN(pMergeInfo->keyFirst, rowKey);
          pMergeInfo->keyLast = TMAX(pMergeInfo->keyLast, rowKey);
H
Hongze Cheng 已提交
201 202
          tsdbAppendTableRowToCols(pTable, pCols, &pSchema, row);
        } else {
dengyihao's avatar
dengyihao 已提交
203 204
          pMergeInfo->keyFirst = TMIN(pMergeInfo->keyFirst, fKey);
          pMergeInfo->keyLast = TMAX(pMergeInfo->keyLast, fKey);
H
Hongze Cheng 已提交
205 206 207 208 209
        }
      }

      tSkipListIterNext(pIter);
      row = tsdbNextIterRow(pIter);
C
Cary Xu 已提交
210
      if (row == NULL || TD_ROW_KEY(row) > maxKey) {
H
Hongze Cheng 已提交
211 212 213
        rowKey = INT64_MAX;
        isRowDel = false;
      } else {
C
Cary Xu 已提交
214 215
        rowKey = TD_ROW_KEY(row);
        isRowDel = TD_ROW_IS_DELETED(row);
H
Hongze Cheng 已提交
216 217 218 219 220 221 222 223 224 225 226 227 228 229
      }

      filterIter++;
      if (filterIter >= nFilterKeys) {
        fKey = INT64_MAX;
      } else {
        fKey = tdGetKey(filterKeys[filterIter]);
      }
    }
  }

  return 0;
}

C
Cary Xu 已提交
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
int32_t tdScanAndConvertSubmitMsg(SSubmitReq *pMsg) {
  ASSERT(pMsg != NULL);
  SSubmitMsgIter msgIter = {0};
  SSubmitBlk    *pBlock = NULL;
  SSubmitBlkIter blkIter = {0};
  STSRow        *row = NULL;

  terrno = TSDB_CODE_SUCCESS;
  pMsg->length = htonl(pMsg->length);
  pMsg->numOfBlocks = htonl(pMsg->numOfBlocks);

  if (tInitSubmitMsgIter(pMsg, &msgIter) < 0) return -1;
  while (true) {
    if (tGetSubmitMsgNext(&msgIter, &pBlock) < 0) return -1;
    if (pBlock == NULL) break;

    pBlock->uid = htobe64(pBlock->uid);
    pBlock->suid = htobe64(pBlock->suid);
    pBlock->sversion = htonl(pBlock->sversion);
    pBlock->dataLen = htonl(pBlock->dataLen);
    pBlock->schemaLen = htonl(pBlock->schemaLen);
    pBlock->numOfRows = htons(pBlock->numOfRows);
  }

  if (terrno != TSDB_CODE_SUCCESS) return -1;
  return 0;
}

258
static int tsdbScanAndConvertSubmitMsg(STsdb *pTsdb, SSubmitReq *pMsg) {
H
Hongze Cheng 已提交
259 260 261 262 263
  ASSERT(pMsg != NULL);
  // STsdbMeta *    pMeta = pTsdb->tsdbMeta;
  SSubmitMsgIter msgIter = {0};
  SSubmitBlk *   pBlock = NULL;
  SSubmitBlkIter blkIter = {0};
C
Cary Xu 已提交
264
  STSRow *       row = NULL;
H
Hongze Cheng 已提交
265 266 267 268 269 270 271 272
  TSKEY          now = taosGetTimestamp(pTsdb->config.precision);
  TSKEY          minKey = now - tsTickPerDay[pTsdb->config.precision] * pTsdb->config.keep;
  TSKEY          maxKey = now + tsTickPerDay[pTsdb->config.precision] * pTsdb->config.daysPerFile;

  terrno = TSDB_CODE_SUCCESS;
  pMsg->length = htonl(pMsg->length);
  pMsg->numOfBlocks = htonl(pMsg->numOfBlocks);

H
Hongze Cheng 已提交
273
  if (tInitSubmitMsgIter(pMsg, &msgIter) < 0) return -1;
H
Hongze Cheng 已提交
274
  while (true) {
H
Hongze Cheng 已提交
275
    if (tGetSubmitMsgNext(&msgIter, &pBlock) < 0) return -1;
H
Hongze Cheng 已提交
276 277 278
    if (pBlock == NULL) break;

    pBlock->uid = htobe64(pBlock->uid);
X
Xiaoyu Wang 已提交
279
    pBlock->suid = htobe64(pBlock->suid);
H
Hongze Cheng 已提交
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
    pBlock->sversion = htonl(pBlock->sversion);
    pBlock->dataLen = htonl(pBlock->dataLen);
    pBlock->schemaLen = htonl(pBlock->schemaLen);
    pBlock->numOfRows = htons(pBlock->numOfRows);

#if 0
    if (pBlock->tid <= 0 || pBlock->tid >= pMeta->maxTables) {
      tsdbError("vgId:%d failed to get table to insert data, uid %" PRIu64 " tid %d", REPO_ID(pTsdb), pBlock->uid,
                pBlock->tid);
      terrno = TSDB_CODE_TDB_INVALID_TABLE_ID;
      return -1;
    }

    STable *pTable = pMeta->tables[pBlock->tid];
    if (pTable == NULL || TABLE_UID(pTable) != pBlock->uid) {
      tsdbError("vgId:%d failed to get table to insert data, uid %" PRIu64 " tid %d", REPO_ID(pTsdb), pBlock->uid,
                pBlock->tid);
      terrno = TSDB_CODE_TDB_INVALID_TABLE_ID;
      return -1;
    }

    if (TABLE_TYPE(pTable) == TSDB_SUPER_TABLE) {
      tsdbError("vgId:%d invalid action trying to insert a super table %s", REPO_ID(pTsdb), TABLE_CHAR_NAME(pTable));
      terrno = TSDB_CODE_TDB_INVALID_ACTION;
      return -1;
    }

    // Check schema version and update schema if needed
    if (tsdbCheckTableSchema(pTsdb, pBlock, pTable) < 0) {
      if (terrno == TSDB_CODE_TDB_TABLE_RECONFIGURE) {
        continue;
      } else {
        return -1;
      }
    }

    tsdbInitSubmitBlkIter(pBlock, &blkIter);
    while ((row = tsdbGetSubmitBlkNext(&blkIter)) != NULL) {
      if (tsdbCheckRowRange(pTsdb, pTable, row, minKey, maxKey, now) < 0) {
        return -1;
      }
    }
#endif
  }

  if (terrno != TSDB_CODE_SUCCESS) return -1;
  return 0;
}

H
Hongze Cheng 已提交
329 330 331 332 333 334 335 336
static int tsdbMemTableInsertTbData(STsdb *pTsdb, SSubmitBlk *pBlock, int32_t *pAffectedRows) {
  // STsdbMeta       *pMeta = pRepo->tsdbMeta;
  // int32_t          points = 0;
  // STable          *pTable = NULL;
  SSubmitBlkIter blkIter = {0};
  STsdbMemTable *pMemTable = pTsdb->mem;
  void *         tptr;
  STbData *      pTbData;
C
Cary Xu 已提交
337
  STSRow *       row;
H
Hongze Cheng 已提交
338 339 340
  TSKEY          keyMin;
  TSKEY          keyMax;

H
Hongze Cheng 已提交
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
  // SMemTable       *pMemTable = NULL;
  // STableData      *pTableData = NULL;
  // STsdbCfg        *pCfg = &(pRepo->config);

  tptr = taosHashGet(pMemTable->pHashIdx, &(pBlock->uid), sizeof(pBlock->uid));
  if (tptr == NULL) {
    pTbData = tsdbNewTbData(pBlock->uid);
    if (pTbData == NULL) {
      return -1;
    }

    // Put into hash
    taosHashPut(pMemTable->pHashIdx, &(pBlock->uid), sizeof(pBlock->uid), &(pTbData), sizeof(pTbData));

    // Put into skiplist
    tSkipListPut(pMemTable->pSlIdx, pTbData);
  } else {
    pTbData = *(STbData **)tptr;
  }

H
Hongze Cheng 已提交
361
  tInitSubmitBlkIter(pBlock, &blkIter);
H
Hongze Cheng 已提交
362
  if (blkIter.row == NULL) return 0;
C
Cary Xu 已提交
363
  keyMin = TD_ROW_KEY(blkIter.row);
H
Hongze Cheng 已提交
364

H
Hongze Cheng 已提交
365
  tSkipListPutBatchByIter(pTbData->pData, &blkIter, (iter_next_fn_t)tGetSubmitBlkNext);
H
Hongze Cheng 已提交
366

H
Hongze Cheng 已提交
367
  // Set statistics
C
Cary Xu 已提交
368
  keyMax = TD_ROW_KEY(blkIter.row);
H
Hongze Cheng 已提交
369

H
Hongze Cheng 已提交
370 371 372
  pTbData->nrows += pBlock->numOfRows;
  if (pTbData->keyMin > keyMin) pTbData->keyMin = keyMin;
  if (pTbData->keyMax < keyMax) pTbData->keyMax = keyMax;
H
Hongze Cheng 已提交
373

H
Hongze Cheng 已提交
374 375 376
  pMemTable->nRow += pBlock->numOfRows;
  if (pMemTable->keyMin > keyMin) pMemTable->keyMin = keyMin;
  if (pMemTable->keyMax < keyMax) pMemTable->keyMax = keyMax;
H
Hongze Cheng 已提交
377

C
Cary Xu 已提交
378
  // STSRow* lastRow = NULL;
H
Hongze Cheng 已提交
379 380 381 382 383 384 385
  // int64_t osize = SL_SIZE(pTableData->pData);
  // tsdbSetupSkipListHookFns(pTableData->pData, pRepo, pTable, &points, &lastRow);
  // tSkipListPutBatchByIter(pTableData->pData, &blkIter, (iter_next_fn_t)tsdbGetSubmitBlkNext);
  // int64_t dsize = SL_SIZE(pTableData->pData) - osize;
  // (*pAffectedRows) += points;

  // if(lastRow != NULL) {
C
Cary Xu 已提交
386
  //   TSKEY lastRowKey = TD_ROW_KEY(lastRow);
H
Hongze Cheng 已提交
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
  //   if (pMemTable->keyFirst > firstRowKey) pMemTable->keyFirst = firstRowKey;
  //   pMemTable->numOfRows += dsize;

  //   if (pTableData->keyFirst > firstRowKey) pTableData->keyFirst = firstRowKey;
  //   pTableData->numOfRows += dsize;
  //   if (pMemTable->keyLast < lastRowKey) pMemTable->keyLast = lastRowKey;
  //   if (pTableData->keyLast < lastRowKey) pTableData->keyLast = lastRowKey;
  //   if (tsdbUpdateTableLatestInfo(pRepo, pTable, lastRow) < 0) {
  //     return -1;
  //   }
  // }

  // STSchema *pSchema = tsdbGetTableSchemaByVersion(pTable, pBlock->sversion, -1);
  // pRepo->stat.pointsWritten += points * schemaNCols(pSchema);
  // pRepo->stat.totalStorage += points * schemaVLen(pSchema);

  return 0;
}

static STbData *tsdbNewTbData(tb_uid_t uid) {
wafwerar's avatar
wafwerar 已提交
407
  STbData *pTbData = (STbData *)taosMemoryCalloc(1, sizeof(*pTbData));
H
Hongze Cheng 已提交
408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
  if (pTbData == NULL) {
    return NULL;
  }

  pTbData->uid = uid;
  pTbData->keyMin = TSKEY_MAX;
  pTbData->keyMax = TSKEY_MIN;
  pTbData->nrows = 0;

  // uint8_t skipListCreateFlags;
  // if (pCfg->update == TD_ROW_DISCARD_UPDATE)
  //   skipListCreateFlags = SL_DISCARD_DUP_KEY;
  // else
  //   skipListCreateFlags = SL_UPDATE_DUP_KEY;

  // pTableData->pData =
  //     tSkipListCreate(TSDB_DATA_SKIPLIST_LEVEL, TSDB_DATA_TYPE_TIMESTAMP, TYPE_BYTES[TSDB_DATA_TYPE_TIMESTAMP],
  //                     tkeyComparFn, skipListCreateFlags, tsdbGetTsTupleKey);
  // if (pTableData->pData == NULL) {
  //   terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
wafwerar's avatar
wafwerar 已提交
428
  //   taosMemoryFree(pTableData);
H
Hongze Cheng 已提交
429 430 431 432 433 434
  //   return NULL;
  // }

  pTbData->pData = tSkipListCreate(5, TSDB_DATA_TYPE_TIMESTAMP, sizeof(int64_t), tkeyComparFn, SL_DISCARD_DUP_KEY,
                                   tsdbGetTsTupleKey);
  if (pTbData->pData == NULL) {
wafwerar's avatar
wafwerar 已提交
435
    taosMemoryFree(pTbData);
H
Hongze Cheng 已提交
436 437 438 439 440 441 442 443 444
    return NULL;
  }

  return pTbData;
}

static void tsdbFreeTbData(STbData *pTbData) {
  if (pTbData) {
    tSkipListDestroy(pTbData->pData);
wafwerar's avatar
wafwerar 已提交
445
    taosMemoryFree(pTbData);
H
Hongze Cheng 已提交
446 447 448
  }
}

C
Cary Xu 已提交
449
static char *tsdbGetTsTupleKey(const void *data) { return (char *)TD_ROW_KEY_ADDR((STSRow *)data); }
H
Hongze Cheng 已提交
450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465

static int tsdbTbDataComp(const void *arg1, const void *arg2) {
  STbData *pTbData1 = (STbData *)arg1;
  STbData *pTbData2 = (STbData *)arg2;

  if (pTbData1->uid > pTbData2->uid) {
    return 1;
  } else if (pTbData1->uid == pTbData2->uid) {
    return 0;
  } else {
    return -1;
  }
}

static char *tsdbTbDataGetUid(const void *arg) {
  STbData *pTbData = (STbData *)arg;
H
Hongze Cheng 已提交
466
  return (char *)(&(pTbData->uid));
H
Hongze Cheng 已提交
467
}
C
Cary Xu 已提交
468
static int tsdbAppendTableRowToCols(STable *pTable, SDataCols *pCols, STSchema **ppSchema, STSRow *row) {
H
Hongze Cheng 已提交
469
  if (pCols) {
C
Cary Xu 已提交
470 471
    if (*ppSchema == NULL || schemaVersion(*ppSchema) != TD_ROW_SVER(row)) {
      *ppSchema = tsdbGetTableSchemaImpl(pTable, false, false, TD_ROW_SVER(row));
H
Hongze Cheng 已提交
472 473 474 475 476 477
      if (*ppSchema == NULL) {
        ASSERT(false);
        return -1;
      }
    }

C
Cary Xu 已提交
478
    tdAppendSTSRowToDataCol(row, *ppSchema, pCols, true);
H
Hongze Cheng 已提交
479 480 481 482
  }

  return 0;
}
H
Hongze Cheng 已提交
483 484

/* ------------------------ REFACTORING ------------------------ */
H
Hongze Cheng 已提交
485
#if 0
S
Shengliang Guan 已提交
486
int tsdbInsertDataToMemTable(STsdbMemTable *pMemTable, SSubmitReq *pMsg) {
H
Hongze Cheng 已提交
487
  SMemAllocator *pMA = pMemTable->pMA;
H
refact  
Hongze Cheng 已提交
488
  STbData *      pTbData = (STbData *)TD_MA_MALLOC(pMA, sizeof(*pTbData));
H
Hongze Cheng 已提交
489 490 491 492
  if (pTbData == NULL) {
    // TODO
  }

H
Hongze Cheng 已提交
493
  TD_SLIST_PUSH(&(pMemTable->list), pTbData);
H
Hongze Cheng 已提交
494

H
Hongze Cheng 已提交
495
  return 0;
H
Hongze Cheng 已提交
496 497
}

H
more  
Hongze Cheng 已提交
498 499
#include "tdataformat.h"
#include "tfunctional.h"
H
Hongze Cheng 已提交
500
#include "tsdbRowMergeBuf.h"
H
more  
Hongze Cheng 已提交
501 502 503 504 505 506 507 508 509
#include "tsdbint.h"
#include "tskiplist.h"

#define TSDB_DATA_SKIPLIST_LEVEL 5
#define TSDB_MAX_INSERT_BATCH 512

typedef struct {
  int32_t  totalLen;
  int32_t  len;
C
Cary Xu 已提交
510
  STSRow*  row;
H
more  
Hongze Cheng 已提交
511 512 513 514 515 516 517 518 519 520 521 522 523
} SSubmitBlkIter;

typedef struct {
  int32_t totalLen;
  int32_t len;
  void *  pMsg;
} SSubmitMsgIter;

static SMemTable *  tsdbNewMemTable(STsdbRepo *pRepo);
static void         tsdbFreeMemTable(SMemTable *pMemTable);
static STableData*  tsdbNewTableData(STsdbCfg *pCfg, STable *pTable);
static void         tsdbFreeTableData(STableData *pTableData);
static int          tsdbAdjustMemMaxTables(SMemTable *pMemTable, int maxTables);
C
Cary Xu 已提交
524
static int          tsdbAppendTableRowToCols(STable *pTable, SDataCols *pCols, STSchema **ppSchema, STSRow* row);
H
more  
Hongze Cheng 已提交
525
static int          tsdbInitSubmitBlkIter(SSubmitBlk *pBlock, SSubmitBlkIter *pIter);
C
Cary Xu 已提交
526
static STSRow*      tsdbGetSubmitBlkNext(SSubmitBlkIter *pIter);
S
Shengliang Guan 已提交
527
static int          tsdbScanAndConvertSubmitMsg(STsdbRepo *pRepo, SSubmitReq *pMsg);
H
more  
Hongze Cheng 已提交
528
static int          tsdbInsertDataToTable(STsdbRepo *pRepo, SSubmitBlk *pBlock, int32_t *affectedrows);
S
Shengliang Guan 已提交
529
static int          tsdbInitSubmitMsgIter(SSubmitReq *pMsg, SSubmitMsgIter *pIter);
H
more  
Hongze Cheng 已提交
530 531
static int          tsdbGetSubmitMsgNext(SSubmitMsgIter *pIter, SSubmitBlk **pPBlock);
static int          tsdbCheckTableSchema(STsdbRepo *pRepo, SSubmitBlk *pBlock, STable *pTable);
C
Cary Xu 已提交
532
static int          tsdbUpdateTableLatestInfo(STsdbRepo *pRepo, STable *pTable, STSRow* row);
H
more  
Hongze Cheng 已提交
533

C
Cary Xu 已提交
534
static FORCE_INLINE int tsdbCheckRowRange(STsdbRepo *pRepo, STable *pTable, STSRow* row, TSKEY minKey, TSKEY maxKey,
H
more  
Hongze Cheng 已提交
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
                                          TSKEY now);


// ---------------- INTERNAL FUNCTIONS ----------------
int tsdbRefMemTable(STsdbRepo *pRepo, SMemTable *pMemTable) {
  if (pMemTable == NULL) return 0;
  int ref = T_REF_INC(pMemTable);
	tsdbDebug("vgId:%d ref memtable %p ref %d", REPO_ID(pRepo), pMemTable, ref);
  return 0;
}

// Need to lock the repository
int tsdbUnRefMemTable(STsdbRepo *pRepo, SMemTable *pMemTable) {
  if (pMemTable == NULL) return 0;

	int ref = T_REF_DEC(pMemTable);
	tsdbDebug("vgId:%d unref memtable %p ref %d", REPO_ID(pRepo), pMemTable, ref);
  if (ref == 0) {
    STsdbBufPool *pBufPool = pRepo->pPool;

    SListNode *pNode = NULL;
    bool addNew = false;
    if (tsdbLockRepo(pRepo) < 0) return -1;
    while ((pNode = tdListPopHead(pMemTable->bufBlockList)) != NULL) {
      if (pBufPool->nRecycleBlocks > 0) {
        tsdbRecycleBufferBlock(pBufPool, pNode, false);
        pBufPool->nRecycleBlocks -= 1;
      } else {
        if(pBufPool->nElasticBlocks > 0 && listNEles(pBufPool->bufBlockList) > 2) {
          tsdbRecycleBufferBlock(pBufPool, pNode, true);
        } else {
          tdListAppendNode(pBufPool->bufBlockList, pNode);
          addNew = true;
        }
      }      
    }
    if (addNew) {
wafwerar's avatar
wafwerar 已提交
572
      int code = taosThreadCondSignal(&pBufPool->poolNotEmpty);
H
more  
Hongze Cheng 已提交
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 603 604 605 606 607 608 609 610 611 612
      if (code != 0) {
        if (tsdbUnlockRepo(pRepo) < 0) return -1;
        tsdbError("vgId:%d failed to signal pool not empty since %s", REPO_ID(pRepo), strerror(code));
        terrno = TAOS_SYSTEM_ERROR(code);
        return -1;
      }
    }

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

    for (int i = 0; i < pMemTable->maxTables; i++) {
      if (pMemTable->tData[i] != NULL) {
        tsdbFreeTableData(pMemTable->tData[i]);
      }
    }

    tdListDiscard(pMemTable->actList);
    tdListDiscard(pMemTable->bufBlockList);
    tsdbFreeMemTable(pMemTable);
  }
  return 0;
}

int tsdbTakeMemSnapshot(STsdbRepo *pRepo, SMemSnapshot *pSnapshot, SArray *pATable) {
  memset(pSnapshot, 0, sizeof(*pSnapshot));

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

  pSnapshot->omem = pRepo->mem;
  pSnapshot->imem = pRepo->imem;
  tsdbRefMemTable(pRepo, pRepo->mem);
  tsdbRefMemTable(pRepo, pRepo->imem);

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

  if (pSnapshot->omem) {
    taosRLockLatch(&(pSnapshot->omem->latch));

    pSnapshot->mem = &(pSnapshot->mtable);

wafwerar's avatar
wafwerar 已提交
613
    pSnapshot->mem->tData = (STableData **)taosMemoryCalloc(pSnapshot->omem->maxTables, sizeof(STableData *));
H
more  
Hongze Cheng 已提交
614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659
    if (pSnapshot->mem->tData == NULL) {
      terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
      taosRUnLockLatch(&(pSnapshot->omem->latch));
      tsdbUnRefMemTable(pRepo, pSnapshot->omem);
      tsdbUnRefMemTable(pRepo, pSnapshot->imem);
      pSnapshot->mem = NULL;
      pSnapshot->imem = NULL;
      pSnapshot->omem = NULL;
      return -1;
    }

    pSnapshot->mem->keyFirst = pSnapshot->omem->keyFirst;
    pSnapshot->mem->keyLast = pSnapshot->omem->keyLast;
    pSnapshot->mem->numOfRows = pSnapshot->omem->numOfRows;
    pSnapshot->mem->maxTables = pSnapshot->omem->maxTables;

    for (size_t i = 0; i < taosArrayGetSize(pATable); i++) {
      STable *    pTable = *(STable **)taosArrayGet(pATable, i);
      int32_t     tid = TABLE_TID(pTable);
      STableData *pTableData = (tid < pSnapshot->omem->maxTables) ? pSnapshot->omem->tData[tid] : NULL;

      if ((pTableData == NULL) || (TABLE_UID(pTable) != pTableData->uid)) continue;

      pSnapshot->mem->tData[tid] = pTableData;
      T_REF_INC(pTableData);
    }

    taosRUnLockLatch(&(pSnapshot->omem->latch));
  }

  tsdbDebug("vgId:%d take memory snapshot, pMem %p pIMem %p", REPO_ID(pRepo), pSnapshot->omem, pSnapshot->imem);
  return 0;
}

void tsdbUnTakeMemSnapShot(STsdbRepo *pRepo, SMemSnapshot *pSnapshot) {
  tsdbDebug("vgId:%d untake memory snapshot, pMem %p pIMem %p", REPO_ID(pRepo), pSnapshot->omem, pSnapshot->imem);

  if (pSnapshot->mem) {
    ASSERT(pSnapshot->omem != NULL);

    for (size_t i = 0; i < pSnapshot->mem->maxTables; i++) {
      STableData *pTableData = pSnapshot->mem->tData[i];
      if (pTableData) {
        tsdbFreeTableData(pTableData);
      }
    }
wafwerar's avatar
wafwerar 已提交
660
    taosMemoryFreeClear(pSnapshot->mem->tData);
H
more  
Hongze Cheng 已提交
661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715

    tsdbUnRefMemTable(pRepo, pSnapshot->omem);
  }

  tsdbUnRefMemTable(pRepo, pSnapshot->imem);

  pSnapshot->mem = NULL;
  pSnapshot->imem = NULL;
  pSnapshot->omem = NULL;
}

int tsdbSyncCommitConfig(STsdbRepo* pRepo) {
  ASSERT(pRepo->config_changed == true);
  tsem_wait(&(pRepo->readyToCommit));

  if (pRepo->code != TSDB_CODE_SUCCESS) {
    tsdbWarn("vgId:%d try to commit config when TSDB not in good state: %s", REPO_ID(pRepo), tstrerror(terrno));
  }

  if (tsdbLockRepo(pRepo) < 0) return -1;
  tsdbScheduleCommit(pRepo, COMMIT_CONFIG_REQ);
  if (tsdbUnlockRepo(pRepo) < 0) return -1;

  tsem_wait(&(pRepo->readyToCommit));
  tsem_post(&(pRepo->readyToCommit));

  if (pRepo->code != TSDB_CODE_SUCCESS) {
    terrno = pRepo->code;
    return -1;
  }

  terrno = TSDB_CODE_SUCCESS;
  return 0;
}

/**
 * This is an important function to load data or try to load data from memory skiplist iterator.
 * 
 * This function load memory data until:
 * 1. iterator ends
 * 2. data key exceeds maxKey
 * 3. rowsIncreased = rowsInserted - rowsDeleteSucceed >= maxRowsToRead
 * 4. operations in pCols not exceeds its max capacity if pCols is given
 * 
 * The function tries to procceed AS MUCH AS POSSIBLE.
 */
int tsdbLoadDataFromCache(STable *pTable, SSkipListIterator *pIter, TSKEY maxKey, int maxRowsToRead, SDataCols *pCols,
                          TKEY *filterKeys, int nFilterKeys, bool keepDup, SMergeInfo *pMergeInfo) {
  ASSERT(maxRowsToRead > 0 && nFilterKeys >= 0);
  if (pIter == NULL) return 0;
  STSchema * pSchema = NULL;
  TSKEY      rowKey = 0;
  TSKEY      fKey = 0;
  bool       isRowDel = false;
  int        filterIter = 0;
C
Cary Xu 已提交
716
  STSRow*    row = NULL;
H
more  
Hongze Cheng 已提交
717 718 719 720 721 722 723 724 725 726
  SMergeInfo mInfo;

  if (pMergeInfo == NULL) pMergeInfo = &mInfo;

  memset(pMergeInfo, 0, sizeof(*pMergeInfo));
  pMergeInfo->keyFirst = INT64_MAX;
  pMergeInfo->keyLast = INT64_MIN;
  if (pCols) tdResetDataCols(pCols);

  row = tsdbNextIterRow(pIter);
C
Cary Xu 已提交
727
  if (row == NULL || TD_ROW_KEY(row) > maxKey) {
H
more  
Hongze Cheng 已提交
728 729 730
    rowKey = INT64_MAX;
    isRowDel = false;
  } else {
C
Cary Xu 已提交
731
    rowKey = TD_ROW_KEY(row);
H
more  
Hongze Cheng 已提交
732 733 734 735 736 737 738 739 740 741 742 743 744
    isRowDel = memRowDeleted(row);
  }

  if (filterIter >= nFilterKeys) {
    fKey = INT64_MAX;
  } else {
    fKey = tdGetKey(filterKeys[filterIter]);
  }

  while (true) {
    if (fKey == INT64_MAX && rowKey == INT64_MAX) break;

    if (fKey < rowKey) {
dengyihao's avatar
dengyihao 已提交
745 746
      pMergeInfo->keyFirst = TMIN(pMergeInfo->keyFirst, fKey);
      pMergeInfo->keyLast = TMAX(pMergeInfo->keyLast, fKey);
H
more  
Hongze Cheng 已提交
747 748 749 750 751 752 753 754 755 756 757 758 759 760 761

      filterIter++;
      if (filterIter >= nFilterKeys) {
        fKey = INT64_MAX;
      } else {
        fKey = tdGetKey(filterKeys[filterIter]);
      }
    } else if (fKey > rowKey) {
      if (isRowDel) {
        pMergeInfo->rowsDeleteFailed++;
      } else {
        if (pMergeInfo->rowsInserted - pMergeInfo->rowsDeleteSucceed >= maxRowsToRead) break;
        if (pCols && pMergeInfo->nOperations >= pCols->maxPoints) break;
        pMergeInfo->rowsInserted++;
        pMergeInfo->nOperations++;
dengyihao's avatar
dengyihao 已提交
762 763
        pMergeInfo->keyFirst = TMIN(pMergeInfo->keyFirst, rowKey);
        pMergeInfo->keyLast = TMAX(pMergeInfo->keyLast, rowKey);
H
more  
Hongze Cheng 已提交
764 765 766 767 768
        tsdbAppendTableRowToCols(pTable, pCols, &pSchema, row);
      }

      tSkipListIterNext(pIter);
      row = tsdbNextIterRow(pIter);
C
Cary Xu 已提交
769
      if (row == NULL || TD_ROW_KEY(row) > maxKey) {
H
more  
Hongze Cheng 已提交
770 771 772
        rowKey = INT64_MAX;
        isRowDel = false;
      } else {
C
Cary Xu 已提交
773
        rowKey = TD_ROW_KEY(row);
H
more  
Hongze Cheng 已提交
774 775 776 777 778 779 780 781 782 783 784 785 786 787
        isRowDel = memRowDeleted(row);
      }
    } else {
      if (isRowDel) {
        ASSERT(!keepDup);
        if (pCols && pMergeInfo->nOperations >= pCols->maxPoints) break;
        pMergeInfo->rowsDeleteSucceed++;
        pMergeInfo->nOperations++;
        tsdbAppendTableRowToCols(pTable, pCols, &pSchema, row);
      } else {
        if (keepDup) {
          if (pCols && pMergeInfo->nOperations >= pCols->maxPoints) break;
          pMergeInfo->rowsUpdated++;
          pMergeInfo->nOperations++;
dengyihao's avatar
dengyihao 已提交
788 789
          pMergeInfo->keyFirst = TMIN(pMergeInfo->keyFirst, rowKey);
          pMergeInfo->keyLast = TMAX(pMergeInfo->keyLast, rowKey);
H
more  
Hongze Cheng 已提交
790 791
          tsdbAppendTableRowToCols(pTable, pCols, &pSchema, row);
        } else {
dengyihao's avatar
dengyihao 已提交
792 793
          pMergeInfo->keyFirst = TMIN(pMergeInfo->keyFirst, fKey);
          pMergeInfo->keyLast = TMAX(pMergeInfo->keyLast, fKey);
H
more  
Hongze Cheng 已提交
794 795 796 797 798
        }
      }

      tSkipListIterNext(pIter);
      row = tsdbNextIterRow(pIter);
C
Cary Xu 已提交
799
      if (row == NULL || TD_ROW_KEY(row) > maxKey) {
H
more  
Hongze Cheng 已提交
800 801 802
        rowKey = INT64_MAX;
        isRowDel = false;
      } else {
C
Cary Xu 已提交
803
        rowKey = TD_ROW_KEY(row);
H
more  
Hongze Cheng 已提交
804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820
        isRowDel = memRowDeleted(row);
      }

      filterIter++;
      if (filterIter >= nFilterKeys) {
        fKey = INT64_MAX;
      } else {
        fKey = tdGetKey(filterKeys[filterIter]);
      }
    }
  }

  return 0;
}

// ---------------- LOCAL FUNCTIONS ----------------

C
Cary Xu 已提交
821
static FORCE_INLINE int tsdbCheckRowRange(STsdbRepo *pRepo, STable *pTable, STSRow* row, TSKEY minKey, TSKEY maxKey,
H
more  
Hongze Cheng 已提交
822
                                          TSKEY now) {
C
Cary Xu 已提交
823
  TSKEY rowKey = TD_ROW_KEY(row);
H
more  
Hongze Cheng 已提交
824 825 826 827 828 829 830 831 832 833 834 835 836 837
  if (rowKey < minKey || rowKey > maxKey) {
    tsdbError("vgId:%d table %s tid %d uid %" PRIu64 " timestamp is out of range! now %" PRId64 " minKey %" PRId64
              " maxKey %" PRId64 " row key %" PRId64,
              REPO_ID(pRepo), TABLE_CHAR_NAME(pTable), TABLE_TID(pTable), TABLE_UID(pTable), now, minKey, maxKey,
              rowKey);
    terrno = TSDB_CODE_TDB_TIMESTAMP_OUT_OF_RANGE;
    return -1;
  }

  return 0;
}


//row1 has higher priority
C
Cary Xu 已提交
838
static STSRow* tsdbInsertDupKeyMerge(STSRow* row1, STSRow* row2, STsdbRepo* pRepo,
H
more  
Hongze Cheng 已提交
839
                                     STSchema **ppSchema1, STSchema **ppSchema2,
C
Cary Xu 已提交
840
                                     STable* pTable, int32_t* pPoints, STSRow** pLastRow) {
H
more  
Hongze Cheng 已提交
841 842 843 844 845 846 847 848 849

  //for compatiblity, duplicate key inserted when update=0 should be also calculated as affected rows!
  if(row1 == NULL && row2 == NULL && pRepo->config.update == TD_ROW_DISCARD_UPDATE) {
    (*pPoints)++;
    return NULL;
  }

  tsdbTrace("vgId:%d a row is %s table %s tid %d uid %" PRIu64 " key %" PRIu64, REPO_ID(pRepo),
            "updated in", TABLE_CHAR_NAME(pTable), TABLE_TID(pTable), TABLE_UID(pTable),
C
Cary Xu 已提交
850
            TD_ROW_KEY(row1));
H
more  
Hongze Cheng 已提交
851 852

  if(row2 == NULL || pRepo->config.update != TD_ROW_PARTIAL_UPDATE) {
C
Cary Xu 已提交
853
    void* pMem = tsdbAllocBytes(pRepo, TD_ROW_LEN(row1));
H
more  
Hongze Cheng 已提交
854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883
    if(pMem == NULL) return NULL;
    memRowCpy(pMem, row1);
    (*pPoints)++;
    *pLastRow = pMem;
    return pMem;
  }

  STSchema *pSchema1 = *ppSchema1;
  STSchema *pSchema2 = *ppSchema2;
  SMergeBuf * pBuf = &pRepo->mergeBuf;
  int dv1 = memRowVersion(row1);
  int dv2 = memRowVersion(row2);
  if(pSchema1 == NULL || schemaVersion(pSchema1) != dv1) {
    if(pSchema2 != NULL && schemaVersion(pSchema2) == dv1) {
      *ppSchema1 = pSchema2;
    } else {
      *ppSchema1 = tsdbGetTableSchemaImpl(pTable, false, false, memRowVersion(row1), (int8_t)memRowType(row1));
    }
    pSchema1 = *ppSchema1;
  }

  if(pSchema2 == NULL || schemaVersion(pSchema2) != dv2) {
    if(schemaVersion(pSchema1) == dv2) {
      pSchema2 = pSchema1;
    } else {
      *ppSchema2 = tsdbGetTableSchemaImpl(pTable, false, false, memRowVersion(row2), (int8_t)memRowType(row2));
      pSchema2 = *ppSchema2;
    }
  }

C
Cary Xu 已提交
884
  STSRow* tmp = tsdbMergeTwoRows(pBuf, row1, row2, pSchema1, pSchema2);
H
more  
Hongze Cheng 已提交
885

C
Cary Xu 已提交
886
  void* pMem = tsdbAllocBytes(pRepo, TD_ROW_LEN(tmp));
H
more  
Hongze Cheng 已提交
887 888 889 890 891 892 893 894 895 896 897 898
  if(pMem == NULL) return NULL;
  memRowCpy(pMem, tmp);

  (*pPoints)++;
  *pLastRow = pMem;
  return pMem;
}

static void* tsdbInsertDupKeyMergePacked(void** args) {
  return tsdbInsertDupKeyMerge(args[0], args[1], args[2], (STSchema**)&args[3], (STSchema**)&args[4], args[5], args[6], args[7]);
}

C
Cary Xu 已提交
899
static void tsdbSetupSkipListHookFns(SSkipList* pSkipList, STsdbRepo *pRepo, STable *pTable, int32_t* pPoints, STSRow** pLastRow) {
H
more  
Hongze Cheng 已提交
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 954 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

  if(pSkipList->insertHandleFn == NULL) {
    tGenericSavedFunc *dupHandleSavedFunc = genericSavedFuncInit((GenericVaFunc)&tsdbInsertDupKeyMergePacked, 9);
    dupHandleSavedFunc->args[2] = pRepo;
    dupHandleSavedFunc->args[3] = NULL;
    dupHandleSavedFunc->args[4] = NULL;
    dupHandleSavedFunc->args[5] = pTable;
    pSkipList->insertHandleFn = dupHandleSavedFunc;
  }
  pSkipList->insertHandleFn->args[6] = pPoints;
  pSkipList->insertHandleFn->args[7] = pLastRow;
}

static int tsdbCheckTableSchema(STsdbRepo *pRepo, SSubmitBlk *pBlock, STable *pTable) {
  ASSERT(pTable != NULL);

  STSchema *pSchema = tsdbGetTableSchemaImpl(pTable, false, false, -1, -1);
  int       sversion = schemaVersion(pSchema);

  if (pBlock->sversion == sversion) {
    return 0;
  } else {
    if (TABLE_TYPE(pTable) == TSDB_STREAM_TABLE) {  // stream table is not allowed to change schema
      terrno = TSDB_CODE_TDB_IVD_TB_SCHEMA_VERSION;
      return -1;
    }
  }

  if (pBlock->sversion > sversion) {  // may need to update table schema
    if (pBlock->schemaLen > 0) {
      tsdbDebug(
          "vgId:%d table %s tid %d uid %" PRIu64 " schema version %d is out of data, client version %d, update...",
          REPO_ID(pRepo), TABLE_CHAR_NAME(pTable), TABLE_TID(pTable), TABLE_UID(pTable), sversion, pBlock->sversion);
      ASSERT(pBlock->schemaLen % sizeof(STColumn) == 0);
      int       numOfCols = pBlock->schemaLen / sizeof(STColumn);
      STColumn *pTCol = (STColumn *)pBlock->data;

      STSchemaBuilder schemaBuilder = {0};
      if (tdInitTSchemaBuilder(&schemaBuilder, pBlock->sversion) < 0) {
        terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
        tsdbError("vgId:%d failed to update schema of table %s since %s", REPO_ID(pRepo), TABLE_CHAR_NAME(pTable),
                  tstrerror(terrno));
        return -1;
      }

      for (int i = 0; i < numOfCols; i++) {
        if (tdAddColToSchema(&schemaBuilder, pTCol[i].type, htons(pTCol[i].colId), htons(pTCol[i].bytes)) < 0) {
          terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
          tsdbError("vgId:%d failed to update schema of table %s since %s", REPO_ID(pRepo), TABLE_CHAR_NAME(pTable),
                    tstrerror(terrno));
          tdDestroyTSchemaBuilder(&schemaBuilder);
          return -1;
        }
      }

      STSchema *pNSchema = tdGetSchemaFromBuilder(&schemaBuilder);
      if (pNSchema == NULL) {
        terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
        tdDestroyTSchemaBuilder(&schemaBuilder);
        return -1;
      }

      tdDestroyTSchemaBuilder(&schemaBuilder);
      tsdbUpdateTableSchema(pRepo, pTable, pNSchema, true);
    } else {
      tsdbDebug(
          "vgId:%d table %s tid %d uid %" PRIu64 " schema version %d is out of data, client version %d, reconfigure...",
          REPO_ID(pRepo), TABLE_CHAR_NAME(pTable), TABLE_TID(pTable), TABLE_UID(pTable), sversion, pBlock->sversion);
      terrno = TSDB_CODE_TDB_TABLE_RECONFIGURE;
      return -1;
    }
  } else {
    ASSERT(pBlock->sversion >= 0);
    if (tsdbGetTableSchemaImpl(pTable, false, false, pBlock->sversion, -1) == NULL) {
      tsdbError("vgId:%d invalid submit schema version %d to table %s tid %d from client", REPO_ID(pRepo),
                pBlock->sversion, TABLE_CHAR_NAME(pTable), TABLE_TID(pTable));
      terrno = TSDB_CODE_TDB_IVD_TB_SCHEMA_VERSION;
      return -1;
    }
  }

  return 0;
}

C
Cary Xu 已提交
984
static void updateTableLatestColumn(STsdbRepo *pRepo, STable *pTable, STSRow* row) {
H
more  
Hongze Cheng 已提交
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 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
  tsdbDebug("vgId:%d updateTableLatestColumn, %s row version:%d", REPO_ID(pRepo), pTable->name->data,
            memRowVersion(row));

  STSchema* pSchema = tsdbGetTableLatestSchema(pTable);
  if (tsdbUpdateLastColSchema(pTable, pSchema) < 0) {
    return;
  }

  pSchema = tsdbGetTableSchemaByVersion(pTable, memRowVersion(row), (int8_t)memRowType(row));
  if (pSchema == NULL) {
    return;
  }

  SDataCol *pLatestCols = pTable->lastCols;
  int32_t kvIdx = 0;

  for (int16_t j = 0; j < schemaNCols(pSchema); j++) {
    STColumn *pTCol = schemaColAt(pSchema, j);
    // ignore not exist colId
    int16_t idx = tsdbGetLastColumnsIndexByColId(pTable, pTCol->colId);
    if (idx == -1) {
      continue;
    }

    void *value = NULL;

    value = tdGetMemRowDataOfColEx(row, pTCol->colId, (int8_t)pTCol->type,
                                   TD_DATA_ROW_HEAD_SIZE + pSchema->columns[j].offset, &kvIdx);

    if ((value == NULL) || isNull(value, pTCol->type)) {
      continue;
    }
    // lock
    TSDB_WLOCK_TABLE(pTable); 
    SDataCol *pDataCol = &(pLatestCols[idx]);
    if (pDataCol->pData == NULL) {
wafwerar's avatar
wafwerar 已提交
1021
      pDataCol->pData = taosMemoryMalloc(pTCol->bytes);
H
more  
Hongze Cheng 已提交
1022 1023
      pDataCol->bytes = pTCol->bytes;
    } else if (pDataCol->bytes < pTCol->bytes) {
wafwerar's avatar
wafwerar 已提交
1024
      pDataCol->pData = taosMemoryRealloc(pDataCol->pData, pTCol->bytes);
H
more  
Hongze Cheng 已提交
1025 1026 1027 1028 1029 1030 1031 1032
      pDataCol->bytes = pTCol->bytes;
    }
    // the actual value size
    uint16_t bytes = IS_VAR_DATA_TYPE(pTCol->type) ? varDataTLen(value) : pTCol->bytes;
    // the actual data size CANNOT larger than column size
    assert(pTCol->bytes >= bytes);
    memcpy(pDataCol->pData, value, bytes);
    //tsdbInfo("updateTableLatestColumn vgId:%d cache column %d for %d,%s", REPO_ID(pRepo), j, pDataCol->bytes, (char*)pDataCol->pData);
C
Cary Xu 已提交
1033
    pDataCol->ts = TD_ROW_KEY(row);
H
more  
Hongze Cheng 已提交
1034 1035 1036 1037 1038
    // unlock
    TSDB_WUNLOCK_TABLE(pTable); 
  }
}

C
Cary Xu 已提交
1039
static int tsdbUpdateTableLatestInfo(STsdbRepo *pRepo, STable *pTable, STSRow* row) {
H
more  
Hongze Cheng 已提交
1040 1041 1042 1043
  STsdbCfg *pCfg = &pRepo->config;

  // if cacheLastRow config has been reset, free the lastRow
  if (!pCfg->cacheLastRow && pTable->lastRow != NULL) {
C
Cary Xu 已提交
1044
    STSRow* cachedLastRow = pTable->lastRow;
H
more  
Hongze Cheng 已提交
1045 1046 1047 1048 1049 1050
    TSDB_WLOCK_TABLE(pTable);
    pTable->lastRow = NULL;
    TSDB_WUNLOCK_TABLE(pTable);
    taosTZfree(cachedLastRow);
  }

C
Cary Xu 已提交
1051
  if (tsdbGetTableLastKeyImpl(pTable) <= TD_ROW_KEY(row)) {
H
more  
Hongze Cheng 已提交
1052
    if (CACHE_LAST_ROW(pCfg) || pTable->lastRow != NULL) {
C
Cary Xu 已提交
1053 1054 1055 1056
      STSRow* nrow = pTable->lastRow;
      if (taosTSizeof(nrow) < TD_ROW_LEN(row)) {
        STSRow* orow = nrow;
        nrow = taosTMalloc(TD_ROW_LEN(row));
H
more  
Hongze Cheng 已提交
1057 1058 1059 1060 1061 1062 1063
        if (nrow == NULL) {
          terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
          return -1;
        }

        memRowCpy(nrow, row);
        TSDB_WLOCK_TABLE(pTable);
C
Cary Xu 已提交
1064
        pTable->lastKey = TD_ROW_KEY(row);
H
more  
Hongze Cheng 已提交
1065 1066 1067 1068 1069
        pTable->lastRow = nrow;
        TSDB_WUNLOCK_TABLE(pTable);
        taosTZfree(orow);
      } else {
        TSDB_WLOCK_TABLE(pTable);
C
Cary Xu 已提交
1070
        pTable->lastKey = TD_ROW_KEY(row);
H
more  
Hongze Cheng 已提交
1071 1072 1073 1074
        memRowCpy(nrow, row);
        TSDB_WUNLOCK_TABLE(pTable);
      }
    } else {
C
Cary Xu 已提交
1075
      pTable->lastKey = TD_ROW_KEY(row);
H
more  
Hongze Cheng 已提交
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
    }

    if (CACHE_LAST_NULL_COLUMN(pCfg)) {
      updateTableLatestColumn(pRepo, pTable, row);
    }
  }

  pTable->cacheLastConfigVersion = pRepo->cacheLastConfigVersion;

  return 0;
}

#endif