Something went wrong. Try again.
SQL frontend over the catalog engine
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683(* A trigger over the in-memory store: the store keeps its text ({!Catalog.Spi.define}) and the engine checks it, and fires it from each INSERT, UPDATE and DELETE it runs. Each expected answer is the sqlite3 CLI's (3.54.1) for the same statements. *)
module Value = Catalog.Value
let vrows = Alcotest.list (Alcotest.testable (Fmt.Dump.list Value.pp) (List.equal Value.equal))
let i n = Value.Int nlet s x = Value.Text xlet run db sql = match Sql.exec db sql with Sql.Rows r -> r | Sql.Done -> []
let refused db msg sql = match Sql.exec db sql with | _ -> Alcotest.failf "%s: accepted, sqlite3 refuses it with %S" sql msg | exception Catalog.Error e -> Alcotest.(check string) sql msg (Fmt.str "%a" Catalog.Error.pp e)
let fresh () = let db = Sql.v (Catalog.of_mem []) in ignore (run db "CREATE TABLE t(a, b); CREATE TABLE log(x)"); db
(* lang_createtrigger.html: an AFTER INSERT trigger runs its body once for each row, reading the row as NEW. Its writes are not the statement's own changes (sqlite3 answers 3, 7, then changes() 2 and total_changes() 4). *)let test_after_insert () = let db = fresh () in ignore (run db "CREATE TRIGGER tr AFTER INSERT ON t BEGIN INSERT INTO log VALUES \ (NEW.a + NEW.b); END"); ignore (run db "INSERT INTO t VALUES (1, 2), (3, 4)"); Alcotest.check vrows "one log row a row" [ [ i 3L ]; [ i 7L ] ] (run db "SELECT * FROM log"); Alcotest.check vrows "the statement's changes" [ [ i 2L ] ] (run db "SELECT changes()"); Alcotest.check vrows "every change" [ [ i 4L ] ] (run db "SELECT total_changes()")
(* An UPDATE OF trigger fires for an UPDATE assigning one of its columns, and its WHEN reads OLD and NEW. sqlite3 logs 2->12 and 4->14 alone. *)let test_update_of_when () = let db = fresh () in ignore (run db "INSERT INTO t VALUES (1, 2), (3, 4)"); ignore (run db "CREATE TRIGGER tu BEFORE UPDATE OF b ON t WHEN NEW.b > OLD.b BEGIN \ INSERT INTO log VALUES (OLD.b || '->' || NEW.b); END"); ignore (run db "UPDATE t SET b = b + 10"); ignore (run db "UPDATE t SET a = 0"); ignore (run db "UPDATE t SET b = 1 WHERE b = 12"); Alcotest.check vrows "the log" [ [ s "2->12" ]; [ s "4->14" ] ] (run db "SELECT * FROM log"); Alcotest.check vrows "the rows" [ [ i 0L; i 1L ]; [ i 0L; i 14L ] ] (run db "SELECT * FROM t")
(* A DELETE trigger reads the row as OLD. *)let test_after_delete () = let db = fresh () in ignore (run db "INSERT INTO t VALUES (1, 2), (3, 4)"); ignore (run db "CREATE TRIGGER td AFTER DELETE ON t BEGIN INSERT INTO log VALUES \ ('gone ' || OLD.b); END"); ignore (run db "DELETE FROM t WHERE a = 3"); Alcotest.check vrows "the log" [ [ s "gone 4" ] ] (run db "SELECT * FROM log"); Alcotest.check vrows "the statement's changes" [ [ i 1L ] ] (run db "SELECT changes()")
(* lang_createtrigger.html, RAISE(): IGNORE drops the row the BEFORE trigger fired for, ABORT undoes the statement with its message. sqlite3 keeps 1 and 2 through both statements. *)let test_raise () = let db = fresh () in ignore (run db "CREATE TRIGGER g BEFORE INSERT ON t WHEN NEW.a < 0 BEGIN SELECT \ RAISE(IGNORE); END"); ignore (run db "CREATE TRIGGER h BEFORE INSERT ON t WHEN NEW.a > 100 BEGIN SELECT \ RAISE(ABORT, 'too big'); END"); ignore (run db "INSERT INTO t(a) VALUES (1), (-1), (2)"); Alcotest.check vrows "IGNORE skipped a row" [ [ i 1L ]; [ i 2L ] ] (run db "SELECT a FROM t"); Alcotest.check vrows "the statement's changes" [ [ i 2L ] ] (run db "SELECT changes()"); refused db "too big" "INSERT INTO t(a) VALUES (3), (200)"; Alcotest.check vrows "ABORT undid the statement" [ [ i 1L ]; [ i 2L ] ] (run db "SELECT a FROM t")
(* A trigger whose program is on the stack does not fire again unless recursive_triggers is on (lang_createtrigger.html, pragma.html), and the stack holds SQLITE_MAX_TRIGGER_DEPTH programs. sqlite3 answers 2, 0, 1, 5, then refuses and leaves 5. *)let test_recursion () = let db = Sql.v (Catalog.of_mem []) in ignore (run db "CREATE TABLE c(n); INSERT INTO c VALUES (0)"); ignore (run db "CREATE TRIGGER r AFTER UPDATE ON c WHEN NEW.n < 5 BEGIN UPDATE c SET n \ = n + 1; END"); ignore (run db "UPDATE c SET n = 1"); Alcotest.check vrows "not recursive" [ [ i 2L ] ] (run db "SELECT * FROM c"); Alcotest.check vrows "off" [ [ i 0L ] ] (run db "PRAGMA recursive_triggers"); ignore (run db "PRAGMA recursive_triggers = 1"); Alcotest.check vrows "on" [ [ i 1L ] ] (run db "PRAGMA recursive_triggers"); ignore (run db "UPDATE c SET n = 1"); Alcotest.check vrows "recursive" [ [ i 5L ] ] (run db "SELECT * FROM c"); ignore (run db "DROP TRIGGER r"); ignore (run db "CREATE TRIGGER r AFTER UPDATE ON c BEGIN UPDATE c SET n = n + 1; END"); refused db "triggers nested too deep" "UPDATE c SET n = 0"; Alcotest.check vrows "undone" [ [ i 5L ] ] (run db "SELECT * FROM c")
(* A REPLACE fires the DELETE triggers of the rows it deletes only under recursive_triggers (lang_conflict.html). sqlite3 logs nothing, then "del b". *)let test_replace_deletes () = let db = Sql.v (Catalog.of_mem []) in ignore (run db "CREATE TABLE k(id INTEGER PRIMARY KEY, v); CREATE TABLE log(x); INSERT \ INTO k VALUES (1, 'a')"); ignore (run db "CREATE TRIGGER d AFTER DELETE ON k BEGIN INSERT INTO log VALUES ('del \ ' || OLD.v); END"); ignore (run db "INSERT OR REPLACE INTO k VALUES (1, 'b')"); Alcotest.check vrows "off" [] (run db "SELECT * FROM log"); ignore (run db "PRAGMA recursive_triggers = ON"); ignore (run db "INSERT OR REPLACE INTO k VALUES (1, 'c')"); Alcotest.check vrows "on" [ [ s "del b" ] ] (run db "SELECT * FROM log"); Alcotest.check vrows "the row" [ [ i 1L; s "c" ] ] (run db "SELECT * FROM k")
(* trigger.c, codeTriggerProgram: the firing statement's OR clause overrides the step's. sqlite3 answers 1|new. *)let test_policy () = let db = Sql.v (Catalog.of_mem []) in ignore (run db "CREATE TABLE a(x); CREATE TABLE b(k UNIQUE, v); INSERT INTO b VALUES \ (1, 'old')"); ignore (run db "CREATE TRIGGER g AFTER INSERT ON a BEGIN INSERT OR IGNORE INTO b \ VALUES (NEW.x, 'new'); END"); ignore (run db "INSERT OR REPLACE INTO a VALUES (1)"); Alcotest.check vrows "REPLACE" [ [ i 1L; s "new" ] ] (run db "SELECT * FROM b")
(* A trigger is part of the schema a transaction undoes, and its name is taken among triggers. *)let test_definition () = let db = fresh () in ignore (run db "BEGIN; CREATE TRIGGER tr AFTER INSERT ON t BEGIN INSERT INTO log \ VALUES (NEW.a); END; ROLLBACK"); ignore (run db "INSERT INTO t VALUES (1, 1)"); Alcotest.check vrows "rolled back" [ [ i 0L ] ] (run db "SELECT count(*) FROM log"); ignore (run db "CREATE TRIGGER tr AFTER INSERT ON t BEGIN INSERT INTO log VALUES \ (NEW.a); END"); refused db "trigger tr already exists" "CREATE TRIGGER tr AFTER INSERT ON t BEGIN SELECT 1; END"; ignore (run db "DROP TABLE t; CREATE TABLE t(a, b)"); ignore (run db "INSERT INTO t VALUES (5, 5)"); Alcotest.check vrows "dropped with its table" [ [ i 0L ] ] (run db "SELECT count(*) FROM log")
(* {1 Firing, step by step}
The rows a write leaves say nothing about whether a body was skipped by its guard, abandoned by an IGNORE, or never selected at all. The steps are asked separately here, and the executor a body runs through is a fake that records the statements handed to it, so a test can say exactly which bodies ran and in which order. *)
module T = Sql.Private.Triggermodule C = Sql.Private.Connectionmodule Ast = Sql.Ast
let names tgs = List.map (fun (tg : Ast.create_trigger) -> tg.name) tgslet strings = Alcotest.(list string)
let definition ?(kind = `Trigger) name sql = Catalog.Spi.Definition.v kind ~name ~table:"t" (Some sql)
(* Definitions as a store lists them, each under its rowid. *)let numbered defs = List.mapi (fun i d -> (Int64.of_int (i + 1), d)) defs
let test_of_definitions_parses_triggers () = Alcotest.check strings "both, in the order the store keeps them" [ "a"; "b" ] (names @@ T.of_definitions @@ numbered [ definition "a" "CREATE TRIGGER a AFTER INSERT ON t BEGIN SELECT 1; END"; definition "b" "CREATE TRIGGER b AFTER DELETE ON t BEGIN SELECT 2; END"; ])
(* A view is a definition too, and is not a program. *)let test_of_definitions_ignores_views () = Alcotest.check strings "only the trigger" [] (names @@ T.of_definitions @@ numbered [ definition ~kind:`View "v" "CREATE VIEW v AS SELECT 1" ])
(* A store another writer wrote can hold a trigger this engine does not parse. That costs the trigger, not the store. *)let test_of_definitions_drops_what_it_cannot_parse () = Alcotest.check strings "the parseable one survives alone" [ "ok" ] (names @@ T.of_definitions @@ numbered [ definition "bad" "CREATE TRIGGER bad AFTER INSERT ON t BEGIN <<>> END"; definition "ok" "CREATE TRIGGER ok AFTER INSERT ON t BEGIN SELECT 1; END"; definition "two" "CREATE TRIGGER two AFTER INSERT ON t BEGIN SELECT 1; END; SELECT \ 2"; ])
let parse sql = Option.get (T.of_sql sql)
let tg name timing event = Fmt.kstr parse "CREATE TRIGGER %s %s %s ON t BEGIN SELECT 1; END" name timing event
let all = [ tg "bi" "BEFORE" "INSERT"; tg "ai" "AFTER" "INSERT"; tg "ad" "AFTER" "DELETE"; tg "au" "AFTER" "UPDATE"; tg "auc" "AFTER" "UPDATE OF a, b"; ]
let matching ?(tgs = all) ?(table = "t") ~timing ~event () = names (T.matching tgs ~timing ~event ~table)
let test_matching_selects_by_timing_and_event () = Alcotest.check strings "BEFORE INSERT" [ "bi" ] (matching ~timing:Ast.Before ~event:`Insert ()); Alcotest.check strings "AFTER INSERT" [ "ai" ] (matching ~timing:Ast.After ~event:`Insert ()); Alcotest.check strings "AFTER DELETE" [ "ad" ] (matching ~timing:Ast.After ~event:`Delete ()); Alcotest.check strings "BEFORE DELETE fires nothing here" [] (matching ~timing:Ast.Before ~event:`Delete ())
(* A bare UPDATE trigger fires whatever the statement assigned; an UPDATE OF fires only when the statement assigned one of its columns. *)let test_matching_reads_update_of_columns () = Alcotest.check strings "a assigned: both" [ "auc"; "au" ] (matching ~timing:Ast.After ~event:(`Update [ "a" ]) ()); Alcotest.check strings "c assigned: only the bare one" [ "au" ] (matching ~timing:Ast.After ~event:(`Update [ "c" ]) ()); Alcotest.check strings "nothing assigned: still the bare one" [ "au" ] (matching ~timing:Ast.After ~event:(`Update []) ())
(* Column and table names are identifiers, so a differently spelled statement fires the same triggers. *)let test_matching_compares_identifiers () = Alcotest.check strings "an assigned column spelled in another case" [ "auc"; "au" ] (matching ~timing:Ast.After ~event:(`Update [ "A" ]) ()); Alcotest.check strings "and the table too" [ "ai" ] (matching ~table:"T" ~timing:Ast.After ~event:`Insert ()); Alcotest.check strings "but not another table" [] (matching ~table:"other" ~timing:Ast.After ~event:`Insert ())
(* The newest trigger fires first, and the order does not read the names: sqlite3 links each new trigger onto the head of its table's list (sqlite3FinishTrigger, trigger.c), and reading a schema back walks it in order onto the same head. The documentation calls the order undefined (lang_createtrigger.html); a row a body wrote does not, which is why it is pinned. *)let test_matching_fires_the_newest_first () = let tgs = [ tg "z" "AFTER" "INSERT"; tg "a" "AFTER" "INSERT" ] in Alcotest.check strings "the later declaration first, not sorted" [ "a"; "z" ] (matching ~tgs ~timing:Ast.After ~event:`Insert ())
let int_ n = Ast.Int (Int64.of_int n)
let bound scope = List.map (fun (name, cells) -> (name, List.map (fun (c, v) -> (c, Sql.Value_ops.text_of_value v)) cells)) scope
let scope_t = Alcotest.(list (pair string (list (pair string string))))
let test_bindings_puts_each_row_under_its_name () = Alcotest.check scope_t "OLD then NEW, each qualified" [ ("old", [ ("a", "1"); ("b", "x") ]); ("new", [ ("a", "2"); ("b", "y") ]) ] (bound (T.bindings ~cols:[ "a"; "b" ] ~old:(Some [ int_ 1; Ast.Text "x" ]) ~new_:(Some [ int_ 2; Ast.Text "y" ]) ()))
(* An INSERT has no OLD row and a DELETE no NEW one, so neither is bound at all, which is what makes [NEW.x] in a DELETE trigger a name that does not resolve rather than one that reads NULL. *)let test_bindings_omits_the_row_a_write_has_not () = Alcotest.check scope_t "an INSERT binds NEW alone" [ ("new", [ ("a", "2") ]) ] (bound (T.bindings ~cols:[ "a" ] ~old:None ~new_:(Some [ int_ 2 ]) ())); Alcotest.check scope_t "a DELETE binds OLD alone" [ ("old", [ ("a", "1") ]) ] (bound (T.bindings ~cols:[ "a" ] ~old:(Some [ int_ 1 ]) ~new_:None ())); Alcotest.check scope_t "and neither is neither" [] (bound (T.bindings ~cols:[ "a" ] ~old:None ~new_:None ()))
(* A firing row on a rowid table has a key like any other row of it, and [OLD.rowid] and [NEW.rowid] read it (resolve.c, lookupName). It is bound where a scan publishes it ({!Sql.Private.Resolve.rowid_sentinel}), so all three spellings resolve to it and a declared column of one of those names shadows it as it shadows a scan's. *)let rowid_slot = Sql.Private.Resolve.rowid_sentinel
let test_bindings_carry_the_key_each_row_is_at () = Alcotest.check scope_t "an UPDATE over a key move binds both ends" [ ("old", [ ("a", "1"); (rowid_slot, "3") ]); ("new", [ ("a", "2"); (rowid_slot, "12") ]); ] (bound (T.bindings ~cols:[ "a" ] ~old:(Some [ int_ 1 ]) ~old_rowid:3L ~new_:(Some [ int_ 2 ]) ~new_rowid:12L ())); Alcotest.check scope_t "an INSERT binds the key the row was given" [ ("new", [ ("a", "2"); (rowid_slot, "40") ]) ] (bound (T.bindings ~cols:[ "a" ] ~old:None ~new_:(Some [ int_ 2 ]) ~new_rowid:40L ())); Alcotest.check scope_t "a DELETE binds the key the row was at" [ ("old", [ ("a", "1"); (rowid_slot, "7") ]) ] (bound (T.bindings ~cols:[ "a" ] ~old:(Some [ int_ 1 ]) ~old_rowid:7L ~new_:None ()))
(* A WITHOUT ROWID table's rows have no key of their own, so the caller hands none and the slot is absent. *)let test_bindings_omit_a_key_the_table_has_not () = Alcotest.check scope_t "no key, no slot" [ ("new", [ ("a", "2") ]) ] (bound (T.bindings ~cols:[ "a" ] ~old:None ~new_:(Some [ int_ 2 ]) ()))
type db = { triggers : Ast.create_trigger list; connection : Sql.t; (** the stack the programs run on, and the counts and the rowid a firing saves and puts back *) mutable ran : string list; (** the body statements run, newest first *) mutable scope_seen : int; (** how many bodies saw a non-empty scope *) mutable policies : Ast.insert_conflict list; (** the frame's policy each body statement ran under, newest first *) raise_on : (string * (Sql.Ir.raise_action * Ast.value option)) list; (** the RAISE each named body statement reaches, if any *)}
let db ?(raise_on = []) triggers = { triggers; connection = Sql.v (Catalog.of_mem []); ran = []; scope_seen = 0; policies = []; raise_on; }
let frame d = C.current d.connection
(* The resolution a violation carries, as a name a test can read. *)let conflict = function | Ast.Unspecified -> "unspecified" | Ast.Abort -> "abort" | Ast.Fail -> "fail" | Ast.Ignore -> "ignore" | Ast.Replace -> "replace" | Ast.Rollback -> "rollback"
module Reader = struct type t = db
let triggers d = d.triggers let connection d = d.connection
let catalog _ = Sql.Private.Query.closed ~encoding:Sql.Encoding.Utf8 "a trigger test with no rows"end
module Fire = T.Make (Reader)
(* The statement executor a body runs through. It records what it was handed, notes whether the OLD/NEW scope was in place at the time, and raises where the test asked it to, which is how a [RAISE()] reaches [fire] in the engine too. *)let run_body d stmt = let text = match stmt with Ast.Select s -> Sql.Private.Render.select s | _ -> "?" in d.ran <- text :: d.ran; (match (frame d).scope with | [] -> () | _ :: _ -> d.scope_seen <- d.scope_seen + 1); d.policies <- (frame d).orconf :: d.policies; match List.assoc_opt text d.raise_on with | None -> () | Some (action, message) -> raise (Sql.Ir.Raised (action, message))
let ran d = List.rev d.ran
let fire ?(orconf = Ast.Unspecified) ?(timing = Ast.After) ?(event = `Insert) ?(cols = [ "a" ]) ?old ?old_rowid ?(new_ = Some [ Ast.Int 1L ]) ?new_rowid d = Fire.fire d ~run_body ~orconf ~timing ~event ~table:"t" ~cols ~old ?old_rowid ~new_ ?new_rowid ()
let body name stmts = Fmt.kstr parse "CREATE TRIGGER %s AFTER INSERT ON t BEGIN %s END" name stmts
(* [f] run [n] programs deep. *)let rec nested d n f = if n = 0 then f () else C.program d.connection ~scope:[] ~orconf:Ast.Unspecified (fun () -> nested d (n - 1) f)
let test_no_matching_trigger_runs_nothing () = let d = db [ tg "bi" "BEFORE" "INSERT" ] in Alcotest.(check bool) "the write goes on" true (fire d); Alcotest.check strings "and no body ran" [] (ran d)
(* Inside a firing, a trigger whose program is already on the stack is skipped and the others run, as sqlite3 does with recursive_triggers OFF; with it ON the running one fires again. *)let test_a_running_trigger_is_skipped () = let d = db [ body "a" "SELECT 1;"; body "b" "SELECT 2;" ] in let inside_a f = C.program ~name:"A" d.connection ~scope:[ ("new", [ ("a", Ast.Int 1L) ]) ] ~orconf:Ast.Unspecified f in inside_a (fun () -> Alcotest.(check bool) "the write goes on" true (fire d); Alcotest.check strings "only the trigger not running ran" [ "SELECT 2" ] (ran d); Alcotest.(check int) "and the frame came back" 1 (frame d).depth); d.ran <- []; C.set_recursive_triggers d.connection true; inside_a (fun () -> Alcotest.(check bool) "the write goes on" true (fire d); Alcotest.check strings "recursive_triggers runs both" [ "SELECT 2"; "SELECT 1" ] (ran d))
(* A program pushed onto a stack of [max_depth] programs fails the statement, before its WHEN is read; one fewer runs. *)let test_a_push_past_the_depth_fails () = let d = db [ body "a" "SELECT 1;" ] in nested d C.max_depth (fun () -> Alcotest.check_raises "the 1001st program" (Catalog.Error (Runtime "triggers nested too deep")) (fun () -> ignore (fire d : bool))); Alcotest.check strings "and nothing ran" [] (ran d); nested d (C.max_depth - 1) (fun () -> Alcotest.(check bool) "the 1000th runs" true (fire d)); Alcotest.check strings "its body" [ "SELECT 1" ] (ran d)
(* Trigger by trigger, newest first, and each body's statements in the order it wrote them. *)let test_bodies_run_in_order_under_the_row () = let d = db [ body "a" "SELECT 1; SELECT 2;"; body "b" "SELECT 3;" ] in Alcotest.(check bool) "the write goes on" true (fire d); Alcotest.check strings "every body statement, trigger by trigger" [ "SELECT 3"; "SELECT 1"; "SELECT 2" ] (ran d); Alcotest.(check int) "each saw the firing row" 3 d.scope_seen; Alcotest.check scope_t "and the scope is cleared afterwards" [] (bound (frame d).scope)
(* Each body statement runs under the policy of the statement that fired it, which {!T.step_policy} lays over the statement's own OR clause, and the frame before the firing comes back when it ends. A firing that left the policy behind would hand the next statement's steps a REPLACE nobody wrote. *)let test_bodies_run_under_the_firing_policy () = let d = db [ body "a" "SELECT 1; SELECT 2;" ] in Alcotest.(check bool) "the write goes on" true (fire ~orconf:Ast.Replace d); Alcotest.(check (list string)) "both statements ran under REPLACE" [ "replace"; "replace" ] (List.map conflict d.policies); Alcotest.(check string) "and the frame's policy is gone afterwards" "unspecified" (conflict (frame d).orconf); Alcotest.(check string) "a policy overrides a step's own clause" "replace" (conflict (T.step_policy { C.top with orconf = Ast.Replace } Ast.Ignore)); Alcotest.(check string) "no policy leaves the step its own" "ignore" (conflict (T.step_policy C.top Ast.Ignore))
let test_a_false_guard_skips_the_body () = let d = db [ parse "CREATE TRIGGER a AFTER INSERT ON t WHEN 0 BEGIN SELECT 1; END"; parse "CREATE TRIGGER b AFTER INSERT ON t WHEN NULL BEGIN SELECT 2; END"; parse "CREATE TRIGGER c AFTER INSERT ON t WHEN 1 BEGIN SELECT 3; END"; ] in Alcotest.(check bool) "the write goes on" true (fire d); Alcotest.check strings "only the guard that passed" [ "SELECT 3" ] (ran d)
(* A WHEN is read as a NUMERIC cast reads it, so a text or blob is true only when its numeric prefix is nonzero. sqlite3 3.54.1: CREATE TABLE t(x); CREATE TABLE log(v); CREATE TRIGGER tr AFTER INSERT ON t WHEN new.x BEGIN INSERT INTO log VALUES (new.x); END; INSERT INTO t VALUES ('0'),('abc'),(x'31'),('1x'),('0.0'); SELECT quote(v) FROM log; -- X'31' then '1x' A guard that took any text as true runs all five bodies. *)let test_a_text_guard_reads_its_number () = let d = db [ parse "CREATE TRIGGER a AFTER INSERT ON t WHEN '0' BEGIN SELECT 1; END"; parse "CREATE TRIGGER b AFTER INSERT ON t WHEN 'abc' BEGIN SELECT 2; END"; parse "CREATE TRIGGER c AFTER INSERT ON t WHEN x'31' BEGIN SELECT 3; END"; parse "CREATE TRIGGER e AFTER INSERT ON t WHEN '1x' BEGIN SELECT 4; END"; parse "CREATE TRIGGER f AFTER INSERT ON t WHEN '0.0' BEGIN SELECT 5; END"; ] in Alcotest.(check bool) "the write goes on" true (fire d); Alcotest.check strings "only the guards whose number is nonzero" [ "SELECT 3"; "SELECT 4" ] (List.sort compare (ran d))
let raised_by action = ("SELECT 9", (action, Some (Ast.Text "boom")))
(* IGNORE stops nothing and answers false: this body is abandoned, and so are the bodies of the triggers after it for this row, after it in firing order, which is the trigger declared before it. *)let test_ignore_abandons_the_rest_of_the_row () = let d = db ~raise_on:[ raised_by Sql.Ir.Ignore ] [ body "a" "SELECT 1; SELECT 9; SELECT 2;"; body "b" "SELECT 3;" ] in Alcotest.(check bool) "the row is not written" false (fire d); Alcotest.check strings "nothing after the RAISE ran" [ "SELECT 3"; "SELECT 1"; "SELECT 9" ] (ran d); Alcotest.(check string) "and no resolution was recorded" "unspecified" (conflict (C.resolved d.connection)); Alcotest.check scope_t "the scope is still cleared" [] (bound (frame d).scope)
let stops action expected = let d = db ~raise_on:[ raised_by action ] [ body "a" "SELECT 9;" ] in Alcotest.check_raises "the message alone, as sqlite3 reports it" (Catalog.Error (Constraint (Trigger "boom"))) (fun () -> ignore (fire d : bool)); Alcotest.(check string) "the resolution the RAISE named" expected (conflict (C.resolved d.connection)); Alcotest.check scope_t "and the scope is cleared however it ended" [] (bound (frame d).scope)
let test_abort_stops_the_statement () = stops Sql.Ir.Abort "abort"let test_fail_keeps_the_earlier_rows () = stops Sql.Ir.Fail "fail"let test_rollback_reaches_the_transaction () = stops Sql.Ir.Rollback "rollback"
(* RAISE(ABORT, NULL) reports nothing: sqlite3 raises the message alone, and a NULL message converts to no text at all. *)let test_a_null_message_reports_nothing () = let d = db ~raise_on:[ ("SELECT 9", (Sql.Ir.Abort, Some Ast.Null)) ] [ body "a" "SELECT 9;" ] in Alcotest.check_raises "empty" (Catalog.Error (Constraint (Trigger ""))) (fun () -> ignore (fire d : bool))
let test_no_message_reports_nothing () = let d = db ~raise_on:[ ("SELECT 9", (Sql.Ir.Abort, None)) ] [ body "a" "SELECT 9;" ] in Alcotest.check_raises "empty" (Catalog.Error (Constraint (Trigger ""))) (fun () -> ignore (fire d : bool))
let suite = ( "trigger", [ Alcotest.test_case "AFTER INSERT" `Quick test_after_insert; Alcotest.test_case "UPDATE OF and WHEN" `Quick test_update_of_when; Alcotest.test_case "AFTER DELETE" `Quick test_after_delete; Alcotest.test_case "RAISE" `Quick test_raise; Alcotest.test_case "recursion" `Quick test_recursion; Alcotest.test_case "REPLACE deletes" `Quick test_replace_deletes; Alcotest.test_case "conflict policy" `Quick test_policy; Alcotest.test_case "a definition" `Quick test_definition; Alcotest.test_case "of_definitions: parses the triggers" `Quick test_of_definitions_parses_triggers; Alcotest.test_case "of_definitions: ignores views" `Quick test_of_definitions_ignores_views; Alcotest.test_case "of_definitions: drops what it cannot parse" `Quick test_of_definitions_drops_what_it_cannot_parse; Alcotest.test_case "matching: by timing and event" `Quick test_matching_selects_by_timing_and_event; Alcotest.test_case "matching: UPDATE OF columns" `Quick test_matching_reads_update_of_columns; Alcotest.test_case "matching: names are identifiers" `Quick test_matching_compares_identifiers; Alcotest.test_case "matching: the newest trigger first" `Quick test_matching_fires_the_newest_first; Alcotest.test_case "bindings: OLD and NEW are qualified" `Quick test_bindings_puts_each_row_under_its_name; Alcotest.test_case "bindings: a write binds only the rows it has" `Quick test_bindings_omits_the_row_a_write_has_not; Alcotest.test_case "bindings: each row carries the key it is at" `Quick test_bindings_carry_the_key_each_row_is_at; Alcotest.test_case "bindings: no key where the table keeps none" `Quick test_bindings_omit_a_key_the_table_has_not; Alcotest.test_case "fire: no matching trigger runs nothing" `Quick test_no_matching_trigger_runs_nothing; Alcotest.test_case "fire: a running trigger is skipped" `Quick test_a_running_trigger_is_skipped; Alcotest.test_case "fire: a push past the depth fails" `Quick test_a_push_past_the_depth_fails; Alcotest.test_case "fire: bodies run in order under the row" `Quick test_bodies_run_in_order_under_the_row; Alcotest.test_case "fire: bodies run under the firing policy" `Quick test_bodies_run_under_the_firing_policy; Alcotest.test_case "fire: a false WHEN skips the body" `Quick test_a_false_guard_skips_the_body; Alcotest.test_case "fire: a text WHEN reads its number" `Quick test_a_text_guard_reads_its_number; Alcotest.test_case "raise: IGNORE abandons the rest of the row" `Quick test_ignore_abandons_the_rest_of_the_row; Alcotest.test_case "raise: ABORT stops the statement" `Quick test_abort_stops_the_statement; Alcotest.test_case "raise: FAIL keeps the earlier rows" `Quick test_fail_keeps_the_earlier_rows; Alcotest.test_case "raise: ROLLBACK reaches the transaction" `Quick test_rollback_reaches_the_transaction; Alcotest.test_case "raise: a NULL message reports nothing" `Quick test_a_null_message_reports_nothing; Alcotest.test_case "raise: no message reports nothing" `Quick test_no_message_reports_nothing; ] )