TreeNode.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. /*
  2. * Copyright (c) 2021, Jan de Visser <jan@de-visser.net>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Debug.h>
  7. #include <AK/Format.h>
  8. #include <AK/StringBuilder.h>
  9. #include <LibSQL/BTree.h>
  10. #include <LibSQL/Serializer.h>
  11. namespace SQL {
  12. DownPointer::DownPointer(TreeNode* owner, Block::Index block_index)
  13. : m_owner(owner)
  14. , m_block_index(block_index)
  15. , m_node(nullptr)
  16. {
  17. }
  18. DownPointer::DownPointer(TreeNode* owner, TreeNode* node)
  19. : m_owner(owner)
  20. , m_block_index((node) ? node->block_index() : 0)
  21. , m_node(adopt_own_if_nonnull(node))
  22. {
  23. }
  24. DownPointer::DownPointer(TreeNode* owner, DownPointer& down)
  25. : m_owner(owner)
  26. , m_block_index(down.m_block_index)
  27. , m_node(move(down.m_node))
  28. {
  29. }
  30. DownPointer::DownPointer(DownPointer&& other)
  31. : m_owner(other.m_owner)
  32. , m_block_index(other.block_index())
  33. , m_node(other.m_node ? move(other.m_node) : nullptr)
  34. {
  35. }
  36. TreeNode* DownPointer::node()
  37. {
  38. if (!m_node)
  39. deserialize(m_owner->tree().serializer());
  40. return m_node;
  41. }
  42. void DownPointer::deserialize(Serializer& serializer)
  43. {
  44. if (m_node || !m_block_index)
  45. return;
  46. serializer.read_storage(m_block_index);
  47. m_node = serializer.make_and_deserialize<TreeNode>(m_owner->tree(), m_owner, m_block_index);
  48. }
  49. TreeNode::TreeNode(BTree& tree, Block::Index block_index)
  50. : IndexNode(block_index)
  51. , m_tree(tree)
  52. , m_up(nullptr)
  53. , m_entries()
  54. , m_down()
  55. {
  56. }
  57. TreeNode::TreeNode(BTree& tree, TreeNode* up, Block::Index block_index)
  58. : IndexNode(block_index)
  59. , m_tree(tree)
  60. , m_up(up)
  61. , m_entries()
  62. , m_down()
  63. {
  64. m_down.append(DownPointer(this, nullptr));
  65. m_is_leaf = true;
  66. }
  67. TreeNode::TreeNode(BTree& tree, TreeNode* up, DownPointer& left, Block::Index block_index)
  68. : IndexNode(block_index)
  69. , m_tree(tree)
  70. , m_up(up)
  71. , m_entries()
  72. , m_down()
  73. {
  74. if (left.m_node != nullptr)
  75. left.m_node->m_up = this;
  76. m_down.append(DownPointer(this, left));
  77. m_is_leaf = left.block_index() == 0;
  78. if (!block_index)
  79. set_block_index(m_tree.request_new_block_index());
  80. }
  81. TreeNode::TreeNode(BTree& tree, TreeNode* up, TreeNode* left, Block::Index block_index)
  82. : IndexNode(block_index)
  83. , m_tree(tree)
  84. , m_up(up)
  85. , m_entries()
  86. , m_down()
  87. {
  88. m_down.append(DownPointer(this, left));
  89. m_is_leaf = left->block_index() == 0;
  90. }
  91. void TreeNode::deserialize(Serializer& serializer)
  92. {
  93. auto nodes = serializer.deserialize<u32>();
  94. dbgln_if(SQL_DEBUG, "Deserializing node. Size {}", nodes);
  95. if (nodes > 0) {
  96. for (u32 i = 0; i < nodes; i++) {
  97. auto left = serializer.deserialize<u32>();
  98. dbgln_if(SQL_DEBUG, "Down[{}] {}", i, left);
  99. if (!m_down.is_empty())
  100. VERIFY((left == 0) == m_is_leaf);
  101. else
  102. m_is_leaf = (left == 0);
  103. m_entries.append(serializer.deserialize<Key>(m_tree.descriptor()));
  104. m_down.empend(this, left);
  105. }
  106. auto right = serializer.deserialize<u32>();
  107. dbgln_if(SQL_DEBUG, "Right {}", right);
  108. VERIFY((right == 0) == m_is_leaf);
  109. m_down.empend(this, right);
  110. }
  111. }
  112. void TreeNode::serialize(Serializer& serializer) const
  113. {
  114. u32 sz = size();
  115. serializer.serialize<u32>(sz);
  116. if (sz > 0) {
  117. for (auto ix = 0u; ix < size(); ix++) {
  118. auto& entry = m_entries[ix];
  119. dbgln_if(SQL_DEBUG, "Serializing Left[{}] = {}", ix, m_down[ix].block_index());
  120. serializer.serialize<u32>(is_leaf() ? 0u : m_down[ix].block_index());
  121. serializer.serialize<Key>(entry);
  122. }
  123. dbgln_if(SQL_DEBUG, "Serializing Right = {}", m_down[size()].block_index());
  124. serializer.serialize<u32>(is_leaf() ? 0u : m_down[size()].block_index());
  125. }
  126. }
  127. size_t TreeNode::length() const
  128. {
  129. if (!size())
  130. return 0;
  131. size_t len = sizeof(u32);
  132. for (auto& key : m_entries)
  133. len += sizeof(u32) + key.length();
  134. return len;
  135. }
  136. bool TreeNode::insert(Key const& key)
  137. {
  138. dbgln_if(SQL_DEBUG, "[#{}] INSERT({})", block_index(), key.to_byte_string());
  139. if (!is_leaf())
  140. return node_for(key)->insert_in_leaf(key);
  141. return insert_in_leaf(key);
  142. }
  143. bool TreeNode::update_key_pointer(Key const& key)
  144. {
  145. dbgln_if(SQL_DEBUG, "[#{}] UPDATE({}, {})", block_index(), key.to_byte_string(), key.block_index());
  146. if (!is_leaf())
  147. return node_for(key)->update_key_pointer(key);
  148. for (auto ix = 0u; ix < size(); ix++) {
  149. if (key == m_entries[ix]) {
  150. dbgln_if(SQL_DEBUG, "[#{}] {} == {}",
  151. block_index(), key.to_byte_string(), m_entries[ix].to_byte_string());
  152. if (m_entries[ix].block_index() != key.block_index()) {
  153. m_entries[ix].set_block_index(key.block_index());
  154. dump_if(SQL_DEBUG, "To WAL");
  155. tree().serializer().serialize_and_write<TreeNode>(*this);
  156. }
  157. return true;
  158. }
  159. }
  160. return false;
  161. }
  162. bool TreeNode::insert_in_leaf(Key const& key)
  163. {
  164. VERIFY(is_leaf());
  165. if (!m_tree.duplicates_allowed()) {
  166. for (auto& entry : m_entries) {
  167. if (key == entry) {
  168. dbgln_if(SQL_DEBUG, "[#{}] duplicate key {}", block_index(), key.to_byte_string());
  169. return false;
  170. }
  171. }
  172. }
  173. dbgln_if(SQL_DEBUG, "[#{}] insert_in_leaf({})", block_index(), key.to_byte_string());
  174. just_insert(key, nullptr);
  175. return true;
  176. }
  177. Block::Index TreeNode::down_pointer(size_t ix) const
  178. {
  179. return m_down[ix].block_index();
  180. }
  181. TreeNode* TreeNode::down_node(size_t ix)
  182. {
  183. return m_down[ix].node();
  184. }
  185. TreeNode* TreeNode::node_for(Key const& key)
  186. {
  187. dump_if(SQL_DEBUG, ByteString::formatted("node_for(Key {})", key.to_byte_string()));
  188. if (is_leaf())
  189. return this;
  190. for (size_t ix = 0; ix < size(); ix++) {
  191. if (key < m_entries[ix]) {
  192. dbgln_if(SQL_DEBUG, "[{}] {} < {} v{}",
  193. block_index(), (ByteString)key, (ByteString)m_entries[ix], m_down[ix].block_index());
  194. return down_node(ix)->node_for(key);
  195. }
  196. }
  197. dbgln_if(SQL_DEBUG, "[#{}] {} >= {} v{}",
  198. block_index(), key.to_byte_string(), (ByteString)m_entries[size() - 1], m_down[size()].block_index());
  199. return down_node(size())->node_for(key);
  200. }
  201. Optional<u32> TreeNode::get(Key& key)
  202. {
  203. dump_if(SQL_DEBUG, ByteString::formatted("get({})", key.to_byte_string()));
  204. for (auto ix = 0u; ix < size(); ix++) {
  205. if (key < m_entries[ix]) {
  206. if (is_leaf()) {
  207. dbgln_if(SQL_DEBUG, "[#{}] {} < {} -> 0",
  208. block_index(), key.to_byte_string(), (ByteString)m_entries[ix]);
  209. return {};
  210. } else {
  211. dbgln_if(SQL_DEBUG, "[{}] {} < {} ({} -> {})",
  212. block_index(), key.to_byte_string(), (ByteString)m_entries[ix],
  213. ix, m_down[ix].block_index());
  214. return down_node(ix)->get(key);
  215. }
  216. }
  217. if (key == m_entries[ix]) {
  218. dbgln_if(SQL_DEBUG, "[#{}] {} == {} -> {}",
  219. block_index(), key.to_byte_string(), (ByteString)m_entries[ix],
  220. m_entries[ix].block_index());
  221. key.set_block_index(m_entries[ix].block_index());
  222. return m_entries[ix].block_index();
  223. }
  224. }
  225. if (m_entries.is_empty()) {
  226. dbgln_if(SQL_DEBUG, "[#{}] {} Empty node??", block_index(), key.to_byte_string());
  227. VERIFY_NOT_REACHED();
  228. }
  229. if (is_leaf()) {
  230. dbgln_if(SQL_DEBUG, "[#{}] {} > {} -> 0",
  231. block_index(), key.to_byte_string(), (ByteString)m_entries[size() - 1]);
  232. return {};
  233. }
  234. dbgln_if(SQL_DEBUG, "[#{}] {} > {} ({} -> {})",
  235. block_index(), key.to_byte_string(), (ByteString)m_entries[size() - 1],
  236. size(), m_down[size()].block_index());
  237. return down_node(size())->get(key);
  238. }
  239. void TreeNode::just_insert(Key const& key, TreeNode* right)
  240. {
  241. dbgln_if(SQL_DEBUG, "[#{}] just_insert({}, right = {})",
  242. block_index(), (ByteString)key, (right) ? right->block_index() : 0);
  243. dump_if(SQL_DEBUG, "Before");
  244. for (auto ix = 0u; ix < size(); ix++) {
  245. if (key < m_entries[ix]) {
  246. m_entries.insert(ix, key);
  247. VERIFY(is_leaf() == (right == nullptr));
  248. m_down.insert(ix + 1, DownPointer(this, right));
  249. if (length() > Block::DATA_SIZE) {
  250. split();
  251. } else {
  252. dump_if(SQL_DEBUG, "To WAL");
  253. tree().serializer().serialize_and_write(*this);
  254. }
  255. return;
  256. }
  257. }
  258. m_entries.append(key);
  259. m_down.empend(this, right);
  260. if (length() > Block::DATA_SIZE) {
  261. split();
  262. } else {
  263. dump_if(SQL_DEBUG, "To WAL");
  264. tree().serializer().serialize_and_write(*this);
  265. }
  266. }
  267. void TreeNode::split()
  268. {
  269. dump_if(SQL_DEBUG, "Splitting node");
  270. if (!m_up)
  271. // Make new m_up. This is the new root node.
  272. m_up = m_tree.new_root();
  273. // Take the left pointer for the new node:
  274. auto median_index = size() / 2;
  275. if (!(size() % 2))
  276. ++median_index;
  277. DownPointer left = m_down.take(median_index);
  278. // Create the new right node:
  279. auto* new_node = new TreeNode(tree(), m_up, left);
  280. // Move the rightmost keys from this node to the new right node:
  281. while (m_entries.size() > median_index) {
  282. auto entry = m_entries.take(median_index);
  283. auto down = m_down.take(median_index);
  284. // Reparent to new right node:
  285. if (down.m_node != nullptr)
  286. down.m_node->m_up = new_node;
  287. new_node->m_entries.append(entry);
  288. new_node->m_down.append(move(down));
  289. }
  290. // Move the median key in the node one level up. Its right node will
  291. // be the new node:
  292. auto median = m_entries.take_last();
  293. dump_if(SQL_DEBUG, "Split Left To WAL");
  294. tree().serializer().serialize_and_write(*this);
  295. new_node->dump_if(SQL_DEBUG, "Split Right to WAL");
  296. tree().serializer().serialize_and_write(*new_node);
  297. m_up->just_insert(median, new_node);
  298. }
  299. void TreeNode::dump_if(int flag, ByteString&& msg)
  300. {
  301. if (!flag)
  302. return;
  303. StringBuilder builder;
  304. builder.appendff("[#{}] ", block_index());
  305. if (!msg.is_empty())
  306. builder.appendff("{}", msg);
  307. builder.append(": "sv);
  308. if (m_up)
  309. builder.appendff("[^{}] -> ", m_up->block_index());
  310. else
  311. builder.append("* -> "sv);
  312. for (size_t ix = 0; ix < m_entries.size(); ix++) {
  313. if (!is_leaf())
  314. builder.appendff("[v{}] ", m_down[ix].block_index());
  315. else
  316. VERIFY(m_down[ix].block_index() == 0);
  317. builder.appendff("'{}' ", (ByteString)m_entries[ix]);
  318. }
  319. if (!is_leaf())
  320. builder.appendff("[v{}]", m_down[size()].block_index());
  321. else
  322. VERIFY(m_down[size()].block_index() == 0);
  323. builder.appendff(" (size {}", (int)size());
  324. if (is_leaf())
  325. builder.append(", leaf"sv);
  326. builder.append(')');
  327. dbgln(builder.to_byte_string());
  328. }
  329. void TreeNode::list_node(int indent)
  330. {
  331. auto do_indent = [&]() {
  332. for (int i = 0; i < indent; ++i)
  333. warn(" ");
  334. };
  335. do_indent();
  336. warnln("--> #{}", block_index());
  337. for (auto ix = 0u; ix < size(); ix++) {
  338. if (!is_leaf())
  339. down_node(ix)->list_node(indent + 2);
  340. do_indent();
  341. warnln("{}", m_entries[ix].to_byte_string());
  342. }
  343. if (!is_leaf())
  344. down_node(size())->list_node(indent + 2);
  345. }
  346. }