(*--------------------------------------------------------------------------- Copyright (c) 2026 Thomas Gazagnaire. All rights reserved. SPDX-License-Identifier: ISC ---------------------------------------------------------------------------*) open Model open Handle module Engine = Sql.Private.Engine module Resolve = Sql.Private.Resolve module Query = Sql.Private.Query module Ident = Catalog.Ident module Table = Sql.Private.Table module Conflict = Sql.Private.Conflict let ident_equal = Ident.equal (* How a write names the row it acts on: by rowid on a rowid table, by the whole row on a WITHOUT ROWID one. Re-exported from {!Store} so the constructors are in scope for the rewrite tail below. *) type row_addr = Store.addr = Rowid of int64 | Row of Sql.Ast.value list (* Everything the storage primitives ask of this handle: {!Store.S}. The tables, the remembered maximum and the durable AUTOINCREMENT counter beside it, the kv cache a write makes stale, and where a violation records its undo scope. What maintaining an index reads of the schema rides on the schema, so it is not asked here. *) module Store_reader = struct type t = Handle.t let table = Cat.gtable let counter = Autoinc.max_rowid let drop_counter t name = Ident.Tbl.remove t.insert_rowids name let autoinc_rowid = Autoinc.next_rowid let note_inserted = Autoinc.note_inserted (* The key caches hear of each row a write moves, so a lookup by key stays an O(1) hash hit through a write of any door rather than a scan re-derived after one. *) let row_stored = Kv_store.row_stored let row_dropped = Kv_store.row_dropped let rows_undecoded = Kv_store.rows_undecoded let wrote t = t.writes <- t.writes + 1 let connection = Handle.connection end (* The storage door every write below goes through, and the one the key-value and [Raw] facades reach a single row through. Applied here rather than beside {!Store} itself, because this is where the handle those primitives act on is already concrete. *) module Rows = Store.Make (Store_reader) (* The rows an INSERT ... SELECT draws from its source query, each handed over as the query produces it. The source is run by the SELECT executor, which is built above this layer, so the runner arrives through {!install} once it exists. Nothing can reach a write before then: every door onto a handle is the facade's, and the facade installs it as it opens. *) let select_runner : (Handle.t -> Query.catalog -> Sql.Ast.value array -> Query.binding list -> Sql.Ast.select -> f:(Sql.Ast.value list -> unit) -> unit) ref = ref (fun _ _ _ _ _ ~f:_ -> failwith "INSERT ... SELECT: no select runner installed") let install ~insert_select_iter = select_runner := insert_select_iter let select_source t cat params scope select ~f = !select_runner t cat params scope select ~f (* A table's column names, in declared order: what a row is aligned to, what an OLD/NEW scope binds by, and what an expression over one row resolves against. Read off the schema of the table the statement has already resolved, so a statement of many rows names its table once. *) let columns (gt : generic_table) = Lazy.force gt.schema.names (* The table a write acts on. Tables and views share one namespace, so a name a view holds is taken: answering "no such table" would say it is free, which CREATE TABLE then refuses. sqlite3 refuses while preparing. No INSTEAD OF trigger stands behind a view here, so every write onto one is refused. *) let target_table t name = match Handle.name_holder t name with | Some View_name -> Catalog.Error.fail_prepare "cannot modify %s because it is a view" name | Some (Table_name | Index_name) | None -> Cat.gtable t name (* {!Sql.Private.Write.check_returning} over the row of [gt]. *) let check_returning cat params ~table gt returning = Sql.Private.Write.check_returning cat params ~table ~cols:(columns gt) ~rowid:(rowid_stored gt) returning (* {!Sql.Private.Write.check_statement}, outside a trigger: a trigger's step is prepared again at every firing ({!program}), its names were resolved, with the trigger's row, when the trigger was created, and its calls are met at its first row. *) let check_statement t cat st ~where ~returning exprs = if Handle.scope t = [] then Sql.Private.Write.check_statement cat st ~where ~returning exprs (* {!Sql.Private.Write.check_insert_calls}, outside a trigger, as above. *) let check_insert_calls t cat (i : Sql.Ast.insert) = if Handle.scope t = [] then Sql.Private.Write.check_insert_calls cat i (* The key a row of [gt] is in scope under while a statement's expressions run over it. A rowid table publishes it, so [rowid] and its aliases resolve in a WHERE, a SET expression and RETURNING as in a scan. A WITHOUT ROWID table publishes none, so the spelling reaches nothing and the resolver refuses the statement. The walk still needs a key for every row it visits; this decides only whether the key is a name the statement may spell. *) let named_rowid gt rowid = if rowid_stored gt then Some rowid else None (* A program over the rows a statement reaches, lowered as the statement is prepared ({!Engine.row_values}), except in a trigger's step: sqlite3 codes a trigger's program once for the statement that fires it, and the step here is prepared again at every firing, so its program is lowered at the first row it reaches, and a firing that reaches none lowers nothing. *) let program t lower = if Handle.scope t = [] then lower () else let p = lazy (lower ()) in fun ?rowid values -> (Lazy.force p) ?rowid values (* Parsed triggers, their NEW and OLD collated as the columns of their tables ({!Resolve.trigger_collations}), memoised against the physical [extra_master] and [all_tables] lists: a schema change replaces one of them and re-parses, while every row of a statement reuses the same parse. Each comes with the refusal its names earn ({!Resolve.check_trigger}), worked out once, the first time a statement that fires it asks. *) let trigger_entries t = match t.trigger_cache with | Some (em, at, tgs, refusals) when em == t.extra_master && at == t.all_tables -> (tgs, refusals) | _ -> let env = Query.resolve_env (Cat.v t) in let tgs = List.map (Resolve.trigger_collations env) (List.filter_map (fun (rm : raw_master_entry) -> match (rm.type_, rm.sql) with | "trigger", Sql.Ast.Text sql -> Sql.Private.Trigger.of_sql sql | _ -> None) t.extra_master) in let refusal tg = lazy (match Resolve.check_trigger env tg with | () -> None | exception Catalog.Error (Prepare msg) -> Some msg) in let refusals = List.map (fun tg -> (tg, refusal tg)) tgs in t.trigger_cache <- Some (t.extra_master, t.all_tables, tgs, refusals); (tgs, refusals) let triggers t = fst (trigger_entries t) (* 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_triggers t ~event ~table = let tgs, refusals = trigger_entries t in List.iter (fun timing -> List.iter (fun tg -> match Lazy.force (List.assq tg refusals) with | None -> () | Some msg -> Catalog.Error.fail_prepare "%s" msg) (Sql.Private.Trigger.matching tgs ~timing ~event ~table)) [ Sql.Ast.Before; After; Instead_of ] (* Everything firing a trigger is allowed to ask of this handle: {!Sql.Private.Trigger.S}. The programs, the connection whose stack they run on, and the catalog a WHEN guard is evaluated against. The body runner is handed to each firing rather than read off the handle. *) module Trigger_reader = struct type t = Handle.t let triggers = triggers let connection = Handle.connection let catalog = Cat.v end module Trig = Sql.Private.Trigger.Make (Trigger_reader) (* Everything foreign-key enforcement is allowed to ask of this handle, and nothing else -- {!Sql.Private.Foreign_key.S}. What a walk needs is the tables, the rows of one and a seek into the parent's key; the writes an action makes are the row programs below. *) module Fk_reader = struct type t = Handle.t let enforcing t = Sql.Private.Connection.foreign_keys (Handle.connection t) let tables t = List.map (fun gt -> Row.table gt.schema) t.all_tables let named = Handle.table let table t name = Option.map (fun gt -> Row.table gt.schema) (named t name) (* Each unique index of every row over columns alone, the PRIMARY KEY of a WITHOUT ROWID table among them, each column under the sequence the index orders it by. *) let unique_keys t name = match named t name with | None -> [] | Some gt -> let names = Lazy.force gt.schema.names in let column cid (order : Sql.Order.t) = Option.map (fun c -> (c, order.collation)) (List.nth_opt names cid) in let rec all acc = function | [] -> Some (List.rev acc) | Some k :: rest -> all (k :: acc) rest | None :: _ -> None in let index (idx : index) = if (not idx.unique) || idx.where <> None then None else all [] (List.map2 (fun key order -> match key with | Column cid -> column cid order | Expression _ -> None) idx.keys idx.orders) in let primary_key = match gt.store with | Rowid_rows _ | Pk_index_rows { key = None; _ } -> None | Pk_index_rows { key = Some (key, len); _ } -> all [] (List.filteri (fun i _ -> i < len) (List.map (fun (k : index_column) -> column k.cid k.order) key)) in Option.to_list primary_key @ List.filter_map index gt.indexes let fold_rows t name ~init ~f = Cat.fold_table t name ~init ~f:(fun r row acc -> f (Some r) row acc) (* The same seek an equality-keyed UPDATE or DELETE finds its rows through: an equality on the rowid is a single fetch, and any index covering the columns is looked up. The rowids it carries are of no use here -- a parent lookup asks whether the key is there, not where -- so they are dropped. *) let seek_key t name eqs = let gt = Cat.gtable t name in let key (c, v) = (c, Sql.Value_ops.compared (Seek.column_affinity gt c) v) in Option.map (fun (_, rows) -> List.map snd rows) (Cat.index_scan_rowid t name (List.map key eqs)) (* The rows of [name] an index whose key leads with exactly the columns of [eqs] holds under their values, with their rowids: the lookup sqlite3's scan of a child table plans (fkey.c, fkScanChildren). The index compares as it orders, which equates more values than a key match does (an integer and the real equal to it, two spellings under NOCASE), so the rows are a superset the caller filters. Only an index ordering each column under its declared sequence serves: one under another sequence holds the rows the column's comparison matches apart. A partial index does not hold every row, and a table with no rowid is read whole. *) let seek_rows t name eqs = let gt = Cat.gtable t name in match gt.store with | Pk_index_rows _ -> None | Rowid_rows _ -> let names = Lazy.force gt.schema.names in let n = List.length eqs in let leads (idx : index) = Fast_path.seekable_index gt.schema.columns ~keys:n idx && List.for_all2 (fun key (c, _) -> match key with | Column pos -> ident_equal (List.nth names pos) c | Expression _ -> false) (Index.key_prefix n idx.keys) eqs in Option.map (fun idx -> List.filter_map (function | Rowid r -> Option.map (fun v -> (Some r, v)) (Rows.read t name r) | Row _ -> None) (Index.lookup idx (Array.of_list (List.map snd eqs)))) (List.find_opt leads gt.indexes) end module Fk = Sql.Private.Foreign_key.Make (Fk_reader) let foreign_key_violations = Fk.violations (* Whether [c] names the rowid of [gt]: a rowid spelling or its INTEGER PRIMARY KEY alias. *) let rowid_key gt c = Sql.Ast.is_rowid_name c || Option.fold ~none:false ~some:(fun i -> ident_equal c (List.nth (columns gt) i)) (Decl.rowid_alias gt.schema) (* [where] as the seeks below read it within a trigger's firing: a rowid equality against a qualified reference to the enclosing row, [rowid = NEW.id], holds the integer the reference has in this firing, as sqlite3 codes NEW.id as a register of the trigger program and seeks OP_SeekRowid. Only the top-level AND conjuncts are read, as {!Fast_path.equalities} reads them; a reference qualified by the statement's own [frame] is the target's column and stays; any other value stays a reference, since an equality against a column of another affinity is not a seek of its value. The rows found are filtered by [where] itself. *) let seek_where t gt ~frame where = match Handle.scope t with | [] -> where | scope -> (* A NEW.x a comparison takes its sequence from carries it as a [COLLATE] ({!Resolve.trigger_collations}); a sequence orders text, and an integer against the rowid compares the same under any, so the wrapper is seen through. *) let rec bound (e : Sql.Ast.expr) = match e with | Col (Some q, c) when not (ident_equal q frame) -> ( match Option.bind (Ident.assoc_opt q scope) (Ident.assoc_opt c) with | Some (Sql.Ast.Int _ as v) -> Sql.Ast.Lit v | _ -> e) | Collate (r, _) -> ( match bound r with Sql.Ast.Lit _ as v -> v | _ -> e) | e -> e in let rec go (e : Sql.Ast.expr) = match e with | Binary (And, a, b) -> Sql.Ast.Binary (And, go a, go b) | Binary (Eq, (Col (_, c) as k), v) when rowid_key gt c -> Binary (Eq, k, bound v) | Binary (Eq, v, (Col (_, c) as k)) when rowid_key gt c -> Binary (Eq, bound v, k) | e -> e in Option.map go where (* Whether [seek], a WHERE as {!seek_where} reads it within a trigger's firing, pins the target's rowid to an integer, [rowid = NEW.id]. sqlite3 codes that as an OP_SeekRowid of the trigger program, which it compiles once for the statement that fires it; {!indexed_victims} reads the row as directly, where the select {!selected_rows} runs would be prepared, planned and compiled again at every firing. *) let seeks_rowid t gt seek = Handle.scope t <> [] && match seek with | None -> false | Some w -> List.exists (function c, Sql.Ast.Int _ -> rowid_key gt c | _ -> false) (Fast_path.equalities gt.schema.columns [||] w) (* Whether no trigger on [table] fires for [event]. *) let fires_none t ~table event = List.for_all (fun timing -> Sql.Private.Trigger.matching (triggers t) ~timing ~event ~table = []) [ Sql.Ast.Before; After ] (* sqlite3 clears a table whole for a DELETE with no WHERE where nothing has to see each row go: no DELETE trigger and no foreign key to count (delete.c, sqlite3DeleteFrom, pWhere == 0 and not bComplex). A one-pass DELETE asks the same of its table. *) let clears t table = fires_none t ~table `Delete && not (Fk.required t table) let drop_deletes t table = Fk.drop_deletes t (Handle.connection t) table let drop_delete_runs t table = Fk.drop_delete_runs t (Handle.connection t) table (* The cost sqlite3's planner gives a seek of [n] leading key columns of an index on a table of default statistics (where.c, whereLoopAddBtreeIndex): [nOut] is the rows it selects, one for a unique key bound whole and else sqlite3DefaultRowEst's estimate, and [rRun] the descent and the entries it steps over, with a lookup of the row for each where the index does not cover the read. *) let fk_seek_cost ~unique ~covering ~idx_width ~table_width n = let n_out = if unique then 0 else match List.nth_opt [ 33; 32; 30; 28; 26 ] (n - 1) with | Some e -> e | None -> 23 in (* estLog of the default 1048576 rows *) let log_size = 43 in let run = Log_est.add log_size (n_out + 1 + (15 * idx_width / table_width)) in ((if covering then run else Log_est.add run (n_out + 16)), n_out) (* The child key columns of [fk], over [cgt], a seek may bind, each with the sequence it must be ordered under: those the comparison of the parent's value with the child's may use (sqlite3IndexAffinityOk: the child's affinity is numeric or the parent's is not), under the parent's collating sequence, or the child's against a rowid. *) let fk_usable ~cgt ~pgt (fk : Sql.Private.Foreign_key.key) pcols name (order : Sql.Order.t) = let side gt c = Sql.Private.Foreign_key.side (Row.table gt.schema) c in match List.find_opt (fun (c, _) -> ident_equal c name) (List.combine fk.columns pcols) with | None -> false | Some (c, p) -> let cs = side cgt c and ps = side pgt p in (cs.numeric || not ps.numeric) && Sql.Collation.equal order.collation (if ps.rowid then cs.coll else ps.coll) (* The leading key columns of [keys], as [(cid, order)], that [usable] lets a seek bind, each once. *) let fk_bound (columns : column array) ~usable keys = let rec prefix acc = function | (cid, order) :: rest when cid >= 0 && cid < Array.length columns && usable columns.(cid).name order && not (List.mem cid acc) -> prefix (cid :: acc) rest | _ -> List.rev acc in prefix [] keys let fk_terms (columns : column array) bound = "(" ^ String.concat " AND " (List.map (fun cid -> columns.(cid).name ^ "=?") bound) ^ ")" (* The seek of the index [idx] of [cgt], with its cost, where it binds a leading column. *) let fk_index_seek cgt ~usable ~read (idx : index) = let columns = Array.of_list cgt.schema.columns in if idx.where <> None then None else let keys = List.map2 (fun k o -> match k with Column cid -> (cid, o) | Expression _ -> (-1, o)) idx.keys idx.orders in match fk_bound columns ~usable keys with | [] -> None | bound -> let n = List.length bound in let covering = Fast_path.covers cgt idx ~read in let cost = fk_seek_cost ~unique:(idx.unique && n = List.length idx.keys) ~covering ~idx_width:(Where_loop.index_width cgt idx) ~table_width:(Where_loop.table_width cgt) n in Some ( cost, Fmt.str "%sINDEX %s %s" (if covering then "COVERING " else "") idx.name (fk_terms columns bound) ) (* The seek of a WITHOUT ROWID table's PRIMARY KEY, where it binds a leading column. *) let fk_primary_key_seek cgt ~usable = match cgt.store with | Rowid_rows _ | Pk_index_rows { key = None; _ } -> None | Pk_index_rows { key = Some (key, len); _ } -> ( let columns = Array.of_list cgt.schema.columns in let key = List.filteri (fun i _ -> i < len) key in match fk_bound columns ~usable (List.map (fun (k : index_column) -> (k.cid, k.order)) key) with | [] -> None | bound -> let n = List.length bound in let table_width = Where_loop.table_width cgt in let cost = fk_seek_cost ~unique:(n = len) ~covering:true ~idx_width:table_width ~table_width n in Some (cost, "PRIMARY KEY " ^ fk_terms columns bound)) (* Of two seeks, the cheaper, the earlier of equal cost. *) let fk_cheaper best c = match (best, c) with | None, c -> c | Some ((run, out), _), Some (((run', out'), _) as c) when run' < run || (run' = run && out' < out) -> Some c | best, _ -> best (* The [EXPLAIN QUERY PLAN] line of the loop over [child] for the rows whose columns [fk] references a key of the parent (fkey.c, fkScanChildren): a rowid seek where a child column is the INTEGER PRIMARY KEY, else the cheapest seek of an index, or of a WITHOUT ROWID table's PRIMARY KEY, whose leading columns are child columns the comparison may use ({!fk_usable}), and a scan where none serves. Of two seeks of equal cost the newer index is taken, as sqlite3's list of a table's indexes holds them newest first. *) let fk_child_loop t child (fk : Sql.Private.Foreign_key.key) pcols = let cgt = Cat.gtable t child and pgt = Cat.gtable t fk.parent in let usable = fk_usable ~cgt ~pgt fk pcols in let rowid c = (Sql.Private.Foreign_key.side (Row.table cgt.schema) c).rowid in if List.exists rowid fk.columns then Fmt.str "SEARCH %s USING INTEGER PRIMARY KEY (rowid=?)" child else let names = Lazy.force cgt.schema.names in let read = List.filter_map (fun c -> Decl.column_index names c) fk.columns in match List.fold_left fk_cheaper None (List.map (fk_index_seek cgt ~usable ~read) (List.rev cgt.indexes) @ [ fk_primary_key_seek cgt ~usable ]) with | Some (_, using) -> Fmt.str "SEARCH %s USING %s" child using | None -> "SCAN " ^ child (* The [EXPLAIN QUERY PLAN] line of each loop over a child table that the foreign keys referencing [table] run when a row of it is deleted ([changed] is [None]) or an [UPDATE] assigns [changed] (fkey.c, sqlite3FkCheck's loops, in the order of sqlite3FkReferences): one per key, the newest first, and for an [UPDATE] two passes of the keys whose parent columns it assigns. It is [[]] without foreign keys enforced, and refuses a key whose parent columns are no key of [table]. *) let foreign_key_plan t table ~changed = if not (Fk_reader.enforcing t) then [] else let pass = List.concat_map (fun gt -> let child = gt.schema.tbl_name in List.filter_map (fun (fk : Sql.Private.Foreign_key.key) -> if ident_equal fk.parent table && Fk.modified changed (Fk.named_columns t fk) then Some (fk_child_loop t child fk (Fk.parent_columns t ~child fk)) else None) (Sql.Private.Foreign_key.declared (Row.table gt.schema))) (List.rev t.all_tables) in match changed with None -> pass | Some _ -> pass @ pass