Insert and split — the tree grows — separator keys promoted to the parent page
An INSERT writes one cell when there's room; when the leaf is full it splits and a separator key is promoted to the parent — splits cascade upward, and only a root split adds a level.
Scene 4 left the cursor finding any leaf in 3 page reads. Now we actually run the INSERT — and watch what the leaf does when it has, and doesn't have, room.
Scene 05
Insert and split — the tree grows
- Watch
- Try it
- Predict
- Capture
Watch INSERT rowid=42 land in the leaf. Each tick adds one row: a new cell goes into the cell content area (bottom), a new pointer goes into the cell-pointer array (top), and the fill meter climbs.
Highlighted lines are the ones running in the diagram right now.
def insert(leaf, cell):if leaf.free_bytes >= cell.size:offset = leaf.alloc_in_content_area(cell.size)leaf.write_cell(offset, cell)leaf.cell_pointer_array.insert_sorted(offset, cell.key)returnsplit_leaf(leaf, cell) # no room → split
def split_leaf(leaf, new_cell):sibling = pager.allocate_page(kind='leaf')median = redistribute(leaf, sibling, new_cell)sep_key = median.keypromote_to_parent(leaf.parent, sep_key, sibling)
def promote_to_parent(parent, sep_key, new_child):if parent is None: # we were the rootnew_root = pager.allocate_page(kind='root')new_root.add_child(old_root)new_root.add_separator(sep_key, new_child)tree.depth += 1 # the only path that gains depthreturnif parent.has_room_for(sep_key):parent.insert_separator(sep_key, new_child)returnsplit_interior(parent, sep_key, new_child) # cascade
Where this sits in Build a B-tree storage engine (SQLite-style)
Scene 05 of 11, in the Mutations act — Insert, split, delete — and why the file doesn't shrink.. An INSERT writes one cell when there's room; when full, the leaf splits and a separator promotes to the parent — cascades grow the tree.
Up next. Inserts grow the tree neatly. Deletes — surprisingly — don't undo that growth. The next half-step shows why your file stays huge after a big DELETE and what VACUUM is for.
All 11 scenes in Build a B-tree storage engine (SQLite-style) · Every curriculum