B-tree storage engine with SQLite-compatible file format, in pure OCaml
README.md

btree #

A B-tree storage engine written in OCaml that writes SQLite database files.

Every embedded store needs an on-disk format, and a brand-new one comes with no tools: when a file breaks, nobody can look inside until someone writes them. btree writes the table and index B-trees of the SQLite file format instead, so the sqlite3 shell and DB Browser can open and inspect its files. Its API is a persistent ordered map from int64 rowids to strings (Table) and a persistent ordered set of strings (Index).

Installation #

$ opam install btree

If opam cannot find the package, add the overlay repository first:

$ opam repo add samoht https://tangled.org/gazagnaire.org/opam-overlay.git
$ opam update
$ opam install btree

Place in the stack #

btree is the storage layer of sqlite, a pure-OCaml SQL engine over SQLite files. It takes the SQL values its records hold and its error type from catalog, and the order of an index key, its collating sequence and text encoding, from sql. It knows pages, cells and records, and parses no SQL. An application that wants a database uses sqlite, and one that wants an ordered map on disk, in a format other tools read, uses btree directly.

The library does no I/O itself. The pager takes an open file, and what the device guarantees, from a Block.Platform of the block package, so the same code runs on Eio (btree.eio) and on the simulated Block.Sim. The page cache is capped in bytes and modelled on the 2Q policy. A page enters cold and stays only if it is used again, so a full scan, which reads each of its pages once, does not evict the pages in use.

Usage #

A table in memory #

let demo () =
  let pager = Btree.Pager.mem ~page_size:4096 () in
  let table = Btree.Table.v pager in
  Btree.Table.insert table ~rowid:1L "Hello";
  Btree.Table.insert table ~rowid:2L "World";
  (match Btree.Table.find table 1L with
   | Some v -> Fmt.pr "1 -> %s@." v
   | None -> ());
  Btree.Table.iter table (fun rowid data ->
      Printf.printf "%Ld: %s\n" rowid data)

An index in memory #

let index_demo () =
  let pager = Btree.Pager.mem ~page_size:4096 () in
  let index = Btree.Index.v pager in
  Btree.Index.insert index "key";
  Btree.Index.mem index "key"

A table in a file #

To store the tree in a file, create the pager on an Eio file with btree.eio, then call Pager.sync to write it out. sqlite3 can open the result:

let persist ~fs =
  Eio.Path.with_open_out
    ~create:(`If_missing 0o644) Eio.Path.(fs / "demo.db")
    (fun file ->
      let pager = Btree_eio.Pager.v ~page_size:4096 file in
      let table = Btree.Table.v pager in
      Btree.Table.insert table ~rowid:1L "persisted";
      Btree.Pager.sync pager)

To reopen the table, create a pager on the same file and call Btree.Table.open_ pager ~root_page. The root page number is the one Btree.Table.save_root returned, or 1 for a new file.

Standards #

The file is in the SQLite database file format, as sqlite3 3.54.1 writes it. Section 1 of that document gives the header, the B-tree pages and cells, overflow chains, the freelist and the pointer map of an auto-vacuum database. Section 2 gives the record format. Section 4 gives the write-ahead log, which Btree.Wal reads and writes, and its shared index is the WAL-index format of Btree.Wal_index.

The format has two kinds of B-tree. A table B-tree is a B+tree, with rows only in the leaves and rowid keys with child pointers in the interior pages. An index B-tree keeps keys in interior and leaf pages alike.

The format updates pages in place, where copy-on-write engines such as LMDB and sanakirja write each changed page to a fresh location and swap one root pointer. A reader of a copy-on-write tree keeps its snapshot without waiting. Here a reader either waits for the writer or reads through the write-ahead log, which holds new pages until a checkpoint copies them into the file. That costs throughput under concurrent load, and buys the existing SQLite tools.

API #

  • Table: v, open_, insert, find, delete, iter, fold, and save_root to reopen the table later.
  • Index: v, open_, insert, mem, find, delete, and iter, fold_from, fold_prefix and by_prefix for ordered and prefix scans.
  • Pager: Btree_eio.Pager.v over an Eio file, Pager.Make over any Block.Platform, Pager.mem in memory; sync writes the dirty pages, and snapshot and rollback abort a transaction.

The modules below them (Page, Cell, Record, Overflow, Ptrmap, Wal, Wal_index) each implement one part of the file format, and lib/btree.mli lists them from the bytes up.

Papers #

  • Rudolf Bayer and Edward McCreight, "Organization and Maintenance of Large Ordered Indexes", Acta Informatica 1(3), 1972. The B-tree.
  • Douglas Comer, "The Ubiquitous B-Tree", ACM Computing Surveys 11(2), 1979. The B+-tree variant, which the table B-trees use.
  • Theodore Johnson and Dennis Shasha, "2Q: A Low Overhead High Performance Buffer Management Replacement Algorithm", VLDB 1994. The policy of the page cache.

LMDB is a C B+tree with memory-mapped copy-on-write, sanakirja a Rust copy-on-write B-tree used by Pijul, and bbolt a Go B+tree used by etcd.

Licence #

ISC. See LICENSE.md.