(** sqlite3 interop tests for ocaml-sqlite's SQL engine. Read path: [traces/catalog.db] is a real database built by the sqlite3 CLI from [scripts/fixtures.sql], and [traces/expected/.txt] holds sqlite3's output for [scripts/queries/.sql]. Each test opens that database with {!Sqlite.open_}, runs the query through {!Sqlite.Raw.query}, and checks our output matches sqlite3's byte-for-byte. Storage path: [traces/without_rowid.db] is a second sqlite3-built database whose tables are mostly [WITHOUT ROWID], which sqlite3 stores in index b-trees keyed by the row itself rather than in rowid-keyed table b-trees (file format 2.4). [traces/without_rowid_expected/.txt] holds sqlite3's output for [scripts/without_rowid_queries/.sql]. The ordinary tables in that file are queried too: one table's storage must not decide whether the rest of the database can be read. Whatever this build cannot do with such a table it has to say by name, so the same database is also asked for something it must refuse, and the refusal is checked for the table's name rather than left as a b-tree parse failure. Write path: each [scripts/mutations//setup.sql] is run by sqlite3 against a fresh database and [verify.sql] dumps the final table state into [traces/mutations_expected/.txt]. Each test runs the same setup through {!Sqlite.Raw.exec} on a fresh in-memory database and checks the verify query matches sqlite3's dump. Integrity guard (regen only): [scripts/generate.sh] also builds several insert/delete scenarios with the OCaml [sql] CLI and runs sqlite3 [PRAGMA integrity_check] on each, so a B-tree layout our lenient reader would accept but sqlite3 calls malformed fails regen. sqlite3 is {e not} required to run the tests -- only to regenerate traces: [dune build @traces]. *) (* sqlite3 list mode: columns joined by '|', rendered exactly as the sqlite3 shell does (NULL empty, floats with a trailing '.', text/blobs verbatim). *) let render db sql = Sqlite.Raw.query db sql ~params:[] |> List.map (fun row -> String.concat "|" (List.map Sqlite.Value.to_text row)) |> String.concat "\n" let query_names dir = Eio.Path.read_dir dir |> List.filter_map (Filename.chop_suffix_opt ~suffix:".sql") |> List.sort String.compare let mentions needle s = let n = String.length needle in String.length s >= n && List.exists (fun i -> String.sub s i n = needle) (List.init (String.length s - n + 1) Fun.id) (* What a statement this build is asked to carry out over such a database says about itself. Three answers are told apart, and any other exception escapes and fails the case. A storage refusal is a limitation, arrives as [Sqlite.Error (Unsupported _)], and has to name the table: a database holds both tables this build can use and tables it cannot, and a message naming only a b-tree page does not say which one was reached. A constraint refusal is not a limitation at all -- it is the answer sqlite3 gives to the same statement over the same file, and it is the reconnected index that gives it here. And a statement this build carries out says so. The three lists below draw those lines, and a case moving across one has to be moved here. *) let outcome db ~table sql = match Sqlite.Raw.exec db sql ~params:[] with | () -> "carried out" | exception Sqlite.Error (Unsupported msg) -> if mentions table msg then "refused, naming " ^ table else "refused without naming " ^ table ^ ": " ^ msg | exception Sqlite.Error (Constraint _ as msg_e) -> let msg = Fmt.str "%a" Sqlite.Error.pp msg_e in "duplicate: " ^ msg (* One read-path scenario: the sqlite3-built database [trace], the directory its queries live in, the directory holding sqlite3's answers to them, and the [(name, statement)] pairs each of the three outcomes is asked for, so that no list can grow by another quietly shrinking. [name] is the table a refusal has to name, and the constraint a duplicate has to name. *) type scenario = { trace : Eio.Fs.dir_ty Eio.Path.t; queries : Eio.Fs.dir_ty Eio.Path.t; expected : Eio.Fs.dir_ty Eio.Path.t; refuses : (string * string) list; duplicates : (string * string) list; carries : (string * string) list; } let catalog cwd = { trace = Eio.Path.(cwd / "traces" / "catalog.db"); queries = Eio.Path.(cwd / "scripts" / "queries"); expected = Eio.Path.(cwd / "traces" / "expected"); refuses = []; duplicates = []; carries = []; } let without_rowid cwd = { trace = Eio.Path.(cwd / "traces" / "without_rowid.db"); queries = Eio.Path.(cwd / "scripts" / "without_rowid_queries"); expected = Eio.Path.(cwd / "traces" / "without_rowid_expected"); (* A WITHOUT ROWID table's record is its b-tree key, so dropping a column moves every row: the whole tree has to be rebuilt under the new layout, which this build does not do. *) refuses = [ ("descending", "ALTER TABLE descending DROP COLUMN v") ]; (* [indexed] carries a UNIQUE constraint, whose autoindex the reopen connects to the b-tree sqlite_master roots it at -- so the entries it compares a written row against are the ones sqlite3 put there, and a row duplicating one is refused by the constraint that holds it. *) duplicates = [ ("indexed.u", "INSERT INTO indexed VALUES ('k9', 9, 'g9')") ]; (* [kvpair] has nothing but its PRIMARY KEY, which is the b-tree the rows are the keys of, so a write into it is a key into that tree. [indexed] also carries a CREATE INDEX, and a row breaking neither index goes in through both. *) carries = [ ("kvpair", "INSERT INTO kvpair VALUES ('echo', 5)"); ("indexed", "INSERT INTO indexed VALUES ('k9', 99, 'g9')"); ]; } (* Run every query of one scenario through our engine, paired with sqlite3's committed answer. The trace is read-only under the dune sandbox and [Sqlite.open_] opens read-write (WAL replay), so it is copied first -- into a temporary file, and removed with the [-wal] and [-journal] it may leave beside it. Copying into the cwd is invisible under dune, whose cwd is the build directory, and drops scratch databases next to the committed fixtures when the binary is run by hand from the source tree, which is how this package says to run it. *) let run_scenario fs sw s = let copy = Filename.temp_file "sqlite3_interop_" ".db" in let cleanup () = List.iter (fun p -> Eio.Path.unlink ~missing_ok:true Eio.Path.(fs / p)) [ copy; copy ^ "-wal"; copy ^ "-journal" ] in Fun.protect ~finally:cleanup @@ fun () -> let path = Eio.Path.(fs / copy) in Eio.Path.save ~create:(`Or_truncate 0o600) path (Eio.Path.load s.trace); let db = Sqlite.open_ ~sw ~create:false path in let results = List.map (fun name -> let sql = Eio.Path.load Eio.Path.(s.queries / (name ^ ".sql")) in let expected = String.trim (Eio.Path.load Eio.Path.(s.expected / (name ^ ".txt"))) in (name, expected, String.trim (render db sql))) (query_names s.queries) in let outcomes want pairs = List.map (fun (table, sql) -> (sql, want table, outcome db ~table sql)) pairs in let refused = outcomes (fun table -> "refused, naming " ^ table) s.refuses in let duplicated = outcomes (fun constr -> "duplicate: UNIQUE constraint failed: " ^ constr) s.duplicates in let carried = outcomes (fun _ -> "carried out") s.carries in Sqlite.close db; (results, refused @ duplicated @ carried) let mutation_names dir = Eio.Path.read_dir dir |> List.filter (fun n -> Eio.Path.is_directory Eio.Path.(dir / n)) |> List.sort String.compare (* Run a write scenario: a fresh in-memory database, the setup script through [Sqlite.Raw.exec], then the verify SELECT rendered like sqlite3's list mode. *) let run_mutation cwd name = let script leaf = Eio.Path.(load (cwd / "scripts" / "mutations" / name / leaf)) in let db = Sqlite.in_memory () in Sqlite.Raw.exec db (script "setup.sql") ~params:[]; let expected = String.trim (Eio.Path.load Eio.Path.(cwd / "traces" / "mutations_expected" / (name ^ ".txt"))) in (name, expected, String.trim (render db (script "verify.sql"))) let () = (* Run every query through our engine first, then assert against the traces outside the Eio scope so Alcotest's exit doesn't tear down the switch. *) let (results, _), (storage, refused), mutations = Eio_main.run @@ fun env -> let fs = Eio.Stdenv.fs env and cwd = Eio.Stdenv.cwd env in let read, storage = Eio.Switch.run @@ fun sw -> (run_scenario fs sw (catalog cwd), run_scenario fs sw (without_rowid cwd)) in let mutations = List.map (run_mutation cwd) (mutation_names Eio.Path.(cwd / "scripts" / "mutations")) in (read, storage, mutations) in let case (name, expected, got) = Alcotest.test_case name `Quick (fun () -> Alcotest.(check string) name expected got) in Alcotest.run "sqlite3-interop" [ ("query vs sqlite3", List.map case results); ("without rowid vs sqlite3", List.map case storage); ("without rowid writes", List.map case refused); ("exec vs sqlite3", List.map case mutations); ]