(*--------------------------------------------------------------------------- Copyright (c) 2026 Thomas Gazagnaire. All rights reserved. SPDX-License-Identifier: ISC ---------------------------------------------------------------------------*) open Model open Handle include Write_model (* Whether an UPDATE assigning [changed] carries the row to another key: it assigns the rowid by a name no column declares ([named]), or the INTEGER PRIMARY KEY (update.c, chngRowid). *) let moves_key gt ~changed ~named = named || Option.fold ~none:false ~some:(fun i -> List.exists (ident_equal (List.nth (columns gt) i)) changed) (Decl.rowid_alias gt.schema) (* Both statements find their rows by walking the whole table and testing the predicate, which is quadratic with a primary key in the WHERE. Reuse the SELECT path: pull the top-level [col = const] conjuncts and ask the planner for the rows matching them. What comes back is a superset, and both callers re-apply the whole predicate, so narrowing what they look at changes nothing. The rows come back in descending rowid order and callers reverse them. *) let indexed_victims t table params where = match where with | None -> None | Some e -> ( match Option.bind (Cat.plain_rowid_gtable t table) (fun gt -> match Fast_path.equalities gt.schema.columns params e with | [] -> None | eqs -> Cat.index_scan_rowid t gt.schema.tbl_name eqs) with | None -> None | Some (_, rows) -> (* [plain_rowid_gtable] already ruled out the rowid-less tables, so every row here carries one; a row that somehow does not cannot be addressed for rewriting and is left to the scan. *) let keyed = List.filter_map (fun (rid, values) -> Option.map (fun rid -> (rid, values)) rid) rows in if List.length keyed <> List.length rows then None else Some (List.sort (fun (a, _) (b, _) -> compare b a) keyed)) (* The rows of [table] folded by [f], walked as a full scan: counted in {!Handle.t.scanned} as sqlite3 counts SQLITE_STMTSTATUS_FULLSCAN_STEP, one fewer than the rows walked, as a query's scan is. *) let walk_table t table ~init ~f = let walked = ref 0 in let acc = Cat.fold_table t table ~init ~f:(fun rowid values acc -> incr walked; f rowid values acc) in Catalog.Cursor.add t.scanned (max 0 (!walked - 1)); acc (* A select that is just a bare [VALUES] list carries its literal tuples directly, so [INSERT ... VALUES] skips the query executor. *) let values_of_select : Sql.Ast.select -> Sql.Ast.expr list list option = function | { ctes = []; distinct = false; cols = [ { expr = Star; alias = None } ]; from = Values rows; joins = []; where = None; group_by = []; having = None; compound = []; order_by = []; limit = None; offset = None; } -> Some rows | _ -> None (* The row an UPDATE rewrites, as its BEFORE triggers left it: sought again at its address, [None] where a trigger removed it, and every column the SET does not assign reloaded from it, 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, and the key stays the one the rewrite moves the row to. *) let reloaded t ~gt ~changed ?rowid addr new_values = Option.map (fun stored -> let row = List.map2 (fun (c, nv) sv -> if List.exists (ident_equal c) changed then nv else sv) (List.combine (columns gt) new_values) stored in Table.generate (Row.table gt.schema) ?rowid row) (Rows.current t gt addr) (* A STRICT table's datatypes, where no CHECK constraint has had them checked first: sqlite3TableAffinity's OP_TypeCheck, run before the first index is asked ({!Rows.resolve_unique}). *) let typed gt ~checks row = Conflict.datatypes (Row.table gt.schema) checks row (* NOT NULL, then CHECK ({!Conflict.check_row}). [written] names the columns an UPDATE assigned, the only ones its NOT NULL asks about. *) let checked t ~gt ~checks ~conflict ~written ?rowid row = Conflict.check_row (Row.table gt.schema) (Handle.connection t) checks ~override:conflict ~written ?rowid row (* The key a rewritten row leaves at: what the statement assigned to it, through the INTEGER PRIMARY KEY column where the table declares one and through [set_rowid] where it does not, and the key the row already sits at where the statement assigned neither. Every constraint is asked about that key, since it is the one the row will be found under. *) let rewritten_rowid schema ?set_rowid addr new_values = match addr with | Row _ -> None | Rowid r -> ( match match Decl.rowid_alias schema with | Some i -> List.nth_opt new_values i | None -> set_rowid with | None -> Some r | Some v -> ( match Rowid.of_value v with | Some n -> Some n | None -> Catalog.Error.fail Mismatch)) (* The key a rewrite leaves the row at, as the uniqueness pass asks about it. Only a key the rewrite moves the row to can be another row's already: one it stays at is not probed for, as sqlite3 checks the rowid only where it changes (update.c, chngKey; insert.c, the OP_Eq over the old rowid). *) let rewritten_key addr rowid = { Store.rowid; written = (match addr with Rowid r -> r <> rowid | Row _ -> true); } (* The rows an action reads, each named by the rowid this handle's walk of its table gives it ({!Fk_reader.fold_rows}). *) let collected rows = List.filter_map (fun (rowid, values) -> Option.map (fun r -> (r, values, ())) rowid) rows (* The rows a statement collected, each acted on by [f] at its turn, which answers [Some] for a row it wrote. Once anything but the statement's own row writes has moved a row -- a trigger, a foreign-key action, a REPLACE -- each row still to come is read again first and skipped if it is gone (update.c and delete.c seek each collected key, OP_NotExists). *) let each_collected t gt ~f rows = let stale = ref false in List.filter_map (fun (rowid, values, x) -> match if !stale then Rows.current t gt (Rows.addr gt rowid values) else Some values with | None -> None | Some values -> let writes = t.writes in let r = f (rowid, values, x) in if t.writes <> writes + if Option.is_some r then 1 else 0 then stale := true; r) rows (* What a rewrite of [old] to [new_] counts into the foreign-key counters: sqlite3FkCheck on the old row, then on the new one (update.c), where the statement counts them ([keys]). *) let fk_rewrite t table ~keys ~changed ~old_rowid ~old new_ = if keys then begin let self = (old_rowid, old) and conn = Handle.connection t in Fk.check_old t table conn ~changed ~self old; Fk.check_new t table conn ~changed ~self new_ end (* {!Sql.Private.Trigger.before_update_row} of a row of [gt]. *) let before_update_row t gt ~changed ?rowid row = Sql.Private.Trigger.before_update_row (triggers t) (Row.table gt.schema) ~changed ?rowid row (* Whether [expr] reads a column [assigned] names, or the rowid where [key_moved] (update.c, sqlite3ExprReferencesUpdatedColumn). *) let reads_assigned ~assigned ~key_moved expr = let hit = ref false in Sql.Private.Resolve.walk_expr ~table:(fun () _ -> ()) ~col:(fun () _ name -> if List.exists (ident_equal name) assigned || (key_moved && Sql.Ast.is_rowid_name name) then hit := true) ~nest:(fun () _ -> ()) ~cte:(fun () _ -> Some ()) () expr; !hit (* Which indexes an UPDATE of a row of [gt] assigning [changed] rewrites, and whether it holds the row's REAL columns as reals ({!Row.real_in_record}), both decided from the statement as sqlite3 decides them. An index is rewritten when the key moves, or when its key or its WHERE reads an assigned column (update.c:580, aRegIdx), a generated column counting as assigned when its expression reads one (update.c, aXRef). The values are held as reals once sqlite3GenerateConstraintChecks prepares an index entry or evaluates a CHECK, which it does for a CHECK that reads an assigned column (insert.c:2077, 2426). Every index is rewritten where the foreign keys ask for it ({!Fk.rewrites_indexes}). A WITHOUT ROWID table's own b-tree is always rewritten, which the store answers for. *) let update_storage t gt ~checks ~changed ~key_moved = let cols = columns gt in let rec close assigned = match List.filter_map (fun (name, e) -> if (not (List.exists (ident_equal name) assigned)) && reads_assigned ~assigned ~key_moved e then Some name else None) (Table.generated (Row.table gt.schema)) with | [] -> assigned | more -> close (more @ assigned) in let assigned = close changed in let reads = reads_assigned ~assigned ~key_moved in let every = Fk.rewrites_indexes t gt.schema.tbl_name ~changed ~key_moved in let touched (idx : index) = key_moved || every || Option.fold ~none:false ~some:reads idx.where || List.exists (function | Column cid -> List.exists (ident_equal (List.nth cols cid)) assigned | Expression e -> reads e) idx.keys in let reals = List.exists touched gt.indexes || List.exists (fun (_, e) -> reads e) checks.Conflict.exprs in (reals, touched) (* What a statement's rewrites of [gt]'s rows assigning [changed] share, decided once for it as sqlite3 codes them once (update.c): whether the row is held as reals and which indexes a rewrite touches ({!update_storage}), and whether the key moves: where the statement assigns the rowid, through the INTEGER PRIMARY KEY or by a name no column declares ([named]; update.c, chngRowid); and whether its foreign keys are counted and their actions taken, which sqlite3 codes only for a table some key is on (sqlite3FkRequired). *) type rewrite_plan = { reals : bool; touched : index -> bool; key_moved : bool; keys : bool; } let rewrite_plan t gt ~checks ~changed ~named = let key_moved = moves_key gt ~changed ~named in let reals, touched = update_storage t gt ~checks ~changed ~key_moved in let touched_ones = List.filter_map (fun (idx : index) -> if touched idx then Some idx.name else None) gt.indexes in { reals; touched = (fun (idx : index) -> List.exists (String.equal idx.name) touched_ones); key_moved; keys = Fk.required t gt.schema.tbl_name; } (* The rowid a rewrite of the row at [addr] to [new_values] leaves it at, the key that rowid gives, and the values as stored. The generated columns are computed once that rowid is known, since one may read the INTEGER PRIMARY KEY (update.c, after the new rowid is computed). *) let rewritten schema ?set_rowid addr new_values = let new_values = Table.coerce (Row.table schema) new_values in let rowid = rewritten_rowid schema ?set_rowid addr new_values in let key = Option.map (rewritten_key addr) rowid in (rowid, key, Table.generate (Row.table schema) ?rowid new_values) (* Rewrite the row at [addr] to [new_values] through sqlite3's program for one updated row (update.c): every value stored by its column's affinity and the generated columns computed from the rest, the BEFORE triggers fired, the row sought and reloaded if they moved anything, then NOT NULL, CHECK, the uniqueness constraints and the foreign keys, the write, the foreign-key actions and the AFTER triggers. [changed] names the columns the statement assigned, which NOT NULL and an UPDATE trigger answer for. An UPDATE and an UPSERT's DO UPDATE half are both row rewrites, so both come through here. [conflict] is the statement's [UPDATE OR ]; [None] is a rewrite a resolution dropped, or a row a BEFORE trigger removed. [held] (default [false]) says [old] is the row stored at [addr], as {!Rows.read} answers it: where nothing has written since, the store takes it rather than read the row again. *) let rec store_update t ~run_trigger_body ~gt ~checks ~conflict ~changed ~plan ?(held = false) ?at ?set_rowid addr ~old new_values = let schema = gt.schema in let table = schema.tbl_name in let cols = columns gt in let rowid, key, new_values = rewritten schema ?set_rowid addr new_values in (* The keys the firing row is at on either side of the rewrite: the one the row was found under, and the one it leaves at -- which an assignment to the key may have moved, so an UPDATE trigger reports both ends of the move. *) let old_rowid = match addr with Rowid r -> Some r | Row _ -> None in let fire timing new_values = Trig.fire t ~run_body:run_trigger_body ~orconf:conflict ~timing ~event:(`Update changed) ~table ~cols ~old:(Some old) ?old_rowid ~new_:(Some new_values) ?new_rowid:rowid () in let writes = t.writes in (* A BEFORE trigger that raises IGNORE leaves the row as it was, which is the same [None] a conflict resolution answers for a row it dropped. *) if not (fire Before (before_update_row t gt ~changed ?rowid new_values)) then None else let after_before = if t.writes = writes then Some new_values else reloaded t ~gt ~changed ?rowid addr new_values in let written = Some (changed @ List.map fst (Table.generated (Row.table schema))) in match Option.bind after_before (checked t ~gt ~checks ~conflict ~written ?rowid) with | None -> None | Some new_values -> ( match Rows.resolve_unique t table ~override:conflict ?replace:(replacing t ~run_trigger_body gt) ?typed:(typed gt ~checks new_values) ?key ~exclude:addr ~touched:plan.touched new_values with (* No upsert is passed, so no [Upsert] comes back. *) | Skip | Upsert _ -> None | Clear -> let changed = Some changed in fk_rewrite t table ~keys:plan.keys ~changed ~old_rowid ~old new_values; (* the row and the cursor on it are as they were where nothing wrote *) let unmoved = t.writes = writes in Rows.update t ~table ~reals:plan.reals ~touched:plan.touched ?old:(if held && unmoved then Some old else None) ?at:(if unmoved then at else None) addr ?to_rowid:rowid new_values; Sql.Private.Connection.add (Handle.connection t) 1; fk_actions t ~run_trigger_body table ~keys:plan.keys ~changed ~old ~new_:new_values (); (* The row is written; an AFTER trigger's IGNORE has nothing left to skip, so its answer is not read. *) ignore (fire After new_values); Some (rowid, new_values)) (* The foreign-key actions a parent row's delete or rewrite takes, 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. There are none to take where the statement counts no foreign key of [table] ([keys]). *) and fk_actions t ~run_trigger_body table ~keys ~changed ~old ?new_ () = if keys then List.iter (fun (action : Fk.action) -> Sql.Private.Trigger.program (Handle.connection t) ~orconf:Sql.Ast.Abort (fun () -> match action with | Restrict refused -> if refused () then Sql.Private.Connection.fail (Handle.connection t) Sql.Ast.Abort Foreign_key | Delete (child, rows) -> let gt = Cat.gtable t child in let cols = columns gt in let keys = Fk.required t child in ignore (each_collected t gt ~f:(fun (rowid, values, ()) -> if delete_program t ~run_trigger_body ~table:child ~cols ~keys (Rows.addr gt rowid values) values then Some () else None) (collected (rows ())) : unit list) | Update (child, set, values, rows) -> let gt = Cat.gtable t child in let cols = columns gt in let cat = Cat.v t in let checks = Conflict.checks cat [||] ~table:gt.schema.tbl_name ~cols (Decl.table_checks gt.schema) in let plan = rewrite_plan t gt ~checks ~changed:set ~named:false in ignore (each_collected t gt ~f:(fun (rowid, old, ()) -> store_update t ~run_trigger_body ~gt ~checks ~plan ~conflict:Sql.Ast.Abort ~changed:set (Rows.addr gt rowid old) ~old (Sql.Private.Foreign_key.replace ~columns:cols set values old)) (collected (rows ())) : (int64 option * Sql.Ast.value list) list))) (Fk.actions t table (Handle.connection t) ~changed ~old ?new_ ()) (* Take one row out through sqlite3's program for one deleted row (delete.c, sqlite3GenerateRowDelete): the BEFORE triggers, the row sought again if they moved anything and kept out of the rest if it is gone, the foreign keys it is a parent of, the removal, the foreign-key actions, the AFTER triggers. [false] is a row a BEFORE trigger kept, by raising IGNORE or by removing it first. Every delete goes through here, whether written as SQL, reached through the key-value door, or made by a REPLACE, which fires the triggers under [orconf] REPLACE and only where [triggers] says recursive_triggers is on, and is not counted ([count]), as sqlite3GenerateRowDelete's count argument says. [keys] says the statement counts the foreign keys of [table] and takes their actions, which sqlite3 codes only where some key is on it (sqlite3FkRequired). [held] is as for {!store_update}, of [values]. *) and delete_program ?(orconf = Sql.Ast.Unspecified) ?(triggers = true) ?(count = true) ?(held = false) ?at t ~run_trigger_body ~table ~cols ~keys addr values = (* The key the row is at, where it is addressed by one at all -- a WITHOUT ROWID table addresses its rows by the whole row and publishes no key. *) let old_rowid = match addr with Rowid r -> Some r | Row _ -> None in let fire timing () = (not triggers) || Trig.fire t ~run_body:run_trigger_body ~orconf ~timing ~event:`Delete ~table ~cols ~old:(Some values) ?old_rowid ~new_:None () in let writes = t.writes in if not (fire Before ()) then false else if t.writes <> writes && Rows.current t (Cat.gtable t table) addr = None then false else begin if keys then Fk.check_old t table (Handle.connection t) ~changed:None ~self:(old_rowid, values) values; (* the row and the cursor on it are as they were where nothing wrote *) let unmoved = t.writes = writes in Rows.delete t ~table ?old:(if held && unmoved then Some values else None) ?at:(if unmoved then at else None) addr; if count then Sql.Private.Connection.add (Handle.connection t) 1; fk_actions t ~run_trigger_body table ~keys ~changed:None ~old:values (); (* the row is gone; an AFTER trigger's IGNORE has nothing to keep *) ignore (fire After ()); true end (* The delete a REPLACE resolution makes of a row in the way of [gt]'s row: the delete row program, where the table has DELETE triggers to fire under recursive_triggers or foreign keys to count, and a bare delete otherwise (insert.c, sqlite3GenerateConstraintChecks, regTrigCnt: the program runs for [pTrigger] or sqlite3FkRequired). *) and replacing t ~run_trigger_body (gt : generic_table) = let table = gt.schema.tbl_name in let deletes timing = Sql.Private.Trigger.matching (triggers t) ~timing ~event:`Delete ~table <> [] in let fire = Sql.Private.Connection.recursive_triggers (Handle.connection t) && (deletes Before || deletes After) in let keys = Fk.required t table in if not (fire || keys) then None else Some (fun addr -> Option.iter (fun values -> ignore (delete_program ~orconf:Sql.Ast.Replace ~triggers:fire ~count:false t ~run_trigger_body ~table ~cols:(columns gt) ~keys addr values : bool)) (Rows.current t gt addr)) let remove_row t ~run_trigger_body ~table ~cols ?held addr values = delete_program ?held t ~run_trigger_body ~table ~cols ~keys:(Fk.required t table) addr values (* The assignment in [sets] each of [cols] takes, [None] for a column it leaves, found once for the rows a statement rewrites, as sqlite3 maps each column to its assignment once while it codes the statement (update.c, aXRef). *) let set_slots ~cols ~sets = List.map (fun c -> Ident.assoc_opt c sets) cols (* A stored row rewritten by a SET list: each value replaced by the assignment its column takes ([slots], {!set_slots}), kept where the list carries none. A stored row is read at the width its table declares, so the two lists are the same length wherever a row reaches here; one that is not is refused rather than left to raise [Failure "nth"] from inside the walk. *) let assigned_row ~table ~slots ~eval values = let declared = List.length slots and stored = List.length values in if declared <> stored then Fmt.invalid_arg "table %s declares %d columns but the row holds %d values" table declared stored; List.map2 (fun slot v -> match slot with Some e -> eval e | None -> v) slots values (* A SET column must exist ({!Sql.Private.Write.check_set_column}). *) let check_set_column gt cols c = Sql.Private.Write.check_set_column ~cols ~rowid:(rowid_stored gt) c (* The target an upsert names on [gt] ({!Conflict.target}): its rowid, the PRIMARY KEY its rows are keyed by, or one of its unique indexes. *) let upsert_target (gt : generic_table) up = let names = columns gt in Conflict.target ~table:gt.schema.tbl_name ~columns:names ~rowid:(rowid_stored gt) ~alias:(Decl.rowid_alias gt.schema) ~primary_key: (List.find_map (function | Ok (k : index_key) when k.origin = Primary_key -> Some (List.map (List.nth names) (List.filter_map key_column_position k.keys)) | _ -> None) (Decl.unique_constraints ~without_rowid:true gt.schema)) (List.filter_map (fun (idx : index) -> if idx.unique then Some { Conflict.name = idx.name; keys = List.map (fun k -> Option.map (List.nth names) (key_column_position k)) idx.keys; where = idx.where; } else None) gt.indexes) up (* An upsert's DO UPDATE is checked as sqlite3 prepares the INSERT ({!Sql.Private.Write.check_do_update}). A trigger's step is met at its first row, as {!check_statement} says. *) let check_do_update t cat gt ~cols (up : Sql.Ast.upsert) = if Handle.scope t = [] then Sql.Private.Write.check_do_update cat ~table:gt.schema.tbl_name ~cols ~rowid:(rowid_stored gt) ~constrained: (Decl.rowid_alias gt.schema <> None || List.exists (fun (idx : index) -> idx.unique) gt.indexes || match gt.store with Pk_index_rows _ -> true | Rowid_rows _ -> false) up (* The DO UPDATE arm of an UPSERT: rewrite the conflicting row [rid] per the SET assignments (gated by an optional WHERE), with [excluded] the would-be- inserted row in scope. Returns the rewritten row, or [None] when WHERE skips it. *) let upsert_do_update t cat params ~run_trigger_body ~scope ~gt ~checks addr (sets, where) ~excluded = let table = gt.schema.tbl_name in let cols = columns gt in (* The row the conflict named, which a rowid table is read for and a table whose rows are their own keys carries in the address itself. *) let current = match addr with | Rowid rid -> Option.get (Rows.read t table rid) | Row values -> values in let eval = Engine.eval_upsert ~scope cat params ~table ~cols ~current ~excluded in let passes = match where with | None -> true | Some w -> Sql.Value_ops.tri_of (eval w) = Sql.Value_ops.T in if not passes then None else let new_values = assigned_row ~table ~slots:(set_slots ~cols ~sets) ~eval current in let changed = List.map fst sets in store_update t ~run_trigger_body ~gt ~checks ~conflict:Sql.Ast.Abort ~changed ~plan:(rewrite_plan t gt ~checks ~changed ~named:false) addr ~old:current new_values (* Whether an INSERT computes every row of its source [s] before it stores the first. sqlite3 runs the source as a co-routine and copies it into a temporary table first when the target has an INSERT trigger, a RETURNING among them, or when the source reads the target, through a view as directly (insert.c, sqlite3Insert: "if( pTrigger || readsTable(pParse, iDb, pTab) ) useTempTable = 1"; trigger.c, triggersReallyExist, TK_RETURNING). Otherwise each row is stored before the next is computed. *) let source_first t ~table ~returning s = returning <> [] || (let has timing = Sql.Private.Trigger.matching (triggers t) ~timing ~event:`Insert ~table <> [] in has Before || has After) || let view name = Option.map (fun (v : Sql.Ast.create_view) -> v.select) (Cat.view t name) in Query.reads_table ~view table s (* {!source_first} of a multi-row VALUES [rows]. A single row is the same either way. *) let values_first ~first = function | [] | [ _ ] -> false | rows -> first { (Sql.Private.Lower.post_select []) with from = Values rows } let insert_from_values ~first cat params scope insert_vals rows = let eval = List.map (Engine.eval_const ~scope cat params) in if values_first ~first rows then List.filter_map insert_vals (List.map eval rows) else List.filter_map (fun tuple -> insert_vals (eval tuple)) rows (* [INSERT INTO t DEFAULT VALUES] is the tuple of the defaults of the columns an INSERT writes, stored through the same path as a written-out tuple with no column list: its values take their columns' affinity and answer to a STRICT table's declared types like any other, and the generated columns are computed from them (insert.c, sqlite3Insert, pList = 0). *) let insert_default_row table default_for insert_vals = List.filter_map Fun.id [ insert_vals (List.map default_for (Table.written_columns table)) ] (* The rows of a SELECT source, stored as they come unless {!source_first} says the statement computes them all first. *) let insert_from_select t cat params scope ~first insert_vals s = match values_of_select s with | Some rows -> insert_from_values ~first cat params scope insert_vals rows | None when first s -> let rows = ref [] in select_source t cat params scope s ~f:(fun vals -> rows := vals :: !rows); List.filter_map insert_vals (List.rev !rows) | None -> let stored = ref [] in select_source t cat params scope s ~f:(fun vals -> Option.iter (fun r -> stored := r :: !stored) (insert_vals vals)); List.rev !stored (* 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 table 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 whose rows are their own index keys has no key to read. *) let before_insert gt ?(key : Store.key option) row = let generate rowid = (Table.generate (Row.table gt.schema) ?rowid row, rowid) in match (key, gt.store) with | Some { rowid; _ }, _ -> generate (Some rowid) | None, Rowid_rows _ -> generate (Some (-1L)) | None, Pk_index_rows _ -> generate None (* What an INSERT into [table] codes beside the write, decided once for the statement as sqlite3 codes it when it prepares it: whether it has a BEFORE and an AFTER trigger to fire (insert.c, sqlite3CodeRowTrigger), a table with none building no row for one to read, and whether it counts foreign keys (sqlite3FkRequired). *) type coded = { before : bool; after : bool; keys : bool } let insert_coded t table = let fires timing = Sql.Private.Trigger.matching (triggers t) ~timing ~event:`Insert ~table <> [] in { before = fires Sql.Ast.Before; after = fires Sql.Ast.After; keys = Fk.required t table; } (* The rest of an inserted row's program once NOT NULL and CHECK passed: the uniqueness constraints, in which an upsert's target resolves to its action, the row's foreign keys, the write and the AFTER triggers (insert.c, sqlite3GenerateConstraintChecks and sqlite3CompleteInsertion). *) let insert_checked t ~run_trigger_body ~gt ~coded ~checks ~conflict ?upsert ?key ~stored row = let schema = gt.schema in let table = schema.tbl_name in let pass_upsert = Option.map (fun (target, action) -> (target, match action with `Nothing -> `Nothing | `Update _ -> `Update)) upsert in match Rows.resolve_unique t table ~override:conflict ?upsert:pass_upsert ?typed:(typed gt ~checks row) ?replace:(replacing t ~run_trigger_body gt) ?key row with | Skip -> None | Upsert a -> ( (* sqlite3UpsertDoUpdate runs on the stored row with the row that would have been inserted as [excluded], after which this row is done. *) match upsert with | Some (_, `Update f) -> f a ~excluded:row | Some (_, `Nothing) | None -> None) | Clear -> if coded.keys then Fk.check_new t table (Handle.connection t) ~changed:None row; (* The uniqueness pass above has just probed every b-tree for [row] at [key], and nothing has written since. *) let rowid = Rows.insert t ~table ?key ~resolved:true row in Sql.Private.Connection.add (Handle.connection t) 1; (* The one place a row reaches storage, so the one place the connection's last insert rowid moves. A row a resolution refused or skipped never got here, and a WITHOUT ROWID table's rows take no rowid to remember -- which is exactly what sqlite3 leaves the value at across either. *) if rowid_stored gt then Sql.Private.Connection.set_last_insert_rowid (Handle.connection t) rowid; (* The row is stored; an AFTER trigger's IGNORE has nothing left to skip. *) if coded.after then ignore (Trig.fire t ~run_body:run_trigger_body ~orconf:conflict ~timing:After ~event:`Insert ~table ~cols:(columns gt) ~old:None ~new_:(Some row) ?new_rowid:(named_rowid gt rowid) ()); Some (stored rowid row) (* Store a row, aligned to the columns and each value stored by its column's affinity, through sqlite3's program for one inserted row (insert.c, sqlite3Insert): the BEFORE triggers, the key, the generated columns, NOT NULL, CHECK, then {!insert_checked}. [conflict] is the statement's [OR ] clause; [Unspecified] leaves every constraint its own. [checks] is its CHECK constraints, derived once for the statement. [named] is the value the statement wrote for the rowid. [upsert] is the statement's ON CONFLICT target and what its action does with the row it applies to. The answer is [stored rowid row] for the stored row, rowid-alias filled, the DO UPDATE's answer, or [None] for a row a resolution or a BEFORE trigger dropped. *) let insert_row t ~run_trigger_body ~gt ~coded ~checks ~conflict ?upsert ?named ~stored row = let schema = gt.schema in let written = Rows.written_key gt ?named row in (* A BEFORE trigger that raises IGNORE drops the row, which is what [None] says here -- the same answer a conflict resolution gives for one it skipped. With none to fire, the row it would read is not made. *) if coded.before && let before_row, before_rowid = before_insert gt ?key:written row in not (Trig.fire t ~run_body:run_trigger_body ~orconf:conflict ~timing:Before ~event:`Insert ~table:schema.tbl_name ~cols:(columns gt) ~old:None ~new_:(Some before_row) ?new_rowid:before_rowid ()) then None else (* Drawn once and carried through the constraints and the write alike: two probes of a table at the rowid ceiling answer differently, and the key a CHECK reads has to be the key the row is stored under. *) let key = match written with Some _ -> written | None -> Rows.drawn_key t gt in (* The counter rises to the key now, before any constraint can drop the row (insert.c, sqlite3Insert, autoIncStep). *) Option.iter (fun (k : Store.key) -> Autoinc.step t gt k.rowid) key; let rowid = Option.map (fun (k : Store.key) -> k.rowid) key in (* The key is that column's value, so the row carries it into every constraint below: a CHECK naming the INTEGER PRIMARY KEY sees the key the row will be stored under, which is what sqlite3 resolves a read of the column to. The generated columns are computed from it, "in case one of the generated columns is derived from the INTEGER PRIMARY KEY" (insert.c, sqlite3Insert), and every reader below reads this row. *) let row = Table.generate (Row.table schema) ?rowid row in Option.bind (checked t ~gt ~checks ~conflict ~written:None ?rowid row) (insert_checked t ~run_trigger_body ~gt ~coded ~checks ~conflict ?upsert ?key ~stored) let store_row t ~run_trigger_body ~gt ~checks ~conflict row = insert_row t ~run_trigger_body ~gt ~coded:(insert_coded t gt.schema.tbl_name) ~checks ~conflict ~stored:(fun rowid row -> (rowid, row)) row (* The rows an INSERT's source gives, each through [insert_vals]. *) let insert_source t cat params scope table ~default_for ~first insert_vals = function | Sql.Ast.Values rows -> insert_from_values ~first cat params scope insert_vals rows | Default_values -> insert_default_row table default_for insert_vals | Select s -> insert_from_select t cat params scope ~first insert_vals s (* The transfer [INSERT INTO t SELECT * FROM s] makes where sqlite3 makes one ({!Transfer}): [s] a table, [t] with no INSERT trigger, and [t] empty where the transfer needs it to be. *) let transfer t ~table gt (i : Sql.Ast.insert) = match Transfer.source i with | None -> None | Some name -> ( match Handle.name_holder t name with | Some Table_name -> ( let has timing = Sql.Private.Trigger.matching (triggers t) ~timing ~event:`Insert ~table <> [] in match Transfer.plan ~fk_enforce: (Sql.Private.Connection.foreign_keys (Handle.connection t)) ~triggers:(has Before || has After) ~conflict:i.conflict ~dst:gt (Cat.gtable t name) with | None -> None | Some x -> let empty = row_count gt.store ~upto:1 = 0 in if x.needs_empty && not empty then None else Some (Sql.Private.Connection.add (Handle.connection t) (Rows.transfer t ~table ~empty ~stored:(fun rowid -> Sql.Private.Connection.set_last_insert_rowid (Handle.connection t) rowid; Autoinc.step t gt rowid) x))) | Some (View_name | Index_name) | None -> None) (* An INSERT ... SELECT is checked for its arity before a row is read, as sqlite3 checks it when it prepares the statement: a SELECT that yields no row is refused all the same. *) let check_select_arity cat table (i : Sql.Ast.insert) = match i.source with | Select s -> let n = List.length (Resolve.select_columns (Query.resolve_env cat) s) in Table.check_arity table ~named:i.columns n | Values _ | Default_values -> () (* [store] for an INSERT with [returning]: the rows stored are the statement's answer for its RETURNING alone, so without one no row outlives its own store, and a long INSERT ... SELECT holds none of them for the next. *) let kept_for returning store = if returning <> [] then store else fun vals -> ignore (store vals : _ option); None let exec_insert_rows t cat params ~run_trigger_body gt (i : Sql.Ast.insert) = let table = i.table in let schema = gt.schema in let cols = columns gt in let tbl = Row.table schema in check_select_arity cat tbl i; let checks = Conflict.checks cat params ~table:schema.tbl_name ~cols (Decl.table_checks schema) in let scope = Handle.scope t in let default_for = Table.default ~scope tbl cat params in (* Resolved once, before any row is touched: the target names a constraint or the statement is refused, whether or not a row would have conflicted. *) let upsert = Option.map (fun (up : Sql.Ast.upsert) -> let target = upsert_target gt up in check_do_update t cat gt ~cols up; ( target, match up.action with | Sql.Ast.Nothing -> `Nothing | Sql.Ast.Update (sets, where) -> `Update (fun addr ~excluded -> upsert_do_update t cat params ~run_trigger_body ~scope ~gt ~checks addr (sets, where) ~excluded) )) i.upsert in let stored rowid row = ((if rowid_stored gt then Some rowid else None), row) in let coded = insert_coded t schema.tbl_name in (* The column list may name the rowid, which is a key and not a column: its entries leave the tuple, and the value they wrote decides the key the row goes in at. The list is resolved against the table once. *) let writer = Table.writer tbl ~has_rowid:(rowid_stored gt) ~named:i.columns in let insert_vals vals = let row, named_rowid = Table.write writer ~default_for vals in insert_row t ~run_trigger_body ~gt ~coded ~checks ~conflict:i.conflict ?upsert ?named:named_rowid ~stored row in insert_source t cat params scope tbl ~default_for ~first:(source_first t ~table ~returning:i.returning) (kept_for i.returning insert_vals) i.source (* An INSERT registers its target's AUTOINCREMENT counter with the statement before it stores a row, so the counter is written when the statement ends whether or not a row was (insert.c, autoIncBegin). *) let exec_insert t cat params ~run_trigger_body (i : Sql.Ast.insert) = let table = i.table in vet_triggers t ~event:`Insert ~table; Fk.prepare t (Handle.connection t) table `Insert; let gt = target_table t table in check_insert_calls t cat i; check_returning cat params ~table gt i.returning; Autoinc.register t gt; match transfer t ~table gt i with | Some () -> [] | None -> exec_insert_rows t cat params ~run_trigger_body gt i (* The ON CONFLICT each key of [gt] declares: the INTEGER PRIMARY KEY's, each unique index's, and a WITHOUT ROWID table's PRIMARY KEY's, which the registration of a statement's counters reads to know where a REPLACE may delete ({!Sql.Private.Autoinc.Programs}). *) let declared_conflicts (gt : generic_table) = List.filter_map (fun (c : column) -> if c.is_rowid_alias then c.primary_key else None) gt.schema.columns @ List.filter_map (fun (i : index) -> if i.unique then Some i.on_conflict else None) gt.indexes @ match gt.store with | Pk_index_rows p -> [ p.on_conflict ] | Rowid_rows _ -> [] (* Whether a write into [gt] under the policy [orconf] may settle a uniqueness conflict by REPLACE ({!Sql.Private.Conflict.replaces}). *) let replaces gt orconf = Sql.Private.Conflict.replaces (declared_conflicts gt) orconf module Programs = Sql.Private.Autoinc.Programs (struct type t = Handle.t let triggers = triggers let declared t name = Option.map declared_conflicts (Handle.table t name) let action_writes = Fk.action_writes let recursive_triggers t = Sql.Private.Connection.recursive_triggers (Handle.connection t) let register t name = Option.iter (Autoinc.register t) (Handle.table t name) end) let register_programs t (stmt : Sql.Ast.stmt) = if Autoinc.in_use t then Programs.register t stmt let collated = Sql.Private.Write.collated let collated_where cat ~frame ~table = Option.map (collated cat ~frame ~table) (* The name the row an UPDATE rewrites is bound under. [UPDATE t AS q SET ...] binds it under the alias for the whole statement, the SET expressions and the WHERE alike, and binding it renames the table: [t.a] under an aliased UPDATE reaches nothing, exactly as it reaches nothing under an aliased DELETE. *) let update_frame (u : Sql.Ast.update) = Option.value u.alias ~default:u.table (* An UPDATE with every column's declared COLLATE made explicit, in the WHERE and in the SET expressions alike: a comparison inside an assignment compares under the same rule as one in the predicate. *) let collated_update cat (u : Sql.Ast.update) = let collate = collated cat ~frame:(update_frame u) ~table:u.table in { u with Sql.Ast.where = Option.map collate u.where; sets = List.map (fun (c, e) -> (c, collate e)) u.sets; } (* Whether the keys of [rows] strictly decrease. *) let rec descending = function | (a, _) :: ((b, _) :: _ as rest) -> Int64.compare a b > 0 && descending rest | _ -> true (* The rows of [table] that [where] keeps, read by [select] as the select [SELECT rowid, cols FROM table AS frame WHERE where] -- so the WHERE takes the access path a query's would, a seek of a key for an equality or an IN list, and an IN (SELECT ...) is run once and counted -- in descending rowid order, as a walk collects them. In a trigger step, the frame's OLD and NEW are bound in as parameters after [params] ({!Resolve.bind_scope}), so a key they pin is sought as a bound value is, and every firing runs the one select, whose plan the handle keeps: sqlite3 codes them as registers of a trigger program it compiles once (trigger.c, codeRowTrigger). [None] where the statement is not that select: a table without a rowid, a WITH, or a select [select] declines. *) let row_select ?(set = []) ~frame ~table ~cols where = let col c = { Sql.Ast.expr = Col (Some frame, c); alias = None } in let value e = { Sql.Ast.expr = e; alias = None } in { (Sql.Private.Lower.post_select ((col Sql.Private.Resolve.rowid_sentinel :: List.map col cols) @ List.map value set)) with from = Table { name = table; schema = None; alias = (if frame = table then None else Some frame); subquery = None; }; where; } let selected_rows ~select t cat params gt ~frame ~table ~cols ~ctes where = match (select, where) with | Some select, Some where when ctes = [] && rowid_stored gt -> let s = row_select ~frame ~table ~cols (Some where) in let s, params = match Handle.scope t with | [] -> (s, params) | scope -> Resolve.bind_scope (Query.resolve_env cat) scope s ~params in Option.map (fun rows -> let keyed = List.fold_left (fun acc -> function | Sql.Ast.Int rid :: vs -> (rid, vs) :: acc | _ -> acc) [] rows in (* a scan or a rowid seek answers in ascending order, which the fold has reversed already; only an index's order is sorted *) if descending keyed then keyed else List.sort (fun (a, _) (b, _) -> Int64.compare b a) keyed) (select s params) | _ -> None (* The names [e] reads, its subqueries' included. *) let names_read e = let names = ref [] in Sql.Private.Resolve.walk_expr ~table:(fun () _ -> ()) ~col:(fun () _ name -> names := name :: !names) ~nest:(fun () _ -> ()) ~cte:(fun () _ -> Some ()) () e; !names (* Whether the select of [where] over [gt] walks the table's own b-tree and no index's: no index reads a column [where] names, so the planner seeks none, and none holds every column, so none stands for the table in a covering scan. A write under such a scan reaches no page it walks but the table's, which its cursor follows ({!Btree.Table.Cursor}). *) let table_scanned gt where = let cols = columns gt in let named = names_read where in let reads e = List.exists (fun n -> List.exists (ident_equal n) named) (names_read e) in List.for_all (fun (idx : index) -> List.length idx.keys < List.length cols && (not (Option.fold ~none:false ~some:reads idx.where)) && not (List.exists (function | Column cid -> List.exists (ident_equal (List.nth cols cid)) named | Expression e -> reads e) idx.keys)) gt.indexes (* sqlite3's one-pass DELETE (delete.c, ONEPASS_MULTI): each row the WHERE keeps is removed where the scan stands on it, and the scan goes on from the row past it, so no row is held for the next. It is taken where the removal is the only write a row makes -- no DELETE trigger, no foreign key on either side -- the WHERE holds no subquery, and the scan walks the table itself ({!table_scanned}). The rows removed come back, in table order, only for a RETURNING to read; [None] where the pass is not taken or [scan] declines the select. *) let one_pass_delete ?scan t gt (d : Sql.Ast.delete) ~frame ~cols ~run_trigger_body where = match (scan, where) with | Some scan, Some w when d.ctes = [] && Handle.scope t = [] && rowid_stored gt && (not (Sql.Ast.holds_select w)) && clears t d.table && table_scanned gt w -> let deleted = ref [] and keep = d.returning <> [] in let remove = function | Sql.Ast.Int rid :: values -> if (* [clears] holds: no foreign key is on the table *) delete_program t ~run_trigger_body ~table:d.table ~cols ~keys:false ~held:true (Rows.addr gt rid values) values && keep then deleted := (Some rid, values) :: !deleted | _ -> () in if scan (row_select ~frame ~table:d.table ~cols where) ~f:remove then Some (List.rev !deleted) else None | _ -> None (* The rows of the rowid table [gt] from [lo] to [hi], each handed to [f] with the cursor standing on it and its rowid as a scan reads them, the cursor seeking [lo] and stopping past [hi] as sqlite3 walks a rowid range (where.c, WHERE_IPK: OP_SeekGE, then OP_Next under an OP_Gt end test). [f] may delete the row it is handed, at the cursor or by its rowid: the cursor goes on from past it ({!Btree.Table.Cursor}). *) let iter_rowid_span gt btree ~lo ~hi ~f = let module C = Btree.Table.Cursor in let schema = gt.schema in let c = Integrity.read C.v btree in let e = Btree.Table.encoding btree in let rec walk more = if more then let rowid = Integrity.read C.rowid c in if Int64.compare rowid hi <= 0 then begin let stored = Integrity.read (fun c -> Btree.Record.decode_sub e (C.payload_buf c) ~off:(C.payload_off c) ~len:(C.payload_len c)) c in f c rowid (Row.of_record ~schema ~rowid (Row.record stored)); walk (Integrity.read C.next c) end in walk (Integrity.read (fun c -> C.seek_from c lo) c) (* sqlite3's one-pass DELETE over a rowid range (delete.c, ONEPASS_MULTI over a WHERE_IPK range): where the WHERE bounds the rowid ({!Rowid_range.bounds}) and the removal is the only write a row makes -- no DELETE trigger, no foreign key, no subquery in the WHERE -- the rows of the span are walked from its low edge, each the WHERE keeps removed where the walk stands, and the walk stops past the high edge. The rows removed come back, in table order, only for a RETURNING to read; [None] where the pass is not taken. *) let span_pass_delete t gt (d : Sql.Ast.delete) params ~cols ~keep ~run_trigger_body where = match (gt.store, where) with | Rowid_rows btree, Some w when d.ctes = [] && Handle.scope t = [] && (not (Sql.Ast.holds_select w)) && clears t d.table -> ( match Rowid_range.bounds gt.schema.columns d.table d.alias params w with | None -> None | Some (lo, hi, _, _) -> let deleted = ref [] and returning = d.returning <> [] in iter_rowid_span gt btree ~lo ~hi ~f:(fun at rid values -> if keep (rid, values) && delete_program ~held:true ~at t ~run_trigger_body ~table:d.table ~cols ~keys:false (Rowid rid) values && returning then deleted := (Some rid, values) :: !deleted); Some (List.rev !deleted)) | _ -> None (* Whether a DELETE's [where] keeps the row [(rowid, values)]: compiled once for the statement, or evaluated per row where it holds a subquery. *) let delete_keeps t ~scope cat params gt ~frame ~cols where = let test = match where with | Some w when Sql.Ast.holds_select w -> fun ?rowid values -> Engine.row_matches ~scope ?rowid cat params frame cols where values | Some _ | None -> program t (fun () -> Engine.row_filter ~scope cat params frame cols ~rowid:(rowid_stored gt) where) in fun (rowid, values) -> test ?rowid:(named_rowid gt rowid) values (* sqlite3's truncate optimization (delete.c, sqlite3DeleteFrom): a DELETE with no WHERE that no row has to be seen leaving -- no DELETE trigger, no foreign key counting the table ({!clears}) and no RETURNING, which sqlite3 compiles as a trigger of its own -- empties the table and every index of it whole, one OP_Clear per b-tree, and counts the rows the table held. An index entry no row owns goes with the rest, where a walk of the rows would leave it. [None] where the DELETE is not one sqlite3 truncates. *) let truncate t (d : Sql.Ast.delete) = if d.where = None && d.returning = [] && clears t d.table then begin Sql.Private.Connection.add (Handle.connection t) (Rows.clear t ~table:d.table); Some [] end else None let exec_delete ?select ?scan t cat params ~run_trigger_body (d : Sql.Ast.delete) = vet_triggers t ~event:`Delete ~table:d.table; Fk.prepare t (Handle.connection t) d.table `Delete; (* A leading WITH binds its CTEs for the WHERE subqueries. *) let cat = if d.ctes = [] then cat else Query.materialize_ctes cat params d.ctes in let gt = target_table t d.table in let cols = columns gt in check_statement t cat (Sql.Ast.Delete d) ~where:d.where ~returning:d.returning []; check_returning cat params ~table:d.table gt d.returning; let scope = Handle.scope t in (* [DELETE FROM t AS x] qualifies WHERE columns by the alias, so the row frame is named by the alias when present. *) let frame = Option.value d.alias ~default:d.table in let where = collated_where cat ~frame ~table:d.table d.where in (* Collect first, then delete: the predicate (which may run a subquery over the same table) reads a consistent snapshot, not a half-deleted one. *) let keep = delete_keeps t ~scope cat params gt ~frame ~cols where in match match truncate t d with | Some _ as deleted -> deleted | None -> ( match span_pass_delete t gt d params ~cols ~keep ~run_trigger_body where with | Some _ as deleted -> deleted | None -> one_pass_delete ?scan t gt d ~frame ~cols ~run_trigger_body where) with | Some deleted -> deleted | None -> let seek = seek_where t gt ~frame d.where in let selected = if seeks_rowid t gt seek then None else selected_rows ~select t cat params gt ~frame ~table:d.table ~cols ~ctes:d.ctes where in let victims = match selected with | Some rows -> rows | None -> ( match indexed_victims t d.table params seek with | Some rows -> List.filter keep rows | None -> let f rowid values acc = if keep (rowid, values) then (rowid, values) :: acc else acc in walk_table t d.table ~init:[] ~f) in let keys = Fk.required t d.table in let deleted = each_collected t gt ~f:(fun (rid, values, ()) -> if delete_program t ~run_trigger_body ~table:d.table ~cols ~keys ~held:true (Rows.addr gt rid values) values then Some (rid, values) else None) (List.rev_map (fun (rid, values) -> (rid, values, ())) victims) in (* the deleted rows, in table order, for RETURNING (pre-delete values) *) List.map (fun (rid, values) -> ((if rowid_stored gt then Some rid else None), values)) deleted (* The DELETE FROM [table] a DROP TABLE runs first under foreign keys (fkey.c, sqlite3FkDropTable): every row, in table order, through the delete program with the table's own triggers off (pParse->disableTriggers) and its foreign-key actions on, which fire the triggers of the tables they write. *) let delete_for_drop t ~run_trigger_body table = let gt = Cat.gtable t table in let cols = columns gt in let rows = Cat.fold_table t table ~init:[] ~f:(fun r v acc -> (r, v) :: acc) in ignore (each_collected t gt ~f:(fun (rid, values, ()) -> if delete_program ~triggers:false t ~run_trigger_body ~table ~cols ~keys:(Fk.required t table) (Rows.addr gt rid values) values then Some () else None) (List.rev_map (fun (rid, values) -> (rid, values, ())) rows) : unit list) (* The expressions an UPDATE evaluates for each row it rewrites: the assignment that stands for each column, the last, then the one that carries the row to another key ({!update_sets_rowid}). *) let set_exprs (u : Sql.Ast.update) ~sets_rowid = let standing = List.fold_left (fun acc (c, e) -> if List.exists (fun (c', _) -> ident_equal c c') acc then acc else (c, e) :: acc) [] (List.rev u.sets) in List.map snd standing @ Option.to_list sets_rowid (* Whether [exprs] are evaluated in the one scope the statement runs in -- no FROM, whose join rows each bring their own -- and hold no subquery, which keeps the row-at-a-time path. *) let lowered_once (u : Sql.Ast.update) exprs = u.from = None && not (List.exists Sql.Ast.holds_select exprs) (* The SET values an UPDATE stores, lowered once for the statement rather than once a row ({!Engine.row_values}), where they are {!lowered_once}. It maps a row to the value of each of [exprs] ({!set_exprs}), found by the expression itself. *) let set_values t cat params (u : Sql.Ast.update) gt ~cols ~exprs = if not (lowered_once u exprs) then None else let run = program t (fun () -> Engine.row_values ~scope:(Handle.scope t) cat params (update_frame u) cols ~rowid:(rowid_stored gt) exprs) in Some (fun rowid values -> let pairs = List.combine exprs (run ?rowid:(named_rowid gt rowid) values) in fun e -> List.assq e pairs) (* Store one matched target row rewritten by [u], [eval] giving the value of each SET expression for it, through the shared rewrite tail under the statement's [plan]. Returns the post-update row for RETURNING. *) let update_store t ~run_trigger_body (u : Sql.Ast.update) ~cols ~checks ~changed ~plan ~sets_rowid gt = (* A column assigned more than once in SET takes its LAST assignment, as sqlite3 does; the reversed list makes [assoc_opt] find the last. *) let slots = set_slots ~cols ~sets:(List.rev u.sets) in fun ~at ~eval (rowid, values) -> let new_values = assigned_row ~table:u.table ~slots ~eval values in store_update t ~run_trigger_body ~gt ~checks ~conflict:u.conflict ~changed ~plan ~held:true ?at ?set_rowid:(Option.map eval sets_rowid) (Rows.addr gt rowid values) ~old:values new_values (* Rewrite one matched target row: evaluate the SET assignments in [fscope] (the joined aux row for UPDATE ... FROM, else the trigger scope), through [set_values] where the statement lowered them once, then [store] it. *) let update_rewrite_row cat params (u : Sql.Ast.update) ~cols ~set_values ~store gt = fun ~at (rowid, values, fscope) -> let eval = match Lazy.force set_values with | Some f -> f rowid values | None -> fun e -> Engine.eval_in_row ~scope:fscope ?rowid:(named_rowid gt rowid) cat params (update_frame u) cols values e in store ~at ~eval (rowid, values) (* The assignment that carries the row to another key, where the SET names the rowid by a spelling no column of the table declares. The last such assignment stands, as the last assignment to any column does. A table declaring an INTEGER PRIMARY KEY has no such assignment: the spelling is that column, resolved to it before the SET list is read, so the rewrite is an ordinary column write and the key follows the column. *) let update_sets_rowid gt (u : Sql.Ast.update) = let has_rowid = rowid_stored gt in List.fold_left (fun acc (c, e) -> if Decl.written_rowid gt.schema.columns ~has_rowid c then Some e else acc) None u.sets (* An UPDATE's assignments with the rowid spellings resolved to the column that holds the key: on a table declaring an INTEGER PRIMARY KEY the keyword and the alias are one column, so an assignment through either is an assignment to it and the last one written wins, exactly as for any column. *) let resolve_update_rowid gt (u : Sql.Ast.update) = let has_rowid = rowid_stored gt in match Decl.rowid_alias gt.schema with | None -> u | Some i -> let alias = (List.nth gt.schema.columns i).name in { u with Sql.Ast.sets = List.map (fun (c, e) -> if Decl.written_rowid gt.schema.columns ~has_rowid c then (alias, e) else (c, e)) u.sets; } (* Every SET column of an UPDATE must exist ({!check_set_column}). *) let check_update_columns gt (u : Sql.Ast.update) cols = List.iter (fun (c, _) -> check_set_column gt cols c) u.sets (* The rows an UPDATE rewrites, each with the join-row scope its WHERE matched under. Collected in full before any rewrite, so the predicate sees a consistent snapshot rather than rows a previous rewrite moved. *) let update_victims ?select t cat params (u : Sql.Ast.update) gt ~cols ~from_scopes = let frame = update_frame u in (* Without FROM the one scope is the statement's, and a WHERE holding no subquery is lowered once for every row it tests. *) let test = match (u.from, u.where) with | None, w when not (Option.fold ~none:false ~some:Sql.Ast.holds_select w) -> let f = program t (fun () -> Engine.row_filter ~scope:(Handle.scope t) cat params frame cols ~rowid:(rowid_stored gt) w) in fun _fscope ?rowid values -> f ?rowid values | _ -> fun fscope ?rowid values -> Engine.row_matches ~scope:fscope ?rowid cat params frame cols u.where values in let matching (rowid, values) = Option.map (fun fscope -> (rowid, values, fscope)) (List.find_opt (fun fscope -> test fscope ?rowid:(named_rowid gt rowid) values) from_scopes) in (* The index is asked only without [FROM]: the equality extraction drops column qualifiers, so with auxiliary tables in scope a predicate about one of them would be read as a constraint on the target and narrow it wrongly. *) let seek = seek_where t gt ~frame u.where in let selected = if u.from <> None || seeks_rowid t gt seek then None else selected_rows ~select t cat params gt ~frame ~table:u.table ~cols ~ctes:u.ctes u.where in match selected with | Some rows -> List.map (fun (rid, values) -> (rid, values, [])) rows | None -> ( match if u.from = None then indexed_victims t u.table params seek else None with | Some rows -> List.filter_map matching rows | None -> walk_table t u.table ~init:[] ~f:(fun rowid values acc -> match matching (rowid, values) with | Some v -> v :: acc | None -> acc)) (* Whether a row's rewrite by [u] under its [plan] is the only write it makes besides its index entries: the key left where it is, no UPDATE trigger, no foreign key on either side and no REPLACE, as update.c asks of WHERE_ONEPASS_MULTIROW. An index the SET reaches is written where the row is; the walk declines only an index it writes ({!one_pass_update}). *) let rewrites_alone t gt (u : Sql.Ast.update) ~changed ~plan = (not plan.key_moved) && fires_none t ~table:u.table (`Update changed) && (not (Fk.required t u.table)) && not (replaces gt u.conflict) (* Each row of [u]'s select rewritten as [scan] reaches it. A rewrite that moves cells moves none the scan has still to read out from under it: the table cursor goes on past the row it stood on ({!Btree.Table.Cursor.next}), and the readers of its columns take nothing they read before the move for the row they stand on after it ({!Btree.Table.Cursor.moves}). The value of each SET expression [exprs] holds is a column of the select, after the row's own, so the statement's one program evaluates the WHERE and the assignments, as sqlite3 codes them (update.c). With no RETURNING to read them, it answers no rows. *) let rewrite_pass scan ~refused (u : Sql.Ast.update) ~cols ~exprs ~store = let rec split n acc = function | v :: rest when n > 0 -> split (n - 1) (v :: acc) rest | rest -> (List.rev acc, rest) in let width = List.length cols in let rewrite_here = function | Sql.Ast.Int rid :: row -> let values, set = split width [] row in let pairs = List.combine exprs set in ignore (store ~at:None ~eval:(fun e -> List.assq e pairs) (rid, values) : _ option) | _ -> () in if scan ~refused (row_select ~set:exprs ~frame:(update_frame u) ~table:u.table ~cols u.where) ~f:rewrite_here then Some [] else None (* sqlite3's one-pass UPDATE (update.c, ONEPASS_MULTI): each row the WHERE keeps is rewritten where the scan stands on it, in the scan's order, so no row is held for the next and a SET subquery reading the table reads the rows rewritten before it. It is taken where the rewrite is the only write a row makes besides its index entries -- no UPDATE trigger, no foreign key on either side, no REPLACE, the key left where it is ([alone], {!rewrites_alone}) -- with no FROM, no RETURNING and no subquery in the WHERE, as sqlite3 asks of WHERE_ONEPASS_MULTIROW. [scan] declines a walk of an index the SET reaches ([plan.touched]), as update.c turns ONEPASS_MULTI off where aiCurOnePass[1] is among aToOpen: the walk would meet its moved entries again. [None] where the pass is not taken or [scan] declines the select. *) let one_pass_update ?scan t gt (u : Sql.Ast.update) ~cols ~alone ~plan ~exprs ~store = match scan with | Some scan when alone && u.from = None && u.returning = [] && u.ctes = [] && Handle.scope t = [] && rowid_stored gt && not (Option.fold ~none:false ~some:Sql.Ast.holds_select u.where) -> let refused name = List.exists (fun (idx : index) -> plan.touched idx && ident_equal idx.name name) gt.indexes in rewrite_pass scan ~refused u ~cols ~exprs ~store | Some _ | None -> None (* sqlite3's one-pass UPDATE over a rowid range, as {!span_pass_delete} deletes one: where {!one_pass_update} would rewrite alone and the WHERE bounds the rowid, the rows of the span are walked from its low edge, each the WHERE keeps rewritten where the walk stands, and the walk stops past the high edge. *) let span_pass_update t cat params gt (u : Sql.Ast.update) ~cols ~alone ~exprs ~set_values ~rewrite = match (gt.store, u.where) with | Rowid_rows btree, Some w when alone && lowered_once u exprs && u.ctes = [] && Handle.scope t = [] && not (Sql.Ast.holds_select w) -> ( match Rowid_range.bounds gt.schema.columns u.table u.alias params w with | None -> None | Some (lo, hi, _, _) -> ignore (Lazy.force set_values); let keeps = Engine.row_filter cat params (update_frame u) cols ~rowid:true u.where in let rows = ref [] and returning = u.returning <> [] in iter_rowid_span gt btree ~lo ~hi ~f:(fun at rid values -> if keeps ~rowid:rid values then match rewrite ~at:(Some at) (rid, values, []) with | Some row when returning -> rows := row :: !rows | Some _ | None -> ()); Some (List.rev !rows)) | _ -> None (* [UPDATE ... FROM] joins auxiliary tables to the target; each join-row is an outer scope visible to WHERE and SET. With no FROM, the lone scope is the trigger scope, so the plain UPDATE path is unchanged. A target row is updated for the first join-row that satisfies WHERE (sqlite3 leaves the choice unspecified when several match). *) let from_scopes t cat params (u : Sql.Ast.update) = let scope = Handle.scope t in match u.from with | None -> [ scope ] | Some (from, joins) -> List.map (fun env -> env @ scope) (Engine.from_bindings ~scope cat params from joins) (* The statement's rewrite plan, decided once as sqlite3 codes it once (update.c), and whether a row's rewrite under it is the only write it makes ({!rewrites_alone}). *) let update_plan t gt (u : Sql.Ast.update) ~checks ~changed ~sets_rowid = let plan = rewrite_plan t gt ~checks ~changed ~named:(Option.is_some sets_rowid) in (plan, rewrites_alone t gt u ~changed ~plan) let exec_update ?select ?scan t cat params ~run_trigger_body (u : Sql.Ast.update) = vet_triggers t ~event:(`Update (List.map fst u.sets)) ~table:u.table; Fk.prepare t (Handle.connection t) u.table (`Update (List.map fst u.sets)); (* A leading WITH binds its CTEs for the SET/WHERE subqueries. *) let cat = if u.ctes = [] then cat else Query.materialize_ctes cat params u.ctes in let gt = target_table t u.table in let cols = columns gt in let checks = Conflict.checks cat params ~table:gt.schema.tbl_name ~cols (Decl.table_checks gt.schema) in check_update_columns gt u cols; check_statement t cat (Sql.Ast.Update u) ~where:u.where ~returning:u.returning (List.map snd u.sets); check_returning cat params ~table:u.table gt u.returning; let u = collated_update cat (resolve_update_rowid gt u) in let sets_rowid = update_sets_rowid gt u in let from_scopes = from_scopes t cat params u in let changed = List.map fst u.sets in let exprs = set_exprs u ~sets_rowid in (* lowered where a row is rewritten one at a time, the one-pass rewrite taking its values from its own select *) let set_values = lazy (set_values t cat params u gt ~cols ~exprs) in let plan, alone = update_plan t gt u ~checks ~changed ~sets_rowid in let store = update_store t ~run_trigger_body u ~cols ~checks ~changed ~plan ~sets_rowid gt in let rewrite = update_rewrite_row cat params u ~cols ~set_values ~store gt in (* The victims come last row first. They are rewritten in table order, as sqlite3 visits them (update.c), each checked against the rows the ones before it left: of two rows taking one UNIQUE value, OR IGNORE keeps the first's rewrite, and a bare UPDATE fails on a row whose new key a later row still holds. Returns the post-update rows, in that order, for RETURNING. A rewrite a resolution dropped changed no row, so it contributes none. *) match match span_pass_update t cat params gt u ~cols ~alone ~exprs ~set_values ~rewrite with | Some _ as rows -> rows | None -> one_pass_update ?scan t gt u ~cols ~alone ~plan ~exprs ~store with | Some rows -> rows | None -> (* what the lowering refuses is refused before a row is read, an empty table's statement included, as sqlite3 refuses it while it prepares the statement *) ignore (Lazy.force set_values); let victims = update_victims ?select t cat params u gt ~cols ~from_scopes in each_collected t gt ~f:(rewrite ~at:None) (List.rev victims)