从整个建树过程的单元测试b_plus_tree_print_test来理清楚B+ Tree建树的过程以及思路
这个单元测试程序就是一个命令行工具,通过命令来插入和删除Key,然后可视化B + Tree, 其命令参数如下
std::string usageMessage() {
std::string message =
"Enter any of the following commands after the prompt > :\n"
"\ti <k> -- Insert <k> (int64_t) as both key and value).\n"
"\tf <filename> -- insert multiple keys from reading file.\n"
"\tc <filename> -- delete multiple keys from reading file.\n"
"\td <k> -- Delete key <k> and its associated value.\n"
"\tg <filename>.dot -- Output the tree in graph format to a dot file\n"
"\tp -- Print the B+ tree.\n"
"\tq -- Quit. (Or use Ctl-D.)\n"
"\t? -- Print this help message.\n\n"
"Please Enter Leaf node max size and Internal node max size:\n"
"Example: 5 5\n>";
return message;
}
首先看其插入过程:
case 'i':
std::cin >> key;
rid.Set(static_cast<int32_t>(key >> 32), static_cast<int>(key & 0xFFFFFFFF));
index_key.SetFromInteger(key);
tree.Insert(index_key, rid, transaction);
break;
从Insert函数入手
根据注释写出如下代码
/*
* 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) {
assert(transaction != nullptr);
if(IsEmpty()){
StartNewTree(key, value);
InsertIntoLeaf(key, value, transaction);
return true;
}
return InsertIntoLeaf(key, value, transaction);
}
然后去实现上述涉及到的三个函数
根据根节点的id信息,判断B+树是否为空。
/*
* 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; }
/*
* 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) {
}
/*
* 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) {
return false;
}