tdbBtree.c 40.4 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
#define TDB_BTREE_ROOT 0x1
#define TDB_BTREE_LEAF 0x2

H
Hongze Cheng 已提交
21
struct SBTree {
H
Hongze Cheng 已提交
22 23 24 25 26 27 28 29 30 31 32
  SPgno         root;
  int           keyLen;
  int           valLen;
  SPager       *pPager;
  tdb_cmpr_fn_t kcmpr;
  int           pageSize;
  int           maxLocal;
  int           minLocal;
  int           maxLeaf;
  int           minLeaf;
  void         *pBuf;
H
Hongze Cheng 已提交
33 34
};

H
Hongze Cheng 已提交
35 36
#define TDB_BTREE_PAGE_COMMON_HDR u8 flags;

H
Hongze Cheng 已提交
37
#define TDB_BTREE_PAGE_GET_FLAGS(PAGE)        (PAGE)->pData[0]
H
Hongze Cheng 已提交
38
#define TDB_BTREE_PAGE_SET_FLAGS(PAGE, flags) ((PAGE)->pData[0] = (flags))
H
Hongze Cheng 已提交
39 40
#define TDB_BTREE_PAGE_IS_ROOT(PAGE)          (TDB_BTREE_PAGE_GET_FLAGS(PAGE) & TDB_BTREE_ROOT)
#define TDB_BTREE_PAGE_IS_LEAF(PAGE)          (TDB_BTREE_PAGE_GET_FLAGS(PAGE) & TDB_BTREE_LEAF)
H
refact  
Hongze Cheng 已提交
41 42 43
#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 已提交
44

H
Hongze Cheng 已提交
45
#pragma pack(push, 1)
wafwerar's avatar
wafwerar 已提交
46
typedef struct {
H
Hongze Cheng 已提交
47 48 49
  TDB_BTREE_PAGE_COMMON_HDR
} SLeafHdr;

wafwerar's avatar
wafwerar 已提交
50 51
typedef struct {
  TDB_BTREE_PAGE_COMMON_HDR
H
Hongze Cheng 已提交
52 53
  SPgno pgno;  // right-most child
} SIntHdr;
wafwerar's avatar
wafwerar 已提交
54
#pragma pack(pop)
H
more  
Hongze Cheng 已提交
55

H
Hongze Cheng 已提交
56
typedef struct {
H
Hongze Cheng 已提交
57
  u8      flags;
H
Hongze Cheng 已提交
58
  SBTree *pBt;
H
Hongze Cheng 已提交
59
} SBtreeInitPageArg;
H
Hongze Cheng 已提交
60

H
Hongze Cheng 已提交
61
static int tdbDefaultKeyCmprFn(const void *pKey1, int keyLen1, const void *pKey2, int keyLen2);
H
Hongze Cheng 已提交
62
static int tdbBtreeOpenImpl(SBTree *pBt);
H
Hongze Cheng 已提交
63
static int tdbBtreeInitPage(SPage *pPage, void *arg, int init);
H
Hongze Cheng 已提交
64 65
static int tdbBtreeEncodeCell(SPage *pPage, const void *pKey, int kLen, const void *pVal, int vLen, SCell *pCell,
                              int *szCell);
H
Hongze Cheng 已提交
66
static int tdbBtreeDecodeCell(SPage *pPage, const SCell *pCell, SCellDecoder *pDecoder);
H
Hongze Cheng 已提交
67
static int tdbBtreeBalance(SBTC *pBtc);
H
Hongze Cheng 已提交
68
static int tdbBtreeCellSize(const SPage *pPage, SCell *pCell);
H
Hongze Cheng 已提交
69
static int tdbBtcMoveDownward(SBTC *pBtc);
H
Hongze Cheng 已提交
70
static int tdbBtcMoveUpward(SBTC *pBtc);
H
Hongze Cheng 已提交
71

H
Hongze Cheng 已提交
72
int tdbBtreeOpen(int keyLen, int valLen, SPager *pPager, tdb_cmpr_fn_t kcmpr, SBTree **ppBt) {
H
Hongze Cheng 已提交
73
  SBTree *pBt;
H
Hongze Cheng 已提交
74
  int     ret;
H
more  
Hongze Cheng 已提交
75

H
Hongze Cheng 已提交
76 77
  ASSERT(keyLen != 0);

H
Hongze Cheng 已提交
78
  *ppBt = NULL;
H
Hongze Cheng 已提交
79

H
Hongze Cheng 已提交
80
  pBt = (SBTree *)tdbOsCalloc(1, sizeof(*pBt));
H
Hongze Cheng 已提交
81 82 83 84 85
  if (pBt == NULL) {
    return -1;
  }

  // pBt->keyLen
H
Hongze Cheng 已提交
86
  pBt->keyLen = keyLen < 0 ? TDB_VARIANT_LEN : keyLen;
H
Hongze Cheng 已提交
87
  // pBt->valLen
H
Hongze Cheng 已提交
88
  pBt->valLen = valLen < 0 ? TDB_VARIANT_LEN : valLen;
H
refact  
Hongze Cheng 已提交
89 90
  // pBt->pPager
  pBt->pPager = pPager;
H
Hongze Cheng 已提交
91 92
  // pBt->kcmpr
  pBt->kcmpr = kcmpr ? kcmpr : tdbDefaultKeyCmprFn;
H
Hongze Cheng 已提交
93
  // pBt->pageSize
H
Hongze Cheng 已提交
94
  pBt->pageSize = pPager->pageSize;
H
Hongze Cheng 已提交
95
  // pBt->maxLocal
H
Hongze Cheng 已提交
96
  pBt->maxLocal = tdbPageCapacity(pBt->pageSize, sizeof(SIntHdr)) / 4;
H
Hongze Cheng 已提交
97
  // pBt->minLocal: Should not be allowed smaller than 15, which is [nPayload][nKey][nData]
H
Hongze Cheng 已提交
98
  pBt->minLocal = pBt->maxLocal / 2;
H
Hongze Cheng 已提交
99
  // pBt->maxLeaf
H
Hongze Cheng 已提交
100
  pBt->maxLeaf = tdbPageCapacity(pBt->pageSize, sizeof(SLeafHdr));
H
Hongze Cheng 已提交
101 102
  // pBt->minLeaf
  pBt->minLeaf = pBt->minLocal;
H
Hongze Cheng 已提交
103

H
Hongze Cheng 已提交
104 105 106
  // TODO: pBt->root
  ret = tdbBtreeOpenImpl(pBt);
  if (ret < 0) {
H
Hongze Cheng 已提交
107
    tdbOsFree(pBt);
H
Hongze Cheng 已提交
108 109 110
    return -1;
  }

H
Hongze Cheng 已提交
111
  *ppBt = pBt;
H
Hongze Cheng 已提交
112 113 114 115
  return 0;
}

int tdbBtreeClose(SBTree *pBt) {
H
Hongze Cheng 已提交
116
  if (pBt) {
H
Hongze Cheng 已提交
117
    tdbFree(pBt->pBuf);
H
Hongze Cheng 已提交
118 119
    tdbOsFree(pBt);
  }
H
Hongze Cheng 已提交
120 121 122
  return 0;
}

H
Hongze Cheng 已提交
123
int tdbBtreeInsert(SBTree *pBt, const void *pKey, int kLen, const void *pVal, int vLen, TXN *pTxn) {
H
Hongze Cheng 已提交
124 125 126 127 128 129 130 131 132
  SBTC   btc;
  SCell *pCell;
  void  *pBuf;
  int    szCell;
  int    szBuf;
  int    ret;
  int    idx;
  int    c;

H
Hongze Cheng 已提交
133
  tdbBtcOpen(&btc, pBt, pTxn);
H
Hongze Cheng 已提交
134

H
Hongze Cheng 已提交
135 136
  // move to the position to insert
  ret = tdbBtcMoveTo(&btc, pKey, kLen, &c);
H
Hongze Cheng 已提交
137
  if (ret < 0) {
H
Hongze Cheng 已提交
138 139
    tdbBtcClose(&btc);
    ASSERT(0);
H
Hongze Cheng 已提交
140 141 142
    return -1;
  }

H
Hongze Cheng 已提交
143
  if (btc.idx == -1) {
H
Hongze Cheng 已提交
144
    btc.idx = 0;
H
Hongze Cheng 已提交
145
  } else {
H
Hongze Cheng 已提交
146
    if (c > 0) {
H
Hongze Cheng 已提交
147 148 149
      btc.idx++;
    } else if (c == 0) {
      // dup key not allowed
H
Hongze Cheng 已提交
150
      ASSERT(0);
H
Hongze Cheng 已提交
151 152 153 154
      return -1;
    }
  }

H
Hongze Cheng 已提交
155 156
  ret = tdbBtcUpsert(&btc, pKey, kLen, pVal, vLen, 1);
  if (ret < 0) {
H
Hongze Cheng 已提交
157
    ASSERT(0);
H
Hongze Cheng 已提交
158
    tdbBtcClose(&btc);
H
Hongze Cheng 已提交
159 160
    return -1;
  }
H
Hongze Cheng 已提交
161

H
Hongze Cheng 已提交
162 163 164 165 166 167 168 169 170 171 172 173 174
  tdbBtcClose(&btc);
  return 0;
}

int tdbBtreeDelete(SBTree *pBt, const void *pKey, int kLen, TXN *pTxn) {
  SBTC btc;
  int  c;
  int  ret;

  tdbBtcOpen(&btc, pBt, pTxn);

  // move the cursor
  ret = tdbBtcMoveTo(&btc, pKey, kLen, &c);
H
Hongze Cheng 已提交
175
  if (ret < 0) {
H
Hongze Cheng 已提交
176 177
    tdbBtcClose(&btc);
    ASSERT(0);
H
more  
Hongze Cheng 已提交
178 179 180
    return -1;
  }

H
Hongze Cheng 已提交
181
  if (btc.idx < 0 || c != 0) {
H
more  
Hongze Cheng 已提交
182
    tdbBtcClose(&btc);
H
Hongze Cheng 已提交
183 184
    return -1;
  }
H
Hongze Cheng 已提交
185

H
Hongze Cheng 已提交
186 187
  // delete the key
  if (tdbBtcDelete(&btc) < 0) {
H
Hongze Cheng 已提交
188
    tdbBtcClose(&btc);
H
Hongze Cheng 已提交
189
    return -1;
H
Hongze Cheng 已提交
190 191
  }

H
Hongze Cheng 已提交
192
  tdbBtcClose(&btc);
H
more  
Hongze Cheng 已提交
193 194 195
  return 0;
}

H
Hongze Cheng 已提交
196
int tdbBtreeUpsert(SBTree *pBt, const void *pKey, int nKey, const void *pData, int nData, TXN *pTxn) {
H
Hongze Cheng 已提交
197 198 199 200 201 202 203
  SBTC btc;
  int  c;
  int  ret;

  tdbBtcOpen(&btc, pBt, pTxn);

  // move the cursor
H
Hongze Cheng 已提交
204
  ret = tdbBtcMoveTo(&btc, pKey, nKey, &c);
H
Hongze Cheng 已提交
205 206
  if (ret < 0) {
    ASSERT(0);
H
Hongze Cheng 已提交
207
    tdbBtcClose(&btc);
H
Hongze Cheng 已提交
208 209 210
    return -1;
  }

H
Hongze Cheng 已提交
211 212 213 214 215 216 217
  if (btc.idx == -1) {
    btc.idx = 0;
    c = 1;
  } else {
    if (c > 0) {
      btc.idx = btc.idx + 1;
    }
H
Hongze Cheng 已提交
218 219
  }

H
Hongze Cheng 已提交
220 221 222
  ret = tdbBtcUpsert(&btc, pKey, nKey, pData, nData, c);
  if (ret < 0) {
    ASSERT(0);
H
Hongze Cheng 已提交
223 224 225 226 227 228 229 230
    tdbBtcClose(&btc);
    return -1;
  }

  tdbBtcClose(&btc);
  return 0;
}

H
Hongze Cheng 已提交
231
int tdbBtreeGet(SBTree *pBt, const void *pKey, int kLen, void **ppVal, int *vLen) {
H
Hongze Cheng 已提交
232 233 234 235
  return tdbBtreePGet(pBt, pKey, kLen, NULL, NULL, ppVal, vLen);
}

int tdbBtreePGet(SBTree *pBt, const void *pKey, int kLen, void **ppKey, int *pkLen, void **ppVal, int *vLen) {
H
refact  
Hongze Cheng 已提交
236
  SBTC         btc;
H
Hongze Cheng 已提交
237 238
  SCell       *pCell;
  int          cret;
H
Hongze Cheng 已提交
239
  int          ret;
H
Hongze Cheng 已提交
240 241
  void        *pTKey = NULL;
  void        *pTVal = NULL;
H
Hongze Cheng 已提交
242 243
  SCellDecoder cd;

H
Hongze Cheng 已提交
244
  tdbBtcOpen(&btc, pBt, NULL);
H
Hongze Cheng 已提交
245

H
Hongze Cheng 已提交
246 247 248 249 250
  ret = tdbBtcMoveTo(&btc, pKey, kLen, &cret);
  if (ret < 0) {
    tdbBtcClose(&btc);
    ASSERT(0);
  }
H
Hongze Cheng 已提交
251

H
Hongze Cheng 已提交
252
  if (btc.idx < 0 || cret) {
H
Hongze Cheng 已提交
253 254
    tdbBtcClose(&btc);
    return -1;
H
Hongze Cheng 已提交
255 256 257 258 259
  }

  pCell = tdbPageGetCell(btc.pPage, btc.idx);
  tdbBtreeDecodeCell(btc.pPage, pCell, &cd);

H
Hongze Cheng 已提交
260
  if (ppKey) {
H
Hongze Cheng 已提交
261
    pTKey = tdbRealloc(*ppKey, cd.kLen);
H
Hongze Cheng 已提交
262 263 264 265 266 267 268 269
    if (pTKey == NULL) {
      tdbBtcClose(&btc);
      ASSERT(0);
      return -1;
    }
    *ppKey = pTKey;
    *pkLen = cd.kLen;
    memcpy(*ppKey, cd.pKey, cd.kLen);
270 271
  }

H
Hongze Cheng 已提交
272
  if (ppVal) {
H
Hongze Cheng 已提交
273
    pTVal = tdbRealloc(*ppVal, cd.vLen);
H
Hongze Cheng 已提交
274 275 276 277 278 279 280 281
    if (pTVal == NULL) {
      tdbBtcClose(&btc);
      ASSERT(0);
      return -1;
    }
    *ppVal = pTVal;
    *vLen = cd.vLen;
    memcpy(*ppVal, cd.pVal, cd.vLen);
282
  }
H
Hongze Cheng 已提交
283

H
Hongze Cheng 已提交
284 285
  tdbBtcClose(&btc);

286 287 288
  return 0;
}

H
Hongze Cheng 已提交
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
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 已提交
307 308 309 310 311 312 313 314 315 316
}

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 已提交
317
    // 1. TODO: Search the main DB to check if the DB exists
H
Hongze Cheng 已提交
318 319
    ret = tdbPagerOpenDB(pBt->pPager, &pgno, true);
    ASSERT(ret == 0);
H
Hongze Cheng 已提交
320 321 322 323 324 325 326 327
  }

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

  // Try to create a new database
H
Hongze Cheng 已提交
328
  ret = tdbPagerAllocPage(pBt->pPager, &pgno);
H
Hongze Cheng 已提交
329
  if (ret < 0) {
H
Hongze Cheng 已提交
330
    ASSERT(0);
H
Hongze Cheng 已提交
331 332 333 334 335
    return -1;
  }

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

H
Hongze Cheng 已提交
337 338 339
  return 0;
}

H
Hongze Cheng 已提交
340
static int tdbBtreeInitPage(SPage *pPage, void *arg, int init) {
H
Hongze Cheng 已提交
341
  SBTree *pBt;
H
Hongze Cheng 已提交
342
  u8      flags;
H
Hongze Cheng 已提交
343
  u8      leaf;
H
Hongze Cheng 已提交
344

H
Hongze Cheng 已提交
345
  pBt = ((SBtreeInitPageArg *)arg)->pBt;
H
Hongze Cheng 已提交
346

H
Hongze Cheng 已提交
347 348 349 350 351
  if (init) {
    // init page
    flags = TDB_BTREE_PAGE_GET_FLAGS(pPage);
    leaf = TDB_BTREE_PAGE_IS_LEAF(pPage);
    TDB_BTREE_ASSERT_FLAG(flags);
H
Hongze Cheng 已提交
352

H
Hongze Cheng 已提交
353
    tdbPageInit(pPage, leaf ? sizeof(SLeafHdr) : sizeof(SIntHdr), tdbBtreeCellSize);
H
Hongze Cheng 已提交
354
  } else {
H
Hongze Cheng 已提交
355 356 357 358
    // zero page
    flags = ((SBtreeInitPageArg *)arg)->flags;
    leaf = flags & TDB_BTREE_LEAF;
    TDB_BTREE_ASSERT_FLAG(flags);
H
Hongze Cheng 已提交
359

H
Hongze Cheng 已提交
360
    tdbPageZero(pPage, leaf ? sizeof(SLeafHdr) : sizeof(SIntHdr), tdbBtreeCellSize);
H
Hongze Cheng 已提交
361

H
Hongze Cheng 已提交
362 363 364
    if (leaf) {
      SLeafHdr *pLeafHdr = (SLeafHdr *)(pPage->pData);
      pLeafHdr->flags = flags;
H
Hongze Cheng 已提交
365

H
Hongze Cheng 已提交
366 367 368 369 370 371
    } else {
      SIntHdr *pIntHdr = (SIntHdr *)(pPage->pData);
      pIntHdr->flags = flags;
      pIntHdr->pgno = 0;
    }
  }
H
Hongze Cheng 已提交
372

H
refact  
Hongze Cheng 已提交
373
  if (leaf) {
H
Hongze Cheng 已提交
374 375 376 377 378 379 380 381 382 383
    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 已提交
384

H
Hongze Cheng 已提交
385
  return 0;
H
Hongze Cheng 已提交
386 387
}

H
Hongze Cheng 已提交
388
// TDB_BTREE_BALANCE =====================
H
Hongze Cheng 已提交
389
static int tdbBtreeBalanceDeeper(SBTree *pBt, SPage *pRoot, SPage **ppChild, TXN *pTxn) {
H
Hongze Cheng 已提交
390 391 392 393
  SPager           *pPager;
  SPage            *pChild;
  SPgno             pgnoChild;
  int               ret;
H
Hongze Cheng 已提交
394
  u8                flags;
H
Hongze Cheng 已提交
395
  SIntHdr          *pIntHdr;
H
Hongze Cheng 已提交
396
  SBtreeInitPageArg zArg;
H
Hongze Cheng 已提交
397
  u8                leaf;
H
Hongze Cheng 已提交
398 399

  pPager = pRoot->pPager;
H
Hongze Cheng 已提交
400
  flags = TDB_BTREE_PAGE_GET_FLAGS(pRoot);
H
refact  
Hongze Cheng 已提交
401
  leaf = TDB_BTREE_PAGE_IS_LEAF(pRoot);
H
Hongze Cheng 已提交
402

H
Hongze Cheng 已提交
403 404
  // allocate a new child page
  pgnoChild = 0;
H
Hongze Cheng 已提交
405
  zArg.flags = TDB_FLAG_REMOVE(flags, TDB_BTREE_ROOT);
H
Hongze Cheng 已提交
406
  zArg.pBt = pBt;
H
Hongze Cheng 已提交
407
  ret = tdbPagerFetchPage(pPager, &pgnoChild, &pChild, tdbBtreeInitPage, &zArg, pTxn);
H
Hongze Cheng 已提交
408 409 410 411
  if (ret < 0) {
    return -1;
  }

H
Hongze Cheng 已提交
412 413 414 415
  if (!leaf) {
    ((SIntHdr *)pChild->pData)->pgno = ((SIntHdr *)(pRoot->pData))->pgno;
  }

H
Hongze Cheng 已提交
416 417 418 419 420 421 422
  ret = tdbPagerWrite(pPager, pChild);
  if (ret < 0) {
    // TODO
    ASSERT(0);
    return 0;
  }

H
Hongze Cheng 已提交
423
  // Copy the root page content to the child page
H
Hongze Cheng 已提交
424
  tdbPageCopy(pRoot, pChild);
H
Hongze Cheng 已提交
425 426 427 428

  // Reinitialize the root page
  zArg.flags = TDB_BTREE_ROOT;
  zArg.pBt = pBt;
H
Hongze Cheng 已提交
429
  ret = tdbBtreeInitPage(pRoot, &zArg, 0);
H
Hongze Cheng 已提交
430 431 432 433
  if (ret < 0) {
    return -1;
  }

H
Hongze Cheng 已提交
434
  pIntHdr = (SIntHdr *)(pRoot->pData);
H
Hongze Cheng 已提交
435
  pIntHdr->pgno = pgnoChild;
H
Hongze Cheng 已提交
436

H
Hongze Cheng 已提交
437 438 439 440
  *ppChild = pChild;
  return 0;
}

H
Hongze Cheng 已提交
441
static int tdbBtreeBalanceNonRoot(SBTree *pBt, SPage *pParent, int idx, TXN *pTxn) {
H
Hongze Cheng 已提交
442 443 444
  int ret;

  int    nOlds;
H
Hongze Cheng 已提交
445
  SPage *pOlds[3] = {0};
H
Hongze Cheng 已提交
446 447
  SCell *pDivCell[3] = {0};
  int    szDivCell[3];
H
Hongze Cheng 已提交
448
  int    sIdx;
H
Hongze Cheng 已提交
449
  u8     childNotLeaf;
H
Hongze Cheng 已提交
450
  SPgno  rPgno;
H
Hongze Cheng 已提交
451

H
Hongze Cheng 已提交
452
  {  // Find 3 child pages at most to do balance
H
Hongze Cheng 已提交
453 454 455
    int    nCells = TDB_PAGE_TOTAL_CELLS(pParent);
    SCell *pCell;

H
Hongze Cheng 已提交
456 457 458 459 460 461 462 463 464 465 466 467 468 469
    if (nCells <= 2) {
      sIdx = 0;
      nOlds = nCells + 1;
    } else {
      // has more than three child pages
      if (idx == 0) {
        sIdx = 0;
      } else if (idx == nCells) {
        sIdx = idx - 2;
      } else {
        sIdx = idx - 1;
      }
      nOlds = 3;
    }
H
Hongze Cheng 已提交
470 471
    for (int i = 0; i < nOlds; i++) {
      ASSERT(sIdx + i <= nCells);
H
Hongze Cheng 已提交
472

H
Hongze Cheng 已提交
473
      SPgno pgno;
H
Hongze Cheng 已提交
474
      if (sIdx + i == nCells) {
H
refact  
Hongze Cheng 已提交
475
        ASSERT(!TDB_BTREE_PAGE_IS_LEAF(pParent));
H
Hongze Cheng 已提交
476 477
        pgno = ((SIntHdr *)(pParent->pData))->pgno;
      } else {
H
Hongze Cheng 已提交
478
        pCell = tdbPageGetCell(pParent, sIdx + i);
H
Hongze Cheng 已提交
479 480 481
        pgno = *(SPgno *)pCell;
      }

H
Hongze Cheng 已提交
482 483
      ret = tdbPagerFetchPage(pBt->pPager, &pgno, pOlds + i, tdbBtreeInitPage,
                              &((SBtreeInitPageArg){.pBt = pBt, .flags = 0}), pTxn);
H
Hongze Cheng 已提交
484 485 486 487
      if (ret < 0) {
        ASSERT(0);
        return -1;
      }
H
Hongze Cheng 已提交
488 489 490 491 492 493 494

      ret = tdbPagerWrite(pBt->pPager, pOlds[i]);
      if (ret < 0) {
        // TODO
        ASSERT(0);
        return -1;
      }
H
Hongze Cheng 已提交
495
    }
H
Hongze Cheng 已提交
496
    // copy the parent key out if child pages are not leaf page
H
refact  
Hongze Cheng 已提交
497
    childNotLeaf = !TDB_BTREE_PAGE_IS_LEAF(pOlds[0]);
H
Hongze Cheng 已提交
498
    if (childNotLeaf) {
H
Hongze Cheng 已提交
499 500 501 502
      for (int i = 0; i < nOlds; i++) {
        if (sIdx + i < TDB_PAGE_TOTAL_CELLS(pParent)) {
          pCell = tdbPageGetCell(pParent, sIdx + i);
          szDivCell[i] = tdbBtreeCellSize(pParent, pCell);
H
Hongze Cheng 已提交
503
          pDivCell[i] = tdbOsMalloc(szDivCell[i]);
H
Hongze Cheng 已提交
504 505
          memcpy(pDivCell[i], pCell, szDivCell[i]);
        }
H
Hongze Cheng 已提交
506

H
Hongze Cheng 已提交
507 508 509
        if (i < nOlds - 1) {
          ((SPgno *)pDivCell[i])[0] = ((SIntHdr *)pOlds[i]->pData)->pgno;
          ((SIntHdr *)pOlds[i]->pData)->pgno = 0;
H
Hongze Cheng 已提交
510
          tdbPageInsertCell(pOlds[i], TDB_PAGE_TOTAL_CELLS(pOlds[i]), pDivCell[i], szDivCell[i], 1);
H
Hongze Cheng 已提交
511
        }
H
Hongze Cheng 已提交
512
      }
H
Hongze Cheng 已提交
513
      rPgno = ((SIntHdr *)pOlds[nOlds - 1]->pData)->pgno;
H
Hongze Cheng 已提交
514
    }
H
Hongze Cheng 已提交
515 516 517 518 519 520 521 522

    ret = tdbPagerWrite(pBt->pPager, pParent);
    if (ret < 0) {
      // TODO
      ASSERT(0);
      return -1;
    }

H
Hongze Cheng 已提交
523
    // drop the cells on parent page
H
Hongze Cheng 已提交
524 525 526 527 528 529 530 531
    for (int i = 0; i < nOlds; i++) {
      nCells = TDB_PAGE_TOTAL_CELLS(pParent);
      if (sIdx < nCells) {
        tdbPageDropCell(pParent, sIdx);
      } else {
        ((SIntHdr *)pParent->pData)->pgno = 0;
      }
    }
H
Hongze Cheng 已提交
532 533
  }

H
Hongze Cheng 已提交
534
  int nNews = 0;
H
Hongze Cheng 已提交
535
  struct {
H
Hongze Cheng 已提交
536 537 538 539
    int cnt;
    int size;
    int iPage;
    int oIdx;
H
Hongze Cheng 已提交
540
  } infoNews[5] = {0};
H
Hongze Cheng 已提交
541 542 543

  {  // Get how many new pages are needed and the new distribution

H
Hongze Cheng 已提交
544 545 546
    // first loop to find minimum number of pages needed
    for (int oPage = 0; oPage < nOlds; oPage++) {
      SPage *pPage = pOlds[oPage];
H
Hongze Cheng 已提交
547 548
      SCell *pCell;
      int    cellBytes;
H
Hongze Cheng 已提交
549
      int    oIdx;
H
Hongze Cheng 已提交
550

H
Hongze Cheng 已提交
551
      for (oIdx = 0; oIdx < TDB_PAGE_TOTAL_CELLS(pPage); oIdx++) {
H
Hongze Cheng 已提交
552
        pCell = tdbPageGetCell(pPage, oIdx);
H
Hongze Cheng 已提交
553 554
        cellBytes = TDB_BYTES_CELL_TAKEN(pPage, pCell);

H
Hongze Cheng 已提交
555 556
        if (infoNews[nNews].size + cellBytes > TDB_PAGE_USABLE_SIZE(pPage)) {
          // page is full, use a new page
H
Hongze Cheng 已提交
557
          nNews++;
H
Hongze Cheng 已提交
558

H
Hongze Cheng 已提交
559 560 561 562 563 564 565
          ASSERT(infoNews[nNews].size + cellBytes <= TDB_PAGE_USABLE_SIZE(pPage));

          if (childNotLeaf) {
            // for non-child page, this cell is used as the right-most child,
            // the divider cell to parent as well
            continue;
          }
H
Hongze Cheng 已提交
566
        }
H
Hongze Cheng 已提交
567 568
        infoNews[nNews].cnt++;
        infoNews[nNews].size += cellBytes;
H
Hongze Cheng 已提交
569
        infoNews[nNews].iPage = oPage;
H
Hongze Cheng 已提交
570
        infoNews[nNews].oIdx = oIdx;
H
Hongze Cheng 已提交
571 572 573
      }
    }

H
Hongze Cheng 已提交
574
    nNews++;
H
Hongze Cheng 已提交
575 576 577

    // back loop to make the distribution even
    for (int iNew = nNews - 1; iNew > 0; iNew--) {
H
Hongze Cheng 已提交
578
      SCell *pCell;
H
Hongze Cheng 已提交
579 580
      int    szLCell, szRCell;

H
Hongze Cheng 已提交
581
      // balance page (iNew) and (iNew-1)
H
Hongze Cheng 已提交
582
      for (;;) {
H
Hongze Cheng 已提交
583
        pCell = tdbPageGetCell(pOlds[infoNews[iNew - 1].iPage], infoNews[iNew - 1].oIdx);
H
Hongze Cheng 已提交
584

H
Hongze Cheng 已提交
585 586 587
        szLCell = tdbBtreeCellSize(pOlds[infoNews[iNew - 1].iPage], pCell);
        if (!childNotLeaf) {
          szRCell = szLCell;
H
Hongze Cheng 已提交
588
        } else {
H
Hongze Cheng 已提交
589
          int    iPage = infoNews[iNew - 1].iPage;
H
Hongze Cheng 已提交
590
          int    oIdx = infoNews[iNew - 1].oIdx + 1;
H
Hongze Cheng 已提交
591
          SPage *pPage;
H
Hongze Cheng 已提交
592
          for (;;) {
H
Hongze Cheng 已提交
593
            pPage = pOlds[iPage];
H
Hongze Cheng 已提交
594 595 596 597
            if (oIdx < TDB_PAGE_TOTAL_CELLS(pPage)) {
              break;
            }

H
Hongze Cheng 已提交
598
            iPage++;
H
Hongze Cheng 已提交
599 600 601 602 603
            oIdx = 0;
          }

          pCell = tdbPageGetCell(pPage, oIdx);
          szRCell = tdbBtreeCellSize(pPage, pCell);
H
Hongze Cheng 已提交
604 605 606 607 608 609 610 611
        }

        ASSERT(infoNews[iNew - 1].cnt > 0);

        if (infoNews[iNew].size + szRCell >= infoNews[iNew - 1].size - szRCell) {
          break;
        }

H
Hongze Cheng 已提交
612
        // Move a cell right forward
H
Hongze Cheng 已提交
613 614
        infoNews[iNew - 1].cnt--;
        infoNews[iNew - 1].size -= szLCell;
H
Hongze Cheng 已提交
615
        infoNews[iNew - 1].oIdx--;
H
Hongze Cheng 已提交
616
        for (;;) {
H
Hongze Cheng 已提交
617
          if (infoNews[iNew - 1].oIdx >= 0) {
H
Hongze Cheng 已提交
618 619
            break;
          }
H
Hongze Cheng 已提交
620

H
Hongze Cheng 已提交
621 622
          infoNews[iNew - 1].iPage--;
          infoNews[iNew - 1].oIdx = TDB_PAGE_TOTAL_CELLS(pOlds[infoNews[iNew - 1].iPage]) - 1;
H
Hongze Cheng 已提交
623 624 625
        }

        infoNews[iNew].cnt++;
H
Hongze Cheng 已提交
626
        infoNews[iNew].size += szRCell;
H
Hongze Cheng 已提交
627
      }
H
Hongze Cheng 已提交
628
    }
H
Hongze Cheng 已提交
629 630
  }

H
Hongze Cheng 已提交
631 632 633 634 635 636 637 638 639 640 641 642 643
  SPage *pNews[5] = {0};
  {  // Allocate new pages, reuse the old page when possible

    SPgno             pgno;
    SBtreeInitPageArg iarg;
    u8                flags;

    flags = TDB_BTREE_PAGE_GET_FLAGS(pOlds[0]);

    for (int iNew = 0; iNew < nNews; iNew++) {
      if (iNew < nOlds) {
        pNews[iNew] = pOlds[iNew];
      } else {
H
Hongze Cheng 已提交
644
        pgno = 0;
H
Hongze Cheng 已提交
645 646
        iarg.pBt = pBt;
        iarg.flags = flags;
H
Hongze Cheng 已提交
647
        ret = tdbPagerFetchPage(pBt->pPager, &pgno, pNews + iNew, tdbBtreeInitPage, &iarg, pTxn);
H
Hongze Cheng 已提交
648 649 650
        if (ret < 0) {
          ASSERT(0);
        }
H
Hongze Cheng 已提交
651 652 653 654 655 656 657

        ret = tdbPagerWrite(pBt->pPager, pNews[iNew]);
        if (ret < 0) {
          // TODO
          ASSERT(0);
          return -1;
        }
H
Hongze Cheng 已提交
658 659
      }
    }
H
Hongze Cheng 已提交
660 661

    // TODO: sort the page according to the page number
H
Hongze Cheng 已提交
662 663
  }

H
Hongze Cheng 已提交
664
  {  // Do the real cell distribution
H
Hongze Cheng 已提交
665
    SPage            *pOldsCopy[3] = {0};
H
Hongze Cheng 已提交
666 667 668 669
    SCell            *pCell;
    int               szCell;
    SBtreeInitPageArg iarg;
    int               iNew, nNewCells;
H
Hongze Cheng 已提交
670
    SCellDecoder      cd;
H
Hongze Cheng 已提交
671 672 673 674

    iarg.pBt = pBt;
    iarg.flags = TDB_BTREE_PAGE_GET_FLAGS(pOlds[0]);
    for (int i = 0; i < nOlds; i++) {
H
Hongze Cheng 已提交
675 676
      tdbPageCreate(pOlds[0]->pageSize, &pOldsCopy[i], tdbDefaultMalloc, NULL);
      tdbBtreeInitPage(pOldsCopy[i], &iarg, 0);
H
Hongze Cheng 已提交
677 678 679 680
      tdbPageCopy(pOlds[i], pOldsCopy[i]);
    }
    iNew = 0;
    nNewCells = 0;
H
Hongze Cheng 已提交
681
    tdbBtreeInitPage(pNews[iNew], &iarg, 0);
H
Hongze Cheng 已提交
682 683 684 685 686 687 688 689 690 691 692

    for (int iOld = 0; iOld < nOlds; iOld++) {
      SPage *pPage;

      pPage = pOldsCopy[iOld];

      for (int oIdx = 0; oIdx < TDB_PAGE_TOTAL_CELLS(pPage); oIdx++) {
        pCell = tdbPageGetCell(pPage, oIdx);
        szCell = tdbBtreeCellSize(pPage, pCell);

        ASSERT(nNewCells <= infoNews[iNew].cnt);
H
Hongze Cheng 已提交
693
        ASSERT(iNew < nNews);
H
Hongze Cheng 已提交
694 695 696 697

        if (nNewCells < infoNews[iNew].cnt) {
          tdbPageInsertCell(pNews[iNew], nNewCells, pCell, szCell, 0);
          nNewCells++;
H
Hongze Cheng 已提交
698

H
Hongze Cheng 已提交
699 700 701 702 703 704 705
          // insert parent page
          if (!childNotLeaf && nNewCells == infoNews[iNew].cnt) {
            SIntHdr *pIntHdr = (SIntHdr *)pParent->pData;

            if (iNew == nNews - 1 && pIntHdr->pgno == 0) {
              pIntHdr->pgno = TDB_PAGE_PGNO(pNews[iNew]);
            } else {
H
Hongze Cheng 已提交
706 707
              tdbBtreeDecodeCell(pPage, pCell, &cd);

H
Hongze Cheng 已提交
708
              // TODO: pCell here may be inserted as an overflow cell, handle it
H
Hongze Cheng 已提交
709
              SCell *pNewCell = tdbOsMalloc(cd.kLen + 9);
H
Hongze Cheng 已提交
710 711 712
              int    szNewCell;
              SPgno  pgno;
              pgno = TDB_PAGE_PGNO(pNews[iNew]);
H
Hongze Cheng 已提交
713
              tdbBtreeEncodeCell(pParent, cd.pKey, cd.kLen, (void *)&pgno, sizeof(SPgno), pNewCell, &szNewCell);
H
Hongze Cheng 已提交
714
              tdbPageInsertCell(pParent, sIdx++, pNewCell, szNewCell, 0);
H
Hongze Cheng 已提交
715
              tdbOsFree(pNewCell);
H
Hongze Cheng 已提交
716
            }
H
Hongze Cheng 已提交
717 718

            // move to next new page
H
Hongze Cheng 已提交
719
            iNew++;
H
Hongze Cheng 已提交
720 721
            nNewCells = 0;
            if (iNew < nNews) {
H
Hongze Cheng 已提交
722
              tdbBtreeInitPage(pNews[iNew], &iarg, 0);
H
Hongze Cheng 已提交
723
            }
H
Hongze Cheng 已提交
724 725 726
          }
        } else {
          ASSERT(childNotLeaf);
H
Hongze Cheng 已提交
727
          ASSERT(iNew < nNews - 1);
H
Hongze Cheng 已提交
728

H
Hongze Cheng 已提交
729 730 731 732
          // set current new page right-most child
          ((SIntHdr *)pNews[iNew]->pData)->pgno = ((SPgno *)pCell)[0];

          // insert to parent as divider cell
H
Hongze Cheng 已提交
733 734 735
          ASSERT(iNew < nNews - 1);
          ((SPgno *)pCell)[0] = TDB_PAGE_PGNO(pNews[iNew]);
          tdbPageInsertCell(pParent, sIdx++, pCell, szCell, 0);
H
Hongze Cheng 已提交
736 737 738 739

          // move to next new page
          iNew++;
          nNewCells = 0;
H
Hongze Cheng 已提交
740
          if (iNew < nNews) {
H
Hongze Cheng 已提交
741
            tdbBtreeInitPage(pNews[iNew], &iarg, 0);
H
Hongze Cheng 已提交
742
          }
H
Hongze Cheng 已提交
743 744
        }
      }
H
Hongze Cheng 已提交
745
    }
H
Hongze Cheng 已提交
746

H
Hongze Cheng 已提交
747 748 749
    if (childNotLeaf) {
      ASSERT(TDB_PAGE_TOTAL_CELLS(pNews[nNews - 1]) == infoNews[nNews - 1].cnt);
      ((SIntHdr *)(pNews[nNews - 1]->pData))->pgno = rPgno;
H
Hongze Cheng 已提交
750

H
Hongze Cheng 已提交
751 752 753 754 755 756
      SIntHdr *pIntHdr = (SIntHdr *)pParent->pData;
      if (pIntHdr->pgno == 0) {
        pIntHdr->pgno = TDB_PAGE_PGNO(pNews[nNews - 1]);
      } else {
        ((SPgno *)pDivCell[nOlds - 1])[0] = TDB_PAGE_PGNO(pNews[nNews - 1]);
        tdbPageInsertCell(pParent, sIdx, pDivCell[nOlds - 1], szDivCell[nOlds - 1], 0);
H
Hongze Cheng 已提交
757
      }
H
Hongze Cheng 已提交
758 759 760
    }

    for (int i = 0; i < nOlds; i++) {
H
Hongze Cheng 已提交
761
      tdbPageDestroy(pOldsCopy[i], tdbDefaultFree, NULL);
H
Hongze Cheng 已提交
762 763 764
    }
  }

H
Hongze Cheng 已提交
765 766 767 768 769 770 771
  if (TDB_BTREE_PAGE_IS_ROOT(pParent) && TDB_PAGE_TOTAL_CELLS(pParent) == 0) {
    i8 flags = TDB_BTREE_ROOT | TDB_BTREE_PAGE_IS_LEAF(pNews[0]);
    // copy content to the parent page
    tdbBtreeInitPage(pParent, &(SBtreeInitPageArg){.flags = flags, .pBt = pBt}, 0);
    tdbPageCopy(pNews[0], pParent);
  }

H
Hongze Cheng 已提交
772 773
  for (int i = 0; i < 3; i++) {
    if (pDivCell[i]) {
H
Hongze Cheng 已提交
774
      tdbOsFree(pDivCell[i]);
H
Hongze Cheng 已提交
775 776
    }
  }
H
Hongze Cheng 已提交
777

H
more  
Hongze Cheng 已提交
778 779 780
  // TODO: here is not corrent for drop case
  for (int i = 0; i < nNews; i++) {
    if (i < nOlds) {
H
Hongze Cheng 已提交
781
      tdbPagerReturnPage(pBt->pPager, pOlds[i], pTxn);
H
more  
Hongze Cheng 已提交
782
    } else {
H
Hongze Cheng 已提交
783
      tdbPagerReturnPage(pBt->pPager, pNews[i], pTxn);
H
more  
Hongze Cheng 已提交
784 785 786
    }
  }

H
Hongze Cheng 已提交
787
  return 0;
H
Hongze Cheng 已提交
788 789
}

H
Hongze Cheng 已提交
790
static int tdbBtreeBalance(SBTC *pBtc) {
H
Hongze Cheng 已提交
791
  int    iPage;
H
Hongze Cheng 已提交
792 793
  int    ret;
  int    nFree;
H
Hongze Cheng 已提交
794
  SPage *pParent;
H
Hongze Cheng 已提交
795
  SPage *pPage;
H
Hongze Cheng 已提交
796
  u8     flags;
H
Hongze Cheng 已提交
797 798
  u8     leaf;
  u8     root;
H
Hongze Cheng 已提交
799 800 801

  // Main loop to balance the BTree
  for (;;) {
H
Hongze Cheng 已提交
802 803
    iPage = pBtc->iPage;
    pPage = pBtc->pPage;
H
refact  
Hongze Cheng 已提交
804 805
    leaf = TDB_BTREE_PAGE_IS_LEAF(pPage);
    root = TDB_BTREE_PAGE_IS_ROOT(pPage);
H
Hongze Cheng 已提交
806
    nFree = TDB_PAGE_FREE_SIZE(pPage);
H
Hongze Cheng 已提交
807

H
Hongze Cheng 已提交
808 809
    // when the page is not overflow and not too empty, the balance work
    // is finished. Just break out the balance loop.
H
Hongze Cheng 已提交
810
    if (pPage->nOverflow == 0 && nFree < TDB_PAGE_USABLE_SIZE(pPage) * 2 / 3) {
H
Hongze Cheng 已提交
811 812 813 814
      break;
    }

    if (iPage == 0) {
H
Hongze Cheng 已提交
815 816 817
      // For the root page, only balance when the page is overfull,
      // ignore the case of empty
      if (pPage->nOverflow == 0) break;
H
Hongze Cheng 已提交
818

H
Hongze Cheng 已提交
819
      ret = tdbBtreeBalanceDeeper(pBtc->pBt, pPage, &(pBtc->pgStack[1]), pBtc->pTxn);
H
Hongze Cheng 已提交
820 821 822 823
      if (ret < 0) {
        return -1;
      }

H
Hongze Cheng 已提交
824 825 826 827 828
      pBtc->idx = 0;
      pBtc->idxStack[0] = 0;
      pBtc->pgStack[0] = pBtc->pPage;
      pBtc->iPage = 1;
      pBtc->pPage = pBtc->pgStack[1];
H
Hongze Cheng 已提交
829
    } else {
H
Hongze Cheng 已提交
830
      // Generalized balance step
H
Hongze Cheng 已提交
831
      pParent = pBtc->pgStack[iPage - 1];
H
Hongze Cheng 已提交
832

H
Hongze Cheng 已提交
833
      ret = tdbBtreeBalanceNonRoot(pBtc->pBt, pParent, pBtc->idxStack[pBtc->iPage - 1], pBtc->pTxn);
H
Hongze Cheng 已提交
834 835 836 837
      if (ret < 0) {
        return -1;
      }

H
Hongze Cheng 已提交
838
      tdbPagerReturnPage(pBtc->pBt->pPager, pBtc->pPage, pBtc->pTxn);
H
more  
Hongze Cheng 已提交
839

H
Hongze Cheng 已提交
840 841
      pBtc->iPage--;
      pBtc->pPage = pBtc->pgStack[pBtc->iPage];
H
Hongze Cheng 已提交
842 843 844 845 846
    }
  }

  return 0;
}
H
Hongze Cheng 已提交
847
// TDB_BTREE_BALANCE
H
Hongze Cheng 已提交
848

H
Hongze Cheng 已提交
849
// TDB_BTREE_CELL =====================
H
Hongze Cheng 已提交
850 851
static int tdbBtreeEncodePayload(SPage *pPage, SCell *pCell, int nHeader, const void *pKey, int kLen, const void *pVal,
                                 int vLen, int *szPayload) {
H
Hongze Cheng 已提交
852 853 854
  int nPayload;

  nPayload = kLen + vLen;
H
Hongze Cheng 已提交
855 856 857
  if (nPayload + nHeader <= pPage->maxLocal) {
    // no overflow page is needed
    memcpy(pCell + nHeader, pKey, kLen);
H
Hongze Cheng 已提交
858
    if (pVal) {
H
Hongze Cheng 已提交
859
      memcpy(pCell + nHeader + kLen, pVal, vLen);
H
Hongze Cheng 已提交
860 861 862 863 864 865 866 867 868 869 870 871 872 873
    }

    *szPayload = nPayload;
    return 0;
  }

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

  return 0;
}

H
Hongze Cheng 已提交
874 875
static int tdbBtreeEncodeCell(SPage *pPage, const void *pKey, int kLen, const void *pVal, int vLen, SCell *pCell,
                              int *szCell) {
H
Hongze Cheng 已提交
876 877 878 879
  u8  leaf;
  int nHeader;
  int nPayload;
  int ret;
H
Hongze Cheng 已提交
880 881 882

  ASSERT(pPage->kLen == TDB_VARIANT_LEN || pPage->kLen == kLen);
  ASSERT(pPage->vLen == TDB_VARIANT_LEN || pPage->vLen == vLen);
H
Hongze Cheng 已提交
883
  ASSERT(pKey != NULL && kLen > 0);
H
Hongze Cheng 已提交
884

H
Hongze Cheng 已提交
885 886
  nPayload = 0;
  nHeader = 0;
H
refact  
Hongze Cheng 已提交
887
  leaf = TDB_BTREE_PAGE_IS_LEAF(pPage);
H
Hongze Cheng 已提交
888

H
Hongze Cheng 已提交
889
  // 1. Encode Header part
H
Hongze Cheng 已提交
890 891 892 893 894 895 896 897
  /* Encode SPgno if interior page */
  if (!leaf) {
    ASSERT(pPage->vLen == sizeof(SPgno));

    ((SPgno *)(pCell + nHeader))[0] = ((SPgno *)pVal)[0];
    nHeader = nHeader + sizeof(SPgno);
  }

H
Hongze Cheng 已提交
898
  /* Encode kLen if need */
H
Hongze Cheng 已提交
899
  if (pPage->kLen == TDB_VARIANT_LEN) {
H
Hongze Cheng 已提交
900
    nHeader += tdbPutVarInt(pCell + nHeader, kLen);
H
Hongze Cheng 已提交
901 902
  }

H
Hongze Cheng 已提交
903
  /* Encode vLen if need */
H
Hongze Cheng 已提交
904
  if (pPage->vLen == TDB_VARIANT_LEN) {
H
Hongze Cheng 已提交
905
    nHeader += tdbPutVarInt(pCell + nHeader, vLen);
H
Hongze Cheng 已提交
906 907
  }

H
Hongze Cheng 已提交
908
  // 2. Encode payload part
H
Hongze Cheng 已提交
909 910 911
  if ((!leaf) || pPage->vLen == 0) {
    pVal = NULL;
    vLen = 0;
H
Hongze Cheng 已提交
912
  }
H
Hongze Cheng 已提交
913 914

  ret = tdbBtreeEncodePayload(pPage, pCell, nHeader, pKey, kLen, pVal, vLen, &nPayload);
H
Hongze Cheng 已提交
915
  if (ret < 0) {
H
Hongze Cheng 已提交
916 917 918
    // TODO
    ASSERT(0);
    return 0;
H
Hongze Cheng 已提交
919 920
  }

H
Hongze Cheng 已提交
921
  *szCell = nHeader + nPayload;
H
Hongze Cheng 已提交
922 923 924
  return 0;
}

H
Hongze Cheng 已提交
925
static int tdbBtreeDecodePayload(SPage *pPage, const SCell *pCell, int nHeader, SCellDecoder *pDecoder) {
H
Hongze Cheng 已提交
926 927 928
  int nPayload;

  if (pDecoder->pVal) {
H
Hongze Cheng 已提交
929
    ASSERT(!TDB_BTREE_PAGE_IS_LEAF(pPage));
H
Hongze Cheng 已提交
930
    nPayload = pDecoder->kLen;
H
Hongze Cheng 已提交
931 932
  } else {
    nPayload = pDecoder->kLen + pDecoder->vLen;
H
Hongze Cheng 已提交
933 934
  }

H
Hongze Cheng 已提交
935 936 937 938 939
  if (nHeader + nPayload <= pPage->maxLocal) {
    // no over flow case
    pDecoder->pKey = pCell + nHeader;
    if (pDecoder->pVal == NULL && pDecoder->vLen > 0) {
      pDecoder->pVal = pCell + nHeader + pDecoder->kLen;
H
Hongze Cheng 已提交
940
    }
H
Hongze Cheng 已提交
941 942 943 944
    return 0;
  }

  {
H
Hongze Cheng 已提交
945 946
    // TODO: handle overflow case
    ASSERT(0);
H
Hongze Cheng 已提交
947 948
  }

H
Hongze Cheng 已提交
949 950 951 952 953 954 955 956 957
  return 0;
}

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

  nHeader = 0;
H
refact  
Hongze Cheng 已提交
958
  leaf = TDB_BTREE_PAGE_IS_LEAF(pPage);
H
Hongze Cheng 已提交
959

H
Hongze Cheng 已提交
960 961 962 963 964 965 966
  // Clear the state of decoder
  pDecoder->kLen = -1;
  pDecoder->pKey = NULL;
  pDecoder->vLen = -1;
  pDecoder->pVal = NULL;
  pDecoder->pgno = 0;

H
Hongze Cheng 已提交
967
  // 1. Decode header part
H
Hongze Cheng 已提交
968 969 970 971 972 973 974 975
  if (!leaf) {
    ASSERT(pPage->vLen == sizeof(SPgno));

    pDecoder->pgno = ((SPgno *)(pCell + nHeader))[0];
    pDecoder->pVal = (u8 *)(&(pDecoder->pgno));
    nHeader = nHeader + sizeof(SPgno);
  }

H
Hongze Cheng 已提交
976 977 978 979 980 981 982
  if (pPage->kLen == TDB_VARIANT_LEN) {
    nHeader += tdbGetVarInt(pCell + nHeader, &(pDecoder->kLen));
  } else {
    pDecoder->kLen = pPage->kLen;
  }

  if (pPage->vLen == TDB_VARIANT_LEN) {
H
Hongze Cheng 已提交
983
    ASSERT(leaf);
H
Hongze Cheng 已提交
984
    nHeader += tdbGetVarInt(pCell + nHeader, &(pDecoder->vLen));
H
Hongze Cheng 已提交
985
  } else {
H
Hongze Cheng 已提交
986 987
    pDecoder->vLen = pPage->vLen;
  }
H
Hongze Cheng 已提交
988

H
Hongze Cheng 已提交
989
  // 2. Decode payload part
H
Hongze Cheng 已提交
990
  ret = tdbBtreeDecodePayload(pPage, pCell, nHeader, pDecoder);
H
Hongze Cheng 已提交
991 992
  if (ret < 0) {
    return -1;
H
Hongze Cheng 已提交
993 994 995 996 997
  }

  return 0;
}

H
Hongze Cheng 已提交
998
static int tdbBtreeCellSize(const SPage *pPage, SCell *pCell) {
H
refact  
Hongze Cheng 已提交
999
  u8  leaf;
H
Hongze Cheng 已提交
1000 1001 1002
  int szCell;
  int kLen = 0, vLen = 0;

H
refact  
Hongze Cheng 已提交
1003
  leaf = TDB_BTREE_PAGE_IS_LEAF(pPage);
H
Hongze Cheng 已提交
1004 1005
  szCell = 0;

H
refact  
Hongze Cheng 已提交
1006
  if (!leaf) {
H
Hongze Cheng 已提交
1007 1008 1009 1010 1011 1012 1013 1014 1015
    szCell += sizeof(SPgno);
  }

  if (pPage->kLen == TDB_VARIANT_LEN) {
    szCell += tdbGetVarInt(pCell + szCell, &kLen);
  } else {
    kLen = pPage->kLen;
  }

H
refact  
Hongze Cheng 已提交
1016 1017 1018 1019 1020
  if (pPage->vLen == TDB_VARIANT_LEN) {
    ASSERT(leaf);
    szCell += tdbGetVarInt(pCell + szCell, &vLen);
  } else if (leaf) {
    vLen = pPage->vLen;
H
Hongze Cheng 已提交
1021 1022 1023 1024
  }

  szCell = szCell + kLen + vLen;

H
refact  
Hongze Cheng 已提交
1025 1026 1027 1028 1029 1030 1031 1032 1033
  if (szCell <= pPage->maxLocal) {
    return szCell;
  }

  {
    // TODO
    ASSERT(0);
    return 0;
  }
H
Hongze Cheng 已提交
1034
}
H
Hongze Cheng 已提交
1035
// TDB_BTREE_CELL
H
Hongze Cheng 已提交
1036

H
refact  
Hongze Cheng 已提交
1037
// TDB_BTREE_CURSOR =====================
H
Hongze Cheng 已提交
1038
int tdbBtcOpen(SBTC *pBtc, SBTree *pBt, TXN *pTxn) {
H
Hongze Cheng 已提交
1039 1040 1041 1042
  pBtc->pBt = pBt;
  pBtc->iPage = -1;
  pBtc->pPage = NULL;
  pBtc->idx = -1;
H
Hongze Cheng 已提交
1043
  memset(&pBtc->coder, 0, sizeof(SCellDecoder));
H
Hongze Cheng 已提交
1044 1045 1046 1047 1048 1049 1050

  if (pTxn == NULL) {
    pBtc->pTxn = &pBtc->txn;
    tdbTxnOpen(pBtc->pTxn, 0, tdbDefaultMalloc, tdbDefaultFree, NULL, 0);
  } else {
    pBtc->pTxn = pTxn;
  }
H
Hongze Cheng 已提交
1051 1052 1053 1054

  return 0;
}

H
Hongze Cheng 已提交
1055
int tdbBtcMoveToFirst(SBTC *pBtc) {
H
refact  
Hongze Cheng 已提交
1056 1057 1058
  int     ret;
  SBTree *pBt;
  SPager *pPager;
H
Hongze Cheng 已提交
1059 1060
  SCell  *pCell;
  SPgno   pgno;
H
refact  
Hongze Cheng 已提交
1061 1062 1063 1064 1065

  pBt = pBtc->pBt;
  pPager = pBt->pPager;

  if (pBtc->iPage < 0) {
H
Hongze Cheng 已提交
1066
    // move a clean cursor
H
Hongze Cheng 已提交
1067
    ret = tdbPagerFetchPage(pPager, &pBt->root, &(pBtc->pPage), tdbBtreeInitPage,
H
Hongze Cheng 已提交
1068
                            &((SBtreeInitPageArg){.pBt = pBt, .flags = TDB_BTREE_ROOT | TDB_BTREE_LEAF}), pBtc->pTxn);
H
refact  
Hongze Cheng 已提交
1069 1070 1071 1072 1073
    if (ret < 0) {
      ASSERT(0);
      return -1;
    }

H
Hongze Cheng 已提交
1074
    ASSERT(TDB_BTREE_PAGE_IS_ROOT(pBtc->pPage));
H
refact  
Hongze Cheng 已提交
1075

H
Hongze Cheng 已提交
1076 1077 1078 1079
    pBtc->iPage = 0;
    if (TDB_PAGE_TOTAL_CELLS(pBtc->pPage) > 0) {
      pBtc->idx = 0;
    } else {
H
more  
Hongze Cheng 已提交
1080
      // no any data, point to an invalid position
H
Hongze Cheng 已提交
1081 1082
      ASSERT(TDB_BTREE_PAGE_IS_LEAF(pBtc->pPage));
      pBtc->idx = -1;
H
refact  
Hongze Cheng 已提交
1083 1084
      return 0;
    }
H
Hongze Cheng 已提交
1085
  } else {
H
Hongze Cheng 已提交
1086 1087
    ASSERT(0);
#if 0
H
Hongze Cheng 已提交
1088 1089
    // move from a position
    int iPage = 0;
H
refact  
Hongze Cheng 已提交
1090

H
Hongze Cheng 已提交
1091 1092 1093 1094
    for (; iPage < pBtc->iPage; iPage++) {
      ASSERT(pBtc->idxStack[iPage] >= 0);
      if (pBtc->idxStack[iPage]) break;
    }
H
refact  
Hongze Cheng 已提交
1095

H
Hongze Cheng 已提交
1096 1097
    // move upward
    for (;;) {
H
Hongze Cheng 已提交
1098
      if (pBtc->iPage == iPage) {
H
Hongze Cheng 已提交
1099
        pBtc->idx = 0;
H
refact  
Hongze Cheng 已提交
1100 1101
        break;
      }
H
Hongze Cheng 已提交
1102

H
Hongze Cheng 已提交
1103
      tdbBtcMoveUpward(pBtc);
H
Hongze Cheng 已提交
1104
    }
H
Hongze Cheng 已提交
1105
#endif
H
Hongze Cheng 已提交
1106 1107 1108 1109
  }

  // move downward
  for (;;) {
H
refact  
Hongze Cheng 已提交
1110
    if (TDB_BTREE_PAGE_IS_LEAF(pBtc->pPage)) break;
H
Hongze Cheng 已提交
1111

H
Hongze Cheng 已提交
1112
    ret = tdbBtcMoveDownward(pBtc);
H
Hongze Cheng 已提交
1113 1114 1115 1116 1117 1118 1119 1120
    if (ret < 0) {
      ASSERT(0);
      return -1;
    }

    pBtc->idx = 0;
  }

H
Hongze Cheng 已提交
1121 1122 1123 1124
  return 0;
}

int tdbBtcMoveToLast(SBTC *pBtc) {
H
Hongze Cheng 已提交
1125
  int     ret;
H
Hongze Cheng 已提交
1126
  int     nCells;
H
Hongze Cheng 已提交
1127 1128 1129 1130 1131 1132 1133 1134 1135
  SBTree *pBt;
  SPager *pPager;
  SPgno   pgno;

  pBt = pBtc->pBt;
  pPager = pBt->pPager;

  if (pBtc->iPage < 0) {
    // move a clean cursor
H
Hongze Cheng 已提交
1136
    ret = tdbPagerFetchPage(pPager, &pBt->root, &(pBtc->pPage), tdbBtreeInitPage,
H
Hongze Cheng 已提交
1137
                            &((SBtreeInitPageArg){.pBt = pBt, .flags = TDB_BTREE_ROOT | TDB_BTREE_LEAF}), pBtc->pTxn);
H
Hongze Cheng 已提交
1138 1139 1140 1141 1142
    if (ret < 0) {
      ASSERT(0);
      return -1;
    }

H
Hongze Cheng 已提交
1143
    nCells = TDB_PAGE_TOTAL_CELLS(pBtc->pPage);
H
Hongze Cheng 已提交
1144
    pBtc->iPage = 0;
H
Hongze Cheng 已提交
1145 1146 1147 1148 1149 1150 1151 1152
    if (nCells > 0) {
      pBtc->idx = TDB_BTREE_PAGE_IS_LEAF(pBtc->pPage) ? nCells - 1 : nCells;
    } else {
      // no data at all, point to an invalid position
      ASSERT(TDB_BTREE_PAGE_IS_LEAF(pBtc->pPage));
      pBtc->idx = -1;
      return 0;
    }
H
Hongze Cheng 已提交
1153
  } else {
H
Hongze Cheng 已提交
1154 1155
    ASSERT(0);
#if 0
H
Hongze Cheng 已提交
1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166
    int iPage = 0;

    // downward search
    for (; iPage < pBtc->iPage; iPage++) {
      ASSERT(!TDB_BTREE_PAGE_IS_LEAF(pBtc->pgStack[iPage]));
      nCells = TDB_PAGE_TOTAL_CELLS(pBtc->pgStack[iPage]);
      if (pBtc->idxStack[iPage] != nCells) break;
    }

    // move upward
    for (;;) {
H
Hongze Cheng 已提交
1167
      if (pBtc->iPage == iPage) {
H
Hongze Cheng 已提交
1168 1169 1170 1171 1172
        if (TDB_BTREE_PAGE_IS_LEAF(pBtc->pPage)) {
          pBtc->idx = TDB_PAGE_TOTAL_CELLS(pBtc->pPage) - 1;
        } else {
          pBtc->idx = TDB_PAGE_TOTAL_CELLS(pBtc->pPage);
        }
H
Hongze Cheng 已提交
1173
        break;
H
Hongze Cheng 已提交
1174 1175 1176 1177
      }

      tdbBtcMoveUpward(pBtc);
    }
H
Hongze Cheng 已提交
1178
#endif
H
Hongze Cheng 已提交
1179 1180 1181 1182
  }

  // move downward
  for (;;) {
H
Hongze Cheng 已提交
1183 1184 1185 1186 1187 1188 1189 1190 1191
    if (TDB_BTREE_PAGE_IS_LEAF(pBtc->pPage)) break;

    ret = tdbBtcMoveDownward(pBtc);
    if (ret < 0) {
      ASSERT(0);
      return -1;
    }

    nCells = TDB_PAGE_TOTAL_CELLS(pBtc->pPage);
H
refact  
Hongze Cheng 已提交
1192
    if (TDB_BTREE_PAGE_IS_LEAF(pBtc->pPage)) {
H
Hongze Cheng 已提交
1193
      pBtc->idx = nCells - 1;
H
Hongze Cheng 已提交
1194
    } else {
H
Hongze Cheng 已提交
1195
      pBtc->idx = nCells;
H
Hongze Cheng 已提交
1196 1197 1198
    }
  }

H
Hongze Cheng 已提交
1199 1200 1201 1202
  return 0;
}

int tdbBtreeNext(SBTC *pBtc, void **ppKey, int *kLen, void **ppVal, int *vLen) {
H
Hongze Cheng 已提交
1203 1204 1205 1206 1207
  SCell       *pCell;
  SCellDecoder cd;
  void        *pKey, *pVal;
  int          ret;

H
Hongze Cheng 已提交
1208
  // current cursor points to an invalid position
H
Hongze Cheng 已提交
1209
  if (pBtc->idx < 0) {
H
Hongze Cheng 已提交
1210 1211 1212 1213 1214 1215 1216
    return -1;
  }

  pCell = tdbPageGetCell(pBtc->pPage, pBtc->idx);

  tdbBtreeDecodeCell(pBtc->pPage, pCell, &cd);

H
Hongze Cheng 已提交
1217
  pKey = tdbRealloc(*ppKey, cd.kLen);
H
Hongze Cheng 已提交
1218 1219 1220 1221 1222 1223 1224
  if (pKey == NULL) {
    return -1;
  }

  *ppKey = pKey;
  *kLen = cd.kLen;
  memcpy(pKey, cd.pKey, cd.kLen);
C
Cary Xu 已提交
1225 1226 1227

  if (ppVal) {
    // TODO: vLen may be zero
H
Hongze Cheng 已提交
1228
    pVal = tdbRealloc(*ppVal, cd.vLen);
C
Cary Xu 已提交
1229
    if (pVal == NULL) {
H
Hongze Cheng 已提交
1230
      tdbFree(pKey);
C
Cary Xu 已提交
1231 1232 1233 1234 1235 1236 1237
      return -1;
    }

    *ppVal = pVal;
    *vLen = cd.vLen;
    memcpy(pVal, cd.pVal, cd.vLen);
  }
H
Hongze Cheng 已提交
1238 1239

  ret = tdbBtcMoveToNext(pBtc);
H
Hongze Cheng 已提交
1240 1241 1242 1243
  if (ret < 0) {
    ASSERT(0);
    return -1;
  }
H
Hongze Cheng 已提交
1244 1245 1246 1247

  return 0;
}

1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293
int tdbBtreePrev(SBTC *pBtc, void **ppKey, int *kLen, void **ppVal, int *vLen) {
  SCell       *pCell;
  SCellDecoder cd;
  void        *pKey, *pVal;
  int          ret;

  // current cursor points to an invalid position
  if (pBtc->idx < 0) {
    return -1;
  }

  pCell = tdbPageGetCell(pBtc->pPage, pBtc->idx);

  tdbBtreeDecodeCell(pBtc->pPage, pCell, &cd);

  pKey = tdbRealloc(*ppKey, cd.kLen);
  if (pKey == NULL) {
    return -1;
  }

  *ppKey = pKey;
  *kLen = cd.kLen;
  memcpy(pKey, cd.pKey, cd.kLen);

  if (ppVal) {
    // TODO: vLen may be zero
    pVal = tdbRealloc(*ppVal, cd.vLen);
    if (pVal == NULL) {
      tdbFree(pKey);
      return -1;
    }

    *ppVal = pVal;
    *vLen = cd.vLen;
    memcpy(pVal, cd.pVal, cd.vLen);
  }

  ret = tdbBtcMoveToPrev(pBtc);
  if (ret < 0) {
    ASSERT(0);
    return -1;
  }

  return 0;
}

H
Hongze Cheng 已提交
1294
int tdbBtcMoveToNext(SBTC *pBtc) {
H
Hongze Cheng 已提交
1295
  int    nCells;
H
Hongze Cheng 已提交
1296
  int    ret;
H
Hongze Cheng 已提交
1297 1298
  SCell *pCell;

H
refact  
Hongze Cheng 已提交
1299
  ASSERT(TDB_BTREE_PAGE_IS_LEAF(pBtc->pPage));
H
Hongze Cheng 已提交
1300 1301 1302

  if (pBtc->idx < 0) return -1;

H
Hongze Cheng 已提交
1303
  pBtc->idx++;
H
Hongze Cheng 已提交
1304 1305 1306 1307
  if (pBtc->idx < TDB_PAGE_TOTAL_CELLS(pBtc->pPage)) {
    return 0;
  }

H
Hongze Cheng 已提交
1308
  // move upward
H
Hongze Cheng 已提交
1309
  for (;;) {
H
Hongze Cheng 已提交
1310 1311 1312 1313 1314
    if (pBtc->iPage == 0) {
      pBtc->idx = -1;
      return 0;
    }

H
Hongze Cheng 已提交
1315 1316 1317
    tdbBtcMoveUpward(pBtc);
    pBtc->idx++;

H
Hongze Cheng 已提交
1318 1319
    ASSERT(!TDB_BTREE_PAGE_IS_LEAF(pBtc->pPage));
    if (pBtc->idx <= TDB_PAGE_TOTAL_CELLS(pBtc->pPage)) {
H
Hongze Cheng 已提交
1320 1321
      break;
    }
H
Hongze Cheng 已提交
1322 1323
  }

H
Hongze Cheng 已提交
1324
  // move downward
H
Hongze Cheng 已提交
1325
  for (;;) {
H
Hongze Cheng 已提交
1326
    if (TDB_BTREE_PAGE_IS_LEAF(pBtc->pPage)) break;
H
Hongze Cheng 已提交
1327

H
Hongze Cheng 已提交
1328 1329 1330 1331
    ret = tdbBtcMoveDownward(pBtc);
    if (ret < 0) {
      ASSERT(0);
      return -1;
H
Hongze Cheng 已提交
1332
    }
H
Hongze Cheng 已提交
1333 1334

    pBtc->idx = 0;
H
Hongze Cheng 已提交
1335 1336
  }

H
Hongze Cheng 已提交
1337 1338 1339
  return 0;
}

H
Hongze Cheng 已提交
1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376
int tdbBtcMoveToPrev(SBTC *pBtc) {
  if (pBtc->idx < 0) return -1;

  pBtc->idx--;
  if (pBtc->idx >= 0) {
    return 0;
  }

  // move upward
  for (;;) {
    if (pBtc->iPage == 0) {
      pBtc->idx = -1;
      return 0;
    }

    tdbBtcMoveUpward(pBtc);
    pBtc->idx--;
    if (pBtc->idx >= 0) {
      break;
    }
  }

  // move downward
  for (;;) {
    if (TDB_BTREE_PAGE_IS_LEAF(pBtc->pPage)) break;

    tdbBtcMoveDownward(pBtc);
    if (TDB_BTREE_PAGE_IS_LEAF(pBtc->pPage)) {
      pBtc->idx = TDB_PAGE_TOTAL_CELLS(pBtc->pPage) - 1;
    } else {
      pBtc->idx = TDB_PAGE_TOTAL_CELLS(pBtc->pPage);
    }
  }

  return 0;
}

H
Hongze Cheng 已提交
1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390
static int tdbBtcMoveDownward(SBTC *pBtc) {
  int    ret;
  SPgno  pgno;
  SCell *pCell;

  ASSERT(pBtc->idx >= 0);
  ASSERT(!TDB_BTREE_PAGE_IS_LEAF(pBtc->pPage));

  if (pBtc->idx < TDB_PAGE_TOTAL_CELLS(pBtc->pPage)) {
    pCell = tdbPageGetCell(pBtc->pPage, pBtc->idx);
    pgno = ((SPgno *)pCell)[0];
  } else {
    pgno = ((SIntHdr *)pBtc->pPage->pData)->pgno;
  }
H
Hongze Cheng 已提交
1391

H
Hongze Cheng 已提交
1392 1393
  ASSERT(pgno);

H
Hongze Cheng 已提交
1394 1395 1396 1397 1398
  pBtc->pgStack[pBtc->iPage] = pBtc->pPage;
  pBtc->idxStack[pBtc->iPage] = pBtc->idx;
  pBtc->iPage++;
  pBtc->pPage = NULL;
  pBtc->idx = -1;
H
Hongze Cheng 已提交
1399

H
Hongze Cheng 已提交
1400 1401
  ret = tdbPagerFetchPage(pBtc->pBt->pPager, &pgno, &pBtc->pPage, tdbBtreeInitPage,
                          &((SBtreeInitPageArg){.pBt = pBtc->pBt, .flags = 0}), pBtc->pTxn);
H
Hongze Cheng 已提交
1402 1403
  if (ret < 0) {
    ASSERT(0);
H
Hongze Cheng 已提交
1404
    return -1;
H
Hongze Cheng 已提交
1405 1406 1407 1408 1409 1410
  }

  return 0;
}

static int tdbBtcMoveUpward(SBTC *pBtc) {
H
Hongze Cheng 已提交
1411 1412
  if (pBtc->iPage == 0) return -1;

H
Hongze Cheng 已提交
1413
  tdbPagerReturnPage(pBtc->pBt->pPager, pBtc->pPage, pBtc->pTxn);
H
Hongze Cheng 已提交
1414 1415 1416 1417 1418

  pBtc->iPage--;
  pBtc->pPage = pBtc->pgStack[pBtc->iPage];
  pBtc->idx = pBtc->idxStack[pBtc->iPage];

H
Hongze Cheng 已提交
1419
  return 0;
H
Hongze Cheng 已提交
1420
}
H
refact  
Hongze Cheng 已提交
1421

H
Hongze Cheng 已提交
1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438
int tdbBtcGet(SBTC *pBtc, const void **ppKey, int *kLen, const void **ppVal, int *vLen) {
  SCell *pCell;

  if (pBtc->idx < 0 || pBtc->idx >= TDB_PAGE_TOTAL_CELLS(pBtc->pPage)) {
    return -1;
  }

  pCell = tdbPageGetCell(pBtc->pPage, pBtc->idx);
  tdbBtreeDecodeCell(pBtc->pPage, pCell, &pBtc->coder);

  if (ppKey) {
    *ppKey = (void *)pBtc->coder.pKey;
    *kLen = pBtc->coder.kLen;
  }

  if (ppVal) {
    *ppVal = (void *)pBtc->coder.pVal;
H
Hongze Cheng 已提交
1439
    *vLen = pBtc->coder.vLen;
H
Hongze Cheng 已提交
1440 1441 1442 1443 1444
  }

  return 0;
}

H
Hongze Cheng 已提交
1445
int tdbBtcDelete(SBTC *pBtc) {
H
Hongze Cheng 已提交
1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463
  int         idx = pBtc->idx;
  int         nCells = TDB_PAGE_TOTAL_CELLS(pBtc->pPage);
  SPager     *pPager = pBtc->pBt->pPager;
  const void *pKey;
  i8          iPage;
  SPage      *pPage;
  SPgno       pgno;
  SCell      *pCell;
  int         szCell;
  int         nKey;
  int         ret;

  ASSERT(idx >= 0 && idx < nCells);

  // drop the cell on the leaf
  ret = tdbPagerWrite(pPager, pBtc->pPage);
  if (ret < 0) {
    ASSERT(0);
H
Hongze Cheng 已提交
1464 1465 1466 1467 1468
    return -1;
  }

  tdbPageDropCell(pBtc->pPage, idx);

H
Hongze Cheng 已提交
1469
  // update interior page or do balance
H
Hongze Cheng 已提交
1470
  if (idx == nCells - 1) {
H
Hongze Cheng 已提交
1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491
    if (idx) {
      pBtc->idx--;
      tdbBtcGet(pBtc, &pKey, &nKey, NULL, NULL);

      // loop to update the interial page
      pgno = TDB_PAGE_PGNO(pBtc->pPage);
      for (iPage = pBtc->iPage - 1; iPage >= 0; iPage--) {
        pPage = pBtc->pgStack[iPage];
        idx = pBtc->idxStack[iPage];
        nCells = TDB_PAGE_TOTAL_CELLS(pPage);

        if (idx < nCells) {
          ret = tdbPagerWrite(pPager, pPage);
          if (ret < 0) {
            ASSERT(0);
            return -1;
          }

          // update the cell with new key
          pCell = tdbOsMalloc(nKey + 9);
          tdbBtreeEncodeCell(pPage, pKey, nKey, &pgno, sizeof(pgno), pCell, &szCell);
H
Hongze Cheng 已提交
1492

H
Hongze Cheng 已提交
1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505
          ret = tdbPageUpdateCell(pPage, idx, pCell, szCell);
          if (ret < 0) {
            tdbOsFree(pCell);
            ASSERT(0);
            return -1;
          }
          tdbOsFree(pCell);
          break;
        } else {
          pgno = TDB_PAGE_PGNO(pPage);
        }
      }
    } else {
H
Hongze Cheng 已提交
1506
      // delete the leaf page and do balance
H
Hongze Cheng 已提交
1507
      ASSERT(TDB_PAGE_TOTAL_CELLS(pBtc->pPage) == 0);
H
Hongze Cheng 已提交
1508 1509 1510 1511 1512 1513

      ret = tdbBtreeBalance(pBtc);
      if (ret < 0) {
        ASSERT(0);
        return -1;
      }
H
Hongze Cheng 已提交
1514
    }
H
Hongze Cheng 已提交
1515 1516 1517 1518 1519
  }

  return 0;
}

H
Hongze Cheng 已提交
1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577
int tdbBtcUpsert(SBTC *pBtc, const void *pKey, int kLen, const void *pData, int nData, int insert) {
  SCell *pCell;
  int    szCell;
  int    nCells = TDB_PAGE_TOTAL_CELLS(pBtc->pPage);
  int    szBuf;
  void  *pBuf;
  int    ret;

  ASSERT(pBtc->idx >= 0);

  // alloc space
  szBuf = kLen + nData + 14;
  pBuf = tdbRealloc(pBtc->pBt->pBuf, pBtc->pBt->pageSize > szBuf ? szBuf : pBtc->pBt->pageSize);
  if (pBuf == NULL) {
    ASSERT(0);
    return -1;
  }
  pBtc->pBt->pBuf = pBuf;
  pCell = (SCell *)pBtc->pBt->pBuf;

  // encode cell
  ret = tdbBtreeEncodeCell(pBtc->pPage, pKey, kLen, pData, nData, pCell, &szCell);
  if (ret < 0) {
    ASSERT(0);
    return -1;
  }

  // mark dirty
  ret = tdbPagerWrite(pBtc->pBt->pPager, pBtc->pPage);
  if (ret < 0) {
    ASSERT(0);
    return -1;
  }

  // insert or update
  if (insert) {
    ASSERT(pBtc->idx <= nCells);

    ret = tdbPageInsertCell(pBtc->pPage, pBtc->idx, pCell, szCell, 0);
  } else {
    ASSERT(pBtc->idx < nCells);

    ret = tdbPageUpdateCell(pBtc->pPage, pBtc->idx, pCell, szCell);
  }
  if (ret < 0) {
    ASSERT(0);
    return -1;
  }

  // check balance
  if (pBtc->pPage->nOverflow > 0) {
    ret = tdbBtreeBalance(pBtc);
    if (ret < 0) {
      ASSERT(0);
      return -1;
    }
  }

H
Hongze Cheng 已提交
1578 1579 1580
  return 0;
}

H
Hongze Cheng 已提交
1581
int tdbBtcMoveTo(SBTC *pBtc, const void *pKey, int kLen, int *pCRst) {
H
Hongze Cheng 已提交
1582 1583 1584 1585 1586 1587 1588 1589
  int         ret;
  int         nCells;
  int         c;
  SCell      *pCell;
  SBTree     *pBt = pBtc->pBt;
  SPager     *pPager = pBt->pPager;
  const void *pTKey;
  int         tkLen;
H
Hongze Cheng 已提交
1590 1591

  if (pBtc->iPage < 0) {
H
Hongze Cheng 已提交
1592
    // move from a clear cursor
H
Hongze Cheng 已提交
1593 1594
    ret = tdbPagerFetchPage(pPager, &pBt->root, &(pBtc->pPage), tdbBtreeInitPage,
                            &((SBtreeInitPageArg){.pBt = pBt, .flags = TDB_BTREE_ROOT | TDB_BTREE_LEAF}), pBtc->pTxn);
H
Hongze Cheng 已提交
1595
    if (ret < 0) {
H
Hongze Cheng 已提交
1596
      // TODO
H
Hongze Cheng 已提交
1597
      ASSERT(0);
H
Hongze Cheng 已提交
1598
      return 0;
H
Hongze Cheng 已提交
1599 1600 1601
    }

    pBtc->iPage = 0;
H
Hongze Cheng 已提交
1602 1603 1604 1605
    pBtc->idx = -1;
    // for empty tree, just return with an invalid position
    if (TDB_PAGE_TOTAL_CELLS(pBtc->pPage) == 0) return 0;
  } else {
H
Hongze Cheng 已提交
1606 1607
    ASSERT(0);
#if 0
H
Hongze Cheng 已提交
1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641
    SPage *pPage;
    int    idx;
    int    iPage = 0;

    // downward search
    for (; iPage < pBtc->iPage; iPage++) {
      pPage = pBtc->pgStack[iPage];
      idx = pBtc->idxStack[iPage];
      nCells = TDB_PAGE_TOTAL_CELLS(pPage);

      ASSERT(!TDB_BTREE_PAGE_IS_LEAF(pPage));

      // check if key <= current position
      if (idx < nCells) {
        pCell = tdbPageGetCell(pPage, idx);
        tdbBtreeDecodeCell(pPage, pCell, &cd);
        c = pBt->kcmpr(pKey, kLen, cd.pKey, cd.kLen);
        if (c > 0) break;
      }

      // check if key > current - 1 position
      if (idx > 0) {
        pCell = tdbPageGetCell(pPage, idx - 1);
        tdbBtreeDecodeCell(pPage, pCell, &cd);
        c = pBt->kcmpr(pKey, kLen, cd.pKey, cd.kLen);
        if (c <= 0) break;
      }
    }

    // move upward
    for (;;) {
      if (pBtc->iPage == iPage) break;
      tdbBtcMoveUpward(pBtc);
    }
H
Hongze Cheng 已提交
1642
#endif
H
Hongze Cheng 已提交
1643
  }
H
Hongze Cheng 已提交
1644

H
Hongze Cheng 已提交
1645 1646
  // search downward to the leaf
  for (;;) {
H
Hongze Cheng 已提交
1647
    int    lidx, ridx;
H
Hongze Cheng 已提交
1648
    SPage *pPage;
H
Hongze Cheng 已提交
1649

H
Hongze Cheng 已提交
1650 1651 1652 1653
    pPage = pBtc->pPage;
    nCells = TDB_PAGE_TOTAL_CELLS(pPage);
    lidx = 0;
    ridx = nCells - 1;
H
Hongze Cheng 已提交
1654

H
Hongze Cheng 已提交
1655
    ASSERT(nCells > 0);
H
Hongze Cheng 已提交
1656

H
Hongze Cheng 已提交
1657
    // compare first cell
H
Hongze Cheng 已提交
1658 1659 1660
    pBtc->idx = lidx;
    tdbBtcGet(pBtc, &pTKey, &tkLen, NULL, NULL);
    c = pBt->kcmpr(pKey, kLen, pTKey, tkLen);
H
Hongze Cheng 已提交
1661 1662 1663 1664 1665 1666 1667 1668
    if (c <= 0) {
      ridx = lidx - 1;
    } else {
      lidx = lidx + 1;
    }

    // compare last cell
    if (lidx <= ridx) {
H
Hongze Cheng 已提交
1669 1670 1671
      pBtc->idx = ridx;
      tdbBtcGet(pBtc, &pTKey, &tkLen, NULL, NULL);
      c = pBt->kcmpr(pKey, kLen, pTKey, tkLen);
H
Hongze Cheng 已提交
1672 1673 1674 1675 1676 1677 1678
      if (c >= 0) {
        lidx = ridx + 1;
      } else {
        ridx = ridx - 1;
      }
    }

H
Hongze Cheng 已提交
1679 1680 1681
    // binary search
    for (;;) {
      if (lidx > ridx) break;
H
Hongze Cheng 已提交
1682

H
Hongze Cheng 已提交
1683 1684 1685
      pBtc->idx = (lidx + ridx) >> 1;
      tdbBtcGet(pBtc, &pTKey, &tkLen, NULL, NULL);
      c = pBt->kcmpr(pKey, kLen, pTKey, tkLen);
H
Hongze Cheng 已提交
1686 1687
      if (c < 0) {
        // pKey < cd.pKey
H
Hongze Cheng 已提交
1688
        ridx = pBtc->idx - 1;
H
Hongze Cheng 已提交
1689 1690
      } else if (c > 0) {
        // pKey > cd.pKey
H
Hongze Cheng 已提交
1691
        lidx = pBtc->idx + 1;
H
Hongze Cheng 已提交
1692 1693 1694
      } else {
        // pKey == cd.pKey
        break;
H
Hongze Cheng 已提交
1695
      }
H
Hongze Cheng 已提交
1696
    }
H
Hongze Cheng 已提交
1697

H
Hongze Cheng 已提交
1698 1699 1700 1701 1702
    // keep search downward or break
    if (TDB_BTREE_PAGE_IS_LEAF(pPage)) {
      *pCRst = c;
      break;
    } else {
H
Hongze Cheng 已提交
1703 1704
      if (c > 0) {
        pBtc->idx += 1;
H
Hongze Cheng 已提交
1705
      }
H
Hongze Cheng 已提交
1706
      tdbBtcMoveDownward(pBtc);
H
Hongze Cheng 已提交
1707 1708 1709 1710 1711 1712
    }
  }

  return 0;
}

H
refact  
Hongze Cheng 已提交
1713 1714 1715 1716 1717 1718
int tdbBtcClose(SBTC *pBtc) {
  if (pBtc->iPage < 0) return 0;

  for (;;) {
    ASSERT(pBtc->pPage);

H
Hongze Cheng 已提交
1719
    tdbPagerReturnPage(pBtc->pBt->pPager, pBtc->pPage, pBtc->pTxn);
H
refact  
Hongze Cheng 已提交
1720 1721 1722 1723 1724 1725 1726 1727 1728 1729

    pBtc->iPage--;
    if (pBtc->iPage < 0) break;

    pBtc->pPage = pBtc->pgStack[pBtc->iPage];
    pBtc->idx = pBtc->idxStack[pBtc->iPage];
  }

  return 0;
}
H
Hongze Cheng 已提交
1730 1731 1732 1733 1734 1735 1736 1737

int tdbBtcIsValid(SBTC *pBtc) {
  if (pBtc->idx < 0) {
    return 0;
  } else {
    return 1;
  }
}
H
refact  
Hongze Cheng 已提交
1738
// TDB_BTREE_CURSOR
H
Hongze Cheng 已提交
1739

H
refact  
Hongze Cheng 已提交
1740
// TDB_BTREE_DEBUG =====================
H
Hongze Cheng 已提交
1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759
#ifndef NODEBUG
typedef struct {
  SPgno pgno;
  u8    root;
  u8    leaf;
  SPgno rChild;
  int   nCells;
  int   nOvfl;
} SBtPageInfo;

SBtPageInfo btPageInfos[20];

void tdbBtPageInfo(SPage *pPage, int idx) {
  SBtPageInfo *pBtPageInfo;

  pBtPageInfo = btPageInfos + idx;

  pBtPageInfo->pgno = TDB_PAGE_PGNO(pPage);

H
refact  
Hongze Cheng 已提交
1760 1761
  pBtPageInfo->root = TDB_BTREE_PAGE_IS_ROOT(pPage);
  pBtPageInfo->leaf = TDB_BTREE_PAGE_IS_LEAF(pPage);
H
Hongze Cheng 已提交
1762 1763 1764 1765 1766 1767 1768 1769 1770

  pBtPageInfo->rChild = 0;
  if (!pBtPageInfo->leaf) {
    pBtPageInfo->rChild = *(SPgno *)(pPage->pData + 1);
  }

  pBtPageInfo->nCells = TDB_PAGE_TOTAL_CELLS(pPage) - pPage->nOverflow;
  pBtPageInfo->nOvfl = pPage->nOverflow;
}
H
refact  
Hongze Cheng 已提交
1771
#endif
H
Hongze Cheng 已提交
1772
// TDB_BTREE_DEBUG