Something went wrong. Try again.
SQLite file format and SQL engine in pure OCaml
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232(*--------------------------------------------------------------------------- Copyright (c) 2026 Thomas Gazagnaire. All rights reserved. SPDX-License-Identifier: ISC ---------------------------------------------------------------------------*)
(* [Sqlite.Pool] keeps read handles between readings, by the file the path names; [Sqlite.moved] tells a handle its path names another file; [Sqlite.log] reads a log's size off its header. *)
let suffixes = [ ""; "-wal"; "-journal"; "-shm" ]
(* [f path] with a fresh database path, removed afterwards with every file a database writes beside itself, and a second free path beside it. *)let with_path f = Eio_main.run @@ fun env -> let fs = Eio.Stdenv.fs env in let name = Filename.temp_file "sqlite_pool_" ".db" in Sys.remove name; let other = name ^ ".new" in Fun.protect ~finally:(fun () -> List.iter (fun n -> List.iter (fun s -> try Sys.remove (n ^ s) with Sys_error _ -> ()) suffixes) [ name; other ]) (fun () -> f Eio.Path.(fs / name) Eio.Path.(fs / other))
(* A WAL database holding the one row [v], written and closed: its log copied into the file and removed. *)let seed path v = Eio.Switch.run @@ fun sw -> let db = Sqlite.open_ ~sw ~create:true path in Sqlite.Raw.exec db "CREATE TABLE t (v TEXT)" ~params:[]; Sqlite.Raw.exec db "INSERT INTO t VALUES (?)" ~params:[ Text v ]; Sqlite.close db
let value db = match Sqlite.Raw.query db "SELECT v FROM t" ~params:[] with | [ [ Sqlite.Text v ] ] -> v | _ -> Alcotest.fail "not one row"
(* A pool whose opens are counted. *)let pool ~sw path = let opens = ref 0 in let open_ () = incr opens; Ok (Sqlite.open_ ~sw ~create:false ~read_only:true path) in (Sqlite.Pool.v ~open_ path, opens)
let used p f = Eio.Switch.run @@ fun sw -> match Sqlite.Pool.use p ~sw f with | Some (Ok v) -> Some v | Some (Error ()) -> Alcotest.fail "the open failed" | None -> None
(* A reading's handle is given back as its switch ends and read again by the next one, the transaction it left open rolled back: one open for three readings. *)let test_kept () = with_path @@ fun path _ -> seed path "a"; Eio.Switch.run @@ fun sw -> let p, opens = pool ~sw path in let first = used p (fun db -> Sqlite.Raw.exec db "BEGIN" ~params:[]; db) in let second = used p (fun db -> Sqlite.Raw.exec db "BEGIN" ~params:[]; db) in Alcotest.(check bool) "the same handle" true (match (first, second) with Some a, Some b -> a == b | _ -> false); Alcotest.(check (option string)) "it reads" (Some "a") (used p value); Alcotest.(check int) "one open" 1 !opens
(* A path replaced by another file is read through a handle opened on it, the idle one on the old file closed: a second open, the new row. A path naming nothing is [None], and opens nothing. *)let test_replaced () = with_path @@ fun path other -> seed path "a"; seed other "b"; Eio.Switch.run @@ fun sw -> let p, opens = pool ~sw path in Alcotest.(check (option string)) "the first file" (Some "a") (used p value); Eio.Path.rename other path; Alcotest.(check (option string)) "the file replacing it" (Some "b") (used p value); Alcotest.(check int) "two opens" 2 !opens; Eio.Path.unlink path; Alcotest.(check (option string)) "no file" None (used p value); Alcotest.(check int) "no third open" 2 !opens
(* A reading failing with [Eio.Io] loses its handle: the next reading opens another. Any other exception gives it back as its switch ends. *)let test_lost () = with_path @@ fun path other -> seed path "a"; Eio.Switch.run @@ fun sw -> let p, opens = pool ~sw path in (match used p (fun _ -> raise Exit) with | _ -> Alcotest.fail "Exit was not raised" | exception Exit -> ()); Alcotest.(check (option string)) "given back" (Some "a") (used p value); Alcotest.(check int) "one open" 1 !opens; let io = match Eio.Path.load other with | _ -> Alcotest.fail "a missing file was read" | exception (Eio.Io _ as e) -> e in (match used p (fun _ -> raise io) with | _ -> Alcotest.fail "the IO error was not raised" | exception Eio.Io _ -> ()); Alcotest.(check (option string)) "another handle" (Some "a") (used p value); Alcotest.(check int) "two opens" 2 !opens
(* [moved]: a handle on a file another replaces at its path, or removes; a closed handle reads no file. *)let test_moved () = with_path @@ fun path other -> seed path "a"; seed other "b"; Eio.Switch.run @@ fun sw -> let db = Sqlite.open_ ~sw ~create:false ~read_only:true path in Alcotest.(check bool) "in place" false (Sqlite.moved db); Eio.Path.rename other path; Alcotest.(check bool) "replaced" true (Sqlite.moved db); Eio.Path.unlink path; Alcotest.(check bool) "removed" true (Sqlite.moved db); Sqlite.close db; Alcotest.(check bool) "closed" false (Sqlite.moved db); Alcotest.(check bool) "in memory" false (Sqlite.moved (Sqlite.in_memory ()))
(* [log]: none before a write, then the header's 32 bytes and each frame's 24-byte header and page; none once a close copied it back. *)let test_log () = with_path @@ fun path _ -> Alcotest.(check bool) "no database" true (Option.is_none (Sqlite.log path)); Eio.Switch.run @@ fun sw -> let db = Sqlite.open_ ~sw ~create:true path in Sqlite.Raw.exec db "CREATE TABLE t (v TEXT)" ~params:[]; Sqlite.Raw.exec db "INSERT INTO t VALUES ('a')" ~params:[]; (match Sqlite.log path with | None -> Alcotest.fail "no log after a write" | Some { bytes; frames } -> Alcotest.(check bool) "frames" true (frames > 0); Alcotest.(check int) "its bytes" (32 + (frames * (4096 + 24))) bytes); Sqlite.close db; Alcotest.(check bool) "copied back" true (Option.is_none (Sqlite.log path))
(* [remove]: the database, its log, its WAL-index and a journal beside it, each gone, and nothing there is no error. A removal of the file alone would leave a log that the next open replays into a fresh database. *)let test_remove () = with_path @@ fun path _ -> Sqlite.remove path; let beside s = let dir, name = Option.get (Eio.Path.split path) in Eio.Path.(dir / (name ^ s)) in Eio.Switch.run @@ fun sw -> let db = Sqlite.open_ ~sw ~create:true path in Sqlite.Raw.exec db "CREATE TABLE t (v TEXT)" ~params:[]; Sqlite.Raw.exec db "INSERT INTO t VALUES ('a')" ~params:[]; Eio.Path.save ~create:(`Exclusive 0o644) (beside "-journal") ""; let there () = List.map (fun s -> Eio.Path.is_file (beside s)) suffixes in Alcotest.(check (list bool)) "the files a database keeps" [ true; true; true; true ] (there ()); Sqlite.remove path; Alcotest.(check (list bool)) "removed" [ false; false; false; false ] (there ())
(* [log] of a log that started over: [n] pages copied back by a passive checkpoint, then a commit that starts the log from its first frame and leaves the file at its old size (wal.c, walRestartLog). Its frames are the WAL-index header's, that commit's alone, not the file's size over a frame's (fileformat2.html, "The WAL-Index Format"). *)let restarted n () = with_path @@ fun path copy -> Eio.Switch.run @@ fun sw -> let db = Sqlite.open_ ~sw ~create:true path in Sqlite.Raw.run db "PRAGMA wal_autocheckpoint = 0" ~params:[] ~on_row:ignore; Sqlite.Raw.exec db "CREATE TABLE t (v BLOB)" ~params:[]; Sqlite.with_transaction db (fun () -> for _ = 1 to n do Sqlite.Raw.exec db "INSERT INTO t VALUES (zeroblob(3000))" ~params:[] done); let before = Option.get (Sqlite.log path) in Alcotest.(check bool) "the rows' frames" true (before.frames >= n); Sqlite.checkpoint db; Sqlite.Raw.exec db "INSERT INTO t VALUES (x'00')" ~params:[]; let after = Option.get (Sqlite.log path) in Alcotest.(check int) "the file left in place" before.bytes after.bytes; Alcotest.(check bool) (Fmt.str "one commit's frames, not %d" before.frames) true (after.frames > 0 && after.frames <= 2); let wal path = let dir, name = Option.get (Eio.Path.split path) in Eio.Path.(dir / (name ^ "-wal")) in Eio.Path.save ~create:(`Exclusive 0o600) (wal copy) (Eio.Path.load (wal path)); let recovered = Option.get (Sqlite.log copy) in Alcotest.(check int) "without the index, recovery counts the same frames" after.frames recovered.frames; Sqlite.close db
let suite = ( "pool", [ Alcotest.test_case "a reading's handle is kept" `Quick test_kept; Alcotest.test_case "a replaced file is opened again" `Quick test_replaced; Alcotest.test_case "a failed reading loses its handle" `Quick test_lost; Alcotest.test_case "a handle's file moved" `Quick test_moved; Alcotest.test_case "the log's size" `Quick test_log; Alcotest.test_case "a database removed" `Quick test_remove; Alcotest.test_case "a restarted log of 100 frames" `Quick (restarted 100); Alcotest.test_case "a restarted log of 1000 frames" `Quick (restarted 1000); ] )