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

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

H
Hongze Cheng 已提交
18
typedef struct SCommitter SCommitter;
H
more  
Hongze Cheng 已提交
19

H
Hongze Cheng 已提交
20
struct SCommitter {
H
Hongze Cheng 已提交
21 22 23
  STsdb   *pTsdb;
  uint8_t *pBuf1;
  uint8_t *pBuf2;
H
Hongze Cheng 已提交
24
  uint8_t *pBuf3;
H
Hongze Cheng 已提交
25 26
  uint8_t *pBuf4;
  uint8_t *pBuf5;
H
Hongze Cheng 已提交
27
  /* commit data */
H
Hongze Cheng 已提交
28 29 30 31 32 33 34 35 36 37 38 39 40
  int32_t minutes;
  int8_t  precision;
  TSKEY   nextCommitKey;
  // commit file data
  int32_t          commitFid;
  TSKEY            minKey;
  TSKEY            maxKey;
  SDFileSetReader *pReader;
  SDFileSetWriter *pWriter;
  SArray          *aOBlockIdx;
  SArray          *aBlockIdx;
  // commit table data
  SBlockIdx *pBlockIdx;
H
Hongze Cheng 已提交
41
  /* commit del */
H
Hongze Cheng 已提交
42 43
  SDelFReader *pDelFReader;
  SDelFWriter *pDelFWriter;
H
Hongze Cheng 已提交
44 45
  SDelIdx      delIdxOld;
  SDelIdx      delIdxNew;
H
Hongze Cheng 已提交
46 47
  STbData     *pTbData;
  SDelIdxItem *pDelIdxItem;
H
Hongze Cheng 已提交
48 49
  SDelData     delDataOld;
  SDelData     delDataNew;
H
Hongze Cheng 已提交
50
  SDelIdxItem  delIdxItem;
H
Hongze Cheng 已提交
51
  /* commit cache */
H
Hongze Cheng 已提交
52
};
H
refact  
Hongze Cheng 已提交
53

H
Hongze Cheng 已提交
54 55 56 57 58
static int32_t tsdbStartCommit(STsdb *pTsdb, SCommitter *pCommitter);
static int32_t tsdbCommitData(SCommitter *pCommitter);
static int32_t tsdbCommitDel(SCommitter *pCommitter);
static int32_t tsdbCommitCache(SCommitter *pCommitter);
static int32_t tsdbEndCommit(SCommitter *pCommitter, int32_t eno);
H
refact  
Hongze Cheng 已提交
59

H
refact  
Hongze Cheng 已提交
60
int32_t tsdbBegin(STsdb *pTsdb) {
H
Hongze Cheng 已提交
61
  int32_t code = 0;
H
Hongze Cheng 已提交
62

H
Hongze Cheng 已提交
63 64 65
  code = tsdbMemTableCreate(pTsdb, &pTsdb->mem);
  if (code) {
    goto _err;
H
Hongze Cheng 已提交
66 67
  }

H
Hongze Cheng 已提交
68 69 70 71
  return code;

_err:
  return code;
H
Hongze Cheng 已提交
72 73
}

H
more  
Hongze Cheng 已提交
74 75
int32_t tsdbCommit(STsdb *pTsdb) {
  int32_t    code = 0;
H
refact  
Hongze Cheng 已提交
76
  SCommitter commith = {0};
H
Hongze Cheng 已提交
77
  int        fid;
H
refact  
Hongze Cheng 已提交
78

H
more  
Hongze Cheng 已提交
79
  // start commit
H
more  
Hongze Cheng 已提交
80 81 82
  code = tsdbStartCommit(pTsdb, &commith);
  if (code) {
    goto _err;
H
refact  
Hongze Cheng 已提交
83 84
  }

H
refact  
Hongze Cheng 已提交
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
  // commit impl
  code = tsdbCommitData(&commith);
  if (code) {
    goto _err;
  }

  code = tsdbCommitDel(&commith);
  if (code) {
    goto _err;
  }

  code = tsdbCommitCache(&commith);
  if (code) {
    goto _err;
  }

  // end commit
H
more  
Hongze Cheng 已提交
102 103 104 105
  code = tsdbEndCommit(&commith, 0);
  if (code) {
    goto _err;
  }
H
refact  
Hongze Cheng 已提交
106 107 108 109

  return code;

_err:
C
Cary Xu 已提交
110
  tsdbError("vgId:%d, failed to commit since %s", TD_VID(pTsdb->pVnode), tstrerror(code));
H
refact  
Hongze Cheng 已提交
111 112 113
  return code;
}

H
Hongze Cheng 已提交
114
// ===================================== NEW ======================================
H
Hongze Cheng 已提交
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
static int32_t tsdbStartCommit(STsdb *pTsdb, SCommitter *pCommitter) {
  int32_t code = 0;

  ASSERT(pTsdb->mem && pTsdb->imem == NULL);
  // lock();
  pTsdb->imem = pTsdb->mem;
  pTsdb->mem = NULL;
  // unlock();

  pCommitter->pTsdb = pTsdb;

  return code;
}

static int32_t tsdbCommitDataStart(SCommitter *pCommitter);
static int32_t tsdbCommitDataImpl(SCommitter *pCommitter);
static int32_t tsdbCommitDataEnd(SCommitter *pCommitter);

static int32_t tsdbCommitData(SCommitter *pCommitter) {
  int32_t    code = 0;
  STsdb     *pTsdb = pCommitter->pTsdb;
  SMemTable *pMemTable = pTsdb->imem;

  // no data, just return
  if (pMemTable->nRow == 0) {
    tsdbDebug("vgId:%d no data to commit", TD_VID(pTsdb->pVnode));
    goto _exit;
  }
H
Hongze Cheng 已提交
143

H
Hongze Cheng 已提交
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
  // start
  code = tsdbCommitDataStart(pCommitter);
  if (code) {
    goto _err;
  }

  // commit
  code = tsdbCommitDataImpl(pCommitter);
  if (code) {
    goto _err;
  }

  // end
  code = tsdbCommitDataEnd(pCommitter);
  if (code) {
    goto _err;
  }

_exit:
  tsdbDebug("vgId:%d commit TSDB data, nRow:%" PRId64, TD_VID(pTsdb->pVnode), pMemTable->nRow);
  return code;

_err:
  tsdbError("vgId:%d failed to commit TSDB data since %s", TD_VID(pTsdb->pVnode), tstrerror(code));
  return code;
}

static int32_t tsdbCommitDelStart(SCommitter *pCommitter) {
H
Hongze Cheng 已提交
172 173 174 175 176 177
  int32_t    code = 0;
  STsdb     *pTsdb = pCommitter->pTsdb;
  SMemTable *pMemTable = pTsdb->imem;
  SDelFile  *pDelFileR = NULL;  // TODO
  SDelFile  *pDelFileW = NULL;  // TODO

H
Hongze Cheng 已提交
178
  // load old
H
Hongze Cheng 已提交
179
  pCommitter->delIdxOld = (SDelIdx){0};
H
Hongze Cheng 已提交
180
  if (pDelFileR) {
H
Hongze Cheng 已提交
181
    code = tsdbDelFReaderOpen(&pCommitter->pDelFReader, pDelFileR, pTsdb, NULL);
H
Hongze Cheng 已提交
182 183 184 185
    if (code) {
      goto _err;
    }

H
Hongze Cheng 已提交
186
    code = tsdbReadDelIdx(pCommitter->pDelFReader, &pCommitter->delIdxOld, &pCommitter->pBuf1);
H
Hongze Cheng 已提交
187 188 189 190 191
    if (code) {
      goto _err;
    }
  }

H
Hongze Cheng 已提交
192
  // prepare new
H
Hongze Cheng 已提交
193
  pCommitter->delIdxNew = (SDelIdx){0};
H
Hongze Cheng 已提交
194
  code = tsdbDelFWriterOpen(&pCommitter->pDelFWriter, pDelFileW, pTsdb);
H
Hongze Cheng 已提交
195 196 197 198 199 200 201 202 203 204
  if (code) {
    goto _err;
  }

_exit:
  tsdbDebug("vgId:%d commit del start", TD_VID(pTsdb->pVnode));
  return code;

_err:
  tsdbError("vgId:%d commit del start failed since %s", TD_VID(pTsdb->pVnode), tstrerror(code));
H
Hongze Cheng 已提交
205 206 207
  return code;
}

H
Hongze Cheng 已提交
208 209
static int32_t tsdbCommitTableDel(SCommitter *pCommitter);

H
Hongze Cheng 已提交
210
static int32_t tsdbCommitDelImpl(SCommitter *pCommitter) {
H
Hongze Cheng 已提交
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
  int32_t      code = 0;
  STsdb       *pTsdb = pCommitter->pTsdb;
  SMemTable   *pMemTable = pTsdb->imem;
  int32_t      c;
  int32_t      iTbData = 0;
  int32_t      nTbData = taosArrayGetSize(pMemTable->aTbData);
  int32_t      iDelIdxItem = 0;
  int32_t      nDelIdxItem = pCommitter->delIdxOld.offset.nOffset;
  STbData     *pTbData = NULL;
  SDelIdxItem *pDelIdxItem = NULL;
  SDelIdxItem  item;

  while (iTbData < nTbData || iDelIdxItem < nDelIdxItem) {
    pTbData = NULL;
    pDelIdxItem = NULL;
    if (iTbData < nTbData) {
      pTbData = (STbData *)taosArrayGetP(pMemTable->aTbData, iTbData);
    }
    if (iDelIdxItem < nDelIdxItem) {
      tDelIdxGetItemByIdx(&pCommitter->delIdxOld, &item, iDelIdxItem);
      pDelIdxItem = &item;
    }

    if (pTbData && pDelIdxItem) {
      c = tTABLEIDCmprFn(pTbData, pDelIdxItem);
      if (c == 0) {
        iTbData++;
        iDelIdxItem++;
      } else if (c < 0) {
        iTbData++;
        pDelIdxItem = NULL;
      } else {
        iDelIdxItem++;
        pTbData = NULL;
      }
H
Hongze Cheng 已提交
246
    } else {
H
Hongze Cheng 已提交
247 248 249 250 251 252
      if (pTbData) {
        iTbData++;
      }
      if (pDelIdxItem) {
        iDelIdxItem++;
      }
H
Hongze Cheng 已提交
253 254
    }

H
Hongze Cheng 已提交
255 256 257 258 259 260 261 262 263
    if (pTbData && pTbData->pHead == NULL) {
      pTbData = NULL;
    }

    if (pTbData == NULL && pDelIdxItem == NULL) continue;

    // do merge
    pCommitter->pTbData = pTbData;
    pCommitter->pDelIdxItem = pDelIdxItem;
H
Hongze Cheng 已提交
264 265
    code = tsdbCommitTableDel(pCommitter);
    if (code) goto _err;
H
Hongze Cheng 已提交
266 267
  }

H
Hongze Cheng 已提交
268
  return code;
H
Hongze Cheng 已提交
269 270 271 272

_err:
  tsdbError("vgId:%d commit del impl failed since %s", TD_VID(pTsdb->pVnode), tstrerror(code));
  return code;
H
Hongze Cheng 已提交
273 274 275 276
}

static int32_t tsdbCommitDelEnd(SCommitter *pCommitter) {
  int32_t code = 0;
H
Hongze Cheng 已提交
277

H
Hongze Cheng 已提交
278
  code = tsdbWriteDelIdx(pCommitter->pDelFWriter, &pCommitter->delIdxNew, NULL);
H
Hongze Cheng 已提交
279 280 281 282
  if (code) {
    goto _err;
  }

H
Hongze Cheng 已提交
283 284 285 286 287 288
  code = tsdbUpdateDelFileHdr(pCommitter->pDelFWriter, NULL);
  if (code) {
    goto _err;
  }

  code = tsdbDelFWriterClose(pCommitter->pDelFWriter, 1);
H
Hongze Cheng 已提交
289 290 291 292 293 294 295 296 297
  if (code) {
    goto _err;
  }

  if (pCommitter->pDelFReader) {
    code = tsdbDelFReaderClose(pCommitter->pDelFReader);
    if (code) goto _err;
  }

H
more  
Hongze Cheng 已提交
298 299
  tDelIdxClear(&pCommitter->delIdxNew);

H
Hongze Cheng 已提交
300 301 302
  return code;

_err:
H
Hongze Cheng 已提交
303
  tsdbError("vgId:%d commit del end failed since %s", TD_VID(pCommitter->pTsdb->pVnode), tstrerror(code));
H
Hongze Cheng 已提交
304 305 306 307 308 309 310 311
  return code;
}

static int32_t tsdbCommitDel(SCommitter *pCommitter) {
  int32_t    code = 0;
  STsdb     *pTsdb = pCommitter->pTsdb;
  SMemTable *pMemTable = pTsdb->imem;

H
Hongze Cheng 已提交
312
  if (pMemTable->nDel == 0) {
H
Hongze Cheng 已提交
313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
    goto _exit;
  }

  // start
  code = tsdbCommitDelStart(pCommitter);
  if (code) {
    goto _err;
  }

  // impl
  code = tsdbCommitDelImpl(pCommitter);
  if (code) {
    goto _err;
  }

  // end
  code = tsdbCommitDelEnd(pCommitter);
  if (code) {
    goto _err;
  }

_exit:
H
more  
Hongze Cheng 已提交
335
  tsdbDebug("vgId:%d commit del done, nDel:%" PRId64, TD_VID(pTsdb->pVnode), pMemTable->nDel);
H
Hongze Cheng 已提交
336 337 338
  return code;

_err:
H
Hongze Cheng 已提交
339
  tsdbError("vgId:%d commit del failed since %s", TD_VID(pTsdb->pVnode), tstrerror(code));
H
Hongze Cheng 已提交
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 366 367 368 369 370 371 372 373 374 375 376 377 378 379 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 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 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 481 482 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
  return code;
}

static int32_t tsdbCommitCache(SCommitter *pCommitter) {
  int32_t code = 0;
  // TODO
  return code;
}

static int32_t tsdbEndCommit(SCommitter *pCommitter, int32_t eno) {
  int32_t code = 0;
  // TODO
  return code;
}

static int32_t tsdbCommitDataStart(SCommitter *pCommitter) {
  int32_t    code = 0;
  STsdb     *pTsdb = pCommitter->pTsdb;
  SMemTable *pMemTable = pTsdb->imem;

  pCommitter->nextCommitKey = pMemTable->minKey.ts;

  return code;
}

static int32_t tsdbCommitFileData(SCommitter *pCommitter);

static int32_t tsdbCommitDataImpl(SCommitter *pCommitter) {
  int32_t code = 0;

  for (;;) {
    if (pCommitter->nextCommitKey == TSKEY_MAX) break;

    pCommitter->commitFid = TSDB_KEY_FID(pCommitter->nextCommitKey, pCommitter->minutes, pCommitter->precision);
    code = tsdbCommitFileData(pCommitter);
    if (code) {
      goto _err;
    }
  }

_exit:
  return code;

_err:
  return code;
}

static int32_t tsdbCommitDataEnd(SCommitter *pCommitter) {
  int32_t code = 0;
  // TODO
  return code;
}

static int32_t tsdbCommitFileDataStart(SCommitter *pCommitter);
static int32_t tsdbCommitFileDataImpl(SCommitter *pCommitter);
static int32_t tsdbCommitFileDataEnd(SCommitter *pCommitter);

static int32_t tsdbCommitFileData(SCommitter *pCommitter) {
  int32_t code = 0;

  // commit file data start
  code = tsdbCommitFileDataStart(pCommitter);
  if (code) {
    goto _err;
  }

  // commit file data impl
  code = tsdbCommitFileDataImpl(pCommitter);
  if (code) {
    goto _err;
  }

  // commit file data end
  code = tsdbCommitFileDataEnd(pCommitter);
  if (code) {
    goto _err;
  }

  return code;

_err:
  return code;
}

static int32_t tsdbCommitFileDataStart(SCommitter *pCommitter) {
  int32_t    code = 0;
  STsdb     *pTsdb = pCommitter->pTsdb;
  SDFileSet *pRSet = NULL;
  SDFileSet *pWSet = NULL;

  taosArrayClear(pCommitter->aOBlockIdx);
  taosArrayClear(pCommitter->aBlockIdx);

  // search pRSet (todo)

  // open file to read
  if (pRSet) {
    code = tsdbDFileSetReaderOpen(pCommitter->pReader, pTsdb, pRSet);
    if (code) goto _err;

    // create/open the pWSet (todo)
  } else {
    // create the pWSet (todo)
  }

  // open file for write
  code = tsdbDFileSetWriterOpen(pCommitter->pWriter, pTsdb, pWSet);
  if (code) goto _err;

  // read the SBlockIdx part for merge purpose
  code = tsdbLoadSBlockIdx(pCommitter->pReader, pCommitter->aOBlockIdx);
  if (code) goto _err;

_exit:
  return code;

_err:
  return code;
}

static int32_t tsdbCommitTableData(SCommitter *pCommitter);

static int32_t tsdbCommitFileDataImpl(SCommitter *pCommitter) {
  int32_t    code = 0;
  STsdb     *pTsdb = pCommitter->pTsdb;
  SMemTable *pMemTable = pTsdb->imem;
  int32_t    iBlockIdx = 0;
  int32_t    nBlockIdx = taosArrayGetSize(pCommitter->aOBlockIdx);
  int32_t    iTbData = 0;
  int32_t    nTbData = taosArrayGetSize(pMemTable->aTbData);
  SBlockIdx *pBlockIdx;
  STbData   *pTbData;

  while (iTbData < nTbData || iBlockIdx < nBlockIdx) {
    pTbData = NULL;
    pBlockIdx = NULL;

    if (iTbData < nTbData) {
      pTbData = (STbData *)taosArrayGetP(pMemTable->aTbData, iTbData);
    }
    if (iBlockIdx < nBlockIdx) {
      pBlockIdx = (SBlockIdx *)taosArrayGet(pCommitter->aOBlockIdx, iBlockIdx);
    }

    if (pTbData && pBlockIdx) {
      int32_t c = tTABLEIDCmprFn(pTbData, pBlockIdx);
      if (c == 0) {
        iTbData++;
        iBlockIdx++;
      } else if (c < 0) {
        iTbData++;
        pBlockIdx = NULL;
      } else {
        iBlockIdx++;
        pTbData = NULL;
      }
    } else {
      if (pTbData) {
        iTbData++;
      } else {
        iBlockIdx++;
      }
    }

    pCommitter->pTbData = pTbData;
    pCommitter->pBlockIdx = pBlockIdx;
    code = tsdbCommitTableData(pCommitter);
    if (code) {
      goto _err;
    }
  }

  return code;

_err:
  return code;
}

static int32_t tsdbCommitFileDataEnd(SCommitter *pCommitter) {
  int32_t code = 0;
  // TODO
  return code;
}

static int32_t tsdbCommitTableDataStart(SCommitter *pCommitter);
static int32_t tsdbCommitTableDataImpl(SCommitter *pCommitter);
static int32_t tsdbCommitTableDataEnd(SCommitter *pCommitter);

static int32_t tsdbCommitTableData(SCommitter *pCommitter) {
  int32_t code = 0;

  // start
  code = tsdbCommitTableDataStart(pCommitter);
  if (code) {
    goto _err;
  }

  // impl
  code = tsdbCommitTableDataImpl(pCommitter);
  if (code) {
    goto _err;
  }

  // end
  code = tsdbCommitTableDataEnd(pCommitter);
  if (code) {
    goto _err;
  }

_exit:
  return code;

_err:
  return code;
}

static int32_t tsdbCommitTableDataStart(SCommitter *pCommitter) {
  int32_t code = 0;
  // TODO
  return code;
}

static int32_t tsdbCommitTableDataImpl(SCommitter *pCommitter) {
  int32_t code = 0;
  // TODO
  return code;
}

static int32_t tsdbCommitTableDataEnd(SCommitter *pCommitter) {
  int32_t code = 0;
  // TODO
  return code;
}

H
Hongze Cheng 已提交
574
static int32_t tsdbCommitTableDelStart(SCommitter *pCommitter) {
H
Hongze Cheng 已提交
575 576 577 578 579 580 581 582
  int32_t  code = 0;
  tb_uid_t suid;
  tb_uid_t uid;

  if (pCommitter->pTbData) {
    suid = pCommitter->pTbData->suid;
    uid = pCommitter->pTbData->uid;
  }
H
Hongze Cheng 已提交
583 584

  // load old
H
Hongze Cheng 已提交
585
  pCommitter->delDataOld = (SDelData){0};
H
Hongze Cheng 已提交
586 587 588 589 590
  if (pCommitter->pDelIdxItem) {
    suid = pCommitter->pDelIdxItem->suid;
    uid = pCommitter->pDelIdxItem->uid;
    code =
        tsdbReadDelData(pCommitter->pDelFReader, pCommitter->pDelIdxItem, &pCommitter->delDataOld, &pCommitter->pBuf5);
H
Hongze Cheng 已提交
591 592 593 594
    if (code) goto _err;
  }

  // prepare new
H
Hongze Cheng 已提交
595 596 597 598 599 600 601 602 603 604 605 606 607 608 609
  pCommitter->delDataNew.suid = suid;
  pCommitter->delDataNew.uid = uid;
  pCommitter->delDataNew.offset.flag = 0;
  pCommitter->delDataNew.offset.nOffset = 0;
  pCommitter->delDataNew.nData = 0;
  pCommitter->delIdxItem = (SDelIdxItem){
      .suid = suid,
      .uid = uid,
      .minKey = TSKEY_MAX,
      .maxKey = TSKEY_MIN,
      .minVersion = INT64_MAX,
      .maxVersion = INT64_MIN,
      .offset = -1,
      .size = -1,
  };
H
Hongze Cheng 已提交
610 611 612 613 614 615 616 617 618

  return code;

_err:
  tsdbError("vgId:%d commit table del start failed since %s", TD_VID(pCommitter->pTsdb->pVnode), tstrerror(code));
  return code;
}

static int32_t tsdbCommitTableDelImpl(SCommitter *pCommitter) {
H
Hongze Cheng 已提交
619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637
  int32_t      code = 0;
  SDelDataItem item;

  // old
  if (pCommitter->pDelIdxItem) {
    for (int32_t iDelIdxItem = 0; iDelIdxItem < pCommitter->delDataOld.offset.nOffset; iDelIdxItem++) {
      code = tDelDataGetItemByIdx(&pCommitter->delDataOld, &item, iDelIdxItem);
      if (code) goto _err;

      code = tDelDataPutItem(&pCommitter->delDataNew, &item);
      if (code) goto _err;

      // update index
      if (item.version < pCommitter->delIdxItem.minVersion) pCommitter->delIdxItem.minVersion = item.version;
      if (item.version > pCommitter->delIdxItem.maxVersion) pCommitter->delIdxItem.maxVersion = item.version;
      if (item.sKey < pCommitter->delIdxItem.minKey) pCommitter->delIdxItem.minKey = item.sKey;
      if (item.eKey > pCommitter->delIdxItem.maxKey) pCommitter->delIdxItem.maxKey = item.eKey;
    }
  }
H
Hongze Cheng 已提交
638

H
Hongze Cheng 已提交
639 640 641 642
  // new
  if (pCommitter->pTbData) {
    for (SDelOp *pDelOp = pCommitter->pTbData->pHead; pDelOp; pDelOp = pDelOp->pNext) {
      item = (SDelDataItem){.version = pDelOp->version, .sKey = pDelOp->sKey, .eKey = pDelOp->eKey};
H
Hongze Cheng 已提交
643

H
Hongze Cheng 已提交
644 645 646 647 648 649 650 651 652
      code = tDelDataPutItem(&pCommitter->delDataNew, &item);
      if (code) goto _err;

      // update index
      if (item.version < pCommitter->delIdxItem.minVersion) pCommitter->delIdxItem.minVersion = item.version;
      if (item.version > pCommitter->delIdxItem.maxVersion) pCommitter->delIdxItem.maxVersion = item.version;
      if (item.sKey < pCommitter->delIdxItem.minKey) pCommitter->delIdxItem.minKey = item.sKey;
      if (item.eKey > pCommitter->delIdxItem.maxKey) pCommitter->delIdxItem.maxKey = item.eKey;
    }
H
Hongze Cheng 已提交
653 654 655 656 657 658 659 660 661 662 663 664
  }

  return code;

_err:
  return code;
}

static int32_t tsdbCommitTableDelEnd(SCommitter *pCommitter) {
  int32_t code = 0;

  // write table del data
H
Hongze Cheng 已提交
665 666
  code = tsdbWriteDelData(pCommitter->pDelFWriter, &pCommitter->delDataNew, NULL, &pCommitter->delIdxItem.offset,
                          &pCommitter->delIdxItem.size);
H
Hongze Cheng 已提交
667 668 669
  if (code) goto _err;

  // add SDelIdxItem
H
Hongze Cheng 已提交
670
  code = tDelIdxPutItem(&pCommitter->delIdxNew, &pCommitter->delIdxItem);
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
  if (code) goto _err;

  return code;

_err:
  tsdbError("vgId:%d commit table del end failed since %s", TD_VID(pCommitter->pTsdb->pVnode), tstrerror(code));
  return code;
}

static int32_t tsdbCommitTableDel(SCommitter *pCommitter) {
  int32_t code = 0;

  // start
  code = tsdbCommitTableDelStart(pCommitter);
  if (code) goto _err;

  // impl
  code = tsdbCommitTableDelImpl(pCommitter);
  if (code) goto _err;

  // end
  code = tsdbCommitTableDelEnd(pCommitter);
  if (code) goto _err;

  return code;

_err:
  return code;
}

H
Hongze Cheng 已提交
701 702
// // ===================================== OLD ======================================
#if 0
H
Hongze Cheng 已提交
703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724
struct SCommitIter {
  STable      *pTable;
  STbDataIter *pIter;
};

#define TSDB_MAX_SUBBLOCKS               8
#define TSDB_DEFAULT_BLOCK_ROWS(maxRows) ((maxRows)*4 / 5)
#define TSDB_COMMIT_REPO(ch)             TSDB_READ_REPO(&(ch->readh))
#define TSDB_COMMIT_REPO_ID(ch)          REPO_ID(TSDB_READ_REPO(&(ch->readh)))
#define TSDB_COMMIT_WRITE_FSET(ch)       (&((ch)->wSet))
#define TSDB_COMMIT_TABLE(ch)            ((ch)->pTable)
#define TSDB_COMMIT_HEAD_FILE(ch)        TSDB_DFILE_IN_SET(TSDB_COMMIT_WRITE_FSET(ch), TSDB_FILE_HEAD)
#define TSDB_COMMIT_DATA_FILE(ch)        TSDB_DFILE_IN_SET(TSDB_COMMIT_WRITE_FSET(ch), TSDB_FILE_DATA)
#define TSDB_COMMIT_LAST_FILE(ch)        TSDB_DFILE_IN_SET(TSDB_COMMIT_WRITE_FSET(ch), TSDB_FILE_LAST)
#define TSDB_COMMIT_SMAD_FILE(ch)        TSDB_DFILE_IN_SET(TSDB_COMMIT_WRITE_FSET(ch), TSDB_FILE_SMAD)
#define TSDB_COMMIT_SMAL_FILE(ch)        TSDB_DFILE_IN_SET(TSDB_COMMIT_WRITE_FSET(ch), TSDB_FILE_SMAL)
#define TSDB_COMMIT_BUF(ch)              TSDB_READ_BUF(&((ch)->readh))
#define TSDB_COMMIT_COMP_BUF(ch)         TSDB_READ_COMP_BUF(&((ch)->readh))
#define TSDB_COMMIT_EXBUF(ch)            TSDB_READ_EXBUF(&((ch)->readh))
#define TSDB_COMMIT_DEFAULT_ROWS(ch)     TSDB_DEFAULT_BLOCK_ROWS(TSDB_COMMIT_REPO(ch)->pVnode->config.tsdbCfg.maxRows)
#define TSDB_COMMIT_TXN_VERSION(ch)      FS_TXN_VERSION(REPO_FS(TSDB_COMMIT_REPO(ch)))

H
refact  
Hongze Cheng 已提交
725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741
static int     tsdbInitCommitH(SCommitter *pCommith, STsdb *pRepo);
static void    tsdbSeekCommitIter(SCommitter *pCommith, TSKEY key);
static int     tsdbNextCommitFid(SCommitter *pCommith);
static void    tsdbDestroyCommitH(SCommitter *pCommith);
static int32_t tsdbCreateCommitIters(SCommitter *pCommith);
static void    tsdbDestroyCommitIters(SCommitter *pCommith);
static int     tsdbCommitToFile(SCommitter *pCommith, SDFileSet *pSet, int fid);
static int     tsdbSetAndOpenCommitFile(SCommitter *pCommith, SDFileSet *pSet, int fid);
static int     tsdbCommitToTable(SCommitter *pCommith, int tid);
static bool    tsdbCommitIsSameFile(SCommitter *pCommith, int bidx);
static int     tsdbMoveBlkIdx(SCommitter *pCommith, SBlockIdx *pIdx);
static int     tsdbSetCommitTable(SCommitter *pCommith, STable *pTable);
static int     tsdbComparKeyBlock(const void *arg1, const void *arg2);
static int     tsdbWriteBlockInfo(SCommitter *pCommih);
static int     tsdbCommitMemData(SCommitter *pCommith, SCommitIter *pIter, TSKEY keyLimit, bool toData);
static int     tsdbMergeMemData(SCommitter *pCommith, SCommitIter *pIter, int bidx);
static int     tsdbMoveBlock(SCommitter *pCommith, int bidx);
H
Hongze Cheng 已提交
742 743 744
static int  tsdbCommitAddBlock(SCommitter *pCommith, const SBlock *pSupBlock, const SBlock *pSubBlocks, int
nSubBlocks); static int  tsdbMergeBlockData(SCommitter *pCommith, SCommitIter *pIter, SDataCols *pDataCols, TSKEY
keyLimit,
H
refact  
Hongze Cheng 已提交
745 746 747 748 749 750 751 752 753 754 755 756 757
                               bool isLastOneBlock);
static void tsdbResetCommitTable(SCommitter *pCommith);
static void tsdbCloseCommitFile(SCommitter *pCommith, bool hasError);
static bool tsdbCanAddSubBlock(SCommitter *pCommith, SBlock *pBlock, SMergeInfo *pInfo);
static void tsdbLoadAndMergeFromCache(STsdb *pTsdb, SDataCols *pDataCols, int *iter, SCommitIter *pCommitIter,
                                      SDataCols *pTarget, TSKEY maxKey, int maxRows, int8_t update);
static int  tsdbWriteBlockIdx(SDFile *pHeadf, SArray *pIdxA, void **ppBuf);
static int  tsdbApplyRtnOnFSet(STsdb *pRepo, SDFileSet *pSet, SRtn *pRtn);
static int  tsdbLoadDataFromCache(STsdb *pTsdb, STable *pTable, STbDataIter *pIter, TSKEY maxKey, int maxRowsToRead,
                                  SDataCols *pCols, TKEY *filterKeys, int nFilterKeys, bool keepDup,
                                  SMergeInfo *pMergeInfo);

static int32_t tsdbCommitData(SCommitter *pCommith) {
H
refact  
Hongze Cheng 已提交
758
  int32_t    fid;
H
more  
Hongze Cheng 已提交
759
  SDFileSet *pSet = NULL;
H
refact  
Hongze Cheng 已提交
760 761 762
  int32_t    code = 0;
  STsdb     *pTsdb = TSDB_COMMIT_REPO(pCommith);

H
refact  
Hongze Cheng 已提交
763
  // Skip expired memory data and expired FSET
H
refact  
Hongze Cheng 已提交
764 765 766
  tsdbSeekCommitIter(pCommith, pCommith->rtn.minKey);
  while ((pSet = tsdbFSIterNext(&(pCommith->fsIter)))) {
    if (pSet->fid < pCommith->rtn.minFid) {
H
more  
Hongze Cheng 已提交
767
      tsdbInfo("vgId:%d, FSET %d on level %d disk id %d expires, remove it", REPO_ID(pTsdb), pSet->fid,
H
refact  
Hongze Cheng 已提交
768 769 770 771 772 773
               TSDB_FSET_LEVEL(pSet), TSDB_FSET_ID(pSet));
    } else {
      break;
    }
  }

H
more  
Hongze Cheng 已提交
774
  // commit
H
refact  
Hongze Cheng 已提交
775
  fid = tsdbNextCommitFid(pCommith);
H
refact  
Hongze Cheng 已提交
776 777 778 779 780 781 782
  while (true) {
    // Loop over both on disk and memory
    if (pSet == NULL && fid == TSDB_IVLD_FID) break;

    if (pSet && (fid == TSDB_IVLD_FID || pSet->fid < fid)) {
      // Only has existing FSET but no memory data to commit in this
      // existing FSET, only check if file in correct retention
H
refact  
Hongze Cheng 已提交
783 784
      if (tsdbApplyRtnOnFSet(TSDB_COMMIT_REPO(pCommith), pSet, &(pCommith->rtn)) < 0) {
        tsdbDestroyCommitH(pCommith);
H
refact  
Hongze Cheng 已提交
785 786 787
        return -1;
      }

H
refact  
Hongze Cheng 已提交
788
      pSet = tsdbFSIterNext(&(pCommith->fsIter));
H
refact  
Hongze Cheng 已提交
789 790 791 792 793 794 795 796 797 798 799 800 801
    } else {
      // Has memory data to commit
      SDFileSet *pCSet;
      int        cfid;

      if (pSet == NULL || pSet->fid > fid) {
        // Commit to a new FSET with fid: fid
        pCSet = NULL;
        cfid = fid;
      } else {
        // Commit to an existing FSET
        pCSet = pSet;
        cfid = pSet->fid;
H
refact  
Hongze Cheng 已提交
802
        pSet = tsdbFSIterNext(&(pCommith->fsIter));
H
refact  
Hongze Cheng 已提交
803 804
      }

H
refact  
Hongze Cheng 已提交
805 806
      if (tsdbCommitToFile(pCommith, pCSet, cfid) < 0) {
        tsdbDestroyCommitH(pCommith);
H
refact  
Hongze Cheng 已提交
807 808 809
        return -1;
      }

H
refact  
Hongze Cheng 已提交
810
      fid = tsdbNextCommitFid(pCommith);
H
refact  
Hongze Cheng 已提交
811 812
    }
  }
H
more  
Hongze Cheng 已提交
813

H
refact  
Hongze Cheng 已提交
814 815 816
  return code;
}

H
refact  
Hongze Cheng 已提交
817
static int32_t tsdbCommitDel(SCommitter *pCommith) {
H
refact  
Hongze Cheng 已提交
818 819 820 821
  int32_t code = 0;
  // TODO
  return code;
}
H
more  
Hongze Cheng 已提交
822

H
refact  
Hongze Cheng 已提交
823
static int32_t tsdbCommitCache(SCommitter *pCommith) {
H
refact  
Hongze Cheng 已提交
824 825
  int32_t code = 0;
  // TODO
H
more  
Hongze Cheng 已提交
826
  return code;
H
Hongze Cheng 已提交
827 828
}

H
Hongze Cheng 已提交
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 868 869
static int tsdbApplyRtnOnFSet(STsdb *pRepo, SDFileSet *pSet, SRtn *pRtn) {
  SDiskID   did;
  SDFileSet nSet = {0};
  STsdbFS  *pfs = REPO_FS(pRepo);
  int       level;

  ASSERT(pSet->fid >= pRtn->minFid);

  level = tsdbGetFidLevel(pSet->fid, pRtn);

  if (tfsAllocDisk(pRepo->pVnode->pTfs, level, &did) < 0) {
    terrno = TSDB_CODE_TDB_NO_AVAIL_DISK;
    return -1;
  }

  if (did.level > TSDB_FSET_LEVEL(pSet)) {
    // Need to move the FSET to higher level
    tsdbInitDFileSet(pRepo, &nSet, did, pSet->fid, FS_TXN_VERSION(pfs));

    if (tsdbCopyDFileSet(pSet, &nSet) < 0) {
      tsdbError("vgId:%d, failed to copy FSET %d from level %d to level %d since %s", REPO_ID(pRepo), pSet->fid,
                TSDB_FSET_LEVEL(pSet), did.level, tstrerror(terrno));
      return -1;
    }

    if (tsdbUpdateDFileSet(pfs, &nSet) < 0) {
      return -1;
    }

    tsdbInfo("vgId:%d, FSET %d is copied from level %d disk id %d to level %d disk id %d", REPO_ID(pRepo), pSet->fid,
             TSDB_FSET_LEVEL(pSet), TSDB_FSET_ID(pSet), did.level, did.id);
  } else {
    // On a correct level
    if (tsdbUpdateDFileSet(pfs, pSet) < 0) {
      return -1;
    }
  }

  return 0;
}

H
refact  
Hongze Cheng 已提交
870
static int32_t tsdbStartCommit(STsdb *pTsdb, SCommitter *pCHandle) {
H
more  
Hongze Cheng 已提交
871
  int32_t code = 0;
H
more  
Hongze Cheng 已提交
872

H
more  
Hongze Cheng 已提交
873
  tsdbInfo("vgId:%d, start to commit", REPO_ID(pTsdb));
H
more  
Hongze Cheng 已提交
874

H
Hongze Cheng 已提交
875 876 877
  ASSERT(pTsdb->imem == NULL && pTsdb->mem);
  pTsdb->imem = pTsdb->mem;
  pTsdb->mem = NULL;
H
more  
Hongze Cheng 已提交
878 879 880 881 882 883 884
  if (tsdbInitCommitH(pCHandle, pTsdb) < 0) {
    return -1;
  }

  tsdbStartFSTxn(pTsdb, 0, 0);

  return code;
H
more  
Hongze Cheng 已提交
885 886
}

H
refact  
Hongze Cheng 已提交
887
static int32_t tsdbEndCommit(SCommitter *pCHandle, int eno) {
H
more  
Hongze Cheng 已提交
888 889 890 891
  int32_t code = 0;
  STsdb  *pTsdb = TSDB_COMMIT_REPO(pCHandle);

  tsdbDestroyCommitH(pCHandle);
H
more  
Hongze Cheng 已提交
892
  tsdbEndFSTxn(pTsdb);
H
more  
Hongze Cheng 已提交
893
  tsdbMemTableDestroy(pTsdb->imem);
H
more  
Hongze Cheng 已提交
894
  pTsdb->imem = NULL;
H
more  
Hongze Cheng 已提交
895

S
Shengliang Guan 已提交
896
  tsdbInfo("vgId:%d, commit over, %s", REPO_ID(pTsdb), (eno == TSDB_CODE_SUCCESS) ? "succeed" : "failed");
H
more  
Hongze Cheng 已提交
897 898

  return code;
H
more  
Hongze Cheng 已提交
899 900
}

H
refact  
Hongze Cheng 已提交
901
static int tsdbInitCommitH(SCommitter *pCommith, STsdb *pRepo) {
H
refact  
Hongze Cheng 已提交
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
  STsdbCfg *pCfg = REPO_CFG(pRepo);

  memset(pCommith, 0, sizeof(*pCommith));
  tsdbGetRtnSnap(pRepo, &(pCommith->rtn));

  TSDB_FSET_SET_CLOSED(TSDB_COMMIT_WRITE_FSET(pCommith));

  // Init read handle
  if (tsdbInitReadH(&(pCommith->readh), pRepo) < 0) {
    return -1;
  }

  // Init file iterator
  tsdbFSIterInit(&(pCommith->fsIter), REPO_FS(pRepo), TSDB_FS_ITER_FORWARD);

  if (tsdbCreateCommitIters(pCommith) < 0) {
    tsdbDestroyCommitH(pCommith);
    return -1;
  }

  pCommith->aBlkIdx = taosArrayInit(1024, sizeof(SBlockIdx));
  if (pCommith->aBlkIdx == NULL) {
    terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
    tsdbDestroyCommitH(pCommith);
    return -1;
  }

  pCommith->aSupBlk = taosArrayInit(1024, sizeof(SBlock));
  if (pCommith->aSupBlk == NULL) {
    terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
    tsdbDestroyCommitH(pCommith);
    return -1;
  }

  pCommith->aSubBlk = taosArrayInit(1024, sizeof(SBlock));
  if (pCommith->aSubBlk == NULL) {
    terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
    tsdbDestroyCommitH(pCommith);
    return -1;
  }

H
refact  
Hongze Cheng 已提交
943
  pCommith->pDataCols = tdNewDataCols(0, pCfg->maxRows);
H
refact  
Hongze Cheng 已提交
944 945 946 947 948 949 950 951 952 953
  if (pCommith->pDataCols == NULL) {
    terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
    tsdbDestroyCommitH(pCommith);
    return -1;
  }

  return 0;
}

// Skip all keys until key (not included)
H
refact  
Hongze Cheng 已提交
954
static void tsdbSeekCommitIter(SCommitter *pCommith, TSKEY key) {
H
refact  
Hongze Cheng 已提交
955 956 957 958
  for (int i = 0; i < pCommith->niters; i++) {
    SCommitIter *pIter = pCommith->iters + i;
    if (pIter->pTable == NULL || pIter->pIter == NULL) continue;

959 960
    tsdbLoadDataFromCache(TSDB_COMMIT_REPO(pCommith), pIter->pTable, pIter->pIter, key - 1, INT32_MAX, NULL, NULL, 0,
                          true, NULL);
H
refact  
Hongze Cheng 已提交
961 962 963
  }
}

H
refact  
Hongze Cheng 已提交
964
static int tsdbNextCommitFid(SCommitter *pCommith) {
C
Cary Xu 已提交
965 966 967
  STsdb        *pRepo = TSDB_COMMIT_REPO(pCommith);
  STsdbKeepCfg *pCfg = REPO_KEEP_CFG(pRepo);
  int           fid = TSDB_IVLD_FID;
H
more  
Hongze Cheng 已提交
968 969 970

  for (int i = 0; i < pCommith->niters; i++) {
    SCommitIter *pIter = pCommith->iters + i;
C
Cary Xu 已提交
971
    // if (pIter->pTable == NULL || pIter->pIter == NULL) continue;
H
more  
Hongze Cheng 已提交
972 973 974 975 976

    TSKEY nextKey = tsdbNextIterKey(pIter->pIter);
    if (nextKey == TSDB_DATA_TIMESTAMP_NULL) {
      continue;
    } else {
H
refact  
Hongze Cheng 已提交
977
      int tfid = (int)(TSDB_KEY_FID(nextKey, pCfg->days, pCfg->precision));
H
more  
Hongze Cheng 已提交
978 979 980 981 982 983 984 985
      if (fid == TSDB_IVLD_FID || fid > tfid) {
        fid = tfid;
      }
    }
  }

  return fid;
}
H
refact  
Hongze Cheng 已提交
986

H
refact  
Hongze Cheng 已提交
987
static void tsdbDestroyCommitH(SCommitter *pCommith) {
H
refact  
Hongze Cheng 已提交
988 989 990 991 992 993 994 995 996
  pCommith->pDataCols = tdFreeDataCols(pCommith->pDataCols);
  pCommith->aSubBlk = taosArrayDestroy(pCommith->aSubBlk);
  pCommith->aSupBlk = taosArrayDestroy(pCommith->aSupBlk);
  pCommith->aBlkIdx = taosArrayDestroy(pCommith->aBlkIdx);
  tsdbDestroyCommitIters(pCommith);
  tsdbDestroyReadH(&(pCommith->readh));
  tsdbCloseDFileSet(TSDB_COMMIT_WRITE_FSET(pCommith));
}

H
refact  
Hongze Cheng 已提交
997
static int32_t tsdbCommitToFileStart(SCommitter *pCHandle, SDFileSet *pSet, int32_t fid) {
H
Hongze Cheng 已提交
998 999
  int32_t       code = 0;
  STsdb        *pRepo = TSDB_COMMIT_REPO(pCHandle);
C
Cary Xu 已提交
1000
  STsdbKeepCfg *pCfg = REPO_KEEP_CFG(pRepo);
H
Hongze Cheng 已提交
1001

H
more  
Hongze Cheng 已提交
1002
  ASSERT(pSet == NULL || pSet->fid == fid);
H
Hongze Cheng 已提交
1003

H
Hongze Cheng 已提交
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
  pCHandle->fid = fid;
  pCHandle->pSet = pSet;
  pCHandle->isRFileSet = false;
  pCHandle->isDFileSame = false;
  pCHandle->isLFileSame = false;
  taosArrayClear(pCHandle->aBlkIdx);

  tsdbGetFidKeyRange(pCfg->days, pCfg->precision, fid, &(pCHandle->minKey), &(pCHandle->maxKey));

  code = tsdbSetAndOpenCommitFile(pCHandle, pSet, fid);

  return code;
}
H
refact  
Hongze Cheng 已提交
1017
static int32_t tsdbCommitToFileImpl(SCommitter *pCHandle) {
H
Hongze Cheng 已提交
1018 1019 1020 1021
  int32_t code = 0;
  // TODO
  return code;
}
H
refact  
Hongze Cheng 已提交
1022
static int32_t tsdbCommitToFileEnd(SCommitter *pCommith) {
H
Hongze Cheng 已提交
1023 1024
  int32_t code = 0;
  STsdb  *pRepo = TSDB_COMMIT_REPO(pCommith);
H
Hongze Cheng 已提交
1025

H
Hongze Cheng 已提交
1026 1027
  if (tsdbWriteBlockIdx(TSDB_COMMIT_HEAD_FILE(pCommith), pCommith->aBlkIdx, (void **)(&(TSDB_COMMIT_BUF(pCommith))))
  <
H
Hongze Cheng 已提交
1028 1029 1030 1031 1032 1033
      0) {
    tsdbError("vgId:%d, failed to write SBlockIdx part to FSET %d since %s", REPO_ID(pRepo), pCommith->fid,
              tstrerror(terrno));
    tsdbCloseCommitFile(pCommith, true);
    // revert the file change
    tsdbApplyDFileSetChange(TSDB_COMMIT_WRITE_FSET(pCommith), pCommith->pSet);
H
more  
Hongze Cheng 已提交
1034 1035
    return -1;
  }
H
Hongze Cheng 已提交
1036

H
Hongze Cheng 已提交
1037 1038 1039 1040 1041 1042 1043
  if (tsdbUpdateDFileSetHeader(&(pCommith->wSet)) < 0) {
    tsdbError("vgId:%d, failed to update FSET %d header since %s", REPO_ID(pRepo), pCommith->fid, tstrerror(terrno));
    tsdbCloseCommitFile(pCommith, true);
    // revert the file change
    tsdbApplyDFileSetChange(TSDB_COMMIT_WRITE_FSET(pCommith), pCommith->pSet);
    return -1;
  }
H
Hongze Cheng 已提交
1044

H
Hongze Cheng 已提交
1045 1046 1047 1048 1049 1050 1051 1052 1053
  // Close commit file
  tsdbCloseCommitFile(pCommith, false);

  if (tsdbUpdateDFileSet(REPO_FS(pRepo), &(pCommith->wSet)) < 0) {
    return -1;
  }

  return code;
}
H
refact  
Hongze Cheng 已提交
1054
static int32_t tsdbCommitToFile(SCommitter *pCommith, SDFileSet *pSet, int fid) {
H
Hongze Cheng 已提交
1055 1056 1057 1058 1059 1060 1061 1062
  int32_t       code = 0;
  STsdb        *pRepo = TSDB_COMMIT_REPO(pCommith);
  STsdbKeepCfg *pCfg = REPO_KEEP_CFG(pRepo);

  // commit to file start
  code = tsdbCommitToFileStart(pCommith, pSet, fid);
  if (code) {
    goto _err;
H
more  
Hongze Cheng 已提交
1063
  }
H
Hongze Cheng 已提交
1064

C
Cary Xu 已提交
1065
  // Loop to commit each table data in mem and file
C
Cary Xu 已提交
1066 1067
  int mIter = 0, fIter = 0;
  int nBlkIdx = taosArrayGetSize(pCommith->readh.aBlkIdx);
C
Cary Xu 已提交
1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081

  while (true) {
    SBlockIdx   *pIdx = NULL;
    SCommitIter *pIter = NULL;
    if (mIter < pCommith->niters) {
      pIter = pCommith->iters + mIter;
      if (fIter < nBlkIdx) {
        pIdx = taosArrayGet(pCommith->readh.aBlkIdx, fIter);
      }
    } else if (fIter < nBlkIdx) {
      pIdx = taosArrayGet(pCommith->readh.aBlkIdx, fIter);
    } else {
      break;
    }
C
Cary Xu 已提交
1082

H
Hongze Cheng 已提交
1083 1084
    if (pIter && pIter->pTable && (!pIdx || (pIter->pTable->suid <= pIdx->suid || pIter->pTable->uid <= pIdx->uid)))
    {
C
Cary Xu 已提交
1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095
      if (tsdbCommitToTable(pCommith, mIter) < 0) {
        tsdbCloseCommitFile(pCommith, true);
        // revert the file change
        tsdbApplyDFileSetChange(TSDB_COMMIT_WRITE_FSET(pCommith), pSet);
        return -1;
      }

      if (pIdx && (pIter->pTable->uid == pIdx->uid)) {
        ++fIter;
      }
      ++mIter;
C
Cary Xu 已提交
1096 1097
    } else if (pIter && !pIter->pTable) {
      // When table already dropped during commit, pIter is not NULL but pIter->pTable is NULL.
1098
      ++mIter;  // skip the table and do nothing
C
Cary Xu 已提交
1099 1100 1101 1102 1103 1104 1105 1106 1107 1108
    } else if (pIdx) {
      if (tsdbMoveBlkIdx(pCommith, pIdx) < 0) {
        tsdbCloseCommitFile(pCommith, true);
        // revert the file change
        tsdbApplyDFileSetChange(TSDB_COMMIT_WRITE_FSET(pCommith), pSet);
        return -1;
      }
      ++fIter;
    }
  }
H
Hongze Cheng 已提交
1109

H
Hongze Cheng 已提交
1110 1111 1112 1113
  // commit to file end
  code = tsdbCommitToFileEnd(pCommith);
  if (code) {
    goto _err;
H
more  
Hongze Cheng 已提交
1114
  }
H
Hongze Cheng 已提交
1115

H
Hongze Cheng 已提交
1116
  return code;
H
Hongze Cheng 已提交
1117

H
Hongze Cheng 已提交
1118 1119
_err:
  return code;
H
more  
Hongze Cheng 已提交
1120
}
H
refact  
Hongze Cheng 已提交
1121

H
refact  
Hongze Cheng 已提交
1122
static int32_t tsdbCreateCommitIters(SCommitter *pCommith) {
H
Hongze Cheng 已提交
1123 1124 1125
  int32_t      code = 0;
  STsdb       *pRepo = TSDB_COMMIT_REPO(pCommith);
  SMemTable   *pMem = pRepo->imem;
H
Hongze Cheng 已提交
1126
  STbData     *pTbData;
H
Hongze Cheng 已提交
1127
  SCommitIter *pCommitIter;
H
Hongze Cheng 已提交
1128
  STSchema    *pTSchema = NULL;
H
Hongze Cheng 已提交
1129 1130 1131 1132 1133 1134 1135 1136 1137

  pCommith->niters = taosArrayGetSize(pMem->aTbData);
  pCommith->iters = (SCommitIter *)taosMemoryCalloc(pCommith->niters, sizeof(SCommitIter));
  if (pCommith->iters == NULL) {
    code = TSDB_CODE_OUT_OF_MEMORY;
    goto _err;
  }

  for (int32_t iIter = 0; iIter < pCommith->niters; iIter++) {
H
Hongze Cheng 已提交
1138 1139
    pTbData = (STbData *)taosArrayGetP(pMem->aTbData, iIter);
    pCommitIter = &pCommith->iters[iIter];
H
Hongze Cheng 已提交
1140

1141
    pTSchema = metaGetTbTSchema(REPO_META(pRepo), pTbData->uid, -1);
C
Cary Xu 已提交
1142
    if (pTSchema) {
H
Hongze Cheng 已提交
1143
      tsdbTbDataIterCreate(pTbData, NULL, 0, &pCommitIter->pIter);
C
Cary Xu 已提交
1144

C
Cary Xu 已提交
1145 1146
      pCommitIter->pTable = (STable *)taosMemoryMalloc(sizeof(STable));
      pCommitIter->pTable->uid = pTbData->uid;
H
Hongze Cheng 已提交
1147
      pCommitIter->pTable->suid = pTbData->suid;
1148 1149
      pCommitIter->pTable->pSchema = pTSchema;
      pCommitIter->pTable->pCacheSchema = NULL;
C
Cary Xu 已提交
1150
    }
H
refact  
Hongze Cheng 已提交
1151
  }
H
Hongze Cheng 已提交
1152 1153 1154 1155 1156

  return code;

_err:
  return code;
H
refact  
Hongze Cheng 已提交
1157 1158
}

H
refact  
Hongze Cheng 已提交
1159
static void tsdbDestroyCommitIters(SCommitter *pCommith) {
H
Hongze Cheng 已提交
1160
  if (pCommith->iters == NULL) return;
H
refact  
Hongze Cheng 已提交
1161

H
Hongze Cheng 已提交
1162
  for (int i = 1; i < pCommith->niters; i++) {
H
Hongze Cheng 已提交
1163
    tsdbTbDataIterDestroy(pCommith->iters[i].pIter);
1164 1165
    if (pCommith->iters[i].pTable) {
      tdFreeSchema(pCommith->iters[i].pTable->pSchema);
1166
      tdFreeSchema(pCommith->iters[i].pTable->pCacheSchema);
1167 1168
      taosMemoryFreeClear(pCommith->iters[i].pTable);
    }
H
refact  
Hongze Cheng 已提交
1169 1170
  }

wafwerar's avatar
wafwerar 已提交
1171
  taosMemoryFree(pCommith->iters);
H
Hongze Cheng 已提交
1172 1173
  pCommith->iters = NULL;
  pCommith->niters = 0;
H
refact  
Hongze Cheng 已提交
1174 1175
}

H
refact  
Hongze Cheng 已提交
1176
static int tsdbSetAndOpenCommitFile(SCommitter *pCommith, SDFileSet *pSet, int fid) {
H
more  
Hongze Cheng 已提交
1177
  SDiskID    did;
L
Liu Jicong 已提交
1178
  STsdb     *pRepo = TSDB_COMMIT_REPO(pCommith);
H
more  
Hongze Cheng 已提交
1179
  SDFileSet *pWSet = TSDB_COMMIT_WRITE_FSET(pCommith);
H
Hongze Cheng 已提交
1180

H
Hongze Cheng 已提交
1181
  if (tfsAllocDisk(REPO_TFS(pRepo), tsdbGetFidLevel(fid, &(pCommith->rtn)), &did) < 0) {
H
more  
Hongze Cheng 已提交
1182 1183 1184
    terrno = TSDB_CODE_TDB_NO_AVAIL_DISK;
    return -1;
  }
H
Hongze Cheng 已提交
1185

H
more  
Hongze Cheng 已提交
1186 1187 1188 1189 1190
  // Open read FSET
  if (pSet) {
    if (tsdbSetAndOpenReadFSet(&(pCommith->readh), pSet) < 0) {
      return -1;
    }
H
Hongze Cheng 已提交
1191

H
more  
Hongze Cheng 已提交
1192
    pCommith->isRFileSet = true;
H
Hongze Cheng 已提交
1193

H
more  
Hongze Cheng 已提交
1194 1195 1196 1197
    if (tsdbLoadBlockIdx(&(pCommith->readh)) < 0) {
      tsdbCloseAndUnsetFSet(&(pCommith->readh));
      return -1;
    }
H
Hongze Cheng 已提交
1198

H
Hongze Cheng 已提交
1199 1200
    tsdbDebug("vgId:%d, FSET %d at level %d disk id %d is opened to read to commit", REPO_ID(pRepo),
              TSDB_FSET_FID(pSet), TSDB_FSET_LEVEL(pSet), TSDB_FSET_ID(pSet));
H
more  
Hongze Cheng 已提交
1201 1202 1203
  } else {
    pCommith->isRFileSet = false;
  }
H
Hongze Cheng 已提交
1204

H
more  
Hongze Cheng 已提交
1205 1206 1207
  // Set and open commit FSET
  if (pSet == NULL || did.level > TSDB_FSET_LEVEL(pSet)) {
    // Create a new FSET to write data
S
Shengliang Guan 已提交
1208
    tsdbInitDFileSet(pRepo, pWSet, did, fid, FS_TXN_VERSION(REPO_FS(pRepo)));
H
Hongze Cheng 已提交
1209

S
Shengliang Guan 已提交
1210
    if (tsdbCreateDFileSet(pRepo, pWSet, true) < 0) {
S
Shengliang Guan 已提交
1211
      tsdbError("vgId:%d, failed to create FSET %d at level %d disk id %d since %s", REPO_ID(pRepo),
H
more  
Hongze Cheng 已提交
1212 1213 1214 1215 1216 1217
                TSDB_FSET_FID(pWSet), TSDB_FSET_LEVEL(pWSet), TSDB_FSET_ID(pWSet), tstrerror(terrno));
      if (pCommith->isRFileSet) {
        tsdbCloseAndUnsetFSet(&(pCommith->readh));
      }
      return -1;
    }
H
Hongze Cheng 已提交
1218

H
more  
Hongze Cheng 已提交
1219 1220
    pCommith->isDFileSame = false;
    pCommith->isLFileSame = false;
H
Hongze Cheng 已提交
1221

S
Shengliang Guan 已提交
1222
    tsdbDebug("vgId:%d, FSET %d at level %d disk id %d is created to commit", REPO_ID(pRepo), TSDB_FSET_FID(pWSet),
H
more  
Hongze Cheng 已提交
1223 1224 1225 1226
              TSDB_FSET_LEVEL(pWSet), TSDB_FSET_ID(pWSet));
  } else {
    did.level = TSDB_FSET_LEVEL(pSet);
    did.id = TSDB_FSET_ID(pSet);
H
Hongze Cheng 已提交
1227

H
more  
Hongze Cheng 已提交
1228 1229
    pCommith->wSet.fid = fid;
    pCommith->wSet.state = 0;
H
Hongze Cheng 已提交
1230

H
more  
Hongze Cheng 已提交
1231 1232
    // TSDB_FILE_HEAD
    SDFile *pWHeadf = TSDB_COMMIT_HEAD_FILE(pCommith);
S
Shengliang Guan 已提交
1233
    tsdbInitDFile(pRepo, pWHeadf, did, fid, FS_TXN_VERSION(REPO_FS(pRepo)), TSDB_FILE_HEAD);
1234
    if (tsdbCreateDFile(pRepo, pWHeadf, true, TSDB_FILE_HEAD) < 0) {
S
Shengliang Guan 已提交
1235
      tsdbError("vgId:%d, failed to create file %s to commit since %s", REPO_ID(pRepo), TSDB_FILE_FULL_NAME(pWHeadf),
H
more  
Hongze Cheng 已提交
1236
                tstrerror(terrno));
H
Hongze Cheng 已提交
1237

H
more  
Hongze Cheng 已提交
1238 1239 1240
      if (pCommith->isRFileSet) {
        tsdbCloseAndUnsetFSet(&(pCommith->readh));
        return -1;
H
Hongze Cheng 已提交
1241 1242 1243
      }
    }

H
more  
Hongze Cheng 已提交
1244 1245 1246 1247
    // TSDB_FILE_DATA
    SDFile *pRDataf = TSDB_READ_DATA_FILE(&(pCommith->readh));
    SDFile *pWDataf = TSDB_COMMIT_DATA_FILE(pCommith);
    tsdbInitDFileEx(pWDataf, pRDataf);
1248 1249
    // if (tsdbOpenDFile(pWDataf, O_WRONLY) < 0) {
    if (tsdbOpenDFile(pWDataf, TD_FILE_WRITE) < 0) {
S
Shengliang Guan 已提交
1250
      tsdbError("vgId:%d, failed to open file %s to commit since %s", REPO_ID(pRepo), TSDB_FILE_FULL_NAME(pWDataf),
H
more  
Hongze Cheng 已提交
1251
                tstrerror(terrno));
H
Hongze Cheng 已提交
1252

H
more  
Hongze Cheng 已提交
1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268
      tsdbCloseDFileSet(pWSet);
      tsdbRemoveDFile(pWHeadf);
      if (pCommith->isRFileSet) {
        tsdbCloseAndUnsetFSet(&(pCommith->readh));
        return -1;
      }
    }
    pCommith->isDFileSame = true;

    // TSDB_FILE_LAST
    SDFile *pRLastf = TSDB_READ_LAST_FILE(&(pCommith->readh));
    SDFile *pWLastf = TSDB_COMMIT_LAST_FILE(pCommith);
    if (pRLastf->info.size < 32 * 1024) {
      tsdbInitDFileEx(pWLastf, pRLastf);
      pCommith->isLFileSame = true;

1269 1270
      // if (tsdbOpenDFile(pWLastf, O_WRONLY) < 0) {
      if (tsdbOpenDFile(pWLastf, TD_FILE_WRITE) < 0) {
S
Shengliang Guan 已提交
1271
        tsdbError("vgId:%d, failed to open file %s to commit since %s", REPO_ID(pRepo), TSDB_FILE_FULL_NAME(pWLastf),
H
more  
Hongze Cheng 已提交
1272
                  tstrerror(terrno));
H
Hongze Cheng 已提交
1273

H
more  
Hongze Cheng 已提交
1274 1275 1276 1277 1278 1279 1280 1281
        tsdbCloseDFileSet(pWSet);
        tsdbRemoveDFile(pWHeadf);
        if (pCommith->isRFileSet) {
          tsdbCloseAndUnsetFSet(&(pCommith->readh));
          return -1;
        }
      }
    } else {
S
Shengliang Guan 已提交
1282
      tsdbInitDFile(pRepo, pWLastf, did, fid, FS_TXN_VERSION(REPO_FS(pRepo)), TSDB_FILE_LAST);
H
more  
Hongze Cheng 已提交
1283
      pCommith->isLFileSame = false;
H
Hongze Cheng 已提交
1284

1285
      if (tsdbCreateDFile(pRepo, pWLastf, true, TSDB_FILE_LAST) < 0) {
H
Hongze Cheng 已提交
1286 1287
        tsdbError("vgId:%d, failed to create file %s to commit since %s", REPO_ID(pRepo),
        TSDB_FILE_FULL_NAME(pWLastf),
H
more  
Hongze Cheng 已提交
1288
                  tstrerror(terrno));
H
Hongze Cheng 已提交
1289

H
more  
Hongze Cheng 已提交
1290 1291 1292 1293 1294 1295 1296 1297
        tsdbCloseDFileSet(pWSet);
        (void)tsdbRemoveDFile(pWHeadf);
        if (pCommith->isRFileSet) {
          tsdbCloseAndUnsetFSet(&(pCommith->readh));
          return -1;
        }
      }
    }
1298 1299 1300 1301 1302

    // TSDB_FILE_SMAD
    SDFile *pRSmadF = TSDB_READ_SMAD_FILE(&(pCommith->readh));
    SDFile *pWSmadF = TSDB_COMMIT_SMAD_FILE(pCommith);

1303
    if (!taosCheckExistFile(TSDB_FILE_FULL_NAME(pRSmadF))) {
S
Shengliang Guan 已提交
1304
      tsdbDebug("vgId:%d, create data file %s as not exist", REPO_ID(pRepo), TSDB_FILE_FULL_NAME(pRSmadF));
1305 1306 1307
      tsdbInitDFile(pRepo, pWSmadF, did, fid, FS_TXN_VERSION(REPO_FS(pRepo)), TSDB_FILE_SMAD);

      if (tsdbCreateDFile(pRepo, pWSmadF, true, TSDB_FILE_SMAD) < 0) {
H
Hongze Cheng 已提交
1308 1309
        tsdbError("vgId:%d, failed to create file %s to commit since %s", REPO_ID(pRepo),
        TSDB_FILE_FULL_NAME(pWSmadF),
1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321
                  tstrerror(terrno));

        tsdbCloseDFileSet(pWSet);
        (void)tsdbRemoveDFile(pWHeadf);
        if (pCommith->isRFileSet) {
          tsdbCloseAndUnsetFSet(&(pCommith->readh));
          return -1;
        }
      }
    } else {
      tsdbInitDFileEx(pWSmadF, pRSmadF);
      if (tsdbOpenDFile(pWSmadF, O_RDWR) < 0) {
S
Shengliang Guan 已提交
1322
        tsdbError("vgId:%d, failed to open file %s to commit since %s", REPO_ID(pRepo), TSDB_FILE_FULL_NAME(pWSmadF),
1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337
                  tstrerror(terrno));

        tsdbCloseDFileSet(pWSet);
        tsdbRemoveDFile(pWHeadf);
        if (pCommith->isRFileSet) {
          tsdbCloseAndUnsetFSet(&(pCommith->readh));
          return -1;
        }
      }
    }

    // TSDB_FILE_SMAL
    SDFile *pRSmalF = TSDB_READ_SMAL_FILE(&(pCommith->readh));
    SDFile *pWSmalF = TSDB_COMMIT_SMAL_FILE(pCommith);

1338
    if ((pCommith->isLFileSame) && taosCheckExistFile(TSDB_FILE_FULL_NAME(pRSmalF))) {
1339 1340
      tsdbInitDFileEx(pWSmalF, pRSmalF);
      if (tsdbOpenDFile(pWSmalF, O_RDWR) < 0) {
S
Shengliang Guan 已提交
1341
        tsdbError("vgId:%d, failed to open file %s to commit since %s", REPO_ID(pRepo), TSDB_FILE_FULL_NAME(pWSmalF),
1342 1343 1344 1345 1346 1347 1348 1349 1350 1351
                  tstrerror(terrno));

        tsdbCloseDFileSet(pWSet);
        tsdbRemoveDFile(pWHeadf);
        if (pCommith->isRFileSet) {
          tsdbCloseAndUnsetFSet(&(pCommith->readh));
          return -1;
        }
      }
    } else {
S
Shengliang Guan 已提交
1352
      tsdbDebug("vgId:%d, create data file %s as not exist", REPO_ID(pRepo), TSDB_FILE_FULL_NAME(pRSmalF));
1353 1354 1355
      tsdbInitDFile(pRepo, pWSmalF, did, fid, FS_TXN_VERSION(REPO_FS(pRepo)), TSDB_FILE_SMAL);

      if (tsdbCreateDFile(pRepo, pWSmalF, true, TSDB_FILE_SMAL) < 0) {
H
Hongze Cheng 已提交
1356 1357
        tsdbError("vgId:%d, failed to create file %s to commit since %s", REPO_ID(pRepo),
        TSDB_FILE_FULL_NAME(pWSmalF),
1358 1359 1360 1361 1362 1363 1364 1365 1366 1367
                  tstrerror(terrno));

        tsdbCloseDFileSet(pWSet);
        (void)tsdbRemoveDFile(pWHeadf);
        if (pCommith->isRFileSet) {
          tsdbCloseAndUnsetFSet(&(pCommith->readh));
          return -1;
        }
      }
    }
H
more  
Hongze Cheng 已提交
1368
  }
H
Hongze Cheng 已提交
1369 1370 1371 1372

  return 0;
}

H
more  
Hongze Cheng 已提交
1373
// extern int32_t tsTsdbMetaCompactRatio;
H
Hongze Cheng 已提交
1374

H
more  
Hongze Cheng 已提交
1375 1376
static int tsdbWriteBlockInfoImpl(SDFile *pHeadf, STable *pTable, SArray *pSupA, SArray *pSubA, void **ppBuf,
                                  SBlockIdx *pIdx) {
H
more  
Hongze Cheng 已提交
1377 1378 1379 1380 1381
  size_t      nSupBlocks;
  size_t      nSubBlocks;
  uint32_t    tlen;
  SBlockInfo *pBlkInfo;
  int64_t     offset;
L
Liu Jicong 已提交
1382
  SBlock     *pBlock;
H
Hongze Cheng 已提交
1383

H
more  
Hongze Cheng 已提交
1384
  memset(pIdx, 0, sizeof(*pIdx));
H
Hongze Cheng 已提交
1385

H
more  
Hongze Cheng 已提交
1386 1387
  nSupBlocks = taosArrayGetSize(pSupA);
  nSubBlocks = (pSubA == NULL) ? 0 : taosArrayGetSize(pSubA);
H
Hongze Cheng 已提交
1388

H
more  
Hongze Cheng 已提交
1389 1390 1391 1392
  if (nSupBlocks <= 0) {
    // No data (data all deleted)
    return 0;
  }
H
Hongze Cheng 已提交
1393

H
more  
Hongze Cheng 已提交
1394 1395 1396
  tlen = (uint32_t)(sizeof(SBlockInfo) + sizeof(SBlock) * (nSupBlocks + nSubBlocks) + sizeof(TSCKSUM));
  if (tsdbMakeRoom(ppBuf, tlen) < 0) return -1;
  pBlkInfo = *ppBuf;
H
Hongze Cheng 已提交
1397

H
more  
Hongze Cheng 已提交
1398
  pBlkInfo->delimiter = TSDB_FILE_DELIMITER;
H
Hongze Cheng 已提交
1399 1400
  pBlkInfo->suid = pTable->suid;
  pBlkInfo->uid = pTable->uid;
H
Hongze Cheng 已提交
1401

H
more  
Hongze Cheng 已提交
1402 1403 1404
  memcpy((void *)(pBlkInfo->blocks), taosArrayGet(pSupA, 0), nSupBlocks * sizeof(SBlock));
  if (nSubBlocks > 0) {
    memcpy((void *)(pBlkInfo->blocks + nSupBlocks), taosArrayGet(pSubA, 0), nSubBlocks * sizeof(SBlock));
H
Hongze Cheng 已提交
1405

H
more  
Hongze Cheng 已提交
1406 1407
    for (int i = 0; i < nSupBlocks; i++) {
      pBlock = pBlkInfo->blocks + i;
H
Hongze Cheng 已提交
1408

H
more  
Hongze Cheng 已提交
1409 1410 1411 1412 1413
      if (pBlock->numOfSubBlocks > 1) {
        pBlock->offset += (sizeof(SBlockInfo) + sizeof(SBlock) * nSupBlocks);
      }
    }
  }
H
Hongze Cheng 已提交
1414

H
more  
Hongze Cheng 已提交
1415
  taosCalcChecksumAppend(0, (uint8_t *)pBlkInfo, tlen);
H
Hongze Cheng 已提交
1416

H
more  
Hongze Cheng 已提交
1417 1418 1419
  if (tsdbAppendDFile(pHeadf, (void *)pBlkInfo, tlen, &offset) < 0) {
    return -1;
  }
H
Hongze Cheng 已提交
1420

H
more  
Hongze Cheng 已提交
1421
  tsdbUpdateDFileMagic(pHeadf, POINTER_SHIFT(pBlkInfo, tlen - sizeof(TSCKSUM)));
H
Hongze Cheng 已提交
1422

H
more  
Hongze Cheng 已提交
1423 1424
  // Set pIdx
  pBlock = taosArrayGetLast(pSupA);
H
Hongze Cheng 已提交
1425

H
Hongze Cheng 已提交
1426 1427
  pIdx->suid = pTable->suid;
  pIdx->uid = pTable->uid;
H
more  
Hongze Cheng 已提交
1428
  pIdx->hasLast = pBlock->last ? 1 : 0;
H
Hongze Cheng 已提交
1429
  pIdx->maxKey = pBlock->maxKey;
H
more  
Hongze Cheng 已提交
1430 1431 1432
  pIdx->numOfBlocks = (uint32_t)nSupBlocks;
  pIdx->len = tlen;
  pIdx->offset = (uint32_t)offset;
H
Hongze Cheng 已提交
1433

H
more  
Hongze Cheng 已提交
1434 1435
  return 0;
}
H
Hongze Cheng 已提交
1436

H
more  
Hongze Cheng 已提交
1437
static int tsdbWriteBlockIdx(SDFile *pHeadf, SArray *pIdxA, void **ppBuf) {
H
more  
Hongze Cheng 已提交
1438 1439 1440 1441
  SBlockIdx *pBlkIdx;
  size_t     nidx = taosArrayGetSize(pIdxA);
  int        tlen = 0, size;
  int64_t    offset;
H
more  
Hongze Cheng 已提交
1442

H
more  
Hongze Cheng 已提交
1443 1444 1445 1446 1447 1448
  if (nidx <= 0) {
    // All data are deleted
    pHeadf->info.offset = 0;
    pHeadf->info.len = 0;
    return 0;
  }
H
Hongze Cheng 已提交
1449

H
more  
Hongze Cheng 已提交
1450 1451
  for (size_t i = 0; i < nidx; i++) {
    pBlkIdx = (SBlockIdx *)taosArrayGet(pIdxA, i);
H
Hongze Cheng 已提交
1452

H
more  
Hongze Cheng 已提交
1453 1454
    size = tsdbEncodeSBlockIdx(NULL, pBlkIdx);
    if (tsdbMakeRoom(ppBuf, tlen + size) < 0) return -1;
H
Hongze Cheng 已提交
1455

H
more  
Hongze Cheng 已提交
1456 1457
    void *ptr = POINTER_SHIFT(*ppBuf, tlen);
    tsdbEncodeSBlockIdx(&ptr, pBlkIdx);
H
Hongze Cheng 已提交
1458

H
more  
Hongze Cheng 已提交
1459 1460
    tlen += size;
  }
H
Hongze Cheng 已提交
1461

H
more  
Hongze Cheng 已提交
1462 1463 1464
  tlen += sizeof(TSCKSUM);
  if (tsdbMakeRoom(ppBuf, tlen) < 0) return -1;
  taosCalcChecksumAppend(0, (uint8_t *)(*ppBuf), tlen);
H
Hongze Cheng 已提交
1465

H
more  
Hongze Cheng 已提交
1466 1467 1468
  if (tsdbAppendDFile(pHeadf, *ppBuf, tlen, &offset) < tlen) {
    return -1;
  }
H
Hongze Cheng 已提交
1469

H
more  
Hongze Cheng 已提交
1470 1471 1472
  tsdbUpdateDFileMagic(pHeadf, POINTER_SHIFT(*ppBuf, tlen - sizeof(TSCKSUM)));
  pHeadf->info.offset = (uint32_t)offset;
  pHeadf->info.len = tlen;
H
Hongze Cheng 已提交
1473

H
more  
Hongze Cheng 已提交
1474 1475
  return 0;
}
H
Hongze Cheng 已提交
1476

H
Hongze Cheng 已提交
1477
// =================== Commit Time-Series Data
H
refact  
Hongze Cheng 已提交
1478
static int tsdbCommitToTable(SCommitter *pCommith, int tid) {
H
Hongze Cheng 已提交
1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530
  SCommitIter *pIter = pCommith->iters + tid;
  TSKEY        nextKey = tsdbNextIterKey(pIter->pIter);

  tsdbResetCommitTable(pCommith);

  // Set commit table
  if (tsdbSetCommitTable(pCommith, pIter->pTable) < 0) {
    return -1;
  }

  // No disk data and no memory data, just return
  if (pCommith->readh.pBlkIdx == NULL && (nextKey == TSDB_DATA_TIMESTAMP_NULL || nextKey > pCommith->maxKey)) {
    return 0;
  }

  // Must has disk data or has memory data
  int     nBlocks;
  int     bidx = 0;
  SBlock *pBlock;

  if (pCommith->readh.pBlkIdx) {
    if (tsdbLoadBlockInfo(&(pCommith->readh), NULL) < 0) {
      return -1;
    }

    nBlocks = pCommith->readh.pBlkIdx->numOfBlocks;
  } else {
    nBlocks = 0;
  }

  if (bidx < nBlocks) {
    pBlock = pCommith->readh.pBlkInfo->blocks + bidx;
  } else {
    pBlock = NULL;
  }

  while (true) {
    if (pBlock == NULL && (nextKey == TSDB_DATA_TIMESTAMP_NULL || nextKey > pCommith->maxKey)) break;

    if ((nextKey == TSDB_DATA_TIMESTAMP_NULL || nextKey > pCommith->maxKey) ||
        (pBlock && (!pBlock->last) && tsdbComparKeyBlock((void *)(&nextKey), pBlock) > 0)) {
      if (tsdbMoveBlock(pCommith, bidx) < 0) {
        return -1;
      }

      bidx++;
      if (bidx < nBlocks) {
        pBlock = pCommith->readh.pBlkInfo->blocks + bidx;
      } else {
        pBlock = NULL;
      }
    } else if (pBlock && (pBlock->last || tsdbComparKeyBlock((void *)(&nextKey), pBlock) == 0)) {
H
more  
Hongze Cheng 已提交
1531 1532 1533 1534
      // merge pBlock data and memory data
      if (tsdbMergeMemData(pCommith, pIter, bidx) < 0) {
        return -1;
      }
H
more  
Hongze Cheng 已提交
1535

H
more  
Hongze Cheng 已提交
1536 1537 1538 1539 1540 1541 1542
      bidx++;
      if (bidx < nBlocks) {
        pBlock = pCommith->readh.pBlkInfo->blocks + bidx;
      } else {
        pBlock = NULL;
      }
      nextKey = tsdbNextIterKey(pIter->pIter);
H
Hongze Cheng 已提交
1543
    } else {
H
more  
Hongze Cheng 已提交
1544 1545 1546 1547 1548 1549
      // Only commit memory data
      if (pBlock == NULL) {
        if (tsdbCommitMemData(pCommith, pIter, pCommith->maxKey, false) < 0) {
          return -1;
        }
      } else {
H
Hongze Cheng 已提交
1550
        if (tsdbCommitMemData(pCommith, pIter, pBlock->minKey.ts - 1, true) < 0) {
H
more  
Hongze Cheng 已提交
1551 1552 1553 1554
          return -1;
        }
      }
      nextKey = tsdbNextIterKey(pIter->pIter);
H
Hongze Cheng 已提交
1555 1556 1557
    }
  }

C
Cary Xu 已提交
1558
  if (tsdbWriteBlockInfo(pCommith) < 0) {
S
Shengliang Guan 已提交
1559
    tsdbError("vgId:%d, failed to write SBlockInfo part into file %s since %s", TSDB_COMMIT_REPO_ID(pCommith),
C
Cary Xu 已提交
1560 1561 1562 1563 1564 1565 1566
              TSDB_FILE_FULL_NAME(TSDB_COMMIT_HEAD_FILE(pCommith)), tstrerror(terrno));
    return -1;
  }

  return 0;
}

H
refact  
Hongze Cheng 已提交
1567
static int tsdbMoveBlkIdx(SCommitter *pCommith, SBlockIdx *pIdx) {
1568 1569 1570 1571 1572
  SReadH   *pReadh = &pCommith->readh;
  STsdb    *pTsdb = TSDB_READ_REPO(pReadh);
  STSchema *pTSchema = NULL;
  int       nBlocks = pIdx->numOfBlocks;
  int       bidx = 0;
C
Cary Xu 已提交
1573 1574 1575 1576 1577 1578 1579 1580 1581

  tsdbResetCommitTable(pCommith);

  pReadh->pBlkIdx = pIdx;

  if (tsdbLoadBlockInfo(pReadh, NULL) < 0) {
    return -1;
  }

H
Hongze Cheng 已提交
1582
  STable table = {.suid = pIdx->suid, .uid = pIdx->uid, .pSchema = NULL};
1583 1584
  pCommith->pTable = &table;

C
Cary Xu 已提交
1585
  while (bidx < nBlocks) {
1586 1587
    if (!pTSchema && !tsdbCommitIsSameFile(pCommith, bidx)) {
      // Set commit table
1588
      pTSchema = metaGetTbTSchema(REPO_META(pTsdb), pIdx->uid, -1);  // TODO: schema version
1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599
      if (!pTSchema) {
        terrno = TSDB_CODE_OUT_OF_MEMORY;
        return -1;
      }
      table.pSchema = pTSchema;
      if (tsdbSetCommitTable(pCommith, &table) < 0) {
        taosMemoryFreeClear(pTSchema);
        return -1;
      }
    }

C
Cary Xu 已提交
1600
    if (tsdbMoveBlock(pCommith, bidx) < 0) {
S
Shengliang Guan 已提交
1601
      tsdbError("vgId:%d, failed to move block into file %s since %s", TSDB_COMMIT_REPO_ID(pCommith),
C
Cary Xu 已提交
1602
                TSDB_FILE_FULL_NAME(TSDB_COMMIT_HEAD_FILE(pCommith)), tstrerror(terrno));
1603
      taosMemoryFreeClear(pTSchema);
C
Cary Xu 已提交
1604 1605
      return -1;
    }
1606

C
Cary Xu 已提交
1607 1608 1609
    ++bidx;
  }

H
more  
Hongze Cheng 已提交
1610
  if (tsdbWriteBlockInfo(pCommith) < 0) {
S
Shengliang Guan 已提交
1611
    tsdbError("vgId:%d, failed to write SBlockInfo part into file %s since %s", TSDB_COMMIT_REPO_ID(pCommith),
H
more  
Hongze Cheng 已提交
1612
              TSDB_FILE_FULL_NAME(TSDB_COMMIT_HEAD_FILE(pCommith)), tstrerror(terrno));
1613
    taosMemoryFreeClear(pTSchema);
H
more  
Hongze Cheng 已提交
1614 1615
    return -1;
  }
H
Hongze Cheng 已提交
1616

1617
  taosMemoryFreeClear(pTSchema);
H
Hongze Cheng 已提交
1618 1619 1620
  return 0;
}

H
refact  
Hongze Cheng 已提交
1621
static int tsdbSetCommitTable(SCommitter *pCommith, STable *pTable) {
H
Hongze Cheng 已提交
1622
  STSchema *pSchema = tsdbGetTableSchemaImpl(TSDB_COMMIT_REPO(pCommith), pTable, false, false, -1);
H
Hongze Cheng 已提交
1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644

  pCommith->pTable = pTable;

  if (tdInitDataCols(pCommith->pDataCols, pSchema) < 0) {
    terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
    return -1;
  }

  if (pCommith->isRFileSet) {
    if (tsdbSetReadTable(&(pCommith->readh), pTable) < 0) {
      return -1;
    }
  } else {
    pCommith->readh.pBlkIdx = NULL;
  }
  return 0;
}

static int tsdbComparKeyBlock(const void *arg1, const void *arg2) {
  TSKEY   key = *(TSKEY *)arg1;
  SBlock *pBlock = (SBlock *)arg2;

H
Hongze Cheng 已提交
1645
  if (key < pBlock->minKey.ts) {
H
Hongze Cheng 已提交
1646
    return -1;
H
Hongze Cheng 已提交
1647
  } else if (key > pBlock->maxKey.ts) {
H
Hongze Cheng 已提交
1648 1649 1650 1651 1652 1653
    return 1;
  } else {
    return 0;
  }
}

C
Cary Xu 已提交
1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670
/**
 * @brief Write SDataCols to data file.
 *
 * @param pRepo
 * @param pTable
 * @param pDFile
 * @param pDFileAggr
 * @param pDataCols The pDataCols would be generated from mem/imem directly with 2 bits bitmap or from tsdbRead
 * interface with 1 bit bitmap.
 * @param pBlock
 * @param isLast
 * @param isSuper
 * @param ppBuf
 * @param ppCBuf
 * @param ppExBuf
 * @return int
 */
H
more  
Hongze Cheng 已提交
1671
static int tsdbWriteBlockImpl(STsdb *pRepo, STable *pTable, SDFile *pDFile, SDFile *pDFileAggr, SDataCols *pDataCols,
H
Hongze Cheng 已提交
1672 1673
                              SBlock *pBlock, bool isLast, bool isSuper, void **ppBuf, void **ppCBuf, void **ppExBuf)
                              {
C
Cary Xu 已提交
1674 1675
  STsdbCfg     *pCfg = REPO_CFG(pRepo);
  SBlockData   *pBlockData = NULL;
1676
  SAggrBlkData *pAggrBlkData = NULL;
C
Cary Xu 已提交
1677
  STSchema     *pSchema = pTable->pSchema;
1678 1679
  int64_t       offset = 0, offsetAggr = 0;
  int           rowsToWrite = pDataCols->numOfRows;
H
Hongze Cheng 已提交
1680

H
refact  
Hongze Cheng 已提交
1681 1682
  ASSERT(rowsToWrite > 0 && rowsToWrite <= pCfg->maxRows);
  ASSERT((!isLast) || rowsToWrite < pCfg->minRows);
H
Hongze Cheng 已提交
1683 1684

  // Make buffer space
1685
  if (tsdbMakeRoom(ppBuf, tsdbBlockStatisSize(pDataCols->numOfCols, SBlockVerLatest)) < 0) {
H
Hongze Cheng 已提交
1686 1687 1688 1689
    return -1;
  }
  pBlockData = (SBlockData *)(*ppBuf);

1690 1691 1692 1693 1694
  if (tsdbMakeRoom(ppExBuf, tsdbBlockAggrSize(pDataCols->numOfCols, SBlockVerLatest)) < 0) {
    return -1;
  }
  pAggrBlkData = (SAggrBlkData *)(*ppExBuf);

H
Hongze Cheng 已提交
1695
  // Get # of cols not all NULL(not including key column)
C
Cary Xu 已提交
1696 1697
  col_id_t nColsNotAllNull = 0;
  col_id_t nColsOfBlockSma = 0;
1698
  for (int ncol = 1; ncol < pDataCols->numOfCols; ++ncol) {  // ncol from 1, we skip the timestamp column
C
Cary Xu 已提交
1699 1700 1701
    STColumn    *pColumn = pSchema->columns + ncol;
    SDataCol    *pDataCol = pDataCols->cols + ncol;
    SBlockCol   *pBlockCol = pBlockData->cols + nColsNotAllNull;
C
Cary Xu 已提交
1702
    SAggrBlkCol *pAggrBlkCol = (SAggrBlkCol *)pAggrBlkData + nColsOfBlockSma;
H
Hongze Cheng 已提交
1703 1704 1705 1706 1707 1708

    if (isAllRowsNull(pDataCol)) {  // all data to commit are NULL, just ignore it
      continue;
    }

    memset(pBlockCol, 0, sizeof(*pBlockCol));
1709
    memset(pAggrBlkCol, 0, sizeof(*pAggrBlkCol));
H
Hongze Cheng 已提交
1710 1711 1712

    pBlockCol->colId = pDataCol->colId;
    pBlockCol->type = pDataCol->type;
1713 1714
    pAggrBlkCol->colId = pDataCol->colId;

C
Cary Xu 已提交
1715
    if (isSuper && IS_BSMA_ON(pColumn) && tDataTypes[pDataCol->type].statisFunc) {
1716
#if 0
H
Hongze Cheng 已提交
1717 1718 1719
      (*tDataTypes[pDataCol->type].statisFunc)(pDataCol->pData, rowsToWrite, &(pBlockCol->min), &(pBlockCol->max),
                                               &(pBlockCol->sum), &(pBlockCol->minIndex), &(pBlockCol->maxIndex),
                                               &(pBlockCol->numOfNull));
1720
#endif
H
Hongze Cheng 已提交
1721 1722
      (*tDataTypes[pDataCol->type].statisFunc)(pDataCols->bitmapMode, pDataCol->pBitmap, pDataCol->pData,
      rowsToWrite,
C
Cary Xu 已提交
1723 1724
                                               &(pAggrBlkCol->min), &(pAggrBlkCol->max), &(pAggrBlkCol->sum),
                                               &(pAggrBlkCol->minIndex), &(pAggrBlkCol->maxIndex),
1725 1726 1727
                                               &(pAggrBlkCol->numOfNull));

      if (pAggrBlkCol->numOfNull == 0) {
C
Cary Xu 已提交
1728
        pBlockCol->blen = 0;
C
Cary Xu 已提交
1729
      } else {
C
Cary Xu 已提交
1730
        pBlockCol->blen = 1;
C
Cary Xu 已提交
1731
      }
C
Cary Xu 已提交
1732
      ++nColsOfBlockSma;
C
Cary Xu 已提交
1733 1734
    } else if (tdIsBitmapBlkNorm(pDataCol->pBitmap, rowsToWrite, pDataCols->bitmapMode)) {
      // check if all rows normal
C
Cary Xu 已提交
1735
      pBlockCol->blen = 0;
C
Cary Xu 已提交
1736
    } else {
C
Cary Xu 已提交
1737
      pBlockCol->blen = 1;
H
Hongze Cheng 已提交
1738
    }
C
Cary Xu 已提交
1739 1740

    ++nColsNotAllNull;
H
Hongze Cheng 已提交
1741 1742 1743 1744 1745 1746 1747
  }

  ASSERT(nColsNotAllNull >= 0 && nColsNotAllNull <= pDataCols->numOfCols);

  // Compress the data if neccessary
  int      tcol = 0;  // counter of not all NULL and written columns
  uint32_t toffset = 0;
1748
  int32_t  tsize = (int32_t)tsdbBlockStatisSize(nColsNotAllNull, SBlockVerLatest);
H
Hongze Cheng 已提交
1749
  int32_t  lsize = tsize;
C
Cary Xu 已提交
1750
  uint32_t tsizeAggr = (uint32_t)tsdbBlockAggrSize(nColsOfBlockSma, SBlockVerLatest);
H
Hongze Cheng 已提交
1751
  int32_t  keyLen = 0;
C
Cary Xu 已提交
1752
  int32_t  nBitmaps = (int32_t)TD_BITMAP_BYTES(rowsToWrite);
C
Cary Xu 已提交
1753
  int32_t  sBitmaps = isSuper ? (int32_t)TD_BITMAP_BYTES_I(rowsToWrite) : nBitmaps;
C
Cary Xu 已提交
1754

1755
  for (int ncol = 0; ncol < pDataCols->numOfCols; ++ncol) {
H
Hongze Cheng 已提交
1756 1757 1758
    // All not NULL columns finish
    if (ncol != 0 && tcol >= nColsNotAllNull) break;

L
Liu Jicong 已提交
1759
    SDataCol  *pDataCol = pDataCols->cols + ncol;
H
Hongze Cheng 已提交
1760 1761 1762 1763 1764
    SBlockCol *pBlockCol = pBlockData->cols + tcol;

    if (ncol != 0 && (pDataCol->colId != pBlockCol->colId)) continue;

    int32_t flen;  // final length
C
Cary Xu 已提交
1765
    int32_t tlen = dataColGetNEleLen(pDataCol, rowsToWrite, pDataCols->bitmapMode);
C
Cary Xu 已提交
1766

C
Cary Xu 已提交
1767
#ifdef TD_SUPPORT_BITMAP
C
Cary Xu 已提交
1768
    int32_t tBitmaps = 0;
1769
    int32_t tBitmapsLen = 0;
C
Cary Xu 已提交
1770
    if ((ncol != 0) && (pBlockCol->blen > 0)) {
C
Cary Xu 已提交
1771
      tBitmaps = isSuper ? sBitmaps : nBitmaps;
C
Cary Xu 已提交
1772
    }
C
Cary Xu 已提交
1773
#endif
C
Cary Xu 已提交
1774

C
bug fix  
Cary Xu 已提交
1775
    void *tptr, *bptr;
H
Hongze Cheng 已提交
1776 1777

    // Make room
1778
    if (tsdbMakeRoom(ppBuf, lsize + tlen + tBitmaps + 2 * COMP_OVERFLOW_BYTES + sizeof(TSCKSUM)) < 0) {
H
Hongze Cheng 已提交
1779 1780 1781 1782 1783 1784
      return -1;
    }
    pBlockData = (SBlockData *)(*ppBuf);
    pBlockCol = pBlockData->cols + tcol;
    tptr = POINTER_SHIFT(pBlockData, lsize);

H
more  
Hongze Cheng 已提交
1785
    if (pCfg->compression == TWO_STAGE_COMP && tsdbMakeRoom(ppCBuf, tlen + COMP_OVERFLOW_BYTES) < 0) {
H
Hongze Cheng 已提交
1786 1787 1788 1789 1790
      return -1;
    }

    // Compress or just copy
    if (pCfg->compression) {
1791
#if 0
C
Cary Xu 已提交
1792
      flen = (*(tDataTypes[pDataCol->type].compFunc))((char *)pDataCol->pData, tlen, rowsToWrite + tBitmaps, tptr,
H
Hongze Cheng 已提交
1793 1794
                                                      tlen + COMP_OVERFLOW_BYTES, pCfg->compression, *ppCBuf,
                                                      tlen + COMP_OVERFLOW_BYTES);
1795 1796 1797 1798 1799
#endif
      flen = (*(tDataTypes[pDataCol->type].compFunc))((char *)pDataCol->pData, tlen, rowsToWrite, tptr,
                                                      tlen + COMP_OVERFLOW_BYTES, pCfg->compression, *ppCBuf,
                                                      tlen + COMP_OVERFLOW_BYTES);
      if (tBitmaps > 0) {
C
bug fix  
Cary Xu 已提交
1800
        bptr = POINTER_SHIFT(pBlockData, lsize + flen);
C
Cary Xu 已提交
1801
        if (isSuper && !tdDataColsIsBitmapI(pDataCols)) {
C
Cary Xu 已提交
1802
          tdMergeBitmap((uint8_t *)pDataCol->pBitmap, rowsToWrite, (uint8_t *)pDataCol->pBitmap);
C
Cary Xu 已提交
1803
        }
1804
        tBitmapsLen =
C
bug fix  
Cary Xu 已提交
1805
            tsCompressTinyint((char *)pDataCol->pBitmap, tBitmaps, tBitmaps, bptr, tBitmaps + COMP_OVERFLOW_BYTES,
1806 1807 1808 1809
                              pCfg->compression, *ppCBuf, tBitmaps + COMP_OVERFLOW_BYTES);
        TASSERT((tBitmapsLen > 0) && (tBitmapsLen <= (tBitmaps + COMP_OVERFLOW_BYTES)));
        flen += tBitmapsLen;
      }
H
Hongze Cheng 已提交
1810 1811 1812
    } else {
      flen = tlen;
      memcpy(tptr, pDataCol->pData, flen);
1813
      if (tBitmaps > 0) {
C
bug fix  
Cary Xu 已提交
1814
        bptr = POINTER_SHIFT(pBlockData, lsize + flen);
1815 1816 1817
        if (isSuper && !tdDataColsIsBitmapI(pDataCols)) {
          tdMergeBitmap((uint8_t *)pDataCol->pBitmap, rowsToWrite, (uint8_t *)pDataCol->pBitmap);
        }
C
bug fix  
Cary Xu 已提交
1818
        memcpy(bptr, pDataCol->pBitmap, tBitmaps);
1819 1820 1821
        tBitmapsLen = tBitmaps;
        flen += tBitmapsLen;
      }
H
Hongze Cheng 已提交
1822 1823 1824 1825
    }

    // Add checksum
    ASSERT(flen > 0);
1826
    ASSERT(tBitmapsLen <= 1024);
H
Hongze Cheng 已提交
1827 1828 1829 1830 1831
    flen += sizeof(TSCKSUM);
    taosCalcChecksumAppend(0, (uint8_t *)tptr, flen);
    tsdbUpdateDFileMagic(pDFile, POINTER_SHIFT(tptr, flen - sizeof(TSCKSUM)));

    if (ncol != 0) {
H
Hongze Cheng 已提交
1832
      pBlockCol->offset = toffset;
1833 1834
      pBlockCol->len = flen;  // data + bitmaps
      pBlockCol->blen = tBitmapsLen;
1835
      ++tcol;
H
Hongze Cheng 已提交
1836 1837 1838 1839 1840 1841 1842 1843 1844
    } else {
      keyLen = flen;
    }

    toffset += flen;
    lsize += flen;
  }

  pBlockData->delimiter = TSDB_FILE_DELIMITER;
H
Hongze Cheng 已提交
1845
  pBlockData->uid = pTable->uid;
H
Hongze Cheng 已提交
1846 1847 1848 1849 1850 1851 1852 1853 1854 1855
  pBlockData->numOfCols = nColsNotAllNull;

  taosCalcChecksumAppend(0, (uint8_t *)pBlockData, tsize);
  tsdbUpdateDFileMagic(pDFile, POINTER_SHIFT(pBlockData, tsize - sizeof(TSCKSUM)));

  // Write the whole block to file
  if (tsdbAppendDFile(pDFile, (void *)pBlockData, lsize, &offset) < lsize) {
    return -1;
  }

C
Cary Xu 已提交
1856
  uint32_t aggrStatus = nColsOfBlockSma > 0 ? 1 : 0;
1857 1858 1859 1860 1861 1862 1863 1864 1865 1866
  if (aggrStatus > 0) {
    taosCalcChecksumAppend(0, (uint8_t *)pAggrBlkData, tsizeAggr);
    tsdbUpdateDFileMagic(pDFileAggr, POINTER_SHIFT(pAggrBlkData, tsizeAggr - sizeof(TSCKSUM)));

    // Write the whole block to file
    if (tsdbAppendDFile(pDFileAggr, (void *)pAggrBlkData, tsizeAggr, &offsetAggr) < tsizeAggr) {
      return -1;
    }
  }

1867
  // Update pBlock membership variables
H
Hongze Cheng 已提交
1868 1869 1870 1871 1872 1873 1874 1875
  pBlock->last = isLast;
  pBlock->offset = offset;
  pBlock->algorithm = pCfg->compression;
  pBlock->numOfRows = rowsToWrite;
  pBlock->len = lsize;
  pBlock->keyLen = keyLen;
  pBlock->numOfSubBlocks = isSuper ? 1 : 0;
  pBlock->numOfCols = nColsNotAllNull;
C
Cary Xu 已提交
1876
  pBlock->numOfBSma = nColsOfBlockSma;
H
Hongze Cheng 已提交
1877 1878
  pBlock->minKey.ts = dataColsKeyFirst(pDataCols);
  pBlock->maxKey.ts = dataColsKeyLast(pDataCols);
1879 1880 1881
  pBlock->aggrStat = aggrStatus;
  pBlock->blkVer = SBlockVerLatest;
  pBlock->aggrOffset = (uint64_t)offsetAggr;
H
Hongze Cheng 已提交
1882

S
Shengliang Guan 已提交
1883
  tsdbDebug("vgId:%d, uid:%" PRId64 " a block of data is written to file %s, offset %" PRId64
H
Hongze Cheng 已提交
1884
            " numOfRows %d len %d numOfCols %" PRId16 " keyFirst %" PRId64 " keyLast %" PRId64,
H
Hongze Cheng 已提交
1885
            REPO_ID(pRepo), pTable->uid, TSDB_FILE_FULL_NAME(pDFile), offset, rowsToWrite, pBlock->len,
H
Hongze Cheng 已提交
1886
            pBlock->numOfCols, pBlock->minKey.ts, pBlock->maxKey.ts);
H
Hongze Cheng 已提交
1887 1888 1889 1890

  return 0;
}

H
refact  
Hongze Cheng 已提交
1891
static int tsdbWriteBlock(SCommitter *pCommith, SDFile *pDFile, SDataCols *pDataCols, SBlock *pBlock, bool isLast,
H
Hongze Cheng 已提交
1892
                          bool isSuper) {
1893 1894 1895 1896
  return tsdbWriteBlockImpl(TSDB_COMMIT_REPO(pCommith), TSDB_COMMIT_TABLE(pCommith), pDFile,
                            isLast ? TSDB_COMMIT_SMAL_FILE(pCommith) : TSDB_COMMIT_SMAD_FILE(pCommith), pDataCols,
                            pBlock, isLast, isSuper, (void **)(&(TSDB_COMMIT_BUF(pCommith))),
                            (void **)(&(TSDB_COMMIT_COMP_BUF(pCommith))), (void **)(&(TSDB_COMMIT_EXBUF(pCommith))));
H
Hongze Cheng 已提交
1897 1898
}

H
refact  
Hongze Cheng 已提交
1899
static int tsdbWriteBlockInfo(SCommitter *pCommih) {
L
Liu Jicong 已提交
1900
  SDFile   *pHeadf = TSDB_COMMIT_HEAD_FILE(pCommih);
H
more  
Hongze Cheng 已提交
1901
  SBlockIdx blkIdx;
L
Liu Jicong 已提交
1902
  STable   *pTable = TSDB_COMMIT_TABLE(pCommih);
H
Hongze Cheng 已提交
1903

H
Hongze Cheng 已提交
1904 1905
  if (tsdbWriteBlockInfoImpl(pHeadf, pTable, pCommih->aSupBlk, pCommih->aSubBlk, (void
  **)(&(TSDB_COMMIT_BUF(pCommih))),
H
more  
Hongze Cheng 已提交
1906 1907 1908
                             &blkIdx) < 0) {
    return -1;
  }
H
Hongze Cheng 已提交
1909

H
more  
Hongze Cheng 已提交
1910 1911 1912
  if (blkIdx.numOfBlocks == 0) {
    return 0;
  }
H
Hongze Cheng 已提交
1913

H
more  
Hongze Cheng 已提交
1914 1915 1916 1917
  if (taosArrayPush(pCommih->aBlkIdx, (void *)(&blkIdx)) == NULL) {
    terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
    return -1;
  }
H
Hongze Cheng 已提交
1918

H
more  
Hongze Cheng 已提交
1919 1920
  return 0;
}
H
Hongze Cheng 已提交
1921

H
refact  
Hongze Cheng 已提交
1922
static int tsdbCommitMemData(SCommitter *pCommith, SCommitIter *pIter, TSKEY keyLimit, bool toData) {
L
Liu Jicong 已提交
1923 1924
  STsdb     *pRepo = TSDB_COMMIT_REPO(pCommith);
  STsdbCfg  *pCfg = REPO_CFG(pRepo);
H
more  
Hongze Cheng 已提交
1925 1926
  SMergeInfo mInfo;
  int32_t    defaultRows = TSDB_COMMIT_DEFAULT_ROWS(pCommith);
L
Liu Jicong 已提交
1927
  SDFile    *pDFile;
H
more  
Hongze Cheng 已提交
1928 1929
  bool       isLast;
  SBlock     block;
H
more  
Hongze Cheng 已提交
1930

H
more  
Hongze Cheng 已提交
1931
  while (true) {
1932 1933
    tsdbLoadDataFromCache(TSDB_COMMIT_REPO(pCommith), pIter->pTable, pIter->pIter, keyLimit, defaultRows,
                          pCommith->pDataCols, NULL, 0, pCfg->update, &mInfo);
H
more  
Hongze Cheng 已提交
1934

H
more  
Hongze Cheng 已提交
1935
    if (pCommith->pDataCols->numOfRows <= 0) break;
H
more  
Hongze Cheng 已提交
1936

H
refact  
Hongze Cheng 已提交
1937
    if (toData || pCommith->pDataCols->numOfRows >= pCfg->minRows) {
H
more  
Hongze Cheng 已提交
1938 1939 1940 1941 1942 1943
      pDFile = TSDB_COMMIT_DATA_FILE(pCommith);
      isLast = false;
    } else {
      pDFile = TSDB_COMMIT_LAST_FILE(pCommith);
      isLast = true;
    }
H
Hongze Cheng 已提交
1944

H
more  
Hongze Cheng 已提交
1945
    if (tsdbWriteBlock(pCommith, pDFile, pCommith->pDataCols, &block, isLast, true) < 0) return -1;
H
Hongze Cheng 已提交
1946

H
more  
Hongze Cheng 已提交
1947 1948 1949 1950
    if (tsdbCommitAddBlock(pCommith, &block, NULL, 0) < 0) {
      return -1;
    }
  }
H
Hongze Cheng 已提交
1951

H
more  
Hongze Cheng 已提交
1952 1953
  return 0;
}
H
Hongze Cheng 已提交
1954

H
refact  
Hongze Cheng 已提交
1955
static int tsdbMergeMemData(SCommitter *pCommith, SCommitIter *pIter, int bidx) {
L
Liu Jicong 已提交
1956 1957
  STsdb     *pRepo = TSDB_COMMIT_REPO(pCommith);
  STsdbCfg  *pCfg = REPO_CFG(pRepo);
H
more  
Hongze Cheng 已提交
1958
  int        nBlocks = pCommith->readh.pBlkIdx->numOfBlocks;
L
Liu Jicong 已提交
1959
  SBlock    *pBlock = pCommith->readh.pBlkInfo->blocks + bidx;
H
more  
Hongze Cheng 已提交
1960
  TSKEY      keyLimit;
1961
  int16_t    colId = PRIMARYKEY_TIMESTAMP_COL_ID;
H
more  
Hongze Cheng 已提交
1962 1963 1964
  SMergeInfo mInfo;
  SBlock     subBlocks[TSDB_MAX_SUBBLOCKS];
  SBlock     block, supBlock;
L
Liu Jicong 已提交
1965
  SDFile    *pDFile;
H
more  
Hongze Cheng 已提交
1966 1967 1968 1969

  if (bidx == nBlocks - 1) {
    keyLimit = pCommith->maxKey;
  } else {
H
Hongze Cheng 已提交
1970
    keyLimit = pBlock[1].minKey.ts - 1;
H
more  
Hongze Cheng 已提交
1971
  }
H
Hongze Cheng 已提交
1972

H
Hongze Cheng 已提交
1973
  STbDataIter titer = *(pIter->pIter);
C
Cary Xu 已提交
1974
  if (tsdbLoadBlockDataCols(&(pCommith->readh), pBlock, NULL, &colId, 1, false) < 0) return -1;
H
Hongze Cheng 已提交
1975

1976 1977 1978
  tsdbLoadDataFromCache(TSDB_COMMIT_REPO(pCommith), pIter->pTable, &titer, keyLimit, INT32_MAX, NULL,
                        pCommith->readh.pDCols[0]->cols[0].pData, pCommith->readh.pDCols[0]->numOfRows, pCfg->update,
                        &mInfo);
H
Hongze Cheng 已提交
1979

H
more  
Hongze Cheng 已提交
1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991
  if (mInfo.nOperations == 0) {
    // no new data to insert (all updates denied)
    if (tsdbMoveBlock(pCommith, bidx) < 0) {
      return -1;
    }
    *(pIter->pIter) = titer;
  } else if (pBlock->numOfRows + mInfo.rowsInserted - mInfo.rowsDeleteSucceed == 0) {
    // Ignore the block
    ASSERT(0);
    *(pIter->pIter) = titer;
  } else if (tsdbCanAddSubBlock(pCommith, pBlock, &mInfo)) {
    // Add a sub-block
1992 1993 1994
    tsdbLoadDataFromCache(TSDB_COMMIT_REPO(pCommith), pIter->pTable, pIter->pIter, keyLimit, INT32_MAX,
                          pCommith->pDataCols, pCommith->readh.pDCols[0]->cols[0].pData,
                          pCommith->readh.pDCols[0]->numOfRows, pCfg->update, &mInfo);
H
more  
Hongze Cheng 已提交
1995 1996 1997 1998 1999
    if (pBlock->last) {
      pDFile = TSDB_COMMIT_LAST_FILE(pCommith);
    } else {
      pDFile = TSDB_COMMIT_DATA_FILE(pCommith);
    }
H
Hongze Cheng 已提交
2000

H
more  
Hongze Cheng 已提交
2001
    if (tsdbWriteBlock(pCommith, pDFile, pCommith->pDataCols, &block, pBlock->last, false) < 0) return -1;
H
Hongze Cheng 已提交
2002

H
more  
Hongze Cheng 已提交
2003 2004 2005 2006 2007 2008 2009 2010 2011
    if (pBlock->numOfSubBlocks == 1) {
      subBlocks[0] = *pBlock;
      subBlocks[0].numOfSubBlocks = 0;
    } else {
      memcpy(subBlocks, POINTER_SHIFT(pCommith->readh.pBlkInfo, pBlock->offset),
             sizeof(SBlock) * pBlock->numOfSubBlocks);
    }
    subBlocks[pBlock->numOfSubBlocks] = block;
    supBlock = *pBlock;
H
Hongze Cheng 已提交
2012 2013
    supBlock.minKey.ts = mInfo.keyFirst;
    supBlock.maxKey.ts = mInfo.keyLast;
H
more  
Hongze Cheng 已提交
2014 2015 2016 2017 2018 2019 2020
    supBlock.numOfSubBlocks++;
    supBlock.numOfRows = pBlock->numOfRows + mInfo.rowsInserted - mInfo.rowsDeleteSucceed;
    supBlock.offset = taosArrayGetSize(pCommith->aSubBlk) * sizeof(SBlock);

    if (tsdbCommitAddBlock(pCommith, &supBlock, subBlocks, supBlock.numOfSubBlocks) < 0) return -1;
  } else {
    if (tsdbLoadBlockData(&(pCommith->readh), pBlock, NULL) < 0) return -1;
H
Hongze Cheng 已提交
2021 2022
    if (tsdbMergeBlockData(pCommith, pIter, pCommith->readh.pDCols[0], keyLimit, bidx == (nBlocks - 1)) < 0) return
    -1;
H
more  
Hongze Cheng 已提交
2023
  }
H
Hongze Cheng 已提交
2024

H
more  
Hongze Cheng 已提交
2025 2026
  return 0;
}
H
Hongze Cheng 已提交
2027

H
refact  
Hongze Cheng 已提交
2028
static bool tsdbCommitIsSameFile(SCommitter *pCommith, int bidx) {
2029 2030 2031 2032 2033 2034 2035
  SBlock *pBlock = pCommith->readh.pBlkInfo->blocks + bidx;
  if (pBlock->last) {
    return pCommith->isLFileSame;
  }
  return pCommith->isDFileSame;
}

H
refact  
Hongze Cheng 已提交
2036
static int tsdbMoveBlock(SCommitter *pCommith, int bidx) {
H
Hongze Cheng 已提交
2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074
  SBlock *pBlock = pCommith->readh.pBlkInfo->blocks + bidx;
  SDFile *pDFile;
  SBlock  block;
  bool    isSameFile;

  ASSERT(pBlock->numOfSubBlocks > 0);

  if (pBlock->last) {
    pDFile = TSDB_COMMIT_LAST_FILE(pCommith);
    isSameFile = pCommith->isLFileSame;
  } else {
    pDFile = TSDB_COMMIT_DATA_FILE(pCommith);
    isSameFile = pCommith->isDFileSame;
  }

  if (isSameFile) {
    if (pBlock->numOfSubBlocks == 1) {
      if (tsdbCommitAddBlock(pCommith, pBlock, NULL, 0) < 0) {
        return -1;
      }
    } else {
      block = *pBlock;
      block.offset = sizeof(SBlock) * taosArrayGetSize(pCommith->aSubBlk);

      if (tsdbCommitAddBlock(pCommith, &block, POINTER_SHIFT(pCommith->readh.pBlkInfo, pBlock->offset),
                             pBlock->numOfSubBlocks) < 0) {
        return -1;
      }
    }
  } else {
    if (tsdbLoadBlockData(&(pCommith->readh), pBlock, NULL) < 0) return -1;
    if (tsdbWriteBlock(pCommith, pDFile, pCommith->readh.pDCols[0], &block, pBlock->last, true) < 0) return -1;
    if (tsdbCommitAddBlock(pCommith, &block, NULL, 0) < 0) return -1;
  }

  return 0;
}

H
Hongze Cheng 已提交
2075 2076
static int tsdbCommitAddBlock(SCommitter *pCommith, const SBlock *pSupBlock, const SBlock *pSubBlocks, int
nSubBlocks) {
H
Hongze Cheng 已提交
2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089
  if (taosArrayPush(pCommith->aSupBlk, pSupBlock) == NULL) {
    terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
    return -1;
  }

  if (pSubBlocks && taosArrayAddBatch(pCommith->aSubBlk, pSubBlocks, nSubBlocks) == NULL) {
    terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
    return -1;
  }

  return 0;
}

H
refact  
Hongze Cheng 已提交
2090
static int tsdbMergeBlockData(SCommitter *pCommith, SCommitIter *pIter, SDataCols *pDataCols, TSKEY keyLimit,
H
more  
Hongze Cheng 已提交
2091
                              bool isLastOneBlock) {
L
Liu Jicong 已提交
2092
  STsdb    *pRepo = TSDB_COMMIT_REPO(pCommith);
H
more  
Hongze Cheng 已提交
2093 2094
  STsdbCfg *pCfg = REPO_CFG(pRepo);
  SBlock    block;
L
Liu Jicong 已提交
2095
  SDFile   *pDFile;
H
more  
Hongze Cheng 已提交
2096 2097
  bool      isLast;
  int32_t   defaultRows = TSDB_COMMIT_DEFAULT_ROWS(pCommith);
H
more  
Hongze Cheng 已提交
2098

H
more  
Hongze Cheng 已提交
2099 2100
  int biter = 0;
  while (true) {
H
Hongze Cheng 已提交
2101 2102
    tsdbLoadAndMergeFromCache(TSDB_COMMIT_REPO(pCommith), pCommith->readh.pDCols[0], &biter, pIter,
    pCommith->pDataCols,
H
Hongze Cheng 已提交
2103
                              keyLimit, defaultRows, pCfg->update);
H
Hongze Cheng 已提交
2104

H
more  
Hongze Cheng 已提交
2105
    if (pCommith->pDataCols->numOfRows == 0) break;
H
Hongze Cheng 已提交
2106

H
more  
Hongze Cheng 已提交
2107
    if (isLastOneBlock) {
H
refact  
Hongze Cheng 已提交
2108
      if (pCommith->pDataCols->numOfRows < pCfg->minRows) {
H
more  
Hongze Cheng 已提交
2109 2110 2111 2112 2113 2114 2115 2116 2117 2118
        pDFile = TSDB_COMMIT_LAST_FILE(pCommith);
        isLast = true;
      } else {
        pDFile = TSDB_COMMIT_DATA_FILE(pCommith);
        isLast = false;
      }
    } else {
      pDFile = TSDB_COMMIT_DATA_FILE(pCommith);
      isLast = false;
    }
H
Hongze Cheng 已提交
2119

H
more  
Hongze Cheng 已提交
2120 2121 2122
    if (tsdbWriteBlock(pCommith, pDFile, pCommith->pDataCols, &block, isLast, true) < 0) return -1;
    if (tsdbCommitAddBlock(pCommith, &block, NULL, 0) < 0) return -1;
  }
H
more  
Hongze Cheng 已提交
2123

H
more  
Hongze Cheng 已提交
2124 2125
  return 0;
}
H
more  
Hongze Cheng 已提交
2126

H
Hongze Cheng 已提交
2127 2128
static void tsdbLoadAndMergeFromCache(STsdb *pTsdb, SDataCols *pDataCols, int *iter, SCommitIter *pCommitIter,
                                      SDataCols *pTarget, TSKEY maxKey, int maxRows, int8_t update) {
H
more  
Hongze Cheng 已提交
2129 2130
  TSKEY     key1 = INT64_MAX;
  TSKEY     key2 = INT64_MAX;
2131
  TSKEY     lastKey = TSKEY_INITIAL_VAL;
H
more  
Hongze Cheng 已提交
2132
  STSchema *pSchema = NULL;
H
Hongze Cheng 已提交
2133

H
more  
Hongze Cheng 已提交
2134 2135
  ASSERT(maxRows > 0 && dataColsKeyLast(pDataCols) <= maxKey);
  tdResetDataCols(pTarget);
H
more  
Hongze Cheng 已提交
2136

C
Cary Xu 已提交
2137
  pTarget->bitmapMode = pDataCols->bitmapMode;
2138 2139
  // TODO: filter Multi-Version
  // TODO: support delete function
H
more  
Hongze Cheng 已提交
2140 2141
  while (true) {
    key1 = (*iter >= pDataCols->numOfRows) ? INT64_MAX : dataColsKeyAt(pDataCols, *iter);
C
Cary Xu 已提交
2142 2143
    STSRow *row = tsdbNextIterRow(pCommitIter->pIter);
    if (row == NULL || TD_ROW_KEY(row) > maxKey) {
H
more  
Hongze Cheng 已提交
2144 2145
      key2 = INT64_MAX;
    } else {
C
Cary Xu 已提交
2146
      key2 = TD_ROW_KEY(row);
H
more  
Hongze Cheng 已提交
2147
    }
H
more  
Hongze Cheng 已提交
2148

H
more  
Hongze Cheng 已提交
2149
    if (key1 == INT64_MAX && key2 == INT64_MAX) break;
H
more  
Hongze Cheng 已提交
2150

H
more  
Hongze Cheng 已提交
2151
    if (key1 < key2) {
2152 2153 2154
      if (lastKey != TSKEY_INITIAL_VAL) {
        ++pTarget->numOfRows;
      }
C
Cary Xu 已提交
2155
      for (int i = 0; i < pDataCols->numOfCols; ++i) {
H
more  
Hongze Cheng 已提交
2156
        // TODO: dataColAppendVal may fail
C
Cary Xu 已提交
2157
        SCellVal sVal = {0};
C
Cary Xu 已提交
2158
        if (tdGetColDataOfRow(&sVal, pDataCols->cols + i, *iter, pDataCols->bitmapMode) < 0) {
C
Cary Xu 已提交
2159 2160
          TASSERT(0);
        }
H
refact  
Hongze Cheng 已提交
2161
        tdAppendValToDataCol(pTarget->cols + i, sVal.valType, sVal.val, pTarget->numOfRows, pTarget->maxPoints,
C
Cary Xu 已提交
2162
                             pTarget->bitmapMode, false);
H
more  
Hongze Cheng 已提交
2163
      }
H
more  
Hongze Cheng 已提交
2164

2165
      lastKey = key1;
C
Cary Xu 已提交
2166
      ++(*iter);
H
more  
Hongze Cheng 已提交
2167
    } else if (key1 > key2) {
C
Cary Xu 已提交
2168
      if (pSchema == NULL || schemaVersion(pSchema) != TD_ROW_SVER(row)) {
2169
        pSchema = tsdbGetTableSchemaImpl(pTsdb, pCommitIter->pTable, false, false, TD_ROW_SVER(row));
H
more  
Hongze Cheng 已提交
2170 2171
        ASSERT(pSchema != NULL);
      }
H
Hongze Cheng 已提交
2172

2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183
      if (key2 == lastKey) {
        if (TD_SUPPORT_UPDATE(update)) {
          tdAppendSTSRowToDataCol(row, pSchema, pTarget, true);
        }
      } else {
        if (lastKey != TSKEY_INITIAL_VAL) {
          ++pTarget->numOfRows;
        }
        tdAppendSTSRowToDataCol(row, pSchema, pTarget, false);
        lastKey = key2;
      }
H
more  
Hongze Cheng 已提交
2184

H
Hongze Cheng 已提交
2185
      tsdbTbDataIterNext(pCommitIter->pIter);
H
more  
Hongze Cheng 已提交
2186
    } else {
H
Hongze Cheng 已提交
2187
      if (lastKey != key1) {
2188 2189 2190
        if (lastKey != TSKEY_INITIAL_VAL) {
          ++pTarget->numOfRows;
        }
2191 2192 2193
        lastKey = key1;
      }

C
Cary Xu 已提交
2194 2195 2196
      // copy disk data
      for (int i = 0; i < pDataCols->numOfCols; ++i) {
        SCellVal sVal = {0};
2197
        // no duplicated TS keys in pDataCols from file
C
Cary Xu 已提交
2198 2199 2200 2201 2202
        if (tdGetColDataOfRow(&sVal, pDataCols->cols + i, *iter, pDataCols->bitmapMode) < 0) {
          TASSERT(0);
        }
        // TODO: tdAppendValToDataCol may fail
        tdAppendValToDataCol(pTarget->cols + i, sVal.valType, sVal.val, pTarget->numOfRows, pTarget->maxPoints,
C
Cary Xu 已提交
2203
                             pTarget->bitmapMode, false);
C
Cary Xu 已提交
2204 2205 2206 2207 2208
      }

      if (TD_SUPPORT_UPDATE(update)) {
        // copy mem data(Multi-Version)
        if (pSchema == NULL || schemaVersion(pSchema) != TD_ROW_SVER(row)) {
2209
          pSchema = tsdbGetTableSchemaImpl(pTsdb, pCommitIter->pTable, false, false, TD_ROW_SVER(row));
C
Cary Xu 已提交
2210 2211 2212 2213
          ASSERT(pSchema != NULL);
        }

        // TODO: merge with Multi-Version
2214
        tdAppendSTSRowToDataCol(row, pSchema, pTarget, true);
C
Cary Xu 已提交
2215
      }
2216
      ++(*iter);
H
Hongze Cheng 已提交
2217
      tsdbTbDataIterNext(pCommitIter->pIter);
H
more  
Hongze Cheng 已提交
2218 2219
    }

2220 2221 2222 2223 2224
    if (pTarget->numOfRows >= (maxRows - 1)) break;
  }

  if (lastKey != TSKEY_INITIAL_VAL) {
    ++pTarget->numOfRows;
H
more  
Hongze Cheng 已提交
2225 2226
  }
}
H
Hongze Cheng 已提交
2227

H
refact  
Hongze Cheng 已提交
2228
static void tsdbResetCommitTable(SCommitter *pCommith) {
H
Hongze Cheng 已提交
2229 2230 2231 2232 2233
  taosArrayClear(pCommith->aSubBlk);
  taosArrayClear(pCommith->aSupBlk);
  pCommith->pTable = NULL;
}

H
refact  
Hongze Cheng 已提交
2234
static void tsdbCloseCommitFile(SCommitter *pCommith, bool hasError) {
H
Hongze Cheng 已提交
2235 2236 2237 2238 2239 2240 2241 2242 2243 2244
  if (pCommith->isRFileSet) {
    tsdbCloseAndUnsetFSet(&(pCommith->readh));
  }

  if (!hasError) {
    TSDB_FSET_FSYNC(TSDB_COMMIT_WRITE_FSET(pCommith));
  }
  tsdbCloseDFileSet(TSDB_COMMIT_WRITE_FSET(pCommith));
}

H
refact  
Hongze Cheng 已提交
2245
static bool tsdbCanAddSubBlock(SCommitter *pCommith, SBlock *pBlock, SMergeInfo *pInfo) {
L
Liu Jicong 已提交
2246
  STsdb    *pRepo = TSDB_COMMIT_REPO(pCommith);
H
more  
Hongze Cheng 已提交
2247 2248
  STsdbCfg *pCfg = REPO_CFG(pRepo);
  int       mergeRows = pBlock->numOfRows + pInfo->rowsInserted - pInfo->rowsDeleteSucceed;
H
Hongze Cheng 已提交
2249

H
more  
Hongze Cheng 已提交
2250
  ASSERT(mergeRows > 0);
H
Hongze Cheng 已提交
2251

H
refact  
Hongze Cheng 已提交
2252
  if (pBlock->numOfSubBlocks < TSDB_MAX_SUBBLOCKS && pInfo->nOperations <= pCfg->maxRows) {
H
more  
Hongze Cheng 已提交
2253
    if (pBlock->last) {
H
refact  
Hongze Cheng 已提交
2254
      if (pCommith->isLFileSame && mergeRows < pCfg->minRows) return true;
H
more  
Hongze Cheng 已提交
2255
    } else {
H
refact  
Hongze Cheng 已提交
2256
      if (pCommith->isDFileSame && mergeRows <= pCfg->maxRows) return true;
H
more  
Hongze Cheng 已提交
2257 2258
    }
  }
H
Hongze Cheng 已提交
2259

H
more  
Hongze Cheng 已提交
2260
  return false;
H
Hongze Cheng 已提交
2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427
}

static int tsdbAppendTableRowToCols(STsdb *pTsdb, STable *pTable, SDataCols *pCols, STSchema **ppSchema, STSRow *row,
                                    bool merge) {
  if (pCols) {
    if (*ppSchema == NULL || schemaVersion(*ppSchema) != TD_ROW_SVER(row)) {
      *ppSchema = tsdbGetTableSchemaImpl(pTsdb, pTable, false, false, TD_ROW_SVER(row));
      if (*ppSchema == NULL) {
        ASSERT(false);
        return -1;
      }
    }

    tdAppendSTSRowToDataCol(row, *ppSchema, pCols, merge);
  }

  return 0;
}

static int tsdbLoadDataFromCache(STsdb *pTsdb, STable *pTable, STbDataIter *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;
  // only fetch lastKey from mem data as file data not used in this function actually
  TSKEY      lastKey = TSKEY_INITIAL_VAL;
  bool       isRowDel = false;
  int        filterIter = 0;
  STSRow    *row = NULL;
  SMergeInfo mInfo;

  // TODO: support Multi-Version(the rows with the same TS keys in memory can't be merged if its version refered by
  // query handle)

  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);
  if (row == NULL || TD_ROW_KEY(row) > maxKey) {
    rowKey = INT64_MAX;
    isRowDel = false;
  } else {
    rowKey = TD_ROW_KEY(row);
    isRowDel = TD_ROW_IS_DELETED(row);
  }

  if (filterIter >= nFilterKeys) {
    fKey = INT64_MAX;
  } else {
    fKey = tdGetKey(filterKeys[filterIter]);
  }
  // 1. fkey - no dup since merged up to maxVersion of each query handle by tsdbLoadBlockDataCols
  // 2. rowKey - would dup since Multi-Version supported
  while (true) {
    if (fKey == INT64_MAX && rowKey == INT64_MAX) break;

    if (fKey < rowKey) {
      pMergeInfo->keyFirst = TMIN(pMergeInfo->keyFirst, fKey);
      pMergeInfo->keyLast = TMAX(pMergeInfo->keyLast, fKey);

      filterIter++;
      if (filterIter >= nFilterKeys) {
        fKey = INT64_MAX;
      } else {
        fKey = tdGetKey(filterKeys[filterIter]);
      }
#if 1
    } else if (fKey > rowKey) {
      if (isRowDel) {
        // TODO: support delete function
        pMergeInfo->rowsDeleteFailed++;
      } else {
        if (pMergeInfo->rowsInserted - pMergeInfo->rowsDeleteSucceed >= maxRowsToRead) break;
        if (pCols && pMergeInfo->nOperations >= pCols->maxPoints) break;

        if (lastKey != rowKey) {
          pMergeInfo->rowsInserted++;
          pMergeInfo->nOperations++;
          pMergeInfo->keyFirst = TMIN(pMergeInfo->keyFirst, rowKey);
          pMergeInfo->keyLast = TMAX(pMergeInfo->keyLast, rowKey);
          if (pCols) {
            if (lastKey != TSKEY_INITIAL_VAL) {
              ++pCols->numOfRows;
            }
            tsdbAppendTableRowToCols(pTsdb, pTable, pCols, &pSchema, row, false);
          }
          lastKey = rowKey;
        } else {
          if (keepDup) {
            tsdbAppendTableRowToCols(pTsdb, pTable, pCols, &pSchema, row, true);
          } else {
            // discard
          }
        }
      }

      tsdbTbDataIterNext(pIter);
      row = tsdbNextIterRow(pIter);
      if (row == NULL || TD_ROW_KEY(row) > maxKey) {
        rowKey = INT64_MAX;
        isRowDel = false;
      } else {
        rowKey = TD_ROW_KEY(row);
        isRowDel = TD_ROW_IS_DELETED(row);
      }
    } else {           // fkey == rowKey
      if (isRowDel) {  // TODO: support delete function(How to stands for delete in file? rowVersion = -1?)
        ASSERT(!keepDup);
        if (pCols && pMergeInfo->nOperations >= pCols->maxPoints) break;
        pMergeInfo->rowsDeleteSucceed++;
        pMergeInfo->nOperations++;
        tsdbAppendTableRowToCols(pTsdb, pTable, pCols, &pSchema, row, false);
      } else {
        if (keepDup) {
          if (pCols && pMergeInfo->nOperations >= pCols->maxPoints) break;
          if (lastKey != rowKey) {
            pMergeInfo->rowsUpdated++;
            pMergeInfo->nOperations++;
            pMergeInfo->keyFirst = TMIN(pMergeInfo->keyFirst, rowKey);
            pMergeInfo->keyLast = TMAX(pMergeInfo->keyLast, rowKey);
            if (pCols) {
              if (lastKey != TSKEY_INITIAL_VAL) {
                ++pCols->numOfRows;
              }
              tsdbAppendTableRowToCols(pTsdb, pTable, pCols, &pSchema, row, false);
            }
            lastKey = rowKey;
          } else {
            tsdbAppendTableRowToCols(pTsdb, pTable, pCols, &pSchema, row, true);
          }
        } else {
          pMergeInfo->keyFirst = TMIN(pMergeInfo->keyFirst, fKey);
          pMergeInfo->keyLast = TMAX(pMergeInfo->keyLast, fKey);
        }
      }

      tsdbTbDataIterNext(pIter);
      row = tsdbNextIterRow(pIter);
      if (row == NULL || TD_ROW_KEY(row) > maxKey) {
        rowKey = INT64_MAX;
        isRowDel = false;
      } else {
        rowKey = TD_ROW_KEY(row);
        isRowDel = TD_ROW_IS_DELETED(row);
      }

      filterIter++;
      if (filterIter >= nFilterKeys) {
        fKey = INT64_MAX;
      } else {
        fKey = tdGetKey(filterKeys[filterIter]);
      }
    }
#endif
  }
  if (pCols && (lastKey != TSKEY_INITIAL_VAL)) {
    ++pCols->numOfRows;
  }

  return 0;
H
Hongze Cheng 已提交
2428 2429
}
#endif