(*--------------------------------------------------------------------------- Copyright (c) 2026 Thomas Gazagnaire. All rights reserved. SPDX-License-Identifier: ISC ---------------------------------------------------------------------------*) (** Tests for {!Sqlite.Write}: the layer that runs an INSERT, DELETE or UPDATE over the store. The module is internal, so it is driven through the public door it backs -- statements reaching {!Sqlite.Raw.exec} and {!Sqlite.Raw.query}. The write ordering (CHECK before FK before BEFORE-trigger before uniqueness before the write before AFTER-trigger) is pinned end to end by cram/constraints.t, upsert.t and on_conflict.t; what this suite adds is the orchestration the extraction isolated, each asserted on exact stored values: the skip rule a multi-row INSERT OR IGNORE applies to the one violating row, the WHERE that gates an UPSERT's DO UPDATE against the excluded row, the row of declared defaults DEFAULT VALUES stores, and the auxiliary scope UPDATE ... FROM brings into a SET expression. *) let value = Alcotest.testable Sqlite.Value.pp ( = ) let rows = Alcotest.(list (list value)) let exec db sql = Sqlite.Raw.exec db sql ~params:[] let select db sql = Sqlite.Raw.query db sql ~params:[] (* The sentence [sql] is refused with, whichever door raises it: a statement refused while it is prepared raises [Sqlite.Error (Prepare _)] and one refused as it runs raises [Failure], and what a caller reads is the same string. *) let refusal db sql = match exec db sql with | () -> Alcotest.failf "expected %S to be refused" sql | exception Sqlite.Error (Prepare m) -> m | exception Sqlite.Error m_e -> let m = Fmt.str "%a" Sqlite.Error.pp m_e in m (* A CHECK carries no resolution of its own, so INSERT OR IGNORE resolves it to IGNORE: only the offending row is skipped and the rest are stored, even when the violator leads the tuple list. *) let test_insert_or_ignore_skips_the_check_violator () = let db = Sqlite.in_memory () in exec db "CREATE TABLE t (a INTEGER CHECK (a > 0))"; exec db "INSERT OR IGNORE INTO t (a) VALUES (-1), (5), (0), (7)"; Alcotest.check rows "only the rows passing the CHECK survive" [ [ Sqlite.Int 5L ]; [ Sqlite.Int 7L ] ] (select db "SELECT a FROM t ORDER BY a") (* An UPSERT's DO UPDATE is gated by its WHERE, evaluated with the would-be- inserted row visible as [excluded]: a predicate the current row fails leaves it untouched, and the same statement with a predicate it passes rewrites it. *) let test_upsert_do_update_where_gates_the_rewrite () = let db = Sqlite.in_memory () in exec db "CREATE TABLE t (k INTEGER PRIMARY KEY, v INTEGER)"; exec db "INSERT INTO t (k, v) VALUES (1, 10)"; exec db "INSERT INTO t (k, v) VALUES (1, 99) ON CONFLICT (k) DO UPDATE SET v = \ excluded.v WHERE v > 100"; Alcotest.check rows "WHERE the current row fails leaves it as it was" [ [ Sqlite.Int 1L; Sqlite.Int 10L ] ] (select db "SELECT k, v FROM t"); exec db "INSERT INTO t (k, v) VALUES (1, 99) ON CONFLICT (k) DO UPDATE SET v = \ excluded.v WHERE v < 100"; Alcotest.check rows "WHERE the current row passes rewrites it to excluded.v" [ [ Sqlite.Int 1L; Sqlite.Int 99L ] ] (select db "SELECT k, v FROM t") (* An UPSERT's WHERE reads a text through its numeric prefix. sqlite3 3.54.1: CREATE TABLE t(k PRIMARY KEY, v); INSERT INTO t VALUES (1,'a'),(2,'b'),(3,'c'); INSERT INTO t VALUES (1,'z') ON CONFLICT(k) DO UPDATE SET v=excluded.v WHERE '0'; -- and WHERE 'abc' for k = 2, WHERE '3abc' for k = 3 SELECT * FROM t; -- 1|a 2|b 3|z A WHERE that took any text as true rewrites all three. *) let test_upsert_where_reads_text_as_a_number () = let db = Sqlite.in_memory () in exec db "CREATE TABLE t (k PRIMARY KEY, v)"; exec db "INSERT INTO t VALUES (1, 'a'), (2, 'b'), (3, 'c')"; List.iter (fun (k, w) -> exec db (Fmt.str "INSERT INTO t VALUES (%d, 'z') ON CONFLICT (k) DO UPDATE SET v = \ excluded.v WHERE %s" k w)) [ (1, "'0'"); (2, "'abc'"); (3, "'3abc'") ]; Alcotest.check rows "only the WHERE whose number is nonzero rewrites" [ [ Sqlite.Int 1L; Sqlite.Text "a" ]; [ Sqlite.Int 2L; Sqlite.Text "b" ]; [ Sqlite.Int 3L; Sqlite.Text "z" ]; ] (select db "SELECT k, v FROM t ORDER BY k") (* INSERT INTO t DEFAULT VALUES stores the row of every column's declared DEFAULT, each taken to its column's affinity like a written-out tuple. *) let test_default_values_stores_the_declared_defaults () = let db = Sqlite.in_memory () in exec db "CREATE TABLE t (a INTEGER DEFAULT 7, b TEXT DEFAULT 'z', c)"; exec db "INSERT INTO t DEFAULT VALUES"; Alcotest.check rows "each column takes its DEFAULT, none its NULL" [ [ Sqlite.Int 7L; Sqlite.Text "z"; Sqlite.Null ] ] (select db "SELECT a, b, c FROM t") (* UPDATE ... FROM joins an auxiliary table to the target; each join-row is an outer scope a SET expression reads, so a target row takes the value the matching auxiliary row carries. *) let test_update_from_reads_the_joined_scope () = let db = Sqlite.in_memory () in exec db "CREATE TABLE t (k INTEGER, v INTEGER)"; exec db "CREATE TABLE s (k INTEGER, w INTEGER)"; exec db "INSERT INTO t (k, v) VALUES (1, 0), (2, 0)"; exec db "INSERT INTO s (k, w) VALUES (1, 100), (2, 200)"; exec db "UPDATE t SET v = s.w FROM s WHERE t.k = s.k"; Alcotest.check rows "each target row takes its matching auxiliary row's value" [ [ Sqlite.Int 1L; Sqlite.Int 100L ]; [ Sqlite.Int 2L; Sqlite.Int 200L ] ] (select db "SELECT k, v FROM t ORDER BY k") (* An UPDATE names one table and may name it under an alias. [UPDATE t AS q SET ...] (lang_update.html; parse.y takes the target as an [xfullname], which carries the AS) binds the row being rewritten under [q] for the whole statement -- the SET expressions and the WHERE both -- and binding it renames the table, whose own name no longer reaches the row. [AS] is what makes the alias: unlike a FROM source, an UPDATE takes no bare one, so [UPDATE t q SET ...] is a syntax error at that word. A DELETE already has this shape here ([DELETE FROM t AS x], threaded through the row frame), so the two writes are pinned side by side: what a DELETE binds under its alias is what an UPDATE binds under its own, and the DELETE vectors are the boundary the UPDATE ones are read against. The sqlite3 CLI (Apple build, 3.54.0) over [CREATE TABLE t (a INTEGER, b TEXT)] holding [(1,'x')], [(2,'y')], [(3,'z')], each statement run against a fresh copy and read back as [a || '/' || b]: "UPDATE t AS q SET a = q.a + 1" 2/x 3/y 4/z "UPDATE t AS q SET a = a + 1" 2/x 3/y 4/z "UPDATE t AS q SET b = q.b || '!' WHERE q.a = 2" 1/x 2/y! 3/z "UPDATE t AS q SET a = t.a + 1" no such column: t.a "UPDATE t q SET a = a + 1" near "q": syntax error "DELETE FROM t AS x WHERE x.a = 2" 1/x 3/z "DELETE FROM t AS x WHERE t.a = 2" no such column: t.a *) let test_an_update_names_its_table_under_an_alias () = let seeded () = let db = Sqlite.in_memory () in exec db "CREATE TABLE t (a INTEGER, b TEXT)"; exec db "INSERT INTO t (a, b) VALUES (1, 'x'), (2, 'y'), (3, 'z')"; db in let leaves what expected sql = let db = seeded () in exec db sql; Alcotest.check rows what (List.map (fun s -> [ Sqlite.Text s ]) expected) (select db "SELECT a || '/' || b FROM t ORDER BY a") in let refused what expected sql = Alcotest.(check string) what expected (refusal (seeded ()) sql) in leaves "the alias reaches the SET expressions" [ "2/x"; "3/y"; "4/z" ] "UPDATE t AS q SET a = q.a + 1"; leaves "and a bare column under it is the same column" [ "2/x"; "3/y"; "4/z" ] "UPDATE t AS q SET a = a + 1"; leaves "it reaches the WHERE too" [ "1/x"; "2/y!"; "3/z" ] "UPDATE t AS q SET b = q.b || '!' WHERE q.a = 2"; refused "and it renames the table, which no longer answers" "no such column: t.a" "UPDATE t AS q SET a = t.a + 1"; leaves "a DELETE binds its own alias the same way" [ "1/x"; "3/z" ] "DELETE FROM t AS x WHERE x.a = 2"; refused "and renames the table for its WHERE" "no such column: t.a" "DELETE FROM t AS x WHERE t.a = 2"; refused "an UPDATE alias is written with AS" "near \"q\": syntax error" "UPDATE t q SET a = a + 1" (* A keyed DELETE finds its row through the rowid rather than a full scan ([indexed_victims]) and reports the pre-delete values to RETURNING, leaving the other rows in place. *) let test_keyed_delete_returns_and_removes_one_row () = let db = Sqlite.in_memory () in exec db "CREATE TABLE t (a INTEGER PRIMARY KEY, b TEXT)"; exec db "INSERT INTO t (a, b) VALUES (1, 'x'), (2, 'y'), (3, 'z')"; let deleted = ref [] in Sqlite.Raw.run db "DELETE FROM t WHERE a = 2 RETURNING a, b" ~params:[] ~on_row:(fun r -> deleted := r :: !deleted); Alcotest.check rows "RETURNING reports the pre-delete row" [ [ Sqlite.Int 2L; Sqlite.Text "y" ] ] (List.rev !deleted); Alcotest.check rows "only the keyed row is gone" [ [ Sqlite.Int 1L; Sqlite.Text "x" ]; [ Sqlite.Int 3L; Sqlite.Text "z" ] ] (select db "SELECT a, b FROM t ORDER BY a") (* A RETURNING item names a column of the row the statement affects, and a name no column carries is refused while the statement is prepared -- before a row is written, deleted or rewritten. sqlite3 resolves the whole statement in one pass before it runs any of it (sqlite/src/resolve.c, sqlite3ResolveExprNames over the RETURNING list at prepare time), so the refusal costs the table nothing. The sqlite3 CLI (Apple build, 3.54.0), over [CREATE TABLE t (a, b)] holding [(1, 'x')]: each of the three statements below answers "no such column: nope" and [SELECT a, b FROM t] still reads [1|x] after all three, the DELETE included. *) let test_returning_an_unknown_column_is_refused_before_the_write () = let db = Sqlite.in_memory () in exec db "CREATE TABLE t (a, b)"; exec db "INSERT INTO t (a, b) VALUES (1, 'x')"; let untouched label = Alcotest.check rows label [ [ Sqlite.Int 1L; Sqlite.Text "x" ] ] (select db "SELECT a, b FROM t") in Alcotest.(check string) "DELETE ... RETURNING nope" "no such column: nope" (refusal db "DELETE FROM t WHERE a = 1 RETURNING nope"); untouched "the row the DELETE would have removed is still there"; Alcotest.(check string) "UPDATE ... RETURNING nope" "no such column: nope" (refusal db "UPDATE t SET b = 'y' WHERE a = 1 RETURNING nope"); untouched "the row the UPDATE would have rewritten still holds x"; Alcotest.(check string) "INSERT ... RETURNING nope" "no such column: nope" (refusal db "INSERT INTO t (a, b) VALUES (2, 'z') RETURNING nope"); untouched "the row the INSERT would have added is not there" (* A view is a name in the same namespace as a table, and a write reaching one is refused for what it is rather than answered as if nothing carried the name. sqlite3 finds the object, sees it is a view and says so (sqlite/src/insert.c and update.c / delete.c, sqlite3ViewGetColumnNames guarded by "cannot modify %s because it is a view"), which is a different statement from "no such table": one says the name is free, the other says it is taken by something no INSERT trigger stands behind. The sqlite3 CLI (Apple build, 3.54.0), over [CREATE TABLE t (a, b)] holding [(1, 'x')] and [CREATE VIEW v AS SELECT * FROM t]: all three of INSERT, UPDATE and DELETE answer "cannot modify v because it is a view", while preparing, and the table behind the view still reads [1|x]. *) let test_a_view_is_not_a_write_target () = let db = Sqlite.in_memory () in exec db "CREATE TABLE t (a, b)"; exec db "INSERT INTO t (a, b) VALUES (1, 'x')"; exec db "CREATE VIEW v AS SELECT * FROM t"; let refused = "cannot modify v because it is a view" in Alcotest.(check string) "INSERT INTO a view" refused (refusal db "INSERT INTO v (a, b) VALUES (2, 'y')"); Alcotest.(check string) "UPDATE a view" refused (refusal db "UPDATE v SET b = 'z'"); Alcotest.(check string) "DELETE FROM a view" refused (refusal db "DELETE FROM v"); Alcotest.check rows "the table behind the view is untouched" [ [ Sqlite.Int 1L; Sqlite.Text "x" ] ] (select db "SELECT a, b FROM t") (* Naming the rowid on a write A rowid table's key is addressable by three spellings -- [rowid], [_rowid_], [oid] -- and sqlite3 accepts every one of them wherever a column name is written, not only in a SELECT: in an INSERT's column list, which places the row at that key (sqlite/src/insert.c, sqlite3Insert's [ipkColumn]), and in an UPDATE's SET, which moves the row to it. Where the table declares an INTEGER PRIMARY KEY the alias and the keyword are one column, so a write through either spelling lands in the same place. Where it declares none the rowid is a column of no table, and the value written has nowhere to be held but the key itself. Every expected value below is what the sqlite3 CLI (Apple build, 3.54.0) stores for the same statements over the same schema. *) let rowid_key db = List.map (function [ Sqlite.Int r; k ] -> (r, k) | _ -> (0L, Sqlite.Null)) (select db "SELECT rowid, key FROM t ORDER BY rowid") let keyed = Alcotest.(list (pair int64 value)) (* An INSERT that names the rowid places the row at that key, under any of the three spellings, and the next unnamed insert continues from it. *) let test_insert_names_the_rowid () = let db = Sqlite.in_memory () in exec db "CREATE TABLE t (key TEXT, value BLOB)"; exec db "INSERT INTO t (rowid, key, value) VALUES (5, 'a', x'01')"; exec db "INSERT INTO t (_rowid_, key) VALUES (7, 'b')"; exec db "INSERT INTO t (oid, key) VALUES (9, 'c')"; exec db "INSERT INTO t (key) VALUES ('d')"; Alcotest.check keyed "each row sits at the rowid its INSERT named" [ (5L, Sqlite.Text "a"); (7L, Sqlite.Text "b"); (9L, Sqlite.Text "c"); (10L, Sqlite.Text "d"); ] (rowid_key db); Alcotest.check rows "and the named rowid is not stored as a column" [ [ Sqlite.Text "a"; Sqlite.Blob "\x01" ] ] (select db "SELECT key, value FROM t WHERE rowid = 5") (* A column list may name the rowid alone: every column then takes its DEFAULT and the row sits at the key, as sqlite3 3.54.1 answers INSERT INTO t (rowid) VALUES (5) with the row 5|| and a list naming the rowid and a column with one value is refused as "1 values for 2 columns". *) let test_insert_names_only_the_rowid () = let db = Sqlite.in_memory () in exec db "CREATE TABLE t (key TEXT, value BLOB DEFAULT x'02')"; exec db "INSERT INTO t (rowid) VALUES (5)"; Alcotest.check rows "the row at the key, every column its DEFAULT" [ [ Sqlite.Int 5L; Sqlite.Null; Sqlite.Blob "\x02" ] ] (select db "SELECT rowid, key, value FROM t"); Alcotest.check_raises "a list wider than its values is refused" (Sqlite.Error (Prepare "1 values for 2 columns")) (fun () -> exec db "INSERT INTO t (rowid, key) VALUES (7)") (* The rowid is unique whether or not a column names it: an INSERT at a key the table already holds is a UNIQUE violation reported against [rowid] itself, and OR REPLACE takes the sitting row out instead. *) let test_insert_at_a_taken_rowid () = let db = Sqlite.in_memory () in exec db "CREATE TABLE t (key TEXT)"; exec db "INSERT INTO t (rowid, key) VALUES (5, 'a')"; Alcotest.check_raises "a second row at the same key is refused" (Sqlite.Error (Constraint (Unique { table = "t"; columns = [ "rowid" ] }))) (fun () -> exec db "INSERT INTO t (rowid, key) VALUES (5, 'b')"); exec db "INSERT OR REPLACE INTO t (rowid, key) VALUES (5, 'b')"; Alcotest.check keyed "REPLACE leaves one row at the key" [ (5L, Sqlite.Text "b") ] (rowid_key db) (* A rowid holds an integer and nothing else, so the written value is taken to one: NULL asks for the next allocated key, text and a real spelling an integer are that integer, and anything else is a datatype mismatch. *) let test_a_named_rowid_is_an_integer () = let db = Sqlite.in_memory () in exec db "CREATE TABLE t (key TEXT)"; exec db "INSERT INTO t (rowid, key) VALUES (NULL, 'auto')"; exec db "INSERT INTO t (rowid, key) VALUES ('12', 'text')"; exec db "INSERT INTO t (rowid, key) VALUES (2.0, 'real')"; Alcotest.check keyed "each written key reads back as the integer it spells" [ (1L, Sqlite.Text "auto"); (2L, Sqlite.Text "real"); (12L, Sqlite.Text "text"); ] (rowid_key db); Alcotest.check_raises "a value no integer equals is refused" (Sqlite.Error Mismatch) (fun () -> exec db "INSERT INTO t (rowid, key) VALUES ('abc', 'no')"); Alcotest.check_raises "and so is a real that is not whole" (Sqlite.Error Mismatch) (fun () -> exec db "INSERT INTO t (rowid, key) VALUES (2.5, 'no')") (* With an INTEGER PRIMARY KEY declared, the alias and the keyword name one column: a keyword-only INSERT fills the alias, and a list naming both takes the value of whichever entry comes last -- sqlite3 resolves each list entry in turn and the later one overwrites the register the rowid is read from (insert.c, the [ipkColumn = i] assignments). *) let test_the_alias_and_the_keyword_are_one_column () = let db = Sqlite.in_memory () in exec db "CREATE TABLE u (id INTEGER PRIMARY KEY, a TEXT)"; exec db "INSERT INTO u (rowid, a) VALUES (3, 'm')"; exec db "INSERT INTO u (id, rowid, a) VALUES (4, 5, 'n')"; exec db "INSERT INTO u (rowid, id, a) VALUES (6, 7, 'o')"; Alcotest.check rows "the alias reads back the key the keyword named" [ [ Sqlite.Int 3L; Sqlite.Int 3L; Sqlite.Text "m" ]; [ Sqlite.Int 5L; Sqlite.Int 5L; Sqlite.Text "n" ]; [ Sqlite.Int 7L; Sqlite.Int 7L; Sqlite.Text "o" ]; ] (select db "SELECT id, rowid, a FROM u ORDER BY id") (* UPDATE ... SET rowid moves the row to the key it names, indexes following it, and a move onto a key another row holds is the same UNIQUE violation an INSERT there would be. *) let test_update_moves_the_row () = let db = Sqlite.in_memory () in exec db "CREATE TABLE t (key TEXT)"; exec db "CREATE INDEX tk ON t (key)"; exec db "INSERT INTO t (key) VALUES ('x'), ('y'), ('z')"; exec db "UPDATE t SET rowid = 10 WHERE key = 'y'"; Alcotest.check keyed "the row sits at the key the SET named" [ (1L, Sqlite.Text "x"); (3L, Sqlite.Text "z"); (10L, Sqlite.Text "y") ] (rowid_key db); Alcotest.check rows "and the index over it answers with the new key" [ [ Sqlite.Int 10L ] ] (select db "SELECT rowid FROM t WHERE key = 'y'"); Alcotest.check_raises "a move onto a taken key is refused" (Sqlite.Error (Constraint (Unique { table = "t"; columns = [ "rowid" ] }))) (fun () -> exec db "UPDATE t SET rowid = 3 WHERE key = 'x'"); exec db "UPDATE OR REPLACE t SET rowid = 3 WHERE key = 'x'"; Alcotest.check keyed "REPLACE takes the sitting row out instead" [ (3L, Sqlite.Text "x"); (10L, Sqlite.Text "y") ] (rowid_key db) (* The same move written through the INTEGER PRIMARY KEY: assigning the alias carries the row to that key exactly as assigning the keyword does, so the two spellings are one write and not two. *) let test_update_moves_an_integer_primary_key () = let db = Sqlite.in_memory () in exec db "CREATE TABLE u (id INTEGER PRIMARY KEY, a TEXT)"; exec db "CREATE INDEX ua ON u (a)"; exec db "INSERT INTO u VALUES (1, 'x'), (2, 'y')"; exec db "UPDATE u SET rowid = 10 WHERE a = 'y'"; exec db "UPDATE u SET id = 20 WHERE a = 'x'"; Alcotest.check rows "both rows moved, and the alias reads their new keys" [ [ Sqlite.Int 10L; Sqlite.Int 10L; Sqlite.Text "y" ]; [ Sqlite.Int 20L; Sqlite.Int 20L; Sqlite.Text "x" ]; ] (select db "SELECT id, rowid, a FROM u ORDER BY id"); Alcotest.check rows "and the index over the table followed them" [ [ Sqlite.Int 10L ] ] (select db "SELECT id FROM u WHERE a = 'y'") (* A WITHOUT ROWID table has no rowid to name, so the keyword resolves to nothing on either write -- and each door answers with its own sentence, as sqlite3's does. An INSERT names its columns in a list matched against the table, so the refusal names the table; an assignment names a column of the row being rewritten and is resolved like any other reference, so the refusal is the resolver's (cram/no_such_column.t). *) let test_a_rowidless_table_has_no_rowid_to_name () = let db = Sqlite.in_memory () in exec db "CREATE TABLE w (k TEXT PRIMARY KEY, v TEXT) WITHOUT ROWID"; exec db "INSERT INTO w (k, v) VALUES ('a', 'b')"; Alcotest.check_raises "no rowid to place the row at" (Sqlite.Error (Prepare "table w has no column named rowid")) (fun () -> exec db "INSERT INTO w (rowid, k, v) VALUES (1, 'c', 'd')"); Alcotest.check_raises "and none to move it to" (Sqlite.Error (Prepare "no such column: rowid")) (fun () -> exec db "UPDATE w SET rowid = 1") (* A column that shadows the keyword takes it back: [rowid] written on a table declaring a column of that name is that column, so the write stores a value there and the row keeps the key it was allocated. *) let test_a_declared_column_shadows_the_keyword () = let db = Sqlite.in_memory () in exec db "CREATE TABLE t (rowid TEXT, key TEXT)"; exec db "INSERT INTO t (rowid, key) VALUES ('hello', 'a')"; Alcotest.check rows "the value lands in the declared column" [ [ Sqlite.Text "hello"; Sqlite.Int 1L ] ] (select db "SELECT rowid, _rowid_ FROM t"); exec db "UPDATE t SET rowid = 'bye'"; Alcotest.check rows "and an assignment to it rewrites that column" [ [ Sqlite.Text "bye"; Sqlite.Int 1L ] ] (select db "SELECT rowid, _rowid_ FROM t") (* One key per row A CHECK constraint and a partial index's WHERE may both name the row's own rowid, so the write path has to know that key before the row goes in. It also has to be the key the row goes in AT: sqlite3 runs OP_NewRowid once per row and ahead of the constraint block (vdbe.c; insert.c orders the opcode first), so what a constraint reads and what the b-tree is keyed by are one value. A table already holding the largest rowid there is makes the difference visible. Past that key the allocator has no successor to hand out and draws a random candidate instead ({!Rowid.next}), so two draws answer differently and a constraint asked about one draw says nothing about the other. Under a CHECK that admits only the even keys, half the inserts are refused and every row that survives sits at an even rowid -- which is what the sqlite3 CLI (Apple build, 3.54.0) does for this schema, and what a second draw would break. The ceiling is written as a bound parameter, an INSERT naming the rowid on a table with no column to hold it. *) let ceiling_check = "key = 'ceiling' OR rowid % 2 = 0" let test_a_constraint_reads_the_key_the_row_takes () = let db = Sqlite.in_memory () in exec db "CREATE TABLE t (key TEXT, value BLOB, CHECK (key = 'ceiling' OR rowid % 2 \ = 0))"; Sqlite.Raw.exec db "INSERT INTO t (rowid, key, value) VALUES (?, 'ceiling', x'00')" ~params:[ Sqlite.Int Int64.max_int ]; let attempts = 60 in let stored = ref 0 in for _ = 1 to attempts do match exec db "INSERT INTO t (key) VALUES ('r')" with | () -> incr stored | exception Sqlite.Error (Constraint _ as m_e) -> let m = Fmt.str "%a" Sqlite.Error.pp m_e in Alcotest.(check string) "refused by the CHECK naming rowid" ("CHECK constraint failed: " ^ ceiling_check) m done; Alcotest.(check bool) "the draws fell on both sides of the CHECK" true (!stored > 0 && !stored < attempts); Alcotest.check rows "every stored row took a key the CHECK admitted" [ [ Sqlite.Int (Int64.of_int !stored) ] ] (select db "SELECT count(*) FROM t WHERE key = 'r' AND rowid % 2 = 0"); (* Where the INSERT names the key there is nothing to draw, and the CHECK is asked about the key written. *) Alcotest.check_raises "an odd named key is refused" (Sqlite.Error (Constraint (Check ceiling_check))) (fun () -> exec db "INSERT INTO t (rowid, key) VALUES (7, 'odd')"); exec db "INSERT INTO t (rowid, key) VALUES (8, 'even')"; Alcotest.check rows "and an even one is stored at exactly that key" [ [ Sqlite.Text "even" ] ] (select db "SELECT key FROM t WHERE rowid = 8") (* INSERT INTO t SELECT * FROM s between two tables of one shape copies each record whole, and where t has an index it keeps the rowids of s, as sqlite3's transfer does (insert.c, xferOptimization: OP_Rowid rather than OP_NewRowid once the target has an index). The index entries are copied with those rowids, so a seek through t's index finds the row at the rowid it was stored under. An insert of decoded rows would number them 1, 2, 3. The expected values are sqlite3 3.54's. *) let test_transfer_keeps_the_source_rowids () = let db = Sqlite.in_memory () in exec db "CREATE TABLE s (a TEXT, b INTEGER)"; exec db "CREATE INDEX s_a ON s (a)"; exec db "INSERT INTO s (rowid, a, b) VALUES (5, 'x', 1), (10, 'y', 2), (20, 'z', 3)"; exec db "CREATE TABLE t (a TEXT, b INTEGER)"; exec db "CREATE INDEX t_a ON t (a)"; exec db "INSERT INTO t SELECT * FROM s"; Alcotest.check rows "each row at the rowid it had in s" [ [ Sqlite.Int 5L; Sqlite.Text "x"; Sqlite.Int 1L ]; [ Sqlite.Int 10L; Sqlite.Text "y"; Sqlite.Int 2L ]; [ Sqlite.Int 20L; Sqlite.Text "z"; Sqlite.Int 3L ]; ] (select db "SELECT rowid, a, b FROM t ORDER BY rowid"); Alcotest.check rows "the index of t names the same rowids" [ [ Sqlite.Int 10L ] ] (select db "SELECT rowid FROM t WHERE a = 'y'"); Alcotest.check rows "the last rowid copied is the last insert rowid" [ [ Sqlite.Int 20L ] ] (select db "SELECT last_insert_rowid()") (* A column whose DEFAULT text differs makes the tables of two shapes, which sqlite3 does not transfer between: the rows go in decoded and take the next rowids of t. *) let test_a_default_that_differs_is_no_transfer () = let db = Sqlite.in_memory () in exec db "CREATE TABLE s (a TEXT, b INTEGER)"; exec db "INSERT INTO s (rowid, a, b) VALUES (5, 'x', 1), (10, 'y', 2)"; exec db "CREATE TABLE t (a TEXT, b INTEGER DEFAULT 0)"; exec db "CREATE INDEX t_a ON t (a)"; exec db "INSERT INTO t SELECT * FROM s"; Alcotest.check rows "the rows take the rowids t hands out" [ [ Sqlite.Int 1L; Sqlite.Text "x" ]; [ Sqlite.Int 2L; Sqlite.Text "y" ] ] (select db "SELECT rowid, a FROM t ORDER BY rowid") (* Into a target that already holds rows, the transfer inserts each record at its own INTEGER PRIMARY KEY and refuses one already taken: the statement is undone, and the rows copied before the refusal have each moved the last insert rowid, as in sqlite3. *) let test_a_transfer_onto_a_taken_key_is_refused () = let db = Sqlite.in_memory () in exec db "CREATE TABLE s (k INTEGER PRIMARY KEY, v)"; exec db "INSERT INTO s VALUES (1, 'a'), (2, 'b'), (3, 'c')"; exec db "CREATE TABLE t (k INTEGER PRIMARY KEY, v)"; exec db "INSERT INTO t VALUES (3, 'old')"; Alcotest.check_raises "refused at the taken key" (Sqlite.Error (Constraint (Unique { table = "t"; columns = [ "k" ] }))) (fun () -> exec db "INSERT INTO t SELECT * FROM s"); Alcotest.check rows "t is as it was" [ [ Sqlite.Int 3L; Sqlite.Text "old" ] ] (select db "SELECT k, v FROM t"); Alcotest.check rows "the last row copied set the last insert rowid" [ [ Sqlite.Int 2L ] ] (select db "SELECT last_insert_rowid()") (* A statement that fails under ABORT or ROLLBACK is undone and publishes no change; one that fails under FAIL keeps the rows it wrote and publishes their count; total_changes() adds what was published (vdbeaux.c, sqlite3VdbeHalt: a statement rolled back sets the count to 0). sqlite3 3.54.1, the statements one by one, answers 0|1, 1|2, 0|3, 1|4 and 0|4. *) let test_a_failed_statement_publishes_what_it_kept () = let db = Sqlite.in_memory () in let counts () = select db "SELECT changes(), total_changes()" in let counted msg c t = Alcotest.check rows msg [ [ Sqlite.Int c; Sqlite.Int t ] ] (counts ()) in let violates sql = match exec db sql with | () -> Alcotest.failf "expected %S to violate UNIQUE" sql | exception Sqlite.Error (Constraint (Unique _)) -> () in exec db "CREATE TABLE f (a UNIQUE)"; exec db "INSERT INTO f VALUES (1)"; violates "INSERT INTO f VALUES (2), (1)"; counted "ABORT publishes nothing" 0L 1L; violates "INSERT OR FAIL INTO f VALUES (3), (1)"; counted "FAIL publishes the row it kept" 1L 2L; exec db "BEGIN"; exec db "INSERT INTO f VALUES (4)"; violates "INSERT INTO f VALUES (5), (1)"; counted "ABORT inside a transaction" 0L 3L; violates "INSERT OR FAIL INTO f VALUES (6), (1)"; counted "FAIL inside a transaction" 1L 4L; violates "INSERT OR ROLLBACK INTO f VALUES (7), (1)"; counted "ROLLBACK publishes nothing" 0L 4L (* changes() counts SQL statements: a row the table door stores is no part of the next statement's count, which starts from zero as every statement's program does (vdbeaux.c, sqlite3VdbeRewind sets nChange to 0). Carried over, the INSERT below would answer 2. *) let test_a_statement_counts_from_zero () = let db = Sqlite.in_memory () in exec db "CREATE TABLE t (a)"; ignore (Sqlite.Table.insert db ~table:"t" [ Sqlite.Int 1L ] : int64 option); exec db "INSERT INTO t VALUES (2)"; Alcotest.check rows "the INSERT's row alone" [ [ Sqlite.Int 1L ] ] (select db "SELECT changes()") (* A row an earlier step of the same statement removed is passed over, as sqlite3 re-seeks each collected rowid and skips one that is gone (vdbe.c, OP_NotExists). Row 1's REPLACE deletes row 2, which takes the key 2 row 1 moves to; writing row 2 back would leave three rows. *) let test_an_update_skips_a_row_its_replace_removed () = let db = Sqlite.in_memory () in exec db "CREATE TABLE t (a INTEGER, b UNIQUE)"; exec db "INSERT INTO t VALUES (1, 1), (2, 2), (3, 3)"; exec db "UPDATE OR REPLACE t SET b = b + 1"; Alcotest.check rows "row 2 stays deleted" [ [ Sqlite.Int 1L; Sqlite.Int 1L; Sqlite.Int 2L ]; [ Sqlite.Int 3L; Sqlite.Int 3L; Sqlite.Int 4L ]; ] (select db "SELECT rowid, * FROM t ORDER BY rowid") (* The same for a row a BEFORE trigger deleted: its own firing never runs, so the trigger does not delete the row after it on its behalf. *) let test_an_update_skips_a_row_a_trigger_removed () = let db = Sqlite.in_memory () in exec db "CREATE TABLE v (a, b)"; exec db "INSERT INTO v VALUES (1, 1), (2, 2), (3, 3)"; exec db "CREATE TRIGGER tr BEFORE UPDATE ON v BEGIN DELETE FROM v WHERE a = old.a \ + 1; END"; exec db "UPDATE v SET b = b + 10"; Alcotest.check rows "rows 1 and 3 rewritten, row 2 gone" [ [ Sqlite.Int 1L; Sqlite.Int 1L; Sqlite.Int 11L ]; [ Sqlite.Int 3L; Sqlite.Int 3L; Sqlite.Int 13L ]; ] (select db "SELECT rowid, * FROM v ORDER BY rowid") let test_a_delete_skips_a_row_a_trigger_removed () = let db = Sqlite.in_memory () in exec db "CREATE TABLE w (a)"; exec db "CREATE TABLE log (a)"; exec db "INSERT INTO w VALUES (1), (2), (3)"; exec db "CREATE TRIGGER tw BEFORE DELETE ON w BEGIN INSERT INTO log VALUES \ (old.a); DELETE FROM w WHERE a = old.a + 1; END"; exec db "DELETE FROM w"; Alcotest.check rows "no firing for the row row 1's trigger deleted" [ [ Sqlite.Int 1L ]; [ Sqlite.Int 3L ] ] (select db "SELECT a FROM log ORDER BY rowid") (* A row is taken out of its indexes by the values it was collected with only where nothing could have written it since. A BEFORE trigger that rewrites the row's indexed column moves its index entry; were the collected values used, the UPDATE, which writes [b] back unchanged, would find no entry to move and the DELETE would remove the entry the row no longer has, leaving the one the trigger made beside a record that does not match it, which integrity_check reports. The rows are sqlite3 3.54's answer. *) let test_a_row_a_trigger_rewrote_is_read_again () = let db = Sqlite.in_memory () in exec db "CREATE TABLE t (a, b)"; exec db "CREATE INDEX ti ON t (b)"; exec db "INSERT INTO t VALUES (1, 1), (2, 2), (3, 3)"; exec db "CREATE TRIGGER tu BEFORE UPDATE OF a ON t BEGIN UPDATE t SET b = b + 100 \ WHERE rowid = old.rowid; END"; exec db "UPDATE t SET a = a + 10, b = b"; Alcotest.check rows "the rows after the UPDATE" [ [ Sqlite.Int 11L; Int 1L ]; [ Int 12L; Int 2L ]; [ Int 13L; Int 3L ] ] (select db "SELECT a, b FROM t ORDER BY rowid"); Alcotest.check rows "the index matches the rows after the UPDATE" [ [ Sqlite.Text "ok" ] ] (select db "PRAGMA integrity_check"); exec db "CREATE TRIGGER td BEFORE DELETE ON t BEGIN UPDATE t SET b = b + 100 WHERE \ rowid = old.rowid; END"; exec db "DELETE FROM t WHERE a = 11"; Alcotest.check rows "the index matches the rows after the DELETE" [ [ Sqlite.Text "ok" ] ] (select db "PRAGMA integrity_check") (* An UPDATE or a DELETE hands the store the row it collected, which the store then takes out of every index without reading the row again. The collected row has to be the stored one in each shape an index reads: a REAL column holding an integer, a column added after the rows with its DEFAULT, the rowid alias, whether the rows were found by a range or by an equality. A row that differed would leave its old index entries behind, which integrity_check reports; the rows are sqlite3 3.54's answer. *) let test_a_collected_row_is_the_stored_row () = let db = Sqlite.in_memory () in exec db "CREATE TABLE s (a INTEGER PRIMARY KEY, r REAL, c)"; exec db "CREATE INDEX s_r ON s (r)"; exec db "CREATE INDEX s_ac ON s (a, c)"; exec db "INSERT INTO s (a, r, c) VALUES (1, 1, 'x'), (2, 2.5, 'y'), (3, 3, 'z'), \ (4, 4, 'w')"; exec db "ALTER TABLE s ADD COLUMN d DEFAULT 7"; exec db "CREATE INDEX s_d ON s (d)"; exec db "UPDATE s SET c = c || '!' WHERE r > 1"; exec db "UPDATE s SET c = c || '?' WHERE c = 'x'"; exec db "UPDATE s SET d = d + 1 WHERE a >= 3"; exec db "DELETE FROM s WHERE r < 3 AND a > 1"; exec db "DELETE FROM s WHERE c = 'x?'"; Alcotest.check rows "the rows" [ [ Sqlite.Int 3L; Float 3.; Text "z!"; Int 8L ]; [ Int 4L; Float 4.; Text "w!"; Int 8L ]; ] (select db "SELECT a, r, c, d FROM s ORDER BY a"); Alcotest.check rows "the index matches the rows" [ [ Sqlite.Text "ok" ] ] (select db "PRAGMA integrity_check") (* sqlite3 rewrites an UPDATE's rows in table order and evaluates a SET subquery as each row is reached: one correlated to the row reads the table as the rows before it left it, and one that is not is evaluated once for the statement (expr.c, sqlite3CodeSubselect, OP_Once). Each answer is sqlite3 3.54.1's on the same statements: a subquery read from the table as it stood when the statement began gives 5,4,3 and 31,22,13 instead. *) let test_set_subquery_reads_the_rows_before_it () = let db = Sqlite.in_memory () in let run update = exec db "DELETE FROM t"; exec db "INSERT INTO t VALUES (1), (2), (3)"; exec db update; select db "SELECT x FROM t ORDER BY rowid" in let ints l = List.map (fun i -> [ Sqlite.Int (Int64.of_int i) ]) l in exec db "CREATE TABLE t (x)"; Alcotest.check rows "a correlated sum" (ints [ 5; 8; 13 ]) (run "UPDATE t SET x = (SELECT sum(u.x) FROM t AS u WHERE u.x <> t.x)"); Alcotest.check rows "a correlated count" (ints [ 31; 32; 33 ]) (run "UPDATE t SET x = (SELECT count(*) FROM t AS u WHERE u.x >= t.x) * 10 + \ x"); Alcotest.check rows "an uncorrelated max, evaluated once" (ints [ 4; 4; 4 ]) (run "UPDATE t SET x = (SELECT max(x) FROM t) + 1") (* An UPDATE whose rewrite moves a row ahead of the walk that found it -- its rowid, or its entry in the index the WHERE is sought through -- rewrites each row once: sqlite3 takes no one-pass rewrite where the key moves or the SET reaches an index (update.c, chngKey and aRegIdx against WHERE_ONEPASS_MULTIROW), and collects the rows first. *) let test_an_update_moving_its_walk_rewrites_each_row_once () = let db = Sqlite.in_memory () in let ints l = List.map (fun i -> [ Sqlite.Int (Int64.of_int i) ]) l in exec db "CREATE TABLE k (id INTEGER PRIMARY KEY, v); CREATE TABLE a (n INTEGER, \ v); CREATE INDEX an ON a (n)"; for i = 1 to 50 do exec db (Fmt.str "INSERT INTO k VALUES (%d, %d); INSERT INTO a VALUES (%d, %d)" i i i i) done; exec db "UPDATE k SET id = id + 1000 WHERE v >= 0"; Alcotest.check rows "each key moved once" (ints (List.init 50 (fun i -> i + 1001))) (select db "SELECT id FROM k ORDER BY id"); exec db "UPDATE a SET n = n + 1000 WHERE n > 0"; Alcotest.check rows "each indexed value moved once" (ints (List.init 50 (fun i -> i + 1001))) (select db "SELECT n FROM a ORDER BY v"); Alcotest.check rows "the index matches the rows" [ [ Sqlite.Text "ok" ] ] (select db "PRAGMA integrity_check") (* An UPDATE whose SET moves a row's entry further along the index its WHERE is sought through rewrites each row once. The seek steps the index's live entries, so a one-pass rewrite would meet the moved entries again once the key's entries span more than one page: sqlite3 takes no one-pass rewrite where the cursor its loop walks is an index the SET reaches (update.c, aiCurOnePass[1] against aToOpen, ONEPASS_MULTI turned to ONEPASS_OFF) and collects the rows first. The answer is sqlite3 3.54.1's; a one-pass over the index leaves rows rewritten twice and others never. *) let test_an_update_moving_its_index_entry_rewrites_each_row_once () = let db = Sqlite.in_memory () in exec db "CREATE TABLE a (n INTEGER, w INTEGER); CREATE INDEX anw ON a (n, w)"; exec db "WITH RECURSIVE c(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM c WHERE i < \ 1000) INSERT INTO a SELECT 1, i FROM c"; exec db "UPDATE a SET w = w + 1000 WHERE n = 1"; Alcotest.check rows "each entry moved once" (List.init 1000 (fun i -> [ Sqlite.Int (Int64.of_int (i + 1001)) ])) (select db "SELECT w FROM a ORDER BY rowid"); Alcotest.check rows "the index matches the rows" [ [ Sqlite.Text "ok" ] ] (select db "PRAGMA integrity_check") (* An UPDATE whose SET reaches an index its WHERE does not walk rewrites each row where the walk stands, in the walk's order, writing the other index as it goes: sqlite3 turns its one-pass rewrite off only where the cursor its loop walks is an index the SET reaches (update.c, aiCurOnePass[1] against aToOpen). A SET subquery reading the table sees the rows rewritten before its own, in the order of t_c0. The answer is sqlite3 3.54.1's; a rewrite in rowid order answers 1|50|x|a, 2|40|1x|b, 3|45|12x|c. *) let test_an_update_reaching_an_index_it_does_not_walk_is_one_pass () = let db = Sqlite.in_memory () in exec db "CREATE TABLE t (id INTEGER PRIMARY KEY, c0 INTEGER, c1 TEXT, c2 TEXT); \ CREATE INDEX t_c0 ON t (c0); CREATE INDEX t_c2 ON t (c2); INSERT INTO t \ VALUES (1, 50, 'a', 'p'), (2, 40, 'b', 'q'), (3, 45, 'c', 'r'), (4, 10, \ 'd', 's')"; exec db "UPDATE t SET c1 = coalesce((SELECT group_concat(id, '') FROM t AS u WHERE \ u.c1 LIKE '%x' AND u.id <> t.id), '') || 'x', c2 = c1 WHERE c0 > 39"; let row id c0 c1 c2 = Sqlite.[ Int (Int64.of_int id); Int (Int64.of_int c0); Text c1; Text c2 ] in Alcotest.check rows "rewritten in the order of t_c0" [ row 1 50 "23x" "a"; row 2 40 "x" "b"; row 3 45 "2x" "c"; row 4 10 "d" "s"; ] (select db "SELECT id, c0, c1, c2 FROM t ORDER BY id"); Alcotest.check rows "the indexes match the rows" [ [ Sqlite.Text "ok" ] ] (select db "PRAGMA integrity_check") let suite = ( "write", [ Alcotest.test_case "a failed statement publishes what it kept" `Quick test_a_failed_statement_publishes_what_it_kept; Alcotest.test_case "a statement counts from zero" `Quick test_a_statement_counts_from_zero; Alcotest.test_case "INSERT OR IGNORE skips the CHECK violator" `Quick test_insert_or_ignore_skips_the_check_violator; Alcotest.test_case "UPSERT DO UPDATE WHERE gates the rewrite" `Quick test_upsert_do_update_where_gates_the_rewrite; Alcotest.test_case "UPSERT WHERE reads text as a number" `Quick test_upsert_where_reads_text_as_a_number; Alcotest.test_case "DEFAULT VALUES stores the declared defaults" `Quick test_default_values_stores_the_declared_defaults; Alcotest.test_case "UPDATE ... FROM reads the joined scope" `Quick test_update_from_reads_the_joined_scope; Alcotest.test_case "an UPDATE names its table under an alias" `Quick test_an_update_names_its_table_under_an_alias; Alcotest.test_case "a keyed DELETE returns and removes one row" `Quick test_keyed_delete_returns_and_removes_one_row; Alcotest.test_case "RETURNING an unknown column is refused before the write" `Quick test_returning_an_unknown_column_is_refused_before_the_write; Alcotest.test_case "a view is not a write target" `Quick test_a_view_is_not_a_write_target; Alcotest.test_case "INSERT names the rowid alone" `Quick test_insert_names_only_the_rowid; Alcotest.test_case "INSERT names the rowid" `Quick test_insert_names_the_rowid; Alcotest.test_case "INSERT at a taken rowid" `Quick test_insert_at_a_taken_rowid; Alcotest.test_case "a named rowid is an integer" `Quick test_a_named_rowid_is_an_integer; Alcotest.test_case "the alias and the keyword are one column" `Quick test_the_alias_and_the_keyword_are_one_column; Alcotest.test_case "UPDATE moves the row" `Quick test_update_moves_the_row; Alcotest.test_case "UPDATE moves an INTEGER PRIMARY KEY" `Quick test_update_moves_an_integer_primary_key; Alcotest.test_case "a rowidless table has no rowid to name" `Quick test_a_rowidless_table_has_no_rowid_to_name; Alcotest.test_case "a declared column shadows the keyword" `Quick test_a_declared_column_shadows_the_keyword; Alcotest.test_case "a constraint reads the key the row takes" `Quick test_a_constraint_reads_the_key_the_row_takes; Alcotest.test_case "a transfer keeps the source rowids" `Quick test_transfer_keeps_the_source_rowids; Alcotest.test_case "a DEFAULT that differs is no transfer" `Quick test_a_default_that_differs_is_no_transfer; Alcotest.test_case "a transfer onto a taken key is refused" `Quick test_a_transfer_onto_a_taken_key_is_refused; Alcotest.test_case "an UPDATE skips a row its REPLACE removed" `Quick test_an_update_skips_a_row_its_replace_removed; Alcotest.test_case "an UPDATE skips a row a trigger removed" `Quick test_an_update_skips_a_row_a_trigger_removed; Alcotest.test_case "a DELETE skips a row a trigger removed" `Quick test_a_delete_skips_a_row_a_trigger_removed; Alcotest.test_case "a row a trigger rewrote is read again" `Quick test_a_row_a_trigger_rewrote_is_read_again; Alcotest.test_case "a collected row is the stored row" `Quick test_a_collected_row_is_the_stored_row; Alcotest.test_case "a SET subquery reads the rows before it" `Quick test_set_subquery_reads_the_rows_before_it; Alcotest.test_case "an UPDATE moving its walk rewrites each row once" `Quick test_an_update_moving_its_walk_rewrites_each_row_once; Alcotest.test_case "an UPDATE moving its index entry rewrites each row once" `Quick test_an_update_moving_its_index_entry_rewrites_each_row_once; Alcotest.test_case "an UPDATE reaching an index it does not walk is one-pass" `Quick test_an_update_reaching_an_index_it_does_not_walk_is_one_pass; ] )