SQLite file format and SQL engine in pure OCaml
README.md

sqlite #

An SQL database engine in pure OCaml over the SQLite file format.

sqlite reads and writes the database files of sqlite3 3.54.1, with the rollback journal and the write-ahead log that sqlite3 keeps beside them, and it answers SQL as sqlite3 3.54.1 does. A database written here opens in the sqlite3 shell, and one the shell wrote opens here. The engine links no C library, so it runs wherever OCaml runs, MirageOS unikernels included.

Contents #

Installation #

The library needs OCaml 5.1 or later and does its I/O through Eio.

$ opam install sqlite        # the library
$ opam install sqlite-cli    # the sql command

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

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

The stack #

The engine is five packages, each published on its own:

          sqlite
         /   |   \
     btree   |    \
     /   \   |     \
 block    \  |      |
           sql -----+
            |
         catalog

catalog and block are the base. block gives btree and sqlite their files, and says what the device promises across a power cut. catalog holds the SQL values, the typed query language and the interface any store implements to be queried, Catalog.Spi; it holds no engine. sql is the engine and the SQLite dialect: it parses, resolves names and plans each statement, lowers it to its intermediate representation and runs it on its register virtual machine, and it holds sqlite3's value semantics: affinity, the collating sequences and the text encodings. btree reads and writes the file format itself, ordering index keys by sql's collating sequences. It has the table and index B-trees, the record format, the write-ahead log and the page cache. sqlite puts the others together as a database. It owns opening and crash recovery, transactions and locks, the rollback journal, constraints and triggers, and the interfaces below.

Which API to use #

A database is a Sqlite.t, from Sqlite.open_ on a file or Sqlite.in_memory. Four interfaces reach it, and all four work on the same file:

  • Typed queries, written with Catalog.Table and Catalog.Query and run by Sqlite.run and Sqlite.iter, for an application that knows its tables when it is compiled. A row decodes into the caller's record, and a type mismatch or a column of a table the query does not read fails to compile.
  • SQL text, in Sqlite.Raw, for a statement known only at run time or one the typed layer does not express, such as DDL, triggers, window functions and PRAGMA. Rows come back as lists of Sqlite.value.
  • Key-value, in Sqlite.Kv, for strings mapped to strings with no schema to declare.
  • The sql command, in the sqlite-cli package, for the same databases from a shell.

Typed queries #

A table is declared once as a row codec, with typed columns that feed a record constructor, and every query is a comprehension over such tables. Sqlite.run executes the SQL text that Sql.text_of_query writes for it, so a typed query uses the indexes that text would.

type user = { id : int64; name : string }

let id = Catalog.Col.v "id" Catalog.int (fun u -> u.id)
let name = Catalog.Col.v "name" Catalog.text (fun u -> u.name)

let users =
  Catalog.Table.map "users" (fun id name -> { id; name })
  |> Catalog.Table.col id |> Catalog.Table.col name |> Catalog.Table.seal

let named n =
  Catalog.Query.(from users @@ fun u -> where Expr.(get u name = text n) @@ all u)
# let db = Sqlite.in_memory ();;
val db : Sqlite.t = <abstr>
# Sqlite.create_table db
    (Catalog.Table.schema ~primary_key:[ Catalog.Spi.Schema.key "id" ] users);;
- : unit = ()
# Sqlite.insert db users { id = 1L; name = "alice" };;
- : unit = ()
# Sqlite.insert db users { id = 2L; name = "bob" };;
- : unit = ()
# Sqlite.run db (named "bob");;
- : user list = [{id = 2L; name = "bob"}]
# fst (Sql.text_of_query (named "bob"));;
- : string =
"SELECT \"users\".\"id\", \"users\".\"name\" FROM \"users\" WHERE \"users\".\"name\" = ?"

Sqlite.update and Sqlite.delete take the same table and a typed where. Aggregates are typed as well. sum and avg return an option, since SQL gives NULL for an empty group, and an aggregate reaches having but never a WHERE. To declare every table of a database at once, and to refuse a file written for another declaration, use Sqlite.Schema.

A database on disk is opened inside an Eio switch:

let count_users ~fs =
  Eio.Switch.run @@ fun sw ->
  Sqlite.with_open ~sw Eio.Path.(fs / "users.db") @@ fun db ->
  List.length (Sqlite.run db (named "alice"))

SQL text #

Sqlite.Raw.exec runs statements that return no rows, and Sqlite.Raw.query runs one SELECT. Both bind ? placeholders from ~params, left to right.

# let db = Sqlite.in_memory ();;
val db : Sqlite.t = <abstr>
# Sqlite.Raw.exec db ~params:[]
    "CREATE TABLE t (k TEXT, n INTEGER);\n\
     INSERT INTO t VALUES ('a', 1), ('b', 2), ('a', 3)";;
- : unit = ()
# Sqlite.Raw.query db ~params:[ Sqlite.Text "a" ]
    "SELECT k, sum(n) OVER (ORDER BY n) FROM t WHERE k = ?";;
- : Sqlite.value list list =
[[Sqlite.Text "a"; Sqlite.Int 1L]; [Sqlite.Text "a"; Sqlite.Int 4L]]

Sqlite.Raw.prepare parses a statement once for many runs, and Sqlite.Raw.iter streams rows instead of building a list. Sqlite.Table reads and writes rows by rowid as lists of values.

Key-value #

Sqlite.Kv keeps string keys and values in a table kv (key TEXT, value BLOB), and Sqlite.Kv.Table in tables of other names.

# let db = Sqlite.in_memory ();;
val db : Sqlite.t = <abstr>
# Sqlite.Kv.put db "greeting" "hello";;
- : unit = ()
# let blocks = Sqlite.Kv.Table.v db ~name:"blocks";;
val blocks : Sqlite.Kv.Table.t = <abstr>
# Sqlite.Kv.Table.put blocks "cid1" "data1";;
- : unit = ()
# (Sqlite.Kv.find db "greeting", Sqlite.Kv.Table.find blocks "cid1");;
- : string option * string option = (Some "hello", Some "data1")

The sql command #

$ sql write my.db hello=world foo=bar
$ sql query my.db "SELECT key, value FROM kv ORDER BY key"
foo|bar
hello|world
$ sql tables my.db
kv (key TEXT, value BLOB)
$ sql check my.db
ok

sql script runs a file of SQL, as sqlite3 my.db < file does; sql read and sql delete work on the key-value table; sql vacuum rebuilds a database, in place or with --into as a new file. The name :memory: is a new database in memory. Every subcommand takes --help.

A damaged database #

sql check runs PRAGMA integrity_check and names damage in sqlite3's words. A b-tree whose leaves sit at two depths ("Child page depth differs") still holds every row where a search finds it, but a write that would join two of its pages at different depths refuses with SQLITE_CORRUPT and names the damage. VACUUM reads every row and writes every b-tree afresh, which repairs such a file:

$ sql check my.db
*** in database main ***
Tree 2 page 2 cell 0: Child page depth differs
$ sql vacuum my.db
$ sql check my.db
ok

Standards #

The engine implements sqlite3's published formats and protocols, as sqlite3 3.54.1 implements them:

The dialect is sqlite3's, not ISO SQL. Where both define a construct, such as window functions and common table expressions, the engine follows sqlite3. A difference from sqlite3 3.54.1 is a bug.

In WAL mode, the mode of a new database, a commit appends its pages to the log and fsyncs it. The log is copied back into the database file when the database is closed, or once it passes a thousand pages, as sqlite3 does.

Concurrency #

Within one process, a database has one writer at a time and any number of read-only handles (Sqlite.open_ ~read_only:true). A handle is used by one domain, the unit of parallelism in OCaml 5, so each reader domain opens its own. Fibers that write share one handle through Sqlite.Writer, which commits their writes in batches.

Between processes the engine takes sqlite3's locks, so it shares a file with sqlite3 processes as well as with its own. In WAL mode, readers and one writer run at once, and the -shm index records which commit each reader sees. In rollback-journal mode, a commit waits for the readers to finish and a new reader waits for the commit. A handle that cannot get a lock within its busy_timeout raises Sqlite.Error (Busy _).

The engine departs from sqlite3 in one place: a handle holds no lock between transactions, where a sqlite3 WAL connection holds a shared lock for as long as it is open. An idle handle therefore never keeps another process out, and at its next transaction it checks whether the file changed while it held nothing. The Concurrency section of lib/sqlite.mli gives the full rules.

Papers #

These papers explain the ideas this code is built on.

  • Rudolf Bayer and Edward McCreight, "Organization and Maintenance of Large Ordered Indexes", Acta Informatica 1(3), 1972. The B-tree, which every table and index in the file is.
  • Douglas Comer, "The Ubiquitous B-Tree", ACM Computing Surveys 11(2), 1979. The B+-tree variant that SQLite's table B-trees use, with rows only in the leaves.
  • Theodore Johnson and Dennis Shasha, "2Q: A Low Overhead High Performance Buffer Management Replacement Algorithm", VLDB 1994. The page cache follows it and keeps a page only if it is used again, so a long scan does not flush the pages in use.
  • Patricia Selinger, Morton Astrahan, Donald Chamberlin, Raymond Lorie and Thomas Price, "Access Path Selection in a Relational Database Management System", SIGMOD 1979. The cost-based choice between a scan and an index seek, which sqlite3's planner makes and this engine follows.
  • Marc Feeley and Guy Lapalme, "Using Closures for Code Generation", Computer Languages 12(1), 1987. The technique that compiles a simple plan into OCaml closures instead of running it on the virtual machine.
  • Thomas Neumann, "Efficiently Compiling Efficient Query Plans for Modern Hardware", PVLDB 4(9), 2011. Why a query compiled once beats an interpreter that dispatches on the plan for every row.
  • James Cheney, Sam Lindley and Philip Wadler, "A Practical Theory of Language-Integrated Query", ICFP 2013. Queries as typed comprehensions that normalise to one SQL statement, the model behind Catalog.Query.
  • Kevin Gaffney, Martin Prammer, Larry Brasfield, Richard Hipp, Dan Kennedy and Jignesh Patel, "SQLite: Past, Present, and Future", PVLDB 15(12), 2022. How sqlite3 is built, and why its row store suits transactions better than analytics.

Documentation #

The interface documentation is in lib/sqlite.mli, and doc/design.mld describes the bytes the engine writes and why it is written in OCaml. Build the HTML with dune build @doc, or read it with odig doc sqlite once the package is installed.

sqlite3-ocaml and ezsqlite bind the SQLite C library. Turso, first called Limbo, reimplements SQLite in Rust.

Licence #

ISC. See LICENSE.md.