tsdbCommit.c 72.2 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
  code = tsdbWriteDelData(pCommitter->pDelFWriter, &pCommitter->delDataNew, NULL);
H
Hongze Cheng 已提交
666 667 668
  if (code) goto _err;

  // add SDelIdxItem
H
Hongze Cheng 已提交
669
  code = tDelIdxPutItem(&pCommitter->delIdxNew, &pCommitter->delIdxItem);
H
Hongze Cheng 已提交
670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699
  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 已提交
700 701
// // ===================================== OLD ======================================
#if 0
H
Hongze Cheng 已提交
702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723
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 已提交
724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740
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 已提交
741 742 743
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 已提交
744 745 746 747 748 749 750 751 752 753 754 755 756
                               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 已提交
757
  int32_t    fid;
H
more  
Hongze Cheng 已提交
758
  SDFileSet *pSet = NULL;
H
refact  
Hongze Cheng 已提交
759 760 761
  int32_t    code = 0;
  STsdb     *pTsdb = TSDB_COMMIT_REPO(pCommith);

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

H
more  
Hongze Cheng 已提交
773
  // commit
H
refact  
Hongze Cheng 已提交
774
  fid = tsdbNextCommitFid(pCommith);
H
refact  
Hongze Cheng 已提交
775 776 777 778 779 780 781
  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 已提交
782 783
      if (tsdbApplyRtnOnFSet(TSDB_COMMIT_REPO(pCommith), pSet, &(pCommith->rtn)) < 0) {
        tsdbDestroyCommitH(pCommith);
H
refact  
Hongze Cheng 已提交
784 785 786
        return -1;
      }

H
refact  
Hongze Cheng 已提交
787
      pSet = tsdbFSIterNext(&(pCommith->fsIter));
H
refact  
Hongze Cheng 已提交
788 789 790 791 792 793 794 795 796 797 798 799 800
    } 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 已提交
801
        pSet = tsdbFSIterNext(&(pCommith->fsIter));
H
refact  
Hongze Cheng 已提交
802 803
      }

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

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

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

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

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

H
Hongze Cheng 已提交
828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868
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 已提交
869
static int32_t tsdbStartCommit(STsdb *pTsdb, SCommitter *pCHandle) {
H
more  
Hongze Cheng 已提交
870
  int32_t code = 0;
H
more  
Hongze Cheng 已提交
871

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

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

  tsdbStartFSTxn(pTsdb, 0, 0);

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

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

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

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

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

H
refact  
Hongze Cheng 已提交
900
static int tsdbInitCommitH(SCommitter *pCommith, STsdb *pRepo) {
H
refact  
Hongze Cheng 已提交
901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941
  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 已提交
942
  pCommith->pDataCols = tdNewDataCols(0, pCfg->maxRows);
H
refact  
Hongze Cheng 已提交
943 944 945 946 947 948 949 950 951 952
  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 已提交
953
static void tsdbSeekCommitIter(SCommitter *pCommith, TSKEY key) {
H
refact  
Hongze Cheng 已提交
954 955 956 957
  for (int i = 0; i < pCommith->niters; i++) {
    SCommitIter *pIter = pCommith->iters + i;
    if (pIter->pTable == NULL || pIter->pIter == NULL) continue;

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

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

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

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

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

H
refact  
Hongze Cheng 已提交
986
static void tsdbDestroyCommitH(SCommitter *pCommith) {
H
refact  
Hongze Cheng 已提交
987 988 989 990 991 992 993 994 995
  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 已提交
996
static int32_t tsdbCommitToFileStart(SCommitter *pCHandle, SDFileSet *pSet, int32_t fid) {
H
Hongze Cheng 已提交
997 998
  int32_t       code = 0;
  STsdb        *pRepo = TSDB_COMMIT_REPO(pCHandle);
C
Cary Xu 已提交
999
  STsdbKeepCfg *pCfg = REPO_KEEP_CFG(pRepo);
H
Hongze Cheng 已提交
1000

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

H
Hongze Cheng 已提交
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
  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 已提交
1016
static int32_t tsdbCommitToFileImpl(SCommitter *pCHandle) {
H
Hongze Cheng 已提交
1017 1018 1019 1020
  int32_t code = 0;
  // TODO
  return code;
}
H
refact  
Hongze Cheng 已提交
1021
static int32_t tsdbCommitToFileEnd(SCommitter *pCommith) {
H
Hongze Cheng 已提交
1022 1023
  int32_t code = 0;
  STsdb  *pRepo = TSDB_COMMIT_REPO(pCommith);
H
Hongze Cheng 已提交
1024

H
Hongze Cheng 已提交
1025 1026
  if (tsdbWriteBlockIdx(TSDB_COMMIT_HEAD_FILE(pCommith), pCommith->aBlkIdx, (void **)(&(TSDB_COMMIT_BUF(pCommith))))
  <
H
Hongze Cheng 已提交
1027 1028 1029 1030 1031 1032
      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 已提交
1033 1034
    return -1;
  }
H
Hongze Cheng 已提交
1035

H
Hongze Cheng 已提交
1036 1037 1038 1039 1040 1041 1042
  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 已提交
1043

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

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

  return code;
}
H
refact  
Hongze Cheng 已提交
1053
static int32_t tsdbCommitToFile(SCommitter *pCommith, SDFileSet *pSet, int fid) {
H
Hongze Cheng 已提交
1054 1055 1056 1057 1058 1059 1060 1061
  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 已提交
1062
  }
H
Hongze Cheng 已提交
1063

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

  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 已提交
1081

H
Hongze Cheng 已提交
1082 1083
    if (pIter && pIter->pTable && (!pIdx || (pIter->pTable->suid <= pIdx->suid || pIter->pTable->uid <= pIdx->uid)))
    {
C
Cary Xu 已提交
1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094
      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 已提交
1095 1096
    } else if (pIter && !pIter->pTable) {
      // When table already dropped during commit, pIter is not NULL but pIter->pTable is NULL.
1097
      ++mIter;  // skip the table and do nothing
C
Cary Xu 已提交
1098 1099 1100 1101 1102 1103 1104 1105 1106 1107
    } 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 已提交
1108

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

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

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

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

  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 已提交
1137 1138
    pTbData = (STbData *)taosArrayGetP(pMem->aTbData, iIter);
    pCommitIter = &pCommith->iters[iIter];
H
Hongze Cheng 已提交
1139

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

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

  return code;

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

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

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

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

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

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

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

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

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

H
Hongze Cheng 已提交
1198 1199
    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 已提交
1200 1201 1202
  } else {
    pCommith->isRFileSet = false;
  }
H
Hongze Cheng 已提交
1203

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

S
Shengliang Guan 已提交
1209
    if (tsdbCreateDFileSet(pRepo, pWSet, true) < 0) {
S
Shengliang Guan 已提交
1210
      tsdbError("vgId:%d, failed to create FSET %d at level %d disk id %d since %s", REPO_ID(pRepo),
H
more  
Hongze Cheng 已提交
1211 1212 1213 1214 1215 1216
                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 已提交
1217

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

S
Shengliang Guan 已提交
1221
    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 已提交
1222 1223 1224 1225
              TSDB_FSET_LEVEL(pWSet), TSDB_FSET_ID(pWSet));
  } else {
    did.level = TSDB_FSET_LEVEL(pSet);
    did.id = TSDB_FSET_ID(pSet);
H
Hongze Cheng 已提交
1226

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

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

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

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

H
more  
Hongze Cheng 已提交
1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267
      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;

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

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

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

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

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

1302
    if (!taosCheckExistFile(TSDB_FILE_FULL_NAME(pRSmadF))) {
S
Shengliang Guan 已提交
1303
      tsdbDebug("vgId:%d, create data file %s as not exist", REPO_ID(pRepo), TSDB_FILE_FULL_NAME(pRSmadF));
1304 1305 1306
      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 已提交
1307 1308
        tsdbError("vgId:%d, failed to create file %s to commit since %s", REPO_ID(pRepo),
        TSDB_FILE_FULL_NAME(pWSmadF),
1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320
                  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 已提交
1321
        tsdbError("vgId:%d, failed to open file %s to commit since %s", REPO_ID(pRepo), TSDB_FILE_FULL_NAME(pWSmadF),
1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336
                  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);

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

        tsdbCloseDFileSet(pWSet);
        tsdbRemoveDFile(pWHeadf);
        if (pCommith->isRFileSet) {
          tsdbCloseAndUnsetFSet(&(pCommith->readh));
          return -1;
        }
      }
    } else {
S
Shengliang Guan 已提交
1351
      tsdbDebug("vgId:%d, create data file %s as not exist", REPO_ID(pRepo), TSDB_FILE_FULL_NAME(pRSmalF));
1352 1353 1354
      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 已提交
1355 1356
        tsdbError("vgId:%d, failed to create file %s to commit since %s", REPO_ID(pRepo),
        TSDB_FILE_FULL_NAME(pWSmalF),
1357 1358 1359 1360 1361 1362 1363 1364 1365 1366
                  tstrerror(terrno));

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

  return 0;
}

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

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

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

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

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

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

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

H
more  
Hongze Cheng 已提交
1401 1402 1403
  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 已提交
1404

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

H
Hongze Cheng 已提交
1476
// =================== Commit Time-Series Data
H
refact  
Hongze Cheng 已提交
1477
static int tsdbCommitToTable(SCommitter *pCommith, int tid) {
H
Hongze Cheng 已提交
1478 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
  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 已提交
1530 1531 1532 1533
      // merge pBlock data and memory data
      if (tsdbMergeMemData(pCommith, pIter, bidx) < 0) {
        return -1;
      }
H
more  
Hongze Cheng 已提交
1534

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

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

  return 0;
}

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

  tsdbResetCommitTable(pCommith);

  pReadh->pBlkIdx = pIdx;

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

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

C
Cary Xu 已提交
1584
  while (bidx < nBlocks) {
1585 1586
    if (!pTSchema && !tsdbCommitIsSameFile(pCommith, bidx)) {
      // Set commit table
1587
      pTSchema = metaGetTbTSchema(REPO_META(pTsdb), pIdx->uid, -1);  // TODO: schema version
1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598
      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 已提交
1599
    if (tsdbMoveBlock(pCommith, bidx) < 0) {
S
Shengliang Guan 已提交
1600
      tsdbError("vgId:%d, failed to move block into file %s since %s", TSDB_COMMIT_REPO_ID(pCommith),
C
Cary Xu 已提交
1601
                TSDB_FILE_FULL_NAME(TSDB_COMMIT_HEAD_FILE(pCommith)), tstrerror(terrno));
1602
      taosMemoryFreeClear(pTSchema);
C
Cary Xu 已提交
1603 1604
      return -1;
    }
1605

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

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

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

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

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

C
Cary Xu 已提交
1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669
/**
 * @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 已提交
1670
static int tsdbWriteBlockImpl(STsdb *pRepo, STable *pTable, SDFile *pDFile, SDFile *pDFileAggr, SDataCols *pDataCols,
H
Hongze Cheng 已提交
1671 1672
                              SBlock *pBlock, bool isLast, bool isSuper, void **ppBuf, void **ppCBuf, void **ppExBuf)
                              {
C
Cary Xu 已提交
1673 1674
  STsdbCfg     *pCfg = REPO_CFG(pRepo);
  SBlockData   *pBlockData = NULL;
1675
  SAggrBlkData *pAggrBlkData = NULL;
C
Cary Xu 已提交
1676
  STSchema     *pSchema = pTable->pSchema;
1677 1678
  int64_t       offset = 0, offsetAggr = 0;
  int           rowsToWrite = pDataCols->numOfRows;
H
Hongze Cheng 已提交
1679

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

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

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

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

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

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

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

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

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

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

  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;
1747
  int32_t  tsize = (int32_t)tsdbBlockStatisSize(nColsNotAllNull, SBlockVerLatest);
H
Hongze Cheng 已提交
1748
  int32_t  lsize = tsize;
C
Cary Xu 已提交
1749
  uint32_t tsizeAggr = (uint32_t)tsdbBlockAggrSize(nColsOfBlockSma, SBlockVerLatest);
H
Hongze Cheng 已提交
1750
  int32_t  keyLen = 0;
C
Cary Xu 已提交
1751
  int32_t  nBitmaps = (int32_t)TD_BITMAP_BYTES(rowsToWrite);
C
Cary Xu 已提交
1752
  int32_t  sBitmaps = isSuper ? (int32_t)TD_BITMAP_BYTES_I(rowsToWrite) : nBitmaps;
C
Cary Xu 已提交
1753

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

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

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

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

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

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

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

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

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

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

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

    toffset += flen;
    lsize += flen;
  }

  pBlockData->delimiter = TSDB_FILE_DELIMITER;
H
Hongze Cheng 已提交
1844
  pBlockData->uid = pTable->uid;
H
Hongze Cheng 已提交
1845 1846 1847 1848 1849 1850 1851 1852 1853 1854
  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 已提交
1855
  uint32_t aggrStatus = nColsOfBlockSma > 0 ? 1 : 0;
1856 1857 1858 1859 1860 1861 1862 1863 1864 1865
  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;
    }
  }

1866
  // Update pBlock membership variables
H
Hongze Cheng 已提交
1867 1868 1869 1870 1871 1872 1873 1874
  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 已提交
1875
  pBlock->numOfBSma = nColsOfBlockSma;
H
Hongze Cheng 已提交
1876 1877
  pBlock->minKey.ts = dataColsKeyFirst(pDataCols);
  pBlock->maxKey.ts = dataColsKeyLast(pDataCols);
1878 1879 1880
  pBlock->aggrStat = aggrStatus;
  pBlock->blkVer = SBlockVerLatest;
  pBlock->aggrOffset = (uint64_t)offsetAggr;
H
Hongze Cheng 已提交
1881

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

  return 0;
}

H
refact  
Hongze Cheng 已提交
1890
static int tsdbWriteBlock(SCommitter *pCommith, SDFile *pDFile, SDataCols *pDataCols, SBlock *pBlock, bool isLast,
H
Hongze Cheng 已提交
1891
                          bool isSuper) {
1892 1893 1894 1895
  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 已提交
1896 1897
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1975 1976 1977
  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 已提交
1978

H
more  
Hongze Cheng 已提交
1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990
  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
1991 1992 1993
    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 已提交
1994 1995 1996 1997 1998
    if (pBlock->last) {
      pDFile = TSDB_COMMIT_LAST_FILE(pCommith);
    } else {
      pDFile = TSDB_COMMIT_DATA_FILE(pCommith);
    }
H
Hongze Cheng 已提交
1999

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

H
more  
Hongze Cheng 已提交
2002 2003 2004 2005 2006 2007 2008 2009 2010
    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 已提交
2011 2012
    supBlock.minKey.ts = mInfo.keyFirst;
    supBlock.maxKey.ts = mInfo.keyLast;
H
more  
Hongze Cheng 已提交
2013 2014 2015 2016 2017 2018 2019
    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 已提交
2020 2021
    if (tsdbMergeBlockData(pCommith, pIter, pCommith->readh.pDCols[0], keyLimit, bidx == (nBlocks - 1)) < 0) return
    -1;
H
more  
Hongze Cheng 已提交
2022
  }
H
Hongze Cheng 已提交
2023

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

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

H
refact  
Hongze Cheng 已提交
2035
static int tsdbMoveBlock(SCommitter *pCommith, int bidx) {
H
Hongze Cheng 已提交
2036 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
  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 已提交
2074 2075
static int tsdbCommitAddBlock(SCommitter *pCommith, const SBlock *pSupBlock, const SBlock *pSubBlocks, int
nSubBlocks) {
H
Hongze Cheng 已提交
2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088
  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 已提交
2089
static int tsdbMergeBlockData(SCommitter *pCommith, SCommitIter *pIter, SDataCols *pDataCols, TSKEY keyLimit,
H
more  
Hongze Cheng 已提交
2090
                              bool isLastOneBlock) {
L
Liu Jicong 已提交
2091
  STsdb    *pRepo = TSDB_COMMIT_REPO(pCommith);
H
more  
Hongze Cheng 已提交
2092 2093
  STsdbCfg *pCfg = REPO_CFG(pRepo);
  SBlock    block;
L
Liu Jicong 已提交
2094
  SDFile   *pDFile;
H
more  
Hongze Cheng 已提交
2095 2096
  bool      isLast;
  int32_t   defaultRows = TSDB_COMMIT_DEFAULT_ROWS(pCommith);
H
more  
Hongze Cheng 已提交
2097

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

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

H
more  
Hongze Cheng 已提交
2106
    if (isLastOneBlock) {
H
refact  
Hongze Cheng 已提交
2107
      if (pCommith->pDataCols->numOfRows < pCfg->minRows) {
H
more  
Hongze Cheng 已提交
2108 2109 2110 2111 2112 2113 2114 2115 2116 2117
        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 已提交
2118

H
more  
Hongze Cheng 已提交
2119 2120 2121
    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 已提交
2122

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

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

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

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

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

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

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

2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182
      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 已提交
2183

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

C
Cary Xu 已提交
2193 2194 2195
      // copy disk data
      for (int i = 0; i < pDataCols->numOfCols; ++i) {
        SCellVal sVal = {0};
2196
        // no duplicated TS keys in pDataCols from file
C
Cary Xu 已提交
2197 2198 2199 2200 2201
        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 已提交
2202
                             pTarget->bitmapMode, false);
C
Cary Xu 已提交
2203 2204 2205 2206 2207
      }

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

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

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

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

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

H
refact  
Hongze Cheng 已提交
2233
static void tsdbCloseCommitFile(SCommitter *pCommith, bool hasError) {
H
Hongze Cheng 已提交
2234 2235 2236 2237 2238 2239 2240 2241 2242 2243
  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 已提交
2244
static bool tsdbCanAddSubBlock(SCommitter *pCommith, SBlock *pBlock, SMergeInfo *pInfo) {
L
Liu Jicong 已提交
2245
  STsdb    *pRepo = TSDB_COMMIT_REPO(pCommith);
H
more  
Hongze Cheng 已提交
2246 2247
  STsdbCfg *pCfg = REPO_CFG(pRepo);
  int       mergeRows = pBlock->numOfRows + pInfo->rowsInserted - pInfo->rowsDeleteSucceed;
H
Hongze Cheng 已提交
2248

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

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

H
more  
Hongze Cheng 已提交
2259
  return false;
H
Hongze Cheng 已提交
2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 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
}

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 已提交
2427 2428
}
#endif