-
Notifications
You must be signed in to change notification settings - Fork 69
/
Copy pathb_plus_tree.cpp
611 lines (581 loc) · 23.2 KB
/
b_plus_tree.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
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
143
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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
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
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
/**
* b_plus_tree.cpp
*/
#include <iostream>
#include <string>
#include "common/exception.h"
#include "common/logger.h"
#include "common/rid.h"
#include "index/b_plus_tree.h"
#include "page/header_page.h"
namespace cmudb {
INDEX_TEMPLATE_ARGUMENTS
BPLUSTREE_TYPE::BPlusTree(const std::string &name,
BufferPoolManager *buffer_pool_manager,
const KeyComparator &comparator,
page_id_t root_page_id)
: index_name_(name), root_page_id_(root_page_id),
buffer_pool_manager_(buffer_pool_manager), comparator_(comparator) {}
/*
* Helper function to decide whether current b+tree is empty
*/
INDEX_TEMPLATE_ARGUMENTS
bool BPLUSTREE_TYPE::IsEmpty() const { return root_page_id_ == INVALID_PAGE_ID; }
/*****************************************************************************
* SEARCH
*****************************************************************************/
/*
* Return the only value that associated with input key
* This method is used for point query
* @return : true means key exists
*/
INDEX_TEMPLATE_ARGUMENTS
bool BPLUSTREE_TYPE::GetValue(const KeyType &key,
std::vector<ValueType> &result,
Transaction *transaction) {
//step 1. find page
B_PLUS_TREE_LEAF_PAGE_TYPE *tar = FindLeafPage(key);
if (tar == nullptr)
return false;
//step 2. find value
result.resize(1);
auto ret = tar->Lookup(key,result[0],comparator_);
//step 3. unPin buffer pool
buffer_pool_manager_->UnpinPage(tar->GetPageId(), false);
assert(buffer_pool_manager_->CheckAllUnpined());
return ret;
}
/*****************************************************************************
* INSERTION
*****************************************************************************/
/*
* Insert constant key & value pair into b+ tree
* if current tree is empty, start new tree, update root page id and insert
* entry, otherwise insert into leaf page.
* @return: since we only support unique key, if user try to insert duplicate
* keys return false, otherwise return true.
*/
INDEX_TEMPLATE_ARGUMENTS
bool BPLUSTREE_TYPE::Insert(const KeyType &key, const ValueType &value,
Transaction *transaction) {
if (IsEmpty()) {
StartNewTree(key,value);
return true;
}
bool res = InsertIntoLeaf(key,value,transaction);
assert(Check());
return res;
}
/*
* Insert constant key & value pair into an empty tree
* User needs to first ask for new page from buffer pool manager(NOTICE: throw
* an "out of memory" exception if returned value is nullptr), then update b+
* tree's root page id and insert entry directly into leaf page.
*/
INDEX_TEMPLATE_ARGUMENTS
void BPLUSTREE_TYPE::StartNewTree(const KeyType &key, const ValueType &value) {
//step 1. ask for new page from buffer pool manager
page_id_t newPageId;
Page *rootPage = buffer_pool_manager_->NewPage(newPageId);
assert(rootPage != nullptr);
B_PLUS_TREE_LEAF_PAGE_TYPE *root = reinterpret_cast<B_PLUS_TREE_LEAF_PAGE_TYPE *>(rootPage->GetData());
//step 2. update b+ tree's root page id
root->Init(newPageId,INVALID_PAGE_ID);
root_page_id_ = newPageId;
UpdateRootPageId(true);
//step 3. insert entry directly into leaf page.
root->Insert(key,value,comparator_);
buffer_pool_manager_->UnpinPage(newPageId,true);
}
/*
* Insert constant key & value pair into leaf page
* User needs to first find the right leaf page as insertion target, then look
* through leaf page to see whether insert key exist or not. If exist, return
* immdiately, otherwise insert entry. Remember to deal with split if necessary.
* @return: since we only support unique key, if user try to insert duplicate
* keys return false, otherwise return true.
*/
INDEX_TEMPLATE_ARGUMENTS
bool BPLUSTREE_TYPE::InsertIntoLeaf(const KeyType &key, const ValueType &value,
Transaction *transaction) {
B_PLUS_TREE_LEAF_PAGE_TYPE *leafPage = FindLeafPage(key);
ValueType v;
bool exist = leafPage->Lookup(key,v,comparator_);
if (exist) {
buffer_pool_manager_->UnpinPage(leafPage->GetPageId(), false);
return false;
}
leafPage->Insert(key,value,comparator_);
if (leafPage->GetSize() > leafPage->GetMaxSize()) {//insert then split
B_PLUS_TREE_LEAF_PAGE_TYPE *newLeafPage = Split(leafPage);//unpin it in below func
InsertIntoParent(leafPage,newLeafPage->KeyAt(0),newLeafPage,transaction);
}
buffer_pool_manager_->UnpinPage(leafPage->GetPageId(), true);
return true;
}
/*
* Split input page and return newly created page.
* Using template N to represent either internal page or leaf page.
* User needs to first ask for new page from buffer pool manager(NOTICE: throw
* an "out of memory" exception if returned value is nullptr), then move half
* of key & value pairs from input page to newly created page
*/
INDEX_TEMPLATE_ARGUMENTS
template <typename N> N *BPLUSTREE_TYPE::Split(N *node) {
//step 1 ask for new page from buffer pool manager
page_id_t newPageId;
Page* const newPage = buffer_pool_manager_->NewPage(newPageId);
assert(newPage != nullptr);
//step 2 move half of key & value pairs from input page to newly created page
N *newNode = reinterpret_cast<N *>(newPage->GetData());
newNode->Init(newPageId, node->GetParentPageId());
node->MoveHalfTo(newNode, buffer_pool_manager_);
//fetch page and new page need to unpin page(do it outside)
return newNode;
}
/*
* Insert key & value pair into internal page after split
* @param old_node input page from split() method
* @param key
* @param new_node returned page from split() method
* User needs to first find the parent page of old_node, parent node must be
* adjusted to take info of new_node into account. Remember to deal with split
* recursively if necessary.
*/
INDEX_TEMPLATE_ARGUMENTS
void BPLUSTREE_TYPE::InsertIntoParent(BPlusTreePage *old_node,
const KeyType &key,
BPlusTreePage *new_node,
Transaction *transaction) {
if (old_node->IsRootPage()) {
Page* const newPage = buffer_pool_manager_->NewPage(root_page_id_);
assert(newPage != nullptr);
assert(newPage->GetPinCount() == 1);
B_PLUS_TREE_INTERNAL_PAGE *newRoot = reinterpret_cast<B_PLUS_TREE_INTERNAL_PAGE *>(newPage->GetData());
newRoot->Init(root_page_id_);
newRoot->PopulateNewRoot(old_node->GetPageId(),key,new_node->GetPageId());
old_node->SetParentPageId(root_page_id_);
new_node->SetParentPageId(root_page_id_);
UpdateRootPageId();
//fetch page and new page need to unpin page
buffer_pool_manager_->UnpinPage(new_node->GetPageId(),true);
buffer_pool_manager_->UnpinPage(newRoot->GetPageId(),true);
return;
}
page_id_t parentId = old_node->GetParentPageId();
auto *page = FetchPage(parentId);
assert(page != nullptr);
B_PLUS_TREE_INTERNAL_PAGE *parent = reinterpret_cast<B_PLUS_TREE_INTERNAL_PAGE *>(page);
new_node->SetParentPageId(parentId);
buffer_pool_manager_->UnpinPage(new_node->GetPageId(),true);
//insert new node after old node
parent->InsertNodeAfter(old_node->GetPageId(), key, new_node->GetPageId());
if (parent->GetSize() > parent->GetMaxSize()) {
//begin /* Split Parent */
B_PLUS_TREE_INTERNAL_PAGE *newLeafPage = Split(parent);//new page need unpin
InsertIntoParent(parent,newLeafPage->KeyAt(0),newLeafPage,transaction);
}
buffer_pool_manager_->UnpinPage(parentId,true);
}
/*****************************************************************************
* REMOVE
*****************************************************************************/
/*
* Delete key & value pair associated with input key
* If current tree is empty, return immdiately.
* If not, User needs to first find the right leaf page as deletion target, then
* delete entry from leaf page. Remember to deal with redistribute or merge if
* necessary.
*/
INDEX_TEMPLATE_ARGUMENTS
void BPLUSTREE_TYPE::Remove(const KeyType &key, Transaction *transaction) {
if (IsEmpty()) return;
B_PLUS_TREE_LEAF_PAGE_TYPE *delTar = FindLeafPage(key);
int curSize = delTar->RemoveAndDeleteRecord(key,comparator_);
if (curSize < delTar->GetMinSize()) {
CoalesceOrRedistribute(delTar,transaction);
}
buffer_pool_manager_->UnpinPage(delTar->GetPageId(),true);
assert(Check());
}
/*
* User needs to first find the sibling of input page. If sibling's size + input
* page's size > page's max size, then redistribute. Otherwise, merge.
* Using template N to represent either internal page or leaf page.
* @return: true means target leaf page should be deleted, false means no
* deletion happens
*/
INDEX_TEMPLATE_ARGUMENTS
template <typename N>
bool BPLUSTREE_TYPE::CoalesceOrRedistribute(N *node, Transaction *transaction) {
//if (N is the root and N has only one remaining child)
if (node->IsRootPage()) {
return AdjustRoot(node);//make the child of N the new root of the tree and delete N
}
//Let N2 be the previous or next child of parent(N)
N *node2;
bool nPrevN2 = FindSibling(node,node2);
BPlusTreePage *parent = FetchPage(node->GetParentPageId());
B_PLUS_TREE_INTERNAL_PAGE *parentPage = static_cast<B_PLUS_TREE_INTERNAL_PAGE *>(parent);
//if (entries in N and N2 can fit in a single node)
if (node->GetSize() + node2->GetSize() <= node->GetMaxSize()) {
if (nPrevN2) {swap(node,node2);} //assumption node is after node2
int removeIndex = parentPage->ValueIndex(node->GetPageId());
Coalesce(node2,node,parentPage,removeIndex,transaction);//unpin node,node2
buffer_pool_manager_->UnpinPage(parentPage->GetPageId(), true);
return true;
}
/* Redistribution: borrow an entry from N2 */
int nodeInParentIndex = parentPage->ValueIndex(node->GetPageId());
Redistribute(node2,node,nodeInParentIndex);//unpin node,node2
buffer_pool_manager_->UnpinPage(parentPage->GetPageId(), false);
return false;
}
INDEX_TEMPLATE_ARGUMENTS
template <typename N>
bool BPLUSTREE_TYPE::FindSibling(N *node, N * &sibling) {
auto page = FetchPage(node->GetParentPageId());
B_PLUS_TREE_INTERNAL_PAGE *parent = reinterpret_cast<B_PLUS_TREE_INTERNAL_PAGE *>(page);
int index = parent->ValueIndex(node->GetPageId());
int siblingIndex = index - 1;
if (index == 0) { //no prev sibling
siblingIndex = index + 1;
}
sibling = reinterpret_cast<N *>(FetchPage(parent->ValueAt(siblingIndex)));
buffer_pool_manager_->UnpinPage(parent->GetPageId(), false);
return index == 0;//index == 0 means sibling is post node
}
/*
* Move all the key & value pairs from one page to its sibling page, and notify
* buffer pool manager to delete this page. Parent page must be adjusted to
* take info of deletion into account. Remember to deal with coalesce or
* redistribute recursively if necessary.
* Using template N to represent either internal page or leaf page.
* @param neighbor_node sibling page of input "node"
* @param node input from method coalesceOrRedistribute()
* @param parent parent page of input "node"
* @return true means parent node should be deleted, false means no deletion
* happend
*/
INDEX_TEMPLATE_ARGUMENTS
template <typename N>
bool BPLUSTREE_TYPE::Coalesce(
N *&neighbor_node, N *&node,
BPlusTreeInternalPage<KeyType, page_id_t, KeyComparator> *&parent,
int index, Transaction *transaction) {
//assumption neighbor_node is before node
assert(node->GetSize() + neighbor_node->GetSize() <= node->GetMaxSize());
//move later one to previous one
node->MoveAllTo(neighbor_node,index,buffer_pool_manager_);
page_id_t pId = node->GetPageId();
buffer_pool_manager_->UnpinPage(pId,true);
buffer_pool_manager_->DeletePage(pId);
buffer_pool_manager_->UnpinPage(neighbor_node->GetPageId(),true);
parent->Remove(index);
if (parent->GetSize() <= parent->GetMinSize()) {
return CoalesceOrRedistribute(parent,transaction);
}
return false;
}
/*
* Redistribute key & value pairs from one page to its sibling page. If index ==
* 0, move sibling page's first key & value pair into end of input "node",
* otherwise move sibling page's last key & value pair into head of input
* "node".
* Using template N to represent either internal page or leaf page.
* @param neighbor_node sibling page of input "node"
* @param node input from method coalesceOrRedistribute()
*/
INDEX_TEMPLATE_ARGUMENTS
template <typename N>
void BPLUSTREE_TYPE::Redistribute(N *neighbor_node, N *node, int index) {
if (index == 0) {
neighbor_node->MoveFirstToEndOf(node,buffer_pool_manager_);
} else {
neighbor_node->MoveLastToFrontOf(node, index, buffer_pool_manager_);
}
buffer_pool_manager_->UnpinPage(node->GetPageId(), true);
buffer_pool_manager_->UnpinPage(neighbor_node->GetPageId(), true);
}
/*
* Update root page if necessary
* NOTE: size of root page can be less than min size and this method is only
* called within coalesceOrRedistribute() method
* case 1: when you delete the last element in root page, but root page still
* has one last child
* case 2: when you delete the last element in whole b+ tree
* @return : true means root page should be deleted, false means no deletion
* happend
*/
INDEX_TEMPLATE_ARGUMENTS
bool BPLUSTREE_TYPE::AdjustRoot(BPlusTreePage *old_root_node) {
if (old_root_node->IsLeafPage()) {// case 2
assert(old_root_node->GetSize() == 0);
assert (old_root_node->GetParentPageId() == INVALID_PAGE_ID);
buffer_pool_manager_->UnpinPage(old_root_node->GetPageId(), false);
buffer_pool_manager_->DeletePage(old_root_node->GetPageId());
root_page_id_ = INVALID_PAGE_ID;
UpdateRootPageId();
return true;
}
if (old_root_node->GetSize() == 1) {// case 1
B_PLUS_TREE_INTERNAL_PAGE *root = reinterpret_cast<B_PLUS_TREE_INTERNAL_PAGE *>(old_root_node);
const page_id_t newRootId = root->RemoveAndReturnOnlyChild();
root_page_id_ = newRootId;
UpdateRootPageId();
// set the new root's parent id "INVALID_PAGE_ID"
Page *page = buffer_pool_manager_->FetchPage(root_page_id_);
assert(page != nullptr);
B_PLUS_TREE_INTERNAL_PAGE *newRoot =
reinterpret_cast<B_PLUS_TREE_INTERNAL_PAGE *>(page->GetData());
newRoot->SetParentPageId(INVALID_PAGE_ID);
buffer_pool_manager_->UnpinPage(root_page_id_, true);
buffer_pool_manager_->UnpinPage(old_root_node->GetPageId(), false);
buffer_pool_manager_->DeletePage(old_root_node->GetPageId());
}
return false;
}
/*****************************************************************************
* INDEX ITERATOR
*****************************************************************************/
/*
* Input parameter is void, find the leaftmost leaf page first, then construct
* index iterator
* @return : index iterator
*/
INDEX_TEMPLATE_ARGUMENTS
INDEXITERATOR_TYPE BPLUSTREE_TYPE::Begin() {
KeyType useless;
auto start_leaf = FindLeafPage(useless, true);
return INDEXITERATOR_TYPE(start_leaf, 0, buffer_pool_manager_);
}
/*
* Input parameter is low key, find the leaf page that contains the input key
* first, then construct index iterator
* @return : index iterator
*/
INDEX_TEMPLATE_ARGUMENTS
INDEXITERATOR_TYPE BPLUSTREE_TYPE::Begin(const KeyType &key) {
auto start_leaf = FindLeafPage(key);
if (start_leaf == nullptr) {
return INDEXITERATOR_TYPE(start_leaf, 0, buffer_pool_manager_);
}
int idx = start_leaf->KeyIndex(key,comparator_);
return INDEXITERATOR_TYPE(start_leaf, idx, buffer_pool_manager_);
}
/*****************************************************************************
* UTILITIES AND DEBUG
*****************************************************************************/
/*
* Find leaf page containing particular key, if leftMost flag == true, find
* the left most leaf page
*/
INDEX_TEMPLATE_ARGUMENTS
B_PLUS_TREE_LEAF_PAGE_TYPE *BPLUSTREE_TYPE::FindLeafPage(const KeyType &key,
bool leftMost) {
if (IsEmpty()) return nullptr;
//, you need to first fetch the page from buffer pool using its unique page_id, then reinterpret cast to either
// a leaf or an internal page, and unpin the page after any writing or reading operations.
auto pointer = FetchPage(root_page_id_);
page_id_t next;
for (page_id_t cur = root_page_id_; !pointer->IsLeafPage(); cur = next,pointer = FetchPage(cur)) {
B_PLUS_TREE_INTERNAL_PAGE *internalPage = static_cast<B_PLUS_TREE_INTERNAL_PAGE *>(pointer);
if (leftMost) {
next = internalPage->ValueAt(0);
}else {
next = internalPage->Lookup(key,comparator_);
}
buffer_pool_manager_->UnpinPage(cur,false);
}
return static_cast<B_PLUS_TREE_LEAF_PAGE_TYPE *>(pointer);
}
INDEX_TEMPLATE_ARGUMENTS
BPlusTreePage *BPLUSTREE_TYPE::FetchPage(page_id_t page_id) {
auto page = buffer_pool_manager_->FetchPage(page_id);
return reinterpret_cast<BPlusTreePage *>(page->GetData());
}
/*
* Update/Insert root page id in header page(where page_id = 0, header_page is
* defined under include/page/header_page.h)
* Call this method everytime root page id is changed.
* @parameter: insert_record defualt value is false. When set to true,
* insert a record <index_name, root_page_id> into header page instead of
* updating it.
*/
INDEX_TEMPLATE_ARGUMENTS
void BPLUSTREE_TYPE::UpdateRootPageId(int insert_record) {
HeaderPage *header_page = static_cast<HeaderPage *>(
buffer_pool_manager_->FetchPage(HEADER_PAGE_ID));
if (insert_record)
// create a new record<index_name + root_page_id> in header_page
header_page->InsertRecord(index_name_, root_page_id_);
else
// update root_page_id in header_page
header_page->UpdateRecord(index_name_, root_page_id_);
buffer_pool_manager_->UnpinPage(HEADER_PAGE_ID, true);
}
/*
* This method is used for debug only
* print out whole b+tree sturcture, rank by rank
*/
INDEX_TEMPLATE_ARGUMENTS
std::string BPLUSTREE_TYPE::ToString(bool verbose) {
if (IsEmpty()) {
return "Empty tree";
}
std::queue<BPlusTreePage *> todo, tmp;
std::stringstream tree;
auto node = reinterpret_cast<BPlusTreePage *>(
buffer_pool_manager_->FetchPage(root_page_id_));
if (node == nullptr) {
throw Exception(EXCEPTION_TYPE_INDEX,
"all page are pinned while printing");
}
todo.push(node);
bool first = true;
while (!todo.empty()) {
node = todo.front();
if (first) {
first = false;
tree << "| ";
}
// leaf page, print all key-value pairs
if (node->IsLeafPage()) {
auto page = reinterpret_cast<BPlusTreeLeafPage<KeyType, ValueType, KeyComparator> *>(node);
tree << page->ToString(verbose) <<"("<<node->GetPageId()<< ")| ";
} else {
auto page = reinterpret_cast<BPlusTreeInternalPage<KeyType, page_id_t, KeyComparator> *>(node);
tree << page->ToString(verbose) <<"("<<node->GetPageId()<< ")| ";
page->QueueUpChildren(&tmp, buffer_pool_manager_);
}
todo.pop();
if (todo.empty() && !tmp.empty()) {
todo.swap(tmp);
tree << '\n';
first = true;
}
// unpin node when we are done
buffer_pool_manager_->UnpinPage(node->GetPageId(), false);
}
return tree.str();
}
/*
* This method is used for test only
* Read data from file and insert one by one
*/
INDEX_TEMPLATE_ARGUMENTS
void BPLUSTREE_TYPE::InsertFromFile(const std::string &file_name,
Transaction *transaction) {
int64_t key;
std::ifstream input(file_name);
while (input) {
input >> key;
KeyType index_key;
index_key.SetFromInteger(key);
RID rid(key);
Insert(index_key, rid, transaction);
}
}
/*
* This method is used for test only
* Read data from file and remove one by one
*/
INDEX_TEMPLATE_ARGUMENTS
void BPLUSTREE_TYPE::RemoveFromFile(const std::string &file_name,
Transaction *transaction) {
int64_t key;
std::ifstream input(file_name);
while (input) {
input >> key;
KeyType index_key;
index_key.SetFromInteger(key);
Remove(index_key, transaction);
}
}
/***************************************************************************
* Check integrity of B+ tree data structure.
***************************************************************************/
INDEX_TEMPLATE_ARGUMENTS
int BPLUSTREE_TYPE::isBalanced(page_id_t pid) {
if (IsEmpty()) return true;
auto node = reinterpret_cast<BPlusTreePage *>(buffer_pool_manager_->FetchPage(pid));
if (node == nullptr) {
throw Exception(EXCEPTION_TYPE_INDEX,"all page are pinned while isBalanced");
}
int ret = 0;
if (!node->IsLeafPage()) {
auto page = reinterpret_cast<B_PLUS_TREE_INTERNAL_PAGE *>(node);
int last = -2;
for (int i = 0; i < page->GetSize(); i++) {
int cur = isBalanced(page->ValueAt(i));
if (cur >= 0 && last == -2) {
last = cur;
ret = last + 1;
}else if (last != cur) {
ret = -1;
break;
}
}
}
buffer_pool_manager_->UnpinPage(pid,false);
return ret;
}
INDEX_TEMPLATE_ARGUMENTS
bool BPLUSTREE_TYPE::isPageCorr(page_id_t pid,pair<KeyType,KeyType> &out) {
if (IsEmpty()) return true;
auto node = reinterpret_cast<BPlusTreePage *>(buffer_pool_manager_->FetchPage(pid));
if (node == nullptr) {
throw Exception(EXCEPTION_TYPE_INDEX,"all page are pinned while isPageCorr");
}
bool ret = true;
if (node->IsLeafPage()) {
auto page = reinterpret_cast<BPlusTreeLeafPage<KeyType, ValueType, KeyComparator> *>(node);
int size = page->GetSize();
ret = ret && (size >= node->GetMinSize() && size <= node->GetMaxSize());
for (int i = 1; i < size; i++) {
if (comparator_(page->KeyAt(i-1), page->KeyAt(i)) > 0) {
ret = false;
break;
}
}
out = pair<KeyType,KeyType>{page->KeyAt(0),page->KeyAt(size-1)};
} else {
auto page = reinterpret_cast<BPlusTreeInternalPage<KeyType, page_id_t, KeyComparator> *>(node);
int size = page->GetSize();
ret = ret && (size >= node->GetMinSize() && size <= node->GetMaxSize());
pair<KeyType,KeyType> left,right;
for (int i = 1; i < size; i++) {
if (i == 1) {
ret = ret && isPageCorr(page->ValueAt(0),left);
}
ret = ret && isPageCorr(page->ValueAt(i),right);
ret = ret && (comparator_(page->KeyAt(i) ,left.second)>0 && comparator_(page->KeyAt(i), right.first)<=0);
ret = ret && (i == 1 || comparator_(page->KeyAt(i-1) , page->KeyAt(i)) < 0);
if (!ret) break;
left = right;
}
out = pair<KeyType,KeyType>{page->KeyAt(0),page->KeyAt(size-1)};
}
buffer_pool_manager_->UnpinPage(pid,false);
return ret;
}
INDEX_TEMPLATE_ARGUMENTS
bool BPLUSTREE_TYPE::Check(bool forceCheck) {
if (!forceCheck && !openCheck) {
return true;
}
pair<KeyType,KeyType> in;
bool isPageInOrderAndSizeCorr = isPageCorr(root_page_id_, in);
bool isBal = (isBalanced(root_page_id_) >= 0);
bool isAllUnpin = buffer_pool_manager_->CheckAllUnpined();
if (!isPageInOrderAndSizeCorr) cout<<"problem in page order or page size"<<endl;
if (!isBal) cout<<"problem in balance"<<endl;
if (!isAllUnpin) cout<<"problem in page unpin"<<endl;
return isPageInOrderAndSizeCorr && isBal && isAllUnpin;
}
template class BPlusTree<GenericKey<4>, RID, GenericComparator<4>>;
template class BPlusTree<GenericKey<8>, RID, GenericComparator<8>>;
template class BPlusTree<GenericKey<16>, RID, GenericComparator<16>>;
template class BPlusTree<GenericKey<32>, RID, GenericComparator<32>>;
template class BPlusTree<GenericKey<64>, RID, GenericComparator<64>>;
} // namespace cmudb