(*--------------------------------------------------------------------------- Copyright (c) 2026 Thomas Gazagnaire. All rights reserved. SPDX-License-Identifier: ISC ---------------------------------------------------------------------------*) (* The questions sqlite3BeginTrigger asks, in its order: the target, the trigger's name among triggers alone, the timing against the target's kind, then the body's placeholders (trigger.c). *) let check_create ~target ~taken (tg : Ast.create_trigger) = let on_view = match target with | Some `Table -> false | Some `View -> true | None -> Catalog.Error.fail_prepare "no such table: main.%s" tg.table in if taken then begin if not tg.if_not_exists then Catalog.Error.fail_prepare "trigger %s already exists" tg.name; false end else begin (match (on_view, tg.timing) with | true, Instead_of -> Catalog.Error.fail_unsupported "INSTEAD OF trigger on view %s: this engine does not write through a \ view" tg.table | true, (Before | After) -> Catalog.Error.fail_prepare "cannot create %s trigger on view: %s" (match tg.timing with After -> "AFTER" | _ -> "BEFORE") tg.table | false, Instead_of -> Catalog.Error.fail_prepare "cannot create INSTEAD OF trigger on table: %s" tg.table | false, (Before | After) -> ()); (* A trigger program is stored and run later, by a statement that binds nothing for it, so a placeholder has no value to read. *) if Param_number.expr_has_param (Option.value tg.when_ ~default:(Ast.Lit Null)) || List.exists Param_number.stmt_has_param tg.body then Catalog.Error.fail_prepare "trigger cannot use variables"; true end type event = [ `Insert | `Delete | `Update of string list ] (* A trigger is stored as the text of its CREATE TRIGGER, parsed back when it may fire. A definition whose text is not one CREATE TRIGGER is skipped: it costs the trigger, not the store. *) let of_sql sql = match Lexer.parse_statements sql with | Ok [ Ast.Create_trigger tg ] -> Some tg | _ -> None let of_definitions defs = List.filter_map (fun (_, (d : Catalog.Spi.Definition.t)) -> match d.kind with | `Trigger -> Option.bind d.sql of_sql | `Table | `Index | `View -> None) defs (* The newest trigger fires first: sqlite3 links each new trigger onto its table's list head (sqlite3FinishTrigger), so reading a schema back walks the definitions in the order the store keeps them onto the same head. Reversing what the filter kept is that list. The order is documented as undefined, but two bodies writing one log table are told apart by nothing else. *) let matching tgs ~timing ~event ~table = let applies (tg : Ast.create_trigger) = Catalog.Ident.equal tg.table table && Ast.equal_trigger_timing tg.timing timing && match (tg.event, event) with | Insert, `Insert -> true | Delete, `Delete -> true | Update upcols, `Update changed -> upcols = [] || List.exists (fun c -> List.exists (Catalog.Ident.equal c) changed) upcols | _ -> false in List.rev (List.filter applies tgs) (* The firing row's key, in the slot a scan publishes one under ({!Resolve.rowid_sentinel}), which is what makes all three spellings resolve and what lets a declared column shadow it. A row with no key binds no slot. *) let key = function | Some r -> [ (Resolve.rowid_sentinel, Ast.Int r) ] | None -> [] let bindings ~cols ~old ?old_rowid ~new_ ?new_rowid () = let bind name rowid = function | Some vals -> [ (name, List.combine cols vals @ key rowid) ] | None -> [] in bind "old" old_rowid old @ bind "new" new_rowid new_ (* The columns the programs of [tgs] read as NEW.x, their WHEN clauses included (resolve.c, the newmask a NEW.x reference sets). *) let new_reads (tgs : Ast.create_trigger list) = let reads = ref [] in let col () qual name = match qual with | Some q when String.lowercase_ascii q = "new" -> reads := name :: !reads | Some _ | None -> () in let table () _ = () and nest () _ = () and cte () _ = Some () in let expr e = Resolve.walk_expr ~table ~col ~nest ~cte () e in let select s = Resolve.walk_select ~table ~col ~nest ~cte () s in let sets = List.iter (fun (_, e) -> expr e) in let stmt : Ast.stmt -> unit = function | Insert i -> ( (match i.source with | Values rows -> List.iter (List.iter expr) rows | Select s -> select s | Default_values -> ()); match i.upsert with | Some { target_where; action; _ } -> ( Option.iter expr target_where; match action with | Update (s, w) -> sets s; Option.iter expr w | Nothing -> ()) | None -> ()) | Update u -> sets u.sets; Option.iter expr u.where | Delete d -> Option.iter expr d.where | Select s -> select s | _ -> () in List.iter (fun (tg : Ast.create_trigger) -> Option.iter expr tg.when_; List.iter stmt tg.body) tgs; !reads (* sqlite3 loads a column the UPDATE does not assign only where a BEFORE trigger reads it as NEW.x or it is past the 32nd, NULL otherwise, and computes the generated columns from that row (update.c, newmask from sqlite3TriggerColmask, then sqlite3ComputeGeneratedColumns). Only a generated column can show the difference, so a table with none is answered as it is. A read of a column past the 32nd loads them all (resolve.c sets every bit of the mask for it). *) let before_update_row tgs tbl ~changed ?rowid new_values = match Table.generated tbl with | [] -> new_values | generated -> ( match matching tgs ~timing:Before ~event:(`Update changed) ~table:(Table.name tbl) with | [] -> new_values | tgs -> let reads = new_reads tgs in let cols = Table.columns tbl in let has names c = List.exists (Catalog.Ident.equal c) names in let past_32 c = match List.find_index (Catalog.Ident.equal c) cols with | Some i -> i >= 32 | None -> false in if List.exists past_32 reads then new_values else let alias = Table.rowid_alias tbl in let loaded i c = i >= 32 || alias = Some i || has (List.map fst generated) c || has changed c || has reads c in Table.generate tbl ?rowid (List.mapi (fun i (c, v) -> if loaded i c then v else Ast.Null) (List.combine cols new_values))) let step_policy (f : Connection.frame) (own : Ast.insert_conflict) = match f.orconf with Unspecified -> own | o -> o let raised conn (action : Ir.raise_action) message = let fail res = Connection.fail conn res (Trigger (match message with | None | Some Ast.Null -> "" | Some v -> Value_ops.text_of_value v)) in match action with | Ignore -> false | Abort -> fail Ast.Abort | Fail -> fail Ast.Fail | Rollback -> fail Ast.Rollback let program conn ~orconf f = Connection.program conn ~scope:[] ~orconf f module type S = sig type t val triggers : t -> Ast.create_trigger list val connection : t -> Connection.t val catalog : t -> Query.catalog end module Make (R : S) = struct (* Run one trigger's guard and, where it passes, its body statements. *) let run db ~run_body (tg : Ast.create_trigger) = let scope = (Connection.current (R.connection db)).scope in let guard_ok = match tg.when_ with | None -> true | Some w -> Value_ops.tri_of (Engine.eval_const ~scope (R.catalog db) [||] w) = Value_ops.T in if guard_ok then List.iter (fun stmt -> run_body db stmt) tg.body (* With recursive_triggers OFF, a trigger whose program is already on the stack is skipped (trigger.c, sqlite3CodeRowTriggerDirect sets P5 for a named trigger; vdbe.c, OP_Program). *) let runnable conn (tg : Ast.create_trigger) = Connection.recursive_triggers conn || not (List.exists (Catalog.Ident.equal tg.name) (Connection.current conn).running) (* Each trigger runs as a program of its own, pushed as OP_Program pushes one (vdbe.c): a push onto {!Connection.max_depth} frames fails the statement, before the trigger's WHEN is read. Lowering the bodies inside {!Lower.in_trigger_program} is what makes a RAISE() an evaluable node rather than a refused statement; the WHEN guards are inside it too, since sqlite3 accepts a RAISE there. *) let fire db ~run_body ~orconf ~timing ~event ~table ~cols ~old ?old_rowid ~new_ ?new_rowid () = let conn = R.connection db in match List.filter (runnable conn) (matching (R.triggers db) ~timing ~event ~table) with | [] -> true | tgs -> ( let scope = bindings ~cols ~old ?old_rowid ~new_ ?new_rowid () in match Lower.in_trigger_program (fun () -> List.iter (fun (tg : Ast.create_trigger) -> Connection.program ~name:tg.name conn ~scope ~orconf (fun () -> run db ~run_body tg)) tgs) with | () -> true | exception Ir.Raised (action, message) -> raised conn action message) end