(*--------------------------------------------------------------------------- Copyright (c) 2026 Thomas Gazagnaire. All rights reserved. SPDX-License-Identifier: ISC ---------------------------------------------------------------------------*) module Spi = Catalog.Spi module Value = Catalog.Value (* The table a write computes its rows under. A store that tracks no schema holds columns nothing is declared about: no affinity, no DEFAULT, nothing generated. *) let table cat name = match Spi.schema cat name with | Some s -> Table.v s | None -> Table.v (Spi.Schema.v name (List.map Spi.Schema.column (Spi.columns cat name))) (* A rowid holds an integer, so the value a statement writes where the key goes is first taken to one as INTEGER affinity takes it: text spelling an integer is that integer, a whole real is too. This is sqlite3's OP_MustBeInt, which the VDBE applies before the B-tree sees the key; a store refuses whatever is still no integer. *) let as_key = Value_ops.apply_affinity `Integer let set_nth i v row = List.mapi (fun j w -> if j = i then v else w) row (* [row] with the value in its key column taken to a key, and the rowid that value states, if it states one. *) let keyed tbl row = match Table.rowid_alias tbl with | None -> (row, None) | Some i -> ( let k = as_key (List.nth row i) in (set_nth i k row, match k with Value.Int r -> Some r | _ -> None)) let has_rowid cat name = match Spi.schema cat name with Some s -> not s.without_rowid | None -> true (* {1 What a statement checks as it is prepared} *) let check_statement cat st ~where ~returning exprs = Resolve.check_statement (Query.resolve_env cat) st; List.iter (Query.check_expr_calls cat) (exprs @ Option.to_list where @ List.map (fun (rc : Ast.result_col) -> rc.expr) returning) let check_insert_calls cat (i : Ast.insert) = let values = match i.source with | Values [ row ] | Select { from = Values [ row ]; cols = [ { expr = Star; _ } ]; compound = []; _; } -> row | Select ({ from = Values (_ :: _ :: _); cols = [ { expr = Star; _ } ]; _ } as s) -> Query.check_select cat s; [] | Values _ | Select _ | Default_values -> [] in (* a value, written or bound, holds no call and no select: the VALUES of an INSERT a loader runs once per row are those *) List.iter (function Ast.Lit _ | Param _ -> () | e -> Query.check_expr_calls cat e) (values @ List.map (fun (rc : Ast.result_col) -> rc.expr) i.returning) let check_returning cat params ~table ~cols ~rowid = function | [] -> () | returning -> Resolve.check_returning (Query.resolve_env cat) ~table returning; Engine.check_returning cat params ~table ~cols ~rowid returning let collated cat ~frame ~table = Resolve.collate_over (Query.resolve_env cat) [ (frame, table) ] (* An assignment names a column of the row, or the rowid by a spelling no column takes on a table that has one; anything else is refused as a column reference is, the message being the resolver's. *) let check_set_column ~cols ~rowid c = if (not (List.exists (Catalog.Ident.equal c) cols)) && not (rowid && Ast.is_rowid_name c) then Catalog.Error.fail_prepare "no such column: %s" c (* {1 The constraints a row meets} A store holds keys; which resolution a violation takes is this engine's (sqlite3GenerateConstraintChecks, insert.c, through {!Conflict}). A row is checked before the store sees it: NOT NULL, then CHECK, then each uniqueness constraint in the order {!Conflict.order} gives, whose rows in the way are found by reading the store. *) (* One part of a unique key: a column, by its position, or an expression over the row, each compared under its collating sequence. *) type part = Column of int | Computed of Ast.expr type unique = { name : string; keys : string option list; parts : (part * Collation.t) list; where : Ast.expr option; on_conflict : Ast.insert_conflict; } (* What a statement checks a row of [tbl] against: its CHECKs, compiled once, the table's own key, and its unique indexes as they were made, oldest first, the PRIMARY KEY of a WITHOUT ROWID table among them as its own key. *) type constraints = { tbl : Table.t; checks : Conflict.checks; own : [ `Rowid of Ast.insert_conflict | `Keyed of unique ]; created : unique Conflict.check list; } let unique_of tbl ~name ~where ~on_conflict keys = let s = Table.schema tbl in let cols = Table.columns tbl in let sequence name declared = Collate.resolve (Option.value declared ~default:name) in let column_sequence c = Option.bind (List.find_opt (fun (col : Spi.Schema.column) -> Catalog.Ident.equal col.name c) s.columns) (fun (col : Spi.Schema.column) -> col.collation) in let part : Spi.Schema.index_key -> _ = function | Column k -> let i = Option.get (List.find_index (Catalog.Ident.equal k.column) cols) in ( Column i, sequence "BINARY" (match k.collation with | Some _ as c -> c | None -> column_sequence k.column) ) | Expression x -> ( let e = Table.expression tbl ~what:"index expression" x.sql in ( Computed e, match x.collation with | Some c -> Collate.resolve c | None -> Option.value (Collate.sequence e) ~default:Collation.default )) in { name; keys = List.map (function Spi.Schema.Column k -> Some k.column | Expression _ -> None) keys; parts = List.map part keys; where = Option.map (Table.expression tbl ~what:"WHERE") where; on_conflict; } let constraints conn tbl = let s = Table.schema tbl in let table = s.table in let auto = List.map (fun (a : Spi.Schema.autoindex) -> ( a.primary && s.without_rowid, unique_of tbl ~name:a.name ~where:None ~on_conflict:(Conflict.declared a.on_conflict) (List.map (fun k -> Spi.Schema.Column k) a.keys) )) (Spi.Schema.autoindexes s) in let made = List.filter_map (fun (i : Spi.Schema.index) -> if i.unique then Some ( false, unique_of tbl ~name:i.name ~where:i.where ~on_conflict:Unspecified i.keys ) else None) s.indexes in let own = match List.find_opt fst auto with | Some (_, pk) -> `Keyed pk | None -> `Rowid (match (Table.rowid_alias tbl, s.primary_key) with | Some _, Some pk -> Conflict.declared pk.on_conflict | _ -> Unspecified) in { tbl; checks = Conflict.checks (Engine.catalog conn) [||] ~table ~cols:(Table.columns tbl) (Table.checks tbl); own; created = List.map (fun (primary, u) -> if primary then Conflict.Own else Index u) (auto @ made); } (* [written] names the columns an UPDATE assigned, the only ones its NOT NULL asks about. *) let checked conn k = Conflict.check_row k.tbl conn k.checks let name_of (u : unique) = u.name let violation k = function | Conflict.Own -> ( match k.own with | `Keyed u -> Conflict.unique ~table:(Table.name k.tbl) ~index:u.name u.keys | `Rowid _ -> Conflict.unique_rowid ~table:(Table.name k.tbl) (Option.map (List.nth (Table.columns k.tbl)) (Table.rowid_alias k.tbl))) | Index u -> Conflict.unique ~table:(Table.name k.tbl) ~index:u.name u.keys let declared k = function | Conflict.Own -> ( match k.own with `Rowid d -> d | `Keyed u -> u.on_conflict) | Index u -> u.on_conflict (* The key of the row [vals] under [u]: [None] where a part is NULL, which no other key equals (lang_createtable.html sec.3.6), or where the row is not one a partial index holds. *) let key_of k (u : unique) ?rowid vals = let eval e = Engine.eval_in_row ~stored:Index_expression ?rowid (Table.catalog k.tbl) [||] (Table.name k.tbl) (Table.columns k.tbl) vals e in let admitted = match u.where with | None -> true | Some w -> Value_ops.tri_of (eval w) = Value_ops.T in if not admitted then None else let values = List.map (fun (p, _) -> match p with Column i -> List.nth vals i | Computed e -> eval e) u.parts in if List.mem Value.Null values then None else Some values let same_key (u : unique) a b = List.for_all2 (fun (_, seq) (x, y) -> Value_ops.compare_values_coll seq x y = 0) u.parts (List.combine a b) (* The rows of the store in the way of [row], at [key], on [u]: those whose key under [u] equals the row's, but for the one [exclude] names, the row an UPDATE rewrites. *) let in_the_way_of cat k u ?key ~exclude row = match key_of k u ?rowid:key row with | None -> [] | Some mine -> List.filter (fun (r, vals) -> (r = None || r <> exclude) && match key_of k u ?rowid:r vals with | Some theirs -> same_key u mine theirs | None -> false) (Spi.rows_rowid cat (Table.name k.tbl)) (* The rows in the way of [row] on the constraint [c]. The rowid is in the way only of a row stating its key: a key the store hands out is free. *) let in_the_way cat k c ?key ~exclude row = match (c, k.own) with | Conflict.Own, `Rowid _ -> ( match key with | None -> [] | Some n -> List.filter (fun (r, _) -> r = Some n && r <> exclude) (Spi.rows_rowid cat (Table.name k.tbl))) | Own, `Keyed u | Index u, _ -> in_the_way_of cat k u ?key ~exclude row type pass = Clear | Skip | Upsert of (int64 option * Ast.value list) (* Each uniqueness constraint settled where it stands in the order, as sqlite3GenerateConstraintChecks codes them: REPLACE deletes the rows in the way, each through [remove], and goes on, IGNORE drops the row, and a constraint an upsert targets resolves to its DO NOTHING or its DO UPDATE, at the first row in the way. A STRICT table with no CHECK has its datatypes checked before the first index is asked (sqlite3TableAffinity's OP_TypeCheck). [replaced] is told of each row a REPLACE deletes. *) let resolve_unique conn k ~override ?upsert ?key ?exclude ~remove ~replaced row = let cat = Connection.catalog conn in let typed = match Conflict.datatypes k.tbl k.checks row with | None -> ignore | Some check -> let pending = ref true in fun () -> if !pending then begin pending := false; check () end in let order = Conflict.order ~override ~own:(match k.own with `Rowid d -> `Rowid d | `Keyed _ -> `Keyed) ~on_conflict:(declared k) ~targets: (Option.map (fun (t, _) -> Conflict.targets t ~name:name_of) upsert) k.created in let rec walk = function | [] -> typed (); Clear | c :: rest -> ( (match c with Conflict.Index _ -> typed () | Own -> ()); match in_the_way cat k c ?key ~exclude row with | [] -> walk rest | first :: _ as rows -> ( let targeted = match upsert with | Some (t, action) when Conflict.targets t ~name:name_of c -> Some action | Some _ | None -> None in match Conflict.settle conn ~override ~upsert:targeted (declared k c) (fun () -> violation k c) with | Replace -> List.iter (fun row -> remove row; replaced row) rows; walk rest | Skip -> Skip | Upsert -> Upsert first)) in walk order (* A DO UPDATE is resolved as sqlite3 prepares the INSERT (sqlite3UpsertDoUpdate, called per index from insert.c): its SET and WHERE before any row is read, each assignment's value before its column, and none admits an aggregate or a window function. A table with no uniqueness constraint never codes the clause. *) let check_do_update cat ~table ~cols ~rowid ~constrained (up : Ast.upsert) = match up.action with | Update (sets, where) when constrained -> let env = Query.resolve_env cat in let expr e = Resolve.check_upsert_expr env ~table e; Query.check_expr_calls cat e in List.iter (fun (c, e) -> expr e; check_set_column ~cols ~rowid c) sets; Option.iter expr where | Update _ | Nothing -> () (* {1 The rows a statement reaches} *) (* The catalog a statement's expressions run over: the connection's, with the tables of its WITH bound. *) let statement_catalog conn ctes = let cat = Engine.catalog conn in if ctes = [] then cat else Query.materialize_ctes cat [||] ctes (* The rowid a row is in scope under: a rowid table publishes it, so [rowid] and its spellings resolve in a WHERE, a SET and a RETURNING; a WITHOUT ROWID table publishes none. *) let named ~rowid key = if rowid then key else None (* The WHERE as a test of one row, under the outer row [scope]. One holding no subquery is lowered once for every row it tests; one holding a subquery is evaluated row by row, the subquery reading the row it is bound to. *) let row_test qcat ~scope ~frame ~cols ~rowid where = match where with | Some w when Ast.holds_select w -> fun ?rowid vals -> Engine.row_matches ~scope ?rowid qcat [||] frame cols where vals | _ -> Engine.row_filter ~scope qcat [||] frame cols ~rowid where let returned qcat ~table ~cols returning rows = match returning with | [] -> [] | _ -> Engine.returning_rows qcat [||] ~table ~cols returning rows (* {1 Triggers} A write fires the triggers of its table for each row it writes ({!Trigger.Make.fire}): BEFORE ones ahead of the row's constraints, AFTER ones once the store holds it. A trigger's step is a write of its own run by {!run_body}, inside the statement that fired it. *) (* The OLD and NEW rows of the running trigger program, the outer scope of every expression a step evaluates; [[]] outside a firing. *) let scope conn = (Connection.current conn).scope (* A statement's names and calls are checked as it is prepared, outside a trigger: a step is prepared again at every firing, its names resolved against the trigger's row when the statement that fires it is prepared ({!vet}), and its calls met at its first row. *) let outside_trigger conn = scope conn = [] (* The writer of one statement: its connection, the catalog its expressions run over and the triggers of the store, their NEW and OLD collated as the columns of their tables ({!Resolve.trigger_collations}). *) type writer = { conn : Connection.t; qcat : Query.catalog; triggers : Ast.create_trigger list Lazy.t; fks : Foreign_key.Store.t; } let writer conn qcat = let triggers = lazy (List.map (Resolve.trigger_collations (Query.resolve_env qcat)) (Trigger.of_definitions (Spi.definitions (Connection.catalog conn)))) in let fks = Foreign_key.Store.v ~enforcing:(Connection.foreign_keys conn) (Connection.catalog conn) in { conn; qcat; triggers; fks } module Fire = Trigger.Make (struct type t = writer let triggers w = Lazy.force w.triggers let connection w = w.conn let catalog w = w.qcat end) (* {1 Foreign keys} A write counts what each row it writes leaves violated on the connection ({!Foreign_key.Make.check_old}, {!Foreign_key.Make.check_new}), as sqlite3FkCheck does before the store sees the row, and takes the actions of the keys referencing a row it deleted or rewrote once the store holds the change (fkey.c, sqlite3FkActions). *) module Fk = Foreign_key.Make (Foreign_key.Store) (* {1 AUTOINCREMENT} The counters a statement holds ({!Autoinc}) are rows of sqlite_sequence, an ordinary table of the store, read when the statement registers them and written back when it ends. *) let sequence_exists cat = List.exists Autoinc.is_table (Spi.tables cat) let register_counter conn name = let cat = Connection.catalog conn in match Spi.schema cat name with | Some s when s.autoincrement && sequence_exists cat -> ignore (Autoinc.register conn s.table ~read:(fun () -> Autoinc.stored s.table (Spi.rows_rowid cat Autoinc.table)) : Connection.counter) | Some _ | None -> () (* The ON CONFLICT each key of [k] declares: the INTEGER PRIMARY KEY's, a WITHOUT ROWID table's PRIMARY KEY's, and each unique index's. *) let declared_conflicts k = (match k.own with | `Rowid d -> if Option.is_none (Table.rowid_alias k.tbl) then [] else [ d ] | `Keyed u -> [ u.on_conflict ]) @ List.filter_map (function Conflict.Own -> None | Conflict.Index u -> Some u.on_conflict) k.created module Programs = Autoinc.Programs (struct type t = writer let triggers w = Lazy.force w.triggers let declared w name = let cat = Connection.catalog w.conn in if List.exists (Catalog.Ident.equal name) (Spi.tables cat) then Some (declared_conflicts (constraints w.conn (table cat name))) else None let action_writes w name ~changed = Fk.action_writes w.fks name ~changed let recursive_triggers w = Connection.recursive_triggers w.conn let register w name = register_counter w.conn name end) let register_programs conn stmt = if sequence_exists (Connection.catalog conn) then Programs.register (writer conn (Engine.catalog conn)) stmt (* A counter goes back to the row it was read from, which OP_Insert writes whether a program of the statement deleted it or not, or to a new one (insert.c, autoIncrementEnd). *) let flush_counters conn = let cat = Connection.catalog conn in Autoinc.flush conn ~write:(fun (c : Connection.counter) -> let row = [ Value.Text c.name; Value.Int c.seq ] in let held rowid = List.find_opt (fun (r, _) -> Option.equal Int64.equal r (Some rowid)) (Spi.rows_rowid cat Autoinc.table) in match c.stored with | Some (rowid, _) -> ( match held rowid with | Some old -> Spi.update cat Autoinc.table ~row:old row | None -> ignore (Spi.insert cat ~rowid:(Value.Int rowid) Autoinc.table row : int64 option)) | None -> ignore (Spi.insert cat Autoinc.table row : int64 option)) let discard_counters = Autoinc.discard let fires w ~timing ~event ~table = Trigger.matching (Lazy.force w.triggers) ~timing ~event ~table <> [] (* A statement firing [event] on [table] is refused while it is prepared if a trigger it fires names a column nothing binds: sqlite3 codes each trigger's program as it prepares the statement (sqlite3CodeRowTrigger, trigger.c), so the refusal comes before any row is written, whether or not one is. *) let vet w ~event ~table = let env = Query.resolve_env w.qcat in List.iter (fun timing -> List.iter (Resolve.check_trigger env) (Trigger.matching (Lazy.force w.triggers) ~timing ~event ~table)) [ Ast.Before; After; Instead_of ] (* The row of [table] at [key], with values [vals] when it was found, as the store holds it now: [None] once a trigger deleted it. A row with no key is its values. *) let current cat table (key, vals) = List.find_opt (fun (r, v) -> match key with Some _ -> r = key | None -> List.equal Value.equal v vals) (Spi.rows_rowid cat table) (* {1 Row programs} The programs that write one row, which a statement, a trigger step and a foreign-key action all run. *) (* The rows a REPLACE deletes, so a row the statement found before is not written once it is gone (update.c seeks each collected key again, OP_NotExists). *) let deletions () = let gone = Hashtbl.create 8 in ( (fun (key, _) -> Option.iter (fun r -> Hashtbl.replace gone r ()) key), fun key -> Option.fold ~none:false ~some:(Hashtbl.mem gone) key ) (* The row a BEFORE UPDATE trigger left: as the statement found it where no trigger wrote since, else read again, [None] where a trigger deleted it, with every column the SET does not assign reloaded from it and the generated ones computed again (update.c, the reload after the BEFORE trigger program). The assigned columns keep the values computed before the triggers ran. *) let reloaded cat tbl ~changed ~wrote ?at (key, vals) row = if not wrote then Some ((key, vals), row) else Option.map (fun (key, stored) -> let row = List.map2 (fun (c, nv) sv -> if List.exists (Catalog.Ident.equal c) changed then nv else sv) (List.combine (Table.columns tbl) row) stored in ((key, stored), Table.generate tbl ?rowid:at row)) (current cat (Table.name tbl) (key, vals)) (* The store's write of a rewritten row that met its constraints. *) let apply_rewrite cat table ~moved_to ~old row = match moved_to with | None -> Spi.update cat table ~row:old row | Some k -> Spi.delete cat table ~row:old; ignore (Spi.insert cat ~rowid:(as_key k) table row : int64 option) (* Take one row out through sqlite3's program for one deleted row (delete.c, sqlite3GenerateRowDelete): the row sought again where a trigger wrote since it was found, and kept out of the rest if it is gone; the BEFORE triggers, the row sought again if they wrote; the removal; the AFTER triggers. A REPLACE's delete fires them under REPLACE, and only where [triggers] says recursive_triggers is on, and is not counted ([count]). [false] is a row that was gone or that a BEFORE trigger kept by raising IGNORE. *) let rec delete_row ?(orconf = Ast.Unspecified) ?(triggers = true) ?(count = true) w ~run_body ~table ~cols ~wrote row = let conn = w.conn in let cat = Connection.catalog conn in let fired = triggers && (fires w ~timing:Before ~event:`Delete ~table || fires w ~timing:After ~event:`Delete ~table) in let fire timing (key, vals) = (not fired) || Fire.fire w ~run_body ~orconf ~timing ~event:`Delete ~table ~cols ~old:(Some vals) ?old_rowid:key ~new_:None () in let found = if wrote () then current cat table row else Some row in match found with | None -> false | Some row -> ( let before = Connection.total_changes conn in if not (fire Ast.Before row) then false else let row = if Connection.total_changes conn = before then Some row else current cat table row in match row with | None -> false | Some row -> Fk.check_old w.fks table conn ~changed:None ~self:row (snd row); Spi.delete cat table ~row; if count then Connection.add conn 1; fk_actions w ~run_body table ~changed:None ~old:(snd row) (); ignore (fire Ast.After row); true) (* The delete a REPLACE resolution makes of a row in the way of a row of [table]: the delete row program, where the table has DELETE triggers to fire under recursive_triggers, and a bare delete otherwise (insert.c, sqlite3GenerateConstraintChecks, regTrigCnt). *) and replacing w ~run_body ~table ~cols = let triggers = Connection.recursive_triggers w.conn && (fires w ~timing:Before ~event:`Delete ~table || fires w ~timing:After ~event:`Delete ~table) in if not (triggers || Fk.required w.fks table) then fun row -> Spi.delete (Connection.catalog w.conn) table ~row else fun row -> ignore (delete_row ~orconf:Replace ~triggers ~count:false w ~run_body ~table ~cols ~wrote:(fun () -> true) row : bool) (* The row as an UPDATE stores it (update.c): each value under its column's affinity, the generated columns computed again from the key the row leaves at, the BEFORE triggers fired, the row sought again if they wrote ({!reloaded}), then its constraints, NOT NULL asking only of the columns [changed] assigns ({!checked}, {!resolve_unique}), the write and the AFTER triggers. A key no column holds moves as sqlite3 moves it, a delete of the old key and an insert at the new one (update.c, chngKey). [None] is a row a resolution dropped, a BEFORE trigger kept or a trigger deleted. *) and store_rewrite w ~run_body k ~override ~replaced ~changed ~old:(key, vals) (row, moved_to) = let conn = w.conn in let cat = Connection.catalog conn in let tbl = k.tbl in let table = Table.name tbl and cols = Table.columns tbl in let row, alias_key = keyed tbl (Table.coerce tbl row) in let at = match moved_to with | Some k -> ( match as_key k with Value.Int r -> Some r | _ -> None) | None -> if Table.rowid_alias tbl = None then key else alias_key in let row = Table.generate tbl ?rowid:at row in let fire timing (key, vals) row = Fire.fire w ~run_body ~orconf:override ~timing ~event:(`Update changed) ~table ~cols ~old:(Some vals) ?old_rowid:key ~new_:(Some row) ?new_rowid:at () in let written = Some (changed @ List.map fst (Table.generated tbl)) in let store (old, row) = match Option.map (fun row -> ( row, resolve_unique conn k ~override ?key:at ?exclude:(fst old) ~remove:(replacing w ~run_body ~table ~cols) ~replaced row )) (checked conn k ~override ~written ?rowid:at row) with | None | Some (_, (Skip | Upsert _)) -> None | Some (row, Clear) -> let keys_changed = Some changed in Fk.check_old w.fks table conn ~changed:keys_changed ~self:old (snd old); Fk.check_new w.fks table conn ~changed:keys_changed ~self:old row; apply_rewrite cat table ~moved_to ~old row; Connection.add conn 1; fk_actions w ~run_body table ~changed:keys_changed ~old:(snd old) ~new_:row (); ignore (fire Ast.After old row); Some (at, row) in let before = Connection.total_changes conn in if fire Ast.Before (key, vals) (Trigger.before_update_row (Lazy.force w.triggers) tbl ~changed ?rowid:at row) then let wrote = Connection.total_changes conn <> before in Option.bind (reloaded cat tbl ~changed ~wrote ?at (key, vals) row) store else None (* The rows an UPDATE found, each rewritten in turn: one a REPLACE deleted is skipped, and one a trigger wrote since it was found is read again and rewritten from what it holds now ([rewrite]). *) and store_victims w ~run_body k ~override ~changed ~rewrite victims rows = let conn = w.conn in let cat = Connection.catalog conn and table = Table.name k.tbl in let replaced, gone = deletions () in let start = Connection.total_changes conn in let each (key, vals, scope) row = let found = if gone key then None else if Connection.total_changes conn = start then Some (key, vals, row) else Option.map (fun (key, vals) -> (key, vals, rewrite (key, vals, scope))) (current cat table (key, vals)) in Option.bind found (fun (key, vals, row) -> store_rewrite w ~run_body k ~override ~replaced ~changed ~old:(key, vals) row) in List.filter_map Fun.id (List.map2 each victims rows) (* The actions of the keys referencing the row [old] of [parent] a delete or a rewrite to [new_] took out, each run as sqlite3 runs one: a program of no name under ABORT (fkey.c, sqlite3FkActions), whose DELETE or UPDATE of the child rows goes through the child's own row program, its triggers and foreign keys included. RESTRICT refuses at once. *) and fk_actions w ~run_body parent ~changed ~old ?new_ () = let conn = w.conn in let cat = Connection.catalog conn in List.iter (fun (action : Fk.action) -> Trigger.program conn ~orconf:Abort (fun () -> match action with | Restrict refused -> if refused () then Connection.fail conn Abort Foreign_key | Delete (child, rows) -> let cols = Spi.columns cat child in let start = Connection.total_changes conn in let wrote () = Connection.total_changes conn <> start in List.iter (fun row -> ignore (delete_row w ~run_body ~table:child ~cols ~wrote row : bool)) (rows ()) | Update (child, set, values, rows) -> let tbl = table cat child in let cols = Table.columns tbl in let rewrite (_, vals, _) = (Foreign_key.replace ~columns:cols set values vals, None) in let victims = List.map (fun (key, vals) -> (key, vals, [])) (rows ()) in ignore (store_victims w ~run_body (constraints conn tbl) ~override:Abort ~changed:set ~rewrite victims (List.map rewrite victims) : (int64 option * Ast.value list) list))) (Fk.actions w.fks parent conn ~changed ~old ?new_ ()) (* {1 DELETE} *) let delete_with ~run_body conn (d : Ast.delete) = let cat = Connection.catalog conn in let qcat = statement_catalog conn d.ctes in let cols = Spi.columns cat d.table in let rowid = has_rowid cat d.table in let w = writer conn qcat in if outside_trigger conn then begin check_statement qcat (Ast.Delete d) ~where:d.where ~returning:d.returning []; check_returning qcat [||] ~table:d.table ~cols ~rowid d.returning end; vet w ~event:`Delete ~table:d.table; Fk.prepare w.fks conn d.table `Delete; Fmt.kstr Engine.unlowerable "this DELETE FROM %s" d.table @@ fun () -> let frame = Option.value d.alias ~default:d.table in let where = Option.map (collated qcat ~frame ~table:d.table) d.where in let keep = row_test qcat ~scope:(scope conn) ~frame ~cols ~rowid where in (* every row the WHERE keeps is found before the first is deleted, so a subquery over the table reads it whole *) let victims = List.filter (fun (key, vals) -> keep ?rowid:(named ~rowid key) vals) (Spi.rows_rowid cat d.table) in let start = Connection.total_changes conn in let wrote () = Connection.total_changes conn <> start in List.iter (fun row -> ignore (delete_row w ~run_body ~table:d.table ~cols ~wrote row : bool)) victims; returned qcat ~table:d.table ~cols d.returning (List.map (fun (key, vals) -> (named ~rowid key, vals)) victims) (* {1 UPDATE} *) let check_sets ~cols ~rowid (u : Ast.update) = List.iter (fun (c, _) -> check_set_column ~cols ~rowid c) u.sets (* The assignments with each spelling of the rowid made the column that holds the key where the table declares an INTEGER PRIMARY KEY, and the assignment that moves the key, the last one, where it declares none. *) let key_sets tbl ~cols (u : Ast.update) = let rowid_name c = Ast.is_rowid_name c && not (List.exists (Catalog.Ident.equal c) cols) in match Table.rowid_alias tbl with | Some i -> let alias = List.nth cols i in ( List.map (fun (c, e) -> if rowid_name c then (alias, e) else (c, e)) u.sets, None ) | None -> ( List.filter (fun (c, _) -> not (rowid_name c)) u.sets, List.fold_left (fun acc (c, e) -> if rowid_name c then Some e else acc) None u.sets ) (* Each row of [u]'s table its WHERE keeps, with the FROM row it was matched under, all found before the first is rewritten. Without a FROM the one scope is the statement's own. [outer] is the trigger's row a step runs under. *) let update_victims qcat cat (u : Ast.update) ~outer ~frame ~cols ~rowid where = let scopes = match u.from with | None -> [ [] ] | Some (from, joins) -> Engine.from_bindings ~scope:outer qcat [||] from joins in let test = match scopes with | [ [] ] -> let keep = row_test qcat ~scope:outer ~frame ~cols ~rowid where in fun _ ?rowid vals -> keep ?rowid vals | _ -> fun scope ?rowid vals -> Engine.row_matches ~scope:(scope @ outer) ?rowid qcat [||] frame cols where vals in List.filter_map (fun (key, vals) -> let rowid = named ~rowid key in Option.map (fun scope -> (key, vals, scope @ outer)) (List.find_opt (fun scope -> test scope ?rowid vals) scopes)) (Spi.rows_rowid cat u.table) (* The row [vals] as the assignments [sets] rewrite it, the last assignment to a column standing, and the key the assignment [moved] moves it to. *) let rewritten qcat ~frame ~cols ~rowid ~sets ~moved (key, vals, scope) = let eval = Engine.eval_in_row ~scope ?rowid:(named ~rowid key) qcat [||] frame cols vals in let values = List.rev_map (fun (c, e) -> (c, eval e)) sets in let row = List.map2 (fun c old -> match List.find_opt (fun (n, _) -> Catalog.Ident.equal n c) values with | Some (_, v) -> v | None -> old) cols vals in (row, Option.map eval moved) let update_with ~run_body conn (u : Ast.update) = let cat = Connection.catalog conn in let qcat = statement_catalog conn u.ctes in let tbl = table cat u.table in let cols = Table.columns tbl in let rowid = has_rowid cat u.table in let w = writer conn qcat in check_sets ~cols ~rowid u; if outside_trigger conn then begin check_statement qcat (Ast.Update u) ~where:u.where ~returning:u.returning (List.map snd u.sets); check_returning qcat [||] ~table:u.table ~cols ~rowid u.returning end; Fmt.kstr Engine.unlowerable "this UPDATE of %s" u.table @@ fun () -> let k = constraints conn tbl in let frame = Option.value u.alias ~default:u.table in let collate = collated qcat ~frame ~table:u.table in let sets, moved = key_sets tbl ~cols u in let changed = List.map fst sets in vet w ~event:(`Update changed) ~table:u.table; Fk.prepare w.fks conn u.table (`Update changed); let sets = List.map (fun (c, e) -> (c, collate e)) sets in let moved = Option.map collate moved in let where = Option.map collate u.where in let victims = update_victims qcat cat u ~outer:(scope conn) ~frame ~cols ~rowid where in let rewrite = rewritten qcat ~frame ~cols ~rowid ~sets ~moved in let stored = store_victims w ~run_body k ~override:u.conflict ~changed ~rewrite victims (List.map rewrite victims) in returned qcat ~table:u.table ~cols u.returning (List.map (fun (at, row) -> (named ~rowid at, row)) stored) (* {1 INSERT} *) (* The row an INSERT writes for the values [vals] of its source, the key it states and the rowid that key is. A key the column list names goes into the INTEGER PRIMARY KEY where the table declares one, the two being one column (sqlite3's ipkColumn); where it declares none the key lands in no column and reaches the store as the row's key alone. *) let inserted tbl w ~default_for vals = let row, named_key = Table.write w ~default_for vals in let row, key = match (Table.rowid_alias tbl, named_key) with | Some i, Some k -> (set_nth i k row, None) | _, key -> (row, Option.map as_key key) in let row, alias_key = keyed tbl row in let at = match (alias_key, key) with | Some r, _ | None, Some (Value.Int r) -> Some r | None, _ -> None in (Table.generate tbl ?rowid:at row, key, at) (* The rows of [i]'s source, each handed to [store]. sqlite3 runs the source as a co-routine, each row stored before the next is computed, unless the source reads the target, through a view as directly, the target has an INSERT trigger or a RETURNING keeps the rows: then it computes them all first (insert.c, sqlite3Insert: "if( pTrigger || readsTable(pParse, iDb, pTab) ) useTempTable = 1"). A VALUES tuple holds row-independent expressions, evaluated over the one empty row as the tuples of a VALUES in a FROM are, so a column name among them is refused; in a trigger's step it reads the trigger's row. *) let insert_source w tbl ~scope ~default_for (i : Ast.insert) store = let qcat = w.qcat in let first s = i.returning <> [] || fires w ~timing:Before ~event:`Insert ~table:i.table || fires w ~timing:After ~event:`Insert ~table:i.table || let view name = Option.map (fun (v : Ast.create_view) -> v.select) (View.find (Connection.catalog w.conn) name) in Query.reads_table ~view i.table s in match i.source with | Default_values -> store (List.map default_for (Table.written_columns tbl)) | Values tuples | Select { from = Ast.Values tuples; cols = [ { expr = Star; _ } ]; compound = []; _; } -> let each = match scope with | [] -> Engine.constants qcat [||] | scope -> List.map (Engine.eval_const ~scope qcat [||]) in if List.length tuples > 1 && first { (Lower.post_select []) with from = Ast.Values tuples } then List.iter store (List.map each tuples) else List.iter (fun t -> store (each t)) tuples | Select s when first s -> List.iter store (Engine.run_select ~scope qcat s [||]) | Select s -> (* every arm is resolved before the first row is stored, as sqlite3 prepares the whole source *) if scope = [] then Query.check_select qcat s; Engine.iter_select ~scope qcat s [||] ~f:store (* The upsert of [i] made ready before a row is read, as sqlite3 prepares it: its target resolved to a constraint, or refused, and its DO UPDATE checked. *) let upsert_of qcat k ~rowid (i : Ast.insert) = Option.map (fun (up : Ast.upsert) -> let tbl = k.tbl in let table = Table.name tbl and cols = Table.columns tbl in let indexes = List.filter_map (function | Conflict.Index (u : unique) -> Some { Conflict.name = u.name; keys = u.keys; where = u.where } | Own -> None) k.created in let target = Conflict.target ~table ~columns:cols ~rowid ~alias:(Table.rowid_alias tbl) ~primary_key: (match k.own with | `Keyed u -> Some (List.filter_map Fun.id u.keys) | `Rowid _ -> None) indexes up in check_do_update qcat ~table ~cols ~rowid ~constrained:(Table.rowid_alias tbl <> None || k.created <> []) up; (target, up.action)) i.upsert (* The DO UPDATE of an upsert: the row in the way [old] rewritten by the SET assignments, with [excluded] the row the INSERT was refused, where the WHERE holds; a rewrite under ABORT, which fires the UPDATE triggers under ABORT (upsert.c, sqlite3UpsertDoUpdate). *) let do_update w ~run_body k ~replaced (sets, where) ~old:(key, current) ~excluded = let table = Table.name k.tbl and cols = Table.columns k.tbl in let eval = Engine.eval_upsert ~scope:(scope w.conn) w.qcat [||] ~table ~cols ~current ~excluded in match where with | Some e when Value_ops.tri_of (eval e) <> Value_ops.T -> None | _ -> let row = List.map2 (fun c v -> match Catalog.Ident.assoc_opt c sets with | Some e -> eval e | None -> v) cols current in store_rewrite w ~run_body k ~override:Abort ~replaced ~changed:(List.map fst sets) ~old:(key, current) (row, None) (* The row a BEFORE INSERT fires for, and its NEW.rowid. A key the row names is the row's already, so it reads as itself. A key the store would hand out is not drawn until the BEFORE triggers have run: sqlite3 codes the register NEW.rowid reads as -1, and computes the generated columns from it (insert.c, sqlite3Insert). A table with no rowid has no key to read. *) let before_insert tbl ~rowid row at = match at with | Some _ -> (row, at) | None when rowid -> (Table.generate tbl ~rowid:(-1L) row, Some (-1L)) | None -> (row, None) (* The key of a row that names none, drawn where sqlite3 draws it: after the row's BEFORE triggers and before its conflicts are resolved (insert.c, sqlite3Insert: OP_NewRowid ahead of sqlite3GenerateConstraintChecks). A REPLACE that then deletes the table's largest row does not lower it, and the row is stored at it, named. An AUTOINCREMENT table draws above its counter too, which the key, drawn or named, raises. *) let drawn conn table ~rowid (key, at) = let counter = Autoinc.find conn table in let key, at = match at with | Some _ -> (key, at) | None when not rowid -> (key, at) | None -> ( match Spi.new_rowid (Connection.catalog conn) table with | Some after -> let r = match counter with | Some (c : Connection.counter) -> Autoinc.next ~after ~counter:c.seq | None -> after in (Some (Value.Int r), Some r) | None -> (key, at)) in (* the counter takes the key once it is chosen, before any constraint *) Option.iter (fun c -> Option.iter (Autoinc.step c) at) counter; (key, at) (* One row of an INSERT, as its values [row] are written with the key [key] at the rowid [at] (insert.c, sqlite3Insert): its BEFORE triggers, its checks, its keys settled, then the store's insert or the upsert's DO UPDATE, and the AFTER triggers of a row the store took. [keep] is handed each row the statement wrote. *) let insert_row w ~run_body k (i : Ast.insert) ~rowid ~upsert ~replaced ~keep (row, key, at) = let conn = w.conn in let table = Table.name k.tbl and cols = Table.columns k.tbl in let fire timing ~row ?new_rowid () = Fire.fire w ~run_body ~orconf:i.conflict ~timing ~event:`Insert ~table ~cols ~old:None ~new_:(Some row) ?new_rowid () in let before_row, before_rowid = before_insert k.tbl ~rowid row at in if fires w ~timing:Before ~event:`Insert ~table && not (fire Ast.Before ~row:before_row ?new_rowid:before_rowid ()) then () else let key, at = drawn conn i.table ~rowid (key, at) in match checked conn k ~override:i.conflict ~written:None ?rowid:at row with | None -> () | Some row -> ( let action (t, a) = (t, match a with Ast.Nothing -> `Nothing | Update _ -> `Update) in match resolve_unique conn k ~override:i.conflict ?upsert:(Option.map action upsert) ?key:at ~remove:(replacing w ~run_body ~table ~cols) ~replaced row with | Skip -> () | Upsert old -> ( match upsert with | Some (_, Update (sets, where)) -> Option.iter (fun (at, row) -> keep at row) (do_update w ~run_body k ~replaced (sets, where) ~old ~excluded:row) | Some (_, Nothing) | None -> ()) | Clear -> Fk.check_new w.fks table conn ~changed:None row; let at = Spi.insert (Connection.catalog conn) ?rowid:key i.table row in Option.iter (Connection.set_last_insert_rowid conn) at; Connection.add conn 1; (* the row as stored, its INTEGER PRIMARY KEY the key the store drew *) let row = match (Table.rowid_alias k.tbl, at) with | Some i, Some r -> set_nth i (Value.Int r) row | _ -> row in if fires w ~timing:After ~event:`Insert ~table then ignore (fire Ast.After ~row ?new_rowid:at () : bool); keep at row) let insert_with ~run_body conn (i : Ast.insert) = let cat = Connection.catalog conn in let tbl = table cat i.table in let qcat = Engine.catalog conn in let rowid = has_rowid cat i.table in let w = writer conn qcat in if outside_trigger conn then begin check_insert_calls qcat i; check_returning qcat [||] ~table:i.table ~cols:(Table.columns tbl) ~rowid i.returning end; (* a SELECT source's width is checked before a row is read, as sqlite3 checks it when it prepares the statement; a VALUES tuple's as it is written *) (match i.source with | Select { from = Ast.Values _; _ } | Values _ | Default_values -> () | Select s -> Table.check_arity tbl ~named:i.columns (List.length (Resolve.select_columns (Query.resolve_env qcat) s))); vet w ~event:`Insert ~table:i.table; Fk.prepare w.fks conn i.table `Insert; let k = constraints conn tbl in let upsert = upsert_of qcat k ~rowid i in let wr = Table.writer tbl ~has_rowid:rowid ~named:i.columns in let default_for = Table.default tbl qcat [||] in let replaced, _ = deletions () in let stored = ref [] in let keep at row = if i.returning <> [] then stored := (named ~rowid at, row) :: !stored in insert_source w tbl ~scope:(scope conn) ~default_for i (fun vals -> insert_row w ~run_body k i ~rowid ~upsert ~replaced ~keep (inserted tbl wr ~default_for vals)); returned qcat ~table:i.table ~cols:(Table.columns tbl) i.returning (List.rev !stored) (* {1 Trigger steps} *) (* Run one step of a trigger program, in the frame already on the connection. A step is part of the statement that fired it, not a statement of its own: it opens no undo, and the firing statement's undo covers what it writes. Its conflict policy is the frame's where the firing statement named one, else its own OR clause (trigger.c, codeTriggerProgram), and an INSERT, UPDATE or DELETE publishes its count when it ends (OP_ResetCount). A body SELECT runs and its rows are discarded, since a [RAISE()] in it is what stops the firing statement. *) let rec run_body w (stmt : Ast.stmt) = let conn = w.conn in let frame = Connection.current conn in let step f = ignore (f () : Ast.value list list); Connection.publish conn in match stmt with | Insert i -> step (fun () -> insert_with ~run_body conn { i with conflict = Trigger.step_policy frame i.conflict }) | Update u -> step (fun () -> update_with ~run_body conn { u with conflict = Trigger.step_policy frame u.conflict }) | Delete d -> step (fun () -> delete_with ~run_body conn d) | Select s -> ignore (Engine.run_select ~scope:frame.scope (Engine.catalog conn) s [||] : Ast.value list list) | _ -> Fmt.invalid_arg "a trigger body holds only INSERT, UPDATE, DELETE and SELECT" let insert conn i = insert_with ~run_body conn i let update conn u = update_with ~run_body conn u let delete conn d = delete_with ~run_body conn d (* {1 Foreign keys of the schema} *) let keys conn = Foreign_key.Store.v ~enforcing:(Connection.foreign_keys conn) (Connection.catalog conn) let drop_deletes conn table = Fk.drop_deletes (keys conn) conn table (* The DELETE sqlite3FkDropTable runs: every row of [table] through the delete row program with no trigger fired (pParse->disableTriggers), in the table's order. *) let delete_for_drop conn table = if Fk.drop_delete_runs (keys conn) conn table then begin let w = writer conn (Engine.catalog conn) in let cat = Connection.catalog conn in let cols = Spi.columns cat table in List.iter (fun row -> ignore (delete_row ~triggers:false w ~run_body ~table ~cols ~wrote:(fun () -> true) row : bool)) (Spi.rows_rowid cat table) end let foreign_key_violations conn names = Fk.violations (keys conn) names