This repository has been archived by the owner on Sep 4, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bptree.cpp
1188 lines (952 loc) · 45.4 KB
/
bptree.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
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
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
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
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <tuple>
#include <iostream>
#include <array>
#include <unordered_map>
#include <cstring>
#include <math.h>
#include "storage.cpp"
#include "types.h"
using namespace std;
// A node in the B+ Tree.
class BPNode{
public:
Address* ptrToNode; // A pointer to an array of struct {void *blockAddress, short int offset} containing other nodes in storage.
int numOfKeys; // Total number of keys in the current node
int* ptrToKeys; // A node contains number of keys, this parameter pointer to the address of every key
bool isLeafNode; // If current node is a leaf node.
BPNode(int _maxNumOfKey){
// Initialize arrya of pointer to keys and pointer to Node
ptrToKeys = new int[_maxNumOfKey];
ptrToNode = new Address[_maxNumOfKey + 1];
// Initialize every single key to null and offset to 0
for (int i = 0; i < _maxNumOfKey + 1; i++) {
Address nullAddress;
nullAddress.blockAddress = nullptr;
nullAddress.offset = 0;
ptrToNode[i] = nullAddress;
if(i < _maxNumOfKey) {
ptrToKeys[i] = 0;
}
}
numOfKeys = 0;
}
// Get the total number of keys
int getCountOfKeys(){
return numOfKeys;
}
};
// The B+ Tree itself.
class BPlusTree {
private:
// Variables in a B+ tree
DiskStorage* _storage; // Pointer to a memory pool for data blocks.
BPNode* _rootNode; // Pointer to the main memory _rootNode (if it's loaded).
Address _rootAddressOfStorage; // Ppointer to the root address(disk)
int _maxNumOfKey; // Maximum keys defined in a node.
int _numOfNodes; // B+ tree total number of nodes
int _levelOfTrees; // B+ tree level
size_t _sizeOfNode; // Node size in B+ tree equivalent to block size in data file , 200kB in this project
// Updates the parent node to point at both child nodes, and adds a parent node if needed.
void addInternalNode(int keyID, Address parentNodeAddress, Address newLeafNodeAddress) {
// Create a root node and temp ptr which pointing to parent node, to load the copy of data from disk storage
BPNode* _rootNode = nullptr;
BPNode* tempPtr = (BPNode*) parentNodeAddress.blockAddress;
// Check if parent node is root node, if yes then update root node pointing to parent node
if (parentNodeAddress.blockAddress == _rootAddressOfStorage.blockAddress) {
_rootNode = (BPNode*) parentNodeAddress.blockAddress;
}
// If parent node stil not full yet, can directly insertRecord new child node and iterate through all keys in the node to sort the keys
// and update the pointer pointing to child node
if (tempPtr->numOfKeys < _maxNumOfKey) {
int i = 0;
// If current key ID larger than parent node key, then move to next key of parent node
// and use i to store this loaction
while (keyID > tempPtr->ptrToKeys[i] && i < tempPtr->numOfKeys) {
i++;
}
// From above step find out the location to insertRecord new keys , and use bubble sort to sort the order
for (int j = tempPtr->numOfKeys; j > i; j--) {
tempPtr->ptrToKeys[j] = tempPtr->ptrToKeys[j - 1];
}
// Move parent node pointer one step right pointing to lower bound of a key
for (int j = tempPtr->numOfKeys + 1; j > i + 1; j--) {
tempPtr->ptrToNode[j] = tempPtr->ptrToNode[j - 1];
}
tempPtr->ptrToKeys[i] = keyID; // Add in new child and pointing to its upper level parent node
tempPtr->numOfKeys++; // Update parent total number of keys
tempPtr->ptrToNode[i + 1] = newLeafNodeAddress; // Next key of newly added child pointing to new lead node
}
// If parent node no more space for new key , then need to split parent node and insertRecord new parent node
// right behind the previous parent node
else {
BPNode* newInternalNode = new BPNode(_maxNumOfKey); // Create new internal node, since parent node full
_numOfNodes++; // Update total number of nodes
// Same logic as above, keep a temp list of ptrToKeys and ptrToNode to insertRecord into the split nodes.
// Now, we have one extra pointer to keep track of (new child's pointer).
// Create a temp key list array and address pointers to keep track of newly added nodes
int tempKeyList[_maxNumOfKey + 1];
Address tempPointerList[_maxNumOfKey + 2];
// Copy over all the parent node keys data into temp list array
for (int i = 0; i < _maxNumOfKey; i++) {
tempKeyList[i] = tempPtr->ptrToKeys[i];
}
// Copy over all the parent node pointer data into temp list array
for (int i = 0; i < _maxNumOfKey + 1; i++) {
tempPointerList[i] = tempPtr->ptrToNode[i];
}
// Find out the location to insertRecord new key into temp key list
int i = 0;
while (keyID > tempKeyList[i] && i < _maxNumOfKey) {
i++;
}
// Swap the key which is higher than the location we find out from last step to with its left side key
// to make one space for new key
for (int j = _maxNumOfKey; j > i; j--) {
tempKeyList[j] = tempKeyList[j - 1];
}
// Move pointer one step left since above keys move back also, to keep track
for (int j = _maxNumOfKey + 1; j > i + 1; j--) {
tempPointerList[j] = tempPointerList[j - 1];
}
tempKeyList[i] = keyID; // New key has been inserted into temp list
tempPointerList[i + 1] = newLeafNodeAddress; // Pointer address updated
newInternalNode->isLeafNode = false; // update new internal node if leaf node
// Split node into two new node
tempPtr->numOfKeys = ceil((_maxNumOfKey + 1) / 2.0);
newInternalNode->numOfKeys = floor((_maxNumOfKey + 1) / 2.0) - 1;
// Update data from temp list array back to parent node
for (int i = 0; i < tempPtr->numOfKeys; i++) {
tempPtr->ptrToKeys[i] = tempKeyList[i];
}
for(int i = 0; i < tempPtr->numOfKeys + 1; i++){
tempPtr->ptrToNode[i] = tempPointerList[i];
}
// Update data from temp list array back to newly added internal node
int j;
for (int i = 0, j = tempPtr->numOfKeys + 1; i < newInternalNode->numOfKeys; i++, j++) {
newInternalNode->ptrToKeys[i] = tempKeyList[j];
}
for (int i = 0, j = tempPtr->numOfKeys + 1; i < newInternalNode->numOfKeys + 1; i++, j++) {
//cout << "Adding to newInternalNode->ptrToNode[" << i << "]: " << static_cast<void*>(tempPointerList[j].blockAddress) + tempPointerList[j].offset << endl;
newInternalNode->ptrToNode[i] = tempPointerList[j];
}
// To handle the situation when the number of parent key larger than max number of key allowed, set extra key value
// to 0 and address to nullptr
for (int i = tempPtr->numOfKeys; i < _maxNumOfKey; i++) {
tempPtr->ptrToKeys[i] = 0;
}
for (int i = tempPtr->numOfKeys + 1; i < _maxNumOfKey + 1; i++) {
Address nullAddress;
nullAddress.offset = 0;
nullAddress.blockAddress = nullptr;
tempPtr->ptrToNode[i] = nullAddress;
}
// Update current internal node pointer address
Address newInternalNodeAddress;
newInternalNodeAddress.blockAddress = newInternalNode;
newInternalNodeAddress.offset = 0;
// Check whether parent node and root node is same, if yes then create a new root node
if (tempPtr == _rootNode) {
BPNode* newRoot = new BPNode(_maxNumOfKey);
_numOfNodes++;
// Link the new root with parent node and new interal node address
newRoot->ptrToKeys[0] = tempKeyList[tempPtr->numOfKeys];
newRoot->ptrToNode[0] = parentNodeAddress;
newRoot->ptrToNode[1] = newInternalNodeAddress;
// Update new root variables
newRoot->isLeafNode = false;
newRoot->numOfKeys = 1;
_rootNode = newRoot;
// Update root address
_rootAddressOfStorage.blockAddress = _rootNode;
_rootAddressOfStorage.offset = 0;
}
// If parent node not root node
else
{
// Insert new parent node
Address newParentNodeAddress = findParentNode(tempPtr->ptrToKeys[0], _rootAddressOfStorage, parentNodeAddress);
addInternalNode(tempKeyList[tempPtr->numOfKeys], newParentNodeAddress, newInternalNodeAddress);
}
}
}
int removeInternalNode(int targetRecord, BPNode* parentNode, BPNode* childNode) {
//parent node as cursor pointer(cursor)
BPNode* cursor = parentNode;
if(cursor == _rootAddressOfStorage.blockAddress) {
if(cursor->numOfKeys == 1){
if (cursor->ptrToNode[1].blockAddress == childNode){
Address updateRoot;
updateRoot.blockAddress = cursor->ptrToNode[0].blockAddress;
updateRoot.offset = 0;
_rootNode = (BPNode*) updateRoot.blockAddress;
_rootAddressOfStorage = updateRoot;
return 1;
} else if(cursor->ptrToNode[0].blockAddress == childNode){
Address updateRoot;
updateRoot.blockAddress = cursor->ptrToNode[1].blockAddress;
updateRoot.offset = 0;
_rootNode = (BPNode*) updateRoot.blockAddress;
_rootAddressOfStorage = updateRoot;
return 1;
}
}
}
//Parent is not root, find position of key to delete
int position;
for(position = 0; position < cursor->numOfKeys; position++) {
if(cursor->ptrToKeys[position] == targetRecord) {
break;
}
}
//Shift everything infront to overwrite key
for(int i = position; i < cursor->numOfKeys; i++) {
cursor->ptrToKeys[i] = cursor->ptrToKeys[i + 1];
}
//Find position to update pointer
for(position = 0; position < cursor->numOfKeys + 1; position++) {
if(cursor->ptrToNode[position].blockAddress == childNode) {
break;
}
}
//Shift everythiing infront to overwrite ptr
for(int i = position; i < cursor->numOfKeys + 1; i++) {
cursor->ptrToNode[i] = cursor->ptrToNode[i + 1];
}
//Reduce number of keys
cursor->numOfKeys--;
//If we currently got at least the number of key
if(cursor->numOfKeys >= (_maxNumOfKey + 1) / 2 - 1) {
return 0;
}
//If the current cursor is root node also
if(cursor == _rootNode) {
return 0;
}
int leftSibling, rightSibling;
Address parentdiskadd;
parentdiskadd.blockAddress = parentNode;
parentdiskadd.offset = 0;
//Find parent of the current node
Address parentparentnodeadd = findParentNode(cursor->ptrToKeys[0], _rootAddressOfStorage, parentdiskadd);
BPNode* parentparentnode = (BPNode*) parentparentnodeadd.blockAddress;
//Find key from inside parent node
for(position = 0; position < parentparentnode->numOfKeys + 1; position++) {
if(parentparentnode->ptrToNode[position].blockAddress == parentNode) {
leftSibling = position - 1;
rightSibling = position + 1;
break;
}
}
//If parent got left sibling to borrow from
if(leftSibling >= 0){
BPNode* leftnode = (BPNode*) parentparentnode->ptrToNode[leftSibling].blockAddress;
//Then borrow
if(leftnode->numOfKeys >= (_maxNumOfKey + 1) / 2){
for(int i = cursor->numOfKeys; i > 0; i--){
cursor->ptrToKeys[i] = cursor->ptrToKeys[i - 1];
}
cursor->ptrToKeys[0] = parentparentnode->ptrToKeys[leftSibling];
parentparentnode->ptrToKeys[leftSibling] = leftnode->ptrToKeys[leftnode->numOfKeys - 1];
for(int i = cursor->numOfKeys + 1; i > 0; i--){
cursor->ptrToNode[i] = cursor->ptrToNode[i - 1];
}
cursor->ptrToNode[0] = leftnode->ptrToNode[leftnode->numOfKeys];
cursor->numOfKeys++;
leftnode->numOfKeys++;
leftnode->ptrToNode[cursor->numOfKeys] = leftnode->ptrToNode[cursor->numOfKeys + 1];
return 0;
}
}
//If parent no left sibiling but got right sibling
if(rightSibling <= parentparentnode->numOfKeys){
BPNode* rightnode = (BPNode*) parentparentnode->ptrToNode[rightSibling].blockAddress;
//Then borrow from right sibling
if(rightnode->numOfKeys >= (_maxNumOfKey + 1) / 2){
cursor->ptrToKeys[cursor->numOfKeys] = parentparentnode->ptrToKeys[position];
parentparentnode->ptrToKeys[position] = rightnode->ptrToKeys[0];
for(int i = 0; i < rightnode->numOfKeys - 1; i++){
rightnode->ptrToKeys[i] = rightnode->ptrToKeys[i + 1];
}
cursor->ptrToNode[cursor->numOfKeys + 1] = rightnode->ptrToNode[0];
for(int i = 0; i < rightnode->numOfKeys; i++){
rightnode->ptrToNode[i] = rightnode->ptrToNode[i + 1];
}
cursor->numOfKeys++;
rightnode->numOfKeys--;
return 0;
}
}
//No sibiling to borrow from, merge from left sibiling
if(leftSibling >= 0){
BPNode* leftnode = (BPNode*) parentparentnode->ptrToNode[leftSibling].blockAddress;
leftnode->ptrToKeys[leftnode->numOfKeys] = parentparentnode->ptrToKeys[leftSibling];
int j;
for (int i = leftnode->numOfKeys + 1, j = 0; j < cursor->numOfKeys; j++){
leftnode->ptrToKeys[i] = cursor->ptrToKeys[j];
}
Address nulladdress;
nulladdress.blockAddress = nullptr;
nulladdress.offset = 0;
for (int i = leftnode->numOfKeys + 1, j = 0; j < cursor->numOfKeys + 1; j++){
leftnode->ptrToNode[i] = cursor->ptrToNode[j];
cursor->ptrToNode[j] = nulladdress;
}
leftnode->numOfKeys += cursor->numOfKeys + 1;
cursor->numOfKeys = 0;
_numOfNodes--;
//Recurssively remove from parent node.
return removeInternalNode(parentparentnode->ptrToKeys[leftSibling], parentparentnode, parentNode);
}
else if(rightSibling <= parentparentnode->numOfKeys){
//If parent has no left sibling to borrow from then merge
BPNode* rightnode = (BPNode*) parentparentnode->ptrToNode[rightSibling].blockAddress;
cursor->ptrToKeys[cursor->numOfKeys] = parentparentnode->ptrToKeys[rightSibling - 1];
for(int i = cursor->numOfKeys + 1, j = 0; j < rightnode->numOfKeys; j++){
cursor->ptrToKeys[i] = rightnode->ptrToKeys[j];
}
Address nulladdress;
nulladdress.blockAddress = nullptr;
nulladdress.offset = 0;
for(int i = cursor->numOfKeys + 1, j = 0; j < rightnode->numOfKeys + 1; j++){
cursor->ptrToNode[i] = rightnode->ptrToNode[j];
rightnode->ptrToNode[j] = nulladdress;
}
cursor->numOfKeys += rightnode->numOfKeys + 1;
rightnode->numOfKeys = 0;
_numOfNodes--;
return removeInternalNode(parentparentnode->ptrToKeys[rightSibling - 1], parentNode, rightnode);
}
}
// Find the parent address of a node by pass in parameter, lower bound key and child node address, root storage address
Address findParentNode(int lowerBoundKey, Address _rootAddressOfStorage, Address childNodeAddress){
// Load parent from disk first
BPNode* tempPtr = (BPNode*) _rootAddressOfStorage.blockAddress;
BPNode* parent = (BPNode*) tempPtr;
Address nullAddress;
nullAddress.blockAddress = nullptr;
nullAddress.offset = 0;
// If parent node is a leaf ndoe ..obvisouly no child node
if (tempPtr->isLeafNode == true) {
return nullAddress;
}
// If not leaf node, then iterate all parent key and finde out the location
while (tempPtr->isLeafNode == false) {
for (int i = 0; i < tempPtr->numOfKeys + 1; i++) {
if (tempPtr->ptrToNode[i].blockAddress == childNodeAddress.blockAddress) {
Address parentNodeAddress;
parentNodeAddress.blockAddress = parent;
parentNodeAddress.offset = 0;
return parentNodeAddress;
}
}
// If unable find from above iteration, then need go down next tree level
for (int i = 0; i < tempPtr->numOfKeys; i++) {
// If key is lesser, then check left side
if (lowerBoundKey < tempPtr->ptrToKeys[i]) {
parent = tempPtr;
tempPtr = (BPNode*) tempPtr->ptrToNode[i].blockAddress;
break;
}
// If key is larger than current parent node pointer, then check right side
if (i == tempPtr->numOfKeys - 1) {
parent = tempPtr;
tempPtr = (BPNode*) tempPtr->ptrToNode[i + 1].blockAddress;
break;
}
}
}
// If above still can't find, return null address
return nullAddress;
}
public:
// Constructor
BPlusTree(DiskStorage* _storage, size_t sizeOfBlock){
// Check the left over size in a node to store pointers and keys
size_t avaliableNodeSize = sizeOfBlock - sizeof(bool) - sizeof(int);
// Size of Address struct
size_t sizeOfAddress = sizeof(Address);
_maxNumOfKey = 0;
// To check how many keys can fit in one node and update max number of key in a node
while (sizeOfAddress + sizeof(Address) + sizeof(int) <= avaliableNodeSize) {
sizeOfAddress += (sizeof(Address) + sizeof(int));
_maxNumOfKey += 1;
}
if (_maxNumOfKey == 0) {
throw overflow_error("Error: Size of pointer and keys exceeds limit!");
}
// Initialize _rootNode
_rootAddressOfStorage.blockAddress = nullptr;
_rootAddressOfStorage.offset = 0;
_rootNode = nullptr;
// Set node size to be equal to block size.
_sizeOfNode = sizeOfBlock;
// Initialize variables
_levelOfTrees = 0;
_numOfNodes = 0;
this->_storage = _storage;
}
// Inserts new record into B+ tree
void insertRecord(Address recordaddress, int key){
BPNode* _rootNode = (BPNode*) _rootAddressOfStorage.blockAddress;
// Check if have root node, if no create a new root node
if (_rootNode == nullptr) {
// Create a new linked list reserved for each key, to handlie duplicate
// For example, some movie may have same number of votes, so record may
// have more than one record with same number of notes
LinkedListNode* llnode = new LinkedListNode();
llnode->dataaddress.blockAddress = recordaddress.blockAddress;
llnode->dataaddress.offset = recordaddress.offset;
llnode->next = nullptr;
Address linkedListNodeAdress;
linkedListNodeAdress.blockAddress = llnode;
linkedListNodeAdress.offset = 0;
// Create new root node
_rootNode = new BPNode(_maxNumOfKey);
_numOfNodes++;
_rootNode->ptrToKeys[0] = key;
_rootNode->numOfKeys = 1;
_rootNode->isLeafNode = true; // It is root node and leaf node also
_rootNode->ptrToNode[0] = linkedListNodeAdress;
_rootAddressOfStorage.blockAddress = _rootNode;
_rootAddressOfStorage.offset = 0;
} else {
// If already have a root node, then find a location to insert the new record
BPNode* tempPtr = _rootNode;
// Create a parent node to keep track during searchKey the location for new node
BPNode* parent = nullptr;
Address parentDiskAddress;
parentDiskAddress.blockAddress = nullptr;
parentDiskAddress.offset = 0;
// Assign the address of tempPtr pointing to root node
Address tempPtrAddress; // Store current node's _storage address in case we need to update it in _storage.
tempPtrAddress.blockAddress = _rootNode;
tempPtrAddress.offset = 0;
int treeLevel = 0;
// Loop through all non-leaf nodes and keys to find out location which to insert the new record
while (tempPtr->isLeafNode == false) {
parent = tempPtr;
parentDiskAddress.blockAddress = parent;
for (int i = 0; i < tempPtr->numOfKeys; i++) {
// if searchKey key is lesser than the current key we check, then check the life side of tree
if (key < tempPtr->ptrToKeys[i]) {
tempPtr = (BPNode*) tempPtr->ptrToNode[i].blockAddress;
tempPtrAddress.blockAddress = tempPtr;
break;
}
// Else check right side of the tree
if (i == tempPtr->numOfKeys - 1) {
tempPtr = (BPNode*) tempPtr->ptrToNode[i + 1].blockAddress;
tempPtrAddress.blockAddress = tempPtr;
break;
}
}
treeLevel++;
}
// Out of while loop means already reach a leaf node, to put in new record here if space avaliable
if (tempPtr->numOfKeys < _maxNumOfKey) {
int i = 0;
// Loop through all keys to find a place put in the key for new record
while (key > tempPtr->ptrToKeys[i] && i < tempPtr->numOfKeys) {
i++;
}
// Check for duplicate, whether already a key exists , if exist same key, create a linked list to hold for duplicates
if (tempPtr->ptrToKeys[i] == key) {
Address linkedListNodeAdress;
linkedListNodeAdress.blockAddress = tempPtr->ptrToNode[i].blockAddress;
linkedListNodeAdress.offset = tempPtr->ptrToNode[i].offset;
LinkedListNode* prenode = (LinkedListNode*) linkedListNodeAdress.blockAddress + linkedListNodeAdress.offset;
LinkedListNode* curnode = new LinkedListNode();
curnode->dataaddress.blockAddress = recordaddress.blockAddress;
curnode->dataaddress.offset = recordaddress.offset;
curnode->next = nullptr;
while(prenode->next != nullptr){
prenode = prenode->next;
}
prenode->next = curnode;
} else {
// Update pointer location, to keep track the last pointer of key in a node, 1st key pointer for new node
Address next = tempPtr->ptrToNode[tempPtr->numOfKeys];
// In this case i represents the key id we found to insert new record
//, and iterate through all keys and sort them to let the new key fit in
for (int j = tempPtr->numOfKeys; j > i; j--) {
tempPtr->ptrToKeys[j] = tempPtr->ptrToKeys[j - 1];
tempPtr->ptrToNode[j] = tempPtr->ptrToNode[j - 1];
}
// Location has been determined, and insert new key here
tempPtr->ptrToKeys[i] = key;
// Create a new linked list to store record, put all duplicates into the list with same key value
LinkedListNode* llnode = new LinkedListNode();
llnode->dataaddress.blockAddress = recordaddress.blockAddress;
llnode->dataaddress.offset = recordaddress.offset;
llnode->next = nullptr;
Address linkedListNodeAdress;
linkedListNodeAdress.blockAddress = llnode;
linkedListNodeAdress.offset = 0;
// Update current pointer variables
tempPtr->ptrToNode[i] = linkedListNodeAdress;
tempPtr->numOfKeys++;
tempPtr->ptrToNode[tempPtr->numOfKeys] = next;
}
}
else {
// Overflow: If there's no space to insertRecord new key, we have to split this node into two and update the parent if required.
// Create a new leaf node to put half the ptrToKeys and ptrToNode in.
// If no more space to store new record in current node, then split into two node and update the pointers in leaf and parent node
BPNode* newLeafNode = new BPNode(_maxNumOfKey);
_numOfNodes++;
// create temp list array to store key and pointers seperately, copy over current node data into it
int tempKeyList[_maxNumOfKey + 1];
Address tempPointerList[_maxNumOfKey + 1];
Address next = tempPtr->ptrToNode[tempPtr->numOfKeys];
for (int i = 0; i < _maxNumOfKey; i++) {
tempKeyList[i] = tempPtr->ptrToKeys[i];
tempPointerList[i] = tempPtr->ptrToNode[i];
}
// Add the new record into temp list array by iterating current node keys to find proper location
int i = 0;
while (key > tempKeyList[i] && i < _maxNumOfKey) {
i++;
}
if (i < tempPtr->numOfKeys) {
if (tempPtr->ptrToKeys[i] == key) {
Address linkedListNodeAdress;
linkedListNodeAdress.blockAddress = tempPtr->ptrToNode[i].blockAddress;
linkedListNodeAdress.offset = tempPtr->ptrToNode[i].offset;
LinkedListNode* prenode = (LinkedListNode*) linkedListNodeAdress.blockAddress + linkedListNodeAdress.offset;
LinkedListNode* curnode = new LinkedListNode();
curnode->dataaddress.blockAddress = recordaddress.blockAddress;
curnode->dataaddress.offset = recordaddress.offset;
curnode->next = nullptr;
while(prenode->next != nullptr){
prenode = prenode->next;
}
prenode->next = curnode;
return;
}
}
// Use bubble sort to sort keys
for (int j = _maxNumOfKey; j > i; j--) {
tempKeyList[j] = tempKeyList[j - 1];
tempPointerList[j] = tempPointerList[j - 1];
}
// Add new record key and pointer into the temporary lists.
tempKeyList[i] = key;
//Create linked list to handle duplicate key situation
LinkedListNode* llnode = new LinkedListNode();
llnode->dataaddress.blockAddress = recordaddress.blockAddress;
llnode->dataaddress.offset = recordaddress.offset;
llnode->next = nullptr;
Address linkedListNodeAdress;
linkedListNodeAdress.blockAddress = llnode;
linkedListNodeAdress.offset = 0;
// Store the data into temp list
tempPointerList[i] = linkedListNodeAdress;
newLeafNode->isLeafNode = true;
tempPtr->numOfKeys = ceil((_maxNumOfKey + 1) / 2.0);
newLeafNode->numOfKeys = floor((_maxNumOfKey + 1) / 2.0);
newLeafNode->ptrToNode[newLeafNode->numOfKeys] = next;
for (i = 0; i < tempPtr->numOfKeys; i++) {
tempPtr->ptrToKeys[i] = tempKeyList[i];
tempPtr->ptrToNode[i] = tempPointerList[i];
}
// Update keys and pointers for the new leaf node
for (int j = 0; j < newLeafNode->numOfKeys; i++, j++) {
newLeafNode->ptrToKeys[j] = tempKeyList[i];
newLeafNode->ptrToNode[j] = tempPointerList[i];
}
// Add new leaf node address into disk
Address newLeafNodeAddress;
newLeafNodeAddress.blockAddress = newLeafNode;
newLeafNodeAddress.offset = 0;
// Set the current pointer cursor pointing to new leaf node, so later can save new leaf node into disk
tempPtr->ptrToNode[tempPtr->numOfKeys] = newLeafNodeAddress;
// Check if any wrong key and pointer , set it to 0 and null
for (int i = tempPtr->numOfKeys; i < _maxNumOfKey; i++) {
tempPtr->ptrToKeys[i] = 0;
}
for (int i = tempPtr->numOfKeys + 1; i < _maxNumOfKey + 1; i++) {
Address nullAddress;
nullAddress.blockAddress = nullptr;
nullAddress.offset = 0;
tempPtr->ptrToNode[i] = nullAddress;
}
// If current pointer cursor at root node, then make this cursor into a root node
if (tempPtr == _rootNode) {
BPNode* newRoot = new BPNode(_maxNumOfKey);
_numOfNodes++;
newRoot->ptrToKeys[0] = newLeafNode->ptrToKeys[0];
newRoot->ptrToNode[0] = tempPtrAddress;
newRoot->ptrToNode[1] = newLeafNodeAddress;
newRoot->isLeafNode = false;
newRoot->numOfKeys = 1;
_rootNode = newRoot;
_rootAddressOfStorage.blockAddress = _rootNode;
_rootAddressOfStorage.offset = 0;
} else { // If we are not at the _rootNode, we need to insertRecord a new parent in the middle _levelOfTrees of the tree.
addInternalNode(newLeafNode->ptrToKeys[0], parentDiskAddress, newLeafNodeAddress);
}
}
}
}
int removeRecord(int targetRecord){
BPNode* cursorPtr = (BPNode*) _rootAddressOfStorage.blockAddress; // Cursor pointer point to root
BPNode* parentNode; // Keep track parent node when traverse data file
int leftSibling, rightSibling; // Index of left and right child to borrow from.
int deletedNodesCount; // The total number of nodes has been deleted or merged
int updatedNodesCount; // Current total number of nodes after deletion and merge of nodes
int heightOfBPlusTree; // Update B+ tree height
if (cursorPtr != nullptr){
while(!cursorPtr->isLeafNode){
parentNode = cursorPtr;
for (int i = 0; i < cursorPtr->numOfKeys; i++){
leftSibling = i - 1;
rightSibling = i + 1;
int key = getKeyAddress(cursorPtr,i);
// If key is lesser than current key, go to the left pointer's node.
if (targetRecord < key) {
cursorPtr = (BPNode*) cursorPtr->ptrToNode[i].blockAddress;
break;
}
// Else if key larger than all keys in the node, go to last pointer's node (rightmost).
if(cursorPtr->getCountOfKeys() - 1 == i) {
leftSibling = i;
rightSibling = i + 2;
//to-fix: need to update cursor with Next Node
cursorPtr = (BPNode*) cursorPtr->ptrToNode[i + 1].blockAddress;
break;
}
}
}
// When reach leaf node
bool isKeyFound = false;
int position; // Position of target record
for (position = 0; position < cursorPtr->numOfKeys; position++) {
if (getKeyAddress(cursorPtr,position) == targetRecord) {
isKeyFound = true;
break;
}
}
if (!isKeyFound){
cout << " You have reached last record, target record not exist!" << endl;
return 0;
}
deleteTargetKeyFromNode(cursorPtr, position);
movePointersForward(cursorPtr, _maxNumOfKey);
// If current node is root, check if tree still has keys.
if (cursorPtr == _rootNode && cursorPtr->numOfKeys == 0) {
// Reset root pointers in the B+ Tree.
_rootNode = nullptr;
Address nulladd;
nulladd.blockAddress = nullptr;
nulladd.offset = 0;
_rootAddressOfStorage = nulladd;
//todo: need to return numNodesDeleted after deletion
return 1;
}
bool hasUnderflow = checkHasUnderflow(cursorPtr,_maxNumOfKey);
if(hasUnderflow){
// Try to lend from Left Sibling
if (leftSibling >= 0) {
int numNodesDeleted = borrowFromLeftSibling(cursorPtr,parentNode,leftSibling,_maxNumOfKey);
if(numNodesDeleted > 0){
return numNodesDeleted;
}
}
// Try to lend from Right Sibling
if (rightSibling <= parentNode->numOfKeys) {
int numNodesDeleted = borrowFromRightSibling(cursorPtr,parentNode,rightSibling,_maxNumOfKey);
if(numNodesDeleted > 0){
return numNodesDeleted;
}
}
// No Left/Right Sibling to borrow, thus we do Merge Nodes to resolve Underflow
// If left sibling exists, merge with it.
if (leftSibling >= 0){
mergeWithLeftSibling(cursorPtr,parentNode,leftSibling);
} else if (rightSibling <= parentNode->numOfKeys){
mergeWithRightSibling(cursorPtr,parentNode,rightSibling);
}
} else { //No hasUnderflow
return 0;
}
}
return 0;
}
// Method used to search a key
tuple<int,int> searchKey(int lowerBoundKey, int upperBoundKey) {
// Initialize variables
BPNode* parentNode = (BPNode*) _rootAddressOfStorage.blockAddress;
int displayCount = 0;
int indexOfBlock = 0;
int recordIDOfBlock = 0;
int numOfRecordFound = 0;
float avgRating = 0.0;
if (parentNode != nullptr) {
// Loop through non-leaf node keys
while(!parentNode->isLeafNode) {
if(displayCount < 5) {
cout << "Index block: ";
showNodeContent(parentNode);
displayCount++;
}
for (int i = 0; i < parentNode->numOfKeys; i++){
int key = getKeyAddress(parentNode, i);
if (lowerBoundKey < key){
parentNode = (BPNode*) parentNode->ptrToNode[i].blockAddress;
break;
}
// If reach last key, move to right node continue search
if(parentNode->getCountOfKeys() - 1 == i){
parentNode = (BPNode*) parentNode->ptrToNode[i + 1].blockAddress;
break;
}
}
indexOfBlock++;
}
// Loop through leaf node keys to match with target and showBPlusTree result
displayCount = 0;
bool continueSearch = false;
while(!continueSearch){
if(displayCount < 5) {
cout << "Current index leaf block is : ";
showNodeContent(parentNode);
displayCount++;
}
int i;
for (i = 0; i < parentNode->getCountOfKeys(); i++){
int key = getKeyAddress(parentNode,i);
if (key > upperBoundKey) {
continueSearch = true;
cout << "Average of rating: " << (avgRating / numOfRecordFound) << endl;
cout << "Searching completed."<< endl;
break;
}
if (key >= lowerBoundKey && key <= upperBoundKey){
float averageRating = 0.0;
int numOfResultFound = 0;
Address linkedListNodeAdress;
linkedListNodeAdress.blockAddress = parentNode->ptrToNode[i].blockAddress;
linkedListNodeAdress.offset = parentNode->ptrToNode[i].offset;
tie(numOfResultFound, averageRating) = showLinkedList(linkedListNodeAdress);
avgRating += averageRating;
numOfRecordFound += numOfResultFound;
recordIDOfBlock += numOfResultFound;
}
}
if(parentNode->ptrToNode[parentNode->numOfKeys].blockAddress != nullptr && parentNode->ptrToKeys[i] != upperBoundKey){
parentNode = (BPNode*) parentNode->ptrToNode[parentNode->numOfKeys].blockAddress;
indexOfBlock++;
} else {
continueSearch = true;
}
}
}
else
{
cout << "No result found!" << endl;
}
return make_tuple(indexOfBlock, recordIDOfBlock);
}
// To display current B+ tree in console
void showBPlusTree(Address _rootAddressOfStorage, int treeLevel, int maxLevel) {
BPNode* cursorPointer = (BPNode*) _rootAddressOfStorage.blockAddress;
// If tree is not empty
if (cursorPointer != nullptr) {
cout << "Current B+ tree Level is: " << treeLevel;
for (int i = 0; i < treeLevel; i++) { cout << " "; }
showNodeContent(cursorPointer);
if(treeLevel == maxLevel){
return;
}
if (cursorPointer->isLeafNode != true) {
for (int i = 0; i < cursorPointer->numOfKeys + 1; i++) {
Address cursorStorageAddress;
cursorStorageAddress.blockAddress = cursorPointer->ptrToNode[i].blockAddress;
cursorStorageAddress.offset = 0;
showBPlusTree(cursorStorageAddress, treeLevel + 1, maxLevel);
}
}
}
}
// Display a specific node from B+ tree and display all the content of this node
void showNodeContent(BPNode* node) {
// Display contents in the node with this format |pointer|key|pointer|
int i = 0;
cout << " " << node << " - |";
for (int i = 0; i < node->numOfKeys; i++) {
if(node->isLeafNode == true){
int count = 0;
Address linkedListNodeAdress;
linkedListNodeAdress.blockAddress = node->ptrToNode[i].blockAddress;
linkedListNodeAdress.offset = node->ptrToNode[i].offset;
LinkedListNode* prenode = (LinkedListNode*) linkedListNodeAdress.blockAddress + linkedListNodeAdress.offset;
count++;
while(prenode->next != nullptr){
count++;
prenode = prenode->next;
}
cout << static_cast<void*>(node->ptrToNode[i].blockAddress) << "|";
cout << node->ptrToKeys[i] << "-" << count << "|";
} else {
cout << static_cast<void*>(node->ptrToNode[i].blockAddress) << "|";
cout << node->ptrToKeys[i] << "|";
}
}
// Display last remaining pointer
if (node->ptrToNode[node->numOfKeys].blockAddress == nullptr) {
cout << "null|";
} else {
cout << node->ptrToNode[node->numOfKeys].blockAddress << "|";
}
for (int i = node->numOfKeys; i < _maxNumOfKey; i++) {
cout << "x|"; // Remaining empty ptrToKeys
cout << "null|"; // Remaining empty ptrToNode
}
cout << endl;
}