<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Let's Build a Simple Database</title>
    <description>Writing a sqlite clone from scratch in C</description>
    <link>https://guimy.tech/db_tutorial</link>
    <atom:link href="https://guimy.tech/db_tutorial/feed.xml" rel="self" type="application/rss+xml" />
    
    
    
      <item>
        <title>Part 5 - Persistence to Disk</title>
        <description>&lt;blockquote&gt;
  &lt;p&gt;“Nothing in the world can take the place of persistence.” – &lt;a href=&quot;https://en.wikiquote.org/wiki/Calvin_Coolidge&quot;&gt;Calvin Coolidge&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Our database lets you insert records and read them back out, but only as long as you keep the program running. If you kill the program and start it back up, all your records are gone. Here’s a spec for the behavior we want:&lt;/p&gt;

&lt;div class=&quot;language-ruby highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;it&lt;/span&gt; &lt;span class=&quot;s1&quot;&gt;'keeps data after closing connection'&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;do&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;result1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;run_script&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;
    &lt;span class=&quot;s2&quot;&gt;&quot;insert 1 user1 person1@example.com&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;s2&quot;&gt;&quot;.exit&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
  &lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;expect&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;result1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;to&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;match_array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;
    &lt;span class=&quot;s2&quot;&gt;&quot;db &amp;gt; Executed.&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;s2&quot;&gt;&quot;db &amp;gt; &quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
  &lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;result2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;run_script&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;
    &lt;span class=&quot;s2&quot;&gt;&quot;select&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;s2&quot;&gt;&quot;.exit&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
  &lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;expect&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;result2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;to&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;match_array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;
    &lt;span class=&quot;s2&quot;&gt;&quot;db &amp;gt; (1, user1, person1@example.com)&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;s2&quot;&gt;&quot;Executed.&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;s2&quot;&gt;&quot;db &amp;gt; &quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
  &lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;end&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Like sqlite, we’re going to persist records by saving the entire database to a file.&lt;/p&gt;

&lt;p&gt;We already set ourselves up to do that by serializing rows into page-sized memory blocks. To add persistence, we can simply write those blocks of memory to a file, and read them back into memory the next time the program starts up.&lt;/p&gt;

&lt;p&gt;To make this easier, we’re going to make an abstraction called the pager. We ask the pager for page number &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;x&lt;/code&gt;, and the pager gives us back a block of memory. It first looks in its cache. On a cache miss, it copies data from disk into memory (by reading the database file).&lt;/p&gt;

&lt;table class=&quot;image&quot;&gt;
&lt;caption align=&quot;bottom&quot;&gt;How our program matches up with SQLite architecture&lt;/caption&gt;
&lt;tr&gt;&lt;td&gt;&lt;a href=&quot;https://guimy.tech/db_tutorial/assets/images/arch-part5.gif&quot;&gt;&lt;img src=&quot;https://guimy.tech/db_tutorial/assets/images/arch-part5.gif&quot; alt=&quot;How our program matches up with SQLite architecture&quot; /&gt;&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;/table&gt;

&lt;p&gt;The Pager accesses the page cache and the file. The Table object makes requests for pages through the pager:&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;gi&quot;&gt;+typedef struct {
+  int file_descriptor;
+  uint32_t file_length;
+  void* pages[TABLE_MAX_PAGES];
+} Pager;
+
&lt;/span&gt; typedef struct {
&lt;span class=&quot;gd&quot;&gt;-  void* pages[TABLE_MAX_PAGES];
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+  Pager* pager;
&lt;/span&gt;   uint32_t num_rows;
 } Table;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;I’m renaming &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;new_table()&lt;/code&gt; to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;db_open()&lt;/code&gt; because it now has the effect of opening a connection to the database. By opening a connection, I mean:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;opening the database file&lt;/li&gt;
  &lt;li&gt;initializing a pager data structure&lt;/li&gt;
  &lt;li&gt;initializing a table data structure&lt;/li&gt;
&lt;/ul&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;gd&quot;&gt;-Table* new_table() {
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+Table* db_open(const char* filename) {
+  Pager* pager = pager_open(filename);
+  uint32_t num_rows = pager-&amp;gt;file_length / ROW_SIZE;
+
&lt;/span&gt;   Table* table = malloc(sizeof(Table));
&lt;span class=&quot;gd&quot;&gt;-  table-&amp;gt;num_rows = 0;
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+  table-&amp;gt;pager = pager;
+  table-&amp;gt;num_rows = num_rows;
&lt;/span&gt;
   return table;
 }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;db_open()&lt;/code&gt; in turn calls &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;pager_open()&lt;/code&gt;, which opens the database file and keeps track of its size. It also initializes the page cache to all &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;NULL&lt;/code&gt;s.&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;gi&quot;&gt;+Pager* pager_open(const char* filename) {
+  int fd = open(filename,
+                O_RDWR |      // Read/Write mode
+                    O_CREAT,  // Create file if it does not exist
+                S_IWUSR |     // User write permission
+                    S_IRUSR   // User read permission
+                );
+
+  if (fd == -1) {
+    printf(&quot;Unable to open file\n&quot;);
+    exit(EXIT_FAILURE);
+  }
+
+  off_t file_length = lseek(fd, 0, SEEK_END);
+
+  Pager* pager = malloc(sizeof(Pager));
+  pager-&amp;gt;file_descriptor = fd;
+  pager-&amp;gt;file_length = file_length;
+
+  for (uint32_t i = 0; i &amp;lt; TABLE_MAX_PAGES; i++) {
+    pager-&amp;gt;pages[i] = NULL;
+  }
+
+  return pager;
+}
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Following our new abstraction, we move the logic for fetching a page into its own method:&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt; void* row_slot(Table* table, uint32_t row_num) {
   uint32_t page_num = row_num / ROWS_PER_PAGE;
&lt;span class=&quot;gd&quot;&gt;-  void* page = table-&amp;gt;pages[page_num];
-  if (page == NULL) {
-    // Allocate memory only when we try to access page
-    page = table-&amp;gt;pages[page_num] = malloc(PAGE_SIZE);
-  }
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+  void* page = get_page(table-&amp;gt;pager, page_num);
&lt;/span&gt;   uint32_t row_offset = row_num % ROWS_PER_PAGE;
   uint32_t byte_offset = row_offset * ROW_SIZE;
   return page + byte_offset;
 }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;The &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;get_page()&lt;/code&gt; method has the logic for handling a cache miss. We assume pages are saved one after the other in the database file: Page 0 at offset 0, page 1 at offset 4096, page 2 at offset 8192, etc. If the requested page lies outside the bounds of the file, we know it should be blank, so we just allocate some memory and return it. The page will be added to the file when we flush the cache to disk later.&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;gi&quot;&gt;+void* get_page(Pager* pager, uint32_t page_num) {
+  if (page_num &amp;gt; TABLE_MAX_PAGES) {
+    printf(&quot;Tried to fetch page number out of bounds. %d &amp;gt; %d\n&quot;, page_num,
+           TABLE_MAX_PAGES);
+    exit(EXIT_FAILURE);
+  }
+
+  if (pager-&amp;gt;pages[page_num] == NULL) {
+    // Cache miss. Allocate memory and load from file.
+    void* page = malloc(PAGE_SIZE);
+    uint32_t num_pages = pager-&amp;gt;file_length / PAGE_SIZE;
+
+    // We might save a partial page at the end of the file
+    if (pager-&amp;gt;file_length % PAGE_SIZE) {
+      num_pages += 1;
+    }
+
+    if (page_num &amp;lt;= num_pages) {
+      lseek(pager-&amp;gt;file_descriptor, page_num * PAGE_SIZE, SEEK_SET);
+      ssize_t bytes_read = read(pager-&amp;gt;file_descriptor, page, PAGE_SIZE);
+      if (bytes_read == -1) {
+        printf(&quot;Error reading file: %d\n&quot;, errno);
+        exit(EXIT_FAILURE);
+      }
+    }
+
+    pager-&amp;gt;pages[page_num] = page;
+  }
+
+  return pager-&amp;gt;pages[page_num];
+}
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;For now, we’ll wait to flush the cache to disk until the user closes the connection to the database. When the user exits, we’ll call a new method called &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;db_close()&lt;/code&gt;, which&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;flushes the page cache to disk&lt;/li&gt;
  &lt;li&gt;closes the database file&lt;/li&gt;
  &lt;li&gt;frees the memory for the Pager and Table data structures&lt;/li&gt;
&lt;/ul&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;gi&quot;&gt;+void db_close(Table* table) {
+  Pager* pager = table-&amp;gt;pager;
+  uint32_t num_full_pages = table-&amp;gt;num_rows / ROWS_PER_PAGE;
+
+  for (uint32_t i = 0; i &amp;lt; num_full_pages; i++) {
+    if (pager-&amp;gt;pages[i] == NULL) {
+      continue;
+    }
+    pager_flush(pager, i, PAGE_SIZE);
+    free(pager-&amp;gt;pages[i]);
+    pager-&amp;gt;pages[i] = NULL;
+  }
+
+  // There may be a partial page to write to the end of the file
+  // This should not be needed after we switch to a B-tree
+  uint32_t num_additional_rows = table-&amp;gt;num_rows % ROWS_PER_PAGE;
+  if (num_additional_rows &amp;gt; 0) {
+    uint32_t page_num = num_full_pages;
+    if (pager-&amp;gt;pages[page_num] != NULL) {
+      pager_flush(pager, page_num, num_additional_rows * ROW_SIZE);
+      free(pager-&amp;gt;pages[page_num]);
+      pager-&amp;gt;pages[page_num] = NULL;
+    }
+  }
+
+  int result = close(pager-&amp;gt;file_descriptor);
+  if (result == -1) {
+    printf(&quot;Error closing db file.\n&quot;);
+    exit(EXIT_FAILURE);
+  }
+  for (uint32_t i = 0; i &amp;lt; TABLE_MAX_PAGES; i++) {
+    void* page = pager-&amp;gt;pages[i];
+    if (page) {
+      free(page);
+      pager-&amp;gt;pages[i] = NULL;
+    }
+  }
+  free(pager);
+  free(table);
+}
+
&lt;/span&gt;&lt;span class=&quot;gd&quot;&gt;-MetaCommandResult do_meta_command(InputBuffer* input_buffer) {
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+MetaCommandResult do_meta_command(InputBuffer* input_buffer, Table* table) {
&lt;/span&gt;   if (strcmp(input_buffer-&amp;gt;buffer, &quot;.exit&quot;) == 0) {
&lt;span class=&quot;gi&quot;&gt;+    db_close(table);
&lt;/span&gt;     exit(EXIT_SUCCESS);
   } else {
     return META_COMMAND_UNRECOGNIZED_COMMAND;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;In our current design, the length of the file encodes how many rows are in the database, so we need to write a partial page at the end of the file. That’s why &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;pager_flush()&lt;/code&gt; takes both a page number and a size. It’s not the greatest design, but it will go away pretty quickly when we start implementing the B-tree.&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;gi&quot;&gt;+void pager_flush(Pager* pager, uint32_t page_num, uint32_t size) {
+  if (pager-&amp;gt;pages[page_num] == NULL) {
+    printf(&quot;Tried to flush null page\n&quot;);
+    exit(EXIT_FAILURE);
+  }
+
+  off_t offset = lseek(pager-&amp;gt;file_descriptor, page_num * PAGE_SIZE, SEEK_SET);
+
+  if (offset == -1) {
+    printf(&quot;Error seeking: %d\n&quot;, errno);
+    exit(EXIT_FAILURE);
+  }
+
+  ssize_t bytes_written =
+      write(pager-&amp;gt;file_descriptor, pager-&amp;gt;pages[page_num], size);
+
+  if (bytes_written == -1) {
+    printf(&quot;Error writing: %d\n&quot;, errno);
+    exit(EXIT_FAILURE);
+  }
+}
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Lastly, we need to accept the filename as a command-line argument. Don’t forget to also add the extra argument to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;do_meta_command&lt;/code&gt;:&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt; int main(int argc, char* argv[]) {
&lt;span class=&quot;gd&quot;&gt;-  Table* table = new_table();
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+  if (argc &amp;lt; 2) {
+    printf(&quot;Must supply a database filename.\n&quot;);
+    exit(EXIT_FAILURE);
+  }
+
+  char* filename = argv[1];
+  Table* table = db_open(filename);
+
&lt;/span&gt;   InputBuffer* input_buffer = new_input_buffer();
   while (true) {
     print_prompt();
     read_input(input_buffer);

     if (input_buffer-&amp;gt;buffer[0] == '.') {
&lt;span class=&quot;gd&quot;&gt;-      switch (do_meta_command(input_buffer)) {
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+      switch (do_meta_command(input_buffer, table)) {
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;With these changes, we’re able to close then reopen the database, and our records are still there!&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;~ ./db mydb.db
db &amp;gt; insert 1 cstack foo@bar.com
Executed.
db &amp;gt; insert 2 voltorb volty@example.com
Executed.
db &amp;gt; .exit
~
~ ./db mydb.db
db &amp;gt; select
(1, cstack, foo@bar.com)
(2, voltorb, volty@example.com)
Executed.
db &amp;gt; .exit
~
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;For extra fun, let’s take a look at &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;mydb.db&lt;/code&gt; to see how our data is being stored. I’ll use vim as a hex editor to look at the memory layout of the file:&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;vim mydb.db
:%!xxd
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;table class=&quot;image&quot;&gt;
&lt;caption align=&quot;bottom&quot;&gt;Current File Format&lt;/caption&gt;
&lt;tr&gt;&lt;td&gt;&lt;a href=&quot;https://guimy.tech/db_tutorial/assets/images/file-format.png&quot;&gt;&lt;img src=&quot;https://guimy.tech/db_tutorial/assets/images/file-format.png&quot; alt=&quot;Current File Format&quot; /&gt;&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;/table&gt;

&lt;p&gt;The first four bytes are the id of the first row (4 bytes because we store a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;uint32_t&lt;/code&gt;). It’s stored in little-endian byte order, so the least significant byte comes first (01), followed by the higher-order bytes (00 00 00). We used &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;memcpy()&lt;/code&gt; to copy bytes from our &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Row&lt;/code&gt; struct into the page cache, so that means the struct was laid out in memory in little-endian byte order. That’s an attribute of the machine I compiled the program for. If we wanted to write a database file on my machine, then read it on a big-endian machine, we’d have to change our &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;serialize_row()&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;deserialize_row()&lt;/code&gt; methods to always store and read bytes in the same order.&lt;/p&gt;

&lt;p&gt;The next 33 bytes store the username as a null-terminated string. Apparently “cstack” in ASCII hexadecimal is &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;63 73 74 61 63 6b&lt;/code&gt;, followed by a null character (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;00&lt;/code&gt;). The rest of the 33 bytes are unused.&lt;/p&gt;

&lt;p&gt;The next 256 bytes store the email in the same way. Here we can see some random junk after the terminating null character. This is most likely due to uninitialized memory in our &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Row&lt;/code&gt; struct. We copy the entire 256-byte email buffer into the file, including any bytes after the end of the string. Whatever was in memory when we allocated that struct is still there. But since we use a terminating null character, it has no effect on behavior.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;NOTE&lt;/strong&gt;: If we wanted to ensure that all bytes are initialized, it would
suffice to use &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;strncpy&lt;/code&gt; instead of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;memcpy&lt;/code&gt; while copying the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;username&lt;/code&gt;
and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;email&lt;/code&gt; fields of rows in &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;serialize_row&lt;/code&gt;, like so:&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt; void serialize_row(Row* source, void* destination) {
     memcpy(destination + ID_OFFSET, &amp;amp;(source-&amp;gt;id), ID_SIZE);
&lt;span class=&quot;gd&quot;&gt;-    memcpy(destination + USERNAME_OFFSET, &amp;amp;(source-&amp;gt;username), USERNAME_SIZE);
-    memcpy(destination + EMAIL_OFFSET, &amp;amp;(source-&amp;gt;email), EMAIL_SIZE);
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+    strncpy(destination + USERNAME_OFFSET, source-&amp;gt;username, USERNAME_SIZE);
+    strncpy(destination + EMAIL_OFFSET, source-&amp;gt;email, EMAIL_SIZE);
&lt;/span&gt; }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;conclusion&quot;&gt;Conclusion&lt;/h2&gt;

&lt;p&gt;Alright! We’ve got persistence. It’s not the greatest. For example if you kill the program without typing &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.exit&lt;/code&gt;, you lose your changes. Additionally, we’re writing all pages back to disk, even pages that haven’t changed since we read them from disk. These are issues we can address later.&lt;/p&gt;

&lt;p&gt;Next time we’ll introduce cursors, which should make it easier to implement the B-tree.&lt;/p&gt;

&lt;p&gt;Until then!&lt;/p&gt;

&lt;h2 id=&quot;complete-diff&quot;&gt;Complete Diff&lt;/h2&gt;
&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;gi&quot;&gt;+#include &amp;lt;errno.h&amp;gt;
+#include &amp;lt;fcntl.h&amp;gt;
&lt;/span&gt; #include &amp;lt;stdbool.h&amp;gt;
 #include &amp;lt;stdio.h&amp;gt;
 #include &amp;lt;stdlib.h&amp;gt;
 #include &amp;lt;string.h&amp;gt;
 #include &amp;lt;stdint.h&amp;gt;
&lt;span class=&quot;gi&quot;&gt;+#include &amp;lt;unistd.h&amp;gt;
&lt;/span&gt;
 struct InputBuffer_t {
   char* buffer;
&lt;span class=&quot;p&quot;&gt;@@ -62,9 +65,16 @@&lt;/span&gt; const uint32_t PAGE_SIZE = 4096;
 const uint32_t ROWS_PER_PAGE = PAGE_SIZE / ROW_SIZE;
 const uint32_t TABLE_MAX_ROWS = ROWS_PER_PAGE * TABLE_MAX_PAGES;

+typedef struct {
&lt;span class=&quot;gi&quot;&gt;+  int file_descriptor;
+  uint32_t file_length;
+  void* pages[TABLE_MAX_PAGES];
+} Pager;
+
&lt;/span&gt; typedef struct {
   uint32_t num_rows;
&lt;span class=&quot;gd&quot;&gt;-  void* pages[TABLE_MAX_PAGES];
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+  Pager* pager;
&lt;/span&gt; } Table;

@@ -84,32 +94,81 @@ void deserialize_row(void *source, Row* destination) {
   memcpy(&amp;amp;(destination-&amp;gt;email), source + EMAIL_OFFSET, EMAIL_SIZE);
 }

+void* get_page(Pager* pager, uint32_t page_num) {
&lt;span class=&quot;gi&quot;&gt;+  if (page_num &amp;gt; TABLE_MAX_PAGES) {
+     printf(&quot;Tried to fetch page number out of bounds. %d &amp;gt; %d\n&quot;, page_num,
+     	TABLE_MAX_PAGES);
+     exit(EXIT_FAILURE);
+  }
+
+  if (pager-&amp;gt;pages[page_num] == NULL) {
+     // Cache miss. Allocate memory and load from file.
+     void* page = malloc(PAGE_SIZE);
+     uint32_t num_pages = pager-&amp;gt;file_length / PAGE_SIZE;
+
+     // We might save a partial page at the end of the file
+     if (pager-&amp;gt;file_length % PAGE_SIZE) {
+         num_pages += 1;
+     }
+
+     if (page_num &amp;lt;= num_pages) {
+         lseek(pager-&amp;gt;file_descriptor, page_num * PAGE_SIZE, SEEK_SET);
+         ssize_t bytes_read = read(pager-&amp;gt;file_descriptor, page, PAGE_SIZE);
+         if (bytes_read == -1) {
+     	printf(&quot;Error reading file: %d\n&quot;, errno);
+     	exit(EXIT_FAILURE);
+         }
+     }
+
+     pager-&amp;gt;pages[page_num] = page;
+  }
+
+  return pager-&amp;gt;pages[page_num];
+}
+
&lt;/span&gt; void* row_slot(Table* table, uint32_t row_num) {
   uint32_t page_num = row_num / ROWS_PER_PAGE;
&lt;span class=&quot;gd&quot;&gt;-  void *page = table-&amp;gt;pages[page_num];
-  if (page == NULL) {
-     // Allocate memory only when we try to access page
-     page = table-&amp;gt;pages[page_num] = malloc(PAGE_SIZE);
-  }
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+  void *page = get_page(table-&amp;gt;pager, page_num);
&lt;/span&gt;   uint32_t row_offset = row_num % ROWS_PER_PAGE;
   uint32_t byte_offset = row_offset * ROW_SIZE;
   return page + byte_offset;
 }

-Table* new_table() {
&lt;span class=&quot;gd&quot;&gt;-  Table* table = malloc(sizeof(Table));
-  table-&amp;gt;num_rows = 0;
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+Pager* pager_open(const char* filename) {
+  int fd = open(filename,
+     	  O_RDWR | 	// Read/Write mode
+     	      O_CREAT,	// Create file if it does not exist
+     	  S_IWUSR |	// User write permission
+     	      S_IRUSR	// User read permission
+     	  );
+
+  if (fd == -1) {
+     printf(&quot;Unable to open file\n&quot;);
+     exit(EXIT_FAILURE);
+  }
+
+  off_t file_length = lseek(fd, 0, SEEK_END);
+
+  Pager* pager = malloc(sizeof(Pager));
+  pager-&amp;gt;file_descriptor = fd;
+  pager-&amp;gt;file_length = file_length;
+
&lt;/span&gt;   for (uint32_t i = 0; i &amp;lt; TABLE_MAX_PAGES; i++) {
&lt;span class=&quot;gd&quot;&gt;-     table-&amp;gt;pages[i] = NULL;
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+     pager-&amp;gt;pages[i] = NULL;
&lt;/span&gt;   }
&lt;span class=&quot;gd&quot;&gt;-  return table;
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+
+  return pager;
&lt;/span&gt; }

-void free_table(Table* table) {
&lt;span class=&quot;gd&quot;&gt;-  for (int i = 0; table-&amp;gt;pages[i]; i++) {
-     free(table-&amp;gt;pages[i]);
-  }
-  free(table);
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+Table* db_open(const char* filename) {
+  Pager* pager = pager_open(filename);
+  uint32_t num_rows = pager-&amp;gt;file_length / ROW_SIZE;
+
+  Table* table = malloc(sizeof(Table));
+  table-&amp;gt;pager = pager;
+  table-&amp;gt;num_rows = num_rows;
+
+  return table;
&lt;/span&gt; }

 InputBuffer* new_input_buffer() {
&lt;span class=&quot;p&quot;&gt;@@ -142,10 +201,76 @@&lt;/span&gt; void close_input_buffer(InputBuffer* input_buffer) {
   free(input_buffer);
 }

+void pager_flush(Pager* pager, uint32_t page_num, uint32_t size) {
&lt;span class=&quot;gi&quot;&gt;+  if (pager-&amp;gt;pages[page_num] == NULL) {
+     printf(&quot;Tried to flush null page\n&quot;);
+     exit(EXIT_FAILURE);
+  }
+
+  off_t offset = lseek(pager-&amp;gt;file_descriptor, page_num * PAGE_SIZE,
+     		 SEEK_SET);
+
+  if (offset == -1) {
+     printf(&quot;Error seeking: %d\n&quot;, errno);
+     exit(EXIT_FAILURE);
+  }
+
+  ssize_t bytes_written = write(
+     pager-&amp;gt;file_descriptor, pager-&amp;gt;pages[page_num], size
+     );
+
+  if (bytes_written == -1) {
+     printf(&quot;Error writing: %d\n&quot;, errno);
+     exit(EXIT_FAILURE);
+  }
+}
+
+void db_close(Table* table) {
+  Pager* pager = table-&amp;gt;pager;
+  uint32_t num_full_pages = table-&amp;gt;num_rows / ROWS_PER_PAGE;
+
+  for (uint32_t i = 0; i &amp;lt; num_full_pages; i++) {
+     if (pager-&amp;gt;pages[i] == NULL) {
+         continue;
+     }
+     pager_flush(pager, i, PAGE_SIZE);
+     free(pager-&amp;gt;pages[i]);
+     pager-&amp;gt;pages[i] = NULL;
+  }
+
+  // There may be a partial page to write to the end of the file
+  // This should not be needed after we switch to a B-tree
+  uint32_t num_additional_rows = table-&amp;gt;num_rows % ROWS_PER_PAGE;
+  if (num_additional_rows &amp;gt; 0) {
+     uint32_t page_num = num_full_pages;
+     if (pager-&amp;gt;pages[page_num] != NULL) {
+         pager_flush(pager, page_num, num_additional_rows * ROW_SIZE);
+         free(pager-&amp;gt;pages[page_num]);
+         pager-&amp;gt;pages[page_num] = NULL;
+     }
+  }
+
+  int result = close(pager-&amp;gt;file_descriptor);
+  if (result == -1) {
+     printf(&quot;Error closing db file.\n&quot;);
+     exit(EXIT_FAILURE);
+  }
+  for (uint32_t i = 0; i &amp;lt; TABLE_MAX_PAGES; i++) {
+     void* page = pager-&amp;gt;pages[i];
+     if (page) {
+         free(page);
+         pager-&amp;gt;pages[i] = NULL;
+     }
+  }
+
+  free(pager);
+  free(table);
+}
+
&lt;/span&gt; MetaCommandResult do_meta_command(InputBuffer* input_buffer, Table *table) {
   if (strcmp(input_buffer-&amp;gt;buffer, &quot;.exit&quot;) == 0) {
     close_input_buffer(input_buffer);
&lt;span class=&quot;gd&quot;&gt;-    free_table(table);
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+    db_close(table);
&lt;/span&gt;     exit(EXIT_SUCCESS);
   } else {
     return META_COMMAND_UNRECOGNIZED_COMMAND;
&lt;span class=&quot;p&quot;&gt;@@ -182,6 +308,7 @@&lt;/span&gt; PrepareResult prepare_insert(InputBuffer* input_buffer, Statement* statement) {
     return PREPARE_SUCCESS;

 }
&lt;span class=&quot;gi&quot;&gt;+
&lt;/span&gt; PrepareResult prepare_statement(InputBuffer* input_buffer,
                                 Statement* statement) {
   if (strncmp(input_buffer-&amp;gt;buffer, &quot;insert&quot;, 6) == 0) {
&lt;span class=&quot;p&quot;&gt;@@ -227,7 +354,14 @@&lt;/span&gt; ExecuteResult execute_statement(Statement* statement, Table *table) {
 }

 int main(int argc, char* argv[]) {
&lt;span class=&quot;gd&quot;&gt;-  Table* table = new_table();
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+  if (argc &amp;lt; 2) {
+      printf(&quot;Must supply a database filename.\n&quot;);
+      exit(EXIT_FAILURE);
+  }
+
+  char* filename = argv[1];
+  Table* table = db_open(filename);
+
&lt;/span&gt;   InputBuffer* input_buffer = new_input_buffer();
   while (true) {
     print_prompt();
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;And the diff to our tests:&lt;/p&gt;
&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt; describe 'database' do
&lt;span class=&quot;gi&quot;&gt;+  before do
+    `rm -rf test.db`
+  end
+
&lt;/span&gt;   def run_script(commands)
     raw_output = nil
&lt;span class=&quot;gd&quot;&gt;-    IO.popen(&quot;./db&quot;, &quot;r+&quot;) do |pipe|
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+    IO.popen(&quot;./db test.db&quot;, &quot;r+&quot;) do |pipe|
&lt;/span&gt;       commands.each do |command|
         pipe.puts command
       end
&lt;span class=&quot;p&quot;&gt;@@ -28,6 +32,27 @@&lt;/span&gt; describe 'database' do
     ])
   end

+  it 'keeps data after closing connection' do
&lt;span class=&quot;gi&quot;&gt;+    result1 = run_script([
+      &quot;insert 1 user1 person1@example.com&quot;,
+      &quot;.exit&quot;,
+    ])
+    expect(result1).to match_array([
+      &quot;db &amp;gt; Executed.&quot;,
+      &quot;db &amp;gt; &quot;,
+    ])
+
+    result2 = run_script([
+      &quot;select&quot;,
+      &quot;.exit&quot;,
+    ])
+    expect(result2).to match_array([
+      &quot;db &amp;gt; (1, user1, person1@example.com)&quot;,
+      &quot;Executed.&quot;,
+      &quot;db &amp;gt; &quot;,
+    ])
+  end
+
&lt;/span&gt;   it 'prints error message when table is full' do
     script = (1..1401).map do |i|
       &quot;insert #{i} user#{i} person#{i}@example.com&quot;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
</description>
        <pubDate>Fri, 08 Sep 2017 00:00:00 +0000</pubDate>
        <link>https://guimy.tech/db_tutorial/parts/part5.html</link>
        <guid isPermaLink="true">https://guimy.tech/db_tutorial/parts/part5.html</guid>
      </item>
    
      <item>
        <title>Part 6 - The Cursor Abstraction</title>
        <description>&lt;p&gt;This should be a shorter part than the last one. We’re just going to refactor a bit to make it easier to start the B-Tree implementation.&lt;/p&gt;

&lt;p&gt;We’re going to add a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Cursor&lt;/code&gt; object which represents a location in the table. Things you might want to do with cursors:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Create a cursor at the beginning of the table&lt;/li&gt;
  &lt;li&gt;Create a cursor at the end of the table&lt;/li&gt;
  &lt;li&gt;Access the row the cursor is pointing to&lt;/li&gt;
  &lt;li&gt;Advance the cursor to the next row&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Those are the behaviors we’re going to implement now. Later, we will also want to:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Delete the row pointed to by a cursor&lt;/li&gt;
  &lt;li&gt;Modify the row pointed to by a cursor&lt;/li&gt;
  &lt;li&gt;Search a table for a given ID, and create a cursor pointing to the row with that ID&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Without further ado, here’s the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Cursor&lt;/code&gt; type:&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;gi&quot;&gt;+typedef struct {
+  Table* table;
+  uint32_t row_num;
+  bool end_of_table;  // Indicates a position one past the last element
+} Cursor;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Given our current table data structure, all you need to identify a location in a table is the row number.&lt;/p&gt;

&lt;p&gt;A cursor also has a reference to the table it’s part of (so our cursor functions can take just the cursor as a parameter).&lt;/p&gt;

&lt;p&gt;Finally, it has a boolean called &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;end_of_table&lt;/code&gt;. This is so we can represent a position past the end of the table (which is somewhere we may want to insert a row).&lt;/p&gt;

&lt;p&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;table_start()&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;table_end()&lt;/code&gt; create new cursors:&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;gi&quot;&gt;+Cursor* table_start(Table* table) {
+  Cursor* cursor = malloc(sizeof(Cursor));
+  cursor-&amp;gt;table = table;
+  cursor-&amp;gt;row_num = 0;
+  cursor-&amp;gt;end_of_table = (table-&amp;gt;num_rows == 0);
+
+  return cursor;
+}
+
+Cursor* table_end(Table* table) {
+  Cursor* cursor = malloc(sizeof(Cursor));
+  cursor-&amp;gt;table = table;
+  cursor-&amp;gt;row_num = table-&amp;gt;num_rows;
+  cursor-&amp;gt;end_of_table = true;
+
+  return cursor;
+}
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Our &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;row_slot()&lt;/code&gt; function will become &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;cursor_value()&lt;/code&gt;, which returns a pointer to the position described by the cursor:&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;gd&quot;&gt;-void* row_slot(Table* table, uint32_t row_num) {
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+void* cursor_value(Cursor* cursor) {
+  uint32_t row_num = cursor-&amp;gt;row_num;
&lt;/span&gt;   uint32_t page_num = row_num / ROWS_PER_PAGE;
&lt;span class=&quot;gd&quot;&gt;-  void* page = get_page(table-&amp;gt;pager, page_num);
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+  void* page = get_page(cursor-&amp;gt;table-&amp;gt;pager, page_num);
&lt;/span&gt;   uint32_t row_offset = row_num % ROWS_PER_PAGE;
   uint32_t byte_offset = row_offset * ROW_SIZE;
   return page + byte_offset;
 }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Advancing the cursor in our current table structure is as simple as incrementing the row number. This will be a bit more complicated in a B-tree.&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;gi&quot;&gt;+void cursor_advance(Cursor* cursor) {
+  cursor-&amp;gt;row_num += 1;
+  if (cursor-&amp;gt;row_num &amp;gt;= cursor-&amp;gt;table-&amp;gt;num_rows) {
+    cursor-&amp;gt;end_of_table = true;
+  }
+}
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Finally we can change our “virtual machine” methods to use the cursor abstraction. When inserting a row, we open a cursor at the end of table, write to that cursor location, then close the cursor.&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;   Row* row_to_insert = &amp;amp;(statement-&amp;gt;row_to_insert);
&lt;span class=&quot;gi&quot;&gt;+  Cursor* cursor = table_end(table);
&lt;/span&gt;
-  serialize_row(row_to_insert, row_slot(table, table-&amp;gt;num_rows));
&lt;span class=&quot;gi&quot;&gt;+  serialize_row(row_to_insert, cursor_value(cursor));
&lt;/span&gt;   table-&amp;gt;num_rows += 1;

+  free(cursor);
&lt;span class=&quot;gi&quot;&gt;+
&lt;/span&gt;   return EXECUTE_SUCCESS;
 }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;When selecting all rows in the table, we open a cursor at the start of the table, print the row, then advance the cursor to the next row. Repeat until we’ve reached the end of the table.&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt; ExecuteResult execute_select(Statement* statement, Table* table) {
&lt;span class=&quot;gi&quot;&gt;+  Cursor* cursor = table_start(table);
+
&lt;/span&gt;   Row row;
&lt;span class=&quot;gd&quot;&gt;-  for (uint32_t i = 0; i &amp;lt; table-&amp;gt;num_rows; i++) {
-    deserialize_row(row_slot(table, i), &amp;amp;row);
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+  while (!(cursor-&amp;gt;end_of_table)) {
+    deserialize_row(cursor_value(cursor), &amp;amp;row);
&lt;/span&gt;     print_row(&amp;amp;row);
&lt;span class=&quot;gi&quot;&gt;+    cursor_advance(cursor);
&lt;/span&gt;   }
&lt;span class=&quot;gi&quot;&gt;+
+  free(cursor);
+
&lt;/span&gt;   return EXECUTE_SUCCESS;
 }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Alright, that’s it! Like I said, this was a shorter refactor that should help us as we rewrite our table data structure into a B-Tree. &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;execute_select()&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;execute_insert()&lt;/code&gt; can interact with the table entirely through the cursor without assuming anything about how the table is stored.&lt;/p&gt;

&lt;p&gt;Here’s the complete diff to this part:&lt;/p&gt;
&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;p&quot;&gt;@@ -78,6 +78,13 @@&lt;/span&gt; struct {
 } Table;

+typedef struct {
&lt;span class=&quot;gi&quot;&gt;+  Table* table;
+  uint32_t row_num;
+  bool end_of_table; // Indicates a position one past the last element
+} Cursor;
+
&lt;/span&gt; void print_row(Row* row) {
     printf(&quot;(%d, %s, %s)\n&quot;, row-&amp;gt;id, row-&amp;gt;username, row-&amp;gt;email);
 }
&lt;span class=&quot;p&quot;&gt;@@ -126,12 +133,38 @@&lt;/span&gt; void* get_page(Pager* pager, uint32_t page_num) {
     return pager-&amp;gt;pages[page_num];
 }

-void* row_slot(Table* table, uint32_t row_num) {
&lt;span class=&quot;gd&quot;&gt;-  uint32_t page_num = row_num / ROWS_PER_PAGE;
-  void *page = get_page(table-&amp;gt;pager, page_num);
-  uint32_t row_offset = row_num % ROWS_PER_PAGE;
-  uint32_t byte_offset = row_offset * ROW_SIZE;
-  return page + byte_offset;
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+Cursor* table_start(Table* table) {
+  Cursor* cursor = malloc(sizeof(Cursor));
+  cursor-&amp;gt;table = table;
+  cursor-&amp;gt;row_num = 0;
+  cursor-&amp;gt;end_of_table = (table-&amp;gt;num_rows == 0);
+
+  return cursor;
+}
+
+Cursor* table_end(Table* table) {
+  Cursor* cursor = malloc(sizeof(Cursor));
+  cursor-&amp;gt;table = table;
+  cursor-&amp;gt;row_num = table-&amp;gt;num_rows;
+  cursor-&amp;gt;end_of_table = true;
+
+  return cursor;
+}
+
+void* cursor_value(Cursor* cursor) {
+  uint32_t row_num = cursor-&amp;gt;row_num;
+  uint32_t page_num = row_num / ROWS_PER_PAGE;
+  void *page = get_page(cursor-&amp;gt;table-&amp;gt;pager, page_num);
+  uint32_t row_offset = row_num % ROWS_PER_PAGE;
+  uint32_t byte_offset = row_offset * ROW_SIZE;
+  return page + byte_offset;
+}
+
+void cursor_advance(Cursor* cursor) {
+  cursor-&amp;gt;row_num += 1;
+  if (cursor-&amp;gt;row_num &amp;gt;= cursor-&amp;gt;table-&amp;gt;num_rows) {
+    cursor-&amp;gt;end_of_table = true;
+  }
&lt;/span&gt; }

 Pager* pager_open(const char* filename) {
&lt;span class=&quot;p&quot;&gt;@@ -327,19 +360,28 @@&lt;/span&gt; ExecuteResult execute_insert(Statement* statement, Table* table) {
     }

   Row* row_to_insert = &amp;amp;(statement-&amp;gt;row_to_insert);
&lt;span class=&quot;gi&quot;&gt;+  Cursor* cursor = table_end(table);
&lt;/span&gt;
-  serialize_row(row_to_insert, row_slot(table, table-&amp;gt;num_rows));
&lt;span class=&quot;gi&quot;&gt;+  serialize_row(row_to_insert, cursor_value(cursor));
&lt;/span&gt;   table-&amp;gt;num_rows += 1;

+  free(cursor);
&lt;span class=&quot;gi&quot;&gt;+
&lt;/span&gt;   return EXECUTE_SUCCESS;
 }

 ExecuteResult execute_select(Statement* statement, Table* table) {
&lt;span class=&quot;gi&quot;&gt;+  Cursor* cursor = table_start(table);
+
&lt;/span&gt;   Row row;
&lt;span class=&quot;gd&quot;&gt;-  for (uint32_t i = 0; i &amp;lt; table-&amp;gt;num_rows; i++) {
-     deserialize_row(row_slot(table, i), &amp;amp;row);
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+  while (!(cursor-&amp;gt;end_of_table)) {
+     deserialize_row(cursor_value(cursor), &amp;amp;row);
&lt;/span&gt;      print_row(&amp;amp;row);
&lt;span class=&quot;gi&quot;&gt;+     cursor_advance(cursor);
&lt;/span&gt;   }
&lt;span class=&quot;gi&quot;&gt;+
+  free(cursor);
+
&lt;/span&gt;   return EXECUTE_SUCCESS;
 }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
</description>
        <pubDate>Sun, 10 Sep 2017 00:00:00 +0000</pubDate>
        <link>https://guimy.tech/db_tutorial/parts/part6.html</link>
        <guid isPermaLink="true">https://guimy.tech/db_tutorial/parts/part6.html</guid>
      </item>
    
      <item>
        <title>Part 7 - Introduction to the B-Tree</title>
        <description>&lt;p&gt;The B-Tree is the data structure SQLite uses to represent both tables and indexes, so it’s a pretty central idea. This article will just introduce the data structure, so it won’t have any code.&lt;/p&gt;

&lt;p&gt;Why is a tree a good data structure for a database?&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Searching for a particular value is fast (logarithmic time)&lt;/li&gt;
  &lt;li&gt;Inserting / deleting a value you’ve already found is fast (constant-ish time to rebalance)&lt;/li&gt;
  &lt;li&gt;Traversing a range of values is fast (unlike a hash map)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;A B-Tree is different from a binary tree (the “B” probably stands for the inventor’s name, but could also stand for “balanced”). Here’s an example B-Tree:&lt;/p&gt;

&lt;table class=&quot;image&quot;&gt;
&lt;caption align=&quot;bottom&quot;&gt;example B-Tree (https://en.wikipedia.org/wiki/File:B-tree.svg)&lt;/caption&gt;
&lt;tr&gt;&lt;td&gt;&lt;a href=&quot;https://guimy.tech/db_tutorial/assets/images/B-tree.png&quot;&gt;&lt;img src=&quot;https://guimy.tech/db_tutorial/assets/images/B-tree.png&quot; alt=&quot;example B-Tree (https://en.wikipedia.org/wiki/File:B-tree.svg)&quot; /&gt;&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;/table&gt;

&lt;p&gt;Unlike a binary tree, each node in a B-Tree can have more than 2 children. Each node can have up to m children, where m is called the tree’s “order”. To keep the tree mostly balanced, we also say nodes have to have at least m/2 children (rounded up).&lt;/p&gt;

&lt;p&gt;Exceptions:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Leaf nodes have 0 children&lt;/li&gt;
  &lt;li&gt;The root node can have fewer than m children but must have at least 2&lt;/li&gt;
  &lt;li&gt;If the root node is a leaf node (the only node), it still has 0 children&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The picture from above is a B-Tree, which SQLite uses to store indexes. To store tables, SQLites uses a variation called a B+ tree.&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt; &lt;/th&gt;
      &lt;th&gt;B-tree&lt;/th&gt;
      &lt;th&gt;B+ tree&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Pronounced&lt;/td&gt;
      &lt;td&gt;“Bee Tree”&lt;/td&gt;
      &lt;td&gt;“Bee Plus Tree”&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Used to store&lt;/td&gt;
      &lt;td&gt;Indexes&lt;/td&gt;
      &lt;td&gt;Tables&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Internal nodes store keys&lt;/td&gt;
      &lt;td&gt;Yes&lt;/td&gt;
      &lt;td&gt;Yes&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Internal nodes store values&lt;/td&gt;
      &lt;td&gt;Yes&lt;/td&gt;
      &lt;td&gt;No&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Number of children per node&lt;/td&gt;
      &lt;td&gt;Less&lt;/td&gt;
      &lt;td&gt;More&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Internal nodes vs. leaf nodes&lt;/td&gt;
      &lt;td&gt;Same structure&lt;/td&gt;
      &lt;td&gt;Different structure&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Until we get to implementing indexes, I’m going to talk solely about B+ trees, but I’ll just refer to it as a B-tree or a btree.&lt;/p&gt;

&lt;p&gt;Nodes with children are called “internal” nodes. Internal nodes and leaf nodes are structured differently:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;For an order-m tree…&lt;/th&gt;
      &lt;th&gt;Internal Node&lt;/th&gt;
      &lt;th&gt;Leaf Node&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Stores&lt;/td&gt;
      &lt;td&gt;keys and pointers to children&lt;/td&gt;
      &lt;td&gt;keys and values&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Number of keys&lt;/td&gt;
      &lt;td&gt;up to m-1&lt;/td&gt;
      &lt;td&gt;as many as will fit&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Number of pointers&lt;/td&gt;
      &lt;td&gt;number of keys + 1&lt;/td&gt;
      &lt;td&gt;none&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Number of values&lt;/td&gt;
      &lt;td&gt;none&lt;/td&gt;
      &lt;td&gt;number of keys&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Key purpose&lt;/td&gt;
      &lt;td&gt;used for routing&lt;/td&gt;
      &lt;td&gt;paired with value&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Stores values?&lt;/td&gt;
      &lt;td&gt;No&lt;/td&gt;
      &lt;td&gt;Yes&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Let’s work through an example to see how a B-tree grows as you insert elements into it. To keep things simple, the tree will be order 3. That means:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;up to 3 children per internal node&lt;/li&gt;
  &lt;li&gt;up to 2 keys per internal node&lt;/li&gt;
  &lt;li&gt;at least 2 children per internal node&lt;/li&gt;
  &lt;li&gt;at least 1 key per internal node&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;An empty B-tree has a single node: the root node. The root node starts as a leaf node with zero key/value pairs:&lt;/p&gt;

&lt;table class=&quot;image&quot;&gt;
&lt;caption align=&quot;bottom&quot;&gt;empty btree&lt;/caption&gt;
&lt;tr&gt;&lt;td&gt;&lt;a href=&quot;https://guimy.tech/db_tutorial/assets/images/btree1.png&quot;&gt;&lt;img src=&quot;https://guimy.tech/db_tutorial/assets/images/btree1.png&quot; alt=&quot;empty btree&quot; /&gt;&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;/table&gt;

&lt;p&gt;If we insert a couple key/value pairs, they are stored in the leaf node in sorted order.&lt;/p&gt;

&lt;table class=&quot;image&quot;&gt;
&lt;caption align=&quot;bottom&quot;&gt;one-node btree&lt;/caption&gt;
&lt;tr&gt;&lt;td&gt;&lt;a href=&quot;https://guimy.tech/db_tutorial/assets/images/btree2.png&quot;&gt;&lt;img src=&quot;https://guimy.tech/db_tutorial/assets/images/btree2.png&quot; alt=&quot;one-node btree&quot; /&gt;&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;/table&gt;

&lt;p&gt;Let’s say that the capacity of a leaf node is two key/value pairs. When we insert another, we have to split the leaf node and put half the pairs in each node. Both nodes become children of a new internal node which will now be the root node.&lt;/p&gt;

&lt;table class=&quot;image&quot;&gt;
&lt;caption align=&quot;bottom&quot;&gt;two-level btree&lt;/caption&gt;
&lt;tr&gt;&lt;td&gt;&lt;a href=&quot;https://guimy.tech/db_tutorial/assets/images/btree3.png&quot;&gt;&lt;img src=&quot;https://guimy.tech/db_tutorial/assets/images/btree3.png&quot; alt=&quot;two-level btree&quot; /&gt;&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;/table&gt;

&lt;p&gt;The internal node has 1 key and 2 pointers to child nodes. If we want to look up a key that is less than or equal to 5, we look in the left child. If we want to look up a key greater than 5, we look in the right child.&lt;/p&gt;

&lt;p&gt;Now let’s insert the key “2”. First we look up which leaf node it would be in if it was present, and we arrive at the left leaf node. The node is full, so we split the leaf node and create a new entry in the parent node.&lt;/p&gt;

&lt;table class=&quot;image&quot;&gt;
&lt;caption align=&quot;bottom&quot;&gt;four-node btree&lt;/caption&gt;
&lt;tr&gt;&lt;td&gt;&lt;a href=&quot;https://guimy.tech/db_tutorial/assets/images/btree4.png&quot;&gt;&lt;img src=&quot;https://guimy.tech/db_tutorial/assets/images/btree4.png&quot; alt=&quot;four-node btree&quot; /&gt;&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;/table&gt;

&lt;p&gt;Let’s keep adding keys. 18 and 21. We get to the point where we have to split again, but there’s no room in the parent node for another key/pointer pair.&lt;/p&gt;

&lt;table class=&quot;image&quot;&gt;
&lt;caption align=&quot;bottom&quot;&gt;no room in internal node&lt;/caption&gt;
&lt;tr&gt;&lt;td&gt;&lt;a href=&quot;https://guimy.tech/db_tutorial/assets/images/btree5.png&quot;&gt;&lt;img src=&quot;https://guimy.tech/db_tutorial/assets/images/btree5.png&quot; alt=&quot;no room in internal node&quot; /&gt;&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;/table&gt;

&lt;p&gt;The solution is to split the root node into two internal nodes, then create new root node to be their parent.&lt;/p&gt;

&lt;table class=&quot;image&quot;&gt;
&lt;caption align=&quot;bottom&quot;&gt;three-level btree&lt;/caption&gt;
&lt;tr&gt;&lt;td&gt;&lt;a href=&quot;https://guimy.tech/db_tutorial/assets/images/btree6.png&quot;&gt;&lt;img src=&quot;https://guimy.tech/db_tutorial/assets/images/btree6.png&quot; alt=&quot;three-level btree&quot; /&gt;&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;/table&gt;

&lt;p&gt;The depth of the tree only increases when we split the root node. Every leaf node has the same depth and close to the same number of key/value pairs, so the tree remains balanced and quick to search.&lt;/p&gt;

&lt;p&gt;I’m going to hold off on discussion of deleting keys from the tree until after we’ve implemented insertion.&lt;/p&gt;

&lt;p&gt;When we implement this data structure, each node will correspond to one page. The root node will exist in page 0. Child pointers will simply be the page number that contains the child node.&lt;/p&gt;

&lt;p&gt;Next time, we start implementing the btree!&lt;/p&gt;
</description>
        <pubDate>Sat, 23 Sep 2017 00:00:00 +0000</pubDate>
        <link>https://guimy.tech/db_tutorial/parts/part7.html</link>
        <guid isPermaLink="true">https://guimy.tech/db_tutorial/parts/part7.html</guid>
      </item>
    
      <item>
        <title>Part 8 - B-Tree Leaf Node Format</title>
        <description>&lt;p&gt;We’re changing the format of our table from an unsorted array of rows to a B-Tree. This is a pretty big change that is going to take multiple articles to implement. By the end of this article, we’ll define the layout of a leaf node and support inserting key/value pairs into a single-node tree. But first, let’s recap the reasons for switching to a tree structure.&lt;/p&gt;

&lt;h2 id=&quot;alternative-table-formats&quot;&gt;Alternative Table Formats&lt;/h2&gt;

&lt;p&gt;With the current format, each page stores only rows (no metadata) so it is pretty space efficient. Insertion is also fast because we just append to the end. However, finding a particular row can only be done by scanning the entire table. And if we want to delete a row, we have to fill in the hole by moving every row that comes after it.&lt;/p&gt;

&lt;p&gt;If we stored the table as an array, but kept rows sorted by id, we could use binary search to find a particular id. However, insertion would be slow because we would have to move a lot of rows to make space.&lt;/p&gt;

&lt;p&gt;Instead, we’re going with a tree structure. Each node in the tree can contain a variable number of rows, so we have to store some information in each node to keep track of how many rows it contains. Plus there is the storage overhead of all the internal nodes which don’t store any rows. In exchange for a larger database file, we get fast insertion, deletion and lookup.&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt; &lt;/th&gt;
      &lt;th&gt;Unsorted Array of rows&lt;/th&gt;
      &lt;th&gt;Sorted Array of rows&lt;/th&gt;
      &lt;th&gt;Tree of nodes&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Pages contain&lt;/td&gt;
      &lt;td&gt;only data&lt;/td&gt;
      &lt;td&gt;only data&lt;/td&gt;
      &lt;td&gt;metadata, primary keys, and data&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Rows per page&lt;/td&gt;
      &lt;td&gt;more&lt;/td&gt;
      &lt;td&gt;more&lt;/td&gt;
      &lt;td&gt;fewer&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Insertion&lt;/td&gt;
      &lt;td&gt;O(1)&lt;/td&gt;
      &lt;td&gt;O(n)&lt;/td&gt;
      &lt;td&gt;O(log(n))&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Deletion&lt;/td&gt;
      &lt;td&gt;O(n)&lt;/td&gt;
      &lt;td&gt;O(n)&lt;/td&gt;
      &lt;td&gt;O(log(n))&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Lookup by id&lt;/td&gt;
      &lt;td&gt;O(n)&lt;/td&gt;
      &lt;td&gt;O(log(n))&lt;/td&gt;
      &lt;td&gt;O(log(n))&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;h2 id=&quot;node-header-format&quot;&gt;Node Header Format&lt;/h2&gt;

&lt;p&gt;Leaf nodes and internal nodes have different layouts. Let’s make an enum to keep track of node type:&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;gi&quot;&gt;+typedef enum { NODE_INTERNAL, NODE_LEAF } NodeType;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Each node will correspond to one page. Internal nodes will point to their children by storing the page number that stores the child. The btree asks the pager for a particular page number and gets back a pointer into the page cache. Pages are stored in the database file one after the other in order of page number.&lt;/p&gt;

&lt;p&gt;Nodes need to store some metadata in a header at the beginning of the page. Every node will store what type of node it is, whether or not it is the root node, and a pointer to its parent (to allow finding a node’s siblings). I define constants for the size and offset of every header field:&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;gi&quot;&gt;+/*
+ * Common Node Header Layout
+ */
+const uint32_t NODE_TYPE_SIZE = sizeof(uint8_t);
+const uint32_t NODE_TYPE_OFFSET = 0;
+const uint32_t IS_ROOT_SIZE = sizeof(uint8_t);
+const uint32_t IS_ROOT_OFFSET = NODE_TYPE_SIZE;
+const uint32_t PARENT_POINTER_SIZE = sizeof(uint32_t);
+const uint32_t PARENT_POINTER_OFFSET = IS_ROOT_OFFSET + IS_ROOT_SIZE;
+const uint8_t COMMON_NODE_HEADER_SIZE =
+    NODE_TYPE_SIZE + IS_ROOT_SIZE + PARENT_POINTER_SIZE;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;leaf-node-format&quot;&gt;Leaf Node Format&lt;/h2&gt;

&lt;p&gt;In addition to these common header fields, leaf nodes need to store how many “cells” they contain. A cell is a key/value pair.&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;gi&quot;&gt;+/*
+ * Leaf Node Header Layout
+ */
+const uint32_t LEAF_NODE_NUM_CELLS_SIZE = sizeof(uint32_t);
+const uint32_t LEAF_NODE_NUM_CELLS_OFFSET = COMMON_NODE_HEADER_SIZE;
+const uint32_t LEAF_NODE_HEADER_SIZE =
+    COMMON_NODE_HEADER_SIZE + LEAF_NODE_NUM_CELLS_SIZE;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;The body of a leaf node is an array of cells. Each cell is a key followed by a value (a serialized row).&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;gi&quot;&gt;+/*
+ * Leaf Node Body Layout
+ */
+const uint32_t LEAF_NODE_KEY_SIZE = sizeof(uint32_t);
+const uint32_t LEAF_NODE_KEY_OFFSET = 0;
+const uint32_t LEAF_NODE_VALUE_SIZE = ROW_SIZE;
+const uint32_t LEAF_NODE_VALUE_OFFSET =
+    LEAF_NODE_KEY_OFFSET + LEAF_NODE_KEY_SIZE;
+const uint32_t LEAF_NODE_CELL_SIZE = LEAF_NODE_KEY_SIZE + LEAF_NODE_VALUE_SIZE;
+const uint32_t LEAF_NODE_SPACE_FOR_CELLS = PAGE_SIZE - LEAF_NODE_HEADER_SIZE;
+const uint32_t LEAF_NODE_MAX_CELLS =
+    LEAF_NODE_SPACE_FOR_CELLS / LEAF_NODE_CELL_SIZE;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Based on these constants, here’s what the layout of a leaf node looks like currently:&lt;/p&gt;

&lt;table class=&quot;image&quot;&gt;
&lt;caption align=&quot;bottom&quot;&gt;Our leaf node format&lt;/caption&gt;
&lt;tr&gt;&lt;td&gt;&lt;a href=&quot;https://guimy.tech/db_tutorial/assets/images/leaf-node-format.png&quot;&gt;&lt;img src=&quot;https://guimy.tech/db_tutorial/assets/images/leaf-node-format.png&quot; alt=&quot;Our leaf node format&quot; /&gt;&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;/table&gt;

&lt;p&gt;It’s a little space inefficient to use an entire byte per boolean value in the header, but this makes it easier to write code to access those values.&lt;/p&gt;

&lt;p&gt;Also notice that there’s some wasted space at the end. We store as many cells as we can after the header, but the leftover space can’t hold an entire cell. We leave it empty to avoid splitting cells between nodes.&lt;/p&gt;

&lt;h2 id=&quot;accessing-leaf-node-fields&quot;&gt;Accessing Leaf Node Fields&lt;/h2&gt;

&lt;p&gt;The code to access keys, values and metadata all involve pointer arithmetic using the constants we just defined.&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;gi&quot;&gt;+uint32_t* leaf_node_num_cells(void* node) {
+  return node + LEAF_NODE_NUM_CELLS_OFFSET;
+}
+
+void* leaf_node_cell(void* node, uint32_t cell_num) {
+  return node + LEAF_NODE_HEADER_SIZE + cell_num * LEAF_NODE_CELL_SIZE;
+}
+
+uint32_t* leaf_node_key(void* node, uint32_t cell_num) {
+  return leaf_node_cell(node, cell_num);
+}
+
+void* leaf_node_value(void* node, uint32_t cell_num) {
+  return leaf_node_cell(node, cell_num) + LEAF_NODE_KEY_SIZE;
+}
+
+void initialize_leaf_node(void* node) { *leaf_node_num_cells(node) = 0; }
+
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;These methods return a pointer to the value in question, so they can be used both as a getter and a setter.&lt;/p&gt;

&lt;h2 id=&quot;changes-to-pager-and-table-objects&quot;&gt;Changes to Pager and Table Objects&lt;/h2&gt;

&lt;p&gt;Every node is going to take up exactly one page, even if it’s not full. That means our pager no longer needs to support reading/writing partial pages.&lt;/p&gt;
&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;gd&quot;&gt;-void pager_flush(Pager* pager, uint32_t page_num, uint32_t size) {
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+void pager_flush(Pager* pager, uint32_t page_num) {
&lt;/span&gt;   if (pager-&amp;gt;pages[page_num] == NULL) {
     printf(&quot;Tried to flush null page\n&quot;);
     exit(EXIT_FAILURE);
&lt;span class=&quot;p&quot;&gt;@@ -242,7 +337,7 @@&lt;/span&gt; void pager_flush(Pager* pager, uint32_t page_num, uint32_t size) {
   }
 
   ssize_t bytes_written =
&lt;span class=&quot;gd&quot;&gt;-      write(pager-&amp;gt;file_descriptor, pager-&amp;gt;pages[page_num], size);
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+      write(pager-&amp;gt;file_descriptor, pager-&amp;gt;pages[page_num], PAGE_SIZE);
&lt;/span&gt; 
   if (bytes_written == -1) {
     printf(&quot;Error writing: %d\n&quot;, errno);
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt; void db_close(Table* table) {
   Pager* pager = table-&amp;gt;pager;
&lt;span class=&quot;gd&quot;&gt;-  uint32_t num_full_pages = table-&amp;gt;num_rows / ROWS_PER_PAGE;
&lt;/span&gt; 
&lt;span class=&quot;gd&quot;&gt;-  for (uint32_t i = 0; i &amp;lt; num_full_pages; i++) {
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+  for (uint32_t i = 0; i &amp;lt; pager-&amp;gt;num_pages; i++) {
&lt;/span&gt;     if (pager-&amp;gt;pages[i] == NULL) {
       continue;
     }
&lt;span class=&quot;gd&quot;&gt;-    pager_flush(pager, i, PAGE_SIZE);
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+    pager_flush(pager, i);
&lt;/span&gt;     free(pager-&amp;gt;pages[i]);
     pager-&amp;gt;pages[i] = NULL;
   }
 
&lt;span class=&quot;gd&quot;&gt;-  // There may be a partial page to write to the end of the file
-  // This should not be needed after we switch to a B-tree
-  uint32_t num_additional_rows = table-&amp;gt;num_rows % ROWS_PER_PAGE;
-  if (num_additional_rows &amp;gt; 0) {
-    uint32_t page_num = num_full_pages;
-    if (pager-&amp;gt;pages[page_num] != NULL) {
-      pager_flush(pager, page_num, num_additional_rows * ROW_SIZE);
-      free(pager-&amp;gt;pages[page_num]);
-      pager-&amp;gt;pages[page_num] = NULL;
-    }
-  }
-
&lt;/span&gt;   int result = close(pager-&amp;gt;file_descriptor);
   if (result == -1) {
     printf(&quot;Error closing db file.\n&quot;);
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Now it makes more sense to store the number of pages in our database rather than the number of rows. The number of pages should be associated with the pager object, not the table, since it’s the number of pages used by the database, not a particular table. A btree is identified by its root node page number, so the table object needs to keep track of that.&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt; const uint32_t PAGE_SIZE = 4096;
 const uint32_t TABLE_MAX_PAGES = 100;
&lt;span class=&quot;gd&quot;&gt;-const uint32_t ROWS_PER_PAGE = PAGE_SIZE / ROW_SIZE;
-const uint32_t TABLE_MAX_ROWS = ROWS_PER_PAGE * TABLE_MAX_PAGES;
&lt;/span&gt; 
 typedef struct {
   int file_descriptor;
   uint32_t file_length;
&lt;span class=&quot;gi&quot;&gt;+  uint32_t num_pages;
&lt;/span&gt;   void* pages[TABLE_MAX_PAGES];
 } Pager;
 
 typedef struct {
   Pager* pager;
&lt;span class=&quot;gd&quot;&gt;-  uint32_t num_rows;
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+  uint32_t root_page_num;
&lt;/span&gt; } Table;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;p&quot;&gt;@@ -127,6 +200,10 @@&lt;/span&gt; void* get_page(Pager* pager, uint32_t page_num) {
     }
 
     pager-&amp;gt;pages[page_num] = page;
&lt;span class=&quot;gi&quot;&gt;+
+    if (page_num &amp;gt;= pager-&amp;gt;num_pages) {
+      pager-&amp;gt;num_pages = page_num + 1;
+    }
&lt;/span&gt;   }
 
   return pager-&amp;gt;pages[page_num];
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;p&quot;&gt;@@ -184,6 +269,12 @@&lt;/span&gt; Pager* pager_open(const char* filename) {
   Pager* pager = malloc(sizeof(Pager));
   pager-&amp;gt;file_descriptor = fd;
   pager-&amp;gt;file_length = file_length;
&lt;span class=&quot;gi&quot;&gt;+  pager-&amp;gt;num_pages = (file_length / PAGE_SIZE);
+
+  if (file_length % PAGE_SIZE != 0) {
+    printf(&quot;Db file is not a whole number of pages. Corrupt file.\n&quot;);
+    exit(EXIT_FAILURE);
+  }
&lt;/span&gt; 
   for (uint32_t i = 0; i &amp;lt; TABLE_MAX_PAGES; i++) {
     pager-&amp;gt;pages[i] = NULL;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;changes-to-the-cursor-object&quot;&gt;Changes to the Cursor Object&lt;/h2&gt;

&lt;p&gt;A cursor represents a position in the table. When our table was a simple array of rows, we could access a row given just the row number. Now that it’s a tree, we identify a position by the page number of the node, and the cell number within that node.&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt; typedef struct {
   Table* table;
&lt;span class=&quot;gd&quot;&gt;-  uint32_t row_num;
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+  uint32_t page_num;
+  uint32_t cell_num;
&lt;/span&gt;   bool end_of_table;  // Indicates a position one past the last element
 } Cursor;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt; Cursor* table_start(Table* table) {
   Cursor* cursor = malloc(sizeof(Cursor));
   cursor-&amp;gt;table = table;
&lt;span class=&quot;gd&quot;&gt;-  cursor-&amp;gt;row_num = 0;
-  cursor-&amp;gt;end_of_table = (table-&amp;gt;num_rows == 0);
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+  cursor-&amp;gt;page_num = table-&amp;gt;root_page_num;
+  cursor-&amp;gt;cell_num = 0;
+
+  void* root_node = get_page(table-&amp;gt;pager, table-&amp;gt;root_page_num);
+  uint32_t num_cells = *leaf_node_num_cells(root_node);
+  cursor-&amp;gt;end_of_table = (num_cells == 0);
&lt;/span&gt; 
   return cursor;
 }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt; Cursor* table_end(Table* table) {
   Cursor* cursor = malloc(sizeof(Cursor));
   cursor-&amp;gt;table = table;
&lt;span class=&quot;gd&quot;&gt;-  cursor-&amp;gt;row_num = table-&amp;gt;num_rows;
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+  cursor-&amp;gt;page_num = table-&amp;gt;root_page_num;
+
+  void* root_node = get_page(table-&amp;gt;pager, table-&amp;gt;root_page_num);
+  uint32_t num_cells = *leaf_node_num_cells(root_node);
+  cursor-&amp;gt;cell_num = num_cells;
&lt;/span&gt;   cursor-&amp;gt;end_of_table = true;
 
   return cursor;
 }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt; void* cursor_value(Cursor* cursor) {
&lt;span class=&quot;gd&quot;&gt;-  uint32_t row_num = cursor-&amp;gt;row_num;
-  uint32_t page_num = row_num / ROWS_PER_PAGE;
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+  uint32_t page_num = cursor-&amp;gt;page_num;
&lt;/span&gt;   void* page = get_page(cursor-&amp;gt;table-&amp;gt;pager, page_num);
&lt;span class=&quot;gd&quot;&gt;-  uint32_t row_offset = row_num % ROWS_PER_PAGE;
-  uint32_t byte_offset = row_offset * ROW_SIZE;
-  return page + byte_offset;
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+  return leaf_node_value(page, cursor-&amp;gt;cell_num);
&lt;/span&gt; }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt; void cursor_advance(Cursor* cursor) {
&lt;span class=&quot;gd&quot;&gt;-  cursor-&amp;gt;row_num += 1;
-  if (cursor-&amp;gt;row_num &amp;gt;= cursor-&amp;gt;table-&amp;gt;num_rows) {
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+  uint32_t page_num = cursor-&amp;gt;page_num;
+  void* node = get_page(cursor-&amp;gt;table-&amp;gt;pager, page_num);
+
+  cursor-&amp;gt;cell_num += 1;
+  if (cursor-&amp;gt;cell_num &amp;gt;= (*leaf_node_num_cells(node))) {
&lt;/span&gt;     cursor-&amp;gt;end_of_table = true;
   }
 }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;insertion-into-a-leaf-node&quot;&gt;Insertion Into a Leaf Node&lt;/h2&gt;

&lt;p&gt;In this article we’re only going to implement enough to get a single-node tree. Recall from last article that a tree starts out as an empty leaf node:&lt;/p&gt;

&lt;table class=&quot;image&quot;&gt;
&lt;caption align=&quot;bottom&quot;&gt;empty btree&lt;/caption&gt;
&lt;tr&gt;&lt;td&gt;&lt;a href=&quot;https://guimy.tech/db_tutorial/assets/images/btree1.png&quot;&gt;&lt;img src=&quot;https://guimy.tech/db_tutorial/assets/images/btree1.png&quot; alt=&quot;empty btree&quot; /&gt;&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;/table&gt;

&lt;p&gt;Key/value pairs can be added until the leaf node is full:&lt;/p&gt;

&lt;table class=&quot;image&quot;&gt;
&lt;caption align=&quot;bottom&quot;&gt;one-node btree&lt;/caption&gt;
&lt;tr&gt;&lt;td&gt;&lt;a href=&quot;https://guimy.tech/db_tutorial/assets/images/btree2.png&quot;&gt;&lt;img src=&quot;https://guimy.tech/db_tutorial/assets/images/btree2.png&quot; alt=&quot;one-node btree&quot; /&gt;&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;/table&gt;

&lt;p&gt;When we open the database for the first time, the database file will be empty, so we initialize page 0 to be an empty leaf node (the root node):&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt; Table* db_open(const char* filename) {
   Pager* pager = pager_open(filename);
&lt;span class=&quot;gd&quot;&gt;-  uint32_t num_rows = pager-&amp;gt;file_length / ROW_SIZE;
&lt;/span&gt; 
   Table* table = malloc(sizeof(Table));
   table-&amp;gt;pager = pager;
&lt;span class=&quot;gd&quot;&gt;-  table-&amp;gt;num_rows = num_rows;
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+  table-&amp;gt;root_page_num = 0;
+
+  if (pager-&amp;gt;num_pages == 0) {
+    // New database file. Initialize page 0 as leaf node.
+    void* root_node = get_page(pager, 0);
+    initialize_leaf_node(root_node);
+  }
&lt;/span&gt; 
   return table;
 }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Next we’ll make a function for inserting a key/value pair into a leaf node. It will take a cursor as input to represent the position where the pair should be inserted.&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;gi&quot;&gt;+void leaf_node_insert(Cursor* cursor, uint32_t key, Row* value) {
+  void* node = get_page(cursor-&amp;gt;table-&amp;gt;pager, cursor-&amp;gt;page_num);
+
+  uint32_t num_cells = *leaf_node_num_cells(node);
+  if (num_cells &amp;gt;= LEAF_NODE_MAX_CELLS) {
+    // Node full
+    printf(&quot;Need to implement splitting a leaf node.\n&quot;);
+    exit(EXIT_FAILURE);
+  }
+
+  if (cursor-&amp;gt;cell_num &amp;lt; num_cells) {
+    // Make room for new cell
+    for (uint32_t i = num_cells; i &amp;gt; cursor-&amp;gt;cell_num; i--) {
+      memcpy(leaf_node_cell(node, i), leaf_node_cell(node, i - 1),
+             LEAF_NODE_CELL_SIZE);
+    }
+  }
+
+  *(leaf_node_num_cells(node)) += 1;
+  *(leaf_node_key(node, cursor-&amp;gt;cell_num)) = key;
+  serialize_row(value, leaf_node_value(node, cursor-&amp;gt;cell_num));
+}
+
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;We haven’t implemented splitting yet, so we error if the node is full. Next we shift cells one space to the right to make room for the new cell. Then we write the new key/value into the empty space.&lt;/p&gt;

&lt;p&gt;Since we assume the tree only has one node, our &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;execute_insert()&lt;/code&gt; function simply needs to call this helper method:&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt; ExecuteResult execute_insert(Statement* statement, Table* table) {
&lt;span class=&quot;gd&quot;&gt;-  if (table-&amp;gt;num_rows &amp;gt;= TABLE_MAX_ROWS) {
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+  void* node = get_page(table-&amp;gt;pager, table-&amp;gt;root_page_num);
+  if ((*leaf_node_num_cells(node) &amp;gt;= LEAF_NODE_MAX_CELLS)) {
&lt;/span&gt;     return EXECUTE_TABLE_FULL;
   }
 
   Row* row_to_insert = &amp;amp;(statement-&amp;gt;row_to_insert);
   Cursor* cursor = table_end(table);
 
&lt;span class=&quot;gd&quot;&gt;-  serialize_row(row_to_insert, cursor_value(cursor));
-  table-&amp;gt;num_rows += 1;
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+  leaf_node_insert(cursor, row_to_insert-&amp;gt;id, row_to_insert);
&lt;/span&gt; 
   free(cursor);
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;With those changes, our database should work as before! Except now it returns a “Table Full” error much sooner, since we can’t split the root node yet.&lt;/p&gt;

&lt;p&gt;How many rows can the leaf node hold?&lt;/p&gt;

&lt;h2 id=&quot;command-to-print-constants&quot;&gt;Command to Print Constants&lt;/h2&gt;

&lt;p&gt;I’m adding a new meta command to print out a few constants of interest.&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;gi&quot;&gt;+void print_constants() {
+  printf(&quot;ROW_SIZE: %d\n&quot;, ROW_SIZE);
+  printf(&quot;COMMON_NODE_HEADER_SIZE: %d\n&quot;, COMMON_NODE_HEADER_SIZE);
+  printf(&quot;LEAF_NODE_HEADER_SIZE: %d\n&quot;, LEAF_NODE_HEADER_SIZE);
+  printf(&quot;LEAF_NODE_CELL_SIZE: %d\n&quot;, LEAF_NODE_CELL_SIZE);
+  printf(&quot;LEAF_NODE_SPACE_FOR_CELLS: %d\n&quot;, LEAF_NODE_SPACE_FOR_CELLS);
+  printf(&quot;LEAF_NODE_MAX_CELLS: %d\n&quot;, LEAF_NODE_MAX_CELLS);
+}
+
&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;@@ -294,6 +376,14 @@&lt;/span&gt; MetaCommandResult do_meta_command(InputBuffer* input_buffer, Table* table) {
   if (strcmp(input_buffer-&amp;gt;buffer, &quot;.exit&quot;) == 0) {
     db_close(table);
     exit(EXIT_SUCCESS);
&lt;span class=&quot;gi&quot;&gt;+  } else if (strcmp(input_buffer-&amp;gt;buffer, &quot;.constants&quot;) == 0) {
+    printf(&quot;Constants:\n&quot;);
+    print_constants();
+    return META_COMMAND_SUCCESS;
&lt;/span&gt;   } else {
     return META_COMMAND_UNRECOGNIZED_COMMAND;
   }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;I’m also adding a test so we get alerted when those constants change:&lt;/p&gt;
&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;gi&quot;&gt;+  it 'prints constants' do
+    script = [
+      &quot;.constants&quot;,
+      &quot;.exit&quot;,
+    ]
+    result = run_script(script)
+
+    expect(result).to match_array([
+      &quot;db &amp;gt; Constants:&quot;,
+      &quot;ROW_SIZE: 293&quot;,
+      &quot;COMMON_NODE_HEADER_SIZE: 6&quot;,
+      &quot;LEAF_NODE_HEADER_SIZE: 10&quot;,
+      &quot;LEAF_NODE_CELL_SIZE: 297&quot;,
+      &quot;LEAF_NODE_SPACE_FOR_CELLS: 4086&quot;,
+      &quot;LEAF_NODE_MAX_CELLS: 13&quot;,
+      &quot;db &amp;gt; &quot;,
+    ])
+  end
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;So our table can hold 13 rows right now!&lt;/p&gt;

&lt;h2 id=&quot;tree-visualization&quot;&gt;Tree Visualization&lt;/h2&gt;

&lt;p&gt;To help with debugging and visualization, I’m also adding a meta command to print out a representation of the btree.&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;gi&quot;&gt;+void print_leaf_node(void* node) {
+  uint32_t num_cells = *leaf_node_num_cells(node);
+  printf(&quot;leaf (size %d)\n&quot;, num_cells);
+  for (uint32_t i = 0; i &amp;lt; num_cells; i++) {
+    uint32_t key = *leaf_node_key(node, i);
+    printf(&quot;  - %d : %d\n&quot;, i, key);
+  }
+}
+
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;p&quot;&gt;@@ -294,6 +376,14 @@&lt;/span&gt; MetaCommandResult do_meta_command(InputBuffer* input_buffer, Table* table) {
   if (strcmp(input_buffer-&amp;gt;buffer, &quot;.exit&quot;) == 0) {
     db_close(table);
     exit(EXIT_SUCCESS);
&lt;span class=&quot;gi&quot;&gt;+  } else if (strcmp(input_buffer-&amp;gt;buffer, &quot;.btree&quot;) == 0) {
+    printf(&quot;Tree:\n&quot;);
+    print_leaf_node(get_page(table-&amp;gt;pager, 0));
+    return META_COMMAND_SUCCESS;
&lt;/span&gt;   } else if (strcmp(input_buffer-&amp;gt;buffer, &quot;.constants&quot;) == 0) {
     printf(&quot;Constants:\n&quot;);
     print_constants();
     return META_COMMAND_SUCCESS;
   } else {
     return META_COMMAND_UNRECOGNIZED_COMMAND;
   }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;And a test&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;gi&quot;&gt;+  it 'allows printing out the structure of a one-node btree' do
+    script = [3, 1, 2].map do |i|
+      &quot;insert #{i} user#{i} person#{i}@example.com&quot;
+    end
+    script &amp;lt;&amp;lt; &quot;.btree&quot;
+    script &amp;lt;&amp;lt; &quot;.exit&quot;
+    result = run_script(script)
+
+    expect(result).to match_array([
+      &quot;db &amp;gt; Executed.&quot;,
+      &quot;db &amp;gt; Executed.&quot;,
+      &quot;db &amp;gt; Executed.&quot;,
+      &quot;db &amp;gt; Tree:&quot;,
+      &quot;leaf (size 3)&quot;,
+      &quot;  - 0 : 3&quot;,
+      &quot;  - 1 : 1&quot;,
+      &quot;  - 2 : 2&quot;,
+      &quot;db &amp;gt; &quot;
+    ])
+  end
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Uh oh, we’re still not storing rows in sorted order. You’ll notice that &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;execute_insert()&lt;/code&gt; inserts into the leaf node at the position returned by &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;table_end()&lt;/code&gt;. So rows are stored in the order they were inserted, just like before.&lt;/p&gt;

&lt;h2 id=&quot;next-time&quot;&gt;Next Time&lt;/h2&gt;

&lt;p&gt;This all might seem like a step backwards. Our database now stores fewer rows than it did before, and we’re still storing rows in unsorted order. But like I said at the beginning, this is a big change and it’s important to break it up into manageable steps.&lt;/p&gt;

&lt;p&gt;Next time, we’ll implement finding a record by primary key, and start storing rows in sorted order.&lt;/p&gt;

&lt;h2 id=&quot;complete-diff&quot;&gt;Complete Diff&lt;/h2&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;p&quot;&gt;@@ -62,29 +62,101 @@&lt;/span&gt; const uint32_t ROW_SIZE = ID_SIZE + USERNAME_SIZE + EMAIL_SIZE;

 const uint32_t PAGE_SIZE = 4096;
 #define TABLE_MAX_PAGES 100
&lt;span class=&quot;gd&quot;&gt;-const uint32_t ROWS_PER_PAGE = PAGE_SIZE / ROW_SIZE;
-const uint32_t TABLE_MAX_ROWS = ROWS_PER_PAGE * TABLE_MAX_PAGES;
&lt;/span&gt; 
 typedef struct {
   int file_descriptor;
   uint32_t file_length;
&lt;span class=&quot;gi&quot;&gt;+  uint32_t num_pages;
&lt;/span&gt;   void* pages[TABLE_MAX_PAGES];
 } Pager;
 
 typedef struct {
   Pager* pager;
&lt;span class=&quot;gd&quot;&gt;-  uint32_t num_rows;
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+  uint32_t root_page_num;
&lt;/span&gt; } Table;
 
 typedef struct {
   Table* table;
&lt;span class=&quot;gd&quot;&gt;-  uint32_t row_num;
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+  uint32_t page_num;
+  uint32_t cell_num;
&lt;/span&gt;   bool end_of_table;  // Indicates a position one past the last element
 } Cursor;

+typedef enum { NODE_INTERNAL, NODE_LEAF } NodeType;
&lt;span class=&quot;gi&quot;&gt;+
+/*
+ * Common Node Header Layout
+ */
+const uint32_t NODE_TYPE_SIZE = sizeof(uint8_t);
+const uint32_t NODE_TYPE_OFFSET = 0;
+const uint32_t IS_ROOT_SIZE = sizeof(uint8_t);
+const uint32_t IS_ROOT_OFFSET = NODE_TYPE_SIZE;
+const uint32_t PARENT_POINTER_SIZE = sizeof(uint32_t);
+const uint32_t PARENT_POINTER_OFFSET = IS_ROOT_OFFSET + IS_ROOT_SIZE;
+const uint8_t COMMON_NODE_HEADER_SIZE =
+    NODE_TYPE_SIZE + IS_ROOT_SIZE + PARENT_POINTER_SIZE;
+
+/*
+ * Leaf Node Header Layout
+ */
+const uint32_t LEAF_NODE_NUM_CELLS_SIZE = sizeof(uint32_t);
+const uint32_t LEAF_NODE_NUM_CELLS_OFFSET = COMMON_NODE_HEADER_SIZE;
+const uint32_t LEAF_NODE_HEADER_SIZE =
+    COMMON_NODE_HEADER_SIZE + LEAF_NODE_NUM_CELLS_SIZE;
+
+/*
+ * Leaf Node Body Layout
+ */
+const uint32_t LEAF_NODE_KEY_SIZE = sizeof(uint32_t);
+const uint32_t LEAF_NODE_KEY_OFFSET = 0;
+const uint32_t LEAF_NODE_VALUE_SIZE = ROW_SIZE;
+const uint32_t LEAF_NODE_VALUE_OFFSET =
+    LEAF_NODE_KEY_OFFSET + LEAF_NODE_KEY_SIZE;
+const uint32_t LEAF_NODE_CELL_SIZE = LEAF_NODE_KEY_SIZE + LEAF_NODE_VALUE_SIZE;
+const uint32_t LEAF_NODE_SPACE_FOR_CELLS = PAGE_SIZE - LEAF_NODE_HEADER_SIZE;
+const uint32_t LEAF_NODE_MAX_CELLS =
+    LEAF_NODE_SPACE_FOR_CELLS / LEAF_NODE_CELL_SIZE;
+
+uint32_t* leaf_node_num_cells(void* node) {
+  return node + LEAF_NODE_NUM_CELLS_OFFSET;
+}
+
+void* leaf_node_cell(void* node, uint32_t cell_num) {
+  return node + LEAF_NODE_HEADER_SIZE + cell_num * LEAF_NODE_CELL_SIZE;
+}
+
+uint32_t* leaf_node_key(void* node, uint32_t cell_num) {
+  return leaf_node_cell(node, cell_num);
+}
+
+void* leaf_node_value(void* node, uint32_t cell_num) {
+  return leaf_node_cell(node, cell_num) + LEAF_NODE_KEY_SIZE;
+}
+
+void print_constants() {
+  printf(&quot;ROW_SIZE: %d\n&quot;, ROW_SIZE);
+  printf(&quot;COMMON_NODE_HEADER_SIZE: %d\n&quot;, COMMON_NODE_HEADER_SIZE);
+  printf(&quot;LEAF_NODE_HEADER_SIZE: %d\n&quot;, LEAF_NODE_HEADER_SIZE);
+  printf(&quot;LEAF_NODE_CELL_SIZE: %d\n&quot;, LEAF_NODE_CELL_SIZE);
+  printf(&quot;LEAF_NODE_SPACE_FOR_CELLS: %d\n&quot;, LEAF_NODE_SPACE_FOR_CELLS);
+  printf(&quot;LEAF_NODE_MAX_CELLS: %d\n&quot;, LEAF_NODE_MAX_CELLS);
+}
+
+void print_leaf_node(void* node) {
+  uint32_t num_cells = *leaf_node_num_cells(node);
+  printf(&quot;leaf (size %d)\n&quot;, num_cells);
+  for (uint32_t i = 0; i &amp;lt; num_cells; i++) {
+    uint32_t key = *leaf_node_key(node, i);
+    printf(&quot;  - %d : %d\n&quot;, i, key);
+  }
+}
+
&lt;/span&gt; void print_row(Row* row) {
     printf(&quot;(%d, %s, %s)\n&quot;, row-&amp;gt;id, row-&amp;gt;username, row-&amp;gt;email);
 }
&lt;span class=&quot;p&quot;&gt;@@ -101,6 +173,8 @@&lt;/span&gt; void deserialize_row(void *source, Row* destination) {
     memcpy(&amp;amp;(destination-&amp;gt;email), source + EMAIL_OFFSET, EMAIL_SIZE);
 }
 
&lt;span class=&quot;gi&quot;&gt;+void initialize_leaf_node(void* node) { *leaf_node_num_cells(node) = 0; }
+
&lt;/span&gt; void* get_page(Pager* pager, uint32_t page_num) {
   if (page_num &amp;gt; TABLE_MAX_PAGES) {
     printf(&quot;Tried to fetch page number out of bounds. %d &amp;gt; %d\n&quot;, page_num,
&lt;span class=&quot;p&quot;&gt;@@ -128,6 +202,10 @@&lt;/span&gt; void* get_page(Pager* pager, uint32_t page_num) {
     }
 
     pager-&amp;gt;pages[page_num] = page;
&lt;span class=&quot;gi&quot;&gt;+
+    if (page_num &amp;gt;= pager-&amp;gt;num_pages) {
+      pager-&amp;gt;num_pages = page_num + 1;
+    }
&lt;/span&gt;   }
 
   return pager-&amp;gt;pages[page_num];
&lt;span class=&quot;p&quot;&gt;@@ -136,8 +214,12 @@&lt;/span&gt; void* get_page(Pager* pager, uint32_t page_num) {
 Cursor* table_start(Table* table) {
   Cursor* cursor = malloc(sizeof(Cursor));
   cursor-&amp;gt;table = table;
&lt;span class=&quot;gd&quot;&gt;-  cursor-&amp;gt;row_num = 0;
-  cursor-&amp;gt;end_of_table = (table-&amp;gt;num_rows == 0);
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+  cursor-&amp;gt;page_num = table-&amp;gt;root_page_num;
+  cursor-&amp;gt;cell_num = 0;
+
+  void* root_node = get_page(table-&amp;gt;pager, table-&amp;gt;root_page_num);
+  uint32_t num_cells = *leaf_node_num_cells(root_node);
+  cursor-&amp;gt;end_of_table = (num_cells == 0);
&lt;/span&gt; 
   return cursor;
 }
&lt;span class=&quot;p&quot;&gt;@@ -145,24 +227,28 @@&lt;/span&gt; Cursor* table_start(Table* table) {
 Cursor* table_end(Table* table) {
   Cursor* cursor = malloc(sizeof(Cursor));
   cursor-&amp;gt;table = table;
&lt;span class=&quot;gd&quot;&gt;-  cursor-&amp;gt;row_num = table-&amp;gt;num_rows;
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+  cursor-&amp;gt;page_num = table-&amp;gt;root_page_num;
+
+  void* root_node = get_page(table-&amp;gt;pager, table-&amp;gt;root_page_num);
+  uint32_t num_cells = *leaf_node_num_cells(root_node);
+  cursor-&amp;gt;cell_num = num_cells;
&lt;/span&gt;   cursor-&amp;gt;end_of_table = true;
 
   return cursor;
 }
 
 void* cursor_value(Cursor* cursor) {
&lt;span class=&quot;gd&quot;&gt;-  uint32_t row_num = cursor-&amp;gt;row_num;
-  uint32_t page_num = row_num / ROWS_PER_PAGE;
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+  uint32_t page_num = cursor-&amp;gt;page_num;
&lt;/span&gt;   void* page = get_page(cursor-&amp;gt;table-&amp;gt;pager, page_num);
&lt;span class=&quot;gd&quot;&gt;-  uint32_t row_offset = row_num % ROWS_PER_PAGE;
-  uint32_t byte_offset = row_offset * ROW_SIZE;
-  return page + byte_offset;
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+  return leaf_node_value(page, cursor-&amp;gt;cell_num);
&lt;/span&gt; }
 
 void cursor_advance(Cursor* cursor) {
&lt;span class=&quot;gd&quot;&gt;-  cursor-&amp;gt;row_num += 1;
-  if (cursor-&amp;gt;row_num &amp;gt;= cursor-&amp;gt;table-&amp;gt;num_rows) {
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+  uint32_t page_num = cursor-&amp;gt;page_num;
+  void* node = get_page(cursor-&amp;gt;table-&amp;gt;pager, page_num);
+
+  cursor-&amp;gt;cell_num += 1;
+  if (cursor-&amp;gt;cell_num &amp;gt;= (*leaf_node_num_cells(node))) {
&lt;/span&gt;     cursor-&amp;gt;end_of_table = true;
   }
 }
&lt;span class=&quot;p&quot;&gt;@@ -185,6 +271,12 @@&lt;/span&gt; Pager* pager_open(const char* filename) {
   Pager* pager = malloc(sizeof(Pager));
   pager-&amp;gt;file_descriptor = fd;
   pager-&amp;gt;file_length = file_length;
&lt;span class=&quot;gi&quot;&gt;+  pager-&amp;gt;num_pages = (file_length / PAGE_SIZE);
+
+  if (file_length % PAGE_SIZE != 0) {
+    printf(&quot;Db file is not a whole number of pages. Corrupt file.\n&quot;);
+    exit(EXIT_FAILURE);
+  }
&lt;/span&gt; 
   for (uint32_t i = 0; i &amp;lt; TABLE_MAX_PAGES; i++) {
     pager-&amp;gt;pages[i] = NULL;
&lt;span class=&quot;p&quot;&gt;@@ -194,11 +285,15 @@&lt;/span&gt; Pager* pager_open(const char* filename) {
&lt;span class=&quot;p&quot;&gt;@@ -195,11 +287,16 @@&lt;/span&gt; Pager* pager_open(const char* filename) {
 
 Table* db_open(const char* filename) {
   Pager* pager = pager_open(filename);
&lt;span class=&quot;gd&quot;&gt;-  uint32_t num_rows = pager-&amp;gt;file_length / ROW_SIZE;
&lt;/span&gt; 
   Table* table = malloc(sizeof(Table));
   table-&amp;gt;pager = pager;
&lt;span class=&quot;gd&quot;&gt;-  table-&amp;gt;num_rows = num_rows;
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+  table-&amp;gt;root_page_num = 0;
+
+  if (pager-&amp;gt;num_pages == 0) {
+    // New database file. Initialize page 0 as leaf node.
+    void* root_node = get_page(pager, 0);
+    initialize_leaf_node(root_node);
+  }
&lt;/span&gt; 
   return table;
 }
&lt;span class=&quot;p&quot;&gt;@@ -234,7 +331,7 @@&lt;/span&gt; void close_input_buffer(InputBuffer* input_buffer) {
     free(input_buffer);
 }
 
&lt;span class=&quot;gd&quot;&gt;-void pager_flush(Pager* pager, uint32_t page_num, uint32_t size) {
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+void pager_flush(Pager* pager, uint32_t page_num) {
&lt;/span&gt;   if (pager-&amp;gt;pages[page_num] == NULL) {
     printf(&quot;Tried to flush null page\n&quot;);
     exit(EXIT_FAILURE);
&lt;span class=&quot;p&quot;&gt;@@ -242,7 +337,7 @@&lt;/span&gt; void pager_flush(Pager* pager, uint32_t page_num, uint32_t size) {
&lt;span class=&quot;p&quot;&gt;@@ -249,7 +346,7 @@&lt;/span&gt; void pager_flush(Pager* pager, uint32_t page_num, uint32_t size) {
   }
 
   ssize_t bytes_written =
&lt;span class=&quot;gd&quot;&gt;-      write(pager-&amp;gt;file_descriptor, pager-&amp;gt;pages[page_num], size);
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+      write(pager-&amp;gt;file_descriptor, pager-&amp;gt;pages[page_num], PAGE_SIZE);
&lt;/span&gt; 
   if (bytes_written == -1) {
     printf(&quot;Error writing: %d\n&quot;, errno);
&lt;span class=&quot;p&quot;&gt;@@ -252,29 +347,16 @@&lt;/span&gt; void pager_flush(Pager* pager, uint32_t page_num, uint32_t size) {
&lt;span class=&quot;p&quot;&gt;@@ -260,29 +357,16 @@&lt;/span&gt; void pager_flush(Pager* pager, uint32_t page_num, uint32_t size) {
 
 void db_close(Table* table) {
   Pager* pager = table-&amp;gt;pager;
&lt;span class=&quot;gd&quot;&gt;-  uint32_t num_full_pages = table-&amp;gt;num_rows / ROWS_PER_PAGE;
&lt;/span&gt; 
&lt;span class=&quot;gd&quot;&gt;-  for (uint32_t i = 0; i &amp;lt; num_full_pages; i++) {
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+  for (uint32_t i = 0; i &amp;lt; pager-&amp;gt;num_pages; i++) {
&lt;/span&gt;     if (pager-&amp;gt;pages[i] == NULL) {
       continue;
     }
&lt;span class=&quot;gd&quot;&gt;-    pager_flush(pager, i, PAGE_SIZE);
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+    pager_flush(pager, i);
&lt;/span&gt;     free(pager-&amp;gt;pages[i]);
     pager-&amp;gt;pages[i] = NULL;
   }
 
&lt;span class=&quot;gd&quot;&gt;-  // There may be a partial page to write to the end of the file
-  // This should not be needed after we switch to a B-tree
-  uint32_t num_additional_rows = table-&amp;gt;num_rows % ROWS_PER_PAGE;
-  if (num_additional_rows &amp;gt; 0) {
-    uint32_t page_num = num_full_pages;
-    if (pager-&amp;gt;pages[page_num] != NULL) {
-      pager_flush(pager, page_num, num_additional_rows * ROW_SIZE);
-      free(pager-&amp;gt;pages[page_num]);
-      pager-&amp;gt;pages[page_num] = NULL;
-    }
-  }
-
&lt;/span&gt;   int result = close(pager-&amp;gt;file_descriptor);
   if (result == -1) {
     printf(&quot;Error closing db file.\n&quot;);
&lt;span class=&quot;p&quot;&gt;@@ -305,6 +389,14 @@&lt;/span&gt; MetaCommandResult do_meta_command(InputBuffer* input_buffer, Table *table) {
   if (strcmp(input_buffer-&amp;gt;buffer, &quot;.exit&quot;) == 0) {
     db_close(table);
     exit(EXIT_SUCCESS);
&lt;span class=&quot;gi&quot;&gt;+  } else if (strcmp(input_buffer-&amp;gt;buffer, &quot;.btree&quot;) == 0) {
+    printf(&quot;Tree:\n&quot;);
+    print_leaf_node(get_page(table-&amp;gt;pager, 0));
+    return META_COMMAND_SUCCESS;
+  } else if (strcmp(input_buffer-&amp;gt;buffer, &quot;.constants&quot;) == 0) {
+    printf(&quot;Constants:\n&quot;);
+    print_constants();
+    return META_COMMAND_SUCCESS;
&lt;/span&gt;   } else {
     return META_COMMAND_UNRECOGNIZED_COMMAND;
   }
&lt;span class=&quot;p&quot;&gt;@@ -354,16 +446,39 @@&lt;/span&gt; PrepareResult prepare_statement(InputBuffer* input_buffer,
   return PREPARE_UNRECOGNIZED_STATEMENT;
 }
 
&lt;span class=&quot;gi&quot;&gt;+void leaf_node_insert(Cursor* cursor, uint32_t key, Row* value) {
+  void* node = get_page(cursor-&amp;gt;table-&amp;gt;pager, cursor-&amp;gt;page_num);
+
+  uint32_t num_cells = *leaf_node_num_cells(node);
+  if (num_cells &amp;gt;= LEAF_NODE_MAX_CELLS) {
+    // Node full
+    printf(&quot;Need to implement splitting a leaf node.\n&quot;);
+    exit(EXIT_FAILURE);
+  }
+
+  if (cursor-&amp;gt;cell_num &amp;lt; num_cells) {
+    // Make room for new cell
+    for (uint32_t i = num_cells; i &amp;gt; cursor-&amp;gt;cell_num; i--) {
+      memcpy(leaf_node_cell(node, i), leaf_node_cell(node, i - 1),
+             LEAF_NODE_CELL_SIZE);
+    }
+  }
+
+  *(leaf_node_num_cells(node)) += 1;
+  *(leaf_node_key(node, cursor-&amp;gt;cell_num)) = key;
+  serialize_row(value, leaf_node_value(node, cursor-&amp;gt;cell_num));
+}
+
&lt;/span&gt; ExecuteResult execute_insert(Statement* statement, Table* table) {
&lt;span class=&quot;gd&quot;&gt;-  if (table-&amp;gt;num_rows &amp;gt;= TABLE_MAX_ROWS) {
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+  void* node = get_page(table-&amp;gt;pager, table-&amp;gt;root_page_num);
+  if ((*leaf_node_num_cells(node) &amp;gt;= LEAF_NODE_MAX_CELLS)) {
&lt;/span&gt;     return EXECUTE_TABLE_FULL;
   }
 
   Row* row_to_insert = &amp;amp;(statement-&amp;gt;row_to_insert);
   Cursor* cursor = table_end(table);
 
&lt;span class=&quot;gd&quot;&gt;-  serialize_row(row_to_insert, cursor_value(cursor));
-  table-&amp;gt;num_rows += 1;
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+  leaf_node_insert(cursor, row_to_insert-&amp;gt;id, row_to_insert);
&lt;/span&gt; 
   free(cursor);
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;And the specs:&lt;/p&gt;
&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;gi&quot;&gt;+  it 'allows printing out the structure of a one-node btree' do
+    script = [3, 1, 2].map do |i|
+      &quot;insert #{i} user#{i} person#{i}@example.com&quot;
+    end
+    script &amp;lt;&amp;lt; &quot;.btree&quot;
+    script &amp;lt;&amp;lt; &quot;.exit&quot;
+    result = run_script(script)
+
+    expect(result).to match_array([
+      &quot;db &amp;gt; Executed.&quot;,
+      &quot;db &amp;gt; Executed.&quot;,
+      &quot;db &amp;gt; Executed.&quot;,
+      &quot;db &amp;gt; Tree:&quot;,
+      &quot;leaf (size 3)&quot;,
+      &quot;  - 0 : 3&quot;,
+      &quot;  - 1 : 1&quot;,
+      &quot;  - 2 : 2&quot;,
+      &quot;db &amp;gt; &quot;
+    ])
+  end
+
+  it 'prints constants' do
+    script = [
+      &quot;.constants&quot;,
+      &quot;.exit&quot;,
+    ]
+    result = run_script(script)
+
+    expect(result).to match_array([
+      &quot;db &amp;gt; Constants:&quot;,
+      &quot;ROW_SIZE: 293&quot;,
+      &quot;COMMON_NODE_HEADER_SIZE: 6&quot;,
+      &quot;LEAF_NODE_HEADER_SIZE: 10&quot;,
+      &quot;LEAF_NODE_CELL_SIZE: 297&quot;,
+      &quot;LEAF_NODE_SPACE_FOR_CELLS: 4086&quot;,
+      &quot;LEAF_NODE_MAX_CELLS: 13&quot;,
+      &quot;db &amp;gt; &quot;,
+    ])
+  end
&lt;/span&gt; end
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
</description>
        <pubDate>Mon, 25 Sep 2017 00:00:00 +0000</pubDate>
        <link>https://guimy.tech/db_tutorial/parts/part8.html</link>
        <guid isPermaLink="true">https://guimy.tech/db_tutorial/parts/part8.html</guid>
      </item>
    
      <item>
        <title>Part 9 - Binary Search and Duplicate Keys</title>
        <description>&lt;p&gt;Last time we noted that we’re still storing keys in unsorted order. We’re going to fix that problem, plus detect and reject duplicate keys.&lt;/p&gt;

&lt;p&gt;Right now, our &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;execute_insert()&lt;/code&gt; function always chooses to insert at the end of the table. Instead, we should search the table for the correct place to insert, then insert there. If the key already exists there, return an error.&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;p&quot;&gt;ExecuteResult execute_insert(Statement* statement, Table* table) {
&lt;/span&gt;   void* node = get_page(table-&amp;gt;pager, table-&amp;gt;root_page_num);
&lt;span class=&quot;gd&quot;&gt;-  if ((*leaf_node_num_cells(node) &amp;gt;= LEAF_NODE_MAX_CELLS)) {
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+  uint32_t num_cells = (*leaf_node_num_cells(node));
+  if (num_cells &amp;gt;= LEAF_NODE_MAX_CELLS) {
&lt;/span&gt;     return EXECUTE_TABLE_FULL;
   }

   Row* row_to_insert = &amp;amp;(statement-&amp;gt;row_to_insert);
&lt;span class=&quot;gd&quot;&gt;-  Cursor* cursor = table_end(table);
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+  uint32_t key_to_insert = row_to_insert-&amp;gt;id;
+  Cursor* cursor = table_find(table, key_to_insert);
+
+  if (cursor-&amp;gt;cell_num &amp;lt; num_cells) {
+    uint32_t key_at_index = *leaf_node_key(node, cursor-&amp;gt;cell_num);
+    if (key_at_index == key_to_insert) {
+      return EXECUTE_DUPLICATE_KEY;
+    }
+  }
&lt;/span&gt;
   leaf_node_insert(cursor, row_to_insert-&amp;gt;id, row_to_insert);
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;We don’t need the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;table_end()&lt;/code&gt; function anymore.&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;gd&quot;&gt;-Cursor* table_end(Table* table) {
-  Cursor* cursor = malloc(sizeof(Cursor));
-  cursor-&amp;gt;table = table;
-  cursor-&amp;gt;page_num = table-&amp;gt;root_page_num;
-
-  void* root_node = get_page(table-&amp;gt;pager, table-&amp;gt;root_page_num);
-  uint32_t num_cells = *leaf_node_num_cells(root_node);
-  cursor-&amp;gt;cell_num = num_cells;
-  cursor-&amp;gt;end_of_table = true;
-
-  return cursor;
-}
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;We’ll replace it with a method that searches the tree for a given key.&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;gi&quot;&gt;+/*
+Return the position of the given key.
+If the key is not present, return the position
+where it should be inserted
+*/
+Cursor* table_find(Table* table, uint32_t key) {
+  uint32_t root_page_num = table-&amp;gt;root_page_num;
+  void* root_node = get_page(table-&amp;gt;pager, root_page_num);
+
+  if (get_node_type(root_node) == NODE_LEAF) {
+    return leaf_node_find(table, root_page_num, key);
+  } else {
+    printf(&quot;Need to implement searching an internal node\n&quot;);
+    exit(EXIT_FAILURE);
+  }
+}
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;I’m stubbing out the branch for internal nodes because we haven’t implemented internal nodes yet. We can search the leaf node with binary search.&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;gi&quot;&gt;+Cursor* leaf_node_find(Table* table, uint32_t page_num, uint32_t key) {
+  void* node = get_page(table-&amp;gt;pager, page_num);
+  uint32_t num_cells = *leaf_node_num_cells(node);
+
+  Cursor* cursor = malloc(sizeof(Cursor));
+  cursor-&amp;gt;table = table;
+  cursor-&amp;gt;page_num = page_num;
+
+  // Binary search
+  uint32_t min_index = 0;
+  uint32_t one_past_max_index = num_cells;
+  while (one_past_max_index != min_index) {
+    uint32_t index = (min_index + one_past_max_index) / 2;
+    uint32_t key_at_index = *leaf_node_key(node, index);
+    if (key == key_at_index) {
+      cursor-&amp;gt;cell_num = index;
+      return cursor;
+    }
+    if (key &amp;lt; key_at_index) {
+      one_past_max_index = index;
+    } else {
+      min_index = index + 1;
+    }
+  }
+
+  cursor-&amp;gt;cell_num = min_index;
+  return cursor;
+}
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;This will either return&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;the position of the key,&lt;/li&gt;
  &lt;li&gt;the position of another key that we’ll need to move if we want to insert the new key, or&lt;/li&gt;
  &lt;li&gt;the position one past the last key&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Since we’re now checking node type, we need functions to get and set that value in a node.&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;gi&quot;&gt;+NodeType get_node_type(void* node) {
+  uint8_t value = *((uint8_t*)(node + NODE_TYPE_OFFSET));
+  return (NodeType)value;
+}
+
+void set_node_type(void* node, NodeType type) {
+  uint8_t value = type;
+  *((uint8_t*)(node + NODE_TYPE_OFFSET)) = value;
+}
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;We have to cast to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;uint8_t&lt;/code&gt; first to ensure it’s serialized as a single byte.&lt;/p&gt;

&lt;p&gt;We also need to initialize node type.&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;gd&quot;&gt;-void initialize_leaf_node(void* node) { *leaf_node_num_cells(node) = 0; }
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+void initialize_leaf_node(void* node) {
+  set_node_type(node, NODE_LEAF);
+  *leaf_node_num_cells(node) = 0;
+}
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Lastly, we need to make and handle a new error code.&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;gd&quot;&gt;-enum ExecuteResult_t { EXECUTE_SUCCESS, EXECUTE_TABLE_FULL };
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+enum ExecuteResult_t {
+  EXECUTE_SUCCESS,
+  EXECUTE_DUPLICATE_KEY,
+  EXECUTE_TABLE_FULL
+};
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;       case (EXECUTE_SUCCESS):
         printf(&quot;Executed.\n&quot;);
         break;
&lt;span class=&quot;gi&quot;&gt;+      case (EXECUTE_DUPLICATE_KEY):
+        printf(&quot;Error: Duplicate key.\n&quot;);
+        break;
&lt;/span&gt;       case (EXECUTE_TABLE_FULL):
         printf(&quot;Error: Table full.\n&quot;);
         break;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;With these changes, our test can change to check for sorted order:&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;       &quot;db &amp;gt; Executed.&quot;,
       &quot;db &amp;gt; Tree:&quot;,
       &quot;leaf (size 3)&quot;,
&lt;span class=&quot;gd&quot;&gt;-      &quot;  - 0 : 3&quot;,
-      &quot;  - 1 : 1&quot;,
-      &quot;  - 2 : 2&quot;,
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+      &quot;  - 0 : 1&quot;,
+      &quot;  - 1 : 2&quot;,
+      &quot;  - 2 : 3&quot;,
&lt;/span&gt;       &quot;db &amp;gt; &quot;
     ])
   end
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;And we can add a new test for duplicate keys:&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;gi&quot;&gt;+  it 'prints an error message if there is a duplicate id' do
+    script = [
+      &quot;insert 1 user1 person1@example.com&quot;,
+      &quot;insert 1 user1 person1@example.com&quot;,
+      &quot;select&quot;,
+      &quot;.exit&quot;,
+    ]
+    result = run_script(script)
+    expect(result).to match_array([
+      &quot;db &amp;gt; Executed.&quot;,
+      &quot;db &amp;gt; Error: Duplicate key.&quot;,
+      &quot;db &amp;gt; (1, user1, person1@example.com)&quot;,
+      &quot;Executed.&quot;,
+      &quot;db &amp;gt; &quot;,
+    ])
+  end
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;That’s it! Next up: implement splitting leaf nodes and creating internal nodes.&lt;/p&gt;
</description>
        <pubDate>Sun, 01 Oct 2017 00:00:00 +0000</pubDate>
        <link>https://guimy.tech/db_tutorial/parts/part9.html</link>
        <guid isPermaLink="true">https://guimy.tech/db_tutorial/parts/part9.html</guid>
      </item>
    
      <item>
        <title>Part 10 - Splitting a Leaf Node</title>
        <description>&lt;p&gt;Our B-Tree doesn’t feel like much of a tree with only one node. To fix that, we need some code to split a leaf node in twain. And after that, we need to create an internal node to serve as a parent for the two leaf nodes.&lt;/p&gt;

&lt;p&gt;Basically our goal for this article is to go from this:&lt;/p&gt;

&lt;table class=&quot;image&quot;&gt;
&lt;caption align=&quot;bottom&quot;&gt;one-node btree&lt;/caption&gt;
&lt;tr&gt;&lt;td&gt;&lt;a href=&quot;https://guimy.tech/db_tutorial/assets/images/btree2.png&quot;&gt;&lt;img src=&quot;https://guimy.tech/db_tutorial/assets/images/btree2.png&quot; alt=&quot;one-node btree&quot; /&gt;&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;/table&gt;

&lt;p&gt;to this:&lt;/p&gt;

&lt;table class=&quot;image&quot;&gt;
&lt;caption align=&quot;bottom&quot;&gt;two-level btree&lt;/caption&gt;
&lt;tr&gt;&lt;td&gt;&lt;a href=&quot;https://guimy.tech/db_tutorial/assets/images/btree3.png&quot;&gt;&lt;img src=&quot;https://guimy.tech/db_tutorial/assets/images/btree3.png&quot; alt=&quot;two-level btree&quot; /&gt;&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;/table&gt;

&lt;p&gt;First things first, let’s remove the error handling for a full leaf node:&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt; void leaf_node_insert(Cursor* cursor, uint32_t key, Row* value) {
   void* node = get_page(cursor-&amp;gt;table-&amp;gt;pager, cursor-&amp;gt;page_num);
 
   uint32_t num_cells = *leaf_node_num_cells(node);
   if (num_cells &amp;gt;= LEAF_NODE_MAX_CELLS) {
     // Node full
&lt;span class=&quot;gd&quot;&gt;-    printf(&quot;Need to implement splitting a leaf node.\n&quot;);
-    exit(EXIT_FAILURE);
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+    leaf_node_split_and_insert(cursor, key, value);
+    return;
&lt;/span&gt;   }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;p&quot;&gt;ExecuteResult execute_insert(Statement* statement, Table* table) {
&lt;/span&gt;   void* node = get_page(table-&amp;gt;pager, table-&amp;gt;root_page_num);
   uint32_t num_cells = (*leaf_node_num_cells(node));
&lt;span class=&quot;gd&quot;&gt;-  if (num_cells &amp;gt;= LEAF_NODE_MAX_CELLS) {
-    return EXECUTE_TABLE_FULL;
-  }
&lt;/span&gt; 
   Row* row_to_insert = &amp;amp;(statement-&amp;gt;row_to_insert);
   uint32_t key_to_insert = row_to_insert-&amp;gt;id;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;splitting-algorithm&quot;&gt;Splitting Algorithm&lt;/h2&gt;

&lt;p&gt;Easy part’s over. Here’s a description of what we need to do from &lt;a href=&quot;https://play.google.com/store/books/details/Sibsankar_Haldar_SQLite_Database_System_Design_and?id=9Z6IQQnX1JEC&amp;amp;hl=en&quot;&gt;SQLite Database System: Design and Implementation&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;If there is no space on the leaf node, we would split the existing entries residing there and the new one (being inserted) into two equal halves: lower and upper halves. (Keys on the upper half are strictly greater than those on the lower half.) We allocate a new leaf node, and move the upper half into the new node.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Let’s get a handle to the old node and create the new node:&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;gi&quot;&gt;+void leaf_node_split_and_insert(Cursor* cursor, uint32_t key, Row* value) {
+  /*
+  Create a new node and move half the cells over.
+  Insert the new value in one of the two nodes.
+  Update parent or create a new parent.
+  */
+
+  void* old_node = get_page(cursor-&amp;gt;table-&amp;gt;pager, cursor-&amp;gt;page_num);
+  uint32_t new_page_num = get_unused_page_num(cursor-&amp;gt;table-&amp;gt;pager);
+  void* new_node = get_page(cursor-&amp;gt;table-&amp;gt;pager, new_page_num);
+  initialize_leaf_node(new_node);
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Next, copy every cell into its new location:&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;gi&quot;&gt;+  /*
+  All existing keys plus new key should be divided
+  evenly between old (left) and new (right) nodes.
+  Starting from the right, move each key to correct position.
+  */
+  for (int32_t i = LEAF_NODE_MAX_CELLS; i &amp;gt;= 0; i--) {
+    void* destination_node;
+    if (i &amp;gt;= LEAF_NODE_LEFT_SPLIT_COUNT) {
+      destination_node = new_node;
+    } else {
+      destination_node = old_node;
+    }
+    uint32_t index_within_node = i % LEAF_NODE_LEFT_SPLIT_COUNT;
+    void* destination = leaf_node_cell(destination_node, index_within_node);
+
+    if (i == cursor-&amp;gt;cell_num) {
+      serialize_row(value, destination);
+    } else if (i &amp;gt; cursor-&amp;gt;cell_num) {
+      memcpy(destination, leaf_node_cell(old_node, i - 1), LEAF_NODE_CELL_SIZE);
+    } else {
+      memcpy(destination, leaf_node_cell(old_node, i), LEAF_NODE_CELL_SIZE);
+    }
+  }
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Update cell counts in each node’s header:&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;gi&quot;&gt;+  /* Update cell count on both leaf nodes */
+  *(leaf_node_num_cells(old_node)) = LEAF_NODE_LEFT_SPLIT_COUNT;
+  *(leaf_node_num_cells(new_node)) = LEAF_NODE_RIGHT_SPLIT_COUNT;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Then we need to update the nodes’ parent. If the original node was the root, it had no parent. In that case, create a new root node to act as the parent. I’ll stub out the other branch for now:&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;gi&quot;&gt;+  if (is_node_root(old_node)) {
+    return create_new_root(cursor-&amp;gt;table, new_page_num);
+  } else {
+    printf(&quot;Need to implement updating parent after split\n&quot;);
+    exit(EXIT_FAILURE);
+  }
+}
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;allocating-new-pages&quot;&gt;Allocating New Pages&lt;/h2&gt;

&lt;p&gt;Let’s go back and define a few new functions and constants. When we created a new leaf node, we put it in a page decided by &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;get_unused_page_num()&lt;/code&gt;:&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;gi&quot;&gt;+/*
+Until we start recycling free pages, new pages will always
+go onto the end of the database file
+*/
+uint32_t get_unused_page_num(Pager* pager) { return pager-&amp;gt;num_pages; }
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;For now, we’re assuming that in a database with N pages, page numbers 0 through N-1 are allocated. Therefore we can always allocate page number N for new pages. Eventually after we implement deletion, some pages may become empty and their page numbers unused. To be more efficient, we could re-allocate those free pages.&lt;/p&gt;

&lt;h2 id=&quot;leaf-node-sizes&quot;&gt;Leaf Node Sizes&lt;/h2&gt;

&lt;p&gt;To keep the tree balanced, we evenly distribute cells between the two new nodes. If a leaf node can hold N cells, then during a split we need to distribute N+1 cells between two nodes (N original cells plus one new one). I’m arbitrarily choosing the left node to get one more cell if N+1 is odd.&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;gi&quot;&gt;+const uint32_t LEAF_NODE_RIGHT_SPLIT_COUNT = (LEAF_NODE_MAX_CELLS + 1) / 2;
+const uint32_t LEAF_NODE_LEFT_SPLIT_COUNT =
+    (LEAF_NODE_MAX_CELLS + 1) - LEAF_NODE_RIGHT_SPLIT_COUNT;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;creating-a-new-root&quot;&gt;Creating a New Root&lt;/h2&gt;

&lt;p&gt;Here’s how &lt;a href=&quot;https://play.google.com/store/books/details/Sibsankar_Haldar_SQLite_Database_System_Design_and?id=9Z6IQQnX1JEC&amp;amp;hl=en&quot;&gt;SQLite Database System&lt;/a&gt; explains the process of creating a new root node:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;Let N be the root node. First allocate two nodes, say L and R. Move lower half of N into L and the upper half into R. Now N is empty. Add 〈L, K,R〉 in N, where K is the max key in L. Page N remains the root. Note that the depth of the tree has increased by one, but the new tree remains height balanced without violating any B+-tree property.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;At this point, we’ve already allocated the right child and moved the upper half into it. Our function takes the right child as input and allocates a new page to store the left child.&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;gi&quot;&gt;+void create_new_root(Table* table, uint32_t right_child_page_num) {
+  /*
+  Handle splitting the root.
+  Old root copied to new page, becomes left child.
+  Address of right child passed in.
+  Re-initialize root page to contain the new root node.
+  New root node points to two children.
+  */
+
+  void* root = get_page(table-&amp;gt;pager, table-&amp;gt;root_page_num);
+  void* right_child = get_page(table-&amp;gt;pager, right_child_page_num);
+  uint32_t left_child_page_num = get_unused_page_num(table-&amp;gt;pager);
+  void* left_child = get_page(table-&amp;gt;pager, left_child_page_num);
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;The old root is copied to the left child so we can reuse the root page:&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;gi&quot;&gt;+  /* Left child has data copied from old root */
+  memcpy(left_child, root, PAGE_SIZE);
+  set_node_root(left_child, false);
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Finally we initialize the root page as a new internal node with two children.&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;gi&quot;&gt;+  /* Root node is a new internal node with one key and two children */
+  initialize_internal_node(root);
+  set_node_root(root, true);
+  *internal_node_num_keys(root) = 1;
+  *internal_node_child(root, 0) = left_child_page_num;
+  uint32_t left_child_max_key = get_node_max_key(left_child);
+  *internal_node_key(root, 0) = left_child_max_key;
+  *internal_node_right_child(root) = right_child_page_num;
+}
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;internal-node-format&quot;&gt;Internal Node Format&lt;/h2&gt;

&lt;p&gt;Now that we’re finally creating an internal node, we have to define its layout. It starts with the common header, then the number of keys it contains, then the page number of its rightmost child. Internal nodes always have one more child pointer than they have keys. That extra child pointer is stored in the header.&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;gi&quot;&gt;+/*
+ * Internal Node Header Layout
+ */
+const uint32_t INTERNAL_NODE_NUM_KEYS_SIZE = sizeof(uint32_t);
+const uint32_t INTERNAL_NODE_NUM_KEYS_OFFSET = COMMON_NODE_HEADER_SIZE;
+const uint32_t INTERNAL_NODE_RIGHT_CHILD_SIZE = sizeof(uint32_t);
+const uint32_t INTERNAL_NODE_RIGHT_CHILD_OFFSET =
+    INTERNAL_NODE_NUM_KEYS_OFFSET + INTERNAL_NODE_NUM_KEYS_SIZE;
+const uint32_t INTERNAL_NODE_HEADER_SIZE = COMMON_NODE_HEADER_SIZE +
+                                           INTERNAL_NODE_NUM_KEYS_SIZE +
+                                           INTERNAL_NODE_RIGHT_CHILD_SIZE;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;The body is an array of cells where each cell contains a child pointer and a key. Every key should be the maximum key contained in the child to its left.&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;gi&quot;&gt;+/*
+ * Internal Node Body Layout
+ */
+const uint32_t INTERNAL_NODE_KEY_SIZE = sizeof(uint32_t);
+const uint32_t INTERNAL_NODE_CHILD_SIZE = sizeof(uint32_t);
+const uint32_t INTERNAL_NODE_CELL_SIZE =
+    INTERNAL_NODE_CHILD_SIZE + INTERNAL_NODE_KEY_SIZE;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Based on these constants, here’s how the layout of an internal node will look:&lt;/p&gt;

&lt;table class=&quot;image&quot;&gt;
&lt;caption align=&quot;bottom&quot;&gt;Our internal node format&lt;/caption&gt;
&lt;tr&gt;&lt;td&gt;&lt;a href=&quot;https://guimy.tech/db_tutorial/assets/images/internal-node-format.png&quot;&gt;&lt;img src=&quot;https://guimy.tech/db_tutorial/assets/images/internal-node-format.png&quot; alt=&quot;Our internal node format&quot; /&gt;&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;/table&gt;

&lt;p&gt;Notice our huge branching factor. Because each child pointer / key pair is so small, we can fit 510 keys and 511 child pointers in each internal node. That means we’ll never have to traverse many layers of the tree to find a given key!&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;# internal node layers&lt;/th&gt;
      &lt;th&gt;max # leaf nodes&lt;/th&gt;
      &lt;th&gt;Size of all leaf nodes&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;0&lt;/td&gt;
      &lt;td&gt;511^0 = 1&lt;/td&gt;
      &lt;td&gt;4 KB&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;1&lt;/td&gt;
      &lt;td&gt;511^1 = 512&lt;/td&gt;
      &lt;td&gt;~2 MB&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;2&lt;/td&gt;
      &lt;td&gt;511^2 = 261,121&lt;/td&gt;
      &lt;td&gt;~1 GB&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;3&lt;/td&gt;
      &lt;td&gt;511^3 = 133,432,831&lt;/td&gt;
      &lt;td&gt;~550 GB&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;In actuality, we can’t store a full 4 KB of data per leaf node due to the overhead of the header, keys, and wasted space. But we can search through something like 500 GB of data by loading only 4 pages from disk. This is why the B-Tree is a useful data structure for databases.&lt;/p&gt;

&lt;p&gt;Here are the methods for reading and writing to an internal node:&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;gi&quot;&gt;+uint32_t* internal_node_num_keys(void* node) {
+  return node + INTERNAL_NODE_NUM_KEYS_OFFSET;
+}
+
+uint32_t* internal_node_right_child(void* node) {
+  return node + INTERNAL_NODE_RIGHT_CHILD_OFFSET;
+}
+
+uint32_t* internal_node_cell(void* node, uint32_t cell_num) {
+  return node + INTERNAL_NODE_HEADER_SIZE + cell_num * INTERNAL_NODE_CELL_SIZE;
+}
+
+uint32_t* internal_node_child(void* node, uint32_t child_num) {
+  uint32_t num_keys = *internal_node_num_keys(node);
+  if (child_num &amp;gt; num_keys) {
+    printf(&quot;Tried to access child_num %d &amp;gt; num_keys %d\n&quot;, child_num, num_keys);
+    exit(EXIT_FAILURE);
+  } else if (child_num == num_keys) {
+    return internal_node_right_child(node);
+  } else {
+    return internal_node_cell(node, child_num);
+  }
+}
+
+uint32_t* internal_node_key(void* node, uint32_t key_num) {
+  return internal_node_cell(node, key_num) + INTERNAL_NODE_CHILD_SIZE;
+}
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;For an internal node, the maximum key is always its right key. For a leaf node, it’s the key at the maximum index:&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;gi&quot;&gt;+uint32_t get_node_max_key(void* node) {
+  switch (get_node_type(node)) {
+    case NODE_INTERNAL:
+      return *internal_node_key(node, *internal_node_num_keys(node) - 1);
+    case NODE_LEAF:
+      return *leaf_node_key(node, *leaf_node_num_cells(node) - 1);
+  }
+}
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;keeping-track-of-the-root&quot;&gt;Keeping Track of the Root&lt;/h2&gt;

&lt;p&gt;We’re finally using the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;is_root&lt;/code&gt; field in the common node header. Recall that we use it to decide how to split a leaf node:&lt;/p&gt;

&lt;div class=&quot;language-c highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;  &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;is_node_root&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;old_node&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;create_new_root&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cursor&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;table&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;new_page_num&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
  &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;printf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;Need to implement updating parent after split&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;exit&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;EXIT_FAILURE&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
  &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;err&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Here are the getter and setter:&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;gi&quot;&gt;+bool is_node_root(void* node) {
+  uint8_t value = *((uint8_t*)(node + IS_ROOT_OFFSET));
+  return (bool)value;
+}
+
+void set_node_root(void* node, bool is_root) {
+  uint8_t value = is_root;
+  *((uint8_t*)(node + IS_ROOT_OFFSET)) = value;
+}
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Initializing both types of nodes should default to setting &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;is_root&lt;/code&gt; to false:&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt; void initialize_leaf_node(void* node) {
   set_node_type(node, NODE_LEAF);
&lt;span class=&quot;gi&quot;&gt;+  set_node_root(node, false);
&lt;/span&gt;   *leaf_node_num_cells(node) = 0;
 }

+void initialize_internal_node(void* node) {
&lt;span class=&quot;gi&quot;&gt;+  set_node_type(node, NODE_INTERNAL);
+  set_node_root(node, false);
+  *internal_node_num_keys(node) = 0;
+}
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;We should set &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;is_root&lt;/code&gt; to true when creating the first node of the table:&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;     // New database file. Initialize page 0 as leaf node.
     void* root_node = get_page(pager, 0);
     initialize_leaf_node(root_node);
&lt;span class=&quot;gi&quot;&gt;+    set_node_root(root_node, true);
&lt;/span&gt;   }
 
   return table;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;printing-the-tree&quot;&gt;Printing the Tree&lt;/h2&gt;

&lt;p&gt;To help us visualize the state of the database, we should update our &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.btree&lt;/code&gt; metacommand to print a multi-level tree.&lt;/p&gt;

&lt;p&gt;I’m going to replace the current &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;print_leaf_node()&lt;/code&gt; function&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;gd&quot;&gt;-void print_leaf_node(void* node) {
-  uint32_t num_cells = *leaf_node_num_cells(node);
-  printf(&quot;leaf (size %d)\n&quot;, num_cells);
-  for (uint32_t i = 0; i &amp;lt; num_cells; i++) {
-    uint32_t key = *leaf_node_key(node, i);
-    printf(&quot;  - %d : %d\n&quot;, i, key);
-  }
-}
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;with a new recursive function that takes any node, then prints it and its children. It takes an indentation level as a parameter, which increases with each recursive call. I’m also adding a tiny helper function to indent.&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;gi&quot;&gt;+void indent(uint32_t level) {
+  for (uint32_t i = 0; i &amp;lt; level; i++) {
+    printf(&quot;  &quot;);
+  }
+}
+
+void print_tree(Pager* pager, uint32_t page_num, uint32_t indentation_level) {
+  void* node = get_page(pager, page_num);
+  uint32_t num_keys, child;
+
+  switch (get_node_type(node)) {
+    case (NODE_LEAF):
+      num_keys = *leaf_node_num_cells(node);
+      indent(indentation_level);
+      printf(&quot;- leaf (size %d)\n&quot;, num_keys);
+      for (uint32_t i = 0; i &amp;lt; num_keys; i++) {
+        indent(indentation_level + 1);
+        printf(&quot;- %d\n&quot;, *leaf_node_key(node, i));
+      }
+      break;
+    case (NODE_INTERNAL):
+      num_keys = *internal_node_num_keys(node);
+      indent(indentation_level);
+      printf(&quot;- internal (size %d)\n&quot;, num_keys);
+      for (uint32_t i = 0; i &amp;lt; num_keys; i++) {
+        child = *internal_node_child(node, i);
+        print_tree(pager, child, indentation_level + 1);
+
+        indent(indentation_level + 1);
+        printf(&quot;- key %d\n&quot;, *internal_node_key(node, i));
+      }
+      child = *internal_node_right_child(node);
+      print_tree(pager, child, indentation_level + 1);
+      break;
+  }
+}
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;And update the call to the print function, passing an indentation level of zero.&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;   } else if (strcmp(input_buffer-&amp;gt;buffer, &quot;.btree&quot;) == 0) {
     printf(&quot;Tree:\n&quot;);
&lt;span class=&quot;gd&quot;&gt;-    print_leaf_node(get_page(table-&amp;gt;pager, 0));
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+    print_tree(table-&amp;gt;pager, 0, 0);
&lt;/span&gt;     return META_COMMAND_SUCCESS;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Here’s a test case for the new printing functionality!&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;gi&quot;&gt;+  it 'allows printing out the structure of a 3-leaf-node btree' do
+    script = (1..14).map do |i|
+      &quot;insert #{i} user#{i} person#{i}@example.com&quot;
+    end
+    script &amp;lt;&amp;lt; &quot;.btree&quot;
+    script &amp;lt;&amp;lt; &quot;insert 15 user15 person15@example.com&quot;
+    script &amp;lt;&amp;lt; &quot;.exit&quot;
+    result = run_script(script)
+
+    expect(result[14...(result.length)]).to match_array([
+      &quot;db &amp;gt; Tree:&quot;,
+      &quot;- internal (size 1)&quot;,
+      &quot;  - leaf (size 7)&quot;,
+      &quot;    - 1&quot;,
+      &quot;    - 2&quot;,
+      &quot;    - 3&quot;,
+      &quot;    - 4&quot;,
+      &quot;    - 5&quot;,
+      &quot;    - 6&quot;,
+      &quot;    - 7&quot;,
+      &quot;  - key 7&quot;,
+      &quot;  - leaf (size 7)&quot;,
+      &quot;    - 8&quot;,
+      &quot;    - 9&quot;,
+      &quot;    - 10&quot;,
+      &quot;    - 11&quot;,
+      &quot;    - 12&quot;,
+      &quot;    - 13&quot;,
+      &quot;    - 14&quot;,
+      &quot;db &amp;gt; Need to implement searching an internal node&quot;,
+    ])
+  end
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;The new format is a little simplified, so we need to update the existing &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.btree&lt;/code&gt; test:&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;       &quot;db &amp;gt; Executed.&quot;,
       &quot;db &amp;gt; Executed.&quot;,
       &quot;db &amp;gt; Tree:&quot;,
&lt;span class=&quot;gd&quot;&gt;-      &quot;leaf (size 3)&quot;,
-      &quot;  - 0 : 1&quot;,
-      &quot;  - 1 : 2&quot;,
-      &quot;  - 2 : 3&quot;,
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+      &quot;- leaf (size 3)&quot;,
+      &quot;  - 1&quot;,
+      &quot;  - 2&quot;,
+      &quot;  - 3&quot;,
&lt;/span&gt;       &quot;db &amp;gt; &quot;
     ])
   end
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Here’s the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.btree&lt;/code&gt; output of the new test on its own:&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Tree:
- internal (size 1)
  - leaf (size 7)
    - 1
    - 2
    - 3
    - 4
    - 5
    - 6
    - 7
  - key 7
  - leaf (size 7)
    - 8
    - 9
    - 10
    - 11
    - 12
    - 13
    - 14
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;On the least indented level, we see the root node (an internal node). It says &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;size 1&lt;/code&gt; because it has one key. Indented one level, we see a leaf node, a key, and another leaf node. The key in the root node (7) is is the maximum key in the first leaf node. Every key greater than 7 is in the second leaf node.&lt;/p&gt;

&lt;h2 id=&quot;a-major-problem&quot;&gt;A Major Problem&lt;/h2&gt;

&lt;p&gt;If you’ve been following along closely you may notice we’ve missed something big. Look what happens if we try to insert one additional row:&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;db &amp;gt; insert 15 user15 person15@example.com
Need to implement searching an internal node
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Whoops! Who wrote that TODO message? :P&lt;/p&gt;

&lt;p&gt;Next time we’ll continue the epic B-tree saga by implementing search on a multi-level tree.&lt;/p&gt;
</description>
        <pubDate>Mon, 09 Oct 2017 00:00:00 +0000</pubDate>
        <link>https://guimy.tech/db_tutorial/parts/part10.html</link>
        <guid isPermaLink="true">https://guimy.tech/db_tutorial/parts/part10.html</guid>
      </item>
    
      <item>
        <title>Part 11 - Recursively Searching the B-Tree</title>
        <description>&lt;p&gt;Last time we ended with an error inserting our 15th row:&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;db &amp;gt; insert 15 user15 person15@example.com
Need to implement searching an internal node
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;First, replace the code stub with a new function call.&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;   if (get_node_type(root_node) == NODE_LEAF) {
     return leaf_node_find(table, root_page_num, key);
   } else {
&lt;span class=&quot;gd&quot;&gt;-    printf(&quot;Need to implement searching an internal node\n&quot;);
-    exit(EXIT_FAILURE);
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+    return internal_node_find(table, root_page_num, key);
&lt;/span&gt;   }
 }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;This function will perform binary search to find the child that should contain the given key. Remember that the key to the right of each child pointer is the maximum key contained by that child.&lt;/p&gt;

&lt;table class=&quot;image&quot;&gt;
&lt;caption align=&quot;bottom&quot;&gt;three-level btree&lt;/caption&gt;
&lt;tr&gt;&lt;td&gt;&lt;a href=&quot;https://guimy.tech/db_tutorial/assets/images/btree6.png&quot;&gt;&lt;img src=&quot;https://guimy.tech/db_tutorial/assets/images/btree6.png&quot; alt=&quot;three-level btree&quot; /&gt;&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;/table&gt;

&lt;p&gt;So our binary search compares the key to find and the key to the right of the child pointer:&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;gi&quot;&gt;+Cursor* internal_node_find(Table* table, uint32_t page_num, uint32_t key) {
+  void* node = get_page(table-&amp;gt;pager, page_num);
+  uint32_t num_keys = *internal_node_num_keys(node);
+
+  /* Binary search to find index of child to search */
+  uint32_t min_index = 0;
+  uint32_t max_index = num_keys; /* there is one more child than key */
+
+  while (min_index != max_index) {
+    uint32_t index = (min_index + max_index) / 2;
+    uint32_t key_to_right = *internal_node_key(node, index);
+    if (key_to_right &amp;gt;= key) {
+      max_index = index;
+    } else {
+      min_index = index + 1;
+    }
+  }
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Also remember that the children of an internal node can be either leaf nodes or more internal nodes. After we find the correct child, call the appropriate search function on it:&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;gi&quot;&gt;+  uint32_t child_num = *internal_node_child(node, min_index);
+  void* child = get_page(table-&amp;gt;pager, child_num);
+  switch (get_node_type(child)) {
+    case NODE_LEAF:
+      return leaf_node_find(table, child_num, key);
+    case NODE_INTERNAL:
+      return internal_node_find(table, child_num, key);
+  }
+}
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h1 id=&quot;tests&quot;&gt;Tests&lt;/h1&gt;

&lt;p&gt;Now inserting a key into a multi-node btree no longer results in an error. And we can update our test:&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;       &quot;    - 12&quot;,
       &quot;    - 13&quot;,
       &quot;    - 14&quot;,
&lt;span class=&quot;gd&quot;&gt;-      &quot;db &amp;gt; Need to implement searching an internal node&quot;,
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+      &quot;db &amp;gt; Executed.&quot;,
+      &quot;db &amp;gt; &quot;,
&lt;/span&gt;     ])
   end
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;I also think it’s time we revisit another test. The one that tries inserting 1400 rows. It still errors, but the error message is new. Right now, our tests don’t handle it very well when the program crashes. If that happens, let’s just use the output we’ve gotten so far:&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;     raw_output = nil
     IO.popen(&quot;./db test.db&quot;, &quot;r+&quot;) do |pipe|
       commands.each do |command|
&lt;span class=&quot;gd&quot;&gt;-        pipe.puts command
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+        begin
+          pipe.puts command
+        rescue Errno::EPIPE
+          break
+        end
&lt;/span&gt;       end

       pipe.close_write
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;And that reveals that our 1400-row test outputs this error:&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;     end
     script &amp;lt;&amp;lt; &quot;.exit&quot;
     result = run_script(script)
&lt;span class=&quot;gd&quot;&gt;-    expect(result[-2]).to eq('db &amp;gt; Error: Table full.')
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+    expect(result.last(2)).to match_array([
+      &quot;db &amp;gt; Executed.&quot;,
+      &quot;db &amp;gt; Need to implement updating parent after split&quot;,
+    ])
&lt;/span&gt;   end
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Looks like that’s next on our to-do list!&lt;/p&gt;

</description>
        <pubDate>Sun, 22 Oct 2017 00:00:00 +0000</pubDate>
        <link>https://guimy.tech/db_tutorial/parts/part11.html</link>
        <guid isPermaLink="true">https://guimy.tech/db_tutorial/parts/part11.html</guid>
      </item>
    
      <item>
        <title>Part 12 - Scanning a Multi-Level B-Tree</title>
        <description>&lt;p&gt;We now support constructing a multi-level btree, but we’ve broken &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;select&lt;/code&gt; statements in the process. Here’s a test case that inserts 15 rows and then tries to print them.&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;gi&quot;&gt;+  it 'prints all rows in a multi-level tree' do
+    script = []
+    (1..15).each do |i|
+      script &amp;lt;&amp;lt; &quot;insert #{i} user#{i} person#{i}@example.com&quot;
+    end
+    script &amp;lt;&amp;lt; &quot;select&quot;
+    script &amp;lt;&amp;lt; &quot;.exit&quot;
+    result = run_script(script)
+
+    expect(result[15...result.length]).to match_array([
+      &quot;db &amp;gt; (1, user1, person1@example.com)&quot;,
+      &quot;(2, user2, person2@example.com)&quot;,
+      &quot;(3, user3, person3@example.com)&quot;,
+      &quot;(4, user4, person4@example.com)&quot;,
+      &quot;(5, user5, person5@example.com)&quot;,
+      &quot;(6, user6, person6@example.com)&quot;,
+      &quot;(7, user7, person7@example.com)&quot;,
+      &quot;(8, user8, person8@example.com)&quot;,
+      &quot;(9, user9, person9@example.com)&quot;,
+      &quot;(10, user10, person10@example.com)&quot;,
+      &quot;(11, user11, person11@example.com)&quot;,
+      &quot;(12, user12, person12@example.com)&quot;,
+      &quot;(13, user13, person13@example.com)&quot;,
+      &quot;(14, user14, person14@example.com)&quot;,
+      &quot;(15, user15, person15@example.com)&quot;,
+      &quot;Executed.&quot;, &quot;db &amp;gt; &quot;,
+    ])
+  end
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;But when we run that test case right now, what actually happens is:&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;db &amp;gt; select
(2, user1, person1@example.com)
Executed.
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;That’s weird. It’s only printing one row, and that row looks corrupted (notice the id doesn’t match the username).&lt;/p&gt;

&lt;p&gt;The weirdness is because &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;execute_select()&lt;/code&gt; begins at the start of the table, and our current implementation of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;table_start()&lt;/code&gt; returns cell 0 of the root node. But the root of our tree is now an internal node which doesn’t contain any rows. The data that was printed must have been left over from when the root node was a leaf. &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;execute_select()&lt;/code&gt; should really return cell 0 of the leftmost leaf node.&lt;/p&gt;

&lt;p&gt;So get rid of the old implementation:&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;gd&quot;&gt;-Cursor* table_start(Table* table) {
-  Cursor* cursor = malloc(sizeof(Cursor));
-  cursor-&amp;gt;table = table;
-  cursor-&amp;gt;page_num = table-&amp;gt;root_page_num;
-  cursor-&amp;gt;cell_num = 0;
-
-  void* root_node = get_page(table-&amp;gt;pager, table-&amp;gt;root_page_num);
-  uint32_t num_cells = *leaf_node_num_cells(root_node);
-  cursor-&amp;gt;end_of_table = (num_cells == 0);
-
-  return cursor;
-}
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;And add a new implementation that searches for key 0 (the minimum possible key). Even if key 0 does not exist in the table, this method will return the position of the lowest id (the start of the left-most leaf node).&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;gi&quot;&gt;+Cursor* table_start(Table* table) {
+  Cursor* cursor =  table_find(table, 0);
+
+  void* node = get_page(table-&amp;gt;pager, cursor-&amp;gt;page_num);
+  uint32_t num_cells = *leaf_node_num_cells(node);
+  cursor-&amp;gt;end_of_table = (num_cells == 0);
+
+  return cursor;
+}
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;With those changes, it still only prints out one node’s worth of rows:&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;db &amp;gt; select
(1, user1, person1@example.com)
(2, user2, person2@example.com)
(3, user3, person3@example.com)
(4, user4, person4@example.com)
(5, user5, person5@example.com)
(6, user6, person6@example.com)
(7, user7, person7@example.com)
Executed.
db &amp;gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;With 15 entries, our btree consists of one internal node and two leaf nodes, which looks something like this:&lt;/p&gt;

&lt;table class=&quot;image&quot;&gt;
&lt;caption align=&quot;bottom&quot;&gt;structure of our btree&lt;/caption&gt;
&lt;tr&gt;&lt;td&gt;&lt;a href=&quot;https://guimy.tech/db_tutorial/assets/images/btree3.png&quot;&gt;&lt;img src=&quot;https://guimy.tech/db_tutorial/assets/images/btree3.png&quot; alt=&quot;structure of our btree&quot; /&gt;&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;/table&gt;

&lt;p&gt;To scan the entire table, we need to jump to the second leaf node after we reach the end of the first. To do that, we’re going to save a new field in the leaf node header called “next_leaf”, which will hold the page number of the leaf’s sibling node on the right. The rightmost leaf node will have a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;next_leaf&lt;/code&gt; value of 0 to denote no sibling (page 0 is reserved for the root node of the table anyway).&lt;/p&gt;

&lt;p&gt;Update the leaf node header format to include the new field:&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt; const uint32_t LEAF_NODE_NUM_CELLS_SIZE = sizeof(uint32_t);
 const uint32_t LEAF_NODE_NUM_CELLS_OFFSET = COMMON_NODE_HEADER_SIZE;
&lt;span class=&quot;gd&quot;&gt;-const uint32_t LEAF_NODE_HEADER_SIZE =
-    COMMON_NODE_HEADER_SIZE + LEAF_NODE_NUM_CELLS_SIZE;
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+const uint32_t LEAF_NODE_NEXT_LEAF_SIZE = sizeof(uint32_t);
+const uint32_t LEAF_NODE_NEXT_LEAF_OFFSET =
+    LEAF_NODE_NUM_CELLS_OFFSET + LEAF_NODE_NUM_CELLS_SIZE;
+const uint32_t LEAF_NODE_HEADER_SIZE = COMMON_NODE_HEADER_SIZE +
+                                       LEAF_NODE_NUM_CELLS_SIZE +
+                                       LEAF_NODE_NEXT_LEAF_SIZE;
&lt;/span&gt; 
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Add a method to access the new field:&lt;/p&gt;
&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;gi&quot;&gt;+uint32_t* leaf_node_next_leaf(void* node) {
+  return node + LEAF_NODE_NEXT_LEAF_OFFSET;
+}
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Set &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;next_leaf&lt;/code&gt; to 0 by default when initializing a new leaf node:&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;p&quot;&gt;@@ -322,6 +330,7 @@&lt;/span&gt; void initialize_leaf_node(void* node) {
   set_node_type(node, NODE_LEAF);
   set_node_root(node, false);
   *leaf_node_num_cells(node) = 0;
&lt;span class=&quot;gi&quot;&gt;+  *leaf_node_next_leaf(node) = 0;  // 0 represents no sibling
&lt;/span&gt; }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Whenever we split a leaf node, update the sibling pointers. The old leaf’s sibling becomes the new leaf, and the new leaf’s sibling becomes whatever used to be the old leaf’s sibling.&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;p&quot;&gt;@@ -659,6 +671,8 @@&lt;/span&gt; void leaf_node_split_and_insert(Cursor* cursor, uint32_t key, Row* value) {
   uint32_t new_page_num = get_unused_page_num(cursor-&amp;gt;table-&amp;gt;pager);
   void* new_node = get_page(cursor-&amp;gt;table-&amp;gt;pager, new_page_num);
   initialize_leaf_node(new_node);
&lt;span class=&quot;gi&quot;&gt;+  *leaf_node_next_leaf(new_node) = *leaf_node_next_leaf(old_node);
+  *leaf_node_next_leaf(old_node) = new_page_num;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Adding a new field changes a few constants:&lt;/p&gt;
&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;   it 'prints constants' do
     script = [
       &quot;.constants&quot;,
&lt;span class=&quot;p&quot;&gt;@@ -199,9 +228,9 @@&lt;/span&gt; describe 'database' do
       &quot;db &amp;gt; Constants:&quot;,
       &quot;ROW_SIZE: 293&quot;,
       &quot;COMMON_NODE_HEADER_SIZE: 6&quot;,
&lt;span class=&quot;gd&quot;&gt;-      &quot;LEAF_NODE_HEADER_SIZE: 10&quot;,
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+      &quot;LEAF_NODE_HEADER_SIZE: 14&quot;,
&lt;/span&gt;       &quot;LEAF_NODE_CELL_SIZE: 297&quot;,
&lt;span class=&quot;gd&quot;&gt;-      &quot;LEAF_NODE_SPACE_FOR_CELLS: 4086&quot;,
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+      &quot;LEAF_NODE_SPACE_FOR_CELLS: 4082&quot;,
&lt;/span&gt;       &quot;LEAF_NODE_MAX_CELLS: 13&quot;,
       &quot;db &amp;gt; &quot;,
     ])
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Now whenever we want to advance the cursor past the end of a leaf node, we can check if the leaf node has a sibling. If it does, jump to it. Otherwise, we’re at the end of the table.&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;p&quot;&gt;@@ -428,7 +432,15 @@&lt;/span&gt; void cursor_advance(Cursor* cursor) {
 
   cursor-&amp;gt;cell_num += 1;
   if (cursor-&amp;gt;cell_num &amp;gt;= (*leaf_node_num_cells(node))) {
&lt;span class=&quot;gd&quot;&gt;-    cursor-&amp;gt;end_of_table = true;
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+    /* Advance to next leaf node */
+    uint32_t next_page_num = *leaf_node_next_leaf(node);
+    if (next_page_num == 0) {
+      /* This was rightmost leaf */
+      cursor-&amp;gt;end_of_table = true;
+    } else {
+      cursor-&amp;gt;page_num = next_page_num;
+      cursor-&amp;gt;cell_num = 0;
+    }
&lt;/span&gt;   }
 }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;After those changes, we actually print 15 rows…&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;db &amp;gt; select
(1, user1, person1@example.com)
(2, user2, person2@example.com)
(3, user3, person3@example.com)
(4, user4, person4@example.com)
(5, user5, person5@example.com)
(6, user6, person6@example.com)
(7, user7, person7@example.com)
(8, user8, person8@example.com)
(9, user9, person9@example.com)
(10, user10, person10@example.com)
(11, user11, person11@example.com)
(12, user12, person12@example.com)
(13, user13, person13@example.com)
(1919251317, 14, on14@example.com)
(15, user15, person15@example.com)
Executed.
db &amp;gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;…but one of them looks corrupted&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;(1919251317, 14, on14@example.com)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;After some debugging, I found out it’s because of a bug in how we split leaf nodes:&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;p&quot;&gt;@@ -676,7 +690,9 @@&lt;/span&gt; void leaf_node_split_and_insert(Cursor* cursor, uint32_t key, Row* value) {
     void* destination = leaf_node_cell(destination_node, index_within_node);
 
     if (i == cursor-&amp;gt;cell_num) {
&lt;span class=&quot;gd&quot;&gt;-      serialize_row(value, destination);
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+      serialize_row(value,
+                    leaf_node_value(destination_node, index_within_node));
+      *leaf_node_key(destination_node, index_within_node) = key;
&lt;/span&gt;     } else if (i &amp;gt; cursor-&amp;gt;cell_num) {
       memcpy(destination, leaf_node_cell(old_node, i - 1), LEAF_NODE_CELL_SIZE);
     } else {
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Remember that each cell in a leaf node consists of first a key then a value:&lt;/p&gt;

&lt;table class=&quot;image&quot;&gt;
&lt;caption align=&quot;bottom&quot;&gt;Original leaf node format&lt;/caption&gt;
&lt;tr&gt;&lt;td&gt;&lt;a href=&quot;https://guimy.tech/db_tutorial/assets/images/leaf-node-format.png&quot;&gt;&lt;img src=&quot;https://guimy.tech/db_tutorial/assets/images/leaf-node-format.png&quot; alt=&quot;Original leaf node format&quot; /&gt;&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;/table&gt;

&lt;p&gt;We were writing the new row (value) into the start of the cell, where the key should go. That means part of the username was going into the section for id (hence the crazy large id).&lt;/p&gt;

&lt;p&gt;After fixing that bug, we finally print out the entire table as expected:&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;db &amp;gt; select
(1, user1, person1@example.com)
(2, user2, person2@example.com)
(3, user3, person3@example.com)
(4, user4, person4@example.com)
(5, user5, person5@example.com)
(6, user6, person6@example.com)
(7, user7, person7@example.com)
(8, user8, person8@example.com)
(9, user9, person9@example.com)
(10, user10, person10@example.com)
(11, user11, person11@example.com)
(12, user12, person12@example.com)
(13, user13, person13@example.com)
(14, user14, person14@example.com)
(15, user15, person15@example.com)
Executed.
db &amp;gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Whew! One bug after another, but we’re making progress.&lt;/p&gt;

&lt;p&gt;Until next time.&lt;/p&gt;
</description>
        <pubDate>Sat, 11 Nov 2017 00:00:00 +0000</pubDate>
        <link>https://guimy.tech/db_tutorial/parts/part12.html</link>
        <guid isPermaLink="true">https://guimy.tech/db_tutorial/parts/part12.html</guid>
      </item>
    
      <item>
        <title>Part 13 - Updating Parent Node After a Split</title>
        <description>&lt;p&gt;For the next step on our epic b-tree implementation journey, we’re going to handle fixing up the parent node after splitting a leaf. I’m going to use the following example as a reference:&lt;/p&gt;

&lt;table class=&quot;image&quot;&gt;
&lt;caption align=&quot;bottom&quot;&gt;Example of updating internal node&lt;/caption&gt;
&lt;tr&gt;&lt;td&gt;&lt;a href=&quot;https://guimy.tech/db_tutorial/assets/images/updating-internal-node.png&quot;&gt;&lt;img src=&quot;https://guimy.tech/db_tutorial/assets/images/updating-internal-node.png&quot; alt=&quot;Example of updating internal node&quot; /&gt;&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;/table&gt;

&lt;p&gt;In this example, we add the key “3” to the tree. That causes the left leaf node to split. After the split we fix up the tree by doing the following:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Update the first key in the parent to be the maximum key in the left child (“3”)&lt;/li&gt;
  &lt;li&gt;Add a new child pointer / key pair after the updated key
    &lt;ul&gt;
      &lt;li&gt;The new pointer points to the new child node&lt;/li&gt;
      &lt;li&gt;The new key is the maximum key in the new child node (“5”)&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;So first things first, replace our stub code with two new function calls: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;update_internal_node_key()&lt;/code&gt; for step 1 and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;internal_node_insert()&lt;/code&gt; for step 2&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;p&quot;&gt;@@ -670,9 +725,11 @@&lt;/span&gt; void leaf_node_split_and_insert(Cursor* cursor, uint32_t key, Row* value) {
   */
 
   void* old_node = get_page(cursor-&amp;gt;table-&amp;gt;pager, cursor-&amp;gt;page_num);
&lt;span class=&quot;gi&quot;&gt;+  uint32_t old_max = get_node_max_key(old_node);
&lt;/span&gt;   uint32_t new_page_num = get_unused_page_num(cursor-&amp;gt;table-&amp;gt;pager);
   void* new_node = get_page(cursor-&amp;gt;table-&amp;gt;pager, new_page_num);
   initialize_leaf_node(new_node);
&lt;span class=&quot;gi&quot;&gt;+  *node_parent(new_node) = *node_parent(old_node);
&lt;/span&gt;   *leaf_node_next_leaf(new_node) = *leaf_node_next_leaf(old_node);
   *leaf_node_next_leaf(old_node) = new_page_num;
 
&lt;span class=&quot;p&quot;&gt;@@ -709,8 +766,12 @@&lt;/span&gt; void leaf_node_split_and_insert(Cursor* cursor, uint32_t key, Row* value) {
   if (is_node_root(old_node)) {
     return create_new_root(cursor-&amp;gt;table, new_page_num);
   } else {
&lt;span class=&quot;gd&quot;&gt;-    printf(&quot;Need to implement updating parent after split\n&quot;);
-    exit(EXIT_FAILURE);
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+    uint32_t parent_page_num = *node_parent(old_node);
+    uint32_t new_max = get_node_max_key(old_node);
+    void* parent = get_page(cursor-&amp;gt;table-&amp;gt;pager, parent_page_num);
+
+    update_internal_node_key(parent, old_max, new_max);
+    internal_node_insert(cursor-&amp;gt;table, parent_page_num, new_page_num);
+    return;
&lt;/span&gt;   }
 }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;In order to get a reference to the parent, we need to start recording in each node a pointer to its parent node.&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;gi&quot;&gt;+uint32_t* node_parent(void* node) { return node + PARENT_POINTER_OFFSET; }
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;p&quot;&gt;@@ -660,6 +675,48 @@&lt;/span&gt; void create_new_root(Table* table, uint32_t right_child_page_num) {
   uint32_t left_child_max_key = get_node_max_key(left_child);
   *internal_node_key(root, 0) = left_child_max_key;
   *internal_node_right_child(root) = right_child_page_num;
&lt;span class=&quot;gi&quot;&gt;+  *node_parent(left_child) = table-&amp;gt;root_page_num;
+  *node_parent(right_child) = table-&amp;gt;root_page_num;
&lt;/span&gt; }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Now we need to find the affected cell in the parent node. The child doesn’t know its own page number, so we can’t look for that. But it does know its own maximum key, so we can search the parent for that key.&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;gi&quot;&gt;+void update_internal_node_key(void* node, uint32_t old_key, uint32_t new_key) {
+  uint32_t old_child_index = internal_node_find_child(node, old_key);
+  *internal_node_key(node, old_child_index) = new_key;
&lt;/span&gt; }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Inside &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;internal_node_find_child()&lt;/code&gt; we’ll reuse some code we already have for finding a key in an internal node. Refactor &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;internal_node_find()&lt;/code&gt; to use the new helper method.&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;gd&quot;&gt;-Cursor* internal_node_find(Table* table, uint32_t page_num, uint32_t key) {
-  void* node = get_page(table-&amp;gt;pager, page_num);
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+uint32_t internal_node_find_child(void* node, uint32_t key) {
+  /*
+  Return the index of the child which should contain
+  the given key.
+  */
+
&lt;/span&gt;   uint32_t num_keys = *internal_node_num_keys(node);
 
&lt;span class=&quot;gd&quot;&gt;-  /* Binary search to find index of child to search */
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+  /* Binary search */
&lt;/span&gt;   uint32_t min_index = 0;
   uint32_t max_index = num_keys; /* there is one more child than key */
 
&lt;span class=&quot;p&quot;&gt;@@ -386,7 +394,14 @@&lt;/span&gt; Cursor* internal_node_find(Table* table, uint32_t page_num, uint32_t key) {
     }
   }
 
&lt;span class=&quot;gd&quot;&gt;-  uint32_t child_num = *internal_node_child(node, min_index);
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+  return min_index;
+}
+
+Cursor* internal_node_find(Table* table, uint32_t page_num, uint32_t key) {
+  void* node = get_page(table-&amp;gt;pager, page_num);
+
+  uint32_t child_index = internal_node_find_child(node, key);
+  uint32_t child_num = *internal_node_child(node, child_index);
&lt;/span&gt;   void* child = get_page(table-&amp;gt;pager, child_num);
   switch (get_node_type(child)) {
     case NODE_LEAF:
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Now we get to the heart of this article, implementing &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;internal_node_insert()&lt;/code&gt;. I’ll explain it in pieces.&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;gi&quot;&gt;+void internal_node_insert(Table* table, uint32_t parent_page_num,
+                          uint32_t child_page_num) {
+  /*
+  Add a new child/key pair to parent that corresponds to child
+  */
+
+  void* parent = get_page(table-&amp;gt;pager, parent_page_num);
+  void* child = get_page(table-&amp;gt;pager, child_page_num);
+  uint32_t child_max_key = get_node_max_key(child);
+  uint32_t index = internal_node_find_child(parent, child_max_key);
+
+  uint32_t original_num_keys = *internal_node_num_keys(parent);
+  *internal_node_num_keys(parent) = original_num_keys + 1;
+
+  if (original_num_keys &amp;gt;= INTERNAL_NODE_MAX_CELLS) {
+    printf(&quot;Need to implement splitting internal node\n&quot;);
+    exit(EXIT_FAILURE);
+  }
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;The index where the new cell (child/key pair) should be inserted depends on the maximum key in the new child. In the example we looked at, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;child_max_key&lt;/code&gt; would be 5 and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;index&lt;/code&gt; would be 1.&lt;/p&gt;

&lt;p&gt;If there’s no room in the internal node for another cell, throw an error. We’ll implement that later.&lt;/p&gt;

&lt;p&gt;Now let’s look at the rest of the function:&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;gi&quot;&gt;+
+  uint32_t right_child_page_num = *internal_node_right_child(parent);
+  void* right_child = get_page(table-&amp;gt;pager, right_child_page_num);
+
+  if (child_max_key &amp;gt; get_node_max_key(right_child)) {
+    /* Replace right child */
+    *internal_node_child(parent, original_num_keys) = right_child_page_num;
+    *internal_node_key(parent, original_num_keys) =
+        get_node_max_key(right_child);
+    *internal_node_right_child(parent) = child_page_num;
+  } else {
+    /* Make room for the new cell */
+    for (uint32_t i = original_num_keys; i &amp;gt; index; i--) {
+      void* destination = internal_node_cell(parent, i);
+      void* source = internal_node_cell(parent, i - 1);
+      memcpy(destination, source, INTERNAL_NODE_CELL_SIZE);
+    }
+    *internal_node_child(parent, index) = child_page_num;
+    *internal_node_key(parent, index) = child_max_key;
+  }
+}
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Because we store the rightmost child pointer separately from the rest of the child/key pairs, we have to handle things differently if the new child is going to become the rightmost child.&lt;/p&gt;

&lt;p&gt;In our example, we would get into the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;else&lt;/code&gt; block. First we make room for the new cell by shifting other cells one space to the right. (Although in our example there are 0 cells to shift)&lt;/p&gt;

&lt;p&gt;Next, we write the new child pointer and key into the cell determined by &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;index&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;To reduce the size of testcases needed, I’m hardcoding &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;INTERNAL_NODE_MAX_CELLS&lt;/code&gt; for now&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;p&quot;&gt;@@ -126,6 +126,8 @@&lt;/span&gt; const uint32_t INTERNAL_NODE_KEY_SIZE = sizeof(uint32_t);
 const uint32_t INTERNAL_NODE_CHILD_SIZE = sizeof(uint32_t);
 const uint32_t INTERNAL_NODE_CELL_SIZE =
     INTERNAL_NODE_CHILD_SIZE + INTERNAL_NODE_KEY_SIZE;
&lt;span class=&quot;gi&quot;&gt;+/* Keep this small for testing */
+const uint32_t INTERNAL_NODE_MAX_CELLS = 3;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Speaking of tests, our large-dataset test gets past our old stub and gets to our new one:&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;p&quot;&gt;@@ -65,7 +65,7 @@&lt;/span&gt; describe 'database' do
     result = run_script(script)
     expect(result.last(2)).to match_array([
       &quot;db &amp;gt; Executed.&quot;,
&lt;span class=&quot;gd&quot;&gt;-      &quot;db &amp;gt; Need to implement updating parent after split&quot;,
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+      &quot;db &amp;gt; Need to implement splitting internal node&quot;,
&lt;/span&gt;     ])
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Very satisfying, I know.&lt;/p&gt;

&lt;p&gt;I’ll add another test that prints a four-node tree. Just so we test more cases than sequential ids, this test will add records in a pseudorandom order.&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;gi&quot;&gt;+  it 'allows printing out the structure of a 4-leaf-node btree' do
+    script = [
+      &quot;insert 18 user18 person18@example.com&quot;,
+      &quot;insert 7 user7 person7@example.com&quot;,
+      &quot;insert 10 user10 person10@example.com&quot;,
+      &quot;insert 29 user29 person29@example.com&quot;,
+      &quot;insert 23 user23 person23@example.com&quot;,
+      &quot;insert 4 user4 person4@example.com&quot;,
+      &quot;insert 14 user14 person14@example.com&quot;,
+      &quot;insert 30 user30 person30@example.com&quot;,
+      &quot;insert 15 user15 person15@example.com&quot;,
+      &quot;insert 26 user26 person26@example.com&quot;,
+      &quot;insert 22 user22 person22@example.com&quot;,
+      &quot;insert 19 user19 person19@example.com&quot;,
+      &quot;insert 2 user2 person2@example.com&quot;,
+      &quot;insert 1 user1 person1@example.com&quot;,
+      &quot;insert 21 user21 person21@example.com&quot;,
+      &quot;insert 11 user11 person11@example.com&quot;,
+      &quot;insert 6 user6 person6@example.com&quot;,
+      &quot;insert 20 user20 person20@example.com&quot;,
+      &quot;insert 5 user5 person5@example.com&quot;,
+      &quot;insert 8 user8 person8@example.com&quot;,
+      &quot;insert 9 user9 person9@example.com&quot;,
+      &quot;insert 3 user3 person3@example.com&quot;,
+      &quot;insert 12 user12 person12@example.com&quot;,
+      &quot;insert 27 user27 person27@example.com&quot;,
+      &quot;insert 17 user17 person17@example.com&quot;,
+      &quot;insert 16 user16 person16@example.com&quot;,
+      &quot;insert 13 user13 person13@example.com&quot;,
+      &quot;insert 24 user24 person24@example.com&quot;,
+      &quot;insert 25 user25 person25@example.com&quot;,
+      &quot;insert 28 user28 person28@example.com&quot;,
+      &quot;.btree&quot;,
+      &quot;.exit&quot;,
+    ]
+    result = run_script(script)
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;As-is, it will output this:&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;- internal (size 3)
  - leaf (size 7)
    - 1
    - 2
    - 3
    - 4
    - 5
    - 6
    - 7
  - key 1
  - leaf (size 8)
    - 8
    - 9
    - 10
    - 11
    - 12
    - 13
    - 14
    - 15
  - key 15
  - leaf (size 7)
    - 16
    - 17
    - 18
    - 19
    - 20
    - 21
    - 22
  - key 22
  - leaf (size 8)
    - 23
    - 24
    - 25
    - 26
    - 27
    - 28
    - 29
    - 30
db &amp;gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Look carefully and you’ll spot a bug:&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;    - 5
    - 6
    - 7
  - key 1
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;The key there should be 7, not 1!&lt;/p&gt;

&lt;p&gt;After a bunch of debugging, I discovered this was due to some bad pointer arithmetic.&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt; uint32_t* internal_node_key(void* node, uint32_t key_num) {
&lt;span class=&quot;gd&quot;&gt;-  return internal_node_cell(node, key_num) + INTERNAL_NODE_CHILD_SIZE;
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+  return (void*)internal_node_cell(node, key_num) + INTERNAL_NODE_CHILD_SIZE;
&lt;/span&gt; }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;INTERNAL_NODE_CHILD_SIZE&lt;/code&gt; is 4. My intention here was to add 4 bytes to the result of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;internal_node_cell()&lt;/code&gt;, but since &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;internal_node_cell()&lt;/code&gt; returns a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;uint32_t*&lt;/code&gt;, this it was actually adding &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;4 * sizeof(uint32_t)&lt;/code&gt; bytes. I fixed it by casting to a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;void*&lt;/code&gt; before doing the arithmetic.&lt;/p&gt;

&lt;p&gt;NOTE! &lt;a href=&quot;https://stackoverflow.com/questions/3523145/pointer-arithmetic-for-void-pointer-in-c/46238658#46238658&quot;&gt;Pointer arithmetic on void pointers is not part of the C standard and may not work with your compiler&lt;/a&gt;. I may do an article in the future on portability, but I’m leaving my void pointer arithmetic for now.&lt;/p&gt;

&lt;p&gt;Alright. One more step toward a fully-operational btree implementation. The next step should be splitting internal nodes. Until then!&lt;/p&gt;
</description>
        <pubDate>Sun, 26 Nov 2017 00:00:00 +0000</pubDate>
        <link>https://guimy.tech/db_tutorial/parts/part13.html</link>
        <guid isPermaLink="true">https://guimy.tech/db_tutorial/parts/part13.html</guid>
      </item>
    
      <item>
        <title>Part 14 - Splitting a Internal Node</title>
        <description>&lt;p&gt;If the internal node of our B+-tree is full, the process of out database will exit when inserting another cell to the internal node. Now it’s time to working it out. I’m going to use the following example as a reference:&lt;/p&gt;

&lt;table class=&quot;image&quot;&gt;
&lt;caption align=&quot;bottom&quot;&gt;Example of splitting internal node&lt;/caption&gt;
&lt;tr&gt;&lt;td&gt;&lt;a href=&quot;https://guimy.tech/db_tutorial/assets/images/splitting-internal-node.png&quot;&gt;&lt;img src=&quot;https://guimy.tech/db_tutorial/assets/images/splitting-internal-node.png&quot; alt=&quot;Example of splitting internal node&quot; /&gt;&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;/table&gt;

&lt;p&gt;In this example, we add the key “8” to the tree. That causes the third leaf node(with key 7 and key 9) to split. After the split , a new leaf node is created, and then the cell of key “8” should be added to the parent internal node, but now the internal node is full. We fix up the tree by splitting the internal node with the following steps after we finished the splitting of the third leaf node:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Update the old max key “9” in the parent to the new max key in the old leaf node “8”.&lt;/li&gt;
  &lt;li&gt;Split the parent internal node and add a new child pointer/key pair to one of the splited internal node.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;splitting-algorithm&quot;&gt;Splitting Algorithm&lt;/h2&gt;

&lt;p&gt;Let’s take an example of an internal node with the number of maximum keys of 3, and the root internal node is full with keys 7, 21, 28, so this node has four pointers. The result of the splitting of the leaf node is two leaf node with maximum key 14 and 21, so we should insert key key 14 into the parent internal node. The Splitting process just like this:&lt;/p&gt;
&lt;table class=&quot;image&quot;&gt;
&lt;caption align=&quot;bottom&quot;&gt;splitting internal node&lt;/caption&gt;
&lt;tr&gt;&lt;td&gt;&lt;a href=&quot;https://guimy.tech/db_tutorial/assets/images/internal-node-split-demo.png&quot;&gt;&lt;img src=&quot;https://guimy.tech/db_tutorial/assets/images/internal-node-split-demo.png&quot; alt=&quot;splitting internal node&quot; /&gt;&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;/table&gt;

&lt;p&gt;As the part 10 did, we should update the key of the internal node after the splitting of child leaf node. So, in our example above, if the maximum size of internal node is greater than 3, the index of key 14 should be 1 (0-based) of the key array. So we update the key of index 1 with 14, which means replacing key 21 with key 14. As a result, the (left) pointer of key 14 points to the leaf node with maximum key of 14. Then add key 21 and page number to the parent internal node. But the maximum size of internal node is 3, so we should split the internal node.&lt;/p&gt;

&lt;h2 id=&quot;splitting-internal-node&quot;&gt;Splitting internal node&lt;/h2&gt;

&lt;p&gt;So, let’s going on with constants for splitting internal node.&lt;/p&gt;
&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;gi&quot;&gt;+ const u_int32_t INTERNAL_NODE_RIGHT_SPLIT_COUNT = (INTERNAL_NODE_MAX_CELLS + 1) / 2;
+ const u_int32_t INTERNAL_NODE_LEFT_SPLIT_COUNT = (INTERNAL_NODE_MAX_CELLS + 1) - INTERNAL_NODE_RIGHT_SPLIT_COUNT - 1;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;And then, replace our stub code with the new function calls: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;internal_node_split_insert()&lt;/code&gt; for splitting internal node.&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;gi&quot;&gt;+ if (original_num_keys &amp;gt;= INTERNAL_NODE_MAX_CELLS) {
&lt;/span&gt;&lt;span class=&quot;gd&quot;&gt;-   printf(&quot;Need to implement splitting internal node\n&quot;);
-   exit(EXIT_FAILURE);
&lt;/span&gt;&lt;span class=&quot;gi&quot;&gt;+   internal_node_split_insert(table, parent_page_num, child_max_key, child_page_num);
+   return;
+ }
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;The last two parameters of our new function &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;internal_node_split_insert&lt;/code&gt; is the key and page pointer, or page number, to be added into parent internal node. In our new function, we first create a new internal node and initialize this node.&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;gi&quot;&gt;+ void internal_node_split_insert(Table* table, uint32_t parent_page_num, uint32_t insert_cell_key, uint32_t insert_page_num) {
+   uint32_t new_internal_page_num = get_unused_page_num(table-&amp;gt;pager);
+   void* new_node = get_page(table-&amp;gt;pager, new_internal_page_num);
+   initialize_internal_node(new_node);
+   *node_parent(new_node) = parent_page_num;
+ }
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;Find the right child for the new internal node and set the value. It should be noted that the right child for the new internal node should be either the right child of the old node or the new page number to be added. If the right child of the new internal node is the one of the old node, so just assign the page number to the right child of the new internal node, or we should assign the new page number to be added to the target right child and replace the key and page number to be added with the max key of the right child of the old internal node and the corresponding page number.&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;gi&quot;&gt;+ void* old_node = get_page(table-&amp;gt;pager, parent_page_num);
+ int32_t right_child_page_num = *internal_node_right_child(old_node);
+ void* right_child = get_page(table-&amp;gt;pager, right_child_page_num);
+ // move right child
+ int32_t cur_right_child_max_key = get_node_max_key(right_child);
+ if (insert_cell_key &amp;gt; cur_right_child_max_key) {
+   *internal_node_right_child(new_node) = insert_page_num;
+   insert_cell_key = cur_right_child_max_key;
+   insert_page_num = right_child_page_num;
+ } else {
+   *internal_node_right_child(new_node) = right_child_page_num;
+}
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;Then we move half of the key and pointers to the new internal node. First We should find the right postion of the new key should be by invoking the function &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;internal_node_find_child&lt;/code&gt;.&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;gi&quot;&gt;+ // find cell num of insert_cell_key
+ uint32_t cell_num = internal_node_find_child(old_node, insert_cell_key);
+ *internal_node_num_keys(new_node) = INTERNAL_NODE_RIGHT_SPLIT_COUNT;
+ int32_t i = INTERNAL_NODE_MAX_CELLS;
+ for ( ; i &amp;gt;= INTERNAL_NODE_RIGHT_SPLIT_COUNT; i--) {
+   uint32_t index_within_node = i % INTERNAL_NODE_RIGHT_SPLIT_COUNT;
+   void* destination = internal_node_cell(new_node, index_within_node);
+   if (i == cell_num) {
+       *internal_node_key(new_node, index_within_node) = insert_cell_key;
+       *internal_node_child(new_node, index_within_node) = insert_page_num;
+   } else if (i &amp;gt; cell_num) {
+       memcpy(destination, internal_node_cell(old_node, i - 1), INTERNAL_NODE_CELL_SIZE);
+   } else {
+       memcpy(destination, internal_node_cell(old_node, i), INTERNAL_NODE_CELL_SIZE);
+   }
+ }
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;After that, both right child and half of the keys and pointers are moved out from the old internal node, so we  must find a new right child for this internal node, and the righthmost remaing page number or the new added page number should the choice.&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;gi&quot;&gt;+ if (i == cell_num) {
+   *internal_node_right_child(old_node) = insert_page_num;
+ } else {
+   *internal_node_right_child(old_node) = *internal_node_child(old_node, i);
+ }
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;If the new key and page number(or pointer) should be added into the old internal node, the we should move some keys and pointers to make room for new cell.&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;gi&quot;&gt;+ i--;
+ *internal_node_num_keys(old_node) = INTERNAL_NODE_LEFT_SPLIT_COUNT;
+ for (; i &amp;gt;= 0; i--) {
+   uint32_t index_within_node = i % INTERNAL_NODE_LEFT_SPLIT_COUNT;
+   void* destination = internal_node_cell(old_node, index_within_node);
+   if (i == cell_num) {
+       *internal_node_key(old_node, index_within_node) = insert_cell_key;
+       *internal_node_child(old_node, index_within_node) = insert_page_num;
+    } else if (i &amp;gt; cell_num) {
+       memcpy(destination, internal_node_cell(old_node, i - 1), INTERNAL_NODE_CELL_SIZE);
+    } else {
+       continue;
+    }
+ }
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;If the old internal node is the root node, then we should create a new root node as &lt;a href=&quot;./part10.md&quot;&gt;part 10&lt;/a&gt; explained.&lt;/p&gt;

&lt;div class=&quot;language-diff highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;gi&quot;&gt;+ bool node_root = is_node_root(old_node);
+ if (node_root) {
+   create_new_root(table, new_internal_page_num);
+ } else {
+   printf(&quot;Need to implement insert new internal page to parent node\n&quot;);
+   exit(EXIT_FAILURE);
+ }
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;At this moment, we can split the internal node if this node is full, but the new function has not been tested. So in the next part we will add some tests to see if this function could work as we expected.&lt;/p&gt;

</description>
        <pubDate>Thu, 19 May 2022 00:00:00 +0000</pubDate>
        <link>https://guimy.tech/db_tutorial/parts/part14.html</link>
        <guid isPermaLink="true">https://guimy.tech/db_tutorial/parts/part14.html</guid>
      </item>
    
  </channel>
</rss>
