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

#include "tsdb.h"
#include "tsdbMain.h"

#define TSDB_DATA_SKIPLIST_LEVEL 5
20
#define TSDB_MAX_INSERT_BATCH 512
H
TD-353  
Hongze Cheng 已提交
21

H
TD-987  
Hongze Cheng 已提交
22
static SMemTable * tsdbNewMemTable(STsdbRepo *pRepo);
H
TD-353  
Hongze Cheng 已提交
23 24 25 26
static void        tsdbFreeMemTable(SMemTable *pMemTable);
static STableData *tsdbNewTableData(STsdbCfg *pCfg, STable *pTable);
static void        tsdbFreeTableData(STableData *pTableData);
static char *      tsdbGetTsTupleKey(const void *data);
H
TD-987  
Hongze Cheng 已提交
27
static int          tsdbAdjustMemMaxTables(SMemTable *pMemTable, int maxTables);
H
TD-1548  
Hongze Cheng 已提交
28
static int          tsdbAppendTableRowToCols(STable *pTable, SDataCols *pCols, STSchema **ppSchema, SDataRow row);
H
Hongze Cheng 已提交
29 30
static int          tsdbInitSubmitBlkIter(SSubmitBlk *pBlock, SSubmitBlkIter *pIter);
static SDataRow     tsdbGetSubmitBlkNext(SSubmitBlkIter *pIter);
H
Hongze Cheng 已提交
31 32 33 34 35 36 37
static int          tsdbScanAndConvertSubmitMsg(STsdbRepo *pRepo, SSubmitMsg *pMsg);
static int          tsdbInsertDataToTable(STsdbRepo *pRepo, SSubmitBlk *pBlock, int32_t *affectedrows);
static int          tsdbCopyRowToMem(STsdbRepo *pRepo, SDataRow row, STable *pTable, void **ppRow);
static int          tsdbInitSubmitMsgIter(SSubmitMsg *pMsg, SSubmitMsgIter *pIter);
static int          tsdbGetSubmitMsgNext(SSubmitMsgIter *pIter, SSubmitBlk **pPBlock);
static int          tsdbCheckTableSchema(STsdbRepo *pRepo, SSubmitBlk *pBlock, STable *pTable);
static int          tsdbInsertDataToTableImpl(STsdbRepo *pRepo, STable *pTable, void **rows, int rowCounter);
H
Hongze Cheng 已提交
38
static void         tsdbFreeRows(STsdbRepo *pRepo, void **rows, int rowCounter);
39
static int          tsdbUpdateTableLatestInfo(STsdbRepo *pRepo, STable *pTable, SDataRow row);
H
Hongze Cheng 已提交
40 41 42

static FORCE_INLINE int tsdbCheckRowRange(STsdbRepo *pRepo, STable *pTable, SDataRow row, TSKEY minKey, TSKEY maxKey,
                                          TSKEY now);
H
TD-353  
Hongze Cheng 已提交
43

H
Hongze Cheng 已提交
44 45 46 47 48
int32_t tsdbInsertData(TSDB_REPO_T *repo, SSubmitMsg *pMsg, SShellSubmitRspMsg *pRsp) {
  STsdbRepo *    pRepo = (STsdbRepo *)repo;
  SSubmitMsgIter msgIter = {0};
  SSubmitBlk *   pBlock = NULL;
  int32_t        affectedrows = 0;
H
TD-1548  
Hongze Cheng 已提交
49

H
Hongze Cheng 已提交
50 51 52
  if (tsdbScanAndConvertSubmitMsg(pRepo, pMsg) < 0) {
    if (terrno != TSDB_CODE_TDB_TABLE_RECONFIGURE) {
      tsdbError("vgId:%d failed to insert data since %s", REPO_ID(pRepo), tstrerror(terrno));
H
TD-1548  
Hongze Cheng 已提交
53
    }
H
TD-353  
Hongze Cheng 已提交
54 55
    return -1;
  }
H
Hongze Cheng 已提交
56

H
Hongze Cheng 已提交
57 58 59 60 61
  tsdbInitSubmitMsgIter(pMsg, &msgIter);
  while (true) {
    tsdbGetSubmitMsgNext(&msgIter, &pBlock);
    if (pBlock == NULL) break;
    if (tsdbInsertDataToTable(pRepo, pBlock, &affectedrows) < 0) {
H
TD-353  
Hongze Cheng 已提交
62 63
      return -1;
    }
H
TD-353  
Hongze Cheng 已提交
64
  }
H
TD-353  
Hongze Cheng 已提交
65

H
Hongze Cheng 已提交
66
  if (pRsp != NULL) pRsp->affectedRows = htonl(affectedrows);
H
TD-353  
Hongze Cheng 已提交
67

H
Hongze Cheng 已提交
68
  if (tsdbCheckCommit(pRepo) < 0) return -1;
H
TD-353  
Hongze Cheng 已提交
69 70 71
  return 0;
}

H
Hongze Cheng 已提交
72
// ---------------- INTERNAL FUNCTIONS ----------------
H
TD-353  
Hongze Cheng 已提交
73
int tsdbRefMemTable(STsdbRepo *pRepo, SMemTable *pMemTable) {
H
TD-353  
Hongze Cheng 已提交
74
  if (pMemTable == NULL) return 0;
H
Hui Li 已提交
75 76
  int ref = T_REF_INC(pMemTable);
	tsdbDebug("vgId:%d ref memtable %p ref %d", REPO_ID(pRepo), pMemTable, ref);
H
TD-353  
Hongze Cheng 已提交
77
  return 0;
H
TD-353  
Hongze Cheng 已提交
78 79 80 81
}

// Need to lock the repository
int tsdbUnRefMemTable(STsdbRepo *pRepo, SMemTable *pMemTable) {
H
TD-353  
Hongze Cheng 已提交
82
  if (pMemTable == NULL) return 0;
H
TD-353  
Hongze Cheng 已提交
83

H
Hui Li 已提交
84 85 86
	int ref = T_REF_DEC(pMemTable);
	tsdbDebug("vgId:%d unref memtable %p ref %d", REPO_ID(pRepo), pMemTable, ref);
  if (ref == 0) {
H
TD-353  
Hongze Cheng 已提交
87 88 89
    STsdbBufPool *pBufPool = pRepo->pPool;

    SListNode *pNode = NULL;
H
TD-353  
Hongze Cheng 已提交
90
    if (tsdbLockRepo(pRepo) < 0) return -1;
H
TD-353  
Hongze Cheng 已提交
91 92
    while ((pNode = tdListPopHead(pMemTable->bufBlockList)) != NULL) {
      tdListAppendNode(pBufPool->bufBlockList, pNode);
H
TD-353  
Hongze Cheng 已提交
93 94 95
    }
    int code = pthread_cond_signal(&pBufPool->poolNotEmpty);
    if (code != 0) {
H
Hongze Cheng 已提交
96
      if (tsdbUnlockRepo(pRepo) < 0) return -1;
H
TD-353  
Hongze Cheng 已提交
97 98 99
      tsdbError("vgId:%d failed to signal pool not empty since %s", REPO_ID(pRepo), strerror(code));
      terrno = TAOS_SYSTEM_ERROR(code);
      return -1;
H
TD-353  
Hongze Cheng 已提交
100
    }
H
TD-353  
Hongze Cheng 已提交
101
    if (tsdbUnlockRepo(pRepo) < 0) return -1;
H
TD-353  
Hongze Cheng 已提交
102

H
TD-987  
Hongze Cheng 已提交
103
    for (int i = 0; i < pMemTable->maxTables; i++) {
H
TD-353  
Hongze Cheng 已提交
104 105 106 107 108 109 110 111 112 113 114 115
      if (pMemTable->tData[i] != NULL) {
        tsdbFreeTableData(pMemTable->tData[i]);
      }
    }

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

H
TD-353  
Hongze Cheng 已提交
116 117 118 119
int tsdbTakeMemSnapshot(STsdbRepo *pRepo, SMemTable **pMem, SMemTable **pIMem) {
  if (tsdbLockRepo(pRepo) < 0) return -1;

  *pMem = pRepo->mem;
H
TD-353  
Hongze Cheng 已提交
120
  *pIMem = pRepo->imem;
H
TD-353  
Hongze Cheng 已提交
121 122 123 124
  tsdbRefMemTable(pRepo, *pMem);
  tsdbRefMemTable(pRepo, *pIMem);

  if (tsdbUnlockRepo(pRepo) < 0) return -1;
H
TD-353  
Hongze Cheng 已提交
125

H
TD-987  
Hongze Cheng 已提交
126 127 128
  if (*pMem != NULL) taosRLockLatch(&((*pMem)->latch));

  tsdbDebug("vgId:%d take memory snapshot, pMem %p pIMem %p", REPO_ID(pRepo), *pMem, *pIMem);
H
TD-353  
Hongze Cheng 已提交
129
  return 0;
H
TD-353  
Hongze Cheng 已提交
130 131
}

H
TD-987  
Hongze Cheng 已提交
132
void tsdbUnTakeMemSnapShot(STsdbRepo *pRepo, SMemTable *pMem, SMemTable *pIMem) {
H
Hongze Cheng 已提交
133 134
  tsdbDebug("vgId:%d untake memory snapshot, pMem %p pIMem %p", REPO_ID(pRepo), pMem, pIMem);

H
TD-987  
Hongze Cheng 已提交
135 136 137 138 139 140 141 142 143 144
  if (pMem != NULL) {
    taosRUnLockLatch(&(pMem->latch));
    tsdbUnRefMemTable(pRepo, pMem);
  }

  if (pIMem != NULL) {
    tsdbUnRefMemTable(pRepo, pIMem);
  }
}

H
TD-353  
Hongze Cheng 已提交
145
void *tsdbAllocBytes(STsdbRepo *pRepo, int bytes) {
H
TD-353  
Hongze Cheng 已提交
146
  STsdbCfg *     pCfg = &pRepo->config;
H
Hongze Cheng 已提交
147 148
  STsdbBufBlock *pBufBlock = NULL;
  void *         ptr = NULL;
H
TD-353  
Hongze Cheng 已提交
149

H
Hongze Cheng 已提交
150
  // Either allocate from buffer blocks or from SYSTEM memory pool
H
TD-353  
Hongze Cheng 已提交
151
  if (pRepo->mem == NULL) {
H
TD-987  
Hongze Cheng 已提交
152
    SMemTable *pMemTable = tsdbNewMemTable(pRepo);
H
TD-353  
Hongze Cheng 已提交
153
    if (pMemTable == NULL) return NULL;
H
Hongze Cheng 已提交
154 155
    pRepo->mem = pMemTable;
  }
H
TD-353  
Hongze Cheng 已提交
156

H
Hongze Cheng 已提交
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
  ASSERT(pRepo->mem != NULL);

  pBufBlock = tsdbGetCurrBufBlock(pRepo);
  if ((pRepo->mem->extraBuffList != NULL) ||
      ((listNEles(pRepo->mem->bufBlockList) >= pCfg->totalBlocks / 3) && (pBufBlock->remain < bytes))) {
    // allocate from SYSTEM buffer pool
    if (pRepo->mem->extraBuffList == NULL) {
      pRepo->mem->extraBuffList = tdListNew(0);
      if (pRepo->mem->extraBuffList == NULL) {
        terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
        return NULL;
      }
    }

    ASSERT(pRepo->mem->extraBuffList != NULL);
    SListNode *pNode = (SListNode *)malloc(sizeof(SListNode) + bytes);
    if (pNode == NULL) {
H
Hongze Cheng 已提交
174 175 176 177
      if (listNEles(pRepo->mem->extraBuffList) == 0) {
        tdListFree(pRepo->mem->extraBuffList);
        pRepo->mem->extraBuffList = NULL;
      }
H
Hongze Cheng 已提交
178
      terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
H
TD-353  
Hongze Cheng 已提交
179 180 181
      return NULL;
    }

H
Hongze Cheng 已提交
182
    pNode->next = pNode->prev = NULL;
H
Hongze Cheng 已提交
183
    tdListAppendNode(pRepo->mem->extraBuffList, pNode);
H
Hongze Cheng 已提交
184 185 186 187 188 189 190 191 192 193 194
    ptr = (void *)(pNode->data);
    tsdbTrace("vgId:%d allocate %d bytes from SYSTEM buffer block", REPO_ID(pRepo), bytes);
  } else {  // allocate from TSDB buffer pool
    if (pBufBlock == NULL || pBufBlock->remain < bytes) {
      ASSERT(listNEles(pRepo->mem->bufBlockList) < pCfg->totalBlocks / 3);
      if (tsdbLockRepo(pRepo) < 0) return NULL;
      SListNode *pNode = tsdbAllocBufBlockFromPool(pRepo);
      tdListAppendNode(pRepo->mem->bufBlockList, pNode);
      if (tsdbUnlockRepo(pRepo) < 0) return NULL;
      pBufBlock = tsdbGetCurrBufBlock(pRepo);
    }
H
TD-353  
Hongze Cheng 已提交
195

H
Hongze Cheng 已提交
196 197 198 199 200 201
    ASSERT(pBufBlock->remain >= bytes);
    ptr = POINTER_SHIFT(pBufBlock->data, pBufBlock->offset);
    pBufBlock->offset += bytes;
    pBufBlock->remain -= bytes;
    tsdbTrace("vgId:%d allocate %d bytes from TSDB buffer block, nBlocks %d offset %d remain %d", REPO_ID(pRepo), bytes,
              listNEles(pRepo->mem->bufBlockList), pBufBlock->offset, pBufBlock->remain);
H
TD-353  
Hongze Cheng 已提交
202 203 204 205 206
  }

  return ptr;
}

H
TD-353  
Hongze Cheng 已提交
207
int tsdbAsyncCommit(STsdbRepo *pRepo) {
H
Hongze Cheng 已提交
208 209
  if (pRepo->mem == NULL) return 0;

F
freemine 已提交
210
  tsem_wait(&(pRepo->readyToCommit));
H
Hongze Cheng 已提交
211

H
Hongze Cheng 已提交
212 213
  ASSERT(pRepo->imem == NULL);

H
Hongze Cheng 已提交
214 215 216 217
  if (pRepo->code != TSDB_CODE_SUCCESS) {
    tsdbWarn("vgId:%d try to commit when TSDB not in good state: %s", REPO_ID(pRepo), tstrerror(terrno));
  }

218
  if (pRepo->appH.notifyStatus) pRepo->appH.notifyStatus(pRepo->appH.appH, TSDB_STATUS_COMMIT_START, TSDB_CODE_SUCCESS);
H
Hongze Cheng 已提交
219 220 221 222 223
  if (tsdbLockRepo(pRepo) < 0) return -1;
  pRepo->imem = pRepo->mem;
  pRepo->mem = NULL;
  tsdbScheduleCommit(pRepo);
  if (tsdbUnlockRepo(pRepo) < 0) return -1;
H
TD-353  
Hongze Cheng 已提交
224 225 226 227

  return 0;
}

H
Hongze Cheng 已提交
228 229
int tsdbSyncCommit(TSDB_REPO_T *repo) {
  STsdbRepo *pRepo = (STsdbRepo *)repo;
H
Hongze Cheng 已提交
230

H
Hongze Cheng 已提交
231
  tsdbAsyncCommit(pRepo);
F
freemine 已提交
232 233
  tsem_wait(&(pRepo->readyToCommit));
  tsem_post(&(pRepo->readyToCommit));
H
Hongze Cheng 已提交
234 235 236 237 238 239 240 241

  if (pRepo->code != TSDB_CODE_SUCCESS) {
    terrno = pRepo->code;
    return -1;
  } else {
    terrno = TSDB_CODE_SUCCESS;
    return 0;
  }
H
Hongze Cheng 已提交
242 243
}

H
TD-1548  
Hongze Cheng 已提交
244 245 246 247 248 249 250 251 252
/**
 * 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
 * 
H
Hongze Cheng 已提交
253
 * The function tries to procceed AS MUSH AS POSSIBLE.
H
TD-1548  
Hongze Cheng 已提交
254
 */
H
Hongze Cheng 已提交
255
int tsdbLoadDataFromCache(STable *pTable, SSkipListIterator *pIter, TSKEY maxKey, int maxRowsToRead, SDataCols *pCols,
H
TD-1548  
Hongze Cheng 已提交
256 257
                          TKEY *filterKeys, int nFilterKeys, bool keepDup, SMergeInfo *pMergeInfo) {
  ASSERT(maxRowsToRead > 0 && nFilterKeys >= 0 && pMergeInfo != NULL);
H
Hongze Cheng 已提交
258 259
  if (pIter == NULL) return 0;
  STSchema *pSchema = NULL;
H
TD-1548  
Hongze Cheng 已提交
260 261 262
  TSKEY     rowKey = 0;
  TSKEY     fKey = 0;
  bool      isRowDel = false;
H
Hongze Cheng 已提交
263
  int       filterIter = 0;
H
TD-1548  
Hongze Cheng 已提交
264 265 266 267 268
  SDataRow  row = NULL;

  memset(pMergeInfo, 0, sizeof(*pMergeInfo));
  pMergeInfo->keyFirst = INT64_MAX;
  pMergeInfo->keyLast = INT64_MIN;
H
Hongze Cheng 已提交
269
  if (pCols) tdResetDataCols(pCols);
H
TD-1548  
Hongze Cheng 已提交
270 271 272 273

  row = tsdbNextIterRow(pIter);
  if (row == NULL || dataRowKey(row) > maxKey) {
    rowKey = INT64_MAX;
H
Hongze Cheng 已提交
274
    isRowDel = false;
H
TD-1548  
Hongze Cheng 已提交
275 276 277 278 279
  } else {
    rowKey = dataRowKey(row);
    isRowDel = dataRowDeleted(row);
  }

H
Hongze Cheng 已提交
280
  if (filterIter >= nFilterKeys) {
H
TD-1548  
Hongze Cheng 已提交
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
    fKey = INT64_MAX;
  } else {
    fKey = tdGetKey(filterKeys[filterIter]);
  }

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

    if (fKey < rowKey) {
      pMergeInfo->keyFirst = MIN(pMergeInfo->keyFirst, fKey);
      pMergeInfo->keyLast = MAX(pMergeInfo->keyLast, fKey);

      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++;
        pMergeInfo->keyFirst = MIN(pMergeInfo->keyFirst, rowKey);
        pMergeInfo->keyLast = MAX(pMergeInfo->keyLast, rowKey);
        tsdbAppendTableRowToCols(pTable, pCols, &pSchema, row);
      }
H
Hongze Cheng 已提交
311

H
TD-1548  
Hongze Cheng 已提交
312 313 314 315
      tSkipListIterNext(pIter);
      row = tsdbNextIterRow(pIter);
      if (row == NULL || dataRowKey(row) > maxKey) {
        rowKey = INT64_MAX;
H
Hongze Cheng 已提交
316
        isRowDel = false;
H
TD-1548  
Hongze Cheng 已提交
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
      } else {
        rowKey = dataRowKey(row);
        isRowDel = dataRowDeleted(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++;
          pMergeInfo->keyFirst = MIN(pMergeInfo->keyFirst, rowKey);
          pMergeInfo->keyLast = MAX(pMergeInfo->keyLast, rowKey);
          tsdbAppendTableRowToCols(pTable, pCols, &pSchema, row);
H
Hongze Cheng 已提交
336
        } else {
H
TD-1548  
Hongze Cheng 已提交
337 338
          pMergeInfo->keyFirst = MIN(pMergeInfo->keyFirst, fKey);
          pMergeInfo->keyLast = MAX(pMergeInfo->keyLast, fKey);
H
Hongze Cheng 已提交
339 340
        }
      }
H
TD-1438  
Hongze Cheng 已提交
341

H
TD-1548  
Hongze Cheng 已提交
342 343 344 345
      tSkipListIterNext(pIter);
      row = tsdbNextIterRow(pIter);
      if (row == NULL || dataRowKey(row) > maxKey) {
        rowKey = INT64_MAX;
H
Hongze Cheng 已提交
346
        isRowDel = false;
H
TD-1548  
Hongze Cheng 已提交
347 348 349 350
      } else {
        rowKey = dataRowKey(row);
        isRowDel = dataRowDeleted(row);
      }
H
Hongze Cheng 已提交
351

H
TD-1548  
Hongze Cheng 已提交
352 353 354 355 356
      filterIter++;
      if (filterIter >= nFilterKeys) {
        fKey = INT64_MAX;
      } else {
        fKey = tdGetKey(filterKeys[filterIter]);
H
Hongze Cheng 已提交
357
      }
H
TD-1548  
Hongze Cheng 已提交
358 359
    }
  }
H
Hongze Cheng 已提交
360

H
TD-1548  
Hongze Cheng 已提交
361
  return 0;
H
Hongze Cheng 已提交
362 363
}

H
TD-353  
Hongze Cheng 已提交
364
// ---------------- LOCAL FUNCTIONS ----------------
H
TD-987  
Hongze Cheng 已提交
365 366 367
static SMemTable* tsdbNewMemTable(STsdbRepo *pRepo) {
  STsdbMeta *pMeta = pRepo->tsdbMeta;

H
TD-353  
Hongze Cheng 已提交
368 369 370 371 372 373 374 375 376 377
  SMemTable *pMemTable = (SMemTable *)calloc(1, sizeof(*pMemTable));
  if (pMemTable == NULL) {
    terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
    goto _err;
  }

  pMemTable->keyFirst = INT64_MAX;
  pMemTable->keyLast = 0;
  pMemTable->numOfRows = 0;

H
TD-987  
Hongze Cheng 已提交
378 379
  pMemTable->maxTables = pMeta->maxTables;
  pMemTable->tData = (STableData **)calloc(pMemTable->maxTables, sizeof(STableData *));
H
TD-353  
Hongze Cheng 已提交
380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410
  if (pMemTable->tData == NULL) {
    terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
    goto _err;
  }

  pMemTable->actList = tdListNew(0);
  if (pMemTable->actList == NULL) {
    terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
    goto _err;
  }

  pMemTable->bufBlockList = tdListNew(sizeof(STsdbBufBlock*));
  if (pMemTable->bufBlockList == NULL) {
    terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
    goto _err;
  }

  T_REF_INC(pMemTable);

  return pMemTable;

_err:
  tsdbFreeMemTable(pMemTable);
  return NULL;
}

static void tsdbFreeMemTable(SMemTable* pMemTable) {
  if (pMemTable) {
    ASSERT((pMemTable->bufBlockList == NULL) ? true : (listNEles(pMemTable->bufBlockList) == 0));
    ASSERT((pMemTable->actList == NULL) ? true : (listNEles(pMemTable->actList) == 0));

H
Hongze Cheng 已提交
411
    tdListFree(pMemTable->extraBuffList);
H
TD-353  
Hongze Cheng 已提交
412 413
    tdListFree(pMemTable->bufBlockList);
    tdListFree(pMemTable->actList);
S
TD-1848  
Shengliang Guan 已提交
414
    tfree(pMemTable->tData);
H
TD-353  
Hongze Cheng 已提交
415 416 417 418 419 420 421 422 423 424 425
    free(pMemTable);
  }
}

static STableData *tsdbNewTableData(STsdbCfg *pCfg, STable *pTable) {
  STableData *pTableData = (STableData *)calloc(1, sizeof(*pTableData));
  if (pTableData == NULL) {
    terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
    goto _err;
  }

H
TD-353  
Hongze Cheng 已提交
426
  pTableData->uid = TABLE_UID(pTable);
H
TD-353  
Hongze Cheng 已提交
427 428 429 430
  pTableData->keyFirst = INT64_MAX;
  pTableData->keyLast = 0;
  pTableData->numOfRows = 0;

H
TD-1438  
Hongze Cheng 已提交
431 432
  pTableData->pData =
      tSkipListCreate(TSDB_DATA_SKIPLIST_LEVEL, TSDB_DATA_TYPE_TIMESTAMP, TYPE_BYTES[TSDB_DATA_TYPE_TIMESTAMP],
H
TD-1548  
Hongze Cheng 已提交
433
                      tkeyComparFn, pCfg->update ? SL_UPDATE_DUP_KEY : SL_DISCARD_DUP_KEY, tsdbGetTsTupleKey);
H
TD-353  
Hongze Cheng 已提交
434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
  if (pTableData->pData == NULL) {
    terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
    goto _err;
  }

  return pTableData;

_err:
  tsdbFreeTableData(pTableData);
  return NULL;
}

static void tsdbFreeTableData(STableData *pTableData) {
  if (pTableData) {
    tSkipListDestroy(pTableData->pData);
    free(pTableData);
  }
H
TD-353  
Hongze Cheng 已提交
451 452
}

H
TD-1194  
Hongze Cheng 已提交
453
static char *tsdbGetTsTupleKey(const void *data) { return dataRowTuple((SDataRow)data); }
H
TD-353  
Hongze Cheng 已提交
454

455
void tsdbGetFidKeyRange(int daysPerFile, int8_t precision, int fileId, TSKEY *minKey, TSKEY *maxKey) {
H
TD-353  
Hongze Cheng 已提交
456 457
  *minKey = fileId * daysPerFile * tsMsPerDay[precision];
  *maxKey = *minKey + daysPerFile * tsMsPerDay[precision] - 1;
H
TD-353  
Hongze Cheng 已提交
458 459
}

H
TD-987  
Hongze Cheng 已提交
460 461 462 463 464 465 466 467
static int tsdbAdjustMemMaxTables(SMemTable *pMemTable, int maxTables) {
  ASSERT(pMemTable->maxTables < maxTables);

  STableData **pTableData = (STableData **)calloc(maxTables, sizeof(STableData *));
  if (pTableData == NULL) {
    terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
    return -1;
  }
H
fix bug  
Hongze Cheng 已提交
468
  memcpy((void *)pTableData, (void *)pMemTable->tData, sizeof(STableData *) * pMemTable->maxTables);
H
TD-987  
Hongze Cheng 已提交
469 470 471 472 473 474 475 476

  STableData **tData = pMemTable->tData;

  taosWLockLatch(&(pMemTable->latch));
  pMemTable->maxTables = maxTables;
  pMemTable->tData = pTableData;
  taosWUnLockLatch(&(pMemTable->latch));

S
TD-1848  
Shengliang Guan 已提交
477
  tfree(tData);
H
TD-987  
Hongze Cheng 已提交
478

H
TD-1548  
Hongze Cheng 已提交
479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
  return 0;
}

static int tsdbAppendTableRowToCols(STable *pTable, SDataCols *pCols, STSchema **ppSchema, SDataRow row) {
  if (pCols) {
    if (*ppSchema == NULL || schemaVersion(*ppSchema) != dataRowVersion(row)) {
      *ppSchema = tsdbGetTableSchemaImpl(pTable, false, false, dataRowVersion(row));
      if (*ppSchema == NULL) {
        ASSERT(false);
        return -1;
      }
    }

    tdAppendDataRowToDataCol(row, *ppSchema, pCols);
  }

H
Hongze Cheng 已提交
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
  return 0;
}

static int tsdbInitSubmitBlkIter(SSubmitBlk *pBlock, SSubmitBlkIter *pIter) {
  if (pBlock->dataLen <= 0) return -1;
  pIter->totalLen = pBlock->dataLen;
  pIter->len = 0;
  pIter->row = (SDataRow)(pBlock->data+pBlock->schemaLen);
  return 0;
}

static SDataRow tsdbGetSubmitBlkNext(SSubmitBlkIter *pIter) {
  SDataRow row = pIter->row;
  if (row == NULL) return NULL;

  pIter->len += dataRowLen(row);
  if (pIter->len >= pIter->totalLen) {
    pIter->row = NULL;
  } else {
    pIter->row = (char *)row + dataRowLen(row);
  }

  return row;
}

static FORCE_INLINE int tsdbCheckRowRange(STsdbRepo *pRepo, STable *pTable, SDataRow row, TSKEY minKey, TSKEY maxKey,
                                          TSKEY now) {
  if (dataRowKey(row) < minKey || dataRowKey(row) > 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,
              dataRowKey(row));
    terrno = TSDB_CODE_TDB_TIMESTAMP_OUT_OF_RANGE;
    return -1;
  }

H
Hongze Cheng 已提交
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 603 604 605 606 607 608
  return 0;
}

static int tsdbScanAndConvertSubmitMsg(STsdbRepo *pRepo, SSubmitMsg *pMsg) {
  ASSERT(pMsg != NULL);
  STsdbMeta *    pMeta = pRepo->tsdbMeta;
  SSubmitMsgIter msgIter = {0};
  SSubmitBlk *   pBlock = NULL;
  SSubmitBlkIter blkIter = {0};
  SDataRow       row = NULL;
  TSKEY          now = taosGetTimestamp(pRepo->config.precision);
  TSKEY          minKey = now - tsMsPerDay[pRepo->config.precision] * pRepo->config.keep;
  TSKEY          maxKey = now + tsMsPerDay[pRepo->config.precision] * pRepo->config.daysPerFile;

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

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

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

    if (pBlock->tid <= 0 || pBlock->tid >= pMeta->maxTables) {
      tsdbError("vgId:%d failed to get table to insert data, uid %" PRIu64 " tid %d", REPO_ID(pRepo), 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(pRepo), 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(pRepo), TABLE_CHAR_NAME(pTable));
      terrno = TSDB_CODE_TDB_INVALID_ACTION;
      return -1;
    }

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

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

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

static int tsdbInsertDataToTable(STsdbRepo *pRepo, SSubmitBlk *pBlock, int32_t *affectedrows) {
  STsdbMeta *    pMeta = pRepo->tsdbMeta;
  int64_t        points = 0;
  STable *       pTable = NULL;
  SSubmitBlkIter blkIter = {0};
  SDataRow       row = NULL;
609
  void *         rows[TSDB_MAX_INSERT_BATCH] = {0};
H
Hongze Cheng 已提交
610 611 612 613 614 615 616 617 618
  int            rowCounter = 0;

  ASSERT(pBlock->tid < pMeta->maxTables);
  pTable = pMeta->tables[pBlock->tid];
  ASSERT(pTable != NULL && TABLE_UID(pTable) == pBlock->uid);

  tsdbInitSubmitBlkIter(pBlock, &blkIter);
  while ((row = tsdbGetSubmitBlkNext(&blkIter)) != NULL) {
    if (tsdbCopyRowToMem(pRepo, row, pTable, &(rows[rowCounter])) < 0) {
H
Hongze Cheng 已提交
619 620
      tsdbFreeRows(pRepo, rows, rowCounter);
      goto _err;
H
Hongze Cheng 已提交
621 622 623 624 625 626 627 628
    }

    (*affectedrows)++;
    points++;

    if (rows[rowCounter] != NULL) {
      rowCounter++;
    }
629 630 631 632 633 634 635 636 637

    if (rowCounter == TSDB_MAX_INSERT_BATCH) {
      if (tsdbInsertDataToTableImpl(pRepo, pTable, rows, rowCounter) < 0) {
        goto _err;
      }

      rowCounter = 0;
      memset(rows, 0, sizeof(rows));
    }
H
Hongze Cheng 已提交
638 639
  }

640
  if (rowCounter > 0 && tsdbInsertDataToTableImpl(pRepo, pTable, rows, rowCounter) < 0) {
H
Hongze Cheng 已提交
641
    goto _err;
H
Hongze Cheng 已提交
642 643 644 645 646 647 648
  }

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

  return 0;
H
Hongze Cheng 已提交
649 650 651

_err:
  return -1;
H
Hongze Cheng 已提交
652 653 654 655 656 657 658 659 660 661 662 663 664 665 666
}

static int tsdbCopyRowToMem(STsdbRepo *pRepo, SDataRow row, STable *pTable, void **ppRow) {
  STsdbCfg *  pCfg = &pRepo->config;
  TKEY        tkey = dataRowTKey(row);
  TSKEY       key = dataRowKey(row);
  bool        isRowDelete = TKEY_IS_DELETED(tkey);

  if (isRowDelete) {
    if (!pCfg->update) {
      tsdbWarn("vgId:%d vnode is not allowed to update but try to delete a data row", REPO_ID(pRepo));
      terrno = TSDB_CODE_TDB_INVALID_ACTION;
      return -1;
    }

H
Hongze Cheng 已提交
667
    TSKEY lastKey = tsdbGetTableLastKeyImpl(pTable);
668
    if (key > lastKey) {
H
Hongze Cheng 已提交
669
      tsdbTrace("vgId:%d skip to delete row key %" PRId64 " which is larger than table lastKey %" PRId64,
670
                REPO_ID(pRepo), key, lastKey);
H
Hongze Cheng 已提交
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 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 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 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790
      return 0;
    }
  }

  void *pRow = tsdbAllocBytes(pRepo, dataRowLen(row));
  if (pRow == NULL) {
    tsdbError("vgId:%d failed to insert row with key %" PRId64 " to table %s while allocate %d bytes since %s",
              REPO_ID(pRepo), key, TABLE_CHAR_NAME(pTable), dataRowLen(row), tstrerror(terrno));
    return -1;
  }

  dataRowCpy(pRow, row);
  ppRow[0] = pRow;

  tsdbTrace("vgId:%d a row is %s table %s tid %d uid %" PRIu64 " key %" PRIu64, REPO_ID(pRepo),
            isRowDelete ? "deleted from" : "updated in", TABLE_CHAR_NAME(pTable), TABLE_TID(pTable), TABLE_UID(pTable),
            key);

  return 0;
}

static int tsdbInitSubmitMsgIter(SSubmitMsg *pMsg, SSubmitMsgIter *pIter) {
  if (pMsg == NULL) {
    terrno = TSDB_CODE_TDB_SUBMIT_MSG_MSSED_UP;
    return -1;
  }

  pIter->totalLen = pMsg->length;
  pIter->len = 0;
  pIter->pMsg = pMsg;
  if (pMsg->length <= TSDB_SUBMIT_MSG_HEAD_SIZE) {
    terrno = TSDB_CODE_TDB_SUBMIT_MSG_MSSED_UP;
    return -1;
  }

  return 0;
}

static int tsdbGetSubmitMsgNext(SSubmitMsgIter *pIter, SSubmitBlk **pPBlock) {
  if (pIter->len == 0) {
    pIter->len += TSDB_SUBMIT_MSG_HEAD_SIZE;
  } else {
    SSubmitBlk *pSubmitBlk = (SSubmitBlk *)POINTER_SHIFT(pIter->pMsg, pIter->len);
    pIter->len += (sizeof(SSubmitBlk) + pSubmitBlk->dataLen + pSubmitBlk->schemaLen);
  }

  if (pIter->len > pIter->totalLen) {
    terrno = TSDB_CODE_TDB_SUBMIT_MSG_MSSED_UP;
    *pPBlock = NULL;
    return -1;
  }

  *pPBlock = (pIter->len == pIter->totalLen) ? NULL : (SSubmitBlk *)POINTER_SHIFT(pIter->pMsg, pIter->len);

  return 0;
}

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

  STSchema *pSchema = tsdbGetTableSchemaImpl(pTable, false, false, -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) == 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));
H
Hongze Cheng 已提交
791 792
      terrno = TSDB_CODE_TDB_IVD_TB_SCHEMA_VERSION;
      return -1;
H
Hongze Cheng 已提交
793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811
    }
  }

  return 0;
}

static int tsdbInsertDataToTableImpl(STsdbRepo *pRepo, STable *pTable, void **rows, int rowCounter) {
  if (rowCounter < 1) return 0;

  SMemTable * pMemTable = NULL;
  STableData *pTableData = NULL;
  STsdbMeta * pMeta = pRepo->tsdbMeta;
  STsdbCfg *  pCfg = &(pRepo->config);

  ASSERT(pRepo->mem != NULL);
  pMemTable = pRepo->mem;

  if (TABLE_TID(pTable) >= pMemTable->maxTables) {
    if (tsdbAdjustMemMaxTables(pMemTable, pMeta->maxTables) < 0) {
H
Hongze Cheng 已提交
812
      tsdbFreeRows(pRepo, rows, rowCounter);
H
Hongze Cheng 已提交
813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829
      return -1;
    }
  }
  pTableData = pMemTable->tData[TABLE_TID(pTable)];

  if (pTableData == NULL || pTableData->uid != TABLE_UID(pTable)) {
    if (pTableData != NULL) {
      taosWLockLatch(&(pMemTable->latch));
      pMemTable->tData[TABLE_TID(pTable)] = NULL;
      tsdbFreeTableData(pTableData);
      taosWUnLockLatch(&(pMemTable->latch));
    }

    pTableData = tsdbNewTableData(pCfg, pTable);
    if (pTableData == NULL) {
      tsdbError("vgId:%d failed to insert data to table %s uid %" PRId64 " tid %d since %s", REPO_ID(pRepo),
                TABLE_CHAR_NAME(pTable), TABLE_UID(pTable), TABLE_TID(pTable), tstrerror(terrno));
H
Hongze Cheng 已提交
830
      tsdbFreeRows(pRepo, rows, rowCounter);
H
Hongze Cheng 已提交
831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850
      return -1;
    }

    pRepo->mem->tData[TABLE_TID(pTable)] = pTableData;
  }

  ASSERT((pTableData != NULL) && pTableData->uid == TABLE_UID(pTable));

  int64_t osize = SL_SIZE(pTableData->pData);
  tSkipListPutBatch(pTableData->pData, rows, rowCounter);
  int64_t dsize = SL_SIZE(pTableData->pData) - osize;

  if (pMemTable->keyFirst > dataRowKey(rows[0])) pMemTable->keyFirst = dataRowKey(rows[0]);
  if (pMemTable->keyLast < dataRowKey(rows[rowCounter - 1])) pMemTable->keyLast = dataRowKey(rows[rowCounter - 1]);
  pMemTable->numOfRows += dsize;

  if (pTableData->keyFirst > dataRowKey(rows[0])) pTableData->keyFirst = dataRowKey(rows[0]);
  if (pTableData->keyLast < dataRowKey(rows[rowCounter - 1])) pTableData->keyLast = dataRowKey(rows[rowCounter - 1]);
  pTableData->numOfRows += dsize;

851 852 853 854
  // update table latest info
  if (tsdbUpdateTableLatestInfo(pRepo, pTable, rows[rowCounter - 1]) < 0) {
    return -1;
  }
H
Hongze Cheng 已提交
855

H
TD-987  
Hongze Cheng 已提交
856
  return 0;
H
Hongze Cheng 已提交
857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877
}

static void tsdbFreeRows(STsdbRepo *pRepo, void **rows, int rowCounter) {
  ASSERT(pRepo->mem != NULL);
  STsdbBufPool *pBufPool = pRepo->pPool;

  for (int i = rowCounter - 1; i >= 0; --i) {
    SDataRow row = (SDataRow)rows[i];
    int      bytes = (int)dataRowLen(row);

    if (pRepo->mem->extraBuffList == NULL) {
      STsdbBufBlock *pBufBlock = tsdbGetCurrBufBlock(pRepo);
      ASSERT(pBufBlock != NULL && pBufBlock->offset >= bytes);

      pBufBlock->offset -= bytes;
      pBufBlock->remain += bytes;
      ASSERT(row == POINTER_SHIFT(pBufBlock->data, pBufBlock->offset));
      tsdbTrace("vgId:%d free %d bytes to TSDB buffer pool, nBlocks %d offset %d remain %d", REPO_ID(pRepo), bytes,
                listNEles(pRepo->mem->bufBlockList), pBufBlock->offset, pBufBlock->remain);

      if (pBufBlock->offset == 0) {  // return the block to buffer pool
H
Hongze Cheng 已提交
878
        if (tsdbLockRepo(pRepo) < 0) return;
H
Hongze Cheng 已提交
879 880
        SListNode *pNode = tdListPopTail(pRepo->mem->bufBlockList);
        tdListPrependNode(pBufPool->bufBlockList, pNode);
H
Hongze Cheng 已提交
881
        if (tsdbUnlockRepo(pRepo) < 0) return;
H
Hongze Cheng 已提交
882 883 884 885 886 887 888 889 890 891 892 893 894 895
      }
    } else {
      ASSERT(listNEles(pRepo->mem->extraBuffList) > 0);
      SListNode *pNode = tdListPopTail(pRepo->mem->extraBuffList);
      ASSERT(row == pNode->data);
      free(pNode);
      tsdbTrace("vgId:%d free %d bytes to SYSTEM buffer pool", REPO_ID(pRepo), bytes);

      if (listNEles(pRepo->mem->extraBuffList) == 0) {
        tdListFree(pRepo->mem->extraBuffList);
        pRepo->mem->extraBuffList = NULL;
      }
    }
  }
896 897 898 899 900
}

static int tsdbUpdateTableLatestInfo(STsdbRepo *pRepo, STable *pTable, SDataRow row) {
  STsdbCfg *pCfg = &pRepo->config;

H
Hongze Cheng 已提交
901 902
  if (tsdbGetTableLastKeyImpl(pTable) < dataRowKey(row)) {
    if (pCfg->cacheLastRow || pTable->lastRow != NULL) {
903 904 905 906 907 908 909 910 911 912 913
      SDataRow nrow = pTable->lastRow;
      if (taosTSizeof(nrow) < dataRowLen(row)) {
        SDataRow orow = nrow;
        nrow = taosTMalloc(dataRowLen(row));
        if (nrow == NULL) {
          terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
          return -1;
        }

        dataRowCpy(nrow, row);
        TSDB_WLOCK_TABLE(pTable);
H
Hongze Cheng 已提交
914
        pTable->lastKey = dataRowKey(row);
915 916 917 918 919
        pTable->lastRow = nrow;
        TSDB_WUNLOCK_TABLE(pTable);
        taosTZfree(orow);
      } else {
        TSDB_WLOCK_TABLE(pTable);
H
Hongze Cheng 已提交
920
        pTable->lastKey = dataRowKey(row);
921 922 923
        dataRowCpy(nrow, row);
        TSDB_WUNLOCK_TABLE(pTable);
      }
H
Hongze Cheng 已提交
924 925
    } else {
      pTable->lastKey = dataRowKey(row);
926 927 928 929
    }
  }

  return 0;
F
eok  
freemine 已提交
930
}