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

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

H
Hongze Cheng 已提交
18 19 20 21 22
#define TDB_BTREE_ROOT 0x1
#define TDB_BTREE_LEAF 0x2

#define TDB_BTREE_PAGE_IS_ROOT(flags) TDB_FLAG_HAS(flags, TDB_BTREE_ROOT)
#define TDB_BTREE_PAGE_IS_LEAF(flags) TDB_FLAG_HAS(flags, TDB_BTREE_LEAF)
H
Hongze Cheng 已提交
23 24 25
#define TDB_BTREE_ASSERT_FLAG(flags)                                                 \
  ASSERT(TDB_FLAG_IS(flags, TDB_BTREE_ROOT) || TDB_FLAG_IS(flags, TDB_BTREE_LEAF) || \
         TDB_FLAG_IS(flags, TDB_BTREE_ROOT | TDB_BTREE_LEAF) || TDB_FLAG_IS(flags, 0))
H
Hongze Cheng 已提交
26

H
Hongze Cheng 已提交
27
struct SBTree {
H
more  
Hongze Cheng 已提交
28 29 30
  SPgno          root;
  int            keyLen;
  int            valLen;
H
Hongze Cheng 已提交
31
  SPager        *pPager;
H
more  
Hongze Cheng 已提交
32
  FKeyComparator kcmpr;
H
more  
Hongze Cheng 已提交
33
  u8             fanout;
H
Hongze Cheng 已提交
34
  int            pageSize;
H
more  
Hongze Cheng 已提交
35 36 37 38
  int            maxLocal;
  int            minLocal;
  int            maxLeaf;
  int            minLeaf;
H
Hongze Cheng 已提交
39 40
};

H
Hongze Cheng 已提交
41 42 43
typedef struct __attribute__((__packed__)) {
  SPgno rChild;
} SBtPageHdr;
H
more  
Hongze Cheng 已提交
44

H
Hongze Cheng 已提交
45 46 47 48 49
typedef struct {
  u16     flags;
  SBTree *pBt;
} SBtreeZeroPageArg;

H
Hongze Cheng 已提交
50
static int tdbBtCursorMoveTo(SBtCursor *pCur, const void *pKey, int kLen, int *pCRst);
H
more  
Hongze Cheng 已提交
51
static int tdbEncodeLength(u8 *pBuf, uint32_t len);
H
more  
Hongze Cheng 已提交
52
static int tdbCompareKeyAndCell(const void *pKey, int kLen, const void *pCell);
H
Hongze Cheng 已提交
53
static int tdbDefaultKeyCmprFn(const void *pKey1, int keyLen1, const void *pKey2, int keyLen2);
H
Hongze Cheng 已提交
54
static int tdbBtreeOpenImpl(SBTree *pBt);
H
Hongze Cheng 已提交
55 56
static int tdbBtreeZeroPage(SPage *pPage, void *arg);
static int tdbBtreeInitPage(SPage *pPage, void *arg);
H
Hongze Cheng 已提交
57 58
static int tdbEncodeKeyValue(const void *pKey, int kLen, int kLenG, const void *pVal, int vLen, int vLenG, void *pBuf,
                             int *bLen);
H
Hongze Cheng 已提交
59

H
Hongze Cheng 已提交
60
int tdbBtreeOpen(int keyLen, int valLen, SPager *pPager, FKeyComparator kcmpr, SBTree **ppBt) {
H
Hongze Cheng 已提交
61
  SBTree *pBt;
H
Hongze Cheng 已提交
62
  int     ret;
H
more  
Hongze Cheng 已提交
63

H
Hongze Cheng 已提交
64
  *ppBt = NULL;
H
Hongze Cheng 已提交
65 66 67 68 69 70 71 72 73 74

  pBt = (SBTree *)calloc(1, sizeof(*pBt));
  if (pBt == NULL) {
    return -1;
  }

  // pBt->keyLen
  pBt->keyLen = keyLen;
  // pBt->valLen
  pBt->valLen = valLen;
H
refact  
Hongze Cheng 已提交
75 76
  // pBt->pPager
  pBt->pPager = pPager;
H
Hongze Cheng 已提交
77 78
  // pBt->kcmpr
  pBt->kcmpr = kcmpr ? kcmpr : tdbDefaultKeyCmprFn;
H
more  
Hongze Cheng 已提交
79 80 81 82 83 84 85
  // pBt->fanout
  if (keyLen == TDB_VARIANT_LEN) {
    pBt->fanout = TDB_DEFAULT_FANOUT;
  } else {
    ASSERT(0);
    // TODO: pBt->fanout = 0;
  }
H
Hongze Cheng 已提交
86 87 88 89
  // pBt->pageSize
  pBt->pageSize = tdbPagerGetPageSize(pPager);
  // pBt->maxLocal
  pBt->maxLocal = (pBt->pageSize - sizeof(SPageHdr)) / pBt->fanout;
H
Hongze Cheng 已提交
90
  // pBt->minLocal: Should not be allowed smaller than 15, which is [nPayload][nKey][nData]
H
Hongze Cheng 已提交
91 92 93 94 95
  pBt->minLocal = (pBt->pageSize - sizeof(SPageHdr)) / pBt->fanout / 2;
  // pBt->maxLeaf
  pBt->maxLeaf = pBt->pageSize - sizeof(SPageHdr);
  // pBt->minLeaf
  pBt->minLeaf = pBt->minLocal;
H
Hongze Cheng 已提交
96

H
Hongze Cheng 已提交
97 98 99 100 101 102 103
  // TODO: pBt->root
  ret = tdbBtreeOpenImpl(pBt);
  if (ret < 0) {
    free(pBt);
    return -1;
  }

H
Hongze Cheng 已提交
104
  *ppBt = pBt;
H
Hongze Cheng 已提交
105 106 107 108 109 110 111 112
  return 0;
}

int tdbBtreeClose(SBTree *pBt) {
  // TODO
  return 0;
}

H
more  
Hongze Cheng 已提交
113
int tdbBtreeCursor(SBtCursor *pCur, SBTree *pBt) {
H
more  
Hongze Cheng 已提交
114 115
  pCur->pBt = pBt;
  pCur->iPage = -1;
H
more  
Hongze Cheng 已提交
116
  pCur->pPage = NULL;
H
Hongze Cheng 已提交
117
  pCur->idx = -1;
H
more  
Hongze Cheng 已提交
118

H
more  
Hongze Cheng 已提交
119 120 121
  return 0;
}

H
Hongze Cheng 已提交
122
int tdbBtCursorInsert(SBtCursor *pCur, const void *pKey, int kLen, const void *pVal, int vLen) {
H
Hongze Cheng 已提交
123
  int     ret;
H
Hongze Cheng 已提交
124
  int     idx;
H
Hongze Cheng 已提交
125
  SPager *pPager;
H
Hongze Cheng 已提交
126 127 128
  SCell  *pCell;
  int     szCell;
  int     cret;
H
Hongze Cheng 已提交
129

H
Hongze Cheng 已提交
130
  ret = tdbBtCursorMoveTo(pCur, pKey, kLen, &cret);
H
Hongze Cheng 已提交
131 132 133 134 135
  if (ret < 0) {
    // TODO: handle error
    return -1;
  }

H
Hongze Cheng 已提交
136
  if (pCur->idx == -1) {
H
Hongze Cheng 已提交
137
    ASSERT(TDB_PAGE_NCELLS(pCur->pPage) == 0);
H
Hongze Cheng 已提交
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
    idx = 0;
  } else {
    if (cret > 0) {
      // TODO
    } else if (cret < 0) {
      // TODO
    } else {
      /* TODO */
      ASSERT(0);
    }
  }

  // Encode the key-value pairs
  ret = tdbEncodeKeyValue(pKey, kLen, pCur->pPage->kLen, pVal, vLen, pCur->pPage->vLen, pCell, &szCell);

  // Insert the cell to the index
  ret = tdbPageInsertCell(pCur->pPage, idx, pCell, szCell);
  if (ret < 0) {
    return -1;
H
Hongze Cheng 已提交
157 158
  }

H
more  
Hongze Cheng 已提交
159 160 161
  return 0;
}

H
Hongze Cheng 已提交
162
static int tdbBtCursorMoveTo(SBtCursor *pCur, const void *pKey, int kLen, int *pCRst) {
H
Hongze Cheng 已提交
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
  int     ret;
  SBTree *pBt;
  SPager *pPager;

  pBt = pCur->pBt;
  pPager = pBt->pPager;

  if (pCur->iPage < 0) {
    ASSERT(pCur->iPage == -1);
    ASSERT(pCur->idx == -1);

    // Move from the root
    ret = tdbPagerFetchPage(pPager, pBt->root, &(pCur->pPage), tdbBtreeInitPage, pBt);
    if (ret < 0) {
      ASSERT(0);
      return -1;
    }

    pCur->iPage = 0;

H
Hongze Cheng 已提交
183
    if (TDB_PAGE_NCELLS(pCur->pPage) == 0) {
H
Hongze Cheng 已提交
184
      // Current page is empty
H
Hongze Cheng 已提交
185
      ASSERT(TDB_FLAG_IS(TDB_PAGE_FLAGS(pCur->pPage), TDB_BTREE_ROOT | TDB_BTREE_LEAF));
H
Hongze Cheng 已提交
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
      return 0;
    }

    // Search from root page down to leaf
    {
      // TODO
      ASSERT(0);
      // ret = tdbBtCursorMoveToRoot(pCur);
      // if (ret < 0) {
      //   return -1;
      // }

      // if (pCur->pPage->pHdr->nCells == 0) {
      //   // Tree is empty
      // } else {
      //   for (;;) {
      //     int lidx, ridx, midx, c;

      //     pBtPage = pCur->pPage;
      //     lidx = 0;
      //     ridx = pBtPage->pHdr->nCells - 1;
      //     while (lidx <= ridx) {
      //       midx = (lidx + ridx) >> 1;
H
Hongze Cheng 已提交
209
      //       pCell = (void *)(pBtPage->aData + pBtPage->pCellIdx[midx]);
H
Hongze Cheng 已提交
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228

      //       c = tdbCompareKeyAndCell(pKey, kLen, pCell);
      //       if (c == 0) {
      //         break;
      //       } else if (c < 0) {
      //         lidx = lidx + 1;
      //       } else {
      //         ridx = ridx - 1;
      //       }
      //     }
      //   }

      //   /* code */
      // }
    }

  } else {
    // TODO: Move the cursor from a some position instead of a clear state
  }
H
more  
Hongze Cheng 已提交
229

H
Hongze Cheng 已提交
230 231
  return 0;
}
H
more  
Hongze Cheng 已提交
232

H
Hongze Cheng 已提交
233 234 235
static int tdbEncodeKeyValue(const void *pKey, int kLen, int kLenG, const void *pVal, int vLen, int vLenG, void *pBuf,
                             int *bLen) {
  u8 *pPtr;
H
more  
Hongze Cheng 已提交
236

H
Hongze Cheng 已提交
237 238 239 240 241 242 243 244 245 246 247
  ASSERT(kLen > 0 && vLen > 0);
  ASSERT(kLenG == TDB_VARIANT_LEN || kLenG == kLen);
  ASSERT(vLenG == TDB_VARIANT_LEN || vLenG == vLen);

  pPtr = (u8 *)pBuf;
  if (kLenG == TDB_VARIANT_LEN) {
    pPtr += tdbEncodeLength(pPtr, kLen);
  }

  if (vLenG == TDB_VARIANT_LEN) {
    pPtr += tdbEncodeLength(pPtr, vLen);
H
more  
Hongze Cheng 已提交
248
  }
H
more  
Hongze Cheng 已提交
249

H
Hongze Cheng 已提交
250 251 252 253 254 255 256
  memcpy(pPtr, pKey, kLen);
  pPtr += kLen;

  memcpy(pPtr, pVal, vLen);
  pPtr += vLen;

  *bLen = pPtr - (u8 *)pBuf;
H
more  
Hongze Cheng 已提交
257
  return 0;
H
Hongze Cheng 已提交
258 259 260
}

static int tdbDecodeKeyValue(const void *pBuf, void *pKey, int *kLen, void *pVal, int *vLen) {
H
more  
Hongze Cheng 已提交
261 262 263 264 265 266 267 268 269 270
  if (*kLen == TDB_VARIANT_LEN) {
    // Decode the key length
  }

  if (*vLen == TDB_VARIANT_LEN) {
    // Decode the value length
  }

  // TODO: decode the key and value

H
Hongze Cheng 已提交
271 272 273
  return 0;
}

H
more  
Hongze Cheng 已提交
274
static int tdbEncodeLength(u8 *pBuf, uint32_t len) {
H
Hongze Cheng 已提交
275 276 277 278 279 280 281 282 283 284
  int iCount = 0;

  while (len > 127) {
    pBuf[iCount++] = (u8)((len & 0xff) | 128);
    len >>= 7;
  }

  pBuf[iCount++] = (u8)len;

  return iCount;
H
more  
Hongze Cheng 已提交
285 286 287
}

static int tdbBtCursorMoveToRoot(SBtCursor *pCur) {
H
refact  
Hongze Cheng 已提交
288 289
  SBTree *pBt;
  SPager *pPager;
H
Hongze Cheng 已提交
290
  SPage  *pPage;
H
refact  
Hongze Cheng 已提交
291
  int     ret;
H
more  
Hongze Cheng 已提交
292 293

  pBt = pCur->pBt;
H
refact  
Hongze Cheng 已提交
294
  pPager = pBt->pPager;
H
more  
Hongze Cheng 已提交
295

H
Hongze Cheng 已提交
296 297 298 299
  // pPage = tdbPagerGet(pPager, pBt->root, true);
  // if (pPage == NULL) {
  //   // TODO: handle error
  // }
H
more  
Hongze Cheng 已提交
300

H
Hongze Cheng 已提交
301 302 303 304 305
  // ret = tdbInitBtPage(pPage, &pBtPage);
  // if (ret < 0) {
  //   // TODO
  //   return 0;
  // }
H
more  
Hongze Cheng 已提交
306

H
Hongze Cheng 已提交
307 308
  // pCur->pPage = pBtPage;
  // pCur->iPage = 0;
H
more  
Hongze Cheng 已提交
309 310 311 312

  return 0;
}

H
more  
Hongze Cheng 已提交
313 314
static int tdbCompareKeyAndCell(const void *pKey, int kLen, const void *pCell) {
  /* TODO */
H
more  
Hongze Cheng 已提交
315
  return 0;
H
Hongze Cheng 已提交
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
}

static int tdbDefaultKeyCmprFn(const void *pKey1, int keyLen1, const void *pKey2, int keyLen2) {
  int mlen;
  int cret;

  ASSERT(keyLen1 > 0 && keyLen2 > 0 && pKey1 != NULL && pKey2 != NULL);

  mlen = keyLen1 < keyLen2 ? keyLen1 : keyLen2;
  cret = memcmp(pKey1, pKey2, mlen);
  if (cret == 0) {
    if (keyLen1 < keyLen2) {
      cret = -1;
    } else if (keyLen1 > keyLen2) {
      cret = 1;
    } else {
      cret = 0;
    }
  }
  return cret;
H
Hongze Cheng 已提交
336 337 338 339 340 341 342 343 344 345
}

static int tdbBtreeOpenImpl(SBTree *pBt) {
  // Try to get the root page of the an existing btree

  SPgno  pgno;
  SPage *pPage;
  int    ret;

  {
H
Hongze Cheng 已提交
346
    // 1. TODO: Search the main DB to check if the DB exists
H
Hongze Cheng 已提交
347 348 349 350 351 352 353 354 355
    pgno = 0;
  }

  if (pgno != 0) {
    pBt->root = pgno;
    return 0;
  }

  // Try to create a new database
H
Hongze Cheng 已提交
356 357 358 359 360 361 362
  SBtreeZeroPageArg zArg = {.flags = TDB_BTREE_ROOT | TDB_BTREE_LEAF, .pBt = pBt};
  ret = tdbPagerNewPage(pBt->pPager, &pgno, &pPage, tdbBtreeZeroPage, &zArg);
  if (ret < 0) {
    return -1;
  }

  // TODO: Unref the page
H
Hongze Cheng 已提交
363

H
Hongze Cheng 已提交
364 365
  ASSERT(pgno != 0);
  pBt->root = pgno;
H
Hongze Cheng 已提交
366

H
Hongze Cheng 已提交
367 368 369
  return 0;
}

H
Hongze Cheng 已提交
370
static int tdbBtreeInitPage(SPage *pPage, void *arg) {
H
Hongze Cheng 已提交
371
  SBTree *pBt;
H
Hongze Cheng 已提交
372
  u16     flags;
H
Hongze Cheng 已提交
373

H
Hongze Cheng 已提交
374
  pBt = (SBTree *)arg;
H
Hongze Cheng 已提交
375

H
Hongze Cheng 已提交
376 377 378 379 380 381
  flags = TDB_PAGE_FLAGS(pPage);
  if (TDB_BTREE_PAGE_IS_LEAF(flags)) {
    pPage->szAmHdr = 0;
  } else {
    pPage->szAmHdr = sizeof(SBtPageHdr);
  }
H
Hongze Cheng 已提交
382
  pPage->pPageHdr = pPage->pData;
H
Hongze Cheng 已提交
383 384 385 386 387
  pPage->pAmHdr = pPage->pPageHdr + pPage->szPageHdr;
  pPage->pCellIdx = pPage->pAmHdr + pPage->szAmHdr;
  pPage->pFreeStart = pPage->pCellIdx + pPage->szOffset * TDB_PAGE_NCELLS(pPage);
  pPage->pFreeEnd = pPage->pData + TDB_PAGE_CCELLS(pPage);
  pPage->pPageFtr = (SPageFtr *)(pPage->pData + pPage->pageSize - sizeof(SPageFtr));
H
Hongze Cheng 已提交
388

H
Hongze Cheng 已提交
389 390
  TDB_BTREE_ASSERT_FLAG(flags);

H
Hongze Cheng 已提交
391
  // Init other fields
H
Hongze Cheng 已提交
392
  if (TDB_BTREE_PAGE_IS_LEAF(flags)) {
H
Hongze Cheng 已提交
393 394 395 396 397 398 399 400 401 402
    pPage->kLen = pBt->keyLen;
    pPage->vLen = pBt->valLen;
    pPage->maxLocal = pBt->maxLeaf;
    pPage->minLocal = pBt->minLeaf;
  } else {
    pPage->kLen = pBt->keyLen;
    pPage->vLen = sizeof(SPgno);
    pPage->maxLocal = pBt->maxLocal;
    pPage->minLocal = pBt->minLocal;
  }
H
Hongze Cheng 已提交
403 404 405 406

  return 0;
}

H
Hongze Cheng 已提交
407
static int tdbBtreeZeroPage(SPage *pPage, void *arg) {
H
Hongze Cheng 已提交
408
  u16     flags;
H
Hongze Cheng 已提交
409
  SBTree *pBt;
H
Hongze Cheng 已提交
410

H
Hongze Cheng 已提交
411 412
  flags = ((SBtreeZeroPageArg *)arg)->flags;
  pBt = ((SBtreeZeroPageArg *)arg)->pBt;
H
Hongze Cheng 已提交
413

H
Hongze Cheng 已提交
414
  pPage->pPageHdr = pPage->pData;
H
Hongze Cheng 已提交
415

H
Hongze Cheng 已提交
416 417 418 419 420 421
  // Init the page header
  TDB_PAGE_FLAGS_SET(pPage, flags);
  TDB_PAGE_NCELLS_SET(pPage, 0);
  TDB_PAGE_CCELLS_SET(pPage, pBt->pageSize - sizeof(SPageFtr));
  TDB_PAGE_FCELL_SET(pPage, 0);
  TDB_PAGE_NFREE_SET(pPage, 0);
H
Hongze Cheng 已提交
422

H
Hongze Cheng 已提交
423
  tdbBtreeInitPage(pPage, (void *)pBt);
H
Hongze Cheng 已提交
424

H
Hongze Cheng 已提交
425
  return 0;
H
Hongze Cheng 已提交
426 427 428
}

#ifndef TDB_BTREE_BALANCE
H
Hongze Cheng 已提交
429 430 431 432 433 434 435 436 437 438
typedef struct {
  SBTree *pBt;
  SPage  *pParent;
  int     idx;
  i8      nOldPages;
  SPage  *pOldPages[3];
  i8      nNewPages;
  SPage  *pNewPages[5];
} SBtreeBalanceHelper;

H
Hongze Cheng 已提交
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
static int tdbBtreeCopyPageContent(SPage *pFrom, SPage *pTo) {
  /* TODO */

  return 0;
}

static int tdbBtreeBalanceDeeper(SBTree *pBt, SPage *pRoot, SPage **ppChild) {
  SPager           *pPager;
  SPage            *pChild;
  SPgno             pgnoChild;
  int               ret;
  SBtreeZeroPageArg zArg;

  pPager = pRoot->pPager;

  // Allocate a new child page
  zArg.flags = TDB_BTREE_LEAF;
  zArg.pBt = pBt;
  ret = tdbPagerNewPage(pPager, &pgnoChild, &pChild, tdbBtreeZeroPage, &zArg);
  if (ret < 0) {
    return -1;
  }

  // Copy the root page content to the child page
  ret = tdbBtreeCopyPageContent(pRoot, pChild);
  if (ret < 0) {
    return -1;
  }

  {
    // TODO: Copy the over flow part of the page
  }

  // Reinitialize the root page
  zArg.flags = TDB_BTREE_ROOT;
  zArg.pBt = pBt;
  ret = tdbBtreeZeroPage(pRoot, &zArg);
  if (ret < 0) {
    return -1;
  }

H
Hongze Cheng 已提交
480 481 482 483
  *ppChild = pChild;
  return 0;
}

H
Hongze Cheng 已提交
484
static int tdbBtreeBalanceStep1(SBtreeBalanceHelper *pBlh) {
H
Hongze Cheng 已提交
485
#if 0
H
Hongze Cheng 已提交
486 487 488 489 490 491 492 493
  int    i;
  SPage *pParent;
  int    nDiv;
  SPgno  pgno;
  SPage *pPage;
  int    ret;

  pParent = pBlh->pParent;
H
Hongze Cheng 已提交
494
  i = pParent->pPageHdr->nCells + pParent->nOverflow;
H
Hongze Cheng 已提交
495

H
Hongze Cheng 已提交
496 497 498
  if (i < 1) {
    nDiv = 0;
  } else {
H
Hongze Cheng 已提交
499
    if (pBlh->idx == 0) {
H
Hongze Cheng 已提交
500
      nDiv = 0;
H
Hongze Cheng 已提交
501
    } else if (pBlh->idx == i) {
H
Hongze Cheng 已提交
502
      nDiv = i - 2;
H
Hongze Cheng 已提交
503
    } else {
H
Hongze Cheng 已提交
504
      nDiv = pBlh->idx - 1;
H
Hongze Cheng 已提交
505
    }
H
Hongze Cheng 已提交
506 507
    i = 2;
  }
H
Hongze Cheng 已提交
508
  pBlh->nOldPages = i + 1;
H
Hongze Cheng 已提交
509

H
Hongze Cheng 已提交
510
  if (i + nDiv - pParent->nOverflow == pParent->pPageHdr->nCells) {
H
Hongze Cheng 已提交
511
    // pgno = pParent->pPageHdr->rChild;
H
Hongze Cheng 已提交
512 513 514 515 516 517
  } else {
    ASSERT(0);
    // TODO
    pgno = 0;
  }
  for (;;) {
H
Hongze Cheng 已提交
518
    ret = tdbPagerFetchPage(pBlh->pBt->pPager, pgno, &pPage, tdbBtreeInitPage, pBlh->pBt);
H
Hongze Cheng 已提交
519
    if (ret < 0) {
H
Hongze Cheng 已提交
520
      ASSERT(0);
H
Hongze Cheng 已提交
521
      return -1;
H
Hongze Cheng 已提交
522
    }
H
Hongze Cheng 已提交
523

H
Hongze Cheng 已提交
524
    pBlh->pOldPages[i] = pPage;
H
Hongze Cheng 已提交
525 526 527 528

    if ((i--) == 0) break;

    if (pParent->nOverflow && i + nDiv == pParent->aiOvfl[0]) {
H
Hongze Cheng 已提交
529
      // pCellDiv[i] = pParent->apOvfl[0];
H
Hongze Cheng 已提交
530 531 532 533 534 535 536 537 538 539 540 541 542
      // pgno = 0;
      // szNew[i] = tdbPageCellSize(pPage, pCell);
      pParent->nOverflow = 0;
    } else {
      // pCellDiv[i] = TDB_PAGE_CELL_AT(pPage, i + nDiv - pParent->nOverflow);
      // pgno = 0;
      // szNew[i] = tdbPageCellSize(pPage, pCell);

      // Drop the cell from the page
      // ret = tdbPageDropCell(pPage, i + nDiv - pParent->nOverflow, szNew[i]);
      // if (ret < 0) {
      //   return -1;
      // }
H
Hongze Cheng 已提交
543 544 545
    }
  }

H
Hongze Cheng 已提交
546
#endif
H
Hongze Cheng 已提交
547 548 549 550
  return 0;
}

static int tdbBtreeBalanceStep2(SBtreeBalanceHelper *pBlh) {
H
Hongze Cheng 已提交
551
#if 0
H
Hongze Cheng 已提交
552
  SPage *pPage;
H
Hongze Cheng 已提交
553 554 555 556
  int    oidx;
  int    cidx;
  int    limit;
  SCell *pCell;
H
Hongze Cheng 已提交
557 558 559

  for (int i = 0; i < pBlh->nOldPages; i++) {
    pPage = pBlh->pOldPages[i];
H
Hongze Cheng 已提交
560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588
    oidx = 0;
    cidx = 0;

    if (oidx < pPage->nOverflow) {
      limit = pPage->aiOvfl[oidx];
    } else {
      limit = pPage->pPageHdr->nCells;
    }

    // Loop to copy each cell pointer out
    for (;;) {
      if (oidx >= pPage->nOverflow && cidx >= pPage->pPageHdr->nCells) break;

      if (cidx < limit) {
        // Get local cells
        pCell = TDB_PAGE_CELL_AT(pPage, cidx);
      } else if (cidx == limit) {
        // Get overflow cells
        pCell = pPage->apOvfl[oidx++];

        if (oidx < pPage->nOverflow) {
          limit = pPage->aiOvfl[oidx];
        } else {
          limit = pPage->pPageHdr->nCells;
        }
      } else {
        ASSERT(0);
      }
    }
H
Hongze Cheng 已提交
589 590 591 592

    {
      // TODO: Copy divider cells here
    }
H
Hongze Cheng 已提交
593 594 595 596
  }

  /* TODO */

H
Hongze Cheng 已提交
597
#endif
H
Hongze Cheng 已提交
598 599 600 601
  return 0;
}

static int tdbBtreeBalanceStep3(SBtreeBalanceHelper *pBlh) {
H
Hongze Cheng 已提交
602 603 604 605
  for (int i = 0; i < pBlh->nOldPages; i++) {
    /* code */
  }

H
Hongze Cheng 已提交
606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636
  return 0;
}

static int tdbBtreeBalanceStep4(SBtreeBalanceHelper *pBlh) {
  // TODO
  return 0;
}

static int tdbBtreeBalanceStep5(SBtreeBalanceHelper *pBlh) {
  // TODO
  return 0;
}

static int tdbBtreeBalanceStep6(SBtreeBalanceHelper *pBlh) {
  // TODO
  return 0;
}

static int tdbBtreeBalanceNonRoot(SBTree *pBt, SPage *pParent, int idx) {
  int                 ret;
  SBtreeBalanceHelper blh;

  blh.pBt = pBt;
  blh.pParent = pParent;
  blh.idx = idx;

  // Step 1: find two sibling pages and get engough info about the old pages
  ret = tdbBtreeBalanceStep1(&blh);
  if (ret < 0) {
    ASSERT(0);
    return -1;
H
Hongze Cheng 已提交
637 638
  }

H
Hongze Cheng 已提交
639 640 641 642 643
  // Step 2: Load all cells on the old page and the divider cells
  ret = tdbBtreeBalanceStep2(&blh);
  if (ret < 0) {
    ASSERT(0);
    return -1;
H
Hongze Cheng 已提交
644 645
  }

H
Hongze Cheng 已提交
646 647 648 649 650
  // Step 3: Get the number of pages needed to hold all cells
  ret = tdbBtreeBalanceStep3(&blh);
  if (ret < 0) {
    ASSERT(0);
    return -1;
H
Hongze Cheng 已提交
651 652
  }

H
Hongze Cheng 已提交
653 654 655 656 657
  // Step 4: Allocate enough new pages. Reuse old pages as much as possible
  ret = tdbBtreeBalanceStep4(&blh);
  if (ret < 0) {
    ASSERT(0);
    return -1;
H
Hongze Cheng 已提交
658 659
  }

H
Hongze Cheng 已提交
660 661 662 663 664 665 666 667 668 669 670 671
  // Step 5: Insert new divider cells into pParent
  ret = tdbBtreeBalanceStep5(&blh);
  if (ret < 0) {
    ASSERT(0);
    return -1;
  }

  // Step 6: Update the sibling pages
  ret = tdbBtreeBalanceStep6(&blh);
  if (ret < 0) {
    ASSERT(0);
    return -1;
H
Hongze Cheng 已提交
672 673 674 675 676 677 678 679 680
  }

  {
      // TODO: Reset states
  }

  {
    // TODO: Clear resources
  }
H
Hongze Cheng 已提交
681

H
Hongze Cheng 已提交
682 683 684 685 686
  return 0;
}

static int tdbBtreeBalance(SBtCursor *pCur) {
  int    iPage;
H
Hongze Cheng 已提交
687 688
  SPage *pParent;
  int    ret;
H
Hongze Cheng 已提交
689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705

  // Main loop to balance the BTree
  for (;;) {
    iPage = pCur->iPage;

    // TODO: Get the page free space if not get yet
    // if (pPage->nFree < 0) {
    //   if (tdbBtreeComputeFreeSpace(pPage) < 0) {
    //     return -1;
    //   }
    // }

    if (0 /*TODO: balance is over*/) {
      break;
    }

    if (iPage == 0) {
H
Hongze Cheng 已提交
706 707
      // Balance the root page by copy the root page content to
      // a child page and set the root page as empty first
H
Hongze Cheng 已提交
708
      // ASSERT(TDB_BTREE_PAGE_IS_ROOT(pCur->pPage->pPageHdr->flags));
H
Hongze Cheng 已提交
709 710 711 712 713 714 715 716 717 718 719

      ret = tdbBtreeBalanceDeeper(pCur->pBt, pCur->pPage, &(pCur->pgStack[1]));
      if (ret < 0) {
        return -1;
      }

      pCur->idx = 0;
      pCur->idxStack[0] = 0;
      pCur->pgStack[0] = pCur->pPage;
      pCur->iPage = 1;
      pCur->pPage = pCur->pgStack[1];
H
Hongze Cheng 已提交
720 721

    } else {
H
Hongze Cheng 已提交
722 723 724
      // Generalized balance step
      pParent = pCur->pgStack[pCur->iPage - 1];

H
Hongze Cheng 已提交
725
      ret = tdbBtreeBalanceNonRoot(pCur->pBt, pParent, pCur->idxStack[pCur->iPage - 1]);
H
Hongze Cheng 已提交
726 727 728 729 730 731
      if (ret < 0) {
        return -1;
      }

      pCur->iPage--;
      pCur->pPage = pCur->pgStack[pCur->iPage];
H
Hongze Cheng 已提交
732 733 734 735 736
    }
  }

  return 0;
}
H
Hongze Cheng 已提交
737 738
#endif

H
Hongze Cheng 已提交
739
#ifndef TDB_BTREE_CELL  // =========================================================
H
Hongze Cheng 已提交
740
typedef struct {
H
Hongze Cheng 已提交
741 742 743 744 745 746
  int   kLen;
  u8   *pKey;
  int   vLen;
  u8   *pVal;
  SPgno pgno;
  u8   *pTmpSpace;
H
Hongze Cheng 已提交
747 748
} SCellDecoder;

H
Hongze Cheng 已提交
749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779
static int tdbBtreeEncodePayload(SPage *pPage, u8 *pPayload, void *pKey, int kLen, void *pVal, int vLen,
                                 int *szPayload) {
  int nPayload;

  ASSERT(pKey != NULL);

  if (pVal == NULL) {
    vLen = 0;
  }

  nPayload = kLen + vLen;
  if (nPayload <= pPage->maxLocal) {
    // General case without overflow
    memcpy(pPayload, pKey, kLen);
    if (pVal) {
      memcpy(pPayload + kLen, pVal, vLen);
    }

    *szPayload = nPayload;
    return 0;
  }

  {
    // TODO: handle overflow case
    ASSERT(0);
  }

  return 0;
}

static int tdbBtreeEncodeCell(SPage *pPage, void *pKey, int kLen, void *pVal, int vLen, SCell *pCell, int *szCell) {
H
Hongze Cheng 已提交
780
  u16 flags;
H
Hongze Cheng 已提交
781 782 783 784
  u8  leaf;
  int nHeader;
  int nPayload;
  int ret;
H
Hongze Cheng 已提交
785 786 787 788

  ASSERT(pPage->kLen == TDB_VARIANT_LEN || pPage->kLen == kLen);
  ASSERT(pPage->vLen == TDB_VARIANT_LEN || pPage->vLen == vLen);

H
Hongze Cheng 已提交
789 790 791 792
  nPayload = 0;
  nHeader = 0;
  flags = TDB_PAGE_FLAGS(pPage);
  leaf = TDB_BTREE_PAGE_IS_LEAF(flags);
H
Hongze Cheng 已提交
793

H
Hongze Cheng 已提交
794 795
  // 1. Encode Header part
  /* Encode kLen if need */
H
Hongze Cheng 已提交
796
  if (pPage->kLen == TDB_VARIANT_LEN) {
H
Hongze Cheng 已提交
797
    nHeader += tdbPutVarInt(pCell + nHeader, kLen);
H
Hongze Cheng 已提交
798 799
  }

H
Hongze Cheng 已提交
800
  /* Encode vLen if need */
H
Hongze Cheng 已提交
801
  if (pPage->vLen == TDB_VARIANT_LEN) {
H
Hongze Cheng 已提交
802
    nHeader += tdbPutVarInt(pCell + nHeader, vLen);
H
Hongze Cheng 已提交
803 804
  }

H
Hongze Cheng 已提交
805 806
  /* Encode SPgno if interior page */
  if (!leaf) {
H
Hongze Cheng 已提交
807 808
    ASSERT(pPage->vLen == sizeof(SPgno));

H
Hongze Cheng 已提交
809 810 811 812 813 814 815 816 817 818 819 820 821
    ((SPgno *)(pCell + nHeader))[0] = ((SPgno *)pVal)[0];
    nHeader = nHeader + sizeof(SPgno);
  }

  // 2. Encode payload part
  if (leaf) {
    ret = tdbBtreeEncodePayload(pPage, pCell + nHeader, pKey, kLen, pVal, vLen, &nPayload);
  } else {
    ret = tdbBtreeEncodePayload(pPage, pCell + nHeader, pKey, kLen, NULL, 0, &nPayload);
  }
  if (ret < 0) {
    // TODO: handle error
    return -1;
H
Hongze Cheng 已提交
822 823
  }

H
Hongze Cheng 已提交
824
  *szCell = nHeader + nPayload;
H
Hongze Cheng 已提交
825 826 827
  return 0;
}

H
Hongze Cheng 已提交
828 829 830 831
static int tdbBtreeDecodePayload(SPage *pPage, const u8 *pPayload, SCellDecoder *pDecoder) {
  int nPayload;

  ASSERT(pDecoder->pKey == NULL);
H
Hongze Cheng 已提交
832

H
Hongze Cheng 已提交
833 834
  if (pDecoder->pVal) {
    nPayload = pDecoder->kLen + pDecoder->vLen;
H
Hongze Cheng 已提交
835
  } else {
H
Hongze Cheng 已提交
836
    nPayload = pDecoder->kLen;
H
Hongze Cheng 已提交
837 838
  }

H
Hongze Cheng 已提交
839 840 841 842 843 844 845 846 847 848 849
  if (nPayload <= pPage->maxLocal) {
    // General case without overflow
    pDecoder->pKey = (void *)pPayload;
    if (pDecoder->pVal) {
      pDecoder->pVal = (void *)(pPayload + pDecoder->vLen);
    }
  }

  {
    // TODO: handle overflow case
    ASSERT(0);
H
Hongze Cheng 已提交
850 851
  }

H
Hongze Cheng 已提交
852 853 854 855 856 857 858 859 860 861
  return 0;
}

static int tdbBtreeDecodeCell(SPage *pPage, const SCell *pCell, SCellDecoder *pDecoder) {
  u16 flags;
  u8  leaf;
  int nHeader;
  int ret;

  nHeader = 0;
H
Hongze Cheng 已提交
862
  flags = TDB_PAGE_FLAGS(pPage);
H
Hongze Cheng 已提交
863 864 865 866 867 868 869 870 871 872 873
  leaf = TDB_BTREE_PAGE_IS_LEAF(flags);

  // 1. Decode header part
  if (pPage->kLen == TDB_VARIANT_LEN) {
    nHeader += tdbGetVarInt(pCell + nHeader, &(pDecoder->kLen));
  } else {
    pDecoder->kLen = pPage->kLen;
  }

  if (pPage->vLen == TDB_VARIANT_LEN) {
    nHeader += tdbGetVarInt(pCell + nHeader, &(pDecoder->vLen));
H
Hongze Cheng 已提交
874
  } else {
H
Hongze Cheng 已提交
875 876
    pDecoder->vLen = pPage->vLen;
  }
H
Hongze Cheng 已提交
877

H
Hongze Cheng 已提交
878 879
  if (!leaf) {
    ASSERT(pPage->vLen == sizeof(SPgno));
H
Hongze Cheng 已提交
880

H
Hongze Cheng 已提交
881 882 883 884 885 886 887 888 889
    pDecoder->pgno = ((SPgno *)(pCell + nHeader))[0];
    pDecoder->pVal = (u8 *)(&(pDecoder->pgno));
    nHeader = nHeader + sizeof(SPgno);
  }

  // 2. Decode payload part
  ret = tdbBtreeDecodePayload(pPage, pCell + nHeader, pDecoder);
  if (ret < 0) {
    return -1;
H
Hongze Cheng 已提交
890 891 892 893 894
  }

  return 0;
}

H
Hongze Cheng 已提交
895
#endif