(*--------------------------------------------------------------------------- Copyright (c) 2026 Thomas Gazagnaire. All rights reserved. SPDX-License-Identifier: ISC ---------------------------------------------------------------------------*) module Spi = Catalog.Spi module Ident = Catalog.Ident module Value = Catalog.Value type storage = Affinity of Value_ops.affinity | Strict of Strict.t let affinity = function Affinity a -> a | Strict st -> Strict.affinity st type t = { schema : Spi.Schema.t; names : string list; rowid_alias : int option Lazy.t; storage : storage list Lazy.t; catalog : Query.catalog Lazy.t; collate : (Ast.expr -> Ast.expr) Lazy.t; default_exprs : (string * Ast.expr) list Lazy.t; defaults : Value.t array Lazy.t; generated : (string * Ast.expr) list Lazy.t; checks : (string * Ast.expr) list Lazy.t; mutable writer : writer option; } (* What an INSERT's column list asks of each row, resolved against the table once: whether the table has a rowid, each column with its storage, which columns are generated, the list as written, and for each declared column the position of the first entry of the list that names it ([-1] for none: it takes its DEFAULT); the position of the last entry naming the rowid, by a rowid name or the INTEGER PRIMARY KEY ([-1] for none); and the first name that is neither a column nor a rowid name. *) and writer = { w_table : t; w_has_rowid : bool; cols : (string * storage) list; generated_at : bool list; named : string list; width : int; sources : int array; key_at : int; unknown : string option; } let name t = t.schema.table let columns t = t.names let storage t = Lazy.force t.storage let is_strict t = t.schema.strict let rowid_alias t = Lazy.force t.rowid_alias let catalog t = Lazy.force t.catalog let collate t e = Lazy.force t.collate e let defaults t = Lazy.force t.defaults let generated t = Lazy.force t.generated let schema t = t.schema let checks t = Lazy.force t.checks let strict_type ~table (c : Spi.Schema.column) = match Strict.of_type_name c.decl_type with | Some st -> st | None -> if c.decl_type = "" then Catalog.Error.fail_prepare "missing datatype for %s.%s" table c.name else Catalog.Error.fail_prepare "unknown datatype for %s.%s: %S" table c.name c.decl_type (* The affinity a column compares under: its declared type's, but none for [ANY] in a [STRICT] table, which keeps a value as given (stricttables.html, section 3; build.c, sqlite3EndTable). Unlike {!storage}, it refuses no declared type. *) let column_affinity (s : Spi.Schema.t) (c : Spi.Schema.column) = if s.strict && Strict.of_type_name c.decl_type = Some Strict.Any then `Blob else Value_ops.affinity_of_type c.decl_type let column_named (s : Spi.Schema.t) col = List.find_opt (fun (c : Spi.Schema.column) -> Ident.equal c.name col) s.columns let parse what text = match Lexer.parse_expr text with | Ok e -> e | Error msg -> Catalog.Error.fail_prepare "%s %S: %s" what text msg let expression t ~what text = collate t (parse what text) let row_catalog ~encoding (s : Spi.Schema.t) = let affinities = List.map (fun (c : Spi.Schema.column) -> (c.name, column_affinity s c)) s.columns in { (Query.closed ~encoding "an expression over one row") with collation = (fun _ col -> Option.bind (column_named s col) (fun (c : Spi.Schema.column) -> c.collation)); affinity = (fun _ col -> Ident.assoc_opt col affinities); } (* The row is in scope under the table's own name, the only relation a stored expression may read. *) let row_collate (s : Spi.Schema.t) = let names = Spi.Schema.column_names s in let env : Resolve.env = { columns = (fun _ -> names); collation = (fun _ col -> Option.bind (column_named s col) (fun (c : Spi.Schema.column) -> c.collation)); affinity = (fun _ col -> Option.map (column_affinity s) (column_named s col)); decl_type = (fun _ col -> Option.bind (column_named s col) (fun (c : Spi.Schema.column) -> if c.decl_type = "" then None else Some (Column_tokens.shown_type c.decl_type))); table_function_columns = (fun _ -> []); has_rowid = (fun _ -> true); holds = (fun _ -> true); } in Resolve.collate_over env [ (s.table, s.table) ] let v ?(encoding = Encoding.Utf8) (s : Spi.Schema.t) = let storage = lazy (List.map (fun (c : Spi.Schema.column) -> if s.strict then Strict (strict_type ~table:s.table c) else Affinity (Value_ops.affinity_of_type c.decl_type)) s.columns) in let collate = lazy (row_collate s) in (* the columns that declare a DEFAULT, each with it: one that declares none defaults to NULL *) let default_exprs = lazy (List.filter_map (fun (c : Spi.Schema.column) -> match c.default with | None -> None | Some (`Value v) -> Some (c.name, Ast.Lit v) | Some (`Expression text) -> Some (c.name, parse "DEFAULT" text)) s.columns) in let defaults = lazy (let cat = Query.closed ~encoding "a DEFAULT expression" in Array.of_list (List.map (fun c -> match Ident.assoc_opt c (Lazy.force default_exprs) with | Some e -> Engine.eval_const cat [||] e | None -> Value.Null) (Spi.Schema.column_names s))) in let generated = lazy (List.filter_map (fun (c : Spi.Schema.column) -> Option.map (fun (_, text) -> (c.name, Lazy.force collate (parse "generated column" text))) c.generated) s.columns) in { schema = s; names = Spi.Schema.column_names s; rowid_alias = lazy (Spi.Schema.rowid_alias s); storage; catalog = lazy (row_catalog ~encoding s); collate; default_exprs; defaults; generated; checks = lazy (List.map (fun text -> (text, Lazy.force collate (parse "CHECK" text))) s.checks); writer = None; } let default ?(scope = []) t cat params c = match Ident.assoc_opt c (Lazy.force t.default_exprs) with | Some e -> Engine.eval_const ~scope cat params e | None -> Value.Null (* A DEFAULT settled from its text under the affinity [aff], as sqlite3ValueFromExpr (src/vdbemem.c) settles it, or [None] where it does not settle. A literal, or a sign over a numeric one, is one token: its value under [aff], or under TEXT affinity a numeral's text as written, the minus prefixed. A plus is the operand; a minus over anything else negates the operand settled under [aff] and takes [aff] again; a CAST settles its operand under its own affinity, converts it and takes [aff]. Anything else does not settle. *) let rec settle aff (e : Ast.expr) = (* a numeral alone is evaluated, which reads no text *) let eval e = Engine.eval_const (Query.closed ~encoding:Encoding.Utf8 "a DEFAULT expression") [||] e in let under v = Some (Value_ops.apply_affinity aff v) in match e with | Lit v -> under v (* a default is read with no row in hand, so no column can be named true *) | Truth s -> under (Ast.truth_value s) | Numeral s when aff = `Text -> Some (Value.Text s) | Unary_minus (Numeral s) when aff = `Text -> Some (Value.Text ("-" ^ s)) (* read, not coded: a hexadecimal literal too big for 64 bits is no error *) | Numeral s -> under (Ast.number s) | Unary_minus (Numeral s) -> under (Ast.number ~negative:true s) | Unary_minus (Lit (Int _ | Float _)) -> under (eval e) | Unary_plus e -> settle aff e | Unary_minus e -> Option.map (fun v -> Value_ops.apply_affinity aff (eval (Unary_minus (Lit v)))) (settle aff e) | Cast (e, ty) -> Option.map (fun v -> Value_ops.apply_affinity aff (Value_ops.cast ty v)) (settle (Value_ops.affinity_of_type ty) e) | Param _ | Named_param _ | Col _ | Schema_col _ | Star | Qualified_star _ | Unop_not _ | Binary _ | Is_null _ | Is_not_null _ | Is _ | In_list _ | In_select _ | Scalar_select _ | Exists _ | Raise _ | Func _ | Distinct_agg _ | Filter _ | Ordered_agg _ | Window _ | Case _ | Collate _ | Affinity _ -> None let coerce_one st v = Value_ops.apply_affinity (affinity st) v let check_value ~table name st v = match st with | Affinity _ -> () | Strict st -> if not (Strict.accepts st v) then Catalog.Error.fail (Constraint (Datatype { table; column = name; declared = Strict.to_string st; stored = Strict.storage_class v; })) (* sqlite3's OP_TypeCheck, run once the NOT NULL checks have passed. *) let rec check_types ~table names storage values = match (names, storage, values) with | name :: names, st :: storage, v :: values -> check_value ~table name st v; check_types ~table names storage values | _ -> () let check t values = if t.schema.strict then check_types ~table:t.schema.table t.names (storage t) values (* A row is the table's columns filled in, so a value list of another width is not one and the arity is the whole of what went wrong. *) let coerce t values = let storage = storage t in let rec go s vs = match (s, vs) with | st :: s, v :: vs -> coerce_one st v :: go s vs | [], [] -> [] | _ -> Fmt.invalid_arg "table %s declares %d columns but the row holds %d values" (name t) (List.length storage) (List.length values) in go storage values let store_value t j v = let st = List.nth (storage t) j in let v = coerce_one st v in check_value ~table:t.schema.table (List.nth t.names j) st v; v (* [values] with its [i]th value [f v], the list after it shared. *) let rec set_nth i f = function | [] -> [] | v :: vs -> if i = 0 then f v :: vs else v :: set_nth (i - 1) f vs let place_rowid t rowid values = match rowid_alias t with | None -> values | Some idx -> set_nth idx (fun _ -> Value.Int rowid) values (* Which declared columns [expr] names, as positions. A generation expression is required to answer from the row itself ({!Self_ref}), so every name it carries is a column of this table or nothing. *) let reads names expr = let acc = ref [] in Resolve.walk_expr ~table:(fun () _ -> ()) ~col:(fun () _ name -> match Ident.index name names with | Some i -> acc := i :: !acc | None -> ()) ~nest:(fun () _ -> ()) ~cte:(fun () _ -> Some ()) () expr; !acc (* What a column's slot holds: a value the read is done with, one a generation expression still has to compute, or one being computed right now -- which a second demand for it means the schema's generations reach around a cycle. *) let final = '\000' let pending = '\001' let busy = '\002' type row = { table : t; cat : Query.catalog; storage_a : storage array; gens : (Ast.expr * int list) option array; fresh : Bytes.t; state : Bytes.t; slots : Value.t array; mutable rowid : int64 option; } let is_virtual (c : Spi.Schema.column) = match c.generated with Some (`Virtual, _) -> true | Some _ | None -> false (* A row over [slots], which it fills in place rather than copies: one array per cursor, refilled per row, is what serving a column at a time costs. A read computes the VIRTUAL columns, the stored row holding the STORED ones; a write computes both ([stored]). *) let row_over ?(stored = false) t slots = let cols = Array.of_list t.schema.columns in let exprs = generated t in let n = Array.length cols in let fresh = Bytes.make n final in let gens = Array.init n (fun i -> let c = cols.(i) in if not (stored || is_virtual c) then None else Option.map (fun expr -> Bytes.set fresh i pending; (expr, reads t.names expr)) (Ident.assoc_opt c.name exprs)) in { table = t; cat = catalog t; storage_a = Array.of_list (storage t); gens; fresh; state = Bytes.of_string (Bytes.to_string fresh); slots; rowid = None; } let row t = row_over t (Array.make (List.length t.names) Value.Null) let slots r = r.slots let rowid r = r.rowid let start r rowid = Bytes.blit r.fresh 0 r.state 0 (Bytes.length r.fresh); r.rowid <- rowid let rec column r j = let s = Bytes.get r.state j in if s = final then r.slots.(j) else if s = busy then Catalog.Error.fail_prepare "generated column loop on \"%s\"" (List.nth r.table.names j) else begin Bytes.set r.state j busy; match compute r j with | v -> r.slots.(j) <- v; Bytes.set r.state j final; v | exception e -> Bytes.set r.state j pending; raise e end and compute r j = let expr, refs = Option.get r.gens.(j) in List.iter (fun i -> ignore (column r i : Value.t)) refs; let v = Engine.eval_in_row ?rowid:r.rowid ~stored:Generated_column r.cat [||] (name r.table) r.table.names (Array.to_list r.slots) expr in let st = r.storage_a.(j) in let v = coerce_one st v in check_value ~table:(name r.table) (List.nth r.table.names j) st v; v (* Every column of the row, computed left to right so that a row with two columns their type cannot hold is refused by the leftmost of them, as a query reading both is. *) let values r = for j = 0 to Array.length r.slots - 1 do ignore (column r j : Value.t) done; Array.to_list r.slots let generate t ?rowid row = let row = match rowid with Some r -> place_rowid t r row | None -> row in match generated t with | [] -> row | _ -> (* sqlite3ComputeGeneratedColumns applies the table's affinity first, which for a STRICT table is OP_TypeCheck over the written columns, so those are checked here, ahead of NOT NULL and of the generated ones *) if is_strict t then begin let written = Array.of_list (List.map (fun (c : Spi.Schema.column) -> c.generated = None) t.schema.columns) in let keep l = List.filteri (fun i _ -> i < Array.length written && written.(i)) l in check_types ~table:(name t) (keep t.names) (keep (storage t)) (keep row) end; let r = row_over ~stored:true t (Array.of_list row) in r.rowid <- rowid; values r let is_generated t c = List.exists (fun (g : Spi.Schema.column) -> g.generated <> None && Ident.equal g.name c) t.schema.columns let written_columns t = List.filter (fun c -> not (is_generated t c)) t.names let check_arity t ~named n = match named with | [] -> let w = List.length (written_columns t) in if n <> w then Catalog.Error.fail_prepare "table %s has %d columns but %d values were supplied" (name t) w n | named -> if List.length named <> n then Catalog.Error.fail_prepare "%d values for %d columns" n (List.length named) (* A name written where a column name goes that reaches the rowid rather than a column: one of the rowid spellings, no column declaring it, on a table keyed by a rowid. The INTEGER PRIMARY KEY is not this: it answers by its own name. *) let written_rowid t ~has_rowid c = has_rowid && Ast.is_rowid_name c && not (List.exists (Ident.equal c) t.names) let resolve_writer t ~has_rowid ~named = let columns = t.names in (* the generated columns, none in most tables: asked of every column *) let generated = List.filter_map (fun (g : Spi.Schema.column) -> if g.generated <> None then Some g.name else None) t.schema.columns in let generated_at = List.map (fun c -> List.exists (Ident.equal c) generated) columns in let alias = Option.map (List.nth columns) (rowid_alias t) in let named_a = Array.of_list named in let rowid_name = Array.map (written_rowid t ~has_rowid) named_a in let first c = let rec go i = if i >= Array.length named_a then -1 else if (not rowid_name.(i)) && Ident.equal named_a.(i) c then i else go (i + 1) in go 0 in let key_at = ref (-1) and unknown = ref None in for i = Array.length named_a - 1 downto 0 do let c = named_a.(i) in if !key_at < 0 && (rowid_name.(i) || Option.fold ~none:false ~some:(Ident.equal c) alias) then key_at := i; if (not rowid_name.(i)) && not (List.exists (Ident.equal c) columns) then unknown := Some c done; { w_table = t; w_has_rowid = has_rowid; cols = List.combine t.names (storage t); generated_at; named; width = List.fold_left (fun n g -> if g then n else n + 1) 0 generated_at; sources = Array.of_list (List.map first columns); key_at = !key_at; unknown = !unknown; } (* The table keeps the writer of the list it was last asked for: a statement run once per row, as a loader runs its INSERT, asks for the same list each time, by the same list or by one spelled the same. A changed schema is another table, which has resolved nothing. *) let writer t ~has_rowid ~named = match t.writer with | Some w when Bool.equal w.w_has_rowid has_rowid && (w.named == named || List.equal String.equal w.named named) -> w | Some _ | None -> let w = resolve_writer t ~has_rowid ~named in t.writer <- Some w; w let write w ~default_for vals = let t = w.w_table in let storage = storage t in match w.named with | [] -> let n = List.length vals in if n <> w.width then Catalog.Error.fail_prepare "table %s has %d columns but %d values were supplied" (name t) w.width n; (* The values go to the written columns in order; a generated column's slot is filled when the row is generated. *) let rec fill vals storage generated = match (storage, generated) with | st :: storage, true :: generated -> coerce_one st Value.Null :: fill vals storage generated | st :: storage, _ :: generated -> ( match vals with | v :: vals -> coerce_one st v :: fill vals storage generated | [] -> coerce_one st Value.Null :: fill [] storage generated) | _ -> [] in (fill vals storage w.generated_at, None) | named -> (* a name no column answers to is refused first, then a list its values do not fill, as sqlite3 refuses them (insert.c, sqlite3Insert) *) (match w.unknown with | Some c -> Catalog.Error.fail_prepare "table %s has no column named %s" (name t) c | None -> ()); if List.compare_lengths named vals <> 0 then Catalog.Error.fail_prepare "%d values for %d columns" (List.length vals) (List.length named); let vals = Array.of_list vals in let row = List.mapi (fun i (c, st) -> match w.sources.(i) with | -1 -> coerce_one st (default_for c) | j -> coerce_one st vals.(j)) w.cols in (row, if w.key_at < 0 then None else Some vals.(w.key_at))